diff --git a/DEPS b/DEPS index 0d4d2eb..51b6d80 100644 --- a/DEPS +++ b/DEPS
@@ -138,11 +138,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': '7694b90eb000cd91813171cb9ad5a2b45d51dcf9', + 'skia_revision': 'dc57783169c3dee297709e86151ab6f06b8b4854', # 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': '353cbaa98234985eb46270232aae073740b8352a', + 'v8_revision': 'ab5fb228bcaf387cc72dfd93cdc62c1db4867ebf', # 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. @@ -150,7 +150,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '9a4bd48d5f0c367fd1db39e67aaffdbff1736bd6', + 'angle_revision': 'f157aba50a524cded8ab2a1e83c63357c8032c25', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -269,7 +269,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'shaderc_revision': '2a888de1db058adc9093118a7d9d28d4db1d1480', + 'shaderc_revision': '2cbf790c7226100df0736f15f423c936104521d7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -807,7 +807,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '4e5c106f96c40427706ccf1bae049450e6c9c162', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '62a36d561f3ba7bee4568d6cf96b64f9424f6a0e', 'condition': 'checkout_linux', }, @@ -1187,7 +1187,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c0d17117afe95d13bb1920fff2aa67022959a356', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c4e3d7c64fc041b79d4984e15ada99f25b6b126b', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1396,7 +1396,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@fd4e0560a28b36aed4e712d6ea8568e8d5bd4dfe', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@cf45e861a629818950e12110da0169b64c479d55', 'condition': 'checkout_src_internal', },
diff --git a/ash/display/window_tree_host_manager.cc b/ash/display/window_tree_host_manager.cc index bd16e8a..7364e2a 100644 --- a/ash/display/window_tree_host_manager.cc +++ b/ash/display/window_tree_host_manager.cc
@@ -789,8 +789,7 @@ } ui::EventDispatchDetails WindowTreeHostManager::DispatchKeyEventPostIME( - ui::KeyEvent* event, - DispatchKeyEventPostIMECallback callback) { + ui::KeyEvent* event) { aura::Window* root_window = nullptr; if (event->target()) { root_window = static_cast<aura::Window*>(event->target())->GetRootWindow(); @@ -803,8 +802,7 @@ root_window = active_window ? active_window->GetRootWindow() : Shell::GetPrimaryRootWindow(); } - return root_window->GetHost()->DispatchKeyEventPostIME(event, - std::move(callback)); + return root_window->GetHost()->DispatchKeyEventPostIME(event); } AshWindowTreeHost* WindowTreeHostManager::AddWindowTreeHostForDisplay(
diff --git a/ash/display/window_tree_host_manager.h b/ash/display/window_tree_host_manager.h index 0bd021f..02b9e31 100644 --- a/ash/display/window_tree_host_manager.h +++ b/ash/display/window_tree_host_manager.h
@@ -174,8 +174,7 @@ // ui::internal::InputMethodDelegate overrides: ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* event, - DispatchKeyEventPostIMECallback callback) override; + ui::KeyEvent* event) override; private: FRIEND_TEST_ALL_PREFIXES(WindowTreeHostManagerTest, BoundsUpdated);
diff --git a/ash/display/window_tree_host_manager_unittest.cc b/ash/display/window_tree_host_manager_unittest.cc index 7fe678c..04fa70b 100644 --- a/ash/display/window_tree_host_manager_unittest.cc +++ b/ash/display/window_tree_host_manager_unittest.cc
@@ -18,7 +18,6 @@ #include "ash/wm/cursor_manager_test_api.h" #include "ash/wm/window_state.h" #include "ash/wm/wm_event.h" -#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/run_loop.h" #include "base/test/scoped_feature_list.h" @@ -1708,8 +1707,7 @@ dispatcher_api.set_target( Shell::Get()->window_tree_host_manager()->GetRootWindowForDisplayId( GetSecondaryDisplay().id())); - Shell::Get()->window_tree_host_manager()->DispatchKeyEventPostIME( - &key_event, base::NullCallback()); + Shell::Get()->window_tree_host_manager()->DispatchKeyEventPostIME(&key_event); // As long as nothing crashes, we're good. }
diff --git a/chrome/VERSION b/chrome/VERSION index 1e19a1b..128a7e8 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=77 MINOR=0 -BUILD=3830 +BUILD=3831 PATCH=0
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_button_filled.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_button_filled.xml index 233aa12..09c40f47 100644 --- a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_button_filled.xml +++ b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_button_filled.xml
@@ -7,6 +7,7 @@ xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" + android:gravity="center_vertical" android:minHeight="@dimen/min_touch_target_size" app:chipColor="@color/filled_button_bg" app:rippleColor="@color/filled_button_ripple_color"
diff --git a/chrome/android/java/res/layout/top_view.xml b/chrome/android/java/res/layout/top_view.xml index cd97e14f..bfe58af 100644 --- a/chrome/android/java/res/layout/top_view.xml +++ b/chrome/android/java/res/layout/top_view.xml
@@ -5,6 +5,7 @@ <org.chromium.chrome.browser.contacts_picker.TopView xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> @@ -17,9 +18,28 @@ android:layout_marginStart="20dp" android:layout_marginEnd="16dp" /> + <org.chromium.ui.widget.ChipView + android:id="@+id/email_filter" + android:gravity="center" + android:layout_below="@id/explanation" + android:layout_height="wrap_content" + android:layout_marginStart="20dp" + android:layout_width="wrap_content" + style="@style/SuggestionChip" /> + + <org.chromium.ui.widget.ChipView + android:id="@+id/tel_filter" + android:gravity="center" + android:layout_below="@id/explanation" + android:layout_toEndOf="@id/email_filter" + android:layout_height="wrap_content" + android:layout_marginStart="10dp" + android:layout_width="wrap_content" + style="@style/SuggestionChip" /> + <LinearLayout android:id="@+id/content" - android:layout_below="@id/explanation" + android:layout_below="@id/email_filter" android:visibility="gone" style="@style/ListItemContainer">
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactDetails.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactDetails.java index b01b55d..04998a0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactDetails.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactDetails.java
@@ -89,35 +89,42 @@ * separated by newline). * @param longVersion Whether to get all the details (for emails and phone numbers) or only what * will fit in the allotted space on the dialog. + * @param includeEmails Whether to include emails in the returned results. + * @param includeTels Whether to include telephones in the returned results. * @param resources The resources to use for fetching the string. Must be provided if * longVersion is false, otherwise it can be null. * @return A string containing all the contact details registered for this contact. */ - public String getContactDetailsAsString(boolean longVersion, @Nullable Resources resources) { + public String getContactDetailsAsString(boolean longVersion, boolean includeEmails, + boolean includeTels, @Nullable Resources resources) { int count = 0; StringBuilder builder = new StringBuilder(); - for (String email : mEmails) { - if (count++ > 0) { - builder.append("\n"); - } - builder.append(email); - if (!longVersion && mEmails.size() > 1) { - int size = mEmails.size() - 1; - builder.append(resources.getQuantityString( - R.plurals.contacts_picker_more_details, size, size)); - break; + if (includeEmails) { + for (String email : mEmails) { + if (count++ > 0) { + builder.append("\n"); + } + builder.append(email); + if (!longVersion && mEmails.size() > 1) { + int size = mEmails.size() - 1; + builder.append(resources.getQuantityString( + R.plurals.contacts_picker_more_details, size, size)); + break; + } } } - for (String phoneNumber : mPhoneNumbers) { - if (count++ > 0) { - builder.append("\n"); - } - builder.append(phoneNumber); - if (!longVersion && mPhoneNumbers.size() > 1) { - int size = mPhoneNumbers.size() - 1; - builder.append(resources.getQuantityString( - R.plurals.contacts_picker_more_details, size, size)); - break; + if (includeTels) { + for (String phoneNumber : mPhoneNumbers) { + if (count++ > 0) { + builder.append("\n"); + } + builder.append(phoneNumber); + if (!longVersion && mPhoneNumbers.size() > 1) { + int size = mPhoneNumbers.size() - 1; + builder.append(resources.getQuantityString( + R.plurals.contacts_picker_more_details, size, size)); + break; + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactView.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactView.java index e3f65db..bf07c6c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/ContactView.java
@@ -94,7 +94,9 @@ .with(ModalDialogProperties.CONTROLLER, controller) .with(ModalDialogProperties.TITLE, mContactDetails.getDisplayName()) .with(ModalDialogProperties.MESSAGE, - mContactDetails.getContactDetailsAsString(true, null)) + mContactDetails.getContactDetailsAsString(true, + PickerAdapter.includesEmails(), + PickerAdapter.includesTelephones(), null)) .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, mContext.getResources(), R.string.close) .build(); @@ -144,7 +146,8 @@ mDisplayName.setText(displayName); String details = contactDetails.getContactDetailsAsString( - /*longVersion=*/false, mContext.getResources()); + /*longVersion=*/false, /*includeEmails=*/PickerAdapter.includesEmails(), + /*includeTels=*/PickerAdapter.includesTelephones(), mContext.getResources()); mDetailsView.setText(details); mDetailsView.setVisibility(details.isEmpty() ? View.GONE : View.VISIBLE);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerAdapter.java index 7ef1b3c..a38ae33 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerAdapter.java
@@ -25,7 +25,8 @@ * A data adapter for the Contacts Picker. */ public class PickerAdapter extends Adapter<RecyclerView.ViewHolder> - implements ContactsFetcherWorkerTask.ContactsRetrievedCallback { + implements ContactsFetcherWorkerTask.ContactsRetrievedCallback, + TopView.ChipToggledCallback { /** * A ViewHolder for the top-most view in the RecyclerView. The view it contains has a * checkbox and some multi-line text that goes with it, so clicks on either text line @@ -48,6 +49,16 @@ } /** + * The types of filters supported. + */ + @Retention(RetentionPolicy.SOURCE) + @IntDef({FilterType.EMAILS, FilterType.TELEPHONES}) + public @interface FilterType { + int EMAILS = 0; + int TELEPHONES = 1; + } + + /** * The types of views supported. */ @Retention(RetentionPolicy.SOURCE) @@ -81,6 +92,12 @@ // A list of search result indices into the larger data set. private ArrayList<Integer> mSearchResults; + // Whether to include emails in the returned results. + private static boolean sIncludeEmails; + + // Whether to include telephone numbers in the returned results. + private static boolean sIncludeTelephones; + // A list of contacts to use for testing (instead of querying Android). private static ArrayList<ContactDetails> sTestContacts; @@ -95,6 +112,8 @@ mCategoryView = categoryView; mContentResolver = contentResolver; mFormattedOrigin = formattedOrigin; + sIncludeEmails = true; + sIncludeTelephones = true; if (getAllContacts() == null && sTestContacts == null) { mWorkerTask = new ContactsFetcherWorkerTask(mContentResolver, this, @@ -131,7 +150,8 @@ for (ContactDetails contact : mContactDetails) { if (contact.getDisplayName().toLowerCase(Locale.getDefault()).contains(query_lower) || contact.getContactDetailsAsString( - /*longVersion=*/true, /*resources=*/null) + /*longVersion=*/true, includesEmails(), + includesTelephones(), /*resources=*/null) .toLowerCase(Locale.getDefault()) .contains(query_lower)) { mSearchResults.add(count); @@ -175,6 +195,7 @@ .inflate(R.layout.top_view, parent, false); mTopView.setSiteString(mFormattedOrigin); mTopView.registerSelectAllCallback(mCategoryView); + mTopView.registerChipToggledCallback(this); mTopView.updateCheckboxVisibility(mCategoryView.multiSelectionAllowed()); mCategoryView.setTopView(mTopView); if (mContactDetails != null) mTopView.updateContactCount(mContactDetails.size()); @@ -220,6 +241,34 @@ return mContactDetails.size() + (mSearchMode ? 0 : 1); } + // TopView.ChipToggledCallback: + + @Override + public void onChipToggled(@FilterType int chip) { + if (chip == FilterType.EMAILS) { + sIncludeEmails = !sIncludeEmails; + } else if (chip == FilterType.TELEPHONES) { + sIncludeTelephones = !sIncludeTelephones; + } else { + assert false; + } + notifyDataSetChanged(); + } + + /** + * Returns true unless the adapter is filtering out emails. + */ + public static boolean includesEmails() { + return sIncludeEmails; + } + + /** + * Returns true unless the adapter is filtering out telephone numbers. + */ + public static boolean includesTelephones() { + return sIncludeTelephones; + } + /** Sets a list of contacts to use as data for the dialog. For testing use only. */ @VisibleForTesting public static void setTestContacts(ArrayList<ContactDetails> contacts) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java index d20d7e3..d6b8d33 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/PickerCategoryView.java
@@ -323,8 +323,11 @@ for (ContactDetails contactDetails : selectedContacts) { contacts.add(new ContactsPickerListener.Contact( includeNames ? contactDetails.getDisplayNames() : null, - includeEmails ? contactDetails.getEmails() : null, - includeTel ? contactDetails.getPhoneNumbers() : null)); + includeEmails && PickerAdapter.includesEmails() ? contactDetails.getEmails() + : null, + includeTel && PickerAdapter.includesTelephones() + ? contactDetails.getPhoneNumbers() + : null)); } executeAction(ContactsPickerListener.ContactsPickerAction.CONTACTS_SELECTED, contacts); } @@ -345,4 +348,9 @@ public SelectionDelegate<ContactDetails> getSelectionDelegateForTesting() { return mSelectionDelegate; } + + @VisibleForTesting + public TopView getTopViewForTesting() { + return mTopView; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/TopView.java b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/TopView.java index 7b4a3b6..5f05192 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/TopView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contacts_picker/TopView.java
@@ -16,13 +16,15 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.ui.text.SpanApplier; +import org.chromium.ui.widget.ChipView; import java.text.NumberFormat; /** * A container class for the Disclaimer and Select All functionality (and both associated labels). */ -public class TopView extends RelativeLayout implements CompoundButton.OnCheckedChangeListener { +public class TopView extends RelativeLayout + implements CompoundButton.OnCheckedChangeListener, View.OnClickListener { /** * An interface for communicating when the Select All checkbox is toggled. */ @@ -34,6 +36,17 @@ void onSelectAllToggled(boolean allSelected); } + /** + * An interface for communicating when one of the chips has been toggled. + */ + public interface ChipToggledCallback { + /** + * Called when a Chip is toggled. + * @param chip The chip type that was toggled. + */ + void onChipToggled(@PickerAdapter.FilterType int chip); + } + private final Context mContext; // The container box for the checkbox and its label and contact count. @@ -48,6 +61,15 @@ // The callback to use when notifying that the Select All checkbox was toggled. private SelectAllToggleCallback mSelectAllCallback; + // A Chip for filtering out emails. + private ChipView mEmailFilterChip; + + // A Chip for filtering out telephones. + private ChipView mTelephonesFilterChip; + + // The callback to use to notify when the filter chips are toggled. + private ChipToggledCallback mChipToggledCallback; + // Whether to temporarily ignore clicks on the checkbox. private boolean mIgnoreCheck; @@ -69,6 +91,39 @@ TextView title = findViewById(R.id.checkbox_title); title.setText(R.string.contacts_picker_all_contacts); + + mEmailFilterChip = findViewById(R.id.email_filter); + TextView textView = mEmailFilterChip.getPrimaryTextView(); + textView.setText(R.string.top_view_email_filter_label); + mEmailFilterChip.setSelected(true); + mEmailFilterChip.setOnClickListener(this); + + mTelephonesFilterChip = findViewById(R.id.tel_filter); + textView = mTelephonesFilterChip.getPrimaryTextView(); + textView.setText(R.string.top_view_telephone_filter_label); + mTelephonesFilterChip.setSelected(true); + mTelephonesFilterChip.setOnClickListener(this); + } + + @Override + public void onClick(View view) { + int id = view.getId(); + if (id == R.id.email_filter) { + notifyChipToggled(PickerAdapter.FilterType.EMAILS); + } else if (id == R.id.tel_filter) { + notifyChipToggled(PickerAdapter.FilterType.TELEPHONES); + } + } + + /** + * Sends a notification that a chip has been toggled and updates the selection state for it. + * @param chip The id of the chip that was toggled. + */ + public void notifyChipToggled(@PickerAdapter.FilterType int chip) { + ChipView chipView = + chip == PickerAdapter.FilterType.EMAILS ? mEmailFilterChip : mTelephonesFilterChip; + chipView.setSelected(!chipView.isSelected()); + mChipToggledCallback.onChipToggled(chip); } /** @@ -92,6 +147,13 @@ } /** + * Register a callback to use to notify when the filter chips are toggled. + */ + public void registerChipToggledCallback(ChipToggledCallback callback) { + mChipToggledCallback = callback; + } + + /** * Updates the visibility of the Select All checkbox. * @param visible Whether the checkbox should be visible. */
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 038f8973..092fda70 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -3590,7 +3590,12 @@ <message name="IDS_CONTACTS_PICKER_NO_CONTACTS_FOUND" desc="The label shown when no contacts are found (e.g. none exist on the device)."> No contacts found </message> - + <message name="IDS_TOP_VIEW_EMAIL_FILTER_LABEL" desc="The label shown for the email filter toggle button (allowing the user to exclude emails)."> + Emails + </message> + <message name="IDS_TOP_VIEW_TELEPHONE_FILTER_LABEL" desc="The label shown for the telephone filter toggle button (allowing the user to exclude emails)."> + Telephones + </message> <message name="IDS_CONTACTS_PICKER_MORE_DETAILS" desc="Label describing that the user has one or more telephone/emails (used for either). The leading space is a word separator, for those languages that use space as a separator."> {DETAIL_COUNT, plural, =1 { (+ 1 more)}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java index c595166..df0d48f9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contacts_picker/ContactsPickerDialogTest.java
@@ -39,6 +39,7 @@ import org.chromium.ui.ContactsPickerListener; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; @@ -85,7 +86,8 @@ public void setUp() throws Exception { mActivityTestRule.startMainActivityOnBlankPage(); mTestContacts = new ArrayList<ContactDetails>(); - mTestContacts.add(new ContactDetails("0", "Contact 0", null, null)); + mTestContacts.add(new ContactDetails( + "0", "Contact 0", Arrays.asList("0@example.com"), Arrays.asList("555-1234"))); mTestContacts.add(new ContactDetails("1", "Contact 1", null, null)); mTestContacts.add(new ContactDetails("2", "Contact 2", null, null)); mTestContacts.add(new ContactDetails("3", "Contact 3", null, null)); @@ -210,6 +212,18 @@ Assert.assertEquals(expectedAction, mLastActionRecorded); } + private void notifyChipToggled(@PickerAdapter.FilterType int filter) { + TopView topView = mDialog.getCategoryViewForTesting().getTopViewForTesting(); + topView.notifyChipToggled(filter); + } + + private void toggleFilter(@PickerAdapter.FilterType int filter) throws Exception { + RecyclerView recyclerView = getRecyclerView(); + RecyclerViewTestUtils.waitForView(recyclerView, 0); + + TestThreadUtils.runOnUiThreadBlocking(() -> notifyChipToggled(filter)); + } + private void clickSearchButton() throws Exception { ContactsPickerToolbar toolbar = (ContactsPickerToolbar) mDialog.findViewById(R.id.action_bar); @@ -313,6 +327,52 @@ @Test @LargeTest + public void testEmailsRemoved() throws Throwable { + createDialog(/* multiselect = */ false, /* includeNames = */ true, + /* includeEmails = */ true, + /* includeTel = */ true); + Assert.assertTrue(mDialog.isShowing()); + + toggleFilter(PickerAdapter.FilterType.EMAILS); + + int expectedSelectionCount = 1; + clickView(0, expectedSelectionCount, /* expectSelection = */ true); + clickDone(); + + Assert.assertEquals(ContactsPickerAction.CONTACTS_SELECTED, mLastActionRecorded); + Assert.assertEquals(1, mLastSelectedContacts.size()); + Assert.assertEquals( + mTestContacts.get(0).getDisplayName(), mLastSelectedContacts.get(0).names.get(0)); + Assert.assertEquals(null, mLastSelectedContacts.get(0).emails); + + dismissDialog(); + } + + @Test + @LargeTest + public void testTelephonesRemoved() throws Throwable { + createDialog(/* multiselect = */ false, /* includeNames = */ true, + /* includeEmails = */ true, + /* includeTel = */ true); + Assert.assertTrue(mDialog.isShowing()); + + toggleFilter(PickerAdapter.FilterType.TELEPHONES); + + int expectedSelectionCount = 1; + clickView(0, expectedSelectionCount, /* expectSelection = */ true); + clickDone(); + + Assert.assertEquals(ContactsPickerAction.CONTACTS_SELECTED, mLastActionRecorded); + Assert.assertEquals(1, mLastSelectedContacts.size()); + Assert.assertEquals( + mTestContacts.get(0).getDisplayName(), mLastSelectedContacts.get(0).names.get(0)); + Assert.assertEquals(null, mLastSelectedContacts.get(0).tel); + + dismissDialog(); + } + + @Test + @LargeTest public void testSelectAll() throws Throwable { createDialog(/* multiselect = */ true, /* includeNames = */ true, /* includeEmails = */ true,
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index ddf4958..a5f401e 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -3976,25 +3976,28 @@ Setup complete </message> <message name="IDS_PLUGIN_VM_LAUNCHER_ERROR_TITLE" desc="Title of the Plugin VM installer if there was an error during installation."> - Could not set up Plugin VM + Setup couldn't complete + </message> + <message name="IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_TITLE" desc="Title of the Plugin VM installer if Plugin VM is disallowed."> + Plugin VM needs permission to run </message> <message name="IDS_PLUGIN_VM_LAUNCHER_START_DOWNLOADING_MESSAGE" desc="Text of the Plugin VM installer that informs the user that setup may take a while."> - This may take several minutes. + This may take awhile </message> <message name="IDS_PLUGIN_VM_LAUNCHER_DOWNLOADING_MESSAGE" desc="Text of the Plugin VM installer while downloading the VM."> - Downloading the virtual machine. + Downloading the virtual machine </message> <message name="IDS_PLUGIN_VM_LAUNCHER_IMPORTING_MESSAGE" desc="Text of the Plugin VM installer while configuring the VM."> Configuring the virtual machine. This may take a few minutes. </message> <message name="IDS_PLUGIN_VM_LAUNCHER_FINISHED_MESSAGE" desc="Text of the Plugin VM installer after successful installation."> - Click or tap Launch to use Plugin VM. In the future, you can start Plugin VM by selecting the icon in the Launcher. + Plugin VM is ready to use </message> <message name="IDS_PLUGIN_VM_LAUNCHER_ERROR_MESSAGE" desc="Text of the Plugin VM installer if the installation failed."> - An error occurred. Please try again. + Try installing again </message> - <message name="IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_MESSAGE" desc="Error message to be shown if a setup/launch is attempted although Plugin VM is disabled."> - Please contact your admin to enable Plugin VM on this device. + <message name="IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_MESSAGE" desc="Error message to be shown if a setup/launch is attempted although Plugin VM is disallowed."> + Contact your organization's device admin </message> <message name="IDS_PLUGIN_VM_LAUNCHER_DOWNLOAD_PROGRESS_MESSAGE" desc="Text of the Plugin VM installer during downloading Plugin VM image, showing download progress."> <ph name="DOWNLOADED_SIZE">$1<ex>1.2</ex></ph>/<ph name="DOWNLOAD_SIZE">$2<ex>3.4 GB</ex></ph>
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 9e01f123..be39e9e4 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -5417,7 +5417,7 @@ <!-- Password Manager --> <message name="IDS_PASSWORD_MANAGER_CANCEL_BUTTON" desc="Label for the 'dismiss' button in the Manage Password bubble/Update Password infobar. These UIs ask the user if they wish to perform some action with saved passwords, e.g. updating or deleting them; the button dismisses the UI without taking the suggested action."> - Nope + No thanks </message> <if expr="not is_android"> <message name="IDS_PASSWORD_MANAGER_SAVE_BUTTON" desc="Save button text for password manager">
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index dd17b9c..3b3fbe33 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -599,7 +599,7 @@ Plugin VM </message> <message name="IDS_SETTINGS_PLUGIN_VM_PAGE_SUBTEXT" desc="Description for the section for managing Plugin VM."> - Manage settings for running Plugin VM on your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> + Set up permissions </message> <message name="IDS_SETTINGS_PLUGIN_VM_PRINTER_ACCESS" desc="The text in the settings page for allowing printer access from Plugin VM."> Give access to printers
diff --git a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc index 801c6f16..b69a1e0 100644 --- a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc +++ b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc
@@ -506,11 +506,9 @@ auto it = job_details.current_fetch_guids.find(download_guid); DCHECK(it != job_details.current_fetch_guids.end()); - if (it->second.request_body_blob) { - job_details.fetch_description->uploaded_bytes += - it->second.request_body_blob->size; + if (it->second.request_body_blob) it->second.request_body_blob.reset(); - } + job_details.fetch_description->uploaded_bytes += it->second.body_size_bytes; } void BackgroundFetchDelegateImpl::OnDownloadUpdated( @@ -919,6 +917,11 @@ return; } + auto& job_details = job_it->second; + DCHECK(job_details.current_fetch_guids.count(download_guid)); + auto& request_data = job_details.current_fetch_guids.at(download_guid); + request_data.body_size_bytes = blob->size; + auto request_body = base::MakeRefCounted<network::ResourceRequestBody>(); if (base::FeatureList::IsEnabled(network::features::kNetworkService) || profile_->IsOffTheRecord()) { @@ -930,11 +933,7 @@ } else { // Use the blob itself and store the handle for the duration of the upload. request_body->AppendBlob(blob->uuid); - - auto& job_details = job_it->second; - DCHECK(job_details.current_fetch_guids.count(download_guid)); - job_details.current_fetch_guids.at(download_guid).request_body_blob = - std::move(blob); + request_data.request_body_blob = std::move(blob); } std::move(callback).Run(request_body);
diff --git a/chrome/browser/background_fetch/background_fetch_delegate_impl.h b/chrome/browser/background_fetch/background_fetch_delegate_impl.h index ddaf9aa..43b3edf2 100644 --- a/chrome/browser/background_fetch/background_fetch_delegate_impl.h +++ b/chrome/browser/background_fetch/background_fetch_delegate_impl.h
@@ -205,6 +205,7 @@ // while the request is sent out, and will be cleared after. blink::mojom::SerializedBlobPtr request_body_blob = nullptr; + uint64_t body_size_bytes = 0u; uint64_t in_progress_uploaded_bytes = 0u; uint64_t in_progress_downloaded_bytes = 0u; };
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index baddca6..c6bd749 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -125,6 +125,7 @@ "//chromeos/login/session", "//chromeos/network", "//chromeos/services/device_sync/public/cpp", + "//chromeos/services/ime/public/mojom", "//chromeos/services/machine_learning/public/cpp", "//chromeos/services/machine_learning/public/mojom", "//chromeos/services/multidevice_setup/public/cpp", @@ -1065,6 +1066,8 @@ "input_method/candidate_window_controller_impl.h", "input_method/component_extension_ime_manager_impl.cc", "input_method/component_extension_ime_manager_impl.h", + "input_method/ime_service_connector.cc", + "input_method/ime_service_connector.h", "input_method/input_method_configuration.cc", "input_method/input_method_configuration.h", "input_method/input_method_delegate_impl.cc",
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index 279e1934..ec966f7 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -73,6 +73,11 @@ return *this; } + TestCase& EnableFormatDialog() { + enable_format_dialog.emplace(true); + return *this; + } + TestCase& EnableArc() { enable_arc = true; return *this; @@ -138,6 +143,7 @@ base::Optional<bool> enable_drivefs; base::Optional<bool> enable_myfiles_volume; base::Optional<bool> enable_documents_provider; + base::Optional<bool> enable_format_dialog; bool enable_arc = false; bool with_browser = false; bool needs_zip = false; @@ -199,6 +205,11 @@ FileManagerBrowserTestBase::GetEnableDocumentsProvider()); } + bool GetEnableFormatDialog() const override { + return GetParam().enable_format_dialog.value_or( + FileManagerBrowserTestBase::GetEnableFormatDialog()); + } + bool GetEnableArc() const override { return GetParam().enable_arc; } bool GetRequiresStartupBrowser() const override {
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc index 3f6695e..e9c434e 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc
@@ -1570,6 +1570,11 @@ arc::kEnableDocumentsProviderInFilesAppFeature); } + if (IsFormatDialogTest()) { + enabled_features.emplace_back( + chromeos::features::kEnableFileManagerFormatDialog); + } + feature_list_.InitWithFeatures(enabled_features, disabled_features); extensions::ExtensionApiTest::SetUpCommandLine(command_line); @@ -1733,6 +1738,10 @@ return false; } +bool FileManagerBrowserTestBase::GetEnableFormatDialog() const { + return false; +} + bool FileManagerBrowserTestBase::GetEnableArc() const { return false; } @@ -2125,7 +2134,7 @@ extensions::AppWindowRegistry::Get(profile())->app_windows(); ASSERT_FALSE(app_windows.empty()); app_windows.front()->GetNativeWindow()->GetHost()->DispatchKeyEventPostIME( - &key_event, base::NullCallback()); + &key_event); *output = "mediaKeyDispatched"; return; } @@ -2149,7 +2158,7 @@ host = app_windows.front()->GetNativeWindow()->GetHost(); } ASSERT_TRUE(host); - host->DispatchKeyEventPostIME(&key_event, base::NullCallback()); + host->DispatchKeyEventPostIME(&key_event); *output = "tabKeyDispatched"; return; }
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h index 132e5f9..832dd1f4 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.h
@@ -63,6 +63,7 @@ virtual bool GetEnableMyFilesVolume() const; virtual bool GetEnableDocumentsProvider() const; virtual bool GetEnableArc() const; + virtual bool GetEnableFormatDialog() const; virtual bool GetRequiresStartupBrowser() const; virtual bool GetNeedsZipSupport() const; virtual bool GetIsOffline() const; @@ -92,6 +93,9 @@ // Returns true if the test requires Android documents providers. bool IsDocumentsProviderTest() const { return GetEnableDocumentsProvider(); } + // Returns true if the test requires the FormatDialog feature enabled. + bool IsFormatDialogTest() const { return GetEnableFormatDialog(); } + // Returns true if the test requires ARC++. bool IsArcTest() const { return GetEnableArc(); }
diff --git a/chrome/browser/chromeos/input_method/ime_service_connector.cc b/chrome/browser/chromeos/input_method/ime_service_connector.cc new file mode 100644 index 0000000..8013d84 --- /dev/null +++ b/chrome/browser/chromeos/input_method/ime_service_connector.cc
@@ -0,0 +1,84 @@ +// Copyright 2019 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/input_method/ime_service_connector.h" + +#include <utility> + +#include "base/files/file_util.h" +#include "base/logging.h" +#include "chromeos/services/ime/public/mojom/constants.mojom.h" +#include "content/public/common/service_manager_connection.h" + +namespace chromeos { +namespace input_method { + +namespace { + +bool IsImePathInvalid(const base::FilePath& file_path) { + // Only non-empty, relative path which doesn't reference a parent is allowed. + return file_path.empty() || file_path.IsAbsolute() || + file_path.ReferencesParent(); +} + +bool IsURLInvalid(const GURL& url) { + // TODO(https://crbug.com/837156): Use URL whitelist instead of the general + // checks below. + return !url.DomainIs("dl.google.com") || !url.SchemeIs(url::kHttpsScheme); +} + +} // namespace + +ImeServiceConnector::ImeServiceConnector(Profile* profile) + : profile_(profile), + instance_id_(base::Token::CreateRandom()), + access_(this) {} + +ImeServiceConnector::~ImeServiceConnector() = default; + +void ImeServiceConnector::DownloadImeFileTo( + const GURL& url, + const base::FilePath& file_path, + DownloadImeFileToCallback callback) { + // TODO(https://crbug.com/837156): Download file by the network service. + // Validate url and file_path, return an empty file path if not. + if (IsURLInvalid(url) || IsImePathInvalid(file_path)) { + base::FilePath empty_path; + std::move(callback).Run(empty_path); + return; + } + + // Final path always starts from profile path. + base::FilePath full_path = profile_->GetPath().Append(file_path); + std::move(callback).Run(full_path); +} + +void ImeServiceConnector::SetupImeService( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) { + auto* connector = + content::ServiceManagerConnection::GetForProcess()->GetConnector(); + auto per_id_filter = service_manager::ServiceFilter::ByNameWithId( + chromeos::ime::mojom::kServiceName, instance_id_); + + // Connect to the ChromeOS IME service. + if (!access_client_.is_bound()) { + // Connect service as a PlatformAccessClient interface. + connector->Connect(per_id_filter, + access_client_.BindNewPipeAndPassReceiver()); + + access_client_->SetPlatformAccessProvider( + access_.BindNewPipeAndPassRemote()); + } + + // Connect to the same service as a InputEngineManager interface. + connector->Connect(per_id_filter, std::move(receiver)); +} + +void ImeServiceConnector::OnPlatformAccessConnectionLost() { + // Reset the access_client_ + access_client_.reset(); +} + +} // namespace input_method +} // namespace chromeos
diff --git a/chrome/browser/chromeos/input_method/ime_service_connector.h b/chrome/browser/chromeos/input_method/ime_service_connector.h new file mode 100644 index 0000000..7ee2529 --- /dev/null +++ b/chrome/browser/chromeos/input_method/ime_service_connector.h
@@ -0,0 +1,58 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_INPUT_METHOD_IME_SERVICE_CONNECTOR_H_ +#define CHROME_BROWSER_CHROMEOS_INPUT_METHOD_IME_SERVICE_CONNECTOR_H_ + +#include "base/base_paths.h" +#include "base/files/file_path.h" +#include "base/token.h" +#include "chrome/browser/profiles/profile.h" +#include "chromeos/services/ime/public/mojom/input_engine.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" + +#include "services/service_manager/public/cpp/connector.h" +#include "url/gurl.h" + +namespace chromeos { + +namespace input_method { + +// The connector of an ImeService which runs in its own process. +class ImeServiceConnector : public ime::mojom::PlatformAccessProvider { + public: + explicit ImeServiceConnector(Profile* profile); + ~ImeServiceConnector() override; + + // chromeos::ime::mojom::PlatformAccessProvider overrides: + void DownloadImeFileTo(const GURL& url, + const base::FilePath& file_path, + DownloadImeFileToCallback callback) override; + + // Launch an out-of-process IME service and grant necessary Platform access. + void SetupImeService( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver); + + private: + void OnPlatformAccessConnectionLost(); + + Profile* profile_; + + // There is 1:1 mapping from the instance IDs to IME services running out of + // process. + const base::Token instance_id_; + + mojo::Receiver<chromeos::ime::mojom::PlatformAccessProvider> access_; + + mojo::Remote<chromeos::ime::mojom::PlatformAccessClient> access_client_; + + DISALLOW_COPY_AND_ASSIGN(ImeServiceConnector); +}; + +} // namespace input_method +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_INPUT_METHOD_IME_SERVICE_CONNECTOR_H_
diff --git a/chrome/browser/chromeos/input_method/input_method_manager_impl.cc b/chrome/browser/chromeos/input_method/input_method_manager_impl.cc index 98c9196..dae91e670 100644 --- a/chrome/browser/chromeos/input_method/input_method_manager_impl.cc +++ b/chrome/browser/chromeos/input_method/input_method_manager_impl.cc
@@ -854,6 +854,14 @@ return input_view_url; } +void InputMethodManagerImpl::StateImpl::ConnectMojoManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) { + if (!ime_service_connector_) { + ime_service_connector_ = std::make_unique<ImeServiceConnector>(profile); + } + ime_service_connector_->SetupImeService(std::move(receiver)); +} + // ------------------------ InputMethodManagerImpl bool InputMethodManagerImpl::IsLoginKeyboard( const std::string& layout) const { @@ -1151,6 +1159,12 @@ DVLOG(1) << "ActivateInputMethodMenuItem: unknown key: " << key; } +void InputMethodManagerImpl::ConnectInputEngineManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) { + DCHECK(state_); + state_->ConnectMojoManager(std::move(receiver)); +} + bool InputMethodManagerImpl::IsISOLevel5ShiftUsedByCurrentInputMethod() const { return keyboard_->IsISOLevel5ShiftAvailable(); }
diff --git a/chrome/browser/chromeos/input_method/input_method_manager_impl.h b/chrome/browser/chromeos/input_method/input_method_manager_impl.h index 4bbf8a1..896ef4e 100644 --- a/chrome/browser/chromeos/input_method/input_method_manager_impl.h +++ b/chrome/browser/chromeos/input_method/input_method_manager_impl.h
@@ -16,6 +16,7 @@ #include "base/observer_list.h" #include "base/threading/thread_checker.h" #include "chrome/browser/chromeos/input_method/candidate_window_controller.h" +#include "chrome/browser/chromeos/input_method/ime_service_connector.h" #include "chrome/browser/chromeos/login/ui/user_adding_screen.h" #include "chrome/browser/profiles/profile.h" #include "ui/base/ime/chromeos/input_method_manager.h" @@ -116,6 +117,11 @@ void DisableInputView() override; const GURL& GetInputViewUrl() const override; + // Connect to an InputEngineManager instance in an IME Mojo service. + void ConnectMojoManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> + receiver); + // ------------------------- Data members. Profile* const profile; @@ -162,6 +168,8 @@ // Returns the first hardware input method that is allowed or the first // allowed input method, if no hardware input method is allowed. std::string GetAllowedFallBackKeyboardLayout() const; + + std::unique_ptr<ImeServiceConnector> ime_service_connector_; }; // Constructs an InputMethodManager instance. The client is responsible for @@ -189,6 +197,9 @@ std::unique_ptr<InputMethodDescriptors> GetSupportedInputMethods() const override; void ActivateInputMethodMenuItem(const std::string& key) override; + void ConnectInputEngineManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) + override; bool IsISOLevel5ShiftUsedByCurrentInputMethod() const override; bool IsAltGrUsedByCurrentInputMethod() const override; void NotifyImeMenuItemsChanged(
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc index 3eacef2..e883195a 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc
@@ -654,6 +654,11 @@ // in the "succeeding" flow, so verify here, too. chromeos::DeviceOAuth2TokenService* token_service = chromeos::DeviceOAuth2TokenServiceFactory::Get(); + + // For the refresh token for the robot account to be visible, the robot + // account ID must not be empty. + token_service->set_robot_account_id_for_testing(CoreAccountId("dummy")); + EXPECT_TRUE(token_service->RefreshTokenIsAvailable( token_service->GetRobotAccountId())); EXPECT_EQ(device_policy_->GetBlob(),
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service.cc index d23a13e..8a73e49 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service.cc
@@ -72,6 +72,11 @@ return GetDeviceDelegate()->GetRobotAccountId(); } +void DeviceOAuth2TokenService::set_robot_account_id_for_testing( + const CoreAccountId& account_id) { + GetDeviceDelegate()->set_robot_account_id_for_testing(account_id); +} + void DeviceOAuth2TokenService::FetchOAuth2Token( RequestImpl* request, const CoreAccountId& account_id,
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service.h b/chrome/browser/chromeos/settings/device_oauth2_token_service.h index 6c4bd2b0d..20a1883 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service.h +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service.h
@@ -44,6 +44,12 @@ // Pull the robot account ID from device policy. virtual std::string GetRobotAccountId() const; + // Can be used to override the robot account ID for testing purposes. Most + // common use case is to easily inject a non-empty account ID to make the + // refresh token for the robot account visible via GetAccounts() and + // RefreshTokenIsAvailable(). + void set_robot_account_id_for_testing(const CoreAccountId& account_id); + protected: // Implementation of OAuth2TokenService. void FetchOAuth2Token(
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc index e62e7df..b266884 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.cc
@@ -99,7 +99,8 @@ case STATE_VALIDATION_PENDING: case STATE_VALIDATION_STARTED: case STATE_TOKEN_VALID: - accounts.push_back(GetRobotAccountId()); + if (!GetRobotAccountId().empty()) + accounts.push_back(GetRobotAccountId()); return accounts; } @@ -108,6 +109,10 @@ } CoreAccountId DeviceOAuth2TokenServiceDelegate::GetRobotAccountId() const { + if (!robot_account_id_for_testing_.empty()) { + return robot_account_id_for_testing_; + } + std::string account_id; CrosSettings::Get()->GetString(kServiceAccountIdentity, &account_id); return CoreAccountId(account_id);
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h index 7015ab8..464babe 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_delegate.h
@@ -50,9 +50,12 @@ // Pull the robot account ID from device policy. CoreAccountId GetRobotAccountId() const; + void set_robot_account_id_for_testing(const CoreAccountId& account_id) { + robot_account_id_for_testing_ = account_id; + } + // Implementation of OAuth2TokenServiceDelegate. bool RefreshTokenIsAvailable(const CoreAccountId& account_id) const override; - scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() const override; @@ -154,6 +157,8 @@ std::unique_ptr<CrosSettings::ObserverSubscription> service_account_identity_subscription_; + CoreAccountId robot_account_id_for_testing_; + base::WeakPtrFactory<DeviceOAuth2TokenServiceDelegate> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(DeviceOAuth2TokenServiceDelegate);
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc index 8aa2024..20e580f7 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc
@@ -252,6 +252,10 @@ TEST_F(DeviceOAuth2TokenServiceTest, SaveEncryptedToken) { CreateService(); + // The token service won't report there being a token if the robot account ID + // is not set, which would cause the expectation below to fail. + SetRobotAccountId("service_acct@g.com"); + oauth2_service_->SetAndSaveRefreshToken( "test-token", DeviceOAuth2TokenService::StatusCallback()); EXPECT_EQ("test-token", GetRefreshToken());
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 822a0a9..90e3af6 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -33,6 +33,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "base/task/post_task.h" +#include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/test_file_util.h" #include "base/threading/thread_restrictions.h" @@ -147,6 +148,10 @@ using net::URLRequestMockHTTPJob; using net::test_server::EmbeddedTestServer; +// TODO(crbug.com/971199): tests should be fixed to use base::RunLoop::Run() +// and base::RunLoop::Quit() instead of content::RunMessageLoop() and the +// deprecated base::RunLoop::QuitCurrentWhenIdleDeprecated(). + namespace { const char kDownloadTest1Path[] = "download-test1.lib"; @@ -339,35 +344,24 @@ class DownloadsHistoryDataCollector { public: explicit DownloadsHistoryDataCollector(Profile* profile) - : profile_(profile), result_valid_(false) {} + : profile_(profile) {} - bool WaitForDownloadInfo( - std::unique_ptr<std::vector<history::DownloadRow>>* results) { - history::HistoryService* hs = HistoryServiceFactory::GetForProfile( - profile_, ServiceAccessType::EXPLICIT_ACCESS); - DCHECK(hs); - hs->QueryDownloads( - base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete, - base::Unretained(this))); + bool WaitForDownloadInfo(std::vector<history::DownloadRow>* results) { + EXPECT_TRUE(results); + HistoryServiceFactory::GetForProfile(profile_, + ServiceAccessType::EXPLICIT_ACCESS) + ->QueryDownloads(base::BindLambdaForTesting( + [&](std::vector<history::DownloadRow> rows) { + *results = std::move(rows); + base::RunLoop::QuitCurrentWhenIdleDeprecated(); + })); content::RunMessageLoop(); - if (result_valid_) { - *results = std::move(results_); - } - return result_valid_; + return true; } private: - void OnQueryDownloadsComplete( - std::unique_ptr<std::vector<history::DownloadRow>> entries) { - result_valid_ = true; - results_ = std::move(entries); - base::RunLoop::QuitCurrentWhenIdleDeprecated(); - } - Profile* profile_; - std::unique_ptr<std::vector<history::DownloadRow>> results_; - bool result_valid_; DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector); }; @@ -2003,14 +1997,14 @@ // Get what was stored in the history. observer.WaitForStored(); // Get the details on what was stored into the history. - std::unique_ptr<std::vector<history::DownloadRow>> downloads_in_database; + std::vector<history::DownloadRow> downloads_in_database; ASSERT_TRUE(DownloadsHistoryDataCollector( browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); - ASSERT_EQ(1u, downloads_in_database->size()); + ASSERT_EQ(1u, downloads_in_database.size()); // Confirm history storage is what you expect for an interrupted slow download // job. The download isn't continuable, so there's no intermediate file. - history::DownloadRow& row1(downloads_in_database->at(0)); + history::DownloadRow& row1(downloads_in_database[0]); EXPECT_EQ(DestinationFile(browser(), file), row1.target_path); EXPECT_TRUE(row1.current_path.empty()); ASSERT_EQ(2u, row1.url_chain.size()); @@ -2068,11 +2062,11 @@ // Get history details and confirm it's what you expect. observer.WaitForStored(); - std::unique_ptr<std::vector<history::DownloadRow>> downloads_in_database; + std::vector<history::DownloadRow> downloads_in_database; ASSERT_TRUE(DownloadsHistoryDataCollector( browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); - ASSERT_EQ(1u, downloads_in_database->size()); - history::DownloadRow& row1(downloads_in_database->at(0)); + ASSERT_EQ(1u, downloads_in_database.size()); + history::DownloadRow& row1(downloads_in_database[0]); base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf")); EXPECT_EQ(DestinationFile(browser(), file), row1.target_path); EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
diff --git a/chrome/browser/download/download_history.cc b/chrome/browser/download/download_history.cc index c1bc066..342ae98 100644 --- a/chrome/browser/download/download_history.cc +++ b/chrome/browser/download/download_history.cc
@@ -204,8 +204,6 @@ return ShouldUpdateHistoryResult::NO_UPDATE; } -typedef std::vector<history::DownloadRow> InfoVector; - } // anonymous namespace DownloadHistory::HistoryAdapter::HistoryAdapter( @@ -215,8 +213,8 @@ DownloadHistory::HistoryAdapter::~HistoryAdapter() {} void DownloadHistory::HistoryAdapter::QueryDownloads( - const history::HistoryService::DownloadQueryCallback& callback) { - history_->QueryDownloads(callback); + history::HistoryService::DownloadQueryCallback callback) { + history_->QueryDownloads(std::move(callback)); } void DownloadHistory::HistoryAdapter::CreateDownload( @@ -257,8 +255,8 @@ notifier_.GetManager()->GetAllDownloads(&items); for (auto* item : items) OnDownloadCreated(notifier_.GetManager(), item); - history_->QueryDownloads(base::Bind( - &DownloadHistory::QueryCallback, weak_ptr_factory_.GetWeakPtr())); + history_->QueryDownloads(base::BindOnce(&DownloadHistory::QueryCallback, + weak_ptr_factory_.GetWeakPtr())); } DownloadHistory::~DownloadHistory() { @@ -281,7 +279,7 @@ observers_.RemoveObserver(observer); } -void DownloadHistory::QueryCallback(std::unique_ptr<InfoVector> infos) { +void DownloadHistory::QueryCallback(std::vector<history::DownloadRow> rows) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // ManagerGoingDown() may have happened before the history loaded. if (!notifier_.GetManager()) @@ -289,37 +287,37 @@ notifier_.GetManager()->OnHistoryQueryComplete( base::BindOnce(&DownloadHistory::LoadHistoryDownloads, - weak_ptr_factory_.GetWeakPtr(), std::move(infos))); + weak_ptr_factory_.GetWeakPtr(), std::move(rows))); } -void DownloadHistory::LoadHistoryDownloads(std::unique_ptr<InfoVector> infos) { +void DownloadHistory::LoadHistoryDownloads( + std::vector<history::DownloadRow> rows) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(notifier_.GetManager()); - for (InfoVector::const_iterator it = infos->begin(); - it != infos->end(); ++it) { - loading_id_ = history::ToContentDownloadId(it->id); + for (const history::DownloadRow& row : rows) { + loading_id_ = history::ToContentDownloadId(row.id); download::DownloadItem::DownloadState history_download_state = - history::ToContentDownloadState(it->state); + history::ToContentDownloadState(row.state); download::DownloadInterruptReason history_reason = - history::ToContentDownloadInterruptReason(it->interrupt_reason); + history::ToContentDownloadInterruptReason(row.interrupt_reason); download::DownloadItem* item = notifier_.GetManager()->CreateDownloadItem( - it->guid, loading_id_, it->current_path, it->target_path, it->url_chain, - it->referrer_url, it->site_url, it->tab_url, it->tab_referrer_url, - base::nullopt, it->mime_type, it->original_mime_type, it->start_time, - it->end_time, it->etag, it->last_modified, it->received_bytes, - it->total_bytes, + row.guid, loading_id_, row.current_path, row.target_path, row.url_chain, + row.referrer_url, row.site_url, row.tab_url, row.tab_referrer_url, + base::nullopt, row.mime_type, row.original_mime_type, row.start_time, + row.end_time, row.etag, row.last_modified, row.received_bytes, + row.total_bytes, std::string(), // TODO(asanka): Need to persist and restore hash of // partial file for an interrupted download. No need to // store hash for a completed file. history_download_state, - history::ToContentDownloadDangerType(it->danger_type), history_reason, - it->opened, it->last_access_time, it->transient, - history::ToContentReceivedSlices(it->download_slice_info)); + history::ToContentDownloadDangerType(row.danger_type), history_reason, + row.opened, row.last_access_time, row.transient, + history::ToContentReceivedSlices(row.download_slice_info)); // DownloadManager returns a nullptr if it decides to remove the download // permanently. if (item == nullptr) { - ScheduleRemoveDownload(it->id); + ScheduleRemoveDownload(row.id); continue; } DCHECK_EQ(download::DownloadItem::kInvalidId, loading_id_); @@ -333,9 +331,9 @@ OnDownloadUpdated(notifier_.GetManager(), item); } #if BUILDFLAG(ENABLE_EXTENSIONS) - if (!it->by_ext_id.empty() && !it->by_ext_name.empty()) { - new extensions::DownloadedByExtension( - item, it->by_ext_id, it->by_ext_name); + if (!row.by_ext_id.empty() && !row.by_ext_name.empty()) { + new extensions::DownloadedByExtension(item, row.by_ext_id, + row.by_ext_name); item->UpdateObservers(); } #endif
diff --git a/chrome/browser/download/download_history.h b/chrome/browser/download/download_history.h index 882c97e..c9162e0 100644 --- a/chrome/browser/download/download_history.h +++ b/chrome/browser/download/download_history.h
@@ -36,7 +36,7 @@ virtual ~HistoryAdapter(); virtual void QueryDownloads( - const history::HistoryService::DownloadQueryCallback& callback); + history::HistoryService::DownloadQueryCallback callback); virtual void CreateDownload( const history::DownloadRow& info, @@ -96,11 +96,10 @@ private: // Callback from |history_| containing all entries in the downloads database // table. - void QueryCallback(std::unique_ptr<std::vector<history::DownloadRow>> infos); + void QueryCallback(std::vector<history::DownloadRow> rows); // Called to create all history downloads. - void LoadHistoryDownloads( - std::unique_ptr<std::vector<history::DownloadRow>> infos); + void LoadHistoryDownloads(std::vector<history::DownloadRow> rows); // May add |item| to |history_|. void MaybeAddToHistory(download::DownloadItem* item);
diff --git a/chrome/browser/download/download_history_unittest.cc b/chrome/browser/download/download_history_unittest.cc index fc1f1ce1..0bc0250 100644 --- a/chrome/browser/download/download_history_unittest.cc +++ b/chrome/browser/download/download_history_unittest.cc
@@ -46,7 +46,6 @@ namespace { using IdSet = DownloadHistory::IdSet; -using InfoVector = std::vector<history::DownloadRow>; using StrictMockDownloadItem = testing::StrictMock<download::MockDownloadItem>; class FakeHistoryAdapter : public DownloadHistory::HistoryAdapter { @@ -54,28 +53,36 @@ FakeHistoryAdapter() : DownloadHistory::HistoryAdapter(nullptr) {} void QueryDownloads( - const history::HistoryService::DownloadQueryCallback& callback) override { + history::HistoryService::DownloadQueryCallback callback) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&FakeHistoryAdapter::QueryDownloadsDone, - base::Unretained(this), callback)); + base::Unretained(this), std::move(callback))); } void QueryDownloadsDone( - const history::HistoryService::DownloadQueryCallback& callback) { + history::HistoryService::DownloadQueryCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - CHECK(expect_query_downloads_.get()); - callback.Run(std::move(expect_query_downloads_)); + CHECK(expect_query_downloads_.has_value()); + + // Use swap to reset the base::Optional<...> to a known state before + // moving the value (moving the value out of a base::Optional<...> + // does not reset it to base::nullopt). + using std::swap; + base::Optional<std::vector<history::DownloadRow>> rows; + swap(rows, expect_query_downloads_); + + std::move(callback).Run(std::move(*rows)); } void set_slow_create_download(bool slow) { slow_create_download_ = slow; } void CreateDownload( - const history::DownloadRow& info, + const history::DownloadRow& row, history::HistoryService::DownloadCreateCallback callback) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - create_download_info_ = info; + create_download_row_ = row; // Must not call CreateDownload() again before FinishCreateDownload()! DCHECK(create_download_callback_.is_null()); create_download_callback_ = @@ -90,10 +97,10 @@ std::move(create_download_callback_).Run(); } - void UpdateDownload(const history::DownloadRow& info, + void UpdateDownload(const history::DownloadRow& row, bool should_commit_immediately) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - update_download_ = info; + update_download_ = row; should_commit_immediately_ = should_commit_immediately; } @@ -104,14 +111,14 @@ } } - void ExpectWillQueryDownloads(std::unique_ptr<InfoVector> infos) { + void ExpectWillQueryDownloads(std::vector<history::DownloadRow> rows) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - expect_query_downloads_ = std::move(infos); + expect_query_downloads_ = std::move(rows); } void ExpectQueryDownloadsDone() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - EXPECT_TRUE(NULL == expect_query_downloads_.get()); + EXPECT_TRUE(!expect_query_downloads_.has_value()); } void FailCreateDownload() { @@ -119,25 +126,24 @@ fail_create_download_ = true; } - void ExpectDownloadCreated( - const history::DownloadRow& info) { + void ExpectDownloadCreated(const history::DownloadRow& row) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); - EXPECT_EQ(info, create_download_info_); - create_download_info_ = history::DownloadRow(); + EXPECT_EQ(row, create_download_row_); + create_download_row_ = history::DownloadRow(); } void ExpectNoDownloadCreated() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); - EXPECT_EQ(history::DownloadRow(), create_download_info_); + EXPECT_EQ(history::DownloadRow(), create_download_row_); } - void ExpectDownloadUpdated(const history::DownloadRow& info, + void ExpectDownloadUpdated(const history::DownloadRow& row, bool should_commit_immediately) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RunAllPendingInMessageLoop(content::BrowserThread::UI); - EXPECT_EQ(update_download_, info); + EXPECT_EQ(update_download_, row); EXPECT_EQ(should_commit_immediately_, should_commit_immediately); update_download_ = history::DownloadRow(); should_commit_immediately_ = false; @@ -172,9 +178,9 @@ bool should_commit_immediately_ = false; base::OnceClosure create_download_callback_; history::DownloadRow update_download_; - std::unique_ptr<InfoVector> expect_query_downloads_; + base::Optional<std::vector<history::DownloadRow>> expect_query_downloads_; IdSet remove_downloads_; - history::DownloadRow create_download_info_; + history::DownloadRow create_download_row_; DISALLOW_COPY_AND_ASSIGN(FakeHistoryAdapter); }; @@ -213,16 +219,15 @@ // Creates the DownloadHistory. If |return_null_item| is true, |manager_| // will return nullptr on CreateDownloadItem() call, - void CreateDownloadHistory(std::unique_ptr<InfoVector> infos, + void CreateDownloadHistory(std::vector<history::DownloadRow> rows, bool return_null_item = false) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - CHECK(infos.get()); EXPECT_CALL(manager(), AddObserver(_)).WillOnce(WithArg<0>(Invoke( this, &DownloadHistoryTest::SetManagerObserver))); EXPECT_CALL(manager(), RemoveObserver(_)); download_created_index_ = 0; - for (size_t index = 0; index < infos->size(); ++index) { - const history::DownloadRow& row = infos->at(index); + for (size_t index = 0; index < rows.size(); ++index) { + const history::DownloadRow& row = rows.at(index); content::MockDownloadManager::CreateDownloadItemAdapter adapter( row.guid, history::ToContentDownloadId(row.id), row.current_path, row.target_path, row.url_chain, row.referrer_url, row.site_url, @@ -246,7 +251,7 @@ } } history_ = new FakeHistoryAdapter(); - history_->ExpectWillQueryDownloads(std::move(infos)); + history_->ExpectWillQueryDownloads(std::move(rows)); EXPECT_CALL(manager(), GetAllDownloads(_)).WillRepeatedly(Return()); download_history_.reset(new DownloadHistory( &manager(), @@ -282,10 +287,9 @@ history_->FailCreateDownload(); } - void ExpectDownloadCreated( - const history::DownloadRow& info) { + void ExpectDownloadCreated(const history::DownloadRow& row) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - history_->ExpectDownloadCreated(info); + history_->ExpectDownloadCreated(row); } void ExpectNoDownloadCreated() { @@ -293,10 +297,10 @@ history_->ExpectNoDownloadCreated(); } - void ExpectDownloadUpdated(const history::DownloadRow& info, + void ExpectDownloadUpdated(const history::DownloadRow& row, bool should_commit_immediately) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - history_->ExpectDownloadUpdated(info, should_commit_immediately); + history_->ExpectDownloadUpdated(row, should_commit_immediately); } void ExpectNoDownloadUpdated() { @@ -324,7 +328,7 @@ const char* url_string, const char* referrer_string, download::DownloadItem::DownloadState state, - history::DownloadRow* info) { + history::DownloadRow* row) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); size_t index = items_.size(); @@ -332,82 +336,82 @@ base::Time now = base::Time::Now(); - info->current_path = base::FilePath(path); - info->target_path = base::FilePath(path); - info->url_chain.push_back(GURL(url_string)); - info->referrer_url = GURL(referrer_string); - info->site_url = GURL("http://example.com"); - info->tab_url = GURL("http://example.com/tab-url"); - info->tab_referrer_url = GURL("http://example.com/tab-referrer-url"); - info->mime_type = "application/octet-stream"; - info->original_mime_type = "application/octet-stream"; - info->start_time = now - base::TimeDelta::FromMinutes(10); - info->end_time = now - base::TimeDelta::FromMinutes(1); - info->etag = "Etag"; - info->last_modified = "abc"; - info->received_bytes = 100; - info->total_bytes = 100; - info->state = history::ToHistoryDownloadState(state); - info->danger_type = history::ToHistoryDownloadDangerType( + row->current_path = base::FilePath(path); + row->target_path = base::FilePath(path); + row->url_chain.push_back(GURL(url_string)); + row->referrer_url = GURL(referrer_string); + row->site_url = GURL("http://example.com"); + row->tab_url = GURL("http://example.com/tab-url"); + row->tab_referrer_url = GURL("http://example.com/tab-referrer-url"); + row->mime_type = "application/octet-stream"; + row->original_mime_type = "application/octet-stream"; + row->start_time = now - base::TimeDelta::FromMinutes(10); + row->end_time = now - base::TimeDelta::FromMinutes(1); + row->etag = "Etag"; + row->last_modified = "abc"; + row->received_bytes = 100; + row->total_bytes = 100; + row->state = history::ToHistoryDownloadState(state); + row->danger_type = history::ToHistoryDownloadDangerType( download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); - info->interrupt_reason = history::ToHistoryDownloadInterruptReason( + row->interrupt_reason = history::ToHistoryDownloadInterruptReason( download::DOWNLOAD_INTERRUPT_REASON_NONE); - info->id = + row->id = history::ToHistoryDownloadId(static_cast<uint32_t>(items_.size() + 1)); - info->guid = base::GenerateGUID(); - info->opened = false; - info->last_access_time = now; - info->transient = false; + row->guid = base::GenerateGUID(); + row->opened = false; + row->last_access_time = now; + row->transient = false; - EXPECT_CALL(item(index), GetId()).WillRepeatedly(Return(info->id)); + EXPECT_CALL(item(index), GetId()).WillRepeatedly(Return(row->id)); EXPECT_CALL(item(index), GetGuid()) - .WillRepeatedly(ReturnRefOfCopy(info->guid)); + .WillRepeatedly(ReturnRefOfCopy(row->guid)); EXPECT_CALL(item(index), GetFullPath()) - .WillRepeatedly(ReturnRefOfCopy(info->current_path)); + .WillRepeatedly(ReturnRefOfCopy(row->current_path)); EXPECT_CALL(item(index), GetTargetFilePath()) - .WillRepeatedly(ReturnRefOfCopy(info->target_path)); - DCHECK_LE(1u, info->url_chain.size()); + .WillRepeatedly(ReturnRefOfCopy(row->target_path)); + DCHECK_LE(1u, row->url_chain.size()); EXPECT_CALL(item(index), GetURL()) - .WillRepeatedly(ReturnRefOfCopy(info->url_chain[0])); + .WillRepeatedly(ReturnRefOfCopy(row->url_chain[0])); EXPECT_CALL(item(index), GetUrlChain()) - .WillRepeatedly(ReturnRefOfCopy(info->url_chain)); + .WillRepeatedly(ReturnRefOfCopy(row->url_chain)); EXPECT_CALL(item(index), GetMimeType()) - .WillRepeatedly(Return(info->mime_type)); + .WillRepeatedly(Return(row->mime_type)); EXPECT_CALL(item(index), GetOriginalMimeType()) - .WillRepeatedly(Return(info->original_mime_type)); + .WillRepeatedly(Return(row->original_mime_type)); EXPECT_CALL(item(index), GetReferrerUrl()) - .WillRepeatedly(ReturnRefOfCopy(info->referrer_url)); + .WillRepeatedly(ReturnRefOfCopy(row->referrer_url)); EXPECT_CALL(item(index), GetSiteUrl()) - .WillRepeatedly(ReturnRefOfCopy(info->site_url)); + .WillRepeatedly(ReturnRefOfCopy(row->site_url)); EXPECT_CALL(item(index), GetTabUrl()) - .WillRepeatedly(ReturnRefOfCopy(info->tab_url)); + .WillRepeatedly(ReturnRefOfCopy(row->tab_url)); EXPECT_CALL(item(index), GetTabReferrerUrl()) - .WillRepeatedly(ReturnRefOfCopy(info->tab_referrer_url)); + .WillRepeatedly(ReturnRefOfCopy(row->tab_referrer_url)); EXPECT_CALL(item(index), GetStartTime()) - .WillRepeatedly(Return(info->start_time)); + .WillRepeatedly(Return(row->start_time)); EXPECT_CALL(item(index), GetEndTime()) - .WillRepeatedly(Return(info->end_time)); + .WillRepeatedly(Return(row->end_time)); EXPECT_CALL(item(index), GetETag()) - .WillRepeatedly(ReturnRefOfCopy(info->etag)); + .WillRepeatedly(ReturnRefOfCopy(row->etag)); EXPECT_CALL(item(index), GetLastModifiedTime()) - .WillRepeatedly(ReturnRefOfCopy(info->last_modified)); + .WillRepeatedly(ReturnRefOfCopy(row->last_modified)); EXPECT_CALL(item(index), GetReceivedBytes()) - .WillRepeatedly(Return(info->received_bytes)); + .WillRepeatedly(Return(row->received_bytes)); EXPECT_CALL(item(index), GetReceivedSlices()) .WillRepeatedly(ReturnRefOfCopy( std::vector<download::DownloadItem::ReceivedSlice>())); EXPECT_CALL(item(index), GetTotalBytes()) - .WillRepeatedly(Return(info->total_bytes)); + .WillRepeatedly(Return(row->total_bytes)); EXPECT_CALL(item(index), GetState()).WillRepeatedly(Return(state)); EXPECT_CALL(item(index), GetDangerType()) .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)); EXPECT_CALL(item(index), GetLastReason()) .WillRepeatedly(Return(download::DOWNLOAD_INTERRUPT_REASON_NONE)); - EXPECT_CALL(item(index), GetOpened()).WillRepeatedly(Return(info->opened)); + EXPECT_CALL(item(index), GetOpened()).WillRepeatedly(Return(row->opened)); EXPECT_CALL(item(index), GetLastAccessTime()) - .WillRepeatedly(Return(info->last_access_time)); + .WillRepeatedly(Return(row->last_access_time)); EXPECT_CALL(item(index), IsTransient()) - .WillRepeatedly(Return(info->transient)); + .WillRepeatedly(Return(row->transient)); EXPECT_CALL(item(index), GetTargetDisposition()) .WillRepeatedly( Return(download::DownloadItem::TARGET_DISPOSITION_OVERWRITE)); @@ -419,16 +423,16 @@ Return(state == download::DownloadItem::IN_PROGRESS ? download::DownloadItem::TYPE_ACTIVE_DOWNLOAD : download::DownloadItem::TYPE_HISTORY_IMPORT)); - EXPECT_CALL(manager(), GetDownload(info->id)) + EXPECT_CALL(manager(), GetDownload(row->id)) .WillRepeatedly(Return(&item(index))); EXPECT_CALL(item(index), IsTemporary()).WillRepeatedly(Return(false)); #if BUILDFLAG(ENABLE_EXTENSIONS) - new extensions::DownloadedByExtension(&item(index), info->by_ext_id, - info->by_ext_name); + new extensions::DownloadedByExtension(&item(index), row->by_ext_id, + row->by_ext_name); #endif - info->download_slice_info = history::GetHistoryDownloadSliceInfos( - item(index)); + row->download_slice_info = + history::GetHistoryDownloadSliceInfos(item(index)); std::vector<download::DownloadItem*> items; for (size_t i = 0; i < items_.size(); ++i) { @@ -468,14 +472,13 @@ // Load a download from history, create the item, OnDownloadCreated, // OnDownloadUpdated, OnDownloadRemoved. - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); { - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info); - CreateDownloadHistory(std::move(infos)); + std::vector<history::DownloadRow> rows = {row}; + CreateDownloadHistory(std::move(rows)); ExpectNoDownloadCreated(); } EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); @@ -483,12 +486,12 @@ // Pretend that something changed on the item. EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); - info.opened = true; - ExpectDownloadUpdated(info, false); + row.opened = true; + ExpectDownloadUpdated(row, false); // Pretend that the user removed the item. IdSet ids; - ids.insert(info.id); + ids.insert(row.id); item(0).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } @@ -499,14 +502,13 @@ // Load a download from history, create the item, OnDownloadCreated, // OnDownloadUpdated, OnDownloadRemoved. - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); { - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info); - CreateDownloadHistory(std::move(infos)); + std::vector<history::DownloadRow> rows = {row}; + CreateDownloadHistory(std::move(rows)); ExpectNoDownloadCreated(); } EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); @@ -519,7 +521,7 @@ // Pretend that the user removed the item. IdSet ids; - ids.insert(info.id); + ids.insert(row.id); item(0).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } @@ -533,9 +535,9 @@ history::HistoryService::DownloadQueryCallback* callback_storage) : HistoryAdapter(nullptr), query_callback_(callback_storage) {} - void QueryDownloads(const history::HistoryService::DownloadQueryCallback& - callback) override { - *query_callback_ = callback; + void QueryDownloads( + history::HistoryService::DownloadQueryCallback callback) override { + *query_callback_ = std::move(callback); } history::HistoryService::DownloadQueryCallback* query_callback_; @@ -556,9 +558,8 @@ ASSERT_FALSE(query_callback.is_null()); // Now invoke the query completion callback. - std::unique_ptr<std::vector<history::DownloadRow>> query_results( - new std::vector<history::DownloadRow>()); - query_callback.Run(std::move(query_results)); + std::vector<history::DownloadRow> query_results; + std::move(query_callback).Run(std::move(query_results)); EXPECT_TRUE(observer.on_history_query_complete_called_); history->RemoveObserver(&observer); } @@ -567,7 +568,7 @@ // observer that was added after the initial history query completing. TEST_F(DownloadHistoryTest, DownloadHistoryTest_OnHistoryQueryComplete_Post) { TestDownloadHistoryObserver observer; - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); download_history()->AddObserver(&observer); EXPECT_TRUE(observer.on_history_query_complete_called_); download_history()->RemoveObserver(&observer); @@ -581,27 +582,27 @@ // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); // Pretend the manager just created |item|. CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Pretend that something changed on the item. EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); - info.opened = true; - ExpectDownloadUpdated(info, false); + row.opened = true; + ExpectDownloadUpdated(row, false); // Pretend that the user removed the item. IdSet ids; - ids.insert(info.id); + ids.insert(row.id); item(0).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); } @@ -610,15 +611,15 @@ // updates. TEST_F(DownloadHistoryTest, DownloadHistoryTest_Update) { SetDownloadDBEnabled(false); - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); base::FilePath new_path(FILE_PATH_LITERAL("/foo/baz.txt")); @@ -628,28 +629,28 @@ // current_path EXPECT_CALL(item(0), GetFullPath()).WillRepeatedly(ReturnRefOfCopy(new_path)); - info.current_path = new_path; + row.current_path = new_path; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, true); + ExpectDownloadUpdated(row, true); // target_path EXPECT_CALL(item(0), GetTargetFilePath()) .WillRepeatedly(ReturnRefOfCopy(new_path)); - info.target_path = new_path; + row.target_path = new_path; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // end_time EXPECT_CALL(item(0), GetEndTime()).WillRepeatedly(Return(new_time)); - info.end_time = new_time; + row.end_time = new_time; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // received_bytes EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(101)); - info.received_bytes = 101; + row.received_bytes = 101; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // received slices std::vector<download::DownloadItem::ReceivedSlice> slices; @@ -657,65 +658,65 @@ slices.push_back(download::DownloadItem::ReceivedSlice(1000, 500)); EXPECT_CALL(item(0), GetReceivedSlices()).WillRepeatedly( ReturnRefOfCopy(slices)); - info.download_slice_info = history::GetHistoryDownloadSliceInfos(item(0)); + row.download_slice_info = history::GetHistoryDownloadSliceInfos(item(0)); item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // total_bytes EXPECT_CALL(item(0), GetTotalBytes()).WillRepeatedly(Return(102)); - info.total_bytes = 102; + row.total_bytes = 102; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // etag EXPECT_CALL(item(0), GetETag()).WillRepeatedly(ReturnRefOfCopy(new_etag)); - info.etag = new_etag; + row.etag = new_etag; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // last_modified EXPECT_CALL(item(0), GetLastModifiedTime()) .WillRepeatedly(ReturnRefOfCopy(new_last_modifed)); - info.last_modified = new_last_modifed; + row.last_modified = new_last_modifed; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // state // Changing the state to INTERRUPTED will remove its stored state. EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(download::DownloadItem::INTERRUPTED)); - info.state = history::DownloadState::INTERRUPTED; + row.state = history::DownloadState::INTERRUPTED; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // Changing the state back to IN_PROGRESS to reset its stored state. EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(download::DownloadItem::IN_PROGRESS)); - info.state = history::DownloadState::IN_PROGRESS; + row.state = history::DownloadState::IN_PROGRESS; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, true); + ExpectDownloadUpdated(row, true); // danger_type EXPECT_CALL(item(0), GetDangerType()) .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT)); - info.danger_type = history::DownloadDangerType::DANGEROUS_CONTENT; + row.danger_type = history::DownloadDangerType::DANGEROUS_CONTENT; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // interrupt_reason EXPECT_CALL(item(0), GetLastReason()) .WillRepeatedly( Return(download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED)); - info.interrupt_reason = history::ToHistoryDownloadInterruptReason( + row.interrupt_reason = history::ToHistoryDownloadInterruptReason( download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED); item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); // opened EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true)); - info.opened = true; + row.opened = true; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, false); + ExpectDownloadUpdated(row, false); } // Test creating a new item, saving it, removing it by setting it Temporary, @@ -727,16 +728,16 @@ // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::COMPLETE, &info); + download::DownloadItem::COMPLETE, &row); // Pretend the manager just created |item|. CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Pretend the item was marked temporary. DownloadHistory should remove it @@ -744,7 +745,7 @@ EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(true)); item(0).NotifyObserversDownloadUpdated(); IdSet ids; - ids.insert(info.id); + ids.insert(row.id); ExpectDownloadsRemoved(ids); // Change something that would make DownloadHistory call UpdateDownload if the @@ -757,24 +758,24 @@ // DownloadHistory call CreateDownload. EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(false)); item(0).NotifyObserversDownloadUpdated(); - info.received_bytes = 4200; - ExpectDownloadCreated(info); + row.received_bytes = 4200; + ExpectDownloadCreated(row); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100)); item(0).NotifyObserversDownloadUpdated(); - info.received_bytes = 100; - ExpectDownloadUpdated(info, true); + row.received_bytes = 100; + ExpectDownloadUpdated(row, true); } // Test removing downloads while they're still being added. TEST_F(DownloadHistoryTest, DownloadHistoryTest_RemoveWhileAdding) { - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::COMPLETE, &info); + download::DownloadItem::COMPLETE, &row); EXPECT_CALL(item(0), IsDone()).WillRepeatedly(Return(true)); // Instruct CreateDownload() to not callback to DownloadHistory immediately, // but to wait for FinishCreateDownload(). @@ -782,7 +783,7 @@ // Pretend the manager just created |item|. CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); // Call OnDownloadRemoved before calling back to DownloadHistory::ItemAdded(). @@ -799,7 +800,7 @@ // RemoveDownloads() for the item that was removed while it was being added. FinishCreateDownload(); IdSet ids; - ids.insert(info.id); + ids.insert(row.id); ExpectDownloadsRemoved(ids); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); } @@ -808,18 +809,16 @@ TEST_F(DownloadHistoryTest, DownloadHistoryTest_Multiple) { // Load a download from history, create the item, OnDownloadCreated, // OnDownloadUpdated, OnDownloadRemoved. - history::DownloadRow info0, info1; + history::DownloadRow row0, row1; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::COMPLETE, &info0); + download::DownloadItem::COMPLETE, &row0); InitBasicItem(FILE_PATH_LITERAL("/foo/qux.pdf"), "http://example.com/qux.pdf", "http://example.com/referrer1.html", - download::DownloadItem::COMPLETE, &info1); + download::DownloadItem::COMPLETE, &row1); { - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info0); - infos->push_back(info1); - CreateDownloadHistory(std::move(infos)); + std::vector<history::DownloadRow> rows = {row0, row1}; + CreateDownloadHistory(std::move(rows)); ExpectNoDownloadCreated(); } @@ -828,8 +827,8 @@ // Pretend that the user removed both items. IdSet ids; - ids.insert(info0.id); - ids.insert(info1.id); + ids.insert(row0.id); + ids.insert(row1.id); item(0).NotifyObserversDownloadRemoved(); item(1).NotifyObserversDownloadRemoved(); ExpectDownloadsRemoved(ids); @@ -842,35 +841,35 @@ // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::COMPLETE, &info); + download::DownloadItem::COMPLETE, &row); FailCreateDownload(); // Pretend the manager just created |item|. CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100)); item(0).NotifyObserversDownloadUpdated(); - info.received_bytes = 100; - ExpectDownloadCreated(info); + row.received_bytes = 100; + ExpectDownloadCreated(row); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); } TEST_F(DownloadHistoryTest, DownloadHistoryTest_UpdateWhileAdding) { // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated, // OnDownloadRemoved. - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::COMPLETE, &info); + download::DownloadItem::COMPLETE, &row); EXPECT_CALL(item(0), IsDone()).WillRepeatedly(Return(true)); // Instruct CreateDownload() to not callback to DownloadHistory immediately, // but to wait for FinishCreateDownload(). @@ -878,7 +877,7 @@ // Pretend the manager just created |item|. CallOnDownloadCreated(0); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0))); // Pretend that something changed on the item. @@ -890,8 +889,8 @@ // ItemAdded should call OnDownloadUpdated, which should detect that the item // changed while it was being added and call UpdateDownload immediately. - info.opened = true; - ExpectDownloadUpdated(info, true); + row.opened = true; + ExpectDownloadUpdated(row, true); } // Test creating and updating an item with DownloadDB enabled. @@ -900,12 +899,12 @@ SetDownloadDBEnabled(true); // Create a fresh item not from download DB - CreateDownloadHistory(std::unique_ptr<InfoVector>(new InfoVector())); + CreateDownloadHistory({}); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); // Incomplete download will not be inserted into history. CallOnDownloadCreated(0); @@ -915,9 +914,9 @@ EXPECT_CALL(item(0), IsDone()).WillRepeatedly(Return(true)); EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(download::DownloadItem::COMPLETE)); - info.state = history::DownloadState::COMPLETE; + row.state = history::DownloadState::COMPLETE; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadCreated(info); + ExpectDownloadCreated(row); } // Test creating history download item that exists in DownloadDB. @@ -925,16 +924,15 @@ // Enable download DB. SetDownloadDBEnabled(true); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); // Modify the item so it doesn't match the history record. EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(50)); - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info); - CreateDownloadHistory(std::move(infos)); + std::vector<history::DownloadRow> rows = {row}; + CreateDownloadHistory(std::move(rows)); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); // Modify the item, it should not trigger any updates. @@ -946,11 +944,11 @@ EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(download::DownloadItem::COMPLETE)); EXPECT_CALL(item(0), IsDone()).WillRepeatedly(Return(true)); - info.opened = true; - info.received_bytes = 50; - info.state = history::DownloadState::COMPLETE; + row.opened = true; + row.received_bytes = 50; + row.state = history::DownloadState::COMPLETE; item(0).NotifyObserversDownloadUpdated(); - ExpectDownloadUpdated(info, true); + ExpectDownloadUpdated(row, true); } // Test creating a in-progress history download item that is non-resumable in @@ -960,10 +958,10 @@ // Enable download DB. SetDownloadDBEnabled(true); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); // Modify the item so it doesn't match the history record. EXPECT_CALL(item(0), GetLastReason()) @@ -972,15 +970,14 @@ EXPECT_CALL(item(0), GetState()) .WillRepeatedly(Return(download::DownloadItem::INTERRUPTED)); EXPECT_CALL(item(0), IsDone()).WillRepeatedly(Return(true)); - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info); + std::vector<history::DownloadRow> rows = {row}; // Create the history and a db update should be triggered. - CreateDownloadHistory(std::move(infos)); + CreateDownloadHistory(std::move(rows)); EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0))); - info.interrupt_reason = download::DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN; - info.state = history::DownloadState::INTERRUPTED; - ExpectDownloadUpdated(info, true); + row.interrupt_reason = download::DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN; + row.state = history::DownloadState::INTERRUPTED; + ExpectDownloadUpdated(row, true); } // Test loading history download item that will be cleared by |manager_| @@ -988,18 +985,17 @@ // Enable download DB. SetDownloadDBEnabled(true); - history::DownloadRow info; + history::DownloadRow row; InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"), "http://example.com/bar.pdf", "http://example.com/referrer.html", - download::DownloadItem::IN_PROGRESS, &info); + download::DownloadItem::IN_PROGRESS, &row); - std::unique_ptr<InfoVector> infos(new InfoVector()); - infos->push_back(info); - CreateDownloadHistory(std::move(infos), true); + std::vector<history::DownloadRow> rows = {row}; + CreateDownloadHistory(std::move(rows), true); // The download should be removed from history afterwards. IdSet ids; - ids.insert(info.id); + ids.insert(row.id); ExpectDownloadsRemoved(ids); }
diff --git a/chrome/browser/download/download_ui_controller_unittest.cc b/chrome/browser/download/download_ui_controller_unittest.cc index 45694a03..debc602 100644 --- a/chrome/browser/download/download_ui_controller_unittest.cc +++ b/chrome/browser/download/download_ui_controller_unittest.cc
@@ -111,10 +111,10 @@ download::DownloadItem* notified_item() { return notified_item_; } // DownloadHistory performs a query of existing downloads when it is first - // instantiated. This method returns the completion callback for that query. - // It can be used to inject history downloads. - const HistoryService::DownloadQueryCallback& history_query_callback() const { - return history_adapter_->download_query_callback_; + // instantiated. This method returns a pointer to the completion callback + // for that query. It can be used to inject history downloads. + HistoryService::DownloadQueryCallback* history_query_callback() { + return &(history_adapter_->download_query_callback_); } // DownloadManager::Observer registered by DownloadHistory. @@ -134,8 +134,8 @@ private: void QueryDownloads( - const HistoryService::DownloadQueryCallback& callback) override { - download_query_callback_ = callback; + HistoryService::DownloadQueryCallback callback) override { + download_query_callback_ = std::move(callback); } void UpdateDownload(const history::DownloadRow& data, @@ -327,7 +327,7 @@ // DownloadHistory should already have been created. It performs a query of // existing downloads upon creation. We'll use the callback to inject a // history download. - ASSERT_FALSE(history_query_callback().is_null()); + ASSERT_FALSE(history_query_callback()->is_null()); // download_history_manager_observer is the DownloadManager::Observer // registered by the DownloadHistory. DownloadHistory relies on the @@ -335,10 +335,9 @@ // from history. ASSERT_TRUE(download_history_manager_observer()); - std::unique_ptr<std::vector<history::DownloadRow>> history_downloads; - history_downloads.reset(new std::vector<history::DownloadRow>()); - history_downloads->push_back(history::DownloadRow()); - history_downloads->front().id = 1; + std::vector<history::DownloadRow> history_downloads; + history_downloads.push_back(history::DownloadRow()); + history_downloads.front().id = 1; std::vector<GURL> url_chain; GURL url; @@ -373,7 +372,7 @@ Return(item.get()))); EXPECT_CALL(mock_function, Call()); - history_query_callback().Run(std::move(history_downloads)); + std::move(*history_query_callback()).Run(std::move(history_downloads)); mock_function.Call(); }
diff --git a/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc b/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc index bc7a300..eff7bf7 100644 --- a/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc +++ b/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc
@@ -100,7 +100,7 @@ private: void QueryDownloads( - const HistoryService::DownloadQueryCallback& callback) override {} + HistoryService::DownloadQueryCallback callback) override {} }; // Constructs and returns a TestDownloadCoreService.
diff --git a/chrome/browser/extensions/api/notifications/notifications_api.cc b/chrome/browser/extensions/api/notifications/notifications_api.cc index 45ea951..752316e4 100644 --- a/chrome/browser/extensions/api/notifications/notifications_api.cc +++ b/chrome/browser/extensions/api/notifications/notifications_api.cc
@@ -603,11 +603,6 @@ SetResult(std::make_unique<base::Value>(notification_id)); - // TODO(crbug.com/749402): Cap the length of notification Ids to a certain - // limit if the histogram indicates that this is safe to do. - UMA_HISTOGRAM_COUNTS_1000("Notifications.ExtensionNotificationIdLength", - notification_id.size()); - // TODO(dewittj): Add more human-readable error strings if this fails. if (!CreateNotification(notification_id, ¶ms_->options)) return false;
diff --git a/chrome/browser/extensions/bookmark_app_helper.cc b/chrome/browser/extensions/bookmark_app_helper.cc index 4bc6f9c..1083d79 100644 --- a/chrome/browser/extensions/bookmark_app_helper.cc +++ b/chrome/browser/extensions/bookmark_app_helper.cc
@@ -381,17 +381,10 @@ // installation code shouldn't have to perform UI work. if (for_installable_site_ == web_app::ForInstallableSite::kYes) { web_app_info_.open_as_window = true; - if (install_source_ == WebappInstallSource::OMNIBOX_INSTALL_ICON) { chrome::ShowPWAInstallBubble( contents_, std::make_unique<WebApplicationInfo>(web_app_info_), base::BindOnce(&BookmarkAppHelper::OnBubbleCompleted, weak_factory_.GetWeakPtr())); - } else { - chrome::ShowPWAInstallDialog( - contents_, std::make_unique<WebApplicationInfo>(web_app_info_), - base::BindOnce(&BookmarkAppHelper::OnBubbleCompleted, - weak_factory_.GetWeakPtr())); - } } else { chrome::ShowBookmarkAppDialog( contents_, std::make_unique<WebApplicationInfo>(web_app_info_),
diff --git a/chrome/browser/extensions/chrome_extensions_interface_registration.cc b/chrome/browser/extensions/chrome_extensions_interface_registration.cc index 5a1307a..8d6d170 100644 --- a/chrome/browser/extensions/chrome_extensions_interface_registration.cc +++ b/chrome/browser/extensions/chrome_extensions_interface_registration.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/extensions/chrome_extensions_interface_registration.h" #include <memory> +#include <string> #include <utility> #include "base/bind.h" @@ -37,6 +38,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/video_capture/public/mojom/constants.mojom.h" #include "ui/base/ime/chromeos/extension_ime_util.h" +#include "ui/base/ime/chromeos/input_method_manager.h" #endif #if defined(KIOSK_NEXT) @@ -48,16 +50,15 @@ namespace { #if defined(OS_CHROMEOS) -// Forwards service requests to Service Manager since the renderer cannot launch -// out-of-process services on its own. -template <typename Interface> -void ForwardRequest(const char* service_name, - mojo::InterfaceRequest<Interface> request, - content::RenderFrameHost* source) { - content::ServiceManagerConnection::GetForProcess() - ->GetConnector() - ->BindInterface(service_name, std::move(request)); +#if defined(GOOGLE_CHROME_BUILD) +// Resolves InputEngineManager request in InputMethodManager. +void BindInputEngineManager( + chromeos::ime::mojom::InputEngineManagerRequest request, + content::RenderFrameHost* source) { + chromeos::input_method::InputMethodManager::Get()->ConnectInputEngineManager( + std::move(request)); } +#endif // defined(GOOGLE_CHROME_BUILD) #if defined(KIOSK_NEXT) const char kKioskNextHomeInterfaceBrokerImplKey[] = "cros_kiosk_next_home_impl"; @@ -153,9 +154,7 @@ #if defined(GOOGLE_CHROME_BUILD) // Registry InputEngineManager for official Google XKB Input only. if (extension->id() == chromeos::extension_ime_util::kXkbExtensionId) { - registry->AddInterface(base::BindRepeating( - &ForwardRequest<chromeos::ime::mojom::InputEngineManager>, - chromeos::ime::mojom::kServiceName)); + registry->AddInterface(base::BindRepeating(&BindInputEngineManager)); } #endif // defined(GOOGLE_CHROME_BUILD)
diff --git a/chrome/browser/favicon/favicon_request_handler_factory.cc b/chrome/browser/favicon/favicon_request_handler_factory.cc index 46cb2d13..64decbd 100644 --- a/chrome/browser/favicon/favicon_request_handler_factory.cc +++ b/chrome/browser/favicon/favicon_request_handler_factory.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/session_sync_service_factory.h" #include "components/favicon/core/favicon_request_handler.h" +#include "components/favicon_base/favicon_types.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/sync_sessions/open_tabs_ui_delegate.h" #include "components/sync_sessions/session_sync_service.h" @@ -19,13 +20,13 @@ namespace { -scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForPageUrl( +favicon_base::FaviconRawBitmapResult GetSyncedFaviconForPageUrl( sync_sessions::SessionSyncService* session_sync_service, const GURL& page_url) { sync_sessions::OpenTabsUIDelegate* open_tabs = session_sync_service->GetOpenTabsUIDelegate(); - return open_tabs ? open_tabs->GetSyncedFaviconForPageURL(page_url.spec()) - : nullptr; + return open_tabs ? open_tabs->GetSyncedFaviconForPageURL(page_url) + : favicon_base::FaviconRawBitmapResult(); } } // namespace
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc index 11c099a..7b6b7f7 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc
@@ -11,6 +11,7 @@ #include "base/feature_list.h" #include "base/trace_event/common/trace_event_common.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/page_load_metrics/observers/largest_contentful_paint_handler.h" #include "chrome/browser/page_load_metrics/page_load_metrics_util.h" @@ -20,8 +21,12 @@ #include "chrome/browser/prerender/prerender_manager_factory.h" #include "chrome/browser/prerender/prerender_origin.h" #include "chrome/browser/profiles/profile.h" +#include "components/content_settings/core/browser/cookie_settings.h" +#include "components/content_settings/core/common/features.h" +#include "components/content_settings/core/common/pref_names.h" #include "components/metrics/net/network_metrics_provider.h" #include "components/offline_pages/buildflags/buildflags.h" +#include "components/prefs/pref_service.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "net/base/load_timing_info.h" @@ -251,6 +256,13 @@ builder.SetSiteEngagementScore(rounded_site_engagement_score.value()); } + base::Optional<bool> third_party_cookie_blocking_enabled = + GetThirdPartyCookieBlockingEnabled(info); + if (third_party_cookie_blocking_enabled) { + builder.SetThirdPartyCookieBlockingEnabledForSite( + third_party_cookie_blocking_enabled.value()); + } + if (timing.input_to_navigation_start) { builder.SetExperimental_InputToNavigationStart( timing.input_to_navigation_start.value().InMilliseconds()); @@ -589,6 +601,23 @@ return rounded_document_engagement_score; } +base::Optional<bool> +UkmPageLoadMetricsObserver::GetThirdPartyCookieBlockingEnabled( + const page_load_metrics::PageLoadExtraInfo& info) const { + if (!browser_context_) + return base::nullopt; + + if (!base::FeatureList::IsEnabled(content_settings::kImprovedCookieControls)) + return base::nullopt; + + Profile* profile = Profile::FromBrowserContext(browser_context_); + if (!profile->GetPrefs()->GetBoolean(prefs::kCookieControlsEnabled)) + return base::nullopt; + + auto cookie_settings = CookieSettingsFactory::GetForProfile(profile); + return !cookie_settings->IsThirdPartyAccessAllowed(info.url); +} + void UkmPageLoadMetricsObserver::OnTimingUpdate( content::RenderFrameHost* subframe_rfh, const page_load_metrics::mojom::PageLoadTiming& timing,
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h index aa2905f..62184bc 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h
@@ -118,6 +118,12 @@ base::Optional<int64_t> GetRoundedSiteEngagementScore( const page_load_metrics::PageLoadExtraInfo& info) const; + // Returns whether third party cookie blocking is enabled for the committed + // URL. This is only recorded for users who have prefs::kCookieControlsEnabled + // set to true. + base::Optional<bool> GetThirdPartyCookieBlockingEnabled( + const page_load_metrics::PageLoadExtraInfo& info) const; + // Records the metrics for the nostate prefetch to an event with UKM source ID // |source_id|. void RecordNoStatePrefetchMetrics(
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc index 4f95655..08fac2ee9 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc
@@ -8,13 +8,21 @@ #include "base/metrics/metrics_hashes.h" #include "base/optional.h" +#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "base/test/trace_event_analyzer.h" #include "base/time/time.h" #include "base/trace_event/traced_value.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" #include "chrome/browser/page_load_metrics/page_load_tracker.h" #include "chrome/common/page_load_metrics/test/page_load_metrics_test_util.h" +#include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/cookie_settings.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/features.h" +#include "components/content_settings/core/common/pref_names.h" +#include "components/prefs/pref_service.h" #include "content/public/browser/web_contents.h" #include "content/public/test/navigation_simulator.h" #include "net/base/ip_endpoint.h" @@ -1116,6 +1124,103 @@ } } +TEST_F(UkmPageLoadMetricsObserverTest, ThirdPartyCookieBlockingDisabled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(content_settings::kImprovedCookieControls); + profile()->GetPrefs()->SetBoolean(prefs::kCookieControlsEnabled, false); + + NavigateAndCommit(GURL(kTestUrl1)); + + // Simulate closing the tab. + DeleteContents(); + + std::map<ukm::SourceId, ukm::mojom::UkmEntryPtr> merged_entries = + test_ukm_recorder().GetMergedEntriesByName(PageLoad::kEntryName); + EXPECT_EQ(1ul, merged_entries.size()); + + for (const auto& kv : merged_entries) { + test_ukm_recorder().ExpectEntrySourceHasUrl(kv.second.get(), + GURL(kTestUrl1)); + EXPECT_FALSE(test_ukm_recorder().EntryHasMetric( + kv.second.get(), + PageLoad::kThirdPartyCookieBlockingEnabledForSiteName)); + } +} + +TEST_F(UkmPageLoadMetricsObserverTest, + ThirdPartyCookieBlockingFeatureDisabled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(content_settings::kImprovedCookieControls); + profile()->GetPrefs()->SetBoolean(prefs::kCookieControlsEnabled, true); + + NavigateAndCommit(GURL(kTestUrl1)); + + // Simulate closing the tab. + DeleteContents(); + + std::map<ukm::SourceId, ukm::mojom::UkmEntryPtr> merged_entries = + test_ukm_recorder().GetMergedEntriesByName(PageLoad::kEntryName); + EXPECT_EQ(1ul, merged_entries.size()); + + for (const auto& kv : merged_entries) { + test_ukm_recorder().ExpectEntrySourceHasUrl(kv.second.get(), + GURL(kTestUrl1)); + EXPECT_FALSE(test_ukm_recorder().EntryHasMetric( + kv.second.get(), + PageLoad::kThirdPartyCookieBlockingEnabledForSiteName)); + } +} + +TEST_F(UkmPageLoadMetricsObserverTest, ThirdPartyCookieBlockingEnabled) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(content_settings::kImprovedCookieControls); + profile()->GetPrefs()->SetBoolean(prefs::kCookieControlsEnabled, true); + + NavigateAndCommit(GURL(kTestUrl1)); + + // Simulate closing the tab. + DeleteContents(); + + std::map<ukm::SourceId, ukm::mojom::UkmEntryPtr> merged_entries = + test_ukm_recorder().GetMergedEntriesByName(PageLoad::kEntryName); + EXPECT_EQ(1ul, merged_entries.size()); + + for (const auto& kv : merged_entries) { + test_ukm_recorder().ExpectEntrySourceHasUrl(kv.second.get(), + GURL(kTestUrl1)); + test_ukm_recorder().ExpectEntryMetric( + kv.second.get(), PageLoad::kThirdPartyCookieBlockingEnabledForSiteName, + true); + } +} + +TEST_F(UkmPageLoadMetricsObserverTest, + ThirdPartyCookieBlockingDisabledForSite) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(content_settings::kImprovedCookieControls); + profile()->GetPrefs()->SetBoolean(prefs::kCookieControlsEnabled, true); + auto cookie_settings = CookieSettingsFactory::GetForProfile(profile()); + cookie_settings->SetThirdPartyCookieSetting(GURL(kTestUrl1), + CONTENT_SETTING_ALLOW); + + NavigateAndCommit(GURL(kTestUrl1)); + + // Simulate closing the tab. + DeleteContents(); + + std::map<ukm::SourceId, ukm::mojom::UkmEntryPtr> merged_entries = + test_ukm_recorder().GetMergedEntriesByName(PageLoad::kEntryName); + EXPECT_EQ(1ul, merged_entries.size()); + + for (const auto& kv : merged_entries) { + test_ukm_recorder().ExpectEntrySourceHasUrl(kv.second.get(), + GURL(kTestUrl1)); + test_ukm_recorder().ExpectEntryMetric( + kv.second.get(), PageLoad::kThirdPartyCookieBlockingEnabledForSiteName, + false); + } +} + class TestOfflinePreviewsUkmPageLoadMetricsObserver : public UkmPageLoadMetricsObserver { public:
diff --git a/chrome/browser/printing/print_job_manager.cc b/chrome/browser/printing/print_job_manager.cc index 90e7f15..b4225e7 100644 --- a/chrome/browser/printing/print_job_manager.cc +++ b/chrome/browser/printing/print_job_manager.cc
@@ -35,7 +35,7 @@ base::AutoLock lock(lock_); for (auto it = queued_queries_.begin(); it != queued_queries_.end(); ++it) { std::unique_ptr<PrinterQuery>& query = *it; - if (query->cookie() != document_cookie || query->is_callback_pending()) + if (query->cookie() != document_cookie) continue; std::unique_ptr<PrinterQuery> current_query = std::move(query);
diff --git a/chrome/browser/printing/print_job_unittest.cc b/chrome/browser/printing/print_job_unittest.cc index 0dd6547..bd50607 100644 --- a/chrome/browser/printing/print_job_unittest.cc +++ b/chrome/browser/printing/print_job_unittest.cc
@@ -38,7 +38,8 @@ : PrinterQuery(content::ChildProcessHost::kInvalidUniqueID, content::ChildProcessHost::kInvalidUniqueID) {} - void GetSettingsDone(const PrintSettings& new_settings, + void GetSettingsDone(base::OnceClosure callback, + const PrintSettings& new_settings, PrintingContext::Result result) override { FAIL(); }
diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index bfe5af9e..6bd6dd72 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc
@@ -36,7 +36,8 @@ DCHECK(!worker_); } -void PrinterQuery::GetSettingsDone(const PrintSettings& new_settings, +void PrinterQuery::GetSettingsDone(base::OnceClosure callback, + const PrintSettings& new_settings, PrintingContext::Result result) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); is_print_dialog_box_shown_ = false; @@ -49,24 +50,21 @@ cookie_ = 0; } - if (callback_) { - // This may cause reentrancy like to call StopWorker(). - std::move(callback_).Run(); - } + std::move(callback).Run(); } -void PrinterQuery::PostSettingsDoneToIO(const PrintSettings& new_settings, +void PrinterQuery::PostSettingsDoneToIO(base::OnceClosure callback, + const PrintSettings& new_settings, PrintingContext::Result result) { - // |this| is owned by |callback_|, so |base::Unretained| is safe. + // |this| is owned by |callback|, so |base::Unretained()| is safe. base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::GetSettingsDone, base::Unretained(this), - new_settings, result)); + std::move(callback), new_settings, result)); } std::unique_ptr<PrintJobWorker> PrinterQuery::DetachWorker() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!callback_); DCHECK(worker_); return std::move(worker_); @@ -80,10 +78,6 @@ return cookie_; } -void PrinterQuery::set_callback(base::OnceClosure callback) { - callback_ = std::move(callback); -} - void PrinterQuery::GetSettings(GetSettingsAskParam ask_user_for_settings, int expected_page_count, bool has_selection, @@ -94,34 +88,35 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(!is_print_dialog_box_shown_ || !is_scripted); - StartWorker(std::move(callback)); + StartWorker(); // Real work is done in PrintJobWorker::GetSettings(). is_print_dialog_box_shown_ = ask_user_for_settings == GetSettingsAskParam::ASK_USER; - // |this| is owned by |callback_|, so |base::Unretained| is safe. + // |this| is owned by |callback|, so |base::Unretained()| is safe. worker_->PostTask( FROM_HERE, - base::BindOnce(&PrintJobWorker::GetSettings, - base::Unretained(worker_.get()), - is_print_dialog_box_shown_, expected_page_count, - has_selection, margin_type, is_scripted, is_modifiable, - base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, - base::Unretained(this)))); + base::BindOnce( + &PrintJobWorker::GetSettings, base::Unretained(worker_.get()), + is_print_dialog_box_shown_, expected_page_count, has_selection, + margin_type, is_scripted, is_modifiable, + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, + base::Unretained(this), std::move(callback)))); } void PrinterQuery::SetSettings(base::Value new_settings, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - StartWorker(std::move(callback)); - // |this| is owned by |callback_|, so |base::Unretained| is safe. + StartWorker(); + // |this| is owned by |callback|, so |base::Unretained()| is safe. worker_->PostTask( FROM_HERE, - base::BindOnce(&PrintJobWorker::SetSettings, - base::Unretained(worker_.get()), std::move(new_settings), - base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, - base::Unretained(this)))); + base::BindOnce( + &PrintJobWorker::SetSettings, base::Unretained(worker_.get()), + std::move(new_settings), + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, + base::Unretained(this), std::move(callback)))); } #if defined(OS_CHROMEOS) @@ -130,27 +125,25 @@ base::OnceClosure callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - StartWorker(std::move(callback)); - // |this| is owned by |callback_|, so |base::Unretained| is safe. + StartWorker(); + // |this| is owned by |callback|, so |base::Unretained()| is safe. worker_->PostTask( FROM_HERE, - base::BindOnce(&PrintJobWorker::SetSettingsFromPOD, - base::Unretained(worker_.get()), std::move(new_settings), - base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, - base::Unretained(this)))); + base::BindOnce( + &PrintJobWorker::SetSettingsFromPOD, base::Unretained(worker_.get()), + std::move(new_settings), + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, + base::Unretained(this), std::move(callback)))); } #endif -void PrinterQuery::StartWorker(base::OnceClosure callback) { +void PrinterQuery::StartWorker() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(!callback_); DCHECK(worker_); // Lazily create the worker thread. There is one worker thread per print job. if (!worker_->IsRunning()) worker_->Start(); - - callback_ = std::move(callback); } void PrinterQuery::StopWorker() { @@ -172,10 +165,6 @@ std::move(task)); } -bool PrinterQuery::is_callback_pending() const { - return !callback_.is_null(); -} - bool PrinterQuery::is_valid() const { return !!worker_; }
diff --git a/chrome/browser/printing/printer_query.h b/chrome/browser/printing/printer_query.h index 280af24..03047d9a 100644 --- a/chrome/browser/printing/printer_query.h +++ b/chrome/browser/printing/printer_query.h
@@ -72,9 +72,6 @@ // Stops the worker thread since the client is done with this object. virtual void StopWorker(); - // Returns true if a GetSettings() call is pending completion. - bool is_callback_pending() const; - int cookie() const; PrintingContext::Result last_status() const { return last_status_; } @@ -86,18 +83,17 @@ protected: // Virtual so that tests can override. - virtual void GetSettingsDone(const PrintSettings& new_settings, + virtual void GetSettingsDone(base::OnceClosure callback, + const PrintSettings& new_settings, PrintingContext::Result result); - void PostSettingsDoneToIO(const PrintSettings& new_settings, + void PostSettingsDoneToIO(base::OnceClosure callback, + const PrintSettings& new_settings, PrintingContext::Result result); - // For unit tests to manually set the print callback. - void set_callback(base::OnceClosure callback); - private: // Lazy create the worker thread. There is one worker thread per print job. - void StartWorker(base::OnceClosure callback); + void StartWorker(); // Cache of the print context settings for access in the UI thread. PrintSettings settings_; @@ -111,9 +107,6 @@ // Results from the last GetSettingsDone() callback. PrintingContext::Result last_status_ = PrintingContext::FAILED; - // Callback waiting to be run. - base::OnceClosure callback_; - // All the UI is done in a worker thread because many Win32 print functions // are blocking and enters a message loop without your consent. There is one // worker thread per print job.
diff --git a/chrome/browser/printing/test_printer_query.cc b/chrome/browser/printing/test_printer_query.cc index c3c4bca..8049255a 100644 --- a/chrome/browser/printing/test_printer_query.cc +++ b/chrome/browser/printing/test_printer_query.cc
@@ -52,7 +52,6 @@ #if defined(OS_WIN) DCHECK(printer_type_); #endif - set_callback(std::move(callback)); PrintSettings settings; PrintingContext::Result result = PrintSettingsFromJobSettings(new_settings, &settings) @@ -73,7 +72,7 @@ settings.set_printer_type(*printer_type_); #endif - GetSettingsDone(settings, result); + GetSettingsDone(std::move(callback), settings, result); } #if defined(OS_WIN)
diff --git a/chrome/browser/resources/chromeos/login/BUILD.gn b/chrome/browser/resources/chromeos/login/BUILD.gn index 2a0fda6..13c0d8f 100644 --- a/chrome/browser/resources/chromeos/login/BUILD.gn +++ b/chrome/browser/resources/chromeos/login/BUILD.gn
@@ -34,7 +34,6 @@ ":oobe_buttons", ":oobe_change_picture", ":oobe_dialog", - ":oobe_enrollment", ":oobe_eula", ":oobe_i18n_dropdown", ":oobe_network", @@ -286,12 +285,6 @@ js_library("oobe_dialog") { } -js_library("oobe_enrollment") { - deps = [ - "//ui/webui/resources/js:i18n_behavior", - ] -} - js_library("oobe_eula") { deps = [ ":oobe_dialog_host_behavior",
diff --git a/chrome/browser/resources/chromeos/login/custom_elements_oobe.html b/chrome/browser/resources/chromeos/login/custom_elements_oobe.html index 618f0cc..5a3a32cd 100644 --- a/chrome/browser/resources/chromeos/login/custom_elements_oobe.html +++ b/chrome/browser/resources/chromeos/login/custom_elements_oobe.html
@@ -18,7 +18,6 @@ <include src="oobe_buttons.html"> <include src="oobe_change_picture.html"> <include src="oobe_dialog.html"> -<include src="oobe_enrollment.html"> <include src="oobe_eula.html"> <include src="oobe_hid_detection.html"> <include src="oobe_reset.html">
diff --git a/chrome/browser/resources/chromeos/login/custom_elements_oobe.js b/chrome/browser/resources/chromeos/login/custom_elements_oobe.js index b91be2ea..7659f64 100644 --- a/chrome/browser/resources/chromeos/login/custom_elements_oobe.js +++ b/chrome/browser/resources/chromeos/login/custom_elements_oobe.js
@@ -30,7 +30,6 @@ // <include src="oobe_buttons.js"> // <include src="oobe_change_picture.js"> // <include src="oobe_dialog.js"> -// <include src="oobe_enrollment.js"> // <include src="oobe_eula.js"> // <include src="oobe_hid_detection.js"> // <include src="oobe_reset.js">
diff --git a/chrome/browser/resources/chromeos/login/enterprise_enrollment.html b/chrome/browser/resources/chromeos/login/enterprise_enrollment.html index 3db3a2a..a40486aa 100644 --- a/chrome/browser/resources/chromeos/login/enterprise_enrollment.html +++ b/chrome/browser/resources/chromeos/login/enterprise_enrollment.html
@@ -7,6 +7,34 @@ <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="stylesheet" href="gaia_card_parameters.css"> +<!-- Icons to use during enterprise enrollment --> + +<iron-iconset-svg name="oobe-enrollment-32" size="32"> + <svg> + <defs> + <g id="briefcase" fill="none" fill-rule="evenodd"> + <path d="M0 0h32v32H0z"></path> + <path d="M7 7h20v20H7z"></path> + <path fill="#1A73E8" fill-rule="nonzero" + d="M26.667 8h-5.334V5.333a2.657 2.657 0 0 0-2.666-2.666h-5.334a2.657 2.657 0 0 0-2.666 2.666V8H5.333a2.646 2.646 0 0 0-2.653 2.667l-.013 14.666A2.657 2.657 0 0 0 5.333 28h21.334a2.657 2.657 0 0 0 2.666-2.667V10.667A2.657 2.657 0 0 0 26.667 8zM16 20a2.675 2.675 0 0 1-2.667-2.667c0-1.466 1.2-2.666 2.667-2.666 1.467 0 2.667 1.2 2.667 2.666C18.667 18.8 17.467 20 16 20zm2.667-12h-5.334V5.333h5.334V8z"></path> + </g> + </defs> + </svg> +</iron-iconset-svg> + +<iron-iconset-svg name="oobe-enrollment-64" size="64"> + <svg> + <defs> + <g id="briefcase" fill="none" fill-rule="evenodd"> + <path d="M0 0h64v64H0z"></path> + <path d="M14 14h40v40H14z"></path> + <path fill="#1A73E8" fill-rule="nonzero" + d="M53.333 16H42.667v-5.333a5.315 5.315 0 0 0-5.334-5.334H26.667a5.315 5.315 0 0 0-5.334 5.334V16H10.667c-2.96 0-5.307 2.373-5.307 5.333l-.027 29.334A5.315 5.315 0 0 0 10.667 56h42.666a5.315 5.315 0 0 0 5.334-5.333V21.333A5.315 5.315 0 0 0 53.333 16zM32 40c-2.933 0-5.333-2.4-5.333-5.333 0-2.934 2.4-5.334 5.333-5.334 2.933 0 5.333 2.4 5.333 5.334C37.333 37.6 34.933 40 32 40zm5.333-24H26.667v-5.333h10.666V16z"></path> + </g> + </defs> + </svg> +</iron-iconset-svg> + <dom-module id="enterprise-enrollment"> <template> <div id="oauth-enroll-step-contents"> @@ -67,10 +95,17 @@ icon1x="oobe-enrollment-32:briefcase" icon2x="oobe-enrollment-64:briefcase"></hd-iron-icon> <h1 slot="title" i18n-content="oauthEnrollSuccessTitle"></h1> - <oobe-enrollment-success-with-domain - id="oauth-enroll-success-subtitle" - slot="subtitle"> - </oobe-enrollment-success-with-domain> + <div slot="subtitle"> + <div hidden="[[!isEmpty_(enrolledDomain_)]]"> + [[i18nDynamic(locale,'oauthEnrollSuccessTitle')]] + </div> + <div hidden="[[isEmpty_(enrolledDomain_)]]"> + <div inner-h-t-m-l= + "[[successText_(locale, deviceName_, enrolledDomain_)]]"> + </div> + <div>[[i18nDynamic(locale, 'oauthEnrollAbeSuccessSupport')]]</div> + </div> + </div> <div slot="footer" class="flex layout vertical center end-justified"> <img srcset="images/enrollment_success_illustration_1x.png 1x, images/enrollment_success_illustration_2x.png 2x"
diff --git a/chrome/browser/resources/chromeos/login/enterprise_enrollment.js b/chrome/browser/resources/chromeos/login/enterprise_enrollment.js index 52f44e5..ebc1db4 100644 --- a/chrome/browser/resources/chromeos/login/enterprise_enrollment.js +++ b/chrome/browser/resources/chromeos/login/enterprise_enrollment.js
@@ -50,6 +50,22 @@ screen: { type: Object, }, + + /** + * Domain the device was enrolled to. + */ + enrolledDomain_: { + type: String, + value: '', + }, + + /** + * Name of the device that was enrolled. + */ + deviceName_: { + type: String, + value: 'Chromebook', + }, }, /** @@ -328,9 +344,8 @@ */ showAttestationBasedEnrollmentSuccess: function( device, enterpriseEnrollmentDomain) { - this.$['oauth-enroll-success-subtitle'].deviceName = device; - this.$['oauth-enroll-success-subtitle'].enrollmentDomain = - enterpriseEnrollmentDomain; + this.enrolledDomain_ = enterpriseEnrollmentDomain; + this.deviceName_ = device; this.showStep(ENROLLMENT_STEP.SUCCESS); }, @@ -547,5 +562,17 @@ updateLocalizedContent: function() { this.offlineAdUi_.i18nUpdateLocale(); + }, + + /** + * Generates message on the success screen. + */ + successText_: function(locale, device, domain) { + return this.i18nAdvanced( + 'oauthEnrollAbeSuccessDomain', {substitutions: [device, domain]}); + }, + + isEmpty_: function(str) { + return !str; } });
diff --git a/chrome/browser/resources/chromeos/login/oobe_enrollment.html b/chrome/browser/resources/chromeos/login/oobe_enrollment.html deleted file mode 100644 index 7d8ddbe5..0000000 --- a/chrome/browser/resources/chromeos/login/oobe_enrollment.html +++ /dev/null
@@ -1,49 +0,0 @@ -<!-- Copyright 2018 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. --> - -<link rel="import" href="chrome://resources/html/i18n_behavior.html"> -<link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/iron-iconset-svg/iron-iconset-svg.html"> - -<!-- Icons to use during enterprise enrollment --> - -<iron-iconset-svg name="oobe-enrollment-32" size="32"> - <svg> - <defs> - <g id="briefcase" fill="none" fill-rule="evenodd"> - <path d="M0 0h32v32H0z"></path> - <path d="M7 7h20v20H7z"></path> - <path fill="#1A73E8" fill-rule="nonzero" - d="M26.667 8h-5.334V5.333a2.657 2.657 0 0 0-2.666-2.666h-5.334a2.657 2.657 0 0 0-2.666 2.666V8H5.333a2.646 2.646 0 0 0-2.653 2.667l-.013 14.666A2.657 2.657 0 0 0 5.333 28h21.334a2.657 2.657 0 0 0 2.666-2.667V10.667A2.657 2.657 0 0 0 26.667 8zM16 20a2.675 2.675 0 0 1-2.667-2.667c0-1.466 1.2-2.666 2.667-2.666 1.467 0 2.667 1.2 2.667 2.666C18.667 18.8 17.467 20 16 20zm2.667-12h-5.334V5.333h5.334V8z"></path> - </g> - </defs> - </svg> -</iron-iconset-svg> - -<iron-iconset-svg name="oobe-enrollment-64" size="64"> - <svg> - <defs> - <g id="briefcase" fill="none" fill-rule="evenodd"> - <path d="M0 0h64v64H0z"></path> - <path d="M14 14h40v40H14z"></path> - <path fill="#1A73E8" fill-rule="nonzero" - d="M53.333 16H42.667v-5.333a5.315 5.315 0 0 0-5.334-5.334H26.667a5.315 5.315 0 0 0-5.334 5.334V16H10.667c-2.96 0-5.307 2.373-5.307 5.333l-.027 29.334A5.315 5.315 0 0 0 10.667 56h42.666a5.315 5.315 0 0 0 5.334-5.333V21.333A5.315 5.315 0 0 0 53.333 16zM32 40c-2.933 0-5.333-2.4-5.333-5.333 0-2.934 2.4-5.334 5.333-5.334 2.933 0 5.333 2.4 5.333 5.334C37.333 37.6 34.933 40 32 40zm5.333-24H26.667v-5.333h10.666V16z"></path> - </g> - </defs> - </svg> -</iron-iconset-svg> - -<dom-module id="oobe-enrollment-success-with-domain"> - <template> - <div hidden="[[enrollmentDomain]]"> - [[i18nDynamic(locale,'oauthEnrollSuccessTitle')]] - </div> - <div hidden="[[!enrollmentDomain]]"> - <div inner-h-t-m-l="[[localizedText_(locale, deviceName, - enrollmentDomain)]]"> - </div> - <div>[[i18nDynamic(locale, 'oauthEnrollAbeSuccessSupport')]]</div> - </div> - </template> -</dom-module>
diff --git a/chrome/browser/resources/chromeos/login/oobe_enrollment.js b/chrome/browser/resources/chromeos/login/oobe_enrollment.js deleted file mode 100644 index 409013fe..0000000 --- a/chrome/browser/resources/chromeos/login/oobe_enrollment.js +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2018 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. - -Polymer({ - is: 'oobe-enrollment-success-with-domain', - behaviors: [I18nBehavior], - properties: { - /** - * Domain the device was enrolled to. - */ - enrollmentDomain: { - type: String, - value: '', - reflectToAttribute: true, - }, - - /** - * Name of the device that was enrolled. - */ - deviceName: { - type: String, - value: 'Chromebook', - }, - }, - - localizedText_: function(locale, device, domain) { - return this.i18nAdvanced( - 'oauthEnrollAbeSuccessDomain', {substitutions: [device, domain]}); - } -});
diff --git a/chrome/browser/resources/chromeos/select_to_speak/prefs_manager.js b/chrome/browser/resources/chromeos/select_to_speak/prefs_manager.js index 50bde8e..fc0c1d1 100644 --- a/chrome/browser/resources/chromeos/select_to_speak/prefs_manager.js +++ b/chrome/browser/resources/chromeos/select_to_speak/prefs_manager.js
@@ -259,7 +259,7 @@ /** * Generates the basic speech options for Select-to-Speak based on user * preferences. Call for each chrome.tts.speak. - * @return {!Object} options The TTS options. + * @return {!TtsOptions} options The TTS options. * @public */ PrefsManager.prototype.speechOptions = function() {
diff --git a/chrome/browser/resources/ntp4/apps_page.js b/chrome/browser/resources/ntp4/apps_page.js index 5c14150..c14a00e 100644 --- a/chrome/browser/resources/ntp4/apps_page.js +++ b/chrome/browser/resources/ntp4/apps_page.js
@@ -261,6 +261,10 @@ /** * Initialize the app object. * @param {Object} appData The data object that describes the app. + * + * TODO(crbug.com/425829): This function makes use of deprecated getter or + * setter functions. + * @suppress {deprecated} */ initialize: function(appData) { this.appData = appData; @@ -310,6 +314,9 @@ // This hack is here so that appContents.contextMenu will be the same as // this.contextMenu. const self = this; + + // TODO(crbug.com/425829): Remove above suppression once we no longer use + // deprecated function defineGetter. this.appContents_.__defineGetter__('contextMenu', function() { return self.contextMenu; });
diff --git a/chrome/browser/resources/settings/people_page/change_picture.html b/chrome/browser/resources/settings/people_page/change_picture.html index 002b1f13..d83319e 100644 --- a/chrome/browser/resources/settings/people_page/change_picture.html +++ b/chrome/browser/resources/settings/people_page/change_picture.html
@@ -100,6 +100,7 @@ </div> </div> <cr-picture-list id="pictureList" + hidden="[[!defaultImages_]]" camera-present="[[cameraPresent_]]" default-images="[[getDefaultImages_(defaultImages_, firstDefaultImageIndex_)]]"
diff --git a/chrome/browser/resources/settings/people_page/change_picture.js b/chrome/browser/resources/settings/people_page/change_picture.js index 9c9183b..f97aa38e 100644 --- a/chrome/browser/resources/settings/people_page/change_picture.js +++ b/chrome/browser/resources/settings/people_page/change_picture.js
@@ -39,13 +39,11 @@ /** * The active set of default user images. - * @private {!Array<!settings.DefaultImage>} + * @private {?Array<!settings.DefaultImage>} */ defaultImages_: { - type: Array, - value: function() { - return []; - }, + type: Object, + value: null, }, /** @@ -277,7 +275,7 @@ * @private */ getDefaultImages_(defaultImages, firstDefaultImageIndex) { - return defaultImages.slice(firstDefaultImageIndex); + return defaultImages ? defaultImages.slice(firstDefaultImageIndex) : []; }, /**
diff --git a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc index e204879..5b28c1e4 100644 --- a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc +++ b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc
@@ -333,8 +333,8 @@ } if (history_service->BackendLoaded()) { history_service->QueryDownloads( - base::Bind(&LastDownloadFinder::OnDownloadQuery, - weak_ptr_factory_.GetWeakPtr(), profile)); + base::BindOnce(&LastDownloadFinder::OnDownloadQuery, + weak_ptr_factory_.GetWeakPtr(), profile)); } else { // else wait until history is loaded. history_service_observer_.Add(history_service); @@ -350,7 +350,7 @@ void LastDownloadFinder::OnDownloadQuery( Profile* profile, - std::unique_ptr<std::vector<history::DownloadRow>> downloads) { + std::vector<history::DownloadRow> downloads) { // Early-exit if the history search for this profile was abandoned. auto iter = profile_states_.find(profile); if (iter == profile_states_.end()) @@ -361,7 +361,7 @@ // Find the most recent from this profile and use it if it's better than // anything else found so far. const history::DownloadRow* profile_best_binary = - FindMostInteresting(*downloads, true); + FindMostInteresting(downloads, true); if (profile_best_binary && IsMostInterestingBinary(*profile_best_binary, details_.get(), most_recent_binary_row_)) { @@ -371,7 +371,7 @@ } const history::DownloadRow* profile_best_non_binary = - FindMostInteresting(*downloads, false); + FindMostInteresting(downloads, false); if (profile_best_non_binary && IsMoreInterestingNonBinaryThan(*profile_best_non_binary, most_recent_non_binary_row_)) { @@ -445,9 +445,8 @@ if (pair.second == WAITING_FOR_HISTORY || pair.second == WAITING_FOR_NON_BINARY_HISTORY) { history_service->QueryDownloads( - base::Bind(&LastDownloadFinder::OnDownloadQuery, - weak_ptr_factory_.GetWeakPtr(), - pair.first)); + base::BindOnce(&LastDownloadFinder::OnDownloadQuery, + weak_ptr_factory_.GetWeakPtr(), pair.first)); } return; }
diff --git a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.h b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.h index 42913db..faa0b29 100644 --- a/chrome/browser/safe_browsing/incident_reporting/last_download_finder.h +++ b/chrome/browser/safe_browsing/incident_reporting/last_download_finder.h
@@ -101,9 +101,8 @@ // HistoryService::DownloadQueryCallback. Retrieves the most recent completed // executable download from |downloads| and reports results if there are no // more pending queries. - void OnDownloadQuery( - Profile* profile, - std::unique_ptr<std::vector<history::DownloadRow>> downloads); + void OnDownloadQuery(Profile* profile, + std::vector<history::DownloadRow> downloads); // Removes the profile pointed to by |it| from profile_states_ and reports // results if there are no more pending queries.
diff --git a/chrome/browser/tab_contents/navigation_metrics_recorder.cc b/chrome/browser/tab_contents/navigation_metrics_recorder.cc index 58464f9..859d8ee 100644 --- a/chrome/browser/tab_contents/navigation_metrics_recorder.cc +++ b/chrome/browser/tab_contents/navigation_metrics_recorder.cc
@@ -6,6 +6,8 @@ #include "build/build_config.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_metrics.h" #include "components/navigation_metrics/navigation_metrics.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -75,9 +77,11 @@ content::NavigationEntry* last_committed_entry = web_contents()->GetController().GetLastCommittedEntry(); + Profile* profile = Profile::FromBrowserContext(context); navigation_metrics::RecordMainFrameNavigation( last_committed_entry->GetVirtualURL(), - navigation_handle->IsSameDocument(), context->IsOffTheRecord()); + navigation_handle->IsSameDocument(), profile->IsOffTheRecord(), + ProfileMetrics::GetBrowserProfileType(profile)); } WEB_CONTENTS_USER_DATA_KEY_IMPL(NavigationMetricsRecorder)
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index a504487..9a19015 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2650,12 +2650,8 @@ "views/extensions/extensions_toolbar_button.h", "views/extensions/extensions_toolbar_container.cc", "views/extensions/extensions_toolbar_container.h", - "views/extensions/pwa_confirmation.cc", - "views/extensions/pwa_confirmation.h", "views/extensions/pwa_confirmation_bubble_view.cc", "views/extensions/pwa_confirmation_bubble_view.h", - "views/extensions/pwa_confirmation_dialog_view.cc", - "views/extensions/pwa_confirmation_dialog_view.h", "views/extensions/web_app_info_image_source.cc", "views/extensions/web_app_info_image_source.h", "views/feature_promos/feature_promo_bubble_timeout.cc",
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index a465dbd..91d95a36 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -363,6 +363,21 @@ << "browser session."; } +#if defined(OS_LINUX) || defined(OS_WIN) || defined(OS_MACOSX) + if (command_line.HasSwitch(switches::kGuest)) { + PrefService* service = g_browser_process->local_state(); + DCHECK(service); + if (service->GetBoolean(prefs::kBrowserGuestModeEnabled)) { + profile = g_browser_process->profile_manager() + ->GetProfile(ProfileManager::GetGuestProfilePath()) + ->GetOffTheRecordProfile(); + } else { + LOG(WARNING) << "Guest mode disabled by policy, launching a normal " + << "browser session."; + } + } +#endif + #if defined(OS_WIN) // Continue with the incognito profile if this is a credential provider logon. if (command_line.HasSwitch(credential_provider::kGcpwSigninSwitch))
diff --git a/chrome/browser/ui/views/content_setting_bubble_contents.cc b/chrome/browser/ui/views/content_setting_bubble_contents.cc index f10f968..69b51ed 100644 --- a/chrome/browser/ui/views/content_setting_bubble_contents.cc +++ b/chrome/browser/ui/views/content_setting_bubble_contents.cc
@@ -188,55 +188,6 @@ : base::UTF8ToUTF16(GetDevices()[index].name); } -// ContentSettingBubbleContents::Favicon -------------------------------------- - -class ContentSettingBubbleContents::Favicon : public views::ImageView { - public: - Favicon(const gfx::Image& image, - ContentSettingBubbleContents* parent, - views::Link* link); - ~Favicon() override; - - private: - // views::View overrides: - bool OnMousePressed(const ui::MouseEvent& event) override; - void OnMouseReleased(const ui::MouseEvent& event) override; - gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - - ContentSettingBubbleContents* parent_; - views::Link* link_; -}; - -ContentSettingBubbleContents::Favicon::Favicon( - const gfx::Image& image, - ContentSettingBubbleContents* parent, - views::Link* link) - : parent_(parent), - link_(link) { - SetImage(image.AsImageSkia()); -} - -ContentSettingBubbleContents::Favicon::~Favicon() { -} - -bool ContentSettingBubbleContents::Favicon::OnMousePressed( - const ui::MouseEvent& event) { - return event.IsLeftMouseButton() || event.IsMiddleMouseButton(); -} - -void ContentSettingBubbleContents::Favicon::OnMouseReleased( - const ui::MouseEvent& event) { - if ((event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && - HitTestPoint(event.location())) { - parent_->LinkClicked(link_, event.flags()); - } -} - -gfx::NativeCursor ContentSettingBubbleContents::Favicon::GetCursor( - const ui::MouseEvent& event) { - return views::GetNativeHandCursor(); -} - // ContentSettingBubbleContents::ListItemContainer ----------------------------- class ContentSettingBubbleContents::ListItemContainer : public views::View { @@ -275,16 +226,14 @@ void ContentSettingBubbleContents::ListItemContainer::AddItem( const ContentSettingBubbleModel::ListItem& item) { - views::ImageView* icon = nullptr; + views::ImageView* icon = new views::ImageView(); views::Label* label = nullptr; if (item.has_link) { views::Link* link = new views::Link(item.title); link->set_listener(parent_); link->SetElideBehavior(gfx::ELIDE_MIDDLE); - icon = new Favicon(item.image, parent_, link); label = link; } else { - icon = new views::ImageView(); icon->SetImage(item.image.AsImageSkia()); label = new views::Label(item.title); }
diff --git a/chrome/browser/ui/views/content_setting_bubble_contents.h b/chrome/browser/ui/views/content_setting_bubble_contents.h index 24ffc9a..6d97b39 100644 --- a/chrome/browser/ui/views/content_setting_bubble_contents.h +++ b/chrome/browser/ui/views/content_setting_bubble_contents.h
@@ -75,7 +75,6 @@ void OnThemeChanged() override; private: - class Favicon; class ListItemContainer; // Applies coloring to the learn more button.
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation.cc b/chrome/browser/ui/views/extensions/pwa_confirmation.cc deleted file mode 100644 index 6e9b206..0000000 --- a/chrome/browser/ui/views/extensions/pwa_confirmation.cc +++ /dev/null
@@ -1,152 +0,0 @@ -// Copyright 2019 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/ui/views/extensions/pwa_confirmation.h" - -#include "base/strings/string16.h" -#include "base/strings/string_util.h" -#include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "chrome/browser/ui/views/chrome_typography.h" -#include "chrome/browser/ui/views/extensions/web_app_info_image_source.h" -#include "chrome/grit/generated_resources.h" -#include "components/strings/grit/components_strings.h" -#include "components/url_formatter/elide_url.h" -#include "extensions/common/constants.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/text_elider.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/image_view.h" -#include "ui/views/controls/label.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/window/dialog_client_view.h" - -namespace { - -bool g_auto_accept_pwa_for_testing = false; - -// Returns an ImageView containing the app icon. -std::unique_ptr<views::ImageView> CreateIconView( - const std::vector<WebApplicationInfo::IconInfo>& icons) { - constexpr int kIconSize = 48; - gfx::ImageSkia image( - std::make_unique<WebAppInfoImageSource>(kIconSize, icons), - gfx::Size(kIconSize, kIconSize)); - - auto icon_image_view = std::make_unique<views::ImageView>(); - icon_image_view->SetImage(image); - return icon_image_view; -} - -// Returns a label containing the app name. -std::unique_ptr<views::Label> CreateNameLabel(const base::string16& name) { - auto name_label = std::make_unique<views::Label>( - name, CONTEXT_BODY_TEXT_LARGE, views::style::TextStyle::STYLE_PRIMARY); - name_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); - name_label->SetElideBehavior(gfx::ELIDE_TAIL); - return name_label; -} - -std::unique_ptr<views::Label> CreateOriginLabel(const url::Origin& origin) { - auto origin_label = std::make_unique<views::Label>( - FormatOriginForSecurityDisplay( - origin, url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS), - CONTEXT_BODY_TEXT_SMALL, STYLE_SECONDARY); - - origin_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); - - // Elide from head to prevent origin spoofing. - origin_label->SetElideBehavior(gfx::ELIDE_HEAD); - - // Multiline breaks elision, so explicitly disable multiline. - origin_label->SetMultiLine(false); - - return origin_label; -} - -void InitializeDialogView(views::DialogDelegateView* dialog, - const WebApplicationInfo& web_app_info) { - const ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); - - // Use CONTROL insets, because the icon is non-text (see documentation for - // DialogContentType). - gfx::Insets margin_insets = layout_provider->GetDialogInsetsForContentType( - views::CONTROL, views::CONTROL); - dialog->set_margins(margin_insets); - - int icon_label_spacing = layout_provider->GetDistanceMetric( - views::DISTANCE_RELATED_CONTROL_HORIZONTAL); - dialog->SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::kHorizontal, gfx::Insets(), icon_label_spacing)); - - dialog->AddChildView(CreateIconView(web_app_info.icons).release()); - - views::View* labels = new views::View(); - dialog->AddChildView(labels); - labels->SetLayoutManager( - std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); - - labels->AddChildView(CreateNameLabel(web_app_info.title).release()); - labels->AddChildView( - CreateOriginLabel(url::Origin::Create(web_app_info.app_url)).release()); -} - -} // namespace - -PWAConfirmation::PWAConfirmation( - views::DialogDelegateView* dialog, - std::unique_ptr<WebApplicationInfo> web_app_info, - chrome::AppInstallationAcceptanceCallback callback) - : web_app_info_(std::move(web_app_info)), callback_(std::move(callback)) { - DCHECK(web_app_info_); - base::TrimWhitespace(web_app_info_->title, base::TRIM_ALL, - &web_app_info_->title); - // PWAs should always be configured to open in a window. - DCHECK(web_app_info_->open_as_window); - - InitializeDialogView(dialog, *web_app_info_); - - chrome::RecordDialogCreation(chrome::DialogIdentifier::PWA_CONFIRMATION); - - if (g_auto_accept_pwa_for_testing) - dialog->Accept(); -} - -PWAConfirmation::~PWAConfirmation() {} - -base::string16 PWAConfirmation::GetWindowTitle() { - return l10n_util::GetStringUTF16( - IDS_INSTALL_TO_OS_LAUNCH_SURFACE_BUBBLE_TITLE); -} - -base::string16 PWAConfirmation::GetDialogButtonLabel(ui::DialogButton button) { - return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK - ? IDS_INSTALL_PWA_BUTTON_LABEL - : IDS_CANCEL); -} - -views::View* PWAConfirmation::GetInitiallyFocusedView( - views::DialogDelegateView* dialog) { - return nullptr; -} - -void PWAConfirmation::Accept() { - DCHECK(web_app_info_); - std::move(callback_).Run(true, std::move(web_app_info_)); -} - -void PWAConfirmation::WindowClosing() { - if (callback_) { - DCHECK(web_app_info_); - std::move(callback_).Run(false, std::move(web_app_info_)); - } -} - -namespace chrome { - -void SetAutoAcceptPWAInstallConfirmationForTesting(bool auto_accept) { - g_auto_accept_pwa_for_testing = auto_accept; -} - -} // namespace chrome
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation.h b/chrome/browser/ui/views/extensions/pwa_confirmation.h deleted file mode 100644 index 697e78eb..0000000 --- a/chrome/browser/ui/views/extensions/pwa_confirmation.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_H_ -#define CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_H_ - -#include "base/strings/string16.h" -#include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/common/web_application_info.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { -class View; -} - -// Provides the core UI for confirming the installation of a PWA for the -// |PWAConfirmationDialogView| and |PWAConfirmationBubbleView| form factors. -class PWAConfirmation { - public: - static base::string16 GetWindowTitle(); - static base::string16 GetDialogButtonLabel(ui::DialogButton button); - static views::View* GetInitiallyFocusedView( - views::DialogDelegateView* dialog); - - PWAConfirmation(views::DialogDelegateView* dialog, - std::unique_ptr<WebApplicationInfo> web_app_info, - chrome::AppInstallationAcceptanceCallback callback); - ~PWAConfirmation(); - - void Accept(); - void WindowClosing(); - - private: - // The WebApplicationInfo that the user is confirming. - // Cleared when the dialog completes (Accept/WindowClosing). - std::unique_ptr<WebApplicationInfo> web_app_info_; - chrome::AppInstallationAcceptanceCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(PWAConfirmation); -}; - -#endif // CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_H_
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.cc b/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.cc index 0e0af806..a0f86cd 100644 --- a/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.cc +++ b/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.cc
@@ -4,56 +4,161 @@ #include "chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h" +#include "base/strings/string16.h" +#include "base/strings/string_util.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/browser/ui/views/extensions/web_app_info_image_source.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/toolbar_button_provider.h" #include "chrome/browser/ui/views/page_action/omnibox_page_action_icon_container_view.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" +#include "components/url_formatter/elide_url.h" +#include "extensions/common/constants.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/image/image_skia.h" +#include "ui/gfx/text_elider.h" +#include "ui/views/controls/button/label_button.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/window/dialog_client_view.h" namespace { PWAConfirmationBubbleView* g_bubble_ = nullptr; +bool g_auto_accept_pwa_for_testing = false; + +// Returns an ImageView containing the app icon. +std::unique_ptr<views::ImageView> CreateIconView( + const std::vector<WebApplicationInfo::IconInfo>& icons) { + constexpr int kIconSize = 48; + gfx::ImageSkia image( + std::make_unique<WebAppInfoImageSource>(kIconSize, icons), + gfx::Size(kIconSize, kIconSize)); + + auto icon_image_view = std::make_unique<views::ImageView>(); + icon_image_view->SetImage(image); + return icon_image_view; +} + +// Returns a label containing the app name. +std::unique_ptr<views::Label> CreateNameLabel(const base::string16& name) { + auto name_label = std::make_unique<views::Label>( + name, CONTEXT_BODY_TEXT_LARGE, views::style::TextStyle::STYLE_PRIMARY); + name_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + name_label->SetElideBehavior(gfx::ELIDE_TAIL); + return name_label; +} + +std::unique_ptr<views::Label> CreateOriginLabel(const url::Origin& origin) { + auto origin_label = std::make_unique<views::Label>( + FormatOriginForSecurityDisplay( + origin, url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS), + CONTEXT_BODY_TEXT_SMALL, STYLE_SECONDARY); + + origin_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + + // Elide from head to prevent origin spoofing. + origin_label->SetElideBehavior(gfx::ELIDE_HEAD); + + // Multiline breaks elision, so explicitly disable multiline. + origin_label->SetMultiLine(false); + + return origin_label; +} + } // namespace +// static +bool PWAConfirmationBubbleView::IsShowing() { + return g_bubble_; +} + PWAConfirmationBubbleView::PWAConfirmationBubbleView( views::View* anchor_view, views::Button* highlight_button, std::unique_ptr<WebApplicationInfo> web_app_info, chrome::AppInstallationAcceptanceCallback callback) : LocationBarBubbleDelegateView(anchor_view, gfx::Point(), nullptr), - pwa_confirmation_(this, std::move(web_app_info), std::move(callback)) { + web_app_info_(std::move(web_app_info)), + callback_(std::move(callback)) { + DCHECK(web_app_info_); + base::TrimWhitespace(web_app_info_->title, base::TRIM_ALL, + &web_app_info_->title); + // PWAs should always be configured to open in a window. + DCHECK(web_app_info_->open_as_window); + + const ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); + + // Use CONTROL insets, because the icon is non-text (see documentation for + // DialogContentType). + gfx::Insets margin_insets = layout_provider->GetDialogInsetsForContentType( + views::CONTROL, views::CONTROL); + set_margins(margin_insets); + + int icon_label_spacing = layout_provider->GetDistanceMetric( + views::DISTANCE_RELATED_CONTROL_HORIZONTAL); + SetLayoutManager(std::make_unique<views::BoxLayout>( + views::BoxLayout::kHorizontal, gfx::Insets(), icon_label_spacing)); + + AddChildView(CreateIconView(web_app_info_->icons).release()); + + views::View* labels = new views::View(); + AddChildView(labels); + labels->SetLayoutManager( + std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); + + labels->AddChildView(CreateNameLabel(web_app_info_->title).release()); + labels->AddChildView( + CreateOriginLabel(url::Origin::Create(web_app_info_->app_url)).release()); + + chrome::RecordDialogCreation(chrome::DialogIdentifier::PWA_CONFIRMATION); + + if (g_auto_accept_pwa_for_testing) + Accept(); + SetHighlightedButton(highlight_button); } +PWAConfirmationBubbleView::~PWAConfirmationBubbleView() = default; + bool PWAConfirmationBubbleView::ShouldShowCloseButton() const { return true; } base::string16 PWAConfirmationBubbleView::GetWindowTitle() const { - return PWAConfirmation::GetWindowTitle(); + return l10n_util::GetStringUTF16( + IDS_INSTALL_TO_OS_LAUNCH_SURFACE_BUBBLE_TITLE); } base::string16 PWAConfirmationBubbleView::GetDialogButtonLabel( ui::DialogButton button) const { - return PWAConfirmation::GetDialogButtonLabel(button); + return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK + ? IDS_INSTALL_PWA_BUTTON_LABEL + : IDS_CANCEL); } views::View* PWAConfirmationBubbleView::GetInitiallyFocusedView() { - return PWAConfirmation::GetInitiallyFocusedView(this); + return nullptr; } void PWAConfirmationBubbleView::WindowClosing() { DCHECK_EQ(g_bubble_, this); g_bubble_ = nullptr; - pwa_confirmation_.WindowClosing(); + if (callback_) { + DCHECK(web_app_info_); + std::move(callback_).Run(false, std::move(web_app_info_)); + } } bool PWAConfirmationBubbleView::Accept() { - pwa_confirmation_.Accept(); + DCHECK(web_app_info_); + std::move(callback_).Run(true, std::move(web_app_info_)); return true; } @@ -72,16 +177,22 @@ BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); views::View* anchor_view = browser_view->toolbar_button_provider()->GetAnchorView(); - views::Button* highlight_button = + PageActionIconView* icon = browser_view->toolbar_button_provider() ->GetOmniboxPageActionIconContainerView() ->GetPageActionIconView(PageActionIconType::kPwaInstall); - g_bubble_ = new PWAConfirmationBubbleView(anchor_view, highlight_button, - std::move(web_app_info), - std::move(callback)); + g_bubble_ = new PWAConfirmationBubbleView( + anchor_view, icon, std::move(web_app_info), std::move(callback)); views::BubbleDialogDelegateView::CreateBubble(g_bubble_)->Show(); + + icon->Update(); + DCHECK(icon->GetVisible()); +} + +void SetAutoAcceptPWAInstallConfirmationForTesting(bool auto_accept) { + g_auto_accept_pwa_for_testing = auto_accept; } } // namespace chrome
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h b/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h index 3e40d95a..78c1e88 100644 --- a/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h +++ b/chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_BUBBLE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_BUBBLE_VIEW_H_ -#include "chrome/browser/ui/views/extensions/pwa_confirmation.h" +#include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h" #include "chrome/common/web_application_info.h" #include "content/public/browser/web_contents.h" @@ -15,10 +15,13 @@ // icon in the omnibox. class PWAConfirmationBubbleView : public LocationBarBubbleDelegateView { public: + static bool IsShowing(); + PWAConfirmationBubbleView(views::View* anchor_view, views::Button* highlight_button, std::unique_ptr<WebApplicationInfo> web_app_info, chrome::AppInstallationAcceptanceCallback callback); + ~PWAConfirmationBubbleView() override; // LocationBarBubbleDelegateView: bool ShouldShowCloseButton() const override; @@ -29,7 +32,8 @@ bool Accept() override; private: - PWAConfirmation pwa_confirmation_; + std::unique_ptr<WebApplicationInfo> web_app_info_; + chrome::AppInstallationAcceptanceCallback callback_; DISALLOW_COPY_AND_ASSIGN(PWAConfirmationBubbleView); };
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.cc b/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.cc deleted file mode 100644 index 330531d..0000000 --- a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.cc +++ /dev/null
@@ -1,73 +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. - -#include "chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.h" - -#include <memory> -#include <utility> - -#include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "components/constrained_window/constrained_window_views.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/dialog_client_view.h" -#include "url/origin.h" - -PWAConfirmationDialogView::PWAConfirmationDialogView( - std::unique_ptr<WebApplicationInfo> web_app_info, - chrome::AppInstallationAcceptanceCallback callback) - : pwa_confirmation_(this, std::move(web_app_info), std::move(callback)) {} - -PWAConfirmationDialogView::~PWAConfirmationDialogView() {} - -gfx::Size PWAConfirmationDialogView::CalculatePreferredSize() const { - int bubble_width = ChromeLayoutProvider::Get()->GetDistanceMetric( - DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH); - - gfx::Size size = views::DialogDelegateView::CalculatePreferredSize(); - size.SetToMin(gfx::Size(bubble_width - margins().width(), size.height())); - return size; -} - -ui::ModalType PWAConfirmationDialogView::GetModalType() const { - return ui::MODAL_TYPE_CHILD; -} - -base::string16 PWAConfirmationDialogView::GetWindowTitle() const { - return PWAConfirmation::GetWindowTitle(); -} - -bool PWAConfirmationDialogView::ShouldShowCloseButton() const { - return false; -} - -views::View* PWAConfirmationDialogView::GetInitiallyFocusedView() { - return PWAConfirmation::GetInitiallyFocusedView(this); -} - -void PWAConfirmationDialogView::WindowClosing() { - pwa_confirmation_.WindowClosing(); -} - -bool PWAConfirmationDialogView::Accept() { - pwa_confirmation_.Accept(); - return true; -} - -base::string16 PWAConfirmationDialogView::GetDialogButtonLabel( - ui::DialogButton button) const { - return PWAConfirmation::GetDialogButtonLabel(button); -} - -namespace chrome { - -void ShowPWAInstallDialog(content::WebContents* web_contents, - std::unique_ptr<WebApplicationInfo> web_app_info, - AppInstallationAcceptanceCallback callback) { - constrained_window::ShowWebModalDialogViews( - new PWAConfirmationDialogView(std::move(web_app_info), - std::move(callback)), - web_contents); -} - -} // namespace chrome
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.h b/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.h deleted file mode 100644 index 2cb7984..0000000 --- a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.h +++ /dev/null
@@ -1,47 +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 CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_DIALOG_VIEW_H_ -#define CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_DIALOG_VIEW_H_ - -#include <vector> - -#include "base/macros.h" -#include "base/strings/string16.h" -#include "chrome/browser/ui/browser_dialogs.h" -#include "chrome/browser/ui/views/extensions/pwa_confirmation.h" -#include "chrome/common/web_application_info.h" -#include "ui/views/window/dialog_delegate.h" - -// PWAConfirmationDialogView provides a dialog for accepting or rejecting the -// installation of a PWA (Progressive Web App). -class PWAConfirmationDialogView : public views::DialogDelegateView { - public: - // Constructs a PWAConfirmationDialogView. |web_app_info| contains information - // about a web app that has passed the PWA check. - PWAConfirmationDialogView(std::unique_ptr<WebApplicationInfo> web_app_info, - chrome::AppInstallationAcceptanceCallback callback); - ~PWAConfirmationDialogView() override; - - private: - // views::WidgetDelegate: - ui::ModalType GetModalType() const override; - base::string16 GetWindowTitle() const override; - bool ShouldShowCloseButton() const override; - views::View* GetInitiallyFocusedView() override; - void WindowClosing() override; - - // views::DialogDelegateView: - bool Accept() override; - base::string16 GetDialogButtonLabel(ui::DialogButton button) const override; - - // views::View: - gfx::Size CalculatePreferredSize() const override; - - PWAConfirmation pwa_confirmation_; - - DISALLOW_COPY_AND_ASSIGN(PWAConfirmationDialogView); -}; - -#endif // CHROME_BROWSER_UI_VIEWS_EXTENSIONS_PWA_CONFIRMATION_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view_browsertest.cc b/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view_browsertest.cc deleted file mode 100644 index 54d0d4b..0000000 --- a/chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view_browsertest.cc +++ /dev/null
@@ -1,79 +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. - -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/test/test_browser_dialog.h" -#include "chrome/browser/ui/views/extensions/pwa_confirmation_dialog_view.h" -#include "chrome/common/web_application_info.h" -#include "components/constrained_window/constrained_window_views.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkColor.h" - -namespace { - -// Helper class to display the PWAConfirmationView dialog for testing. -class PWAConfirmationDialogViewTest : public DialogBrowserTest { - public: - PWAConfirmationDialogViewTest() {} - - void ShowUi(const std::string& name) override { - constexpr int kIconSize = 48; - WebApplicationInfo::IconInfo icon_info; - icon_info.data.allocN32Pixels(kIconSize, kIconSize, true); - icon_info.data.eraseColor(SK_ColorBLUE); - icon_info.width = kIconSize; - icon_info.height = kIconSize; - - std::unique_ptr<WebApplicationInfo> web_app_info = - std::make_unique<WebApplicationInfo>(); - web_app_info->icons.push_back(icon_info); - web_app_info->open_as_window = true; - if (name == "short_text") { - web_app_info->title = base::ASCIIToUTF16("Title"); - web_app_info->app_url = GURL("https://www.example.com:9090/path"); - } else if (name == "long_text") { - web_app_info->title = - base::ASCIIToUTF16("abcd\n1234567890123456789012345678901234567890"); - - web_app_info->app_url = GURL( - "https://www" - ".1234567890123456789012345678901234567890" - ".com:443/path"); - } else if (name == "rtl") { - web_app_info->title = base::UTF8ToUTF16("דוגמא"); - web_app_info->app_url = GURL("https://דוגמא.דוגמא.דוגמא.אחד.example.com"); - } - constrained_window::ShowWebModalDialogViews( - new PWAConfirmationDialogView( - std::move(web_app_info), - chrome::AppInstallationAcceptanceCallback()), - browser()->tab_strip_model()->GetActiveWebContents()); - } - - private: - DISALLOW_COPY_AND_ASSIGN(PWAConfirmationDialogViewTest); -}; - -// Launches an installation confirmation dialog for a PWA with a short name and -// origin. -IN_PROC_BROWSER_TEST_F(PWAConfirmationDialogViewTest, InvokeUi_short_text) { - ShowAndVerifyUi(); -} - -// Launches an installation confirmation dialog for a PWA with name and origin -// long enough to be elided. -IN_PROC_BROWSER_TEST_F(PWAConfirmationDialogViewTest, InvokeUi_long_text) { - ShowAndVerifyUi(); -} - -// Launches an installation confirmation dialog for a PWA with an RTL subdomain -// which is long enough to be elided. -IN_PROC_BROWSER_TEST_F(PWAConfirmationDialogViewTest, InvokeUi_rtl) { - ShowAndVerifyUi(); -} - -} // namespace
diff --git a/chrome/browser/ui/views/page_action/pwa_install_view.cc b/chrome/browser/ui/views/page_action/pwa_install_view.cc index 8ad94a81..bb056647 100644 --- a/chrome/browser/ui/views/page_action/pwa_install_view.cc +++ b/chrome/browser/ui/views/page_action/pwa_install_view.cc
@@ -9,6 +9,7 @@ #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/banners/app_banner_manager.h" #include "chrome/browser/installable/installable_metrics.h" +#include "chrome/browser/ui/views/extensions/pwa_confirmation_bubble_view.h" #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/components/web_app_tab_helper_base.h" @@ -36,17 +37,23 @@ if (!manager) return false; + bool show_install_button = false; + bool is_probably_promotable = manager->IsProbablyPromotableWebApp(); - auto* tab_helper = - web_app::WebAppTabHelperBase::FromWebContents(web_contents); - bool is_installed = tab_helper && tab_helper->HasAssociatedApp(); - - bool show_install_button = is_probably_promotable && !is_installed; - - if (show_install_button && manager->MaybeConsumeInstallAnimation()) + if (is_probably_promotable && manager->MaybeConsumeInstallAnimation()) AnimateIn(base::nullopt); else ResetSlideAnimation(false); + if (is_probably_promotable) + show_install_button = true; + + auto* web_app_tab_helper = + web_app::WebAppTabHelperBase::FromWebContents(web_contents); + if (web_app_tab_helper && web_app_tab_helper->HasAssociatedApp()) + show_install_button = false; + + if (PWAConfirmationBubbleView::IsShowing()) + show_install_button = true; bool was_visible = GetVisible(); SetVisible(show_install_button);
diff --git a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc index 69f1c10..03b9c93 100644 --- a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc +++ b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.cc
@@ -359,8 +359,10 @@ case State::FINISHED: return l10n_util::GetStringUTF16(IDS_PLUGIN_VM_LAUNCHER_FINISHED_TITLE); case State::ERROR: - case State::NOT_ALLOWED: return l10n_util::GetStringUTF16(IDS_PLUGIN_VM_LAUNCHER_ERROR_TITLE); + case State::NOT_ALLOWED: + return l10n_util::GetStringUTF16( + IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_TITLE); } }
diff --git a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view_browsertest.cc b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view_browsertest.cc index 851ceac..b10076a7 100644 --- a/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view_browsertest.cc +++ b/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view_browsertest.cc
@@ -147,8 +147,9 @@ void CheckSetupNotAllowed() { EXPECT_FALSE(HasAcceptButton()); EXPECT_TRUE(HasCancelButton()); - EXPECT_EQ(view_->GetBigMessage(), - l10n_util::GetStringUTF16(IDS_PLUGIN_VM_LAUNCHER_ERROR_TITLE)); + EXPECT_EQ( + view_->GetBigMessage(), + l10n_util::GetStringUTF16(IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_TITLE)); EXPECT_EQ( view_->GetMessage(), l10n_util::GetStringUTF16(IDS_PLUGIN_VM_LAUNCHER_NOT_ALLOWED_MESSAGE));
diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc index 50b29e8..b36f8836 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc
@@ -30,6 +30,9 @@ #include "ui/base/models/menu_model.h" #include "ui/base/models/menu_separator_types.h" #include "ui/base/models/simple_menu_model.h" +#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/linux_ui/status_icon_linux.h" @@ -317,7 +320,23 @@ void StatusIconLinuxDbus::OnContextMenu( dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender) { - NOTIMPLEMENTED(); + dbus::MessageReader reader(method_call); + int32_t x; + int32_t y; + if (!reader.PopInt32(&x) || !reader.PopInt32(&y)) { + sender.Run(nullptr); + return; + } + + if (!menu_runner_) { + menu_runner_ = std::make_unique<views::MenuRunner>( + concat_menu_.get(), views::MenuRunner::HAS_MNEMONICS | + views::MenuRunner::CONTEXT_MENU | + views::MenuRunner::FIXED_ANCHOR); + } + menu_runner_->RunMenuAt( + nullptr, nullptr, gfx::Rect(gfx::Point(x, y), gfx::Size()), + views::MenuAnchorPosition::kTopRight, ui::MENU_SOURCE_MOUSE); sender.Run(dbus::Response::FromMethodCall(method_call)); } @@ -356,4 +375,5 @@ concat_menu_ = std::make_unique<ConcatMenuModel>(click_action_menu_.get(), model); menu_->SetModel(concat_menu_.get(), send_signal); + menu_runner_.reset(); }
diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h index fb229ef..4c193d0df 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h
@@ -16,6 +16,7 @@ #include "dbus/message.h" #include "dbus/object_proxy.h" #include "ui/base/models/simple_menu_model.h" +#include "ui/views/controls/menu/menu_runner.h" #include "ui/views/linux_ui/status_icon_linux.h" namespace gfx { @@ -99,6 +100,9 @@ // delegate_->GetMenuModel() or |empty_menu_| if the delegate's menu is null. // Appears after the other menus so that it gets destroyed first. std::unique_ptr<ConcatMenuModel> concat_menu_; + // Used when the server doesn't support DBus menus and requests for us to use + // our own menu. + std::unique_ptr<views::MenuRunner> menu_runner_; base::WeakPtrFactory<StatusIconLinuxDbus> weak_factory_;
diff --git a/chrome/browser/ui/web_applications/web_app_dialog_utils.cc b/chrome/browser/ui/web_applications/web_app_dialog_utils.cc index 2d69f63..8d03069 100644 --- a/chrome/browser/ui/web_applications/web_app_dialog_utils.cc +++ b/chrome/browser/ui/web_applications/web_app_dialog_utils.cc
@@ -38,15 +38,9 @@ // BookmarkAppHelper::OnIconsDownloaded(). if (for_installable_site == ForInstallableSite::kYes) { web_app_info->open_as_window = true; - if (install_source == WebappInstallSource::OMNIBOX_INSTALL_ICON) { - chrome::ShowPWAInstallBubble(initiator_web_contents, - std::move(web_app_info), - std::move(web_app_acceptance_callback)); - } else { - chrome::ShowPWAInstallDialog(initiator_web_contents, - std::move(web_app_info), - std::move(web_app_acceptance_callback)); - } + chrome::ShowPWAInstallBubble(initiator_web_contents, + std::move(web_app_info), + std::move(web_app_acceptance_callback)); } else { chrome::ShowBookmarkAppDialog(initiator_web_contents, std::move(web_app_info),
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index cdea805..f461491 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -514,6 +514,7 @@ static constexpr LocalizedString kLocalizedStrings[] = { {"pluginVmPageTitle", IDS_SETTINGS_PLUGIN_VM_PAGE_TITLE}, {"pluginVmPageLabel", IDS_SETTINGS_PLUGIN_VM_PAGE_LABEL}, + {"pluginVmPageSubtext", IDS_SETTINGS_PLUGIN_VM_PAGE_SUBTEXT}, {"pluginVmPrinterAccess", IDS_SETTINGS_PLUGIN_VM_PRINTER_ACCESS}, {"pluginVmSharedPaths", IDS_SETTINGS_PLUGIN_VM_SHARED_PATHS}, {"pluginVmSharedPathsListHeading", @@ -527,10 +528,6 @@ }; AddLocalizedStringsBulk(html_source, kLocalizedStrings, base::size(kLocalizedStrings)); - html_source->AddString( - "pluginVmPageSubtext", - l10n_util::GetStringFUTF16(IDS_SETTINGS_PLUGIN_VM_PAGE_SUBTEXT, - ui::GetChromeOSDeviceName())); } void AddKioskNextShellStrings(content::WebUIDataSource* html_source) {
diff --git a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc index 3e91651..84e8769b 100644 --- a/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc +++ b/chrome/browser/web_applications/extensions/bookmark_app_installation_task_unittest.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/web_applications/components/web_app_provider_base.h" #include "chrome/browser/web_applications/test/test_app_registrar.h" #include "chrome/browser/web_applications/test/test_data_retriever.h" +#include "chrome/browser/web_applications/test/test_web_app_url_loader.h" #include "chrome/browser/web_applications/web_app_install_manager.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" @@ -48,6 +49,29 @@ namespace { +// Returns a factory that will return |data_retriever| the first time it gets +// called. It will DCHECK if called more than once. +web_app::WebAppInstallManager::DataRetrieverFactory GetFactoryForRetriever( + std::unique_ptr<web_app::WebAppDataRetriever> data_retriever) { + // Ideally we would return this lambda directly but passing a mutable lambda + // to BindLambdaForTesting results in a OnceCallback which cannot be used as a + // DataRetrieverFactory because DataRetrieverFactory is a RepeatingCallback. + // For this reason, wrap the OnceCallback in a repeating callback that DCHECKs + // if it gets called more than once. + auto callback = base::BindLambdaForTesting( + [data_retriever = std::move(data_retriever)]() mutable { + return std::move(data_retriever); + }); + + return base::BindRepeating( + [](base::OnceCallback<std::unique_ptr<web_app::WebAppDataRetriever>()> + callback) { + DCHECK(callback); + return std::move(callback).Run(); + }, + base::Passed(std::move(callback))); +} + const GURL kWebAppUrl("https://foo.example"); // TODO(ortuno): Move this to ExternallyInstalledWebAppPrefs or replace with a @@ -262,17 +286,13 @@ std::make_unique<TestBookmarkAppInstallFinalizer>(registrar.get()); install_finalizer_ = install_finalizer.get(); + auto data_retriever = std::make_unique<web_app::TestDataRetriever>(); + data_retriever_ = data_retriever.get(); + auto install_manager = std::make_unique<web_app::WebAppInstallManager>( profile(), registrar.get(), install_finalizer.get()); - install_manager->SetDataRetrieverFactoryForTesting( - base::BindLambdaForTesting([this]() { - // This factory requires a prepared DataRetriever. A test should - // create one with CreateDefaultDataToRetrieve, for example. - DCHECK(prepared_data_retriever_); - return std::unique_ptr<web_app::WebAppDataRetriever>( - std::move(prepared_data_retriever_)); - })); + GetFactoryForRetriever(std::move(data_retriever))); provider->SetRegistrar(std::move(registrar)); provider->SetInstallManager(std::move(install_manager)); @@ -283,55 +303,51 @@ web_app::TestAppRegistrar* registrar() { return registrar_; } TestBookmarkAppInstallFinalizer* finalizer() { return install_finalizer_; } - web_app::TestDataRetriever* data_retriever() { - DCHECK(prepared_data_retriever_); - return prepared_data_retriever_.get(); - } + web_app::TestDataRetriever* data_retriever() { return data_retriever_; } const web_app::InstallFinalizer::FinalizeOptions& finalize_options() { - DCHECK_EQ(1u, finalizer()->finalize_options_list().size()); - return finalizer()->finalize_options_list().at(0); + DCHECK_EQ(1u, install_finalizer_->finalize_options_list().size()); + return install_finalizer_->finalize_options_list().at(0); } - void CreateDefaultDataToRetrieve(const GURL& url) { - DCHECK(!prepared_data_retriever_); - prepared_data_retriever_ = std::make_unique<web_app::TestDataRetriever>(); + std::unique_ptr<BookmarkAppInstallationTask> GetInstallationTaskWithTestMocks( + web_app::InstallOptions options) { + auto manifest = std::make_unique<blink::Manifest>(); + manifest->start_url = options.url; - data_retriever()->SetRendererWebApplicationInfo( + data_retriever_->SetRendererWebApplicationInfo( std::make_unique<WebApplicationInfo>()); - auto manifest = std::make_unique<blink::Manifest>(); - manifest->start_url = url; + data_retriever_->SetManifest(std::move(manifest), /*is_installable=*/true); - data_retriever()->SetManifest(std::move(manifest), /*is_installable=*/true); + data_retriever_->SetIcons(web_app::IconsMap{}); - data_retriever()->SetIcons(web_app::IconsMap{}); + install_finalizer_->SetNextFinalizeInstallResult( + options.url, web_app::InstallResultCode::kSuccess); - finalizer()->SetNextFinalizeInstallResult( - url, web_app::InstallResultCode::kSuccess); + install_finalizer_->SetNextCreateOsShortcutsResult( + install_finalizer_->GetAppIdForUrl(options.url), true); - finalizer()->SetNextCreateOsShortcutsResult( - finalizer()->GetAppIdForUrl(url), true); + auto task = std::make_unique<BookmarkAppInstallationTask>( + profile(), registrar_, install_finalizer_, std::move(options)); + return task; } private: base::test::ScopedFeatureList scoped_feature_list_; web_app::TestAppRegistrar* registrar_ = nullptr; + web_app::TestDataRetriever* data_retriever_ = nullptr; TestBookmarkAppInstallFinalizer* install_finalizer_ = nullptr; - std::unique_ptr<web_app::TestDataRetriever> prepared_data_retriever_; DISALLOW_COPY_AND_ASSIGN(BookmarkAppInstallationTaskTest); }; TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_InstallationSucceeds) { - CreateDefaultDataToRetrieve(kWebAppUrl); - - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), - web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kDefault, - web_app::InstallSource::kInternal)); + auto task = GetInstallationTaskWithTestMocks( + {kWebAppUrl, web_app::LaunchContainer::kDefault, + web_app::InstallSource::kInternal}); base::RunLoop run_loop; @@ -369,15 +385,11 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_InstallationFails) { - CreateDefaultDataToRetrieve(kWebAppUrl); - // Fail GetWebApplicationInfo. + auto task = GetInstallationTaskWithTestMocks( + {kWebAppUrl, web_app::LaunchContainer::kWindow, + web_app::InstallSource::kInternal}); data_retriever()->SetRendererWebApplicationInfo(nullptr); - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), - web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kWindow, - web_app::InstallSource::kInternal)); - base::RunLoop run_loop; task->Install( @@ -402,14 +414,11 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_NoDesktopShortcut) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions install_options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kInternal); install_options.add_to_desktop = false; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; @@ -436,14 +445,11 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_NoQuickLaunchBarShortcut) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions install_options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kInternal); install_options.add_to_quick_launch_bar = false; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -470,15 +476,12 @@ TEST_F( BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_NoDesktopShortcutAndNoQuickLaunchBarShortcut) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions install_options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kInternal); install_options.add_to_desktop = false; install_options.add_to_quick_launch_bar = false; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -504,13 +507,10 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_ForcedContainerWindow) { - CreateDefaultDataToRetrieve(kWebAppUrl); - auto install_options = web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kInternal); - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -531,13 +531,10 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_ForcedContainerTab) { - CreateDefaultDataToRetrieve(kWebAppUrl); - auto install_options = web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kTab, web_app::InstallSource::kInternal); - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -557,13 +554,10 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_DefaultApp) { - CreateDefaultDataToRetrieve(kWebAppUrl); - auto install_options = web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kDefault, web_app::InstallSource::kInternal); - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -584,13 +578,10 @@ TEST_F(BookmarkAppInstallationTaskTest, WebAppOrShortcutFromContents_AppFromPolicy) { - CreateDefaultDataToRetrieve(kWebAppUrl); - auto install_options = web_app::InstallOptions(kWebAppUrl, web_app::LaunchContainer::kDefault, web_app::InstallSource::kExternalPolicy); - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(install_options)); + auto task = GetInstallationTaskWithTestMocks(std::move(install_options)); base::RunLoop run_loop; task->Install(web_contents(), web_app::WebAppUrlLoader::Result::kUrlLoaded, @@ -610,13 +601,10 @@ } TEST_F(BookmarkAppInstallationTaskTest, InstallPlaceholder) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kExternalPolicy); options.install_placeholder = true; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), std::move(options)); + auto task = GetInstallationTaskWithTestMocks(std::move(options)); base::RunLoop run_loop; task->Install( @@ -646,8 +634,6 @@ } TEST_F(BookmarkAppInstallationTaskTest, InstallPlaceholderTwice) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kExternalPolicy); options.install_placeholder = true; @@ -655,9 +641,7 @@ // Install a placeholder app. { - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); - + auto task = GetInstallationTaskWithTestMocks(options); base::RunLoop run_loop; task->Install( web_contents(), web_app::WebAppUrlLoader::Result::kRedirectedUrlLoaded, @@ -673,8 +657,7 @@ } // Try to install it again. - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); + auto task = GetInstallationTaskWithTestMocks(options); base::RunLoop run_loop; task->Install( web_contents(), web_app::WebAppUrlLoader::Result::kRedirectedUrlLoaded, @@ -692,8 +675,6 @@ } TEST_F(BookmarkAppInstallationTaskTest, ReinstallPlaceholderSucceeds) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kExternalPolicy); options.install_placeholder = true; @@ -701,8 +682,7 @@ // Install a placeholder app. { - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); + auto task = GetInstallationTaskWithTestMocks(options); base::RunLoop run_loop; task->Install( @@ -720,14 +700,8 @@ // Replace the placeholder with a real app. options.reinstall_placeholder = true; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); - + auto task = GetInstallationTaskWithTestMocks(options); finalizer()->SetNextUninstallExternalWebAppResult(kWebAppUrl, true); - finalizer()->SetNextFinalizeInstallResult( - kWebAppUrl, web_app::InstallResultCode::kSuccess); - finalizer()->SetNextCreateOsShortcutsResult( - finalizer()->GetAppIdForUrl(kWebAppUrl), true); base::RunLoop run_loop; task->Install( @@ -749,8 +723,6 @@ } TEST_F(BookmarkAppInstallationTaskTest, ReinstallPlaceholderFails) { - CreateDefaultDataToRetrieve(kWebAppUrl); - web_app::InstallOptions options(kWebAppUrl, web_app::LaunchContainer::kWindow, web_app::InstallSource::kExternalPolicy); options.install_placeholder = true; @@ -758,9 +730,7 @@ // Install a placeholder app. { - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); - + auto task = GetInstallationTaskWithTestMocks(options); base::RunLoop run_loop; task->Install( web_contents(), web_app::WebAppUrlLoader::Result::kRedirectedUrlLoaded, @@ -778,8 +748,7 @@ // Replace the placeholder with a real app. options.reinstall_placeholder = true; - auto task = std::make_unique<BookmarkAppInstallationTask>( - profile(), registrar(), finalizer(), options); + auto task = GetInstallationTaskWithTestMocks(options); finalizer()->SetNextUninstallExternalWebAppResult(kWebAppUrl, false);
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 4872dfc..a926a5c 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -868,6 +868,9 @@ #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) const char kEnableNewAppMenuIcon[] = "enable-new-app-menu-icon"; + +// Causes the browser to launch directly in guest mode. +const char kGuest[] = "guest"; #endif #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && \
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 9d509e0..99b23b7 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -269,6 +269,7 @@ #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) extern const char kEnableNewAppMenuIcon[]; +extern const char kGuest[]; #endif #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && \
diff --git a/chrome/common/heap_profiler_controller.cc b/chrome/common/heap_profiler_controller.cc index 2993153..a2f0e08 100644 --- a/chrome/common/heap_profiler_controller.cc +++ b/chrome/common/heap_profiler_controller.cc
@@ -14,14 +14,11 @@ #include "base/sampling_heap_profiler/sampling_heap_profiler.h" #include "base/task/post_task.h" #include "components/metrics/call_stack_profile_builder.h" +#include "components/metrics/call_stack_profile_metrics_provider.h" namespace { -// Enables reporting of sampling heap profiles over UMA. -const base::Feature kHeapProfilerReporting{"HeapProfilerReporting", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Sets sampling interval in bytes. +// Sets heap sampling interval in bytes. const char kHeapProfilerSamplingRate[] = "sampling-rate"; constexpr base::TimeDelta kHeapCollectionInterval = @@ -42,15 +39,12 @@ stopped_->data.Set(); } -// static -bool HeapProfilerController::IsReportingEnabled() { - return base::FeatureList::IsEnabled(kHeapProfilerReporting); -} - void HeapProfilerController::Start() { - if (IsReportingEnabled()) { + if (base::FeatureList::IsEnabled( + metrics::CallStackProfileMetricsProvider::kHeapProfilerReporting)) { int sampling_rate = base::GetFieldTrialParamByFeatureAsInt( - kHeapProfilerReporting, kHeapProfilerSamplingRate, 0); + metrics::CallStackProfileMetricsProvider::kHeapProfilerReporting, + kHeapProfilerSamplingRate, 0); if (sampling_rate > 0) base::SamplingHeapProfiler::Get()->SetSamplingInterval(sampling_rate); base::SamplingHeapProfiler::Get()->Start();
diff --git a/chrome/common/heap_profiler_controller.h b/chrome/common/heap_profiler_controller.h index 731c168c..aae5e915 100644 --- a/chrome/common/heap_profiler_controller.h +++ b/chrome/common/heap_profiler_controller.h
@@ -27,8 +27,6 @@ task_runner_ = std::move(task_runner); } - static bool IsReportingEnabled(); - private: using StoppedFlag = base::RefCountedData<base::AtomicFlag>;
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 436aaa5..d4ccef0 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1749,7 +1749,6 @@ "../browser/ui/views/extensions/extension_uninstall_dialog_view_browsertest.cc", "../browser/ui/views/extensions/extensions_menu_view_browsertest.cc", "../browser/ui/views/extensions/media_galleries_dialog_views_browsertest.cc", - "../browser/ui/views/extensions/pwa_confirmation_dialog_view_browsertest.cc", "../browser/ui/views/external_protocol_dialog_browsertest.cc", "../browser/ui/views/feature_promos/feature_promo_dialog_browsertest.cc", "../browser/ui/views/feature_promos/reopen_tab_promo_controller_dialog_browsertest.cc",
diff --git a/chromeos/services/ime/README.md b/chromeos/services/ime/README.md index e680ee30..78b214f8 100644 --- a/chromeos/services/ime/README.md +++ b/chromeos/services/ime/README.md
@@ -1,6 +1,14 @@ -IME Mojo service provides core IME functionality. +An IME Mojo service provides core IME functionality. -The service prvoides basic rule-based IMEs, and is able to support -advanced IME features by loading a qualified shared library. +IME on ChromeOS consists of three parts: +- The IME running in an extension to provide a soft keyboard +- The sandboxed, core IME service running in ChromeOS (responsible for + processing input and turning it into characters/symbols) +- The IME framework running in the Chrome browser process, that brokers + between the IME extension and the IME service. It also provides additional + functionality to the IME service (for downloading IME data as needed). + +The service provides basic rule-based IMEs, and is able to support +advanced IME features by loading a shared library. Work in progress, design doc: go/cros-ime-decoders-mojo
diff --git a/chromeos/services/ime/ime_service.cc b/chromeos/services/ime/ime_service.cc index 8f9d425..3037ba8 100644 --- a/chromeos/services/ime/ime_service.cc +++ b/chromeos/services/ime/ime_service.cc
@@ -4,6 +4,11 @@ #include "chromeos/services/ime/ime_service.h" +#include <memory> +#include <string> +#include <utility> +#include <vector> + #include "base/bind.h" #include "build/buildflag.h" #include "chromeos/services/ime/public/cpp/buildflags.h" @@ -25,6 +30,9 @@ binders_.Add(base::BindRepeating(&ImeService::AddInputEngineManagerReceiver, base::Unretained(this))); + binders_.Add(base::BindRepeating( + &ImeService::BindPlatformAccessClientReceiver, base::Unretained(this))); + manager_receivers_.set_disconnect_handler(base::BindRepeating( &ImeService::OnConnectionLost, base::Unretained(this))); @@ -60,6 +68,18 @@ // TODO(https://crbug.com/837156): Reset the cleanup timer. } +void ImeService::BindPlatformAccessClientReceiver( + mojo::PendingReceiver<mojom::PlatformAccessClient> receiver) { + if (!access_receiver_.is_bound()) { + access_receiver_.Bind(std::move(receiver)); + } +} + +void ImeService::SetPlatformAccessProvider( + mojo::PendingRemote<mojom::PlatformAccessProvider> access) { + platform_access_.Bind(std::move(access)); +} + void ImeService::OnConnectionLost() { if (manager_receivers_.empty()) { service_binding_.RequestClose();
diff --git a/chromeos/services/ime/ime_service.h b/chromeos/services/ime/ime_service.h index 27a378a..0cb42afd 100644 --- a/chromeos/services/ime/ime_service.h +++ b/chromeos/services/ime/ime_service.h
@@ -5,11 +5,17 @@ #ifndef CHROMEOS_SERVICES_IME_IME_SERVICE_H_ #define CHROMEOS_SERVICES_IME_IME_SERVICE_H_ +#include <memory> +#include <string> +#include <utility> +#include <vector> + #include "chromeos/services/ime/input_engine.h" #include "chromeos/services/ime/public/cpp/shared_lib/interfaces.h" #include "chromeos/services/ime/public/mojom/input_engine.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "services/service_manager/public/cpp/binder_map.h" #include "services/service_manager/public/cpp/service.h" @@ -21,6 +27,7 @@ class ImeService : public service_manager::Service, public mojom::InputEngineManager, + public mojom::PlatformAccessClient, public ImeCrosPlatform { public: explicit ImeService( @@ -42,6 +49,10 @@ const std::vector<uint8_t>& extra, ConnectToImeEngineCallback callback) override; + // mojom::PlatformAccessClient overrides: + void SetPlatformAccessProvider( + mojo::PendingRemote<mojom::PlatformAccessProvider> access) override; + // ImeCrosPlatform overrides: const char* GetImeBundleDir() override; const char* GetImeGlobalDir() override; @@ -55,6 +66,12 @@ void AddInputEngineManagerReceiver( mojo::PendingReceiver<mojom::InputEngineManager> receiver); + // Binds a mojom::PlatformAccessClient receiver to this object. + void BindPlatformAccessClientReceiver( + mojo::PendingReceiver<mojom::PlatformAccessClient> receiver); + + // Handles connection loss to InputEngineManager remote. This should only + // happen when the input engine client exits or crashes. void OnConnectionLost(); service_manager::ServiceBinding service_binding_; @@ -63,6 +80,10 @@ // input engine instance. std::unique_ptr<InputEngine> input_engine_; + // Platform delegate for access to privilege resources. + mojo::Remote<mojom::PlatformAccessProvider> platform_access_; + + mojo::Receiver<mojom::PlatformAccessClient> access_receiver_{this}; mojo::ReceiverSet<mojom::InputEngineManager> manager_receivers_; service_manager::BinderMap binders_;
diff --git a/chromeos/services/ime/public/cpp/manifest.cc b/chromeos/services/ime/public/cpp/manifest.cc index 099ba6c..fbd03ea 100644 --- a/chromeos/services/ime/public/cpp/manifest.cc +++ b/chromeos/services/ime/public/cpp/manifest.cc
@@ -30,7 +30,7 @@ .ExposeCapability( "input_engine", service_manager::Manifest::InterfaceList< - mojom::InputEngineManager, mojom::InputChannel>()) + mojom::InputEngineManager, mojom::PlatformAccessClient>()) .Build()}; return *manifest; }
diff --git a/chromeos/services/ime/public/mojom/BUILD.gn b/chromeos/services/ime/public/mojom/BUILD.gn index 1f14dea..ee6e82e4 100644 --- a/chromeos/services/ime/public/mojom/BUILD.gn +++ b/chromeos/services/ime/public/mojom/BUILD.gn
@@ -12,5 +12,6 @@ public_deps = [ "//mojo/public/mojom/base", + "//url/mojom:url_mojom_gurl", ] }
diff --git a/chromeos/services/ime/public/mojom/input_engine.mojom b/chromeos/services/ime/public/mojom/input_engine.mojom index ae64b42e..3a758eb 100644 --- a/chromeos/services/ime/public/mojom/input_engine.mojom +++ b/chromeos/services/ime/public/mojom/input_engine.mojom
@@ -4,6 +4,16 @@ module chromeos.ime.mojom; +import "mojo/public/mojom/base/file_path.mojom"; +import "url/mojom/url.mojom"; + +// IME on ChromeOS consists of three parts: +// - The IME running in an extension to provide a soft keyboard +// - The sandboxed, core IME service running in ChromeOS (responsible for +// processing input and turning it into characters/symbols) +// - The IME framework running in the Chrome browser process, that brokers +// between the IME extension and the IME service. It also provides additional +// functionality to the IME service (for downloading IME data as needed). // Method of an operation to apply to a text field enum OperationMethod { @@ -49,7 +59,10 @@ bool alt; }; -// Manages access to a set of IME engines. +// Manages access to a set of IME engines, implemented by the IME service +// itself. The IME framework in the browser process is responsible for brokering +// the connection between the IME service and the IME extension, but does not +// otherwise participate. interface InputEngineManager { // Sets up the connection by binding the |to_engine_request| to the input // engine identified by the |ime_spec|. The |extra| is an optional serialized @@ -65,8 +78,9 @@ => (bool success); }; -// A message channel is a paired message sender and receiver, representing -// the communication channel between an client and the input engine connected. +// A message channel is a paired message sender and receiver. It provides the +// communication channel between the IME extension process and the core IME +// service in ChromeOS. // In order to encapsulate all the communication, (e.g. access to some // closed-sourced input engine with decoders), implement the method that takes // a serialized protobuf message (instead of a plaintext) as its argument. @@ -90,3 +104,21 @@ // Gets the keypress count for rulebased logic GetRulebasedKeypressCountForTesting() => (int32 count); }; + +// Implemented in the browser process, used to perform network requests or +// access privileged resources on behalf of the core IME service in ChromeOS. +interface PlatformAccessProvider { + // Download language module from a whitelisted url to a given path. + // Provider will validate the url and return an empty file path if it's + // invalid or downloading fails. + DownloadImeFileTo(url.mojom.Url url, + mojo_base.mojom.FilePath file_path) => + (mojo_base.mojom.FilePath file_path); +}; + +// A client on the input engine side that requires access to the IME-specific +// resources on the platform. +interface PlatformAccessClient { + // Set a platform access provider. + SetPlatformAccessProvider(pending_remote<PlatformAccessProvider> provider); +};
diff --git a/components/favicon/core/favicon_request_handler.cc b/components/favicon/core/favicon_request_handler.cc index cd63cb2..8ce2a49 100644 --- a/components/favicon/core/favicon_request_handler.cc +++ b/components/favicon/core/favicon_request_handler.cc
@@ -212,13 +212,11 @@ return; } - scoped_refptr<base::RefCountedMemory> sync_bitmap = + favicon_base::FaviconRawBitmapResult sync_bitmap_result = synced_favicon_getter_.Run(page_url); - if (sync_bitmap) { + if (sync_bitmap_result.is_valid()) { // If request to sync succeeds, send the retrieved bitmap. RecordFaviconAvailabilityMetric(origin, FaviconAvailability::kSync); - favicon_base::FaviconRawBitmapResult sync_bitmap_result; - sync_bitmap_result.bitmap_data = sync_bitmap; std::move(response_callback).Run(sync_bitmap_result); return; } @@ -266,15 +264,15 @@ return; } - scoped_refptr<base::RefCountedMemory> sync_bitmap = + favicon_base::FaviconRawBitmapResult sync_bitmap_result = synced_favicon_getter_.Run(page_url); - if (sync_bitmap) { + if (sync_bitmap_result.is_valid()) { // If request to sync succeeds, convert the retrieved bitmap to image and // send. RecordFaviconAvailabilityMetric(origin, FaviconAvailability::kSync); favicon_base::FaviconImageResult sync_image_result; sync_image_result.image = - gfx::Image::CreateFrom1xPNGBytes(sync_bitmap.get()); + gfx::Image::CreateFrom1xPNGBytes(sync_bitmap_result.bitmap_data.get()); std::move(response_callback).Run(sync_image_result); return; }
diff --git a/components/favicon/core/favicon_request_handler.h b/components/favicon/core/favicon_request_handler.h index eab6b1b..591167d 100644 --- a/components/favicon/core/favicon_request_handler.h +++ b/components/favicon/core/favicon_request_handler.h
@@ -9,10 +9,10 @@ #include <memory> #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/task/cancelable_task_tracker.h" #include "components/favicon_base/favicon_callback.h" +#include "components/favicon_base/favicon_types.h" #include "components/keyed_service/core/keyed_service.h" #include "url/gurl.h" @@ -61,7 +61,7 @@ public: // Callback that requests the synced bitmap for a page url. using SyncedFaviconGetter = - base::RepeatingCallback<scoped_refptr<base::RefCountedMemory>( + base::RepeatingCallback<favicon_base::FaviconRawBitmapResult( const GURL&)>; FaviconRequestHandler(const SyncedFaviconGetter& synced_favicon_getter,
diff --git a/components/favicon/core/favicon_request_handler_unittest.cc b/components/favicon/core/favicon_request_handler_unittest.cc index 2988a7a..4ba8398 100644 --- a/components/favicon/core/favicon_request_handler_unittest.cc +++ b/components/favicon/core/favicon_request_handler_unittest.cc
@@ -15,6 +15,7 @@ #include "components/favicon/core/features.h" #include "components/favicon/core/large_icon_service.h" #include "components/favicon/core/test/mock_favicon_service.h" +#include "components/favicon_base/favicon_types.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,25 +38,25 @@ const SkColor kTestColor = SK_ColorRED; base::CancelableTaskTracker::TaskId kDummyTaskId = 1; -scoped_refptr<base::RefCountedBytes> CreateTestBitmapBytes() { - scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes()); +SkBitmap CreateTestSkBitmap() { SkBitmap bitmap; bitmap.allocN32Pixels(kDesiredSizeInPixel, kDesiredSizeInPixel); bitmap.eraseColor(kTestColor); - gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data->data()); - return data; + return bitmap; } favicon_base::FaviconRawBitmapResult CreateTestBitmapResult() { + scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes()); + gfx::PNGCodec::EncodeBGRASkBitmap(CreateTestSkBitmap(), false, &data->data()); favicon_base::FaviconRawBitmapResult result; - result.bitmap_data = CreateTestBitmapBytes(); + result.bitmap_data = data; result.icon_url = GURL(kDummyIconUrl); return result; } favicon_base::FaviconImageResult CreateTestImageResult() { favicon_base::FaviconImageResult result; - result.image = gfx::Image::CreateFrom1xPNGBytes(CreateTestBitmapBytes()); + result.image = gfx::Image::CreateFrom1xBitmap(CreateTestSkBitmap()); result.icon_url = GURL(kDummyIconUrl); return result; } @@ -141,7 +142,7 @@ return kDummyTaskId; }); EXPECT_CALL(synced_favicon_getter_, Run(GURL(kDummyPageUrl))) - .WillOnce([](auto) { return nullptr; }); + .WillOnce([](auto) { return favicon_base::FaviconRawBitmapResult(); }); favicon_base::FaviconRawBitmapResult result; favicon_request_handler_.GetRawFaviconForPageURL( GURL(kDummyPageUrl), kDesiredSizeInPixel, @@ -166,7 +167,7 @@ return kDummyTaskId; }); EXPECT_CALL(synced_favicon_getter_, Run(GURL(kDummyPageUrl))) - .WillOnce([](auto) { return CreateTestBitmapBytes(); }); + .WillOnce([](auto) { return CreateTestBitmapResult(); }); favicon_base::FaviconRawBitmapResult result; favicon_request_handler_.GetRawFaviconForPageURL( GURL(kDummyPageUrl), kDesiredSizeInPixel, @@ -289,7 +290,7 @@ return kDummyTaskId; }); EXPECT_CALL(synced_favicon_getter_, Run(GURL(kDummyPageUrl))) - .WillOnce([](auto) { return nullptr; }); + .WillOnce([](auto) { return favicon_base::FaviconRawBitmapResult(); }); favicon_base::FaviconImageResult result; favicon_request_handler_.GetFaviconImageForPageURL( GURL(kDummyPageUrl), base::BindOnce(&StoreImage, &result), @@ -311,7 +312,7 @@ return kDummyTaskId; }); EXPECT_CALL(synced_favicon_getter_, Run(GURL(kDummyPageUrl))) - .WillOnce([](auto) { return CreateTestBitmapBytes(); }); + .WillOnce([](auto) { return CreateTestBitmapResult(); }); favicon_base::FaviconImageResult result; favicon_request_handler_.GetFaviconImageForPageURL( GURL(kDummyPageUrl), base::BindOnce(&StoreImage, &result),
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index cee3caa..425340f 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -1190,9 +1190,11 @@ } // Get all the download entries from the database. -void HistoryBackend::QueryDownloads(std::vector<DownloadRow>* rows) { +std::vector<DownloadRow> HistoryBackend::QueryDownloads() { + std::vector<DownloadRow> rows; if (db_) - db_->QueryDownloads(rows); + db_->QueryDownloads(&rows); + return rows; } // Update a particular download entry.
diff --git a/components/history/core/browser/history_backend.h b/components/history/core/browser/history_backend.h index c664d9f..0551f05 100644 --- a/components/history/core/browser/history_backend.h +++ b/components/history/core/browser/history_backend.h
@@ -337,7 +337,7 @@ // Downloads ----------------------------------------------------------------- uint32_t GetNextDownloadId(); - void QueryDownloads(std::vector<DownloadRow>* rows); + std::vector<DownloadRow> QueryDownloads(); void UpdateDownload(const DownloadRow& data, bool should_commit_immediately); bool CreateDownload(const DownloadRow& history_info); void RemoveDownloads(const std::set<uint32_t>& ids);
diff --git a/components/history/core/browser/history_service.cc b/components/history/core/browser/history_service.cc index d00a16cc..370b14be 100644 --- a/components/history/core/browser/history_service.cc +++ b/components/history/core/browser/history_service.cc
@@ -69,14 +69,6 @@ static const char* kHistoryThreadName = "Chrome_HistoryThread"; -// Callback from WebHistoryService::ExpireWebHistory(). -void ExpireWebHistoryComplete(bool success) { - // Ignore the result. - // - // TODO(davidben): ExpireLocalAndRemoteHistoryBetween callback should not fire - // until this completes. -} - } // namespace // Sends messages from the backend to us on the main thread. This must be a @@ -193,7 +185,7 @@ return; ScheduleTask(PRIORITY_NORMAL, - base::MakeCriticalClosure(base::Bind( + base::MakeCriticalClosure(base::BindOnce( &HistoryBackend::PersistState, history_backend_.get()))); } #endif @@ -720,30 +712,24 @@ std::move(callback)); } -void HistoryService::GetNextDownloadId(const DownloadIdCallback& callback) { +void HistoryService::GetNextDownloadId(DownloadIdCallback callback) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); PostTaskAndReplyWithResult( backend_task_runner_.get(), FROM_HERE, - base::Bind(&HistoryBackend::GetNextDownloadId, history_backend_), - callback); + base::BindOnce(&HistoryBackend::GetNextDownloadId, history_backend_), + std::move(callback)); } // Handle queries for a list of all downloads in the history database's // 'downloads' table. -void HistoryService::QueryDownloads(const DownloadQueryCallback& callback) { +void HistoryService::QueryDownloads(DownloadQueryCallback callback) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK(thread_checker_.CalledOnValidThread()); - std::vector<DownloadRow>* rows = new std::vector<DownloadRow>(); - std::unique_ptr<std::vector<DownloadRow>> scoped_rows(rows); - // Beware! The first Bind() does not simply |scoped_rows.get()| because - // std::move(scoped_rows) nullifies |scoped_rows|, and compilers do not - // guarantee that the first Bind's arguments are evaluated before the second - // Bind's arguments. - backend_task_runner_->PostTaskAndReply( - FROM_HERE, - base::BindOnce(&HistoryBackend::QueryDownloads, history_backend_, rows), - base::BindOnce(callback, std::move(scoped_rows))); + PostTaskAndReplyWithResult( + backend_task_runner_.get(), FROM_HERE, + base::BindOnce(&HistoryBackend::QueryDownloads, history_backend_), + std::move(callback)); } // Handle updates for a particular download. This is a 'fire and forget' @@ -1091,8 +1077,8 @@ } })"); web_history->ExpireHistoryBetween( - /*restrict_urls=*/{}, begin_time, end_time, - base::Bind(&ExpireWebHistoryComplete), partial_traffic_annotation); + /*restrict_urls=*/{}, begin_time, end_time, base::DoNothing(), + partial_traffic_annotation); } ExpireHistoryBetween(/*restrict_urls=*/{}, begin_time, end_time, /*user_initiated=*/true, std::move(callback), tracker); @@ -1131,7 +1117,7 @@ })"); web_history->ExpireHistoryBetween( /*restrict_urls=*/{url}, base::Time(), base::Time::Max(), - base::Bind(&ExpireWebHistoryComplete), partial_traffic_annotation); + base::DoNothing(), partial_traffic_annotation); } DeleteURL(url); }
diff --git a/components/history/core/browser/history_service.h b/components/history/core/browser/history_service.h index 5f89170..5e7c8987 100644 --- a/components/history/core/browser/history_service.h +++ b/components/history/core/browser/history_service.h
@@ -382,22 +382,22 @@ // Implemented by the caller of 'GetNextDownloadId' below, and is called with // the maximum id of all downloads records in the database plus 1. - typedef base::Callback<void(uint32_t)> DownloadIdCallback; + using DownloadIdCallback = base::OnceCallback<void(uint32_t)>; // Responds on the calling thread with the maximum id of all downloads records // in the database plus 1. - void GetNextDownloadId(const DownloadIdCallback& callback); + void GetNextDownloadId(DownloadIdCallback callback); // Implemented by the caller of 'QueryDownloads' below, and is called when the // history service has retrieved a list of all download state. The call - typedef base::Callback<void(std::unique_ptr<std::vector<DownloadRow>>)> - DownloadQueryCallback; + using DownloadQueryCallback = + base::OnceCallback<void(std::vector<DownloadRow>)>; // Begins a history request to retrieve the state of all downloads in the // history db. 'callback' runs when the history service request is complete, // at which point 'info' contains an array of DownloadRow, one per // download. The callback is called on the thread that calls QueryDownloads(). - void QueryDownloads(const DownloadQueryCallback& callback); + void QueryDownloads(DownloadQueryCallback callback); // Called to update the history service about the current state of a download. // This is a 'fire and forget' query, so just pass the relevant state info to @@ -452,8 +452,8 @@ // icon URL (e.g. http://www.google.com/favicon.ico) for which the favicon // data has changed. It is valid to call the callback with non-empty // "page URLs" and no "icon URL" and vice versa. - typedef base::Callback<void(const std::set<GURL>&, const GURL&)> - OnFaviconsChangedCallback; + using OnFaviconsChangedCallback = + base::RepeatingCallback<void(const std::set<GURL>&, const GURL&)>; // Add a callback to the list. The callback will remain registered until the // returned Subscription is destroyed. The Subscription must be destroyed
diff --git a/components/metrics/call_stack_profile_metrics_provider.cc b/components/metrics/call_stack_profile_metrics_provider.cc index dbbda1c..5f7b2e8 100644 --- a/components/metrics/call_stack_profile_metrics_provider.cc +++ b/components/metrics/call_stack_profile_metrics_provider.cc
@@ -8,11 +8,13 @@ #include <vector> #include "base/bind.h" +#include "base/feature_list.h" #include "base/macros.h" #include "base/no_destructor.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "base/time/time.h" +#include "sampled_profile.pb.h" #include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h" namespace metrics { @@ -81,7 +83,12 @@ // If true, profiles provided to MaybeCollect*Profile should be collected. // Otherwise they will be ignored. - bool collection_enabled_ GUARDED_BY(lock_); + // |collection_enabled_| is initialized to true to collect any profiles that + // are generated prior to creation of the CallStackProfileMetricsProvider. + // The ultimate disposition of these pre-creation collected profiles will be + // determined by the initial recording state provided to + // CallStackProfileMetricsProvider. + bool collection_enabled_ GUARDED_BY(lock_) = true; // The last time collection was disabled. Used to determine if collection was // disabled at any point since a profile was started. @@ -205,28 +212,32 @@ serialized_profiles_.clear(); } -// |collection_enabled_| is initialized to true to collect any profiles that are -// generated prior to creation of the CallStackProfileMetricsProvider. The -// ultimate disposition of these pre-creation collected profiles will be -// determined by the initial recording state provided to -// CallStackProfileMetricsProvider. -PendingProfiles::PendingProfiles() : collection_enabled_(true) {} +PendingProfiles::PendingProfiles() = default; } // namespace // CallStackProfileMetricsProvider -------------------------------------------- -const base::Feature CallStackProfileMetricsProvider::kEnableReporting = { - "SamplingProfilerReporting", base::FEATURE_ENABLED_BY_DEFAULT}; +const base::Feature + CallStackProfileMetricsProvider::kSamplingProfilerReporting = { + "SamplingProfilerReporting", base::FEATURE_ENABLED_BY_DEFAULT}; -CallStackProfileMetricsProvider::CallStackProfileMetricsProvider() {} +const base::Feature CallStackProfileMetricsProvider::kHeapProfilerReporting{ + "HeapProfilerReporting", base::FEATURE_DISABLED_BY_DEFAULT}; -CallStackProfileMetricsProvider::~CallStackProfileMetricsProvider() {} +CallStackProfileMetricsProvider::CallStackProfileMetricsProvider() = default; +CallStackProfileMetricsProvider::~CallStackProfileMetricsProvider() = default; // static void CallStackProfileMetricsProvider::ReceiveProfile( base::TimeTicks profile_start_time, SampledProfile profile) { + const base::Feature& feature = + profile.trigger_event() == SampledProfile::PERIODIC_HEAP_COLLECTION + ? kHeapProfilerReporting + : kSamplingProfilerReporting; + if (!base::FeatureList::IsEnabled(feature)) + return; PendingProfiles::GetInstance()->MaybeCollectProfile(profile_start_time, std::move(profile)); } @@ -235,13 +246,16 @@ void CallStackProfileMetricsProvider::ReceiveSerializedProfile( base::TimeTicks profile_start_time, std::string serialized_profile) { + // Heap profiler does not use this path as it only reports profiles + // from the browser process. + if (!base::FeatureList::IsEnabled(kSamplingProfilerReporting)) + return; PendingProfiles::GetInstance()->MaybeCollectSerializedProfile( profile_start_time, std::move(serialized_profile)); } void CallStackProfileMetricsProvider::OnRecordingEnabled() { - PendingProfiles::GetInstance()->SetCollectionEnabled( - base::FeatureList::IsEnabled(kEnableReporting)); + PendingProfiles::GetInstance()->SetCollectionEnabled(true); } void CallStackProfileMetricsProvider::OnRecordingDisabled() { @@ -253,7 +267,9 @@ std::vector<SampledProfile> profiles = PendingProfiles::GetInstance()->RetrieveProfiles(); - DCHECK(base::FeatureList::IsEnabled(kEnableReporting) || profiles.empty()); + DCHECK(base::FeatureList::IsEnabled(kSamplingProfilerReporting) || + base::FeatureList::IsEnabled(kHeapProfilerReporting) || + profiles.empty()); for (auto& profile : profiles) *uma_proto->add_sampled_profile() = std::move(profile);
diff --git a/components/metrics/call_stack_profile_metrics_provider.h b/components/metrics/call_stack_profile_metrics_provider.h index 47623eb..c2b0c6c6 100644 --- a/components/metrics/call_stack_profile_metrics_provider.h +++ b/components/metrics/call_stack_profile_metrics_provider.h
@@ -42,9 +42,12 @@ void ProvideCurrentSessionData( ChromeUserMetricsExtension* uma_proto) override; + // Enables reporting of sampling heap profiles. + static const base::Feature kHeapProfilerReporting; + protected: - // base::Feature for reporting profiles. Provided here for test use. - static const base::Feature kEnableReporting; + // base::Feature for reporting CPU profiles. Provided here for test use. + static const base::Feature kSamplingProfilerReporting; // Reset the static state to the defaults after startup. static void ResetStaticStateForTesting();
diff --git a/components/metrics/call_stack_profile_metrics_provider_unittest.cc b/components/metrics/call_stack_profile_metrics_provider_unittest.cc index 3869cc41..01c7fbc1 100644 --- a/components/metrics/call_stack_profile_metrics_provider_unittest.cc +++ b/components/metrics/call_stack_profile_metrics_provider_unittest.cc
@@ -18,20 +18,20 @@ class CallStackProfileMetricsProviderTest : public testing::Test { public: CallStackProfileMetricsProviderTest() { - scoped_feature_list_.InitAndEnableFeature(TestState::kEnableReporting); TestState::ResetStaticStateForTesting(); + scoped_feature_list_.InitAndEnableFeature( + TestState::kSamplingProfilerReporting); } - ~CallStackProfileMetricsProviderTest() override {} - - private: + protected: // Exposes the feature from the CallStackProfileMetricsProvider. class TestState : public CallStackProfileMetricsProvider { public: - using CallStackProfileMetricsProvider::kEnableReporting; + using CallStackProfileMetricsProvider::kSamplingProfilerReporting; using CallStackProfileMetricsProvider::ResetStaticStateForTesting; }; + private: base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(CallStackProfileMetricsProviderTest); @@ -207,4 +207,69 @@ EXPECT_EQ(0, uma_proto.sampled_profile_size()); } +// Checks that a heap profile is not reported when Finch experiment is not +// enabled. +TEST_F(CallStackProfileMetricsProviderTest, + HeapProfileNotProvidedWithoutFinch) { + CallStackProfileMetricsProvider provider; + base::TimeTicks profile_start_time = base::TimeTicks::Now(); + SampledProfile profile; + profile.set_trigger_event(SampledProfile::PERIODIC_HEAP_COLLECTION); + CallStackProfileMetricsProvider::ReceiveProfile(profile_start_time, profile); + ChromeUserMetricsExtension uma_proto; + provider.ProvideCurrentSessionData(&uma_proto); + EXPECT_EQ(0, uma_proto.sampled_profile_size()); +} + +// Checks that a heap profile is not reported when recording is disabled. +TEST_F(CallStackProfileMetricsProviderTest, + HeapProfileNotProvidedWhenDisabled) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + CallStackProfileMetricsProvider::kHeapProfilerReporting); + CallStackProfileMetricsProvider provider; + provider.OnRecordingDisabled(); + base::TimeTicks profile_start_time = base::TimeTicks::Now(); + SampledProfile profile; + profile.set_trigger_event(SampledProfile::PERIODIC_HEAP_COLLECTION); + CallStackProfileMetricsProvider::ReceiveProfile(profile_start_time, profile); + ChromeUserMetricsExtension uma_proto; + provider.ProvideCurrentSessionData(&uma_proto); + EXPECT_EQ(0, uma_proto.sampled_profile_size()); +} + +// Checks that a heap profile is provided to ProvideCurrentSessionData +// if recording is enabled. +TEST_F(CallStackProfileMetricsProviderTest, HeapProfileProvidedWhenEnabled) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + CallStackProfileMetricsProvider::kHeapProfilerReporting); + CallStackProfileMetricsProvider provider; + provider.OnRecordingEnabled(); + base::TimeTicks profile_start_time = base::TimeTicks::Now(); + SampledProfile profile; + profile.set_trigger_event(SampledProfile::PERIODIC_HEAP_COLLECTION); + CallStackProfileMetricsProvider::ReceiveProfile(profile_start_time, profile); + ChromeUserMetricsExtension uma_proto; + provider.ProvideCurrentSessionData(&uma_proto); + EXPECT_EQ(1, uma_proto.sampled_profile_size()); +} + +// Checks that a CPU profile is not reported when the heap profiler Finch +// experiment is enabled, but sampling CPU Finch is disabled. +TEST_F(CallStackProfileMetricsProviderTest, CpuProfileNotProvidedWithoutFinch) { + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitWithFeatures( + {CallStackProfileMetricsProvider::kHeapProfilerReporting}, + {TestState::kSamplingProfilerReporting}); + CallStackProfileMetricsProvider provider; + base::TimeTicks profile_start_time = base::TimeTicks::Now(); + SampledProfile profile; + profile.set_trigger_event(SampledProfile::PERIODIC_COLLECTION); + CallStackProfileMetricsProvider::ReceiveProfile(profile_start_time, profile); + ChromeUserMetricsExtension uma_proto; + provider.ProvideCurrentSessionData(&uma_proto); + EXPECT_EQ(0, uma_proto.sampled_profile_size()); +} + } // namespace metrics
diff --git a/components/metrics/file_metrics_provider.cc b/components/metrics/file_metrics_provider.cc index 06d1fc2..9e6b787 100644 --- a/components/metrics/file_metrics_provider.cc +++ b/components/metrics/file_metrics_provider.cc
@@ -517,7 +517,6 @@ // static void FileMetricsProvider::MergeHistogramDeltasFromSource(SourceInfo* source) { DCHECK(source->allocator); - SCOPED_UMA_HISTOGRAM_TIMER("UMA.FileMetricsProvider.SnapshotTime.File"); base::PersistentHistogramAllocator::Iterator histogram_iter( source->allocator.get()); @@ -782,8 +781,6 @@ // Check all sources for previous run to see if they need to be read. for (auto iter = sources_for_previous_run_.begin(); iter != sources_for_previous_run_.end();) { - SCOPED_UMA_HISTOGRAM_TIMER("UMA.FileMetricsProvider.InitialCheckTime.File"); - auto temp = iter++; SourceInfo* source = temp->get(); @@ -828,9 +825,6 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); for (const std::unique_ptr<SourceInfo>& source : sources_for_previous_run_) { - SCOPED_UMA_HISTOGRAM_TIMER( - "UMA.FileMetricsProvider.InitialSnapshotTime.File"); - // The source needs to have an allocator attached to it in order to read // histograms out of it. DCHECK(!source->read_complete);
diff --git a/components/navigation_metrics/BUILD.gn b/components/navigation_metrics/BUILD.gn index 1a0101e..182ed14 100644 --- a/components/navigation_metrics/BUILD.gn +++ b/components/navigation_metrics/BUILD.gn
@@ -12,6 +12,7 @@ "//base", "//base:i18n", "//components/dom_distiller/core:core", + "//components/profile_metrics", "//components/url_formatter:url_formatter", "//url", ] @@ -25,6 +26,7 @@ deps = [ ":navigation_metrics", "//base/test:test_support", + "//components/profile_metrics", "//testing/gtest", "//url", ]
diff --git a/components/navigation_metrics/DEPS b/components/navigation_metrics/DEPS index 310f591..1a1a758f 100644 --- a/components/navigation_metrics/DEPS +++ b/components/navigation_metrics/DEPS
@@ -1,4 +1,5 @@ include_rules = [ "+components/dom_distiller/core", + "+components/profile_metrics", "+components/url_formatter", ]
diff --git a/components/navigation_metrics/navigation_metrics.cc b/components/navigation_metrics/navigation_metrics.cc index ece9c39..cdc147c 100644 --- a/components/navigation_metrics/navigation_metrics.cc +++ b/components/navigation_metrics/navigation_metrics.cc
@@ -9,6 +9,7 @@ #include "base/metrics/user_metrics.h" #include "base/stl_util.h" #include "components/dom_distiller/core/url_constants.h" +#include "components/profile_metrics/browser_profile_type.h" #include "components/url_formatter/url_formatter.h" #include "url/gurl.h" @@ -51,9 +52,11 @@ return Scheme::UNKNOWN; } -void RecordMainFrameNavigation(const GURL& url, - bool is_same_document, - bool is_off_the_record) { +void RecordMainFrameNavigation( + const GURL& url, + bool is_same_document, + bool is_off_the_record, + profile_metrics::BrowserProfileType profile_type) { Scheme scheme = GetScheme(url); UMA_HISTOGRAM_ENUMERATION("Navigation.MainFrameScheme", scheme, Scheme::COUNT); @@ -76,9 +79,8 @@ UMA_HISTOGRAM_ENUMERATION("Navigation.MainFrameSchemeDifferentPageOTR", scheme, Scheme::COUNT); } - - base::RecordAction(base::UserMetricsAction("PageLoadInIncognito")); } + UMA_HISTOGRAM_ENUMERATION("Navigation.MainFrameProfileType", profile_type); } void RecordOmniboxURLNavigation(const GURL& url) {
diff --git a/components/navigation_metrics/navigation_metrics.h b/components/navigation_metrics/navigation_metrics.h index 7f4ebcb..a55887a 100644 --- a/components/navigation_metrics/navigation_metrics.h +++ b/components/navigation_metrics/navigation_metrics.h
@@ -7,6 +7,10 @@ class GURL; +namespace profile_metrics { +enum class BrowserProfileType; +} + namespace navigation_metrics { // A Scheme is an C++ enum type loggable in UMA for a histogram of UMA enum type @@ -39,9 +43,11 @@ Scheme GetScheme(const GURL& url); -void RecordMainFrameNavigation(const GURL& url, - bool is_same_document, - bool is_off_the_record); +void RecordMainFrameNavigation( + const GURL& url, + bool is_same_document, + bool is_off_the_record, + profile_metrics::BrowserProfileType profile_type); void RecordOmniboxURLNavigation(const GURL& url);
diff --git a/components/navigation_metrics/navigation_metrics_unittest.cc b/components/navigation_metrics/navigation_metrics_unittest.cc index d48a3196..c4a60ad 100644 --- a/components/navigation_metrics/navigation_metrics_unittest.cc +++ b/components/navigation_metrics/navigation_metrics_unittest.cc
@@ -5,7 +5,7 @@ #include "components/navigation_metrics/navigation_metrics.h" #include "base/test/metrics/histogram_tester.h" -#include "base/test/metrics/user_action_tester.h" +#include "components/profile_metrics/browser_profile_type.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -19,10 +19,10 @@ const char* const kMainFrameSchemeOTR = "Navigation.MainFrameSchemeOTR"; const char* const kMainFrameSchemeDifferentPageOTR = "Navigation.MainFrameSchemeDifferentPageOTR"; -const char* const kPageLoadInIncognito = "PageLoadInIncognito"; constexpr char kMainFrameHasRTLDomain[] = "Navigation.MainFrameHasRTLDomain"; constexpr char kMainFrameHasRTLDomainDifferentPage[] = "Navigation.MainFrameHasRTLDomainDifferentPage"; +constexpr char kMainFrameProfileType[] = "Navigation.MainFrameProfileType"; } // namespace namespace navigation_metrics { @@ -30,7 +30,8 @@ TEST(NavigationMetrics, MainFrameSchemeDifferentDocument) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kTestUrl), false, false); + RecordMainFrameNavigation(GURL(kTestUrl), false, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameScheme, 1); test.ExpectUniqueSample(kMainFrameScheme, 1 /* http */, 1); @@ -38,25 +39,32 @@ test.ExpectUniqueSample(kMainFrameSchemeDifferentPage, 1 /* http */, 1); test.ExpectTotalCount(kMainFrameSchemeOTR, 0); test.ExpectTotalCount(kMainFrameSchemeDifferentPageOTR, 0); + test.ExpectTotalCount(kMainFrameProfileType, 1); + test.ExpectUniqueSample(kMainFrameProfileType, + profile_metrics::BrowserProfileType::kRegular, 1); } TEST(NavigationMetrics, MainFrameSchemeSameDocument) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kTestUrl), true, false); + RecordMainFrameNavigation(GURL(kTestUrl), true, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameScheme, 1); test.ExpectUniqueSample(kMainFrameScheme, 1 /* http */, 1); test.ExpectTotalCount(kMainFrameSchemeDifferentPage, 0); test.ExpectTotalCount(kMainFrameSchemeOTR, 0); test.ExpectTotalCount(kMainFrameSchemeDifferentPageOTR, 0); + test.ExpectTotalCount(kMainFrameProfileType, 1); + test.ExpectUniqueSample(kMainFrameProfileType, + profile_metrics::BrowserProfileType::kRegular, 1); } TEST(NavigationMetrics, MainFrameSchemeDifferentDocumentOTR) { base::HistogramTester test; - base::UserActionTester user_action_tester; - RecordMainFrameNavigation(GURL(kTestUrl), false, true); + RecordMainFrameNavigation(GURL(kTestUrl), false, true, + profile_metrics::BrowserProfileType::kIncognito); test.ExpectTotalCount(kMainFrameScheme, 1); test.ExpectUniqueSample(kMainFrameScheme, 1 /* http */, 1); @@ -66,14 +74,16 @@ test.ExpectUniqueSample(kMainFrameSchemeOTR, 1 /* http */, 1); test.ExpectTotalCount(kMainFrameSchemeDifferentPageOTR, 1); test.ExpectUniqueSample(kMainFrameSchemeDifferentPageOTR, 1 /* http */, 1); - EXPECT_EQ(1, user_action_tester.GetActionCount(kPageLoadInIncognito)); + test.ExpectTotalCount(kMainFrameProfileType, 1); + test.ExpectUniqueSample(kMainFrameProfileType, + profile_metrics::BrowserProfileType::kIncognito, 1); } TEST(NavigationMetrics, MainFrameSchemeSameDocumentOTR) { base::HistogramTester test; - base::UserActionTester user_action_tester; - RecordMainFrameNavigation(GURL(kTestUrl), true, true); + RecordMainFrameNavigation(GURL(kTestUrl), true, true, + profile_metrics::BrowserProfileType::kIncognito); test.ExpectTotalCount(kMainFrameScheme, 1); test.ExpectUniqueSample(kMainFrameScheme, 1 /* http */, 1); @@ -81,12 +91,15 @@ test.ExpectTotalCount(kMainFrameSchemeOTR, 1); test.ExpectUniqueSample(kMainFrameSchemeOTR, 1 /* http */, 1); test.ExpectTotalCount(kMainFrameSchemeDifferentPageOTR, 0); - EXPECT_EQ(1, user_action_tester.GetActionCount(kPageLoadInIncognito)); + test.ExpectTotalCount(kMainFrameProfileType, 1); + test.ExpectUniqueSample(kMainFrameProfileType, + profile_metrics::BrowserProfileType::kIncognito, 1); } TEST(NavigationMetrics, MainFrameDifferentDocumentHasRTLDomainFalse) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kTestUrl), false, false); + RecordMainFrameNavigation(GURL(kTestUrl), false, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameHasRTLDomainDifferentPage, 1); test.ExpectTotalCount(kMainFrameHasRTLDomain, 1); test.ExpectUniqueSample(kMainFrameHasRTLDomainDifferentPage, 0 /* false */, @@ -96,7 +109,8 @@ TEST(NavigationMetrics, MainFrameDifferentDocumentHasRTLDomainTrue) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kRtlUrl), false, false); + RecordMainFrameNavigation(GURL(kRtlUrl), false, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameHasRTLDomainDifferentPage, 1); test.ExpectTotalCount(kMainFrameHasRTLDomain, 1); test.ExpectUniqueSample(kMainFrameHasRTLDomainDifferentPage, 1 /* true */, 1); @@ -105,7 +119,8 @@ TEST(NavigationMetrics, MainFrameSameDocumentHasRTLDomainFalse) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kTestUrl), true, false); + RecordMainFrameNavigation(GURL(kTestUrl), true, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameHasRTLDomainDifferentPage, 0); test.ExpectTotalCount(kMainFrameHasRTLDomain, 1); test.ExpectUniqueSample(kMainFrameHasRTLDomain, 0 /* false */, 1); @@ -113,7 +128,8 @@ TEST(NavigationMetrics, MainFrameSameDocumentHasRTLDomainTrue) { base::HistogramTester test; - RecordMainFrameNavigation(GURL(kRtlUrl), true, false); + RecordMainFrameNavigation(GURL(kRtlUrl), true, false, + profile_metrics::BrowserProfileType::kRegular); test.ExpectTotalCount(kMainFrameHasRTLDomainDifferentPage, 0); test.ExpectTotalCount(kMainFrameHasRTLDomain, 1); test.ExpectUniqueSample(kMainFrameHasRTLDomain, 1 /* true */, 1);
diff --git a/components/sync_sessions/BUILD.gn b/components/sync_sessions/BUILD.gn index aaf60e8f..9c97a5b1 100644 --- a/components/sync_sessions/BUILD.gn +++ b/components/sync_sessions/BUILD.gn
@@ -58,6 +58,7 @@ "//base", "//components/bookmarks/browser", "//components/favicon/core", + "//components/favicon_base", "//components/history/core/browser", "//components/keyed_service/core", "//components/prefs",
diff --git a/components/sync_sessions/DEPS b/components/sync_sessions/DEPS index bf900e2..c1e43a7 100644 --- a/components/sync_sessions/DEPS +++ b/components/sync_sessions/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/bookmarks/browser", "+components/favicon/core", + "+components/favicon_base", "+components/history/core/browser", "+components/keyed_service/core", "+components/prefs",
diff --git a/components/sync_sessions/favicon_cache.cc b/components/sync_sessions/favicon_cache.cc index 4a36980..c5e92f1 100644 --- a/components/sync_sessions/favicon_cache.cc +++ b/components/sync_sessions/favicon_cache.cc
@@ -480,31 +480,38 @@ syncer::SyncChange::ACTION_ADD)); } -scoped_refptr<base::RefCountedMemory> +favicon_base::FaviconRawBitmapResult FaviconCache::GetSyncedFaviconForFaviconURL(const GURL& favicon_url) const { if (!favicon_url.is_valid()) - return nullptr; + return favicon_base::FaviconRawBitmapResult(); auto iter = synced_favicons_.find(favicon_url); UMA_HISTOGRAM_BOOLEAN("Sync.FaviconCacheLookupSucceeded", iter != synced_favicons_.end()); if (iter == synced_favicons_.end()) - return nullptr; + return favicon_base::FaviconRawBitmapResult(); // TODO(zea): support getting other resolutions. if (!iter->second->bitmap_data[SIZE_16].bitmap_data.get()) - return nullptr; + return favicon_base::FaviconRawBitmapResult(); - return iter->second->bitmap_data[SIZE_16].bitmap_data; + favicon_base::FaviconRawBitmapResult sync_bitmap_result; + // Size is at most 16x16. + sync_bitmap_result.pixel_size = gfx::Size(16, 16); + sync_bitmap_result.icon_type = favicon_base::IconType::kFavicon; + sync_bitmap_result.icon_url = favicon_url; + sync_bitmap_result.bitmap_data = + iter->second->bitmap_data[SIZE_16].bitmap_data; + return sync_bitmap_result; } -scoped_refptr<base::RefCountedMemory> FaviconCache::GetSyncedFaviconForPageURL( +favicon_base::FaviconRawBitmapResult FaviconCache::GetSyncedFaviconForPageURL( const GURL& page_url) const { if (!page_url.is_valid()) - return nullptr; + return favicon_base::FaviconRawBitmapResult(); GURL icon_url = GetIconUrlForPageUrl(page_url); if (icon_url.is_empty()) - return nullptr; + return favicon_base::FaviconRawBitmapResult(); return GetSyncedFaviconForFaviconURL(icon_url); }
diff --git a/components/sync_sessions/favicon_cache.h b/components/sync_sessions/favicon_cache.h index 4760a9e..7efaaea 100644 --- a/components/sync_sessions/favicon_cache.h +++ b/components/sync_sessions/favicon_cache.h
@@ -22,6 +22,7 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/task/cancelable_task_tracker.h" +#include "components/favicon_base/favicon_types.h" #include "components/history/core/browser/history_service_observer.h" #include "components/history/core/browser/history_types.h" #include "components/sessions/core/session_id.h" @@ -80,7 +81,7 @@ // If a valid favicon for the icon at |favicon_url| is found, returns a // pointer to the png-encoded image. Otherwise, returns nullptr. - scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForFaviconURL( + favicon_base::FaviconRawBitmapResult GetSyncedFaviconForFaviconURL( const GURL& favicon_url) const; // Returns the value associated with |page_url| in |page_favicon_map_| if one @@ -89,7 +90,7 @@ // If a valid favicon for the icon associated with |page_url| is found, // returns a pointer to the png-encoded image. Otherwise, returns nullptr. - scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForPageURL( + favicon_base::FaviconRawBitmapResult GetSyncedFaviconForPageURL( const GURL& page_url) const; // Load the favicon for |page_url|. Will create a new sync node or update
diff --git a/components/sync_sessions/favicon_cache_unittest.cc b/components/sync_sessions/favicon_cache_unittest.cc index 851c2a4..0a46b39 100644 --- a/components/sync_sessions/favicon_cache_unittest.cc +++ b/components/sync_sessions/favicon_cache_unittest.cc
@@ -347,14 +347,14 @@ const std::string& page_url, const std::string& bytes) const { GURL gurl(page_url); - scoped_refptr<base::RefCountedMemory> favicon = + favicon_base::FaviconRawBitmapResult favicon = cache_.GetSyncedFaviconForPageURL(gurl); - if (!favicon) + if (!favicon.is_valid()) return testing::AssertionFailure() << "Favicon is missing."; - if (favicon->size() != bytes.size()) + if (favicon.bitmap_data->size() != bytes.size()) return testing::AssertionFailure() << "Favicon sizes don't match."; - for (size_t i = 0; i < favicon->size(); ++i) { - if (bytes[i] != *(favicon->front() + i)) + for (size_t i = 0; i < favicon.bitmap_data->size(); ++i) { + if (bytes[i] != *(favicon.bitmap_data->front() + i)) return testing::AssertionFailure() << "Favicon data doesn't match."; } return testing::AssertionSuccess();
diff --git a/components/sync_sessions/open_tabs_ui_delegate.h b/components/sync_sessions/open_tabs_ui_delegate.h index 9d92d9a..b1ea5e3 100644 --- a/components/sync_sessions/open_tabs_ui_delegate.h +++ b/components/sync_sessions/open_tabs_ui_delegate.h
@@ -11,9 +11,11 @@ #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" #include "components/favicon/core/favicon_url_mapper.h" +#include "components/favicon_base/favicon_types.h" #include "components/sessions/core/session_id.h" #include "components/sessions/core/session_types.h" #include "components/sync_sessions/synced_session.h" +#include "url/gurl.h" namespace sync_sessions { @@ -21,9 +23,8 @@ public: // If a valid favicon for the page at |page_url| is found, returns a pointer // to the png-encoded image. Otherwise, returns nullptr. - // TODO(victorvianna): Consider changing from string to GURL. - virtual scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForPageURL( - const std::string& page_url) const = 0; + virtual favicon_base::FaviconRawBitmapResult GetSyncedFaviconForPageURL( + const GURL& page_url) const = 0; // Builds a list of all foreign sessions, ordered from most recent to least // recent. Caller does NOT own SyncedSession objects.
diff --git a/components/sync_sessions/open_tabs_ui_delegate_impl.cc b/components/sync_sessions/open_tabs_ui_delegate_impl.cc index 658f523..fe01092a 100644 --- a/components/sync_sessions/open_tabs_ui_delegate_impl.cc +++ b/components/sync_sessions/open_tabs_ui_delegate_impl.cc
@@ -41,10 +41,9 @@ OpenTabsUIDelegateImpl::~OpenTabsUIDelegateImpl() {} -scoped_refptr<base::RefCountedMemory> -OpenTabsUIDelegateImpl::GetSyncedFaviconForPageURL( - const std::string& page_url) const { - return favicon_cache_->GetSyncedFaviconForPageURL(GURL(page_url)); +favicon_base::FaviconRawBitmapResult +OpenTabsUIDelegateImpl::GetSyncedFaviconForPageURL(const GURL& page_url) const { + return favicon_cache_->GetSyncedFaviconForPageURL(page_url); } bool OpenTabsUIDelegateImpl::GetAllForeignSessions(
diff --git a/components/sync_sessions/open_tabs_ui_delegate_impl.h b/components/sync_sessions/open_tabs_ui_delegate_impl.h index 412dcd0..6f2b8cf 100644 --- a/components/sync_sessions/open_tabs_ui_delegate_impl.h +++ b/components/sync_sessions/open_tabs_ui_delegate_impl.h
@@ -32,8 +32,8 @@ ~OpenTabsUIDelegateImpl() override; // OpenTabsUIDelegate implementation. - scoped_refptr<base::RefCountedMemory> GetSyncedFaviconForPageURL( - const std::string& page_url) const override; + favicon_base::FaviconRawBitmapResult GetSyncedFaviconForPageURL( + const GURL& page_url) const override; bool GetAllForeignSessions( std::vector<const SyncedSession*>* sessions) override; bool GetForeignSession(
diff --git a/content/browser/resources/histograms/histograms_internals.js b/content/browser/resources/histograms/histograms_internals.js index 4be9ac7..24c55fb 100644 --- a/content/browser/resources/histograms/histograms_internals.js +++ b/content/browser/resources/histograms/histograms_internals.js
@@ -20,7 +20,7 @@ */ function addHistograms(histograms) { let htmlOutput = ''; - for (let histogram of histograms) { + for (const histogram of histograms) { htmlOutput += histogram; }
diff --git a/content/browser/service_worker/service_worker_job_unittest.cc b/content/browser/service_worker/service_worker_job_unittest.cc index 1a1e55efa..e9960c2 100644 --- a/content/browser/service_worker/service_worker_job_unittest.cc +++ b/content/browser/service_worker/service_worker_job_unittest.cc
@@ -12,6 +12,7 @@ #include "base/optional.h" #include "base/run_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_feature_list.h" #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" #include "content/browser/frame_host/frame_tree_node.h" @@ -31,12 +32,14 @@ #include "content/common/service_worker/service_worker_utils.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/test/fake_network_url_loader_factory.h" #include "ipc/ipc_test_sink.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" #include "net/http/http_response_headers.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h" @@ -112,6 +115,13 @@ return base::BindOnce(&SaveUnregistrationCallback, expected_status, called); } +void RequestTermination( + blink::mojom::EmbeddedWorkerInstanceHostAssociatedPtr* host) { + // We can't wait for the callback since StopWorker() arrives before it which + // severs the Mojo connection. + (*host)->RequestTermination(base::DoNothing()); +} + } // namespace class ServiceWorkerJobTest : public testing::Test { @@ -451,57 +461,6 @@ EXPECT_EQ(new_registration_by_scope, old_registration); } -// Make sure that the same registration is used and the update_via_cache value -// is updated when registering a duplicate scope+script_url with a different -// update_via_cache value. -TEST_F(ServiceWorkerJobTest, RegisterWithDifferentUpdateViaCache) { - GURL script_url("https://www.example.com/service_worker.js"); - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = GURL("https://www.example.com/"); - - scoped_refptr<ServiceWorkerRegistration> old_registration = - RunRegisterJob(script_url, options); - - EXPECT_EQ(blink::mojom::ServiceWorkerUpdateViaCache::kImports, - old_registration->update_via_cache()); - - // During the above registration, a service worker registration object host - // for ServiceWorkerGlobalScope#registration has been created/added into - // |provider_host|. - ServiceWorkerProviderHost* provider_host = - old_registration->active_version()->provider_host(); - ASSERT_NE(nullptr, provider_host); - - // Clear all service worker object hosts. - provider_host->service_worker_object_hosts_.clear(); - // Ensure that the registration's object host doesn't have the reference. - EXPECT_EQ(1UL, provider_host->registration_object_hosts_.size()); - provider_host->registration_object_hosts_.clear(); - EXPECT_EQ(0UL, provider_host->registration_object_hosts_.size()); - ASSERT_TRUE(old_registration->HasOneRef()); - - scoped_refptr<ServiceWorkerRegistration> old_registration_by_scope = - FindRegistrationForScope(options.scope); - - ASSERT_TRUE(old_registration_by_scope.get()); - - options.update_via_cache = blink::mojom::ServiceWorkerUpdateViaCache::kNone; - scoped_refptr<ServiceWorkerRegistration> new_registration = - RunRegisterJob(script_url, options); - - // Ensure that the registration object is not copied. - ASSERT_EQ(old_registration, new_registration); - EXPECT_EQ(blink::mojom::ServiceWorkerUpdateViaCache::kNone, - new_registration->update_via_cache()); - - ASSERT_FALSE(old_registration->HasOneRef()); - - scoped_refptr<ServiceWorkerRegistration> new_registration_by_scope = - FindRegistrationForScope(options.scope); - - EXPECT_EQ(new_registration_by_scope, old_registration); -} - // An instance client that breaks the Mojo connection upon receiving the // Start() message. class FailStartInstanceClient : public FakeEmbeddedWorkerInstanceClient { @@ -899,559 +858,6 @@ EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, version->status()); } -namespace { // Helpers for the update job tests. - -const GURL kNoChangeOrigin("https://nochange/"); -const GURL kNewVersionOrigin("https://newversion/"); -const char kScope[] = "scope/"; -const char kScript[] = "script.js"; - -void RunNestedUntilIdle() { - base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle(); -} - -void OnIOComplete(int* rv_out, int rv) { - *rv_out = rv; -} - -void WriteResponse(ServiceWorkerStorage* storage, - int64_t id, - const std::string& headers, - IOBuffer* body, - int length) { - std::unique_ptr<ServiceWorkerResponseWriter> writer = - storage->CreateResponseWriter(id); - - std::unique_ptr<net::HttpResponseInfo> info = - std::make_unique<net::HttpResponseInfo>(); - info->request_time = base::Time::Now(); - info->response_time = base::Time::Now(); - info->was_cached = false; - info->headers = new net::HttpResponseHeaders(headers); - scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = - base::MakeRefCounted<HttpResponseInfoIOBuffer>(std::move(info)); - - int rv = -1234; - writer->WriteInfo(info_buffer.get(), base::BindOnce(&OnIOComplete, &rv)); - RunNestedUntilIdle(); - EXPECT_LT(0, rv); - - rv = -1234; - writer->WriteData(body, length, base::BindOnce(&OnIOComplete, &rv)); - RunNestedUntilIdle(); - EXPECT_EQ(length, rv); -} - -void WriteStringResponse(ServiceWorkerStorage* storage, - int64_t id, - const std::string& body) { - scoped_refptr<IOBuffer> body_buffer = - base::MakeRefCounted<WrappedIOBuffer>(body.data()); - const char kHttpHeaders[] = "HTTP/1.0 200 HONKYDORY\0\0"; - std::string headers(kHttpHeaders, base::size(kHttpHeaders)); - WriteResponse(storage, id, headers, body_buffer.get(), body.length()); -} - -class UpdateJobTestHelper : public EmbeddedWorkerTestHelper, - public ServiceWorkerRegistration::Listener, - public ServiceWorkerContextCoreObserver { - public: - struct AttributeChangeLogEntry { - int64_t registration_id; - blink::mojom::ChangedServiceWorkerObjectsMaskPtr mask; - ServiceWorkerRegistrationInfo info; - }; - - struct StateChangeLogEntry { - int64_t version_id; - ServiceWorkerVersion::Status status; - }; - - UpdateJobTestHelper() - : EmbeddedWorkerTestHelper(base::FilePath()), weak_factory_(this) { - context_wrapper()->AddObserver(this); - } - ~UpdateJobTestHelper() override { - context_wrapper()->RemoveObserver(this); - if (observed_registration_.get()) - observed_registration_->RemoveListener(this); - } - - class UpdateJobEmbeddedWorkerInstanceClient - : public FakeEmbeddedWorkerInstanceClient { - public: - UpdateJobEmbeddedWorkerInstanceClient(UpdateJobTestHelper* helper) - : FakeEmbeddedWorkerInstanceClient(helper) {} - ~UpdateJobEmbeddedWorkerInstanceClient() override = default; - - void set_force_start_worker_failure(bool force_start_worker_failure) { - force_start_worker_failure_ = force_start_worker_failure; - } - - void ResumeAfterDownload() override { - if (force_start_worker_failure_) { - host()->OnScriptEvaluationStart(); - host()->OnStarted( - blink::mojom::ServiceWorkerStartStatus::kAbruptCompletion, - helper()->GetNextThreadId(), - blink::mojom::EmbeddedWorkerStartTiming::New()); - return; - } - FakeEmbeddedWorkerInstanceClient::ResumeAfterDownload(); - } - - private: - bool force_start_worker_failure_ = false; - }; - - ServiceWorkerStorage* storage() { return context()->storage(); } - ServiceWorkerJobCoordinator* job_coordinator() { - return context()->job_coordinator(); - } - - scoped_refptr<ServiceWorkerRegistration> SetupInitialRegistration( - const GURL& test_origin) { - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = test_origin.Resolve(kScope); - scoped_refptr<ServiceWorkerRegistration> registration; - bool called = false; - - auto client = std::make_unique<UpdateJobEmbeddedWorkerInstanceClient>(this); - initial_embedded_worker_instance_client_ = client.get(); - AddPendingInstanceClient(std::move(client)); - - job_coordinator()->Register( - test_origin.Resolve(kScript), options, - SaveRegistration(blink::ServiceWorkerStatusCode::kOk, &called, - ®istration)); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(called); - EXPECT_TRUE(registration.get()); - EXPECT_TRUE(registration->active_version()); - EXPECT_FALSE(registration->installing_version()); - EXPECT_FALSE(registration->waiting_version()); - observed_registration_ = registration; - return registration; - } - - // EmbeddedWorkerTestHelper overrides: - void PopulateScriptCacheMap(int64_t version_id, - base::OnceClosure callback) override { - const std::string kMockScriptBody = "mock_script"; - const uint64_t kMockScriptSize = 19284; - ServiceWorkerVersion* version = context()->GetLiveVersion(version_id); - ASSERT_TRUE(version); - ServiceWorkerRegistration* registration = - context()->GetLiveRegistration(version->registration_id()); - ASSERT_TRUE(registration); - GURL script = version->script_url(); - bool is_update = registration->active_version() && - version != registration->active_version(); - - // Simulate network access. - base::TimeDelta time_since_last_check = - base::Time::Now() - registration->last_update_check(); - if (!is_update || script.GetOrigin() != kNoChangeOrigin || - time_since_last_check > kServiceWorkerScriptMaxCacheAge) { - version->embedded_worker()->OnNetworkAccessedForScriptLoad(); - } - - int64_t resource_id = storage()->NewResourceId(); - version->script_cache_map()->NotifyStartedCaching(script, resource_id); - if (!is_update) { - // Spoof caching the script for the initial version. - WriteStringResponse(storage(), resource_id, kMockScriptBody); - version->script_cache_map()->NotifyFinishedCaching( - script, kMockScriptSize, net::OK, std::string()); - } else if (script.GetOrigin() == kNoChangeOrigin) { - // Simulate fetching the updated script and finding it's identical to - // the incumbent. - version->script_cache_map()->NotifyFinishedCaching( - script, kMockScriptSize, net::ERR_FILE_EXISTS, std::string()); - } else { - // Spoof caching the script for the new version. - WriteStringResponse(storage(), resource_id, "mock_different_script"); - version->script_cache_map()->NotifyFinishedCaching( - script, kMockScriptSize, net::OK, std::string()); - } - version->SetMainScriptHttpResponseInfo(CreateHttpResponseInfo()); - std::move(callback).Run(); - } - - // ServiceWorkerContextCoreObserver overrides - void OnVersionStateChanged(int64_t version_id, - const GURL& scope, - ServiceWorkerVersion::Status status) override { - StateChangeLogEntry entry; - entry.version_id = version_id; - entry.status = status; - state_change_log_.push_back(std::move(entry)); - } - - // ServiceWorkerRegistration::Listener overrides - void OnVersionAttributesChanged( - ServiceWorkerRegistration* registration, - blink::mojom::ChangedServiceWorkerObjectsMaskPtr changed_mask, - const ServiceWorkerRegistrationInfo& info) override { - AttributeChangeLogEntry entry; - entry.registration_id = registration->id(); - entry.mask = std::move(changed_mask); - entry.info = info; - attribute_change_log_.push_back(std::move(entry)); - } - - void OnRegistrationFailed(ServiceWorkerRegistration* registration) override { - registration_failed_ = true; - } - - void OnUpdateFound(ServiceWorkerRegistration* registration) override { - update_found_ = true; - } - - UpdateJobEmbeddedWorkerInstanceClient* - initial_embedded_worker_instance_client_ = nullptr; - scoped_refptr<ServiceWorkerRegistration> observed_registration_; - std::vector<AttributeChangeLogEntry> attribute_change_log_; - std::vector<StateChangeLogEntry> state_change_log_; - bool update_found_ = false; - bool registration_failed_ = false; - bool force_start_worker_failure_ = false; - base::Optional<bool> will_be_terminated_; - - base::WeakPtrFactory<UpdateJobTestHelper> weak_factory_; -}; - -void RequestTermination( - blink::mojom::EmbeddedWorkerInstanceHostAssociatedPtr* host) { - // We can't wait for the callback since StopWorker() arrives before it which - // severs the Mojo connection. - (*host)->RequestTermination(base::DoNothing()); -} - -} // namespace - -TEST_F(ServiceWorkerJobTest, Update_NoChange) { - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); - scoped_refptr<ServiceWorkerRegistration> registration = - update_helper->SetupInitialRegistration(kNoChangeOrigin); - ASSERT_TRUE(registration.get()); - ASSERT_EQ(4u, update_helper->state_change_log_.size()); - EXPECT_EQ(ServiceWorkerVersion::INSTALLING, - update_helper->state_change_log_[0].status); - EXPECT_EQ(ServiceWorkerVersion::INSTALLED, - update_helper->state_change_log_[1].status); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, - update_helper->state_change_log_[2].status); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, - update_helper->state_change_log_[3].status); - update_helper->state_change_log_.clear(); - - // Run the update job. - registration->AddListener(update_helper); - scoped_refptr<ServiceWorkerVersion> first_version = - registration->active_version(); - first_version->StartUpdate(); - base::RunLoop().RunUntilIdle(); - - // Verify results. - ASSERT_TRUE(registration->active_version()); - EXPECT_EQ(first_version.get(), registration->active_version()); - EXPECT_FALSE(registration->installing_version()); - EXPECT_FALSE(registration->waiting_version()); - EXPECT_TRUE(update_helper->attribute_change_log_.empty()); - ASSERT_EQ(1u, update_helper->state_change_log_.size()); - EXPECT_NE(registration->active_version()->version_id(), - update_helper->state_change_log_[0].version_id); - EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, - update_helper->state_change_log_[0].status); - EXPECT_FALSE(update_helper->update_found_); -} - -TEST_F(ServiceWorkerJobTest, Update_BumpLastUpdateCheckTime) { - const base::Time kToday = base::Time::Now(); - const base::Time kYesterday = - kToday - base::TimeDelta::FromDays(1) - base::TimeDelta::FromHours(1); - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); - scoped_refptr<ServiceWorkerRegistration> registration = - update_helper->SetupInitialRegistration(kNoChangeOrigin); - ASSERT_TRUE(registration.get()); - - registration->AddListener(update_helper); - - // Run an update where the script did not change and the network was not - // accessed. The check time should not be updated. - registration->set_last_update_check(kToday); - registration->active_version()->StartUpdate(); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(kToday, registration->last_update_check()); - EXPECT_FALSE(update_helper->update_found_); - - // Run an update where the script did not change and the network was accessed. - // The check time should be updated. - registration->set_last_update_check(kYesterday); - registration->active_version()->StartUpdate(); - base::RunLoop().RunUntilIdle(); - EXPECT_LT(kYesterday, registration->last_update_check()); - EXPECT_FALSE(update_helper->update_found_); - registration->RemoveListener(update_helper); - - registration = update_helper->SetupInitialRegistration(kNewVersionOrigin); - ASSERT_TRUE(registration.get()); - - registration->AddListener(update_helper); - - // Run an update where the script changed. The check time should be updated. - registration->set_last_update_check(kYesterday); - registration->active_version()->StartUpdate(); - base::RunLoop().RunUntilIdle(); - EXPECT_LT(kYesterday, registration->last_update_check()); - - // Run an update to a worker that loads successfully but fails to start up - // (script evaluation failure). The check time should be updated. - auto* embedded_worker_instance_client = - update_helper->AddNewPendingInstanceClient< - UpdateJobTestHelper::UpdateJobEmbeddedWorkerInstanceClient>( - update_helper); - embedded_worker_instance_client->set_force_start_worker_failure(true); - registration->set_last_update_check(kYesterday); - registration->active_version()->StartUpdate(); - base::RunLoop().RunUntilIdle(); - EXPECT_LT(kYesterday, registration->last_update_check()); -} - -TEST_F(ServiceWorkerJobTest, Update_NewVersion) { - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); - scoped_refptr<ServiceWorkerRegistration> registration = - update_helper->SetupInitialRegistration(kNewVersionOrigin); - ASSERT_TRUE(registration.get()); - update_helper->state_change_log_.clear(); - auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); - registration->SetTaskRunnerForTest(runner); - - // Run the update job. - registration->AddListener(update_helper); - scoped_refptr<ServiceWorkerVersion> first_version = - registration->active_version(); - first_version->StartUpdate(); - base::RunLoop().RunUntilIdle(); - - // The worker is updated after RequestTermination() is called from the - // renderer. Until then, the active version stays active. - EXPECT_EQ(first_version.get(), registration->active_version()); - // The new worker is installed but not yet to be activated. - scoped_refptr<ServiceWorkerVersion> new_version = - registration->waiting_version(); - EXPECT_EQ(2u, update_helper->attribute_change_log_.size()); - UpdateJobTestHelper::UpdateJobEmbeddedWorkerInstanceClient* client = - update_helper->initial_embedded_worker_instance_client_; - RequestTermination(&client->host()); - - TestServiceWorkerObserver observer(helper_->context_wrapper()); - observer.RunUntilActivated(new_version.get(), runner); - - // Pump the loop again. This ensures |update_helper| observes all - // the status changes, since RunUntilActivated() only ensured - // ServiceWorkerJobTest did. - base::RunLoop().RunUntilIdle(); - - // Verify results. - ASSERT_TRUE(registration->active_version()); - EXPECT_NE(first_version.get(), registration->active_version()); - EXPECT_FALSE(registration->installing_version()); - EXPECT_FALSE(registration->waiting_version()); - ASSERT_EQ(3u, update_helper->attribute_change_log_.size()); - - { - const UpdateJobTestHelper::AttributeChangeLogEntry& entry = - update_helper->attribute_change_log_[0]; - EXPECT_TRUE(entry.mask->installing); - EXPECT_FALSE(entry.mask->waiting); - EXPECT_FALSE(entry.mask->active); - EXPECT_NE(entry.info.installing_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_EQ(entry.info.waiting_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_NE(entry.info.active_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - } - - { - const UpdateJobTestHelper::AttributeChangeLogEntry& entry = - update_helper->attribute_change_log_[1]; - EXPECT_TRUE(entry.mask->installing); - EXPECT_TRUE(entry.mask->waiting); - EXPECT_FALSE(entry.mask->active); - EXPECT_EQ(entry.info.installing_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_NE(entry.info.waiting_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_NE(entry.info.active_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - } - - { - const UpdateJobTestHelper::AttributeChangeLogEntry& entry = - update_helper->attribute_change_log_[2]; - EXPECT_FALSE(entry.mask->installing); - EXPECT_TRUE(entry.mask->waiting); - EXPECT_TRUE(entry.mask->active); - EXPECT_EQ(entry.info.installing_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_EQ(entry.info.waiting_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - EXPECT_NE(entry.info.active_version.version_id, - blink::mojom::kInvalidServiceWorkerVersionId); - } - - // expected version state transitions: - // new.installing, new.installed, - // old.redundant, - // new.activating, new.activated - ASSERT_EQ(5u, update_helper->state_change_log_.size()); - - EXPECT_EQ(registration->active_version()->version_id(), - update_helper->state_change_log_[0].version_id); - EXPECT_EQ(ServiceWorkerVersion::INSTALLING, - update_helper->state_change_log_[0].status); - - EXPECT_EQ(registration->active_version()->version_id(), - update_helper->state_change_log_[1].version_id); - EXPECT_EQ(ServiceWorkerVersion::INSTALLED, - update_helper->state_change_log_[1].status); - - EXPECT_EQ(first_version->version_id(), - update_helper->state_change_log_[2].version_id); - EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, - update_helper->state_change_log_[2].status); - - EXPECT_EQ(registration->active_version()->version_id(), - update_helper->state_change_log_[3].version_id); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, - update_helper->state_change_log_[3].status); - - EXPECT_EQ(registration->active_version()->version_id(), - update_helper->state_change_log_[4].version_id); - EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, - update_helper->state_change_log_[4].status); - - EXPECT_TRUE(update_helper->update_found_); -} - -// Test that the update job uses the script URL of the newest worker when the -// job starts, rather than when it is scheduled. -TEST_F(ServiceWorkerJobTest, Update_ScriptUrlChanged) { - // Create a registration with an active version. - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = GURL("https://www.example.com/one/"); - auto* initial_client = - helper_->AddNewPendingInstanceClient<FakeEmbeddedWorkerInstanceClient>( - helper_.get()); - scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob( - GURL("https://www.example.com/service_worker.js"), options); - auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); - registration->SetTaskRunnerForTest(runner); - - // Queue an Update. When this runs, it will use the waiting version's script. - job_coordinator()->Update(registration.get(), false); - - // Add a waiting version with a new script. - GURL new_script("https://www.example.com/new_worker.js"); - scoped_refptr<ServiceWorkerVersion> version = new ServiceWorkerVersion( - registration.get(), new_script, blink::mojom::ScriptType::kClassic, - 2L /* dummy version id */, helper_->context()->AsWeakPtr()); - registration->SetWaitingVersion(version); - - // Run the update job. - base::RunLoop().RunUntilIdle(); - - // The worker is activated after RequestTermination() is called from the - // renderer. Until then, the active version stays active. - // Still waiting, but the waiting version isn't |version| since another - // ServiceWorkerVersion is created during the update job and the job wipes - // out the older waiting version. - ServiceWorkerVersion* waiting_version = registration->waiting_version(); - EXPECT_TRUE(registration->active_version()); - EXPECT_TRUE(waiting_version); - EXPECT_NE(version.get(), waiting_version); - - RequestTermination(&initial_client->host()); - TestServiceWorkerObserver observer(helper_->context_wrapper()); - observer.RunUntilActivated(waiting_version, runner); - - // The update job should have created a new version with the new script, - // and promoted it to the active version. - EXPECT_EQ(new_script, registration->active_version()->script_url()); - EXPECT_EQ(nullptr, registration->waiting_version()); - EXPECT_EQ(nullptr, registration->installing_version()); -} - -// Test that update fails if the incumbent worker was evicted -// during the update job (this can happen on disk cache failure). -TEST_F(ServiceWorkerJobTest, Update_EvictedIncumbent) { - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); - scoped_refptr<ServiceWorkerRegistration> registration = - update_helper->SetupInitialRegistration(kNewVersionOrigin); - ASSERT_TRUE(registration.get()); - update_helper->state_change_log_.clear(); - - registration->AddListener(update_helper); - scoped_refptr<ServiceWorkerVersion> first_version = - registration->active_version(); - auto* instance_client = helper_->AddNewPendingInstanceClient< - DelayedFakeEmbeddedWorkerInstanceClient>(helper_.get()); - - // Start the update job and make it block on the worker starting. - // Evict the incumbent during that time. - first_version->StartUpdate(); - instance_client->RunUntilStartWorker(); - registration->ForceDelete(); - - // Finish the update job. - instance_client->UnblockStartWorker(); - base::RunLoop().RunUntilIdle(); - - // Verify results. - EXPECT_FALSE(registration->GetNewestVersion()); - EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, first_version->status()); - EXPECT_TRUE(update_helper->attribute_change_log_.empty()); - EXPECT_FALSE(update_helper->update_found_); - EXPECT_TRUE(update_helper->registration_failed_); - EXPECT_TRUE(registration->is_uninstalled()); -} - -TEST_F(ServiceWorkerJobTest, Update_UninstallingRegistration) { - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = GURL("https://www.example.com/one/"); - bool called; - scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob( - GURL("https://www.example.com/service_worker.js"), options); - - // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerProviderHost* host = CreateControllee(); - ServiceWorkerVersion* active_version = registration->active_version(); - active_version->AddControllee(host); - job_coordinator()->Unregister( - GURL("https://www.example.com/one/"), - SaveUnregistration(blink::ServiceWorkerStatusCode::kOk, &called)); - - // Update should abort after it starts and sees uninstalling. - job_coordinator()->Update(registration.get(), false); - - EXPECT_FALSE(called); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(called); - - // Verify the registration was not modified by the Update. - EXPECT_TRUE(registration->is_uninstalling()); - EXPECT_EQ(active_version, registration->active_version()); - EXPECT_EQ(nullptr, registration->waiting_version()); - EXPECT_EQ(nullptr, registration->installing_version()); -} - TEST_F(ServiceWorkerJobTest, RegisterWhileUninstalling) { GURL script1("https://www.example.com/service_worker.js"); GURL script2("https://www.example.com/service_worker.js?new"); @@ -1607,7 +1013,795 @@ EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, new_version->status()); } -TEST_F(ServiceWorkerJobTest, RegisterMultipleTimesWhileUninstalling) { +// A fake service worker for toggling whether a fetch event handler exists. +class FetchHandlerWorker : public FakeServiceWorker { + public: + FetchHandlerWorker(EmbeddedWorkerTestHelper* helper) + : FakeServiceWorker(helper) {} + ~FetchHandlerWorker() override = default; + + void set_has_fetch_handler(bool has_fetch_handler) { + has_fetch_handler_ = has_fetch_handler; + } + + void DispatchInstallEvent( + blink::mojom::ServiceWorker::DispatchInstallEventCallback callback) + override { + std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED, + has_fetch_handler_); + } + + private: + bool has_fetch_handler_ = false; +}; + +TEST_F(ServiceWorkerJobTest, HasFetchHandler) { + GURL script("https://www.example.com/service_worker.js"); + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = GURL("https://www.example.com/"); + scoped_refptr<ServiceWorkerRegistration> registration; + + auto* fetch_handler_worker = + helper_->AddNewPendingServiceWorker<FetchHandlerWorker>(helper_.get()); + fetch_handler_worker->set_has_fetch_handler(true); + RunRegisterJob(script, options); + registration = FindRegistrationForScope(options.scope); + EXPECT_EQ(ServiceWorkerVersion::FetchHandlerExistence::EXISTS, + registration->active_version()->fetch_handler_existence()); + RunUnregisterJob(options.scope); + + auto* no_fetch_handler_worker = + helper_->AddNewPendingServiceWorker<FetchHandlerWorker>(helper_.get()); + no_fetch_handler_worker->set_has_fetch_handler(false); + RunRegisterJob(script, options); + registration = FindRegistrationForScope(options.scope); + EXPECT_EQ(ServiceWorkerVersion::FetchHandlerExistence::DOES_NOT_EXIST, + registration->active_version()->fetch_handler_existence()); + RunUnregisterJob(options.scope); +} + +// Test that clients are alerted of new registrations if they are +// in-scope, so that Clients.claim() or ServiceWorkerContainer.ready work +// correctly. +TEST_F(ServiceWorkerJobTest, AddRegistrationToMatchingProviderHosts) { + GURL scope("https://www.example.com/scope/"); + GURL in_scope("https://www.example.com/scope/page"); + GURL out_scope("https://www.example.com/page"); + + // Make an in-scope client. + ServiceWorkerProviderHost* client = CreateControllee(); + client->UpdateUrls(in_scope, in_scope); + + // Make an in-scope reserved client. + auto provider_info = blink::mojom::ServiceWorkerProviderInfoForWindow::New(); + base::WeakPtr<ServiceWorkerProviderHost> reserved_client = + ServiceWorkerProviderHost::PreCreateNavigationHost( + helper_->context()->AsWeakPtr(), true /* are_ancestors_secure */, + FrameTreeNode::kFrameTreeNodeInvalidId, &provider_info); + reserved_client->UpdateUrls(in_scope, in_scope); + + // Make an out-scope client. + ServiceWorkerProviderHost* out_scope_client = CreateControllee(); + out_scope_client->UpdateUrls(out_scope, out_scope); + + // Make a new registration. + GURL script("https://www.example.com/service_worker.js"); + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = scope; + scoped_refptr<ServiceWorkerRegistration> registration = + RunRegisterJob(script, options); + + EXPECT_EQ(registration.get(), client->MatchRegistration()); + EXPECT_EQ(registration.get(), reserved_client->MatchRegistration()); + EXPECT_NE(registration.get(), out_scope_client->MatchRegistration()); +} + +namespace { // Helpers for the update job tests. + +const GURL kNoChangeOrigin("https://nochange/"); +const GURL kNewVersionOrigin("https://newversion/"); +const char kScope[] = "scope/"; +const char kScript[] = "script.js"; + +const char kHeaders[] = + "HTTP/1.1 200 OK\n" + "Content-Type: application/javascript\n\n"; +const char kBody[] = "/* old body */"; +const char kNewBody[] = "/* new body */"; + +void RunNestedUntilIdle() { + base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle(); +} + +void OnIOComplete(int* rv_out, int rv) { + *rv_out = rv; +} + +void WriteResponse(ServiceWorkerStorage* storage, + int64_t id, + const std::string& headers, + IOBuffer* body, + int length) { + std::unique_ptr<ServiceWorkerResponseWriter> writer = + storage->CreateResponseWriter(id); + + std::unique_ptr<net::HttpResponseInfo> info = + std::make_unique<net::HttpResponseInfo>(); + info->request_time = base::Time::Now(); + info->response_time = base::Time::Now(); + info->was_cached = false; + info->headers = new net::HttpResponseHeaders(headers); + scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = + base::MakeRefCounted<HttpResponseInfoIOBuffer>(std::move(info)); + + int rv = -1234; + writer->WriteInfo(info_buffer.get(), base::BindOnce(&OnIOComplete, &rv)); + RunNestedUntilIdle(); + EXPECT_LT(0, rv); + + rv = -1234; + writer->WriteData(body, length, base::BindOnce(&OnIOComplete, &rv)); + RunNestedUntilIdle(); + EXPECT_EQ(length, rv); +} + +void WriteStringResponse(ServiceWorkerStorage* storage, + int64_t id, + const std::string& body) { + scoped_refptr<IOBuffer> body_buffer = + base::MakeRefCounted<WrappedIOBuffer>(body.data()); + const char kHttpHeaders[] = "HTTP/1.0 200 HONKYDORY\0\0"; + std::string headers(kHttpHeaders, base::size(kHttpHeaders)); + WriteResponse(storage, id, headers, body_buffer.get(), body.length()); +} + +class UpdateJobTestHelper : public EmbeddedWorkerTestHelper, + public ServiceWorkerRegistration::Listener, + public ServiceWorkerContextCoreObserver { + public: + struct AttributeChangeLogEntry { + int64_t registration_id; + blink::mojom::ChangedServiceWorkerObjectsMaskPtr mask; + ServiceWorkerRegistrationInfo info; + }; + + struct StateChangeLogEntry { + int64_t version_id; + ServiceWorkerVersion::Status status; + }; + + UpdateJobTestHelper() + : EmbeddedWorkerTestHelper(base::FilePath()), weak_factory_(this) { + context_wrapper()->AddObserver(this); + if (base::FeatureList::IsEnabled( + blink::features::kServiceWorkerImportedScriptUpdateCheck)) { + loader_factory_for_update_checker_ = + std::make_unique<FakeNetworkURLLoaderFactory>(kHeaders, kBody, true, + net::OK); + SetNetworkFactory(loader_factory_for_update_checker_.get()); + } + } + ~UpdateJobTestHelper() override { + context_wrapper()->RemoveObserver(this); + if (observed_registration_.get()) + observed_registration_->RemoveListener(this); + } + + class UpdateJobEmbeddedWorkerInstanceClient + : public FakeEmbeddedWorkerInstanceClient { + public: + UpdateJobEmbeddedWorkerInstanceClient(UpdateJobTestHelper* helper) + : FakeEmbeddedWorkerInstanceClient(helper) {} + ~UpdateJobEmbeddedWorkerInstanceClient() override = default; + + void set_force_start_worker_failure(bool force_start_worker_failure) { + force_start_worker_failure_ = force_start_worker_failure; + } + + void ResumeAfterDownload() override { + if (force_start_worker_failure_) { + host()->OnScriptEvaluationStart(); + host()->OnStarted( + blink::mojom::ServiceWorkerStartStatus::kAbruptCompletion, + helper()->GetNextThreadId(), + blink::mojom::EmbeddedWorkerStartTiming::New()); + return; + } + FakeEmbeddedWorkerInstanceClient::ResumeAfterDownload(); + } + + private: + bool force_start_worker_failure_ = false; + }; + + ServiceWorkerStorage* storage() { return context()->storage(); } + ServiceWorkerJobCoordinator* job_coordinator() { + return context()->job_coordinator(); + } + + scoped_refptr<ServiceWorkerRegistration> SetupInitialRegistration( + const GURL& test_origin) { + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = test_origin.Resolve(kScope); + scoped_refptr<ServiceWorkerRegistration> registration; + bool called = false; + + auto client = std::make_unique<UpdateJobEmbeddedWorkerInstanceClient>(this); + initial_embedded_worker_instance_client_ = client.get(); + AddPendingInstanceClient(std::move(client)); + + job_coordinator()->Register( + test_origin.Resolve(kScript), options, + SaveRegistration(blink::ServiceWorkerStatusCode::kOk, &called, + ®istration)); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(called); + EXPECT_TRUE(registration.get()); + EXPECT_TRUE(registration->active_version()); + EXPECT_FALSE(registration->installing_version()); + EXPECT_FALSE(registration->waiting_version()); + observed_registration_ = registration; + return registration; + } + + // EmbeddedWorkerTestHelper overrides: + void PopulateScriptCacheMap(int64_t version_id, + base::OnceClosure callback) override { + bool import_script_update_check_enabled = base::FeatureList::IsEnabled( + blink::features::kServiceWorkerImportedScriptUpdateCheck); + + ServiceWorkerVersion* version = context()->GetLiveVersion(version_id); + ASSERT_TRUE(version); + ServiceWorkerRegistration* registration = + context()->GetLiveRegistration(version->registration_id()); + ASSERT_TRUE(registration); + GURL script = version->script_url(); + bool is_update = registration->active_version() && + version != registration->active_version(); + + // When ServiceWorkerImportedScriptUpdateCheck is enabled, whether network + // is accessed is configured in test cases through url loader factory. + // Otherwise, it's simulated as follows: + if (!import_script_update_check_enabled) { + base::TimeDelta time_since_last_check = + base::Time::Now() - registration->last_update_check(); + if (!is_update || script.GetOrigin() != kNoChangeOrigin || + time_since_last_check > kServiceWorkerScriptMaxCacheAge) { + version->embedded_worker()->OnNetworkAccessedForScriptLoad(); + } + } + + int64_t resource_id = storage()->NewResourceId(); + version->script_cache_map()->NotifyStartedCaching(script, resource_id); + if (!is_update) { + // Spoof caching the script for the initial version. + WriteStringResponse(storage(), resource_id, kBody); + version->script_cache_map()->NotifyFinishedCaching( + script, sizeof(kBody) / sizeof(char), net::OK, std::string()); + } else if (script.GetOrigin() == kNoChangeOrigin) { + // It should not reach here when ServiceWorkerImportedScriptUpdateCheck + // is enabled because script is not changed so service worker is not + // started. + DCHECK(!import_script_update_check_enabled); + // When ServiceWorkerImportedScriptUpdateCheck is disabled and + // |kNoChangeOrigin| is used as the script url. + // Simulate fetching the updated script and finding it's identical to + // the incumbent. + version->script_cache_map()->NotifyFinishedCaching( + script, sizeof(kBody) / sizeof(char), net::ERR_FILE_EXISTS, + std::string()); + } else { + // The script must be changed. + WriteStringResponse(storage(), resource_id, kNewBody); + version->script_cache_map()->NotifyFinishedCaching( + script, sizeof(kNewBody) / sizeof(char), net::OK, std::string()); + } + + version->SetMainScriptHttpResponseInfo(CreateHttpResponseInfo()); + std::move(callback).Run(); + } + + // ServiceWorkerContextCoreObserver overrides + void OnVersionStateChanged(int64_t version_id, + const GURL& scope, + ServiceWorkerVersion::Status status) override { + StateChangeLogEntry entry; + entry.version_id = version_id; + entry.status = status; + state_change_log_.push_back(std::move(entry)); + } + + // ServiceWorkerRegistration::Listener overrides + void OnVersionAttributesChanged( + ServiceWorkerRegistration* registration, + blink::mojom::ChangedServiceWorkerObjectsMaskPtr changed_mask, + const ServiceWorkerRegistrationInfo& info) override { + AttributeChangeLogEntry entry; + entry.registration_id = registration->id(); + entry.mask = std::move(changed_mask); + entry.info = info; + attribute_change_log_.push_back(std::move(entry)); + } + + void OnRegistrationFailed(ServiceWorkerRegistration* registration) override { + registration_failed_ = true; + } + + void OnUpdateFound(ServiceWorkerRegistration* registration) override { + update_found_ = true; + } + + UpdateJobEmbeddedWorkerInstanceClient* + initial_embedded_worker_instance_client_ = nullptr; + scoped_refptr<ServiceWorkerRegistration> observed_registration_; + std::vector<AttributeChangeLogEntry> attribute_change_log_; + std::vector<StateChangeLogEntry> state_change_log_; + bool update_found_ = false; + bool registration_failed_ = false; + bool force_start_worker_failure_ = false; + base::Optional<bool> will_be_terminated_; + // This is used only when ServiceWorkerImportedScriptUpdateCheck is enabled. + std::unique_ptr<FakeNetworkURLLoaderFactory> + loader_factory_for_update_checker_; + + base::WeakPtrFactory<UpdateJobTestHelper> weak_factory_; +}; + +} // namespace + +// This class is for cases that can be impacted by different update check +// types. +class ServiceWorkerUpdateJobTest : public ServiceWorkerJobTest, + public testing::WithParamInterface<bool> { + public: + void SetUp() override { + if (IsImportedScriptUpdateCheckEnabled()) { + feature_list_.InitAndEnableFeature( + blink::features::kServiceWorkerImportedScriptUpdateCheck); + } else { + feature_list_.InitAndDisableFeature( + blink::features::kServiceWorkerImportedScriptUpdateCheck); + } + + update_helper_ = new UpdateJobTestHelper(); + helper_.reset(update_helper_); + } + + static bool IsImportedScriptUpdateCheckEnabled() { return GetParam(); } + + protected: + base::test::ScopedFeatureList feature_list_; + UpdateJobTestHelper* update_helper_; +}; + +INSTANTIATE_TEST_SUITE_P(ServiceWorkerUpdateJobTestP, + ServiceWorkerUpdateJobTest, + testing::Bool()); + +// Make sure that the same registration is used and the update_via_cache value +// is updated when registering a service worker with the same parameter except +// for updateViaCache. +TEST_P(ServiceWorkerUpdateJobTest, RegisterWithDifferentUpdateViaCache) { + const GURL script_url("https://www.example.com/service_worker.js"); + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = GURL("https://www.example.com/"); + + scoped_refptr<ServiceWorkerRegistration> old_registration = + RunRegisterJob(script_url, options); + + EXPECT_EQ(blink::mojom::ServiceWorkerUpdateViaCache::kImports, + old_registration->update_via_cache()); + + // During the above registration, a service worker registration object host + // for ServiceWorkerGlobalScope#registration has been created/added into + // |provider_host|. + ServiceWorkerProviderHost* provider_host = + old_registration->active_version()->provider_host(); + ASSERT_TRUE(provider_host); + + // Remove references to |old_registration| so that |old_registration| is the + // only reference to the registration. + provider_host->service_worker_object_hosts_.clear(); + EXPECT_EQ(1UL, provider_host->registration_object_hosts_.size()); + provider_host->registration_object_hosts_.clear(); + EXPECT_EQ(0UL, provider_host->registration_object_hosts_.size()); + EXPECT_TRUE(old_registration->HasOneRef()); + + EXPECT_TRUE(FindRegistrationForScope(options.scope)); + + options.update_via_cache = blink::mojom::ServiceWorkerUpdateViaCache::kNone; + scoped_refptr<ServiceWorkerRegistration> new_registration = + RunRegisterJob(script_url, options); + + // Ensure that the registration object is not copied. + EXPECT_EQ(old_registration, new_registration); + EXPECT_EQ(blink::mojom::ServiceWorkerUpdateViaCache::kNone, + new_registration->update_via_cache()); + + scoped_refptr<ServiceWorkerRegistration> new_registration_by_scope = + FindRegistrationForScope(options.scope); + + EXPECT_EQ(new_registration_by_scope, old_registration); +} + +TEST_P(ServiceWorkerUpdateJobTest, Update_NoChange) { + scoped_refptr<ServiceWorkerRegistration> registration = + update_helper_->SetupInitialRegistration(kNoChangeOrigin); + ASSERT_TRUE(registration.get()); + ASSERT_EQ(4u, update_helper_->state_change_log_.size()); + EXPECT_EQ(ServiceWorkerVersion::INSTALLING, + update_helper_->state_change_log_[0].status); + EXPECT_EQ(ServiceWorkerVersion::INSTALLED, + update_helper_->state_change_log_[1].status); + EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, + update_helper_->state_change_log_[2].status); + EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, + update_helper_->state_change_log_[3].status); + update_helper_->state_change_log_.clear(); + + // Run the update job. + registration->AddListener(update_helper_); + scoped_refptr<ServiceWorkerVersion> first_version = + registration->active_version(); + first_version->StartUpdate(); + base::RunLoop().RunUntilIdle(); + + // Verify results. + ASSERT_TRUE(registration->active_version()); + EXPECT_EQ(first_version.get(), registration->active_version()); + EXPECT_FALSE(registration->installing_version()); + EXPECT_FALSE(registration->waiting_version()); + EXPECT_TRUE(update_helper_->attribute_change_log_.empty()); + EXPECT_FALSE(update_helper_->update_found_); + + // These expectations are only valid when + // ServiceWorkerImportedScriptUpdateCheck is disabled. Otherwise the state + // change data is not available as worker is not started. + if (!IsImportedScriptUpdateCheckEnabled()) { + ASSERT_EQ(1u, update_helper_->state_change_log_.size()); + EXPECT_NE(registration->active_version()->version_id(), + update_helper_->state_change_log_[0].version_id); + EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, + update_helper_->state_change_log_[0].status); + } +} + +TEST_P(ServiceWorkerUpdateJobTest, Update_BumpLastUpdateCheckTime) { + const base::Time kToday = base::Time::Now(); + const base::Time kYesterday = + kToday - base::TimeDelta::FromDays(1) - base::TimeDelta::FromHours(1); + + scoped_refptr<ServiceWorkerRegistration> registration = + update_helper_->SetupInitialRegistration(kNoChangeOrigin); + ASSERT_TRUE(registration.get()); + + registration->AddListener(update_helper_); + + // Run an update where the script did not change and the network was not + // accessed. The check time should not be updated. + // Set network not accessed. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNoChangeOrigin.Resolve(kScript), kHeaders, kBody, + /*network_accessed=*/false, net::OK); + } + registration->set_last_update_check(kToday); + registration->active_version()->StartUpdate(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(kToday, registration->last_update_check()); + EXPECT_FALSE(update_helper_->update_found_); + + // Run an update where the script did not change and the network was + // accessed. The check time should be updated. + // Set network accessed. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNoChangeOrigin.Resolve(kScript), kHeaders, kBody, + /*network_accessed=*/true, net::OK); + } + registration->set_last_update_check(kYesterday); + registration->active_version()->StartUpdate(); + base::RunLoop().RunUntilIdle(); + EXPECT_LT(kYesterday, registration->last_update_check()); + EXPECT_FALSE(update_helper_->update_found_); + registration->RemoveListener(update_helper_); + + registration = update_helper_->SetupInitialRegistration(kNewVersionOrigin); + ASSERT_TRUE(registration.get()); + + registration->AddListener(update_helper_); + + // Run an update where the script changed. The check time should be updated. + // Change script body. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNewVersionOrigin.Resolve(kScript), kHeaders, kNewBody, + /*network_accessed=*/true, net::OK); + } + registration->set_last_update_check(kYesterday); + registration->active_version()->StartUpdate(); + base::RunLoop().RunUntilIdle(); + EXPECT_LT(kYesterday, registration->last_update_check()); + + // Run an update to a worker that loads successfully but fails to start up + // (script evaluation failure). The check time should be updated. + auto* embedded_worker_instance_client = + update_helper_->AddNewPendingInstanceClient< + UpdateJobTestHelper::UpdateJobEmbeddedWorkerInstanceClient>( + update_helper_); + embedded_worker_instance_client->set_force_start_worker_failure(true); + registration->set_last_update_check(kYesterday); + // Change script body. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNewVersionOrigin.Resolve(kScript), kHeaders, kBody, + /*network_accessed=*/true, net::OK); + } + registration->active_version()->StartUpdate(); + base::RunLoop().RunUntilIdle(); + EXPECT_LT(kYesterday, registration->last_update_check()); +} + +TEST_P(ServiceWorkerUpdateJobTest, Update_NewVersion) { + scoped_refptr<ServiceWorkerRegistration> registration = + update_helper_->SetupInitialRegistration(kNewVersionOrigin); + ASSERT_TRUE(registration.get()); + update_helper_->state_change_log_.clear(); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); + registration->SetTaskRunnerForTest(runner); + + // Run the update job and an update is found. + // Change script body. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNewVersionOrigin.Resolve(kScript), kHeaders, kNewBody, + /*network_accessed=*/true, net::OK); + } + registration->AddListener(update_helper_); + scoped_refptr<ServiceWorkerVersion> first_version = + registration->active_version(); + first_version->StartUpdate(); + base::RunLoop().RunUntilIdle(); + + // The worker is updated after RequestTermination() is called from the + // renderer. Until then, the active version stays active. + EXPECT_EQ(first_version.get(), registration->active_version()); + // The new worker is installed but not yet to be activated. + scoped_refptr<ServiceWorkerVersion> new_version = + registration->waiting_version(); + EXPECT_EQ(2u, update_helper_->attribute_change_log_.size()); + UpdateJobTestHelper::UpdateJobEmbeddedWorkerInstanceClient* client = + update_helper_->initial_embedded_worker_instance_client_; + RequestTermination(&client->host()); + + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(new_version.get(), runner); + + // Pump the loop again. This ensures |update_helper_| observes all + // the status changes, since RunUntilActivated() only ensured + // ServiceWorkerJobTest did. + base::RunLoop().RunUntilIdle(); + + // Verify results. + ASSERT_TRUE(registration->active_version()); + EXPECT_NE(first_version.get(), registration->active_version()); + EXPECT_FALSE(registration->installing_version()); + EXPECT_FALSE(registration->waiting_version()); + ASSERT_EQ(3u, update_helper_->attribute_change_log_.size()); + + { + const UpdateJobTestHelper::AttributeChangeLogEntry& entry = + update_helper_->attribute_change_log_[0]; + EXPECT_TRUE(entry.mask->installing); + EXPECT_FALSE(entry.mask->waiting); + EXPECT_FALSE(entry.mask->active); + EXPECT_NE(entry.info.installing_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_EQ(entry.info.waiting_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_NE(entry.info.active_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + } + + { + const UpdateJobTestHelper::AttributeChangeLogEntry& entry = + update_helper_->attribute_change_log_[1]; + EXPECT_TRUE(entry.mask->installing); + EXPECT_TRUE(entry.mask->waiting); + EXPECT_FALSE(entry.mask->active); + EXPECT_EQ(entry.info.installing_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_NE(entry.info.waiting_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_NE(entry.info.active_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + } + + { + const UpdateJobTestHelper::AttributeChangeLogEntry& entry = + update_helper_->attribute_change_log_[2]; + EXPECT_FALSE(entry.mask->installing); + EXPECT_TRUE(entry.mask->waiting); + EXPECT_TRUE(entry.mask->active); + EXPECT_EQ(entry.info.installing_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_EQ(entry.info.waiting_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + EXPECT_NE(entry.info.active_version.version_id, + blink::mojom::kInvalidServiceWorkerVersionId); + } + + // expected version state transitions: + // new.installing, new.installed, + // old.redundant, + // new.activating, new.activated + ASSERT_EQ(5u, update_helper_->state_change_log_.size()); + + EXPECT_EQ(registration->active_version()->version_id(), + update_helper_->state_change_log_[0].version_id); + EXPECT_EQ(ServiceWorkerVersion::INSTALLING, + update_helper_->state_change_log_[0].status); + + EXPECT_EQ(registration->active_version()->version_id(), + update_helper_->state_change_log_[1].version_id); + EXPECT_EQ(ServiceWorkerVersion::INSTALLED, + update_helper_->state_change_log_[1].status); + + EXPECT_EQ(first_version->version_id(), + update_helper_->state_change_log_[2].version_id); + EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, + update_helper_->state_change_log_[2].status); + + EXPECT_EQ(registration->active_version()->version_id(), + update_helper_->state_change_log_[3].version_id); + EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, + update_helper_->state_change_log_[3].status); + + EXPECT_EQ(registration->active_version()->version_id(), + update_helper_->state_change_log_[4].version_id); + EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, + update_helper_->state_change_log_[4].status); + + EXPECT_TRUE(update_helper_->update_found_); +} + +// Test that the update job uses the script URL of the newest worker when the +// job starts, rather than when it is scheduled. +TEST_P(ServiceWorkerUpdateJobTest, Update_ScriptUrlChanged) { + const GURL old_script("https://www.example.com/service_worker.js"); + const GURL new_script("https://www.example.com/new_worker.js"); + + // Create a registration with an active version. + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = GURL("https://www.example.com/one/"); + auto* initial_client = + helper_->AddNewPendingInstanceClient<FakeEmbeddedWorkerInstanceClient>( + helper_.get()); + // Setup the old script response. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + old_script, kHeaders, kBody, /*network_accessed=*/true, net::OK); + } + scoped_refptr<ServiceWorkerRegistration> registration = + RunRegisterJob(old_script, options); + auto runner = base::MakeRefCounted<base::TestSimpleTaskRunner>(); + registration->SetTaskRunnerForTest(runner); + + // Queue an Update. When this runs, it will use the waiting version's script. + job_coordinator()->Update(registration.get(), false); + + // Add a waiting version with a new script. + scoped_refptr<ServiceWorkerVersion> version = new ServiceWorkerVersion( + registration.get(), new_script, blink::mojom::ScriptType::kClassic, + 2L /* dummy version id */, helper_->context()->AsWeakPtr()); + registration->SetWaitingVersion(version); + + if (IsImportedScriptUpdateCheckEnabled()) { + // Setup the new script response. + update_helper_->loader_factory_for_update_checker_->SetResponse( + new_script, kHeaders, kNewBody, /*network_accessed=*/true, net::OK); + + // Make sure the storage has the data of the current waiting version. + const int64_t resource_id = 2; + version->script_cache_map()->NotifyStartedCaching(new_script, resource_id); + WriteStringResponse(update_helper_->storage(), resource_id, kBody); + version->script_cache_map()->NotifyFinishedCaching( + new_script, sizeof(kBody) / sizeof(char), net::OK, std::string()); + } + + // Run the update job. + base::RunLoop().RunUntilIdle(); + + // The worker is activated after RequestTermination() is called from the + // renderer. Until then, the active version stays active. + // Still waiting, but the waiting version isn't |version| since another + // ServiceWorkerVersion is created during the update job and the job wipes + // out the older waiting version. + ServiceWorkerVersion* waiting_version = registration->waiting_version(); + EXPECT_TRUE(registration->active_version()); + EXPECT_TRUE(waiting_version); + EXPECT_NE(version.get(), waiting_version); + + RequestTermination(&initial_client->host()); + TestServiceWorkerObserver observer(helper_->context_wrapper()); + observer.RunUntilActivated(waiting_version, runner); + + // The update job should have created a new version with the new script, + // and promoted it to the active version. + EXPECT_EQ(new_script, registration->active_version()->script_url()); + EXPECT_EQ(nullptr, registration->waiting_version()); + EXPECT_EQ(nullptr, registration->installing_version()); +} + +// Test that update fails if the incumbent worker was evicted +// during the update job (this can happen on disk cache failure). +TEST_P(ServiceWorkerUpdateJobTest, Update_EvictedIncumbent) { + scoped_refptr<ServiceWorkerRegistration> registration = + update_helper_->SetupInitialRegistration(kNewVersionOrigin); + ASSERT_TRUE(registration.get()); + update_helper_->state_change_log_.clear(); + + registration->AddListener(update_helper_); + scoped_refptr<ServiceWorkerVersion> first_version = + registration->active_version(); + auto* instance_client = helper_->AddNewPendingInstanceClient< + DelayedFakeEmbeddedWorkerInstanceClient>(helper_.get()); + + // Start the update job and make it block on the worker starting. + // Evict the incumbent during that time. + // Change script body. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + kNewVersionOrigin.Resolve(kScript), kHeaders, kNewBody, + /*network_accessed=*/true, net::OK); + } + first_version->StartUpdate(); + instance_client->RunUntilStartWorker(); + registration->ForceDelete(); + + // Finish the update job. + instance_client->UnblockStartWorker(); + base::RunLoop().RunUntilIdle(); + + // Verify results. + EXPECT_FALSE(registration->GetNewestVersion()); + EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, first_version->status()); + EXPECT_TRUE(update_helper_->attribute_change_log_.empty()); + EXPECT_FALSE(update_helper_->update_found_); + EXPECT_TRUE(update_helper_->registration_failed_); + EXPECT_TRUE(registration->is_uninstalled()); +} + +TEST_P(ServiceWorkerUpdateJobTest, Update_UninstallingRegistration) { + blink::mojom::ServiceWorkerRegistrationOptions options; + options.scope = GURL("https://www.example.com/one/"); + bool called; + scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob( + GURL("https://www.example.com/service_worker.js"), options); + + // Add a controllee and queue an unregister to force the uninstalling state. + ServiceWorkerProviderHost* host = CreateControllee(); + ServiceWorkerVersion* active_version = registration->active_version(); + active_version->AddControllee(host); + job_coordinator()->Unregister( + GURL("https://www.example.com/one/"), + SaveUnregistration(blink::ServiceWorkerStatusCode::kOk, &called)); + + // Update should abort after it starts and sees uninstalling. + job_coordinator()->Update(registration.get(), false); + + EXPECT_FALSE(called); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(called); + + // Verify the registration was not modified by the Update. + EXPECT_TRUE(registration->is_uninstalling()); + EXPECT_EQ(active_version, registration->active_version()); + EXPECT_EQ(nullptr, registration->waiting_version()); + EXPECT_EQ(nullptr, registration->installing_version()); +} + +TEST_P(ServiceWorkerUpdateJobTest, RegisterMultipleTimesWhileUninstalling) { GURL script1("https://www.example.com/service_worker.js?first"); GURL script2("https://www.example.com/service_worker.js?second"); GURL script3("https://www.example.com/service_worker.js?third"); @@ -1664,53 +1858,6 @@ EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, third_version->status()); } -// A fake service worker for toggling whether a fetch event handler exists. -class FetchHandlerWorker : public FakeServiceWorker { - public: - FetchHandlerWorker(EmbeddedWorkerTestHelper* helper) - : FakeServiceWorker(helper) {} - ~FetchHandlerWorker() override = default; - - void set_has_fetch_handler(bool has_fetch_handler) { - has_fetch_handler_ = has_fetch_handler; - } - - void DispatchInstallEvent( - blink::mojom::ServiceWorker::DispatchInstallEventCallback callback) - override { - std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED, - has_fetch_handler_); - } - - private: - bool has_fetch_handler_ = false; -}; - -TEST_F(ServiceWorkerJobTest, HasFetchHandler) { - GURL script("https://www.example.com/service_worker.js"); - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = GURL("https://www.example.com/"); - scoped_refptr<ServiceWorkerRegistration> registration; - - auto* fetch_handler_worker = - helper_->AddNewPendingServiceWorker<FetchHandlerWorker>(helper_.get()); - fetch_handler_worker->set_has_fetch_handler(true); - RunRegisterJob(script, options); - registration = FindRegistrationForScope(options.scope); - EXPECT_EQ(ServiceWorkerVersion::FetchHandlerExistence::EXISTS, - registration->active_version()->fetch_handler_existence()); - RunUnregisterJob(options.scope); - - auto* no_fetch_handler_worker = - helper_->AddNewPendingServiceWorker<FetchHandlerWorker>(helper_.get()); - no_fetch_handler_worker->set_has_fetch_handler(false); - RunRegisterJob(script, options); - registration = FindRegistrationForScope(options.scope); - EXPECT_EQ(ServiceWorkerVersion::FetchHandlerExistence::DOES_NOT_EXIST, - registration->active_version()->fetch_handler_existence()); - RunUnregisterJob(options.scope); -} - class CheckPauseAfterDownloadEmbeddedWorkerInstanceClient : public FakeEmbeddedWorkerInstanceClient { public: @@ -1737,9 +1884,11 @@ DISALLOW_COPY_AND_ASSIGN(CheckPauseAfterDownloadEmbeddedWorkerInstanceClient); }; -TEST_F(ServiceWorkerJobTest, Update_PauseAfterDownload) { - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); +TEST_P(ServiceWorkerUpdateJobTest, Update_PauseAfterDownload) { + // PauseAfterDownload happens only when + // ServiceWorkerImportedScriptUpdateCheck is disabled. + if (IsImportedScriptUpdateCheckEnabled()) + return; std::vector<CheckPauseAfterDownloadEmbeddedWorkerInstanceClient*> clients; clients.push_back( @@ -1752,12 +1901,12 @@ // The initial version should not pause after download. clients[0]->set_next_pause_after_download(false); scoped_refptr<ServiceWorkerRegistration> registration = - update_helper->SetupInitialRegistration(kNewVersionOrigin); + update_helper_->SetupInitialRegistration(kNewVersionOrigin); ASSERT_EQ(1, clients[0]->num_of_startworker()); // The updated version should pause after download. clients[1]->set_next_pause_after_download(true); - registration->AddListener(update_helper); + registration->AddListener(update_helper_); registration->active_version()->StartUpdate(); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1, clients[1]->num_of_startworker()); @@ -1765,9 +1914,7 @@ // Test that activation doesn't complete if it's triggered by removing a // controllee and starting the worker failed due to shutdown. -TEST_F(ServiceWorkerJobTest, ActivateCancelsOnShutdown) { - UpdateJobTestHelper* update_helper = new UpdateJobTestHelper; - helper_.reset(update_helper); +TEST_P(ServiceWorkerUpdateJobTest, ActivateCancelsOnShutdown) { GURL script("https://www.example.com/service_worker.js"); blink::mojom::ServiceWorkerRegistrationOptions options; options.scope = GURL("https://www.example.com/"); @@ -1787,7 +1934,12 @@ first_version->AddControllee(host); // Update. The new version should be waiting. - registration->AddListener(update_helper); + // Change script body. + if (IsImportedScriptUpdateCheckEnabled()) { + update_helper_->loader_factory_for_update_checker_->SetResponse( + script, kHeaders, kNewBody, /*network_accessed=*/true, net::OK); + } + registration->AddListener(update_helper_); first_version->StartUpdate(); base::RunLoop().RunUntilIdle(); scoped_refptr<ServiceWorkerVersion> new_version = @@ -1819,11 +1971,11 @@ EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, new_version->status()); // Shutdown. - update_helper->context()->wrapper()->Shutdown(); + update_helper_->context()->wrapper()->Shutdown(); auto* embedded_worker_instance_client = - update_helper->AddNewPendingInstanceClient< + update_helper_->AddNewPendingInstanceClient< UpdateJobTestHelper::UpdateJobEmbeddedWorkerInstanceClient>( - update_helper); + update_helper_); embedded_worker_instance_client->set_force_start_worker_failure(true); // Allow the activation to continue. It will fail, and the worker @@ -1833,46 +1985,10 @@ base::RunLoop().RunUntilIdle(); EXPECT_EQ(new_version.get(), registration->active_version()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, new_version->status()); - registration->RemoveListener(update_helper); - // Dispatch Mojo messages for those Mojo interfaces bound on |runner| to avoid - // possible memory leak. + registration->RemoveListener(update_helper_); + // Dispatch Mojo messages for those Mojo interfaces bound on |runner| to + // avoid possible memory leak. runner->RunUntilIdle(); } -// Test that clients are alerted of new registrations if they are -// in-scope, so that Clients.claim() or ServiceWorkerContainer.ready work -// correctly. -TEST_F(ServiceWorkerJobTest, AddRegistrationToMatchingProviderHosts) { - GURL scope("https://www.example.com/scope/"); - GURL in_scope("https://www.example.com/scope/page"); - GURL out_scope("https://www.example.com/page"); - - // Make an in-scope client. - ServiceWorkerProviderHost* client = CreateControllee(); - client->UpdateUrls(in_scope, in_scope); - - // Make an in-scope reserved client. - auto provider_info = blink::mojom::ServiceWorkerProviderInfoForWindow::New(); - base::WeakPtr<ServiceWorkerProviderHost> reserved_client = - ServiceWorkerProviderHost::PreCreateNavigationHost( - helper_->context()->AsWeakPtr(), true /* are_ancestors_secure */, - FrameTreeNode::kFrameTreeNodeInvalidId, &provider_info); - reserved_client->UpdateUrls(in_scope, in_scope); - - // Make an out-scope client. - ServiceWorkerProviderHost* out_scope_client = CreateControllee(); - out_scope_client->UpdateUrls(out_scope, out_scope); - - // Make a new registration. - GURL script("https://www.example.com/service_worker.js"); - blink::mojom::ServiceWorkerRegistrationOptions options; - options.scope = scope; - scoped_refptr<ServiceWorkerRegistration> registration = - RunRegisterJob(script, options); - - EXPECT_EQ(registration.get(), client->MatchRegistration()); - EXPECT_EQ(registration.get(), reserved_client->MatchRegistration()); - EXPECT_NE(registration.get(), out_scope_client->MatchRegistration()); -} - } // namespace content
diff --git a/content/browser/service_worker/service_worker_provider_host.h b/content/browser/service_worker/service_worker_provider_host.h index 42c7124..34c711d 100644 --- a/content/browser/service_worker/service_worker_provider_host.h +++ b/content/browser/service_worker/service_worker_provider_host.h
@@ -451,7 +451,7 @@ FRIEND_TEST_ALL_PREFIXES(ServiceWorkerProviderHostTest, ContextSecurity); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerJobTest, Unregister); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerJobTest, RegisterDuplicateScript); - FRIEND_TEST_ALL_PREFIXES(ServiceWorkerJobTest, + FRIEND_TEST_ALL_PREFIXES(ServiceWorkerUpdateJobTest, RegisterWithDifferentUpdateViaCache); FRIEND_TEST_ALL_PREFIXES(BackgroundSyncManagerTest, RegisterWithoutLiveSWRegistration);
diff --git a/content/browser/service_worker/service_worker_register_job.h b/content/browser/service_worker/service_worker_register_job.h index 0c50060c..4eda2cfe 100644 --- a/content/browser/service_worker/service_worker_register_job.h +++ b/content/browser/service_worker/service_worker_register_job.h
@@ -42,6 +42,11 @@ ServiceWorkerRegistration* registration)> RegistrationCallback; + enum class UpdateCheckType { + kMainScriptDuringStartWorker, // Only check main script. + kAllScriptsBeforeStartWorker, // Check all scripts. + }; + // For registration jobs. CONTENT_EXPORT ServiceWorkerRegisterJob( base::WeakPtr<ServiceWorkerContextCore> context, @@ -80,11 +85,6 @@ ABORT, }; - enum class UpdateCheckType { - kMainScriptDuringStartWorker, // Only check main script. - kAllScriptsBeforeStartWorker, // Check all scripts. - }; - // Holds internal state of ServiceWorkerRegistrationJob, to compel use of the // getter/setter functions. struct Internal {
diff --git a/content/browser/service_worker/service_worker_registration_unittest.cc b/content/browser/service_worker/service_worker_registration_unittest.cc index 0ae1d42..260c90b 100644 --- a/content/browser/service_worker/service_worker_registration_unittest.cc +++ b/content/browser/service_worker/service_worker_registration_unittest.cc
@@ -15,6 +15,7 @@ #include "base/logging.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -27,6 +28,7 @@ #include "content/browser/service_worker/service_worker_context_core_observer.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_provider_host.h" +#include "content/browser/service_worker/service_worker_register_job.h" #include "content/browser/service_worker/service_worker_registration_object_host.h" #include "content/browser/service_worker/service_worker_test_utils.h" #include "content/browser/service_worker/test_service_worker_observer.h" @@ -35,6 +37,7 @@ #include "content/test/test_content_browser_client.h" #include "mojo/core/embedder/embedder.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" #include "url/gurl.h" @@ -951,6 +954,31 @@ std::vector<std::string> bad_messages_; }; +class ServiceWorkerRegistrationObjectHostUpdateTest + : public ServiceWorkerRegistrationObjectHostTest, + public testing::WithParamInterface<bool> { + protected: + void SetUp() override { + if (IsImportedScriptUpdateCheckEnabled()) { + feature_list_.InitAndEnableFeature( + blink::features::kServiceWorkerImportedScriptUpdateCheck); + } else { + feature_list_.InitAndDisableFeature( + blink::features::kServiceWorkerImportedScriptUpdateCheck); + } + ServiceWorkerRegistrationObjectHostTest::SetUp(); + } + + static bool IsImportedScriptUpdateCheckEnabled() { return GetParam(); } + + private: + base::test::ScopedFeatureList feature_list_; +}; + +INSTANTIATE_TEST_SUITE_P(ServiceWorkerRegistrationObjectHostUpdateTestP, + ServiceWorkerRegistrationObjectHostUpdateTest, + testing::Bool()); + TEST_F(ServiceWorkerRegistrationObjectHostTest, BreakConnection_Destroy) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); @@ -969,7 +997,7 @@ EXPECT_EQ(nullptr, context()->GetLiveRegistration(registration_id)); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, Update_Success) { +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, Update_Success) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); @@ -990,7 +1018,8 @@ CallUpdate(registration_host_ptr.get())); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, Update_CrossOriginShouldFail) { +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, + Update_CrossOriginShouldFail) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); @@ -1010,7 +1039,7 @@ EXPECT_EQ(1u, bad_messages_.size()); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, Update_ContentSettingsDisallowsServiceWorker) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); @@ -1031,7 +1060,8 @@ SetBrowserClientForTesting(old_browser_client); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, Update_NoDelayFromControllee) { +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, + Update_NoDelayFromControllee) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); @@ -1060,7 +1090,7 @@ EXPECT_EQ(base::TimeDelta(), registration->self_update_delay()); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, Update_DelayFromWorkerWithoutControllee) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); @@ -1091,7 +1121,7 @@ EXPECT_LE(base::TimeDelta::FromMinutes(5), registration->self_update_delay()); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, Update_NoDelayFromWorkerWithControllee) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); @@ -1332,7 +1362,7 @@ mock_registration_object->update_via_cache()); } -TEST_F(ServiceWorkerRegistrationObjectHostTest, UpdateFound) { +TEST_P(ServiceWorkerRegistrationObjectHostUpdateTest, UpdateFound) { const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl);
diff --git a/content/public/test/no_renderer_crashes_assertion.cc b/content/public/test/no_renderer_crashes_assertion.cc index 1e24725b..1aa143f3 100644 --- a/content/public/test/no_renderer_crashes_assertion.cc +++ b/content/public/test/no_renderer_crashes_assertion.cc
@@ -36,6 +36,7 @@ ChildProcessTerminationInfo* process_info = content::Details<content::ChildProcessTerminationInfo>(details).ptr(); switch (process_info->status) { + case base::TERMINATION_STATUS_LAUNCH_FAILED: case base::TERMINATION_STATUS_NORMAL_TERMINATION: case base::TERMINATION_STATUS_STILL_RUNNING: return; // Not a crash.
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index f691411..03ba42c 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -315,14 +315,6 @@ "media/webrtc/webrtc_video_utils.h", "media/webrtc_logging.cc", "media/webrtc_logging.h", - "media_recorder/media_recorder_handler.cc", - "media_recorder/media_recorder_handler.h", - "media_recorder/vea_encoder.cc", - "media_recorder/vea_encoder.h", - "media_recorder/video_track_recorder.cc", - "media_recorder/video_track_recorder.h", - "media_recorder/vpx_encoder.cc", - "media_recorder/vpx_encoder.h", "menu_item_builder.cc", "menu_item_builder.h", "mhtml_handle_writer.cc", @@ -565,7 +557,6 @@ "//third_party/blink/public/common", "//third_party/boringssl", "//third_party/icu", - "//third_party/libvpx", "//third_party/libyuv", "//third_party/sqlite", "//third_party/webrtc/api:callfactory_api", @@ -713,14 +704,6 @@ ] } - if (rtc_use_h264) { - sources += [ - "media_recorder/h264_encoder.cc", - "media_recorder/h264_encoder.h", - ] - deps += [ "//third_party/openh264:encoder" ] - } - if (enable_plugins) { sources += [ "pepper/audio_helper.cc",
diff --git a/content/renderer/media_recorder/DEPS b/content/renderer/media_recorder/DEPS deleted file mode 100644 index 6a5e82e..0000000 --- a/content/renderer/media_recorder/DEPS +++ /dev/null
@@ -1,5 +0,0 @@ -include_rules = [ - "+third_party/libvpx", - "+third_party/libyuv", - '+third_party/openh264/src/codec/api/svc', -]
diff --git a/content/renderer/media_recorder/OWNERS b/content/renderer/media_recorder/OWNERS deleted file mode 100644 index 9c893fc..0000000 --- a/content/renderer/media_recorder/OWNERS +++ /dev/null
@@ -1,7 +0,0 @@ -guidou@chromium.org - -# Original (legacy) owner. -emircan@chromium.org -mcasas@chromium.org - -# COMPONENT: Blink>MediaRecording
diff --git a/content/renderer/media_recorder/media_recorder_handler.h b/content/renderer/media_recorder/media_recorder_handler.h deleted file mode 100644 index c3428abe..0000000 --- a/content/renderer/media_recorder/media_recorder_handler.h +++ /dev/null
@@ -1,135 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_MEDIA_RECORDER_MEDIA_RECORDER_HANDLER_H_ -#define CONTENT_RENDERER_MEDIA_RECORDER_MEDIA_RECORDER_HANDLER_H_ - -#include <memory> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_piece.h" -#include "base/threading/thread_checker.h" -#include "content/common/content_export.h" -#include "content/renderer/media_recorder/video_track_recorder.h" -#include "third_party/blink/public/platform/web_media_recorder_handler.h" -#include "third_party/blink/public/platform/web_media_stream.h" -#include "third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h" - -namespace blink { -class WebMediaRecorderHandlerClient; -class WebString; -} // namespace blink - -namespace media { -class AudioBus; -class AudioParameters; -class VideoFrame; -class WebmMuxer; -} // namespace media - -namespace content { - -// MediaRecorderHandler orchestrates the creation, lifetime management and -// mapping between: -// - MediaStreamTrack(s) providing data, -// - {Audio,Video}TrackRecorders encoding that data, -// - a WebmMuxer class multiplexing encoded data into a WebM container, and -// - a single recorder client receiving this contained data. -// All methods are called on the same thread as construction and destruction, -// i.e. the Main Render thread. (Note that a BindToCurrentLoop is used to -// guarantee this, since VideoTrackRecorder sends back frames on IO thread.) -class CONTENT_EXPORT MediaRecorderHandler final - : public blink::WebMediaRecorderHandler { - public: - explicit MediaRecorderHandler( - scoped_refptr<base::SingleThreadTaskRunner> task_runner); - ~MediaRecorderHandler() override; - - // blink::WebMediaRecorderHandler. - bool CanSupportMimeType(const blink::WebString& web_type, - const blink::WebString& web_codecs) override; - bool Initialize(blink::WebMediaRecorderHandlerClient* client, - const blink::WebMediaStream& media_stream, - const blink::WebString& type, - const blink::WebString& codecs, - int32_t audio_bits_per_second, - int32_t video_bits_per_second) override; - bool Start(int timeslice) override; - void Stop() override; - void Pause() override; - void Resume() override; - void EncodingInfo(const blink::WebMediaConfiguration& configuration, - OnMediaCapabilitiesEncodingInfoCallback cb) override; - blink::WebString ActualMimeType() override; - - private: - friend class MediaRecorderHandlerTest; - - // Called to indicate there is encoded video data available. |encoded_alpha| - // represents the encode output of alpha channel when available, can be - // nullptr otherwise. - void OnEncodedVideo(const media::WebmMuxer::VideoParameters& params, - std::unique_ptr<std::string> encoded_data, - std::unique_ptr<std::string> encoded_alpha, - base::TimeTicks timestamp, - bool is_key_frame); - void OnEncodedAudio(const media::AudioParameters& params, - std::unique_ptr<std::string> encoded_data, - base::TimeTicks timestamp); - void WriteData(base::StringPiece data); - - // Updates |video_tracks_|,|audio_tracks_| and returns true if any changed. - bool UpdateTracksAndCheckIfChanged(); - - void OnVideoFrameForTesting(scoped_refptr<media::VideoFrame> frame, - const base::TimeTicks& timestamp); - void OnAudioBusForTesting(const media::AudioBus& audio_bus, - const base::TimeTicks& timestamp); - void SetAudioFormatForTesting(const media::AudioParameters& params); - - // Bound to the main render thread. - base::ThreadChecker main_render_thread_checker_; - - // Sanitized video and audio bitrate settings passed on initialize(). - int32_t video_bits_per_second_; - int32_t audio_bits_per_second_; - - // Video Codec, VP8 is used by default. - VideoTrackRecorder::CodecId video_codec_id_; - - // Audio Codec, OPUS is used by default. - blink::AudioTrackRecorder::CodecId audio_codec_id_; - - // |client_| has no notion of time, thus may configure us via start(timeslice) - // to notify it after a certain |timeslice_| has passed. We use a moving - // |slice_origin_timestamp_| to track those time chunks. - base::TimeDelta timeslice_; - base::TimeTicks slice_origin_timestamp_; - - bool recording_; - blink::WebMediaStream media_stream_; // The MediaStream being recorded. - blink::WebVector<blink::WebMediaStreamTrack> video_tracks_; - blink::WebVector<blink::WebMediaStreamTrack> audio_tracks_; - - // |client_| is a weak pointer, and is valid for the lifetime of this object. - blink::WebMediaRecorderHandlerClient* client_; - - std::vector<std::unique_ptr<VideoTrackRecorder>> video_recorders_; - std::vector<std::unique_ptr<blink::AudioTrackRecorder>> audio_recorders_; - - // Worker class doing the actual Webm Muxing work. - std::unique_ptr<media::WebmMuxer> webm_muxer_; - - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - - base::WeakPtrFactory<MediaRecorderHandler> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandler); -}; - -} // namespace content -#endif // CONTENT_RENDERER_MEDIA_RECORDER_MEDIA_RECORDER_HANDLER_H_
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index bcd0c3e..91a1929 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -49,7 +49,6 @@ #include "content/renderer/media/audio_decoder.h" #include "content/renderer/media/renderer_webaudiodevice_impl.h" #include "content/renderer/media/webrtc/transmission_encoding_info_handler.h" -#include "content/renderer/media_recorder/media_recorder_handler.h" #include "content/renderer/mojo/blink_interface_provider_impl.h" #include "content/renderer/p2p/port_allocator.h" #include "content/renderer/render_thread_impl.h" @@ -65,6 +64,7 @@ #include "media/audio/audio_output_device.h" #include "media/blink/webcontentdecryptionmodule_impl.h" #include "media/filters/stream_parser_factory.h" +#include "media/video/gpu_video_accelerator_factories.h" #include "mojo/public/cpp/base/big_buffer.h" #include "mojo/public/cpp/bindings/strong_associated_binding.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -86,7 +86,6 @@ #include "third_party/blink/public/platform/url_conversion.h" #include "third_party/blink/public/platform/web_audio_latency_hint.h" #include "third_party/blink/public/platform/web_blob_registry.h" -#include "third_party/blink/public/platform/web_media_recorder_handler.h" #include "third_party/blink/public/platform/web_media_stream_center.h" #include "third_party/blink/public/platform/web_rtc_certificate_generator.h" #include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h" @@ -119,7 +118,6 @@ using blink::WebAudioLatencyHint; using blink::WebBlobRegistry; using blink::WebDatabaseObserver; -using blink::WebMediaRecorderHandler; using blink::WebMediaStreamCenter; using blink::WebMediaStreamTrack; using blink::WebRTCPeerConnectionHandler; @@ -593,15 +591,6 @@ //------------------------------------------------------------------------------ -std::unique_ptr<WebMediaRecorderHandler> -RendererBlinkPlatformImpl::CreateMediaRecorderHandler( - scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - return std::make_unique<content::MediaRecorderHandler>( - std::move(task_runner)); -} - -//------------------------------------------------------------------------------ - std::unique_ptr<WebRTCPeerConnectionHandler> RendererBlinkPlatformImpl::CreateRTCPeerConnectionHandler( WebRTCPeerConnectionHandlerClient* client, @@ -971,6 +960,16 @@ } //------------------------------------------------------------------------------ +media::GpuVideoAcceleratorFactories* +RendererBlinkPlatformImpl::GetGpuFactories() { + auto* render_thread = RenderThreadImpl::current(); + if (!render_thread) + return nullptr; + + return render_thread->GetGpuFactories(); +} + +//------------------------------------------------------------------------------ void RendererBlinkPlatformImpl::InitializeWebDatabaseHostIfNeeded() { if (!web_database_host_) {
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index a7cc63d..8649e75 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -40,10 +40,13 @@ class WebThreadScheduler; } class WebGraphicsContext3DProvider; -class WebMediaRecorderHandler; class WebSecurityOrigin; } // namespace blink +namespace media { +class GpuVideoAcceleratorFactories; +} + namespace network { class SharedURLLoaderFactory; } @@ -141,8 +144,6 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner) override; std::unique_ptr<blink::WebRTCCertificateGenerator> CreateRTCCertificateGenerator() override; - std::unique_ptr<blink::WebMediaRecorderHandler> CreateMediaRecorderHandler( - scoped_refptr<base::SingleThreadTaskRunner> task_runner) override; std::unique_ptr<blink::WebMediaStreamCenter> CreateMediaStreamCenter() override; scoped_refptr<base::SingleThreadTaskRunner> GetWebRtcWorkerThread() override; @@ -215,6 +216,8 @@ std::unique_ptr<blink::WebURLLoaderFactory> WrapSharedURLLoaderFactory( scoped_refptr<network::SharedURLLoaderFactory> factory) override; + media::GpuVideoAcceleratorFactories* GetGpuFactories() override; + // Returns non-null. // It is invalid to call this in an incomplete env where // RenderThreadImpl::current() returns nullptr (e.g. in some tests).
diff --git a/content/renderer/webgraphicscontext3d_provider_impl.cc b/content/renderer/webgraphicscontext3d_provider_impl.cc index 2817c4c9..d0e38db 100644 --- a/content/renderer/webgraphicscontext3d_provider_impl.cc +++ b/content/renderer/webgraphicscontext3d_provider_impl.cc
@@ -13,6 +13,7 @@ #include "content/public/common/content_switches.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/config/gpu_feature_info.h" +#include "media/renderers/paint_canvas_video_renderer.h" #include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" #include "third_party/skia/include/gpu/GrContext.h" @@ -175,4 +176,11 @@ return provider_->SharedImageInterface(); } +void WebGraphicsContext3DProviderImpl::CopyVideoFrame( + media::PaintCanvasVideoRenderer* video_renderer, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) { + video_renderer->Copy(video_frame, canvas, context_provider()); +} + } // namespace content
diff --git a/content/renderer/webgraphicscontext3d_provider_impl.h b/content/renderer/webgraphicscontext3d_provider_impl.h index 1907def..6068fbb8 100644 --- a/content/renderer/webgraphicscontext3d_provider_impl.h +++ b/content/renderer/webgraphicscontext3d_provider_impl.h
@@ -51,6 +51,9 @@ base::RepeatingCallback<void(const char*, int32_t)>) override; cc::ImageDecodeCache* ImageDecodeCache(SkColorType color_type) override; gpu::SharedImageInterface* SharedImageInterface() override; + void CopyVideoFrame(media::PaintCanvasVideoRenderer* video_render, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) override; viz::ContextProviderCommandBuffer* context_provider() const { return provider_.get();
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 6e07a7e3..aee1790 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1883,8 +1883,6 @@ "../renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc", "../renderer/media/webrtc/webrtc_set_description_observer_unittest.cc", "../renderer/media/webrtc/webrtc_video_track_source_unittest.cc", - "../renderer/media_recorder/media_recorder_handler_unittest.cc", - "../renderer/media_recorder/video_track_recorder_unittest.cc", "../renderer/p2p/filtering_network_manager_unittest.cc", "../renderer/p2p/ipc_network_manager_unittest.cc", "../renderer/peripheral_content_heuristic_unittest.cc", @@ -2122,10 +2120,6 @@ } if (is_chromecast) { - sources -= [ - "../renderer/media_recorder/media_recorder_handler_unittest.cc", - "../renderer/media_recorder/video_track_recorder_unittest.cc", - ] defines += [ "IS_CHROMECAST" ] } @@ -2234,7 +2228,6 @@ "../browser/speech/speech_recognition_engine_unittest.cc", "../browser/speech/speech_recognizer_impl_unittest.cc", ] - deps += [ "//third_party/libvpx" ] } # HID support is not available without udev.
diff --git a/extensions/shell/browser/shell_desktop_controller_aura.cc b/extensions/shell/browser/shell_desktop_controller_aura.cc index 8fa05d0..a22f9da 100644 --- a/extensions/shell/browser/shell_desktop_controller_aura.cc +++ b/extensions/shell/browser/shell_desktop_controller_aura.cc
@@ -229,13 +229,12 @@ #endif ui::EventDispatchDetails ShellDesktopControllerAura::DispatchKeyEventPostIME( - ui::KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) { + ui::KeyEvent* key_event) { if (key_event->target()) { aura::WindowTreeHost* host = static_cast<aura::Window*>(key_event->target()) ->GetRootWindow() ->GetHost(); - return host->DispatchKeyEventPostIME(key_event, std::move(callback)); + return host->DispatchKeyEventPostIME(key_event); } // Send the key event to the focused window. @@ -243,11 +242,10 @@ const_cast<aura::Window*>(focus_controller_->GetActiveWindow()); if (active_window) { return active_window->GetRootWindow()->GetHost()->DispatchKeyEventPostIME( - key_event, std::move(callback)); + key_event); } - return GetPrimaryHost()->DispatchKeyEventPostIME(key_event, - std::move(callback)); + return GetPrimaryHost()->DispatchKeyEventPostIME(key_event); } void ShellDesktopControllerAura::OnKeepAliveStateChanged(
diff --git a/extensions/shell/browser/shell_desktop_controller_aura.h b/extensions/shell/browser/shell_desktop_controller_aura.h index 35ca079..a01b84e 100644 --- a/extensions/shell/browser/shell_desktop_controller_aura.h +++ b/extensions/shell/browser/shell_desktop_controller_aura.h
@@ -97,8 +97,7 @@ // ui::internal::InputMethodDelegate: ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) override; + ui::KeyEvent* key_event) override; // KeepAliveStateObserver: void OnKeepAliveStateChanged(bool is_keeping_alive) override;
diff --git a/gpu/vulkan/vulkan_instance.cc b/gpu/vulkan/vulkan_instance.cc index be186b4..5eef2bf 100644 --- a/gpu/vulkan/vulkan_instance.cc +++ b/gpu/vulkan/vulkan_instance.cc
@@ -148,19 +148,26 @@ // TODO(crbug.com/843346): Make validation work in combination with // VK_KHR_xlib_surface or switch to VK_KHR_xcb_surface. - const base::StringPiece xlib_surface_extension_name("VK_KHR_xlib_surface"); - bool enable_validation = + constexpr base::StringPiece xlib_surface_extension_name( + "VK_KHR_xlib_surface"); + bool require_xlib_surface_extension = std::find_if(enabled_extensions.begin(), enabled_extensions.end(), [xlib_surface_extension_name](const char* e) { return xlib_surface_extension_name == e; - }) == enabled_extensions.end(); - if (enable_validation) { - constexpr base::StringPiece standard_validation( - "VK_LAYER_LUNARG_standard_validation"); - for (const VkLayerProperties& layer_property : instance_layers) { - if (standard_validation == layer_property.layerName) - enabled_layer_names.push_back(standard_validation.data()); + }) != enabled_extensions.end(); + + // VK_LAYER_LUNARG_standard_validation 1.1.106 is required to support + // VK_KHR_xlib_surface. + constexpr base::StringPiece standard_validation( + "VK_LAYER_LUNARG_standard_validation"); + for (const VkLayerProperties& layer_property : instance_layers) { + if (standard_validation != layer_property.layerName) + continue; + if (!require_xlib_surface_extension || + layer_property.specVersion >= VK_MAKE_VERSION(1, 1, 106)) { + enabled_layer_names.push_back(standard_validation.data()); } + break; } #endif // DCHECK_IS_ON()
diff --git a/ios/chrome/browser/tabs/BUILD.gn b/ios/chrome/browser/tabs/BUILD.gn index d7d3462..616fc8d5 100644 --- a/ios/chrome/browser/tabs/BUILD.gn +++ b/ios/chrome/browser/tabs/BUILD.gn
@@ -58,6 +58,7 @@ "//components/history/ios/browser", "//components/language/ios/browser", "//components/navigation_metrics", + "//components/profile_metrics", "//components/sessions", "//components/strings", "//ios/chrome/app/strings",
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index 0229757..e308857 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -20,6 +20,7 @@ #include "base/task/post_task.h" #include "components/favicon/ios/web_favicon_driver.h" #include "components/navigation_metrics/navigation_metrics.h" +#include "components/profile_metrics/browser_profile_type.h" #include "components/sessions/core/serialized_navigation_entry.h" #include "components/sessions/core/session_id.h" #include "components/sessions/core/tab_restore_service.h" @@ -207,9 +208,15 @@ DCHECK(web_state->GetNavigationManager()); web::NavigationItem* item = web_state->GetNavigationManager()->GetLastCommittedItem(); + // TODO(crbug.com/966747): Add a function in browser_state_metrics.h to return + // profile type. + profile_metrics::BrowserProfileType profile_type = + web_state->GetBrowserState()->IsOffTheRecord() + ? profile_metrics::BrowserProfileType::kIncognito + : profile_metrics::BrowserProfileType::kRegular; navigation_metrics::RecordMainFrameNavigation( item ? item->GetVirtualURL() : GURL::EmptyGURL(), true, - web_state->GetBrowserState()->IsOffTheRecord()); + web_state->GetBrowserState()->IsOffTheRecord(), profile_type); } } // anonymous namespace
diff --git a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm index 03ba09f..d73328a 100644 --- a/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator_unittest.mm
@@ -87,7 +87,7 @@ MOCK_CONST_METHOD1( GetSyncedFaviconForPageURL, - scoped_refptr<base::RefCountedMemory>(const std::string& page_url)); + favicon_base::FaviconRawBitmapResult(const GURL& page_url)); MOCK_METHOD1( GetAllForeignSessions, bool(std::vector<const sync_sessions::SyncedSession*>* sessions));
diff --git a/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm b/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm index 43741c4..15b3f1a 100644 --- a/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.mm
@@ -96,7 +96,7 @@ // Whether the view controller is currently being dismissed and new dismiss // requests should be ignored. BOOL _isBeingDismissed; - __weak UIViewController* _settingsDetails; + ios::DismissASMViewControllerBlock _dimissAccountDetailsViewControllerBlock; ResizedAvatarCache* _avatarCache; std::unique_ptr<ChromeIdentityServiceObserverBridge> _identityServiceObserver; @@ -431,9 +431,10 @@ - (void)onEndBatchOfRefreshTokenStateChanges { [self reloadData]; [self popViewIfSignedOut]; - if (![self authService] -> IsAuthenticated() && _settingsDetails) { - [_settingsDetails dismissViewControllerAnimated:YES completion:nil]; - _settingsDetails = nil; + if (![self authService] -> IsAuthenticated() && + _dimissAccountDetailsViewControllerBlock) { + _dimissAccountDetailsViewControllerBlock(/*animated=*/YES); + _dimissAccountDetailsViewControllerBlock = nil; } } @@ -506,19 +507,10 @@ - (void)showAccountDetails:(ChromeIdentity*)identity { if ([_alertCoordinator isVisible]) return; - UIViewController* accountDetails = + _dimissAccountDetailsViewControllerBlock = ios::GetChromeBrowserProvider() ->GetChromeIdentityService() - ->CreateAccountDetailsController(identity, self); - if (!accountDetails) { - // Failed to create a new account details. Ignored. - return; - } - [self presentViewController:accountDetails animated:YES completion:nil]; - - // Keep a weak reference on the account details, to be able to dismiss it - // when the primary account is removed. - _settingsDetails = accountDetails; + ->PresentAccountDetailsController(identity, self, /*animated=*/YES); } - (void)showDisconnect {
diff --git a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm index 0188f8d..73a0c4190 100644 --- a/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm +++ b/ios/chrome/browser/ui/settings/google_services/manage_sync_settings_coordinator.mm
@@ -52,7 +52,7 @@ // Sync service. @property(nonatomic, assign, readonly) syncer::SyncService* syncService; // Dismiss callback for Web and app setting details view. -@property(nonatomic, copy) ios::DismissWebAndAppSettingDetailsControllerBlock +@property(nonatomic, copy) ios::DismissASMViewControllerBlock dismissWebAndAppSettingDetailsControllerBlock; @end
diff --git a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm index 0206ce8f..b7a521e 100644 --- a/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm +++ b/ios/chrome/browser/ui/signin_interaction/signin_interaction_controller_egtest.mm
@@ -128,7 +128,7 @@ // Tests that signing out of a managed account from the Settings works // correctly. -// TODO(crbug.com): Re-enable the test. +// TODO(crbug.com/929967): Re-enable the test. - (void)DISABLED_testSignInDisconnectFromChromeManaged { ChromeIdentity* identity = [SigninEarlGreyUtils fakeManagedIdentity]; ios::FakeChromeIdentityService::GetInstanceFromChromeProvider()->AddIdentity(
diff --git a/ios/public/provider/chrome/browser/signin/chrome_identity_service.h b/ios/public/provider/chrome/browser/signin/chrome_identity_service.h index cde7579..ef42f010 100644 --- a/ios/public/provider/chrome/browser/signin/chrome_identity_service.h +++ b/ios/public/provider/chrome/browser/signin/chrome_identity_service.h
@@ -53,16 +53,8 @@ // the device is blocked. typedef void (^MDMStatusCallback)(bool is_blocked); -// Callback to dismiss Web and App settings details view. No-op, if this block -// is more than once. -// |animated| the view will be dismissed with animation if the value is YES. -// This type is obsolete and should be replaced by -// DismissASMViewControllerBlock. -typedef void (^DismissWebAndAppSettingDetailsControllerBlock)(BOOL animated); - // Callback to dismiss ASM view. No-op, if this block is more than once. // |animated| the view will be dismissed with animation if the value is YES. -// Replaces DismissWebAndAppSettingDetailsControllerBlock type. typedef void (^DismissASMViewControllerBlock)(BOOL animated); // Opaque type representing the MDM (Mobile Device Management) status of the @@ -112,14 +104,18 @@ // Dismisses all the dialogs created by the abstracted flows. virtual void DismissDialogs(); - // Returns a new account details controller to present. A cancel button is - // present as leading navigation item. + // Deprecated. Please use PresentAccountDetailsController(). + // See: crbug.com/858845. virtual UINavigationController* CreateAccountDetailsController( ChromeIdentity* identity, id<ChromeIdentityBrowserOpener> browser_opener); - // Not implemented yet. Please use CreateAccountDetailsController(). - // See: crbug.com/858845. + // Presents a new Account Details view. + // |identity| the identity used to present the view. + // |view_controller| the view to present the details view. + // |animated| the view is presented with animation if YES. + // Returns a block to dismiss the presented view. This block can be ignored if + // not needed. virtual ios::DismissASMViewControllerBlock PresentAccountDetailsController( ChromeIdentity* identity, UIViewController* view_controller,
diff --git a/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.h b/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.h index c55a7f5..916a4e9 100644 --- a/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.h +++ b/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.h
@@ -27,6 +27,10 @@ UINavigationController* CreateAccountDetailsController( ChromeIdentity* identity, id<ChromeIdentityBrowserOpener> browser_opener) override; + DismissASMViewControllerBlock PresentAccountDetailsController( + ChromeIdentity* identity, + UIViewController* viewController, + BOOL animated) override; ChromeIdentityInteractionManager* CreateChromeIdentityInteractionManager( ios::ChromeBrowserState* browser_state, id<ChromeIdentityInteractionManagerDelegate> delegate) const override;
diff --git a/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.mm b/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.mm index 42be995c..cc7cffd 100644 --- a/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.mm +++ b/ios/public/provider/chrome/browser/signin/fake_chrome_identity_service.mm
@@ -124,6 +124,22 @@ return navigationController; } +DismissASMViewControllerBlock +FakeChromeIdentityService::PresentAccountDetailsController( + ChromeIdentity* identity, + UIViewController* viewController, + BOOL animated) { + UIViewController* accountDetailsViewController = + [[FakeAccountDetailsViewController alloc] initWithIdentity:identity]; + [viewController presentViewController:accountDetailsViewController + animated:animated + completion:nil]; + return ^(BOOL animated) { + [accountDetailsViewController dismissViewControllerAnimated:animated + completion:nil]; + }; +} + ChromeIdentityInteractionManager* FakeChromeIdentityService::CreateChromeIdentityInteractionManager( ios::ChromeBrowserState* browser_state,
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 71d50ab..833318a 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -675,7 +675,6 @@ sources = [ "web_state/js/resources/error.js", - "web_state/js/resources/legacy.js", "web_state/js/resources/main_frame_context_menu.js", "web_state/js/resources/main_frame_web_bundle.js", "web_state/js/resources/navigation.js", @@ -708,6 +707,16 @@ ] } +js_compile_bundle("main_frame_document_end_web_bundle") { + visibility = [ ":js_resources" ] + closure_entry_point = "__crWeb.mainFrameDocumentEndWebBundle" + + sources = [ + "favicon/resources/favicon.js", + "web_state/js/resources/main_frame_document_end_web_bundle.js", + ] +} + js_compile_bundle("nav_bundle") { visibility = [ ":js_resources" ] closure_entry_point = "__crWeb.legacynavigation" @@ -721,6 +730,7 @@ public_deps = [ ":all_frames_document_end_web_bundle", ":all_frames_web_bundle", + ":main_frame_document_end_web_bundle", ":main_frame_web_bundle", ":nav_bundle", ]
diff --git a/ios/web/browsing_data/OWNERS b/ios/web/browsing_data/OWNERS new file mode 100644 index 0000000..40031f29 --- /dev/null +++ b/ios/web/browsing_data/OWNERS
@@ -0,0 +1,6 @@ +eugenebut@chromium.org +gambard@chromium.org + +# TEAM: ios-directory-owners@chromium.org +# OS: iOS +# COMPONENT: Mobile>iOSWeb
diff --git a/ios/web/favicon/OWNERS b/ios/web/favicon/OWNERS new file mode 100644 index 0000000..40031f29 --- /dev/null +++ b/ios/web/favicon/OWNERS
@@ -0,0 +1,6 @@ +eugenebut@chromium.org +gambard@chromium.org + +# TEAM: ios-directory-owners@chromium.org +# OS: iOS +# COMPONENT: Mobile>iOSWeb
diff --git a/ios/web/favicon/resources/favicon.js b/ios/web/favicon/resources/favicon.js new file mode 100644 index 0000000..8ccb890a --- /dev/null +++ b/ios/web/favicon/resources/favicon.js
@@ -0,0 +1,22 @@ +// Copyright 2019 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. + +/** + * @fileoverview Gets and returns favicons in main frame. This script should be + * injected only into main frame when it's loaded. + */ + +goog.provide('__crWeb.favicon'); + +// Requires __crWeb.common and __crWeb.message provided by +// __crWeb.allFramesWebBundle. + +/** Beginning of anonymous object */ +(function() { + +__gCrWeb.message.invokeOnHost({ + 'command': 'document.favicons', + 'favicons': __gCrWeb.common.getFavicons() +}); +}()); // End of anonymous object
diff --git a/ios/web/js_messaging/page_script_util.h b/ios/web/js_messaging/page_script_util.h index 6d986fe..280e81f 100644 --- a/ios/web/js_messaging/page_script_util.h +++ b/ios/web/js_messaging/page_script_util.h
@@ -20,6 +20,10 @@ NSString* GetDocumentStartScriptForMainFrame(BrowserState* browser_state); // Returns an autoreleased string containing the JavaScript to be injected into +// the main frame of the web view at the end of the document load. +NSString* GetDocumentEndScriptForMainFrame(BrowserState* browser_state); + +// Returns an autoreleased string containing the JavaScript to be injected into // all frames of the web view as early as possible. NSString* GetDocumentStartScriptForAllFrames(BrowserState* browser_state);
diff --git a/ios/web/js_messaging/page_script_util.mm b/ios/web/js_messaging/page_script_util.mm index 71f9797..46eda827 100644 --- a/ios/web/js_messaging/page_script_util.mm +++ b/ios/web/js_messaging/page_script_util.mm
@@ -91,6 +91,11 @@ return MakeScriptInjectableOnce(@"start_main_frame", script); } +NSString* GetDocumentEndScriptForMainFrame(BrowserState* browser_state) { + NSString* script = GetPageScript(@"main_frame_document_end_web_bundle"); + return MakeScriptInjectableOnce(@"end_main_frame", script); +} + NSString* GetDocumentStartScriptForAllFrames(BrowserState* browser_state) { DCHECK(GetWebClient()); NSString* embedder_page_script =
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index bbcc665c..59bb2fec5 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -12,7 +12,6 @@ #include "ios/web/common/features.h" #import "ios/web/js_messaging/crw_js_injector.h" #import "ios/web/js_messaging/web_frames_manager_impl.h" -#import "ios/web/js_messaging/web_view_js_utils.h" #import "ios/web/navigation/crw_pending_navigation_info.h" #import "ios/web/navigation/crw_session_controller.h" #import "ios/web/navigation/crw_wk_navigation_states.h" @@ -1112,11 +1111,6 @@ [self.navigationStates setState:web::WKNavigationState::FINISHED forNavigation:navigation]; - // Trigger JavaScript driven post-document-load-completion tasks. - // TODO(crbug.com/546350): Investigate using - // WKUserScriptInjectionTimeAtDocumentEnd to inject this material at the - // appropriate time rather than invoking here. - web::ExecuteJavaScript(webView, @"__gCrWeb.didFinishNavigation()", nil); [self.delegate navigationHandler:self didFinishNavigation:context]; if (web::features::StorePendingItemInContext()) {
diff --git a/ios/web/web_state/js/resources/all_frames_web_bundle.js b/ios/web/web_state/js/resources/all_frames_web_bundle.js index 8048e90..664d807 100644 --- a/ios/web/web_state/js/resources/all_frames_web_bundle.js +++ b/ios/web/web_state/js/resources/all_frames_web_bundle.js
@@ -10,4 +10,3 @@ goog.require('__crWeb.common'); goog.require('__crWeb.findInPage'); goog.require('__crWeb.message'); -
diff --git a/ios/web/web_state/js/resources/legacy.js b/ios/web/web_state/js/resources/legacy.js deleted file mode 100644 index b23cba5d..0000000 --- a/ios/web/web_state/js/resources/legacy.js +++ /dev/null
@@ -1,33 +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. - -/** - * @fileoverview Collection of legacy APIs that should eventually be cleaned up. - */ - -goog.provide('__crWeb.legacy'); - -// Requires __crWeb.common and __crWeb.message provided by -// __crWeb.allFramesWebBundle. - -/** Beginning of anonymouse object */ -(function() { - -/** - * Handles document load completion tasks. Invoked from - * [WKNavigationDelegate webView:didFinishNavigation:], when document load is - * complete. - * TODO(crbug.com/546350): Investigate using - * WKUserScriptInjectionTimeAtDocumentEnd to inject this material at the - * appropriate time so that this API will not be needed. - */ -__gCrWeb.didFinishNavigation = function() { - // Send the favicons to the browser. - __gCrWeb.message.invokeOnHost({ - 'command': 'document.favicons', - 'favicons': __gCrWeb.common.getFavicons() - }); -}; - -}()); // End of anonymouse object
diff --git a/ios/web/web_state/js/resources/main_frame_document_end_web_bundle.js b/ios/web/web_state/js/resources/main_frame_document_end_web_bundle.js new file mode 100644 index 0000000..100a6a2 --- /dev/null +++ b/ios/web/web_state/js/resources/main_frame_document_end_web_bundle.js
@@ -0,0 +1,8 @@ +// Copyright 2019 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. + +// Set of scripts injected into main frame of WKWebView at Document End. +goog.provide('__crWeb.mainFrameDocumentEndWebBundle'); + +goog.require('__crWeb.favicon');
diff --git a/ios/web/web_state/js/resources/main_frame_web_bundle.js b/ios/web/web_state/js/resources/main_frame_web_bundle.js index 142f299..5edf7e7 100644 --- a/ios/web/web_state/js/resources/main_frame_web_bundle.js +++ b/ios/web/web_state/js/resources/main_frame_web_bundle.js
@@ -8,7 +8,6 @@ // Requires __crWeb.form provided by __crWeb.allFramesWebBundle. goog.require('__crWeb.error'); -goog.require('__crWeb.legacy'); goog.require('__crWeb.mainFrameContextMenu'); goog.require('__crWeb.navigation'); goog.require('__crWeb.scrollWorkaround');
diff --git a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm index f2a451f..a9b1a0c 100644 --- a/ios/web/web_state/ui/wk_web_view_configuration_provider.mm +++ b/ios/web/web_state/ui/wk_web_view_configuration_provider.mm
@@ -30,8 +30,8 @@ // A key used to associate a WKWebViewConfigurationProvider with a BrowserState. const char kWKWebViewConfigProviderKeyName[] = "wk_web_view_config_provider"; -// Returns an autoreleased instance of WKUserScript to be added to -// configuration's userContentController. +// Returns a WKUserScript for JavsScript injected into the main frame at the +// beginning of the document load. WKUserScript* InternalGetDocumentStartScriptForMainFrame( BrowserState* browser_state) { return [[WKUserScript alloc] @@ -40,8 +40,18 @@ forMainFrameOnly:YES]; } -// Returns an autoreleased instance of WKUserScript to be added to -// configuration's userContentController. +// Returns a WKUserScript for JavsScript injected into the main frame at the +// end of the document load. +WKUserScript* InternalGetDocumentEndScriptForMainFrame( + BrowserState* browser_state) { + return [[WKUserScript alloc] + initWithSource:GetDocumentEndScriptForMainFrame(browser_state) + injectionTime:WKUserScriptInjectionTimeAtDocumentEnd + forMainFrameOnly:YES]; +} + +// Returns a WKUserScript for JavsScript injected into all frames at the +// beginning of the document load. WKUserScript* InternalGetDocumentStartScriptForAllFrames( BrowserState* browser_state) { return [[WKUserScript alloc] @@ -50,8 +60,8 @@ forMainFrameOnly:NO]; } -// Returns an autoreleased instance of WKUserScript to be added to -// configuration's userContentController. +// Returns a WKUserScript for JavsScript injected into all frames at the +// end of the document load. WKUserScript* InternalGetDocumentEndScriptForAllFrames( BrowserState* browser_state) { return [[WKUserScript alloc] @@ -110,6 +120,8 @@ browser_state_)]; [[configuration_ userContentController] addUserScript:InternalGetDocumentEndScriptForAllFrames(browser_state_)]; + [[configuration_ userContentController] + addUserScript:InternalGetDocumentEndScriptForMainFrame(browser_state_)]; if (!scheme_handler_) { scoped_refptr<network::SharedURLLoaderFactory> shared_loader_factory =
diff --git a/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm b/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm index 66cbead..2c8eddd 100644 --- a/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm +++ b/ios/web/web_state/ui/wk_web_view_configuration_provider_unittest.mm
@@ -141,16 +141,19 @@ TEST_F(WKWebViewConfigurationProviderTest, UserScript) { WKWebViewConfiguration* config = GetProvider().GetWebViewConfiguration(); NSArray* scripts = config.userContentController.userScripts; - ASSERT_EQ(3U, scripts.count); + ASSERT_EQ(4U, scripts.count); EXPECT_FALSE(((WKUserScript*)[scripts objectAtIndex:0]).isForMainFrameOnly); EXPECT_TRUE(((WKUserScript*)[scripts objectAtIndex:1]).isForMainFrameOnly); EXPECT_FALSE(((WKUserScript*)[scripts objectAtIndex:2]).isForMainFrameOnly); + EXPECT_TRUE(((WKUserScript*)[scripts objectAtIndex:3]).isForMainFrameOnly); NSString* early_all_frames_script = GetDocumentStartScriptForAllFrames(&browser_state_); NSString* main_frame_script = GetDocumentStartScriptForMainFrame(&browser_state_); NSString* late_all_frames_script = GetDocumentEndScriptForAllFrames(&browser_state_); + NSString* late_main_frame_script = + GetDocumentEndScriptForMainFrame(&browser_state_); // The scripts in |userScrips| are wrapped with a "if (!injected)" check to // avoid double injections, so a substring check is necessary. EXPECT_LT(0U, @@ -158,6 +161,8 @@ EXPECT_LT(0U, [[scripts[1] source] rangeOfString:main_frame_script].length); EXPECT_LT(0U, [[scripts[2] source] rangeOfString:late_all_frames_script].length); + EXPECT_LT(0U, + [[scripts[3] source] rangeOfString:late_main_frame_script].length); } // Tests that observers methods are correctly triggered when observing the
diff --git a/ios/web/webui/OWNERS b/ios/web/webui/OWNERS new file mode 100644 index 0000000..a01224c --- /dev/null +++ b/ios/web/webui/OWNERS
@@ -0,0 +1,6 @@ +gambard@chromium.org +michaeldo@chromium.org + +# TEAM: ios-directory-owners@chromium.org +# OS: iOS +# COMPONENT: UI>Browser>WebUI
diff --git a/media/audio/fake_audio_input_stream.cc b/media/audio/fake_audio_input_stream.cc index 0c03c65..ea06f93 100644 --- a/media/audio/fake_audio_input_stream.cc +++ b/media/audio/fake_audio_input_stream.cc
@@ -3,15 +3,19 @@ // found in the LICENSE file. #include "media/audio/fake_audio_input_stream.h" +#include <memory> #include "base/atomicops.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/files/file_path.h" +#include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_split.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread.h" #include "base/time/time.h" #include "media/audio/audio_manager_base.h" #include "media/audio/simple_sources.h" @@ -34,7 +38,7 @@ const AudioParameters& params) : audio_manager_(manager), callback_(NULL), - fake_audio_worker_(manager->GetWorkerTaskRunner(), params), + capture_thread_("FakeAudioInput"), params_(params), audio_bus_(AudioBus::Create(params)) { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); @@ -51,16 +55,39 @@ return true; } -void FakeAudioInputStream::Start(AudioInputCallback* callback) { +void FakeAudioInputStream::Start(AudioInputCallback* callback) { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); + DCHECK(callback); + DCHECK(!callback_); + DCHECK(!fake_audio_worker_); + callback_ = callback; - fake_audio_worker_.Start(base::BindRepeating( + + base::Thread::Options options; + options.priority = base::ThreadPriority::REALTIME_AUDIO; + CHECK(capture_thread_.StartWithOptions(options)); + + fake_audio_worker_ = + std::make_unique<FakeAudioWorker>(capture_thread_.task_runner(), params_); + + fake_audio_worker_->Start(base::BindRepeating( &FakeAudioInputStream::ReadAudioFromSource, base::Unretained(this))); } void FakeAudioInputStream::Stop() { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); - fake_audio_worker_.Stop(); + // Start was never called + if (!callback_) { + return; + } + + DCHECK(capture_thread_.IsRunning()); + DCHECK(fake_audio_worker_); + + fake_audio_worker_->Stop(); + fake_audio_worker_.reset(); + capture_thread_.Stop(); + callback_ = NULL; } @@ -104,7 +131,7 @@ void FakeAudioInputStream::ReadAudioFromSource(base::TimeTicks ideal_time, base::TimeTicks now) { - DCHECK(audio_manager_->GetWorkerTaskRunner()->BelongsToCurrentThread()); + DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); DCHECK(callback_); if (!audio_source_) @@ -127,7 +154,7 @@ using AudioSourceCallback = AudioOutputStream::AudioSourceCallback; std::unique_ptr<AudioSourceCallback> FakeAudioInputStream::ChooseSource() { - DCHECK(audio_manager_->GetWorkerTaskRunner()->BelongsToCurrentThread()); + DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFileForFakeAudioCapture)) {
diff --git a/media/audio/fake_audio_input_stream.h b/media/audio/fake_audio_input_stream.h index 29f74df..1369332 100644 --- a/media/audio/fake_audio_input_stream.h +++ b/media/audio/fake_audio_input_stream.h
@@ -12,6 +12,7 @@ #include "base/callback_forward.h" #include "base/macros.h" +#include "base/threading/thread.h" #include "media/audio/audio_io.h" #include "media/base/audio_parameters.h" #include "media/base/fake_audio_worker.h" @@ -69,9 +70,10 @@ AudioManagerBase* audio_manager_; AudioInputCallback* callback_; - FakeAudioWorker fake_audio_worker_; + base::Thread capture_thread_; AudioParameters params_; + std::unique_ptr<FakeAudioWorker> fake_audio_worker_; std::unique_ptr<AudioOutputStream::AudioSourceCallback> audio_source_; std::unique_ptr<media::AudioBus> audio_bus_;
diff --git a/media/base/fake_audio_worker_unittest.cc b/media/base/fake_audio_worker_unittest.cc index b1ee9e6..69ce37f 100644 --- a/media/base/fake_audio_worker_unittest.cc +++ b/media/base/fake_audio_worker_unittest.cc
@@ -4,6 +4,8 @@ #include "media/base/fake_audio_worker.h" +#include <limits> +#include <memory> #include <vector> #include "base/bind.h" @@ -11,7 +13,10 @@ #include "base/memory/scoped_refptr.h" #include "base/single_thread_task_runner.h" #include "base/test/scoped_task_environment.h" +#include "base/test/test_mock_time_task_runner.h" +#include "base/time/tick_clock.h" #include "base/time/time.h" +#include "base/time/time_override.h" #include "build/build_config.h" #include "media/base/audio_parameters.h" #include "testing/gmock/include/gmock/gmock-matchers.h" @@ -169,4 +174,92 @@ scoped_task_environment_.FastForwardUntilNoTasksRemain(); EXPECT_THAT(callbacks_, SizeIs(3)); } + +class FakeAudioWorkerMockTaskTest : public testing::Test { + public: + FakeAudioWorkerMockTaskTest() + : params_(AudioParameters::AUDIO_FAKE, CHANNEL_LAYOUT_STEREO, 44100, 128), + fake_worker_(task_runner_, params_) { + DCHECK(!global_clock_); + global_clock_ = task_runner_->GetMockTickClock(); + time_between_callbacks_ = base::TimeDelta::FromMicroseconds( + params_.frames_per_buffer() * base::Time::kMicrosecondsPerSecond / + static_cast<float>(params_.sample_rate())); + clock_overrides_ = std::make_unique<base::subtle::ScopedTimeClockOverrides>( + nullptr, TimeTicksOverride, nullptr); + } + + ~FakeAudioWorkerMockTaskTest() override { global_clock_ = nullptr; } + + void CalledByFakeWorker(base::TimeTicks ideal_time, base::TimeTicks now) { + callbacks_.push_back(base::TimeTicks::Now()); + } + + void SetUp() override { + { + base::TestMockTimeTaskRunner::ScopedContext ctx(task_runner_); + fake_worker_.Start( + base::BindRepeating(&FakeAudioWorkerMockTaskTest::CalledByFakeWorker, + base::Unretained(this))); + } + } + + void TearDown() override { + { + base::TestMockTimeTaskRunner::ScopedContext ctx(task_runner_); + fake_worker_.Stop(); + } + task_runner_->RunUntilIdle(); + } + + protected: + scoped_refptr<base::TestMockTimeTaskRunner> task_runner_ = + new base::TestMockTimeTaskRunner(); + std::unique_ptr<base::subtle::ScopedTimeClockOverrides> clock_overrides_; + AudioParameters params_; + FakeAudioWorker fake_worker_; + base::TimeDelta time_between_callbacks_; + std::vector<base::TimeTicks> callbacks_; + + static const base::TickClock* global_clock_; + static base::TimeTicks TimeTicksOverride() { + DCHECK(global_clock_); + return global_clock_->NowTicks(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(FakeAudioWorkerMockTaskTest); +}; + +const base::TickClock* FakeAudioWorkerMockTaskTest::global_clock_ = nullptr; + +// This test is disabled because when late we skip reading to maintain +// compatibility for input and output streams. +TEST_F(FakeAudioWorkerMockTaskTest, DISABLED_LateCallbackProducesCallback) { + task_runner_->RunUntilIdle(); + EXPECT_THAT(callbacks_, SizeIs(1)); + + // Advancing 2 periods will trigger the late logic. It should result in one + // callback, And one queued item which will run in 0.5 callback periods. + task_runner_->AdvanceMockTickClock(time_between_callbacks_ * 2.5); + task_runner_->RunUntilIdle(); + EXPECT_THAT(callbacks_, SizeIs(2)); + // Fast-forward to trigger the next time. Note that 0.5 does not work due to + // rounding in the next frame logic, since 128 does not divide 44100. + task_runner_->FastForwardBy(time_between_callbacks_ * 0.501); + EXPECT_THAT(callbacks_, SizeIs(3)); +} + +TEST_F(FakeAudioWorkerMockTaskTest, CallbackDelay) { + // Initial call only + task_runner_->RunUntilIdle(); + + // Run the clock forward 1.5 periods and then trigger the callback. + // This means we are not behind, but the next callback should occur + // in 0.5 periods. + task_runner_->AdvanceMockTickClock(time_between_callbacks_ * 1.5); + task_runner_->RunUntilIdle(); + EXPECT_THAT(callbacks_, SizeIs(2)); + EXPECT_EQ(task_runner_->NextPendingTaskDelay(), time_between_callbacks_ / 2); +} } // namespace media
diff --git a/media/gpu/video_decode_accelerator_unittest.cc b/media/gpu/video_decode_accelerator_unittest.cc index ca68be0..7db3114 100644 --- a/media/gpu/video_decode_accelerator_unittest.cc +++ b/media/gpu/video_decode_accelerator_unittest.cc
@@ -37,6 +37,7 @@ #include "base/hash/md5.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "base/message_loop/message_loop.h" #include "base/process/process_handle.h" #include "base/run_loop.h" @@ -865,12 +866,17 @@ // Populate the shared memory buffer w/ the fragment, duplicate its handle, // and hand it off to the decoder. - base::SharedMemory shm; - LOG_ASSERT(shm.CreateAndMapAnonymous(next_fragment_size)); - memcpy(shm.memory(), next_fragment_bytes.data(), next_fragment_size); - - BitstreamBuffer bitstream_buffer(next_bitstream_buffer_id_, shm.handle(), - false /* read_only */, next_fragment_size); + base::UnsafeSharedMemoryRegion shm_region = + base::UnsafeSharedMemoryRegion::Create(next_fragment_size); + LOG_ASSERT(shm_region.IsValid()); + base::WritableSharedMemoryMapping shm_mapping = shm_region.Map(); + LOG_ASSERT(shm_mapping.IsValid()); + memcpy(shm_mapping.memory(), next_fragment_bytes.data(), next_fragment_size); + BitstreamBuffer bitstream_buffer( + next_bitstream_buffer_id_, + base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( + std::move(shm_region)), + next_fragment_size); decode_start_time_[next_bitstream_buffer_id_] = base::TimeTicks::Now(); // Mask against 30 bits, to avoid (undefined) wraparound on signed integer. next_bitstream_buffer_id_ = (next_bitstream_buffer_id_ + 1) & 0x3FFFFFFF;
diff --git a/media/gpu/video_encode_accelerator_unittest.cc b/media/gpu/video_encode_accelerator_unittest.cc index 369adbc..33a668103 100644 --- a/media/gpu/video_encode_accelerator_unittest.cc +++ b/media/gpu/video_encode_accelerator_unittest.cc
@@ -22,6 +22,7 @@ #include "base/macros.h" #include "base/memory/aligned_memory.h" #include "base/memory/ref_counted.h" +#include "base/memory/unsafe_shared_memory_region.h" #include "base/memory/weak_ptr.h" #include "base/numerics/safe_conversions.h" #include "base/process/process_handle.h" @@ -1503,7 +1504,7 @@ // All methods of this class should be run on the same thread. base::ThreadChecker thread_checker_; - std::vector<std::unique_ptr<base::SharedMemory>> output_shms_; + std::vector<std::unique_ptr<base::UnsafeSharedMemoryRegion>> output_shms_; int32_t next_output_buffer_id_; }; @@ -1547,7 +1548,7 @@ void FeedEncoderWithOneInput(); // Provide the encoder with a new output buffer. - void FeedEncoderWithOutput(base::SharedMemory* shm); + void FeedEncoderWithOutput(base::UnsafeSharedMemoryRegion* shm); // Called on finding a complete frame (with |keyframe| set to true for // keyframes, |visible_size| for the visible size of encoded frame) in the @@ -1632,7 +1633,7 @@ std::queue<size_t> keyframe_indices_; // Ids for output BitstreamBuffers. - typedef std::map<int32_t, base::SharedMemory*> IdToSHM; + typedef std::map<int32_t, base::UnsafeSharedMemoryRegion*> IdToSHM; IdToSHM output_buffers_at_client_; // Current offset into input stream. @@ -1948,8 +1949,9 @@ ASSERT_GT(output_buffer_size_, 0UL); for (unsigned int i = 0; i < kNumOutputBuffers; ++i) { - auto shm = std::make_unique<base::SharedMemory>(); - LOG_ASSERT(shm->CreateAndMapAnonymous(output_buffer_size_)); + auto shm = std::make_unique<base::UnsafeSharedMemoryRegion>(); + *shm = base::UnsafeSharedMemoryRegion::Create(output_buffer_size_); + LOG_ASSERT(shm->IsValid()); FeedEncoderWithOutput(shm.get()); output_shms_.push_back(std::move(shm)); } @@ -1987,7 +1989,8 @@ IdToSHM::iterator it = output_buffers_at_client_.find(bitstream_buffer_id); ASSERT_NE(it, output_buffers_at_client_.end()); - base::SharedMemory* shm = it->second; + base::UnsafeSharedMemoryRegion* shm = it->second; + LOG_ASSERT(shm->IsValid()); output_buffers_at_client_.erase(it); if (state_ == CS_FLUSHED || state_ == CS_VALIDATED) @@ -2001,7 +2004,9 @@ encoded_stream_size_since_last_check_ += metadata.payload_size_bytes; - const uint8_t* stream_ptr = static_cast<const uint8_t*>(shm->memory()); + base::WritableSharedMemoryMapping mapping = shm->Map(); + LOG_ASSERT(mapping.IsValid()); + const uint8_t* stream_ptr = static_cast<const uint8_t*>(mapping.memory()); if (metadata.payload_size_bytes > 0) { if (stream_validator_) { stream_validator_->ProcessStreamBuffer(stream_ptr, @@ -2014,7 +2019,7 @@ if (quality_validator_) { scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CopyFrom( - static_cast<const uint8_t*>(shm->memory()), + static_cast<const uint8_t*>(mapping.memory()), static_cast<int>(metadata.payload_size_bytes))); quality_validator_->AddDecodeBuffer(buffer); } @@ -2033,7 +2038,7 @@ EXPECT_TRUE(base::AppendToFile( base::FilePath::FromUTF8Unsafe(test_stream_->out_filename), - static_cast<char*>(shm->memory()), + static_cast<char*>(mapping.memory()), base::checked_cast<int>(metadata.payload_size_bytes))); } } @@ -2202,7 +2207,7 @@ } } -void VEAClient::FeedEncoderWithOutput(base::SharedMemory* shm) { +void VEAClient::FeedEncoderWithOutput(base::UnsafeSharedMemoryRegion* shm) { DCHECK(thread_checker_.CalledOnValidThread()); if (!has_encoder()) return; @@ -2210,8 +2215,11 @@ if (state_ != CS_ENCODING && state_ != CS_FLUSHING) return; - BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, shm->handle(), - false /* read_only */, output_buffer_size_); + BitstreamBuffer bitstream_buffer( + next_output_buffer_id_++, + base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( + shm->Duplicate()), + output_buffer_size_); LOG_ASSERT(output_buffers_at_client_ .insert(std::make_pair(bitstream_buffer.id(), shm)) .second); @@ -2456,7 +2464,8 @@ void SetState(ClientState new_state) override; // Provide the encoder with a new output buffer. - void FeedEncoderWithOutput(base::SharedMemory* shm, size_t output_size); + void FeedEncoderWithOutput(base::UnsafeSharedMemoryRegion* shm, + size_t output_size); const int width_; const int height_; @@ -2517,24 +2526,26 @@ ASSERT_GT(output_size, 0UL); for (unsigned int i = 0; i < kNumOutputBuffers; ++i) { - auto shm = std::make_unique<base::SharedMemory>(); - LOG_ASSERT(shm->CreateAndMapAnonymous(output_size)); + auto shm = std::make_unique<base::UnsafeSharedMemoryRegion>(); + *shm = base::UnsafeSharedMemoryRegion::Create(output_size); + LOG_ASSERT(shm->IsValid()); FeedEncoderWithOutput(shm.get(), output_size); output_shms_.push_back(std::move(shm)); } } -void SimpleVEAClientBase::FeedEncoderWithOutput(base::SharedMemory* shm, - size_t output_size) { +void SimpleVEAClientBase::FeedEncoderWithOutput( + base::UnsafeSharedMemoryRegion* shm, + size_t output_size) { DCHECK(thread_checker_.CalledOnValidThread()); if (!has_encoder()) return; - base::SharedMemoryHandle dup_handle = shm->handle().Duplicate(); - LOG_ASSERT(dup_handle.IsValid()); - - BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, dup_handle, - false /* read_only */, output_size); + BitstreamBuffer bitstream_buffer( + next_output_buffer_id_++, + base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( + shm->Duplicate()), + output_size); encoder_->UseOutputBitstreamBuffer(std::move(bitstream_buffer)); }
diff --git a/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java b/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java index 7911525..39d0a6a7 100644 --- a/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java +++ b/services/device/nfc/android/java/src/org/chromium/device/nfc/NfcImpl.java
@@ -335,6 +335,22 @@ } /** + * Check if the NFC device matches the |compatibility| field in |options|. + * + * @param compatibility denotes the compatibility kind of the found NFC device. + * @return boolean true if NFC the compatibility matches. + */ + boolean checkCompatibility(int compatibility) { + // 'nfc-forum' option can only push messages to NFC standard devices and 'vendor' + // option can only push to vendor specific ones. + if (nfcPushOptions.compatibility == NdefCompatibility.ANY + || nfcPushOptions.compatibility == compatibility) { + return true; + } + return false; + } + + /** * Completes pending push operation. * * @param error should be null when operation is completed successfully, otherwise, @@ -497,6 +513,10 @@ return; } + if (!mPendingPushOperation.checkCompatibility(mTagHandler.compatibility())) { + return; + } + try { mTagHandler.connect(); mTagHandler.write(NfcTypeConverter.toNdefMessage(mPendingPushOperation.ndefMessage));
diff --git a/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java b/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java index b154b84..1cb6cf7 100644 --- a/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java +++ b/services/device/nfc/android/junit/src/org/chromium/device/nfc/NFCTest.java
@@ -18,6 +18,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import android.app.Activity; import android.content.Context; @@ -443,6 +444,78 @@ } /** + * Test that compatibility is checked for Nfc.push() with NFC_FORUM device. + */ + @Test + @Feature({"NFCTest"}) + public void testPushCompatibilityMatchingNfcForum() { + TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); + mDelegate.invokeCallback(); + doReturn(NdefCompatibility.NFC_FORUM).when(mNfcTagHandler).compatibility(); + + // Should match, because |compatibility| is set to NdefCompatibility.ANY + // in createNfcPushOptions(). + PushResponse mockCallback_1 = mock(PushResponse.class); + nfc.push(createMojoNdefMessage(), createNfcPushOptions(), mockCallback_1); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verify(mockCallback_1).call(mErrorCaptor.capture()); + assertNull(mErrorCaptor.getValue()); + + // Should match. + PushResponse mockCallback_2 = mock(PushResponse.class); + NfcPushOptions options_2 = createNfcPushOptions(); + options_2.compatibility = NdefCompatibility.NFC_FORUM; + nfc.push(createMojoNdefMessage(), options_2, mockCallback_2); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verify(mockCallback_2).call(mErrorCaptor.capture()); + assertNull(mErrorCaptor.getValue()); + + // Should not match. + PushResponse mockCallback_3 = mock(PushResponse.class); + NfcPushOptions options_3 = createNfcPushOptions(); + options_3.compatibility = NdefCompatibility.VENDOR; + nfc.push(createMojoNdefMessage(), options_3, mockCallback_3); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verifyZeroInteractions(mockCallback_3); + } + + /** + * Test that compatibility is checked for Nfc.push() with VENDOR device. + */ + @Test + @Feature({"NFCTest"}) + public void testPushCompatibilityMatchingVendor() { + TestNfcImpl nfc = new TestNfcImpl(mContext, mDelegate); + mDelegate.invokeCallback(); + doReturn(NdefCompatibility.VENDOR).when(mNfcTagHandler).compatibility(); + + // Should match, because |compatibility| is set to NdefCompatibility.ANY + // in createNfcPushOptions(). + PushResponse mockCallback_1 = mock(PushResponse.class); + nfc.push(createMojoNdefMessage(), createNfcPushOptions(), mockCallback_1); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verify(mockCallback_1).call(mErrorCaptor.capture()); + assertNull(mErrorCaptor.getValue()); + + // Should match for NdefCompatibility.VENDOR. + PushResponse mockCallback_2 = mock(PushResponse.class); + NfcPushOptions options_2 = createNfcPushOptions(); + options_2.compatibility = NdefCompatibility.VENDOR; + nfc.push(createMojoNdefMessage(), options_2, mockCallback_2); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verify(mockCallback_2).call(mErrorCaptor.capture()); + assertNull(mErrorCaptor.getValue()); + + // Should not match. + PushResponse mockCallback_3 = mock(PushResponse.class); + NfcPushOptions options_3 = createNfcPushOptions(); + options_3.compatibility = NdefCompatibility.NFC_FORUM; + nfc.push(createMojoNdefMessage(), options_3, mockCallback_3); + nfc.processPendingOperationsForTesting(mNfcTagHandler); + verifyZeroInteractions(mockCallback_3); + } + + /** * Test that Nfc.watch() works correctly and client is notified. */ @Test @@ -1195,11 +1268,7 @@ * Creates NfcPushOptions with default values. */ private NfcPushOptions createNfcPushOptions() { - NfcPushOptions pushOptions = new NfcPushOptions(); - pushOptions.target = NfcPushTarget.ANY; - pushOptions.timeout = Double.POSITIVE_INFINITY; - pushOptions.ignoreRead = false; - return pushOptions; + return createNfcPushOptions(/*timeout=*/Double.POSITIVE_INFINITY); } /** @@ -1210,6 +1279,7 @@ pushOptions.target = NfcPushTarget.ANY; pushOptions.timeout = timeout; pushOptions.ignoreRead = false; + pushOptions.compatibility = NdefCompatibility.ANY; return pushOptions; }
diff --git a/services/device/public/mojom/nfc.mojom b/services/device/public/mojom/nfc.mojom index daad8e53..7c20ad3 100644 --- a/services/device/public/mojom/nfc.mojom +++ b/services/device/public/mojom/nfc.mojom
@@ -81,6 +81,9 @@ // If the property is true, the push operation will suspend active watchers // until its completion. bool ignore_read; + + // Defines the accepted kinds of NFC devices. + NDEFCompatibility compatibility; }; struct NDEFRecordTypeFilter { @@ -97,7 +100,7 @@ // Defines media type filtering constraint. string? media_type; - // Defines the accepted kind of NFC devices. + // Defines the accepted kinds of NFC devices. NDEFCompatibility compatibility; };
diff --git a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc index 0516209..9f2b7109 100644 --- a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc +++ b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc
@@ -432,14 +432,20 @@ } // Emit any new interned data entries into the packet. - auto* interned_data = trace_packet->set_interned_data(); + perfetto::protos::pbzero::InternedData* interned_data = nullptr; if (!interned_category.was_emitted) { + if (!interned_data) { + interned_data = trace_packet->set_interned_data(); + } auto* category_entry = interned_data->add_event_categories(); category_entry->set_iid(interned_category.id); category_entry->set_name(category_name); } if (!interned_name.was_emitted) { + if (!interned_data) { + interned_data = trace_packet->set_interned_data(); + } auto* name_entry = interned_data->add_legacy_event_names(); name_entry->set_iid(interned_name.id); name_entry->set_name(copy_strings && privacy_filtering_enabled_ @@ -449,6 +455,9 @@ if (interned_source_location.id) { if (!interned_source_location.was_emitted) { + if (!interned_data) { + interned_data = trace_packet->set_interned_data(); + } auto* source_location_entry = interned_data->add_source_locations(); source_location_entry->set_iid(interned_source_location.id); source_location_entry->set_file_name(trace_event->arg_value(0).as_string); @@ -462,6 +471,9 @@ ++i) { DCHECK(interned_annotation_names[i].id); if (!interned_annotation_names[i].was_emitted) { + if (!interned_data) { + interned_data = trace_packet->set_interned_data(); + } auto* name_entry = interned_data->add_debug_annotation_names(); name_entry->set_iid(interned_annotation_names[i].id); name_entry->set_name(trace_event->arg_name(i));
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 9e2f058a..314fab4 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -261,7 +261,6 @@ "platform/web_media_player_client.h", "platform/web_media_player_encrypted_media_client.h", "platform/web_media_player_source.h", - "platform/web_media_recorder_handler.h", "platform/web_media_recorder_handler_client.h", "platform/web_media_source.h", "platform/web_media_stream.h",
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 95b6559..6b49d8e 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -26,6 +26,7 @@ "badging/badging.mojom", "cache_storage/cache_storage.mojom", "choosers/color_chooser.mojom", + "choosers/date_time_chooser.mojom", "choosers/file_chooser.mojom", "clipboard/clipboard.mojom", "commit_result/commit_result.mojom", @@ -157,6 +158,7 @@ "//services/viz/public/interfaces", "//skia/public/interfaces", "//third_party/blink/public/mojom/usb", + "//ui/base/ime/mojo", "//ui/gfx/geometry/mojo", "//ui/gfx/mojo", "//url/mojom:url_mojom_gurl", @@ -248,7 +250,6 @@ # those high-level service worker mojom files there. mojom("mojom_core") { sources = [ - "choosers/date_time_chooser.mojom", "messaging/cloneable_message.mojom", "messaging/transferable_message.mojom", "messaging/user_activation_snapshot.mojom", @@ -281,7 +282,6 @@ "//services/network/public/mojom", "//services/service_manager/public/mojom", "//skia/public/interfaces", - "//ui/base/ime/mojo", "//url/mojom:url_mojom_gurl", "//url/mojom:url_mojom_origin", ]
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index 37ed9c9..5c0ee40 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2312,6 +2312,7 @@ kFeaturePolicySemicolonSeparatedDeclarations = 2923, kV8CallSiteAPIGetFunctionSloppyCall = 2924, kV8CallSiteAPIGetThisSloppyCall = 2925, + kBuiltInModuleToast = 2926, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/platform/modules/mediastream/DEPS b/third_party/blink/public/platform/modules/mediastream/DEPS index e1f8f4d..c78f34b 100644 --- a/third_party/blink/public/platform/modules/mediastream/DEPS +++ b/third_party/blink/public/platform/modules/mediastream/DEPS
@@ -1,8 +1,4 @@ include_rules = [ - # TODO(crbug.com/923394): Remove this dependency once STL types are - # migrated to WTF types in mediastream. - "+base/stl_util.h", - "+base/memory/singleton.h", "+base/sequence_checker.h", "+media/base",
diff --git a/third_party/blink/public/platform/modules/mediastream/media_stream_audio_deliverer.h b/third_party/blink/public/platform/modules/mediastream/media_stream_audio_deliverer.h index 35338088..6bf8506 100644 --- a/third_party/blink/public/platform/modules/mediastream/media_stream_audio_deliverer.h +++ b/third_party/blink/public/platform/modules/mediastream/media_stream_audio_deliverer.h
@@ -8,7 +8,6 @@ #include <algorithm> #include <vector> -#include "base/stl_util.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" #include "base/trace_event/trace_event.h"
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 19b7846..e7116b7 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -76,6 +76,10 @@ class GpuMemoryBufferManager; } +namespace media { +class GpuVideoAcceleratorFactories; +} + namespace rtc { class Thread; } @@ -110,7 +114,6 @@ class WebGraphicsContext3DProvider; class WebLocalFrame; class WebMediaCapabilitiesClient; -class WebMediaRecorderHandler; class WebMediaStreamCenter; class WebPrescientNetworking; class WebPublicSuffixList; @@ -583,11 +586,6 @@ CreateRTCPeerConnectionHandler(WebRTCPeerConnectionHandlerClient*, scoped_refptr<base::SingleThreadTaskRunner>); - // Creates a WebMediaRecorderHandler to record MediaStreams. - // May return null if the functionality is not available or out of resources. - virtual std::unique_ptr<WebMediaRecorderHandler> CreateMediaRecorderHandler( - scoped_refptr<base::SingleThreadTaskRunner>); - // May return null if WebRTC functionality is not available or out of // resources. virtual std::unique_ptr<WebRTCCertificateGenerator> @@ -676,6 +674,12 @@ return nullptr; } + // GpuVideoAcceleratorFactories -------------------------------------- + + virtual media::GpuVideoAcceleratorFactories* GetGpuFactories() { + return nullptr; + } + // Renderer Memory Metrics ---------------------------------------------- virtual void RecordMetricsForBackgroundedRendererPurge() {}
diff --git a/third_party/blink/public/platform/web_graphics_context_3d_provider.h b/third_party/blink/public/platform/web_graphics_context_3d_provider.h index 1d3d019..2d7b7db 100644 --- a/third_party/blink/public/platform/web_graphics_context_3d_provider.h +++ b/third_party/blink/public/platform/web_graphics_context_3d_provider.h
@@ -39,8 +39,14 @@ namespace cc { class ImageDecodeCache; +class PaintCanvas; } // namespace cc +namespace media { +class PaintCanvasVideoRenderer; +class VideoFrame; +} // namespace media + namespace gpu { struct Capabilities; struct GpuFeatureInfo; @@ -98,6 +104,9 @@ // Return a static software image decode cache for a given color type. virtual cc::ImageDecodeCache* ImageDecodeCache(SkColorType color_type) = 0; virtual gpu::SharedImageInterface* SharedImageInterface() = 0; + virtual void CopyVideoFrame(media::PaintCanvasVideoRenderer* video_render, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) = 0; }; } // namespace blink
diff --git a/third_party/blink/public/platform/web_media_recorder_handler.h b/third_party/blink/public/platform/web_media_recorder_handler.h deleted file mode 100644 index a7f597e..0000000 --- a/third_party/blink/public/platform/web_media_recorder_handler.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MEDIA_RECORDER_HANDLER_H_ -#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MEDIA_RECORDER_HANDLER_H_ - -#include <memory> - -#include "third_party/blink/public/platform/web_common.h" - -#include "base/callback.h" -#include "third_party/blink/public/platform/web_string.h" - -namespace blink { - -class WebMediaRecorderHandlerClient; -struct WebMediaConfiguration; -class WebMediaStream; -struct WebMediaCapabilitiesInfo; - -// Platform interface of a MediaRecorder. -class BLINK_PLATFORM_EXPORT WebMediaRecorderHandler { - public: - virtual ~WebMediaRecorderHandler() = default; - virtual bool Initialize(WebMediaRecorderHandlerClient* client, - const WebMediaStream& stream, - const WebString& type, - const WebString& codecs, - int32_t audio_bits_per_second, - int32_t video_bits_per_second) { - return false; - } - virtual bool Start(int timeslice) { return false; } - virtual void Stop() {} - virtual void Pause() {} - virtual void Resume() {} - - // MediaRecorder API isTypeSupported(), which boils down to - // CanSupportMimeType() [1] "If true is returned from this method, it only - // indicates that the MediaRecorder implementation is capable of recording - // Blob objects for the specified MIME type. Recording may still fail if - // sufficient resources are not available to support the concrete media - // encoding." - // [1] https://w3c.github.io/mediacapture-record/MediaRecorder.html#methods - virtual bool CanSupportMimeType(const WebString& type, - const WebString& codecs) { - return false; - } - - // What is really being encoded??? - virtual WebString ActualMimeType() { return WebString(); } - - // Implements WICG Media Capabilities encodingInfo() call for local encoding. - // https://wicg.github.io/media-capabilities/#media-capabilities-interface - using OnMediaCapabilitiesEncodingInfoCallback = - base::OnceCallback<void(std::unique_ptr<WebMediaCapabilitiesInfo>)>; - virtual void EncodingInfo(const WebMediaConfiguration&, - OnMediaCapabilitiesEncodingInfoCallback) {} -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_MEDIA_RECORDER_HANDLER_H_
diff --git a/third_party/blink/public/platform/web_thread_type.h b/third_party/blink/public/platform/web_thread_type.h index 207e87d..a28f267 100644 --- a/third_party/blink/public/platform/web_thread_type.h +++ b/third_party/blink/public/platform/web_thread_type.h
@@ -27,8 +27,9 @@ kHRTFDatabaseLoaderThread = 14, kTestThread = 15, kAudioEncoderThread = 16, + kVideoEncoderThread = 17, - kCount = 17 + kCount = 18 }; BLINK_PLATFORM_EXPORT const char* GetNameForThreadType(WebThreadType);
diff --git a/third_party/blink/public/web/modules/mediastream/DEPS b/third_party/blink/public/web/modules/mediastream/DEPS index 6e24a703..b3b3fb6a 100644 --- a/third_party/blink/public/web/modules/mediastream/DEPS +++ b/third_party/blink/public/web/modules/mediastream/DEPS
@@ -1,8 +1,4 @@ include_rules = [ - # TODO(crbug.com/923394): Remove this dependency once STL types are - # migrated to WTF types in mediastream. - "+base/stl_util.h", - "+base/compiler_specific.h", "+base/logging.h", "+base/gtest_prod_util.h",
diff --git a/third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_sets.h b/third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_sets.h index 199a8dd3..f9b3d3e 100644 --- a/third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_sets.h +++ b/third_party/blink/public/web/modules/mediastream/media_stream_constraints_util_sets.h
@@ -14,7 +14,6 @@ #include "base/gtest_prod_util.h" #include "base/logging.h" #include "base/optional.h" -#include "base/stl_util.h" #include "third_party/blink/public/platform/web_common.h" #include "third_party/blink/public/platform/web_media_constraints.h"
diff --git a/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.cc.tmpl b/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.cc.tmpl index e15dc39..677a23b 100644 --- a/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.cc.tmpl
@@ -36,13 +36,15 @@ // {{property.name}} {% if property.is_internal or property.runtime_flag %} -bool {{class_name}}::IsEnabled() const { +CSSExposure {{class_name}}::Exposure() const { + {% if property.runtime_flag %} + if (!RuntimeEnabledFeatures::{{property.runtime_flag}}Enabled()) + return CSSExposure::kNone; + {% endif %} {% if property.is_internal %} - return false; - {% elif property.runtime_flag %} - return RuntimeEnabledFeatures::{{property.runtime_flag}}Enabled(); + return CSSExposure::kUA; {% else %} - return true; + return CSSExposure::kWeb; {% endif %} } {% endif %}
diff --git a/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.h.tmpl b/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.h.tmpl index 74e5f376..c8901405 100644 --- a/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.h.tmpl +++ b/third_party/blink/renderer/build/scripts/core/css/properties/templates/css_properties.h.tmpl
@@ -38,7 +38,6 @@ (property.is_property and 'kProperty' or ''), (property.inherited and 'kInherited' or ''), (property.visited and 'kVisited' or ''), - (property.is_internal and 'kInternal' or '') ] | reject('==', '') | join(' | ') %} {% set ctor_args = (not is_alias and [property_id, flags, separator] or []) %} // {{property.name}} @@ -49,7 +48,7 @@ const WTF::AtomicString& GetPropertyNameAtomicString() const override; const char* GetJSPropertyName() const override; {% if property.is_internal or property.runtime_flag %} - bool IsEnabled() const override; + CSSExposure Exposure() const override; {% endif %} {% if not is_alias %} {% if not property.affected_by_all %}
diff --git a/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl b/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl index 7fce333..a5a4939 100644 --- a/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/core/css/templates/style_property_shorthand.cc.tmpl
@@ -84,7 +84,7 @@ {% for longhand_enum_key, shorthands in longhands_dictionary.items() %} case CSSPropertyID::{{longhand_enum_key}}: { {% for shorthand in shorthands %} - if (CSSProperty::Get(CSSPropertyID::{{shorthand.enum_key}}).IsEnabled()) + if (CSSProperty::Get(CSSPropertyID::{{shorthand.enum_key}}).IsWebExposed()) result->UncheckedAppend({{shorthand.name.to_lower_camel_case()}}Shorthand()); {% endfor %} break;
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index d213f2a..8272bf28 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -1228,6 +1228,7 @@ "html/custom/custom_element_test_helpers.h", "html/custom/custom_element_upgrade_sorter_test.cc", "html/forms/email_input_type_test.cc", + "html/forms/external_date_time_chooser_test.cc", "html/forms/external_popup_menu_test.cc", "html/forms/file_input_type_test.cc", "html/forms/form_controller_test.cc",
diff --git a/third_party/blink/renderer/core/animation/animation_time_delta.h b/third_party/blink/renderer/core/animation/animation_time_delta.h index e2d3b6a..64cca32 100644 --- a/third_party/blink/renderer/core/animation/animation_time_delta.h +++ b/third_party/blink/renderer/core/animation/animation_time_delta.h
@@ -109,7 +109,7 @@ // When compiling in TimeDelta-based mode, AnimationTimeDelta is equivalent to // base::TimeDelta. -using AnimationTimeDelta = TimeDelta; +using AnimationTimeDelta = base::TimeDelta; #endif
diff --git a/third_party/blink/renderer/core/animation/document_timeline.cc b/third_party/blink/renderer/core/animation/document_timeline.cc index 85f67327..e8df557b 100644 --- a/third_party/blink/renderer/core/animation/document_timeline.cc +++ b/third_party/blink/renderer/core/animation/document_timeline.cc
@@ -59,7 +59,7 @@ const double DocumentTimeline::kMinimumDelay = 0.04; DocumentTimeline* DocumentTimeline::Create(Document* document, - TimeDelta origin_time, + base::TimeDelta origin_time, PlatformTiming* timing) { return MakeGarbageCollected<DocumentTimeline>(document, origin_time, timing); } @@ -69,15 +69,16 @@ const DocumentTimelineOptions* options) { Document* document = To<Document>(execution_context); return MakeGarbageCollected<DocumentTimeline>( - document, TimeDelta::FromMillisecondsD(options->originTime()), nullptr); + document, base::TimeDelta::FromMillisecondsD(options->originTime()), + nullptr); } DocumentTimeline::DocumentTimeline(Document* document, - TimeDelta origin_time, + base::TimeDelta origin_time, PlatformTiming* timing) : document_(document), origin_time_(origin_time), - zero_time_(TimeTicks() + origin_time_), + zero_time_(base::TimeTicks() + origin_time_), zero_time_initialized_(false), outdated_animation_count_(0), playback_rate_(1), @@ -186,7 +187,7 @@ } void DocumentTimeline::DocumentTimelineTiming::WakeAfter(double duration) { - TimeDelta duration_delta = TimeDelta::FromSecondsD(duration); + base::TimeDelta duration_delta = base::TimeDelta::FromSecondsD(duration); if (timer_.IsActive() && timer_.NextFireInterval() < duration_delta) return; timer_.StartOneShot(duration_delta, FROM_HERE); @@ -202,7 +203,7 @@ DocumentTimeline::PlatformTiming::Trace(visitor); } -TimeTicks DocumentTimeline::ZeroTime() { +base::TimeTicks DocumentTimeline::ZeroTime() { if (!zero_time_initialized_ && document_->Loader()) { zero_time_ = document_->Loader()->GetTiming().ReferenceMonotonicTime() + origin_time_; @@ -212,7 +213,7 @@ } void DocumentTimeline::ResetForTesting() { - zero_time_ = TimeTicks() + origin_time_; + zero_time_ = base::TimeTicks() + origin_time_; zero_time_initialized_ = true; playback_rate_ = 1; last_current_time_internal_ = 0; @@ -226,7 +227,7 @@ return CurrentTimeInternal(is_null) * 1000; } -// TODO(npm): change the return type to base::Optional<TimeTicks>. +// TODO(npm): change the return type to base::Optional<base::TimeTicks>. double DocumentTimeline::CurrentTimeInternal(bool& is_null) { if (!IsActive()) { is_null = true;
diff --git a/third_party/blink/renderer/core/animation/document_timeline.h b/third_party/blink/renderer/core/animation/document_timeline.h index e566c60..080957b 100644 --- a/third_party/blink/renderer/core/animation/document_timeline.h +++ b/third_party/blink/renderer/core/animation/document_timeline.h
@@ -68,15 +68,16 @@ virtual void Trace(blink::Visitor* visitor) {} }; - static DocumentTimeline* Create(Document*, - TimeDelta origin_time = TimeDelta(), - PlatformTiming* = nullptr); + static DocumentTimeline* Create( + Document*, + base::TimeDelta origin_time = base::TimeDelta(), + PlatformTiming* = nullptr); // Web Animations API IDL constructor static DocumentTimeline* Create(ExecutionContext*, const DocumentTimelineOptions*); - DocumentTimeline(Document*, TimeDelta origin_time, PlatformTiming*); + DocumentTimeline(Document*, base::TimeDelta origin_time, PlatformTiming*); ~DocumentTimeline() override = default; bool IsDocumentTimeline() const final { return true; } @@ -99,7 +100,7 @@ wtf_size_t PendingAnimationsCount() const { return animations_needing_update_.size(); } - TimeTicks ZeroTime(); + base::TimeTicks ZeroTime(); double currentTime(bool& is_null) override; double currentTime(); double CurrentTimeInternal(bool& is_null); @@ -134,10 +135,10 @@ // Origin time for the timeline relative to the time origin of the document. // Provided when the timeline is constructed. See // https://drafts.csswg.org/web-animations/#dom-documenttimelineoptions-origintime. - TimeDelta origin_time_; + base::TimeDelta origin_time_; // The origin time. This is computed by adding |origin_time_| to the time // origin of the document. - TimeTicks zero_time_; + base::TimeTicks zero_time_; bool zero_time_initialized_; unsigned outdated_animation_count_; // Animations which will be updated on the next frame
diff --git a/third_party/blink/renderer/core/animation/document_timeline_test.cc b/third_party/blink/renderer/core/animation/document_timeline_test.cc index 32788fa..eaca3c0 100644 --- a/third_party/blink/renderer/core/animation/document_timeline_test.cc +++ b/third_party/blink/renderer/core/animation/document_timeline_test.cc
@@ -166,7 +166,7 @@ auto* document_without_frame = MakeGarbageCollected<Document>(); DocumentTimeline* inactive_timeline = DocumentTimeline::Create( - document_without_frame, TimeDelta(), platform_timing); + document_without_frame, base::TimeDelta(), platform_timing); EXPECT_EQ(0, inactive_timeline->EffectiveTime()); is_null = false; @@ -175,7 +175,7 @@ } TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormal) { - TimeTicks zero_time = timeline->ZeroTime(); + base::TimeTicks zero_time = timeline->ZeroTime(); bool is_null; timeline->SetPlaybackRate(1.0); @@ -194,7 +194,7 @@ } TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormalWithOriginTime) { - TimeDelta origin_time = TimeDelta::FromSeconds(-1000); + base::TimeDelta origin_time = base::TimeDelta::FromSeconds(-1000); timeline = DocumentTimeline::Create(document.Get(), origin_time, platform_timing); timeline->ResetForTesting(); @@ -202,19 +202,19 @@ bool is_null; EXPECT_EQ(1.0, timeline->PlaybackRate()); - EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime()); EXPECT_EQ(1000, timeline->CurrentTimeInternal()); EXPECT_EQ(1000, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100)); - EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime()); EXPECT_EQ(1100, timeline->CurrentTimeInternal()); EXPECT_EQ(1100, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(200)); - EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime()); EXPECT_EQ(1200, timeline->CurrentTimeInternal()); EXPECT_EQ(1200, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); @@ -224,7 +224,7 @@ bool is_null; GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100)); - EXPECT_EQ(TimeTicks(), timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime()); EXPECT_EQ(100, timeline->CurrentTimeInternal()); EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); @@ -249,18 +249,18 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRatePauseWithOriginTime) { bool is_null; - TimeDelta origin_time = TimeDelta::FromSeconds(-1000); + base::TimeDelta origin_time = base::TimeDelta::FromSeconds(-1000); timeline = DocumentTimeline::Create(document.Get(), origin_time, platform_timing); timeline->ResetForTesting(); - EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime()); EXPECT_EQ(1000, timeline->CurrentTimeInternal()); EXPECT_EQ(1000, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100)); - EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime()); EXPECT_EQ(1100, timeline->CurrentTimeInternal()); EXPECT_EQ(1100, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); @@ -290,7 +290,7 @@ bool is_null; GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100)); - EXPECT_EQ(TimeTicks(), timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime()); EXPECT_EQ(100, timeline->CurrentTimeInternal()); EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); @@ -316,7 +316,7 @@ bool is_null; GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100)); - EXPECT_EQ(TimeTicks(), timeline->ZeroTime()); + EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime()); EXPECT_EQ(100, timeline->CurrentTimeInternal()); EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null)); EXPECT_FALSE(is_null); @@ -342,7 +342,7 @@ bool is_null; timeline = DocumentTimeline::Create( - document.Get(), TimeDelta::FromSeconds(-1000), platform_timing); + document.Get(), base::TimeDelta::FromSeconds(-1000), platform_timing); timeline->ResetForTesting(); GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
diff --git a/third_party/blink/renderer/core/animation/effect_stack_test.cc b/third_party/blink/renderer/core/animation/effect_stack_test.cc index b63467b..1f7f2ae 100644 --- a/third_party/blink/renderer/core/animation/effect_stack_test.cc +++ b/third_party/blink/renderer/core/animation/effect_stack_test.cc
@@ -35,7 +35,7 @@ return animation; } - void UpdateTimeline(TimeDelta time) { + void UpdateTimeline(base::TimeDelta time) { GetDocument().GetAnimationClock().UpdateTime( GetDocument().Timeline().ZeroTime() + time); timeline->ServiceAnimations(kTimingUpdateForAnimationFrame); @@ -180,7 +180,7 @@ // to keep the ActiveInterpolationsMap in a Persistent. Persistent<ActiveInterpolationsMap> interpolations; - UpdateTimeline(TimeDelta::FromSeconds(11)); + UpdateTimeline(base::TimeDelta::FromSeconds(11)); ThreadState::Current()->CollectAllGarbageForTesting(); interpolations = MakeGarbageCollected<ActiveInterpolationsMap>( EffectStack::ActiveInterpolations( @@ -190,7 +190,7 @@ EXPECT_EQ(GetFontSizeValue(*interpolations), 3); EXPECT_EQ(3u, SampledEffectCount()); - UpdateTimeline(TimeDelta::FromSeconds(13)); + UpdateTimeline(base::TimeDelta::FromSeconds(13)); ThreadState::Current()->CollectAllGarbageForTesting(); interpolations = MakeGarbageCollected<ActiveInterpolationsMap>( EffectStack::ActiveInterpolations( @@ -200,7 +200,7 @@ EXPECT_EQ(GetFontSizeValue(*interpolations), 3); EXPECT_EQ(3u, SampledEffectCount()); - UpdateTimeline(TimeDelta::FromSeconds(15)); + UpdateTimeline(base::TimeDelta::FromSeconds(15)); ThreadState::Current()->CollectAllGarbageForTesting(); interpolations = MakeGarbageCollected<ActiveInterpolationsMap>( EffectStack::ActiveInterpolations( @@ -210,7 +210,7 @@ EXPECT_EQ(GetFontSizeValue(*interpolations), 3); EXPECT_EQ(2u, SampledEffectCount()); - UpdateTimeline(TimeDelta::FromSeconds(17)); + UpdateTimeline(base::TimeDelta::FromSeconds(17)); ThreadState::Current()->CollectAllGarbageForTesting(); interpolations = MakeGarbageCollected<ActiveInterpolationsMap>( EffectStack::ActiveInterpolations(
diff --git a/third_party/blink/renderer/core/animation/pending_animations.cc b/third_party/blink/renderer/core/animation/pending_animations.cc index dad04858..3f5539d6 100644 --- a/third_party/blink/renderer/core/animation/pending_animations.cc +++ b/third_party/blink/renderer/core/animation/pending_animations.cc
@@ -50,7 +50,7 @@ bool visible = document->GetPage() && document->GetPage()->IsPageVisible(); if (!visible && !timer_.IsActive()) { - timer_.StartOneShot(TimeDelta(), FROM_HERE); + timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } }
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_task.cc b/third_party/blink/renderer/core/content_capture/content_capture_task.cc index f8212b9d..8e01b0b 100644 --- a/third_party/blink/renderer/core/content_capture/content_capture_task.cc +++ b/third_party/blink/renderer/core/content_capture/content_capture_task.cc
@@ -27,7 +27,7 @@ ->GetTaskTimingParameters(task_short_delay_, task_long_delay_); // The histogram is all about time, just disable it if high resolution isn't // supported. - if (TimeTicks::IsHighResolution()) { + if (base::TimeTicks::IsHighResolution()) { histogram_reporter_ = base::MakeRefCounted<ContentCaptureTaskHistogramReporter>(); task_session_->SetSentNodeCountCallback( @@ -210,7 +210,7 @@ if (is_scheduled_) return; - TimeDelta delay; + base::TimeDelta delay; switch (reason) { case ScheduleReason::kFirstContentChange: case ScheduleReason::kScrolling:
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc b/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc index 7c3834b..7ffd4d1 100644 --- a/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc +++ b/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc
@@ -61,9 +61,9 @@ void ContentCaptureTaskHistogramReporter::OnSendContentEnded( size_t sent_content_count) { - TimeTicks now = WTF::CurrentTimeTicks(); + base::TimeTicks now = WTF::CurrentTimeTicks(); if (captured_content_change_time_) { - TimeTicks content_change_time = captured_content_change_time_.value(); + base::TimeTicks content_change_time = captured_content_change_time_.value(); captured_content_change_time_.reset(); capture_content_delay_time_histogram_.CountMilliseconds( now - content_change_time);
diff --git a/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h b/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h index 49d5389..a97d67b 100644 --- a/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h +++ b/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h
@@ -39,15 +39,15 @@ private: // The time of first content change since the last content captured. - base::Optional<WTF::TimeTicks> content_change_time_; + base::Optional<base::TimeTicks> content_change_time_; // The copy of |content_change_time| after the content has been captured; we // need to record the time the content has been sent, |content_change_time_| // shall be released for the next content change. - base::Optional<WTF::TimeTicks> captured_content_change_time_; + base::Optional<base::TimeTicks> captured_content_change_time_; // The time to start capturing content. - WTF::TimeTicks capture_content_start_time_; + base::TimeTicks capture_content_start_time_; // The time to start sending content. - WTF::TimeTicks send_content_start_time_; + base::TimeTicks send_content_start_time_; // Records time from first content change to content that has been sent, its // range is 500ms from to 30s.
diff --git a/third_party/blink/renderer/core/content_capture/task_session.h b/third_party/blink/renderer/core/content_capture/task_session.h index 39d7b1a..fdf100be 100644 --- a/third_party/blink/renderer/core/content_capture/task_session.h +++ b/third_party/blink/renderer/core/content_capture/task_session.h
@@ -98,7 +98,7 @@ // This is for the metrics to record the total node that has been sent. size_t total_sent_nodes_ = 0; // Histogram could be disabed in low time resolution OS, see - // TimeTicks::IsHighResolution and ContentCaptureTask. + // base::TimeTicks::IsHighResolution and ContentCaptureTask. base::Optional<SentNodeCountCallback> callback_; };
diff --git a/third_party/blink/renderer/core/css/BUILD.gn b/third_party/blink/renderer/core/css/BUILD.gn index 660258c..46275fd 100644 --- a/third_party/blink/renderer/core/css/BUILD.gn +++ b/third_party/blink/renderer/core/css/BUILD.gn
@@ -422,6 +422,7 @@ "properties/computed_style_utils.h", "properties/css_direction_aware_resolver.cc", "properties/css_direction_aware_resolver.h", + "properties/css_exposure.h", "properties/css_parsing_utils.cc", "properties/css_parsing_utils.h", "properties/css_property.cc", @@ -610,6 +611,7 @@ "parser/media_condition_test.cc", "parser/sizes_attribute_parser_test.cc", "parser/sizes_calc_parser_test.cc", + "properties/css_exposure_test.cc", "properties/css_parsing_utils_test.cc", "properties/css_property_ref_test.cc", "properties/css_property_test.cc",
diff --git a/third_party/blink/renderer/core/css/css_computed_style_declaration.cc b/third_party/blink/renderer/core/css/css_computed_style_declaration.cc index 94f15165..b39e2e1 100644 --- a/third_party/blink/renderer/core/css/css_computed_style_declaration.cc +++ b/third_party/blink/renderer/core/css/css_computed_style_declaration.cc
@@ -229,7 +229,7 @@ CSSComputedStyleDeclaration::ComputableProperties() { DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { - CSSProperty::FilterEnabledCSSPropertiesIntoVector( + CSSProperty::FilterWebExposedCSSPropertiesIntoVector( kComputedPropertyArray, base::size(kComputedPropertyArray), properties); } return properties;
diff --git a/third_party/blink/renderer/core/css/css_property_value_set.cc b/third_party/blink/renderer/core/css/css_property_value_set.cc index 1e4ae80..a4984eb 100644 --- a/third_party/blink/renderer/core/css/css_property_value_set.cc +++ b/third_party/blink/renderer/core/css/css_property_value_set.cc
@@ -131,7 +131,7 @@ // Only enabled properties should be part of the style. #if DCHECK_IS_ON() DCHECK(!result || - CSSProperty::Get(resolveCSSPropertyID(property_id)).IsEnabled()); + CSSProperty::Get(resolveCSSPropertyID(property_id)).IsWebExposed()); #endif return result; }
diff --git a/third_party/blink/renderer/core/css/css_selector_watch.cc b/third_party/blink/renderer/core/css/css_selector_watch.cc index f159a22..6e143c9 100644 --- a/third_party/blink/renderer/core/css/css_selector_watch.cc +++ b/third_party/blink/renderer/core/css/css_selector_watch.cc
@@ -72,7 +72,7 @@ if (timer_expirations_ < 1) { timer_expirations_++; - callback_selector_change_timer_.StartOneShot(TimeDelta(), FROM_HERE); + callback_selector_change_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); return; } if (GetSupplementable()->GetFrame()) { @@ -131,7 +131,8 @@ } else { timer_expirations_ = 0; if (!callback_selector_change_timer_.IsActive()) { - callback_selector_change_timer_.StartOneShot(TimeDelta(), FROM_HERE); + callback_selector_change_timer_.StartOneShot(base::TimeDelta(), + FROM_HERE); } } }
diff --git a/third_party/blink/renderer/core/css/css_style_declaration.cc b/third_party/blink/renderer/core/css/css_style_declaration.cc index d251d2b5..fcfe968 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration.cc +++ b/third_party/blink/renderer/core/css/css_style_declaration.cc
@@ -140,9 +140,9 @@ if (unresolved_property == CSSPropertyID::kVariable) unresolved_property = CSSPropertyID::kInvalid; map.insert(name, unresolved_property); - DCHECK( - !isValidCSSPropertyID(unresolved_property) || - CSSProperty::Get(resolveCSSPropertyID(unresolved_property)).IsEnabled()); + DCHECK(!isValidCSSPropertyID(unresolved_property) || + CSSProperty::Get(resolveCSSPropertyID(unresolved_property)) + .IsWebExposed()); return unresolved_property; } @@ -195,13 +195,13 @@ for (CSSPropertyID property_id : CSSPropertyIDList()) { const CSSProperty& property_class = CSSProperty::Get(resolveCSSPropertyID(property_id)); - if (property_class.IsEnabled()) + if (property_class.IsWebExposed()) property_names.push_back(property_class.GetJSPropertyName()); } for (CSSPropertyID property_id : kCSSPropertyAliasList) { const CSSUnresolvedProperty* property_class = CSSUnresolvedProperty::GetAliasProperty(property_id); - if (property_class->IsEnabled()) + if (property_class->IsWebExposed()) property_names.push_back(property_class->GetJSPropertyName()); } std::sort(property_names.begin(), property_names.end(),
diff --git a/third_party/blink/renderer/core/css/dom_window_css.cc b/third_party/blink/renderer/core/css/dom_window_css.cc index c4684eb..593d399 100644 --- a/third_party/blink/renderer/core/css/dom_window_css.cc +++ b/third_party/blink/renderer/core/css/dom_window_css.cc
@@ -61,8 +61,8 @@ } #if DCHECK_IS_ON() - DCHECK( - CSSProperty::Get(resolveCSSPropertyID(unresolved_property)).IsEnabled()); + DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property)) + .IsWebExposed()); #endif // This will return false when !important is present
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser.cc b/third_party/blink/renderer/core/css/parser/css_property_parser.cc index 587d60b..57c513db 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser.cc
@@ -168,6 +168,12 @@ return false; } +static inline bool IsExposedInMode(const CSSProperty& property, + CSSParserMode mode) { + return mode == kUASheetMode ? property.IsUAExposed() + : property.IsWebExposed(); +} + template <typename CharacterType> static CSSPropertyID UnresolvedCSSPropertyID(const CharacterType* property_name, unsigned length, @@ -196,9 +202,8 @@ CSSPropertyID property_id = static_cast<CSSPropertyID>(hash_table_entry->id); const CSSProperty& property = CSSProperty::Get(resolveCSSPropertyID(property_id)); - bool enabled = - property.IsEnabled() || (property.IsInternal() && mode == kUASheetMode); - return enabled ? property_id : CSSPropertyID::kInvalid; + bool exposed = IsExposedInMode(property, mode); + return exposed ? property_id : CSSPropertyID::kInvalid; } CSSPropertyID unresolvedCSSPropertyID(const String& string) {
diff --git a/third_party/blink/renderer/core/css/properties/css_exposure.h b/third_party/blink/renderer/core/css/properties/css_exposure.h new file mode 100644 index 0000000..ed17637 --- /dev/null +++ b/third_party/blink/renderer/core/css/properties/css_exposure.h
@@ -0,0 +1,32 @@ +// Copyright 2019 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 THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_ + +namespace blink { + +// Describes whether a property is exposed to author/user style sheets, +// UA style sheets, or not at all. +enum class CSSExposure { + // The property can't be used anywhere, i.e. it's disabled. + kNone, + // The property may be used in UA stylesheets, but not in author and user + // stylesheets, and the property is otherwise not visible to the author. + kUA, + // The property is "web exposed", which means it's available everywhere. + kWeb +}; + +inline bool IsUAExposed(CSSExposure exposure) { + return exposure >= CSSExposure::kUA; +} + +inline bool IsWebExposed(CSSExposure exposure) { + return exposure == CSSExposure::kWeb; +} + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_
diff --git a/third_party/blink/renderer/core/css/properties/css_exposure_test.cc b/third_party/blink/renderer/core/css/properties/css_exposure_test.cc new file mode 100644 index 0000000..6846ea9 --- /dev/null +++ b/third_party/blink/renderer/core/css/properties/css_exposure_test.cc
@@ -0,0 +1,22 @@ +// Copyright 2019 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 "third_party/blink/renderer/core/css/properties/css_exposure.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +TEST(CSSExposureTest, IsUAExposed) { + EXPECT_FALSE(IsUAExposed(CSSExposure::kNone)); + EXPECT_TRUE(IsUAExposed(CSSExposure::kUA)); + EXPECT_TRUE(IsUAExposed(CSSExposure::kWeb)); +} + +TEST(CSSExposureTest, IsWebExposed) { + EXPECT_FALSE(IsWebExposed(CSSExposure::kNone)); + EXPECT_FALSE(IsWebExposed(CSSExposure::kUA)); + EXPECT_TRUE(IsWebExposed(CSSExposure::kWeb)); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc index 99f6b5f..7f7525dc 100644 --- a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc +++ b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
@@ -2577,7 +2577,7 @@ unresolved_property != CSSPropertyID::kVariable) { #if DCHECK_IS_ON() DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property)) - .IsEnabled()); + .IsWebExposed()); #endif range.ConsumeIncludingWhitespace(); return MakeGarbageCollected<CSSCustomIdentValue>(unresolved_property);
diff --git a/third_party/blink/renderer/core/css/properties/css_property.cc b/third_party/blink/renderer/core/css/properties/css_property.cc index ac9a241..5726b816 100644 --- a/third_party/blink/renderer/core/css/properties/css_property.cc +++ b/third_party/blink/renderer/core/css/properties/css_property.cc
@@ -54,13 +54,13 @@ style, svg_style, layout_object, styled_node, allow_visited_style); } -void CSSProperty::FilterEnabledCSSPropertiesIntoVector( +void CSSProperty::FilterWebExposedCSSPropertiesIntoVector( const CSSPropertyID* properties, size_t propertyCount, Vector<const CSSProperty*>& outVector) { for (unsigned i = 0; i < propertyCount; i++) { const CSSProperty& property = Get(properties[i]); - if (property.IsEnabled()) + if (property.IsWebExposed()) outVector.push_back(&property); } }
diff --git a/third_party/blink/renderer/core/css/properties/css_property.h b/third_party/blink/renderer/core/css/properties/css_property.h index 7254e3c..4abe4eb 100644 --- a/third_party/blink/renderer/core/css/properties/css_property.h +++ b/third_party/blink/renderer/core/css/properties/css_property.h
@@ -45,12 +45,13 @@ bool IsLonghand() const { return flags_ & kLonghand; } bool IsInherited() const { return flags_ & kInherited; } bool IsVisited() const { return flags_ & kVisited; } - bool IsInternal() const { return flags_ & kInternal; } bool IsRepeated() const { return repetition_separator_ != '\0'; } char RepetitionSeparator() const { return repetition_separator_; } - virtual bool IsAffectedByAll() const { return IsEnabled() && IsProperty(); } + virtual bool IsAffectedByAll() const { + return IsWebExposed() && IsProperty(); + } virtual bool IsLayoutDependentProperty() const { return false; } virtual bool IsLayoutDependent(const ComputedStyle* style, LayoutObject* layout_object) const { @@ -81,9 +82,10 @@ return *this; } virtual const CSSProperty* GetVisitedProperty() const { return nullptr; } - static void FilterEnabledCSSPropertiesIntoVector(const CSSPropertyID*, - size_t length, - Vector<const CSSProperty*>&); + static void FilterWebExposedCSSPropertiesIntoVector( + const CSSPropertyID*, + size_t length, + Vector<const CSSProperty*>&); protected: enum Flag : uint16_t { @@ -98,8 +100,7 @@ // are permitted in :visited styles. They are used to handle and store the // computed value as seen by painting (as opposed to the computed value // seen by CSSOM, which is represented by the unvisited property). - kVisited = 1 << 7, - kInternal = 1 << 8 + kVisited = 1 << 7 }; constexpr CSSProperty(CSSPropertyID property_id,
diff --git a/third_party/blink/renderer/core/css/properties/css_property_test.cc b/third_party/blink/renderer/core/css/properties/css_property_test.cc index 5941004..07aa78c 100644 --- a/third_party/blink/renderer/core/css/properties/css_property_test.cc +++ b/third_party/blink/renderer/core/css/properties/css_property_test.cc
@@ -5,15 +5,28 @@ #include "third_party/blink/renderer/core/css/properties/css_property.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/css/css_property_names.h" +#include "third_party/blink/renderer/core/css/properties/css_property_instances.h" namespace blink { -TEST(CSSPropertyTest, VisitedPropertiesAreDisabled) { +TEST(CSSPropertyTest, VisitedPropertiesAreNotWebExposed) { for (CSSPropertyID property_id : CSSPropertyIDList()) { const CSSProperty& property = CSSProperty::Get(property_id); - // "Visited" properties are internal, and should never be enabled. - EXPECT_TRUE(!property.IsVisited() || !property.IsEnabled()); + EXPECT_TRUE(!property.IsVisited() || !property.IsWebExposed()); } } +TEST(CSSPropertyTest, GetVisitedPropertyOnlyReturnsVisitedProperties) { + for (CSSPropertyID property_id : CSSPropertyIDList()) { + const CSSProperty& property = CSSProperty::Get(property_id); + const CSSProperty* visited = property.GetVisitedProperty(); + EXPECT_TRUE(!visited || visited->IsVisited()); + } +} + +TEST(CSSPropertyTest, InternalEffectiveZoomNotWebExposed) { + const CSSProperty& property = GetCSSPropertyInternalEffectiveZoom(); + EXPECT_FALSE(property.IsWebExposed()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/css/properties/css_unresolved_property.h b/third_party/blink/renderer/core/css/properties/css_unresolved_property.h index 3011c84..9abed9f 100644 --- a/third_party/blink/renderer/core/css/properties/css_unresolved_property.h +++ b/third_party/blink/renderer/core/css/properties/css_unresolved_property.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_UNRESOLVED_PROPERTY_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_UNRESOLVED_PROPERTY_H_ +#include "third_party/blink/renderer/core/css/properties/css_exposure.h" #include "third_party/blink/renderer/core/css/properties/css_property_instances.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -18,7 +19,9 @@ static const CSSUnresolvedProperty& Get(CSSPropertyID); static const CSSUnresolvedProperty* GetAliasProperty(CSSPropertyID); - virtual bool IsEnabled() const { return true; } + bool IsWebExposed() const { return blink::IsWebExposed(Exposure()); } + bool IsUAExposed() const { return blink::IsUAExposed(Exposure()); } + virtual CSSExposure Exposure() const { return CSSExposure::kWeb; } virtual bool IsResolvedProperty() const { return false; } virtual const char* GetPropertyName() const { NOTREACHED();
diff --git a/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc index 7047250..4228f5f 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc
@@ -7827,7 +7827,7 @@ unresolved_property != CSSPropertyID::kVariable) { #if DCHECK_IS_ON() DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property)) - .IsEnabled()); + .IsWebExposed()); #endif // Now "all" is used by both CSSValue and CSSPropertyValue. // Need to return nullptr when currentValue is CSSPropertyID::kAll.
diff --git a/third_party/blink/renderer/core/css/style_property_serializer.cc b/third_party/blink/renderer/core/css/style_property_serializer.cc index 0d77885..d338cbd 100644 --- a/third_party/blink/renderer/core/css/style_property_serializer.cc +++ b/third_party/blink/renderer/core/css/style_property_serializer.cc
@@ -228,8 +228,8 @@ const CSSProperty& property_class = property.Property(); CSSPropertyID property_id = property_class.PropertyID(); - // Only enabled properties should be part of the style. - DCHECK(property_class.IsEnabled()); + // Only web exposed properties should be part of the style. + DCHECK(property_class.IsWebExposed()); // All shorthand properties should have been expanded at parse time. DCHECK(property_set_.IsDescriptorContext() || (property_class.IsProperty() && !property_class.IsShorthand()));
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc b/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc index d9e810d..8749fb6b 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc +++ b/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc
@@ -35,8 +35,8 @@ void ResetDeadlineForTesting(YieldingDisplayLockBudget& budget, const LifecycleData& lifecycle_data) { budget.deadline_ = - CurrentTimeTicks() + - TimeDelta::FromMillisecondsD(budget.GetCurrentBudgetMs(lifecycle_data)); + CurrentTimeTicks() + base::TimeDelta::FromMillisecondsD( + budget.GetCurrentBudgetMs(lifecycle_data)); } void ResetBudget(std::unique_ptr<DisplayLockBudget> budget, @@ -365,8 +365,8 @@ EXPECT_TRUE(budget.NeedsLifecycleUpdates()); // Advancing the clock a bit will make us still want to the phases. - test_task_runner_->FastForwardBy( - TimeDelta::FromMillisecondsD(GetBudgetMs(budget, lifecycle_data) / 2)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD( + GetBudgetMs(budget, lifecycle_data) / 2)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle, lifecycle_data)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout, @@ -376,7 +376,7 @@ // However, once we're out of budget, we will only do the next phase. test_task_runner_->FastForwardBy( - TimeDelta::FromMillisecondsD(GetBudgetMs(budget, lifecycle_data))); + base::TimeDelta::FromMillisecondsD(GetBudgetMs(budget, lifecycle_data))); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle, lifecycle_data)); @@ -409,8 +409,8 @@ // Now that we're out of budget, phases performed previously should remain // true. - test_task_runner_->FastForwardBy( - TimeDelta::FromMillisecondsD(GetBudgetMs(budget, lifecycle_data) * 2)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD( + GetBudgetMs(budget, lifecycle_data) * 2)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle, lifecycle_data)); EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout, @@ -433,8 +433,8 @@ lifecycle_data)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint, lifecycle_data)); - test_task_runner_->FastForwardBy( - TimeDelta::FromMillisecondsD(GetBudgetMs(budget, lifecycle_data) * 2)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD( + GetBudgetMs(budget, lifecycle_data) * 2)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle, lifecycle_data)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout, @@ -454,7 +454,7 @@ lifecycle_data)); EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint, lifecycle_data)); - test_task_runner_->FastForwardBy(TimeDelta::FromMillisecondsD(10000)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD(10000)); } } @@ -525,7 +525,7 @@ EXPECT_TRUE(parent->NeedsStyleRecalc() || parent->ChildNeedsStyleRecalc()); EXPECT_TRUE(element->NeedsStyleRecalc() || element->ChildNeedsStyleRecalc()); - test_task_runner_->FastForwardBy(TimeDelta::FromMillisecondsD( + test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD( GetBudgetMs(*budget, GetDocument().View()->CurrentLifecycleData()) * 2)); EXPECT_TRUE( budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_context.cc b/third_party/blink/renderer/core/display_lock/display_lock_context.cc index c15153b..128b423 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_context.cc +++ b/third_party/blink/renderer/core/display_lock/display_lock_context.cc
@@ -843,7 +843,7 @@ *GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI), FROM_HERE, WTF::Bind(&DisplayLockContext::TriggerTimeout, WrapWeakPersistent(this)), - TimeDelta::FromMillisecondsD(delay)); + base::TimeDelta::FromMillisecondsD(delay)); } void DisplayLockContext::CancelTimeoutTask() {
diff --git a/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc b/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc index 5f76384a..ea45591 100644 --- a/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc +++ b/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc
@@ -44,8 +44,9 @@ const LifecycleData& lifecycle_data) { if (first_lifecycle_count_ == 0) first_lifecycle_count_ = lifecycle_data.count; - deadline_ = lifecycle_data.start_time + - TimeDelta::FromMillisecondsD(GetCurrentBudgetMs(lifecycle_data)); + deadline_ = + lifecycle_data.start_time + + base::TimeDelta::FromMillisecondsD(GetCurrentBudgetMs(lifecycle_data)); // Figure out the next phase we would run. If we had completed a phase before, // then we should try to complete the next one, otherwise we'll start with the @@ -79,7 +80,7 @@ double YieldingDisplayLockBudget::GetCurrentBudgetMs( const LifecycleData& lifecycle_data) const { int lifecycle_count = lifecycle_data.count - first_lifecycle_count_ + 1; - if (TimeTicks::IsHighResolution()) { + if (base::TimeTicks::IsHighResolution()) { if (lifecycle_count < 3) return 4.; if (lifecycle_count < 10)
diff --git a/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h b/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h index 08e1a4db..06e0cfa 100644 --- a/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h +++ b/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h
@@ -39,7 +39,7 @@ private: unsigned first_lifecycle_count_ = 0; - TimeTicks deadline_; + base::TimeTicks deadline_; base::Optional<Phase> last_completed_phase_; Phase next_phase_from_start_of_lifecycle_ = Phase::kFirst; };
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index 3cb3fbaa..017ac85 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -2583,7 +2583,7 @@ void Document::ClearFocusedElementSoon() { if (!clear_focused_element_timer_.IsActive()) - clear_focused_element_timer_.StartOneShot(TimeDelta(), FROM_HERE); + clear_focused_element_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void Document::ClearFocusedElementTimerFired(TimerBase*) { @@ -2759,14 +2759,13 @@ } void Document::Shutdown() { - if (num_canvases_ > 0) - UMA_HISTOGRAM_COUNTS_100("Blink.Canvas.NumCanvasesPerPage", num_canvases_); TRACE_EVENT0("blink", "Document::shutdown"); CHECK(!frame_ || frame_->Tree().ChildCount() == 0); if (!IsActive()) return; - GetViewportData().Shutdown(); + // An active Document must have an associated frame. + CHECK(frame_); // Frame navigation can cause a new Document to be attached. Don't allow that, // since that will cause a situation where LocalFrame still has a Document @@ -2777,12 +2776,26 @@ // Defer plugin dispose to avoid plugins trying to run script inside // ScriptForbiddenScope, which will crash the renderer after // https://crrev.com/200984 + // TODO(dcheng): This is a temporary workaround, Document::Shutdown() should + // not be running script at all. HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; - // Don't allow script to run in the middle of detachLayoutTree() because a + // Don't allow script to run in the middle of DetachLayoutTree() because a // detaching Document is not in a consistent state. ScriptForbiddenScope forbid_script; lifecycle_.AdvanceTo(DocumentLifecycle::kStopping); + + // Do not add code before this without a documented reason. A postcondition of + // Shutdown() is that |frame_| must not have an attached Document. Allowing + // script execution when the Document is shutting down can make it easy to + // accidentally violate this condition, and the ordering of the scopers above + // is subtle due to legacy interactions with plugins. + + if (num_canvases_ > 0) + UMA_HISTOGRAM_COUNTS_100("Blink.Canvas.NumCanvasesPerPage", num_canvases_); + + GetViewportData().Shutdown(); + View()->Dispose(); // TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes. CHECK(!View()->IsAttached()); @@ -3643,9 +3656,9 @@ auto& before_unload_event = *MakeGarbageCollected<BeforeUnloadEvent>(); before_unload_event.initEvent(event_type_names::kBeforeunload, false, true); load_event_progress_ = kBeforeUnloadEventInProgress; - const TimeTicks beforeunload_event_start = CurrentTimeTicks(); + const base::TimeTicks beforeunload_event_start = CurrentTimeTicks(); dom_window_->DispatchEvent(before_unload_event, this); - const TimeTicks beforeunload_event_end = CurrentTimeTicks(); + const base::TimeTicks beforeunload_event_end = CurrentTimeTicks(); load_event_progress_ = kBeforeUnloadEventCompleted; DEFINE_STATIC_LOCAL( CustomCountHistogram, beforeunload_histogram, @@ -3702,10 +3715,10 @@ String text = before_unload_event.returnValue(); beforeunload_dialog_histogram.Count( BeforeUnloadDialogHistogramEnum::kShowDialog); - const TimeTicks beforeunload_confirmpanel_start = CurrentTimeTicks(); + const base::TimeTicks beforeunload_confirmpanel_start = CurrentTimeTicks(); did_allow_navigation = chrome_client->OpenBeforeUnloadConfirmPanel(text, frame_, is_reload); - const TimeTicks beforeunload_confirmpanel_end = CurrentTimeTicks(); + const base::TimeTicks beforeunload_confirmpanel_end = CurrentTimeTicks(); if (did_allow_navigation) { // Only record when a navigation occurs, since we want to understand // the impact of the before unload dialog on overall input to navigation. @@ -3733,11 +3746,11 @@ if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { - const TimeTicks pagehide_event_start = CurrentTimeTicks(); + const base::TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( *PageTransitionEvent::Create(event_type_names::kPagehide, false), this); - const TimeTicks pagehide_event_end = CurrentTimeTicks(); + const base::TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); @@ -3754,10 +3767,12 @@ if (page_visible) { // Dispatch visibilitychange event, but don't bother doing // other notifications as we're about to be unloaded. - const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); + const base::TimeTicks pagevisibility_hidden_event_start = + CurrentTimeTicks(); DispatchEvent( *Event::CreateBubble(event_type_names::kVisibilitychange)); - const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); + const base::TimeTicks pagevisibility_hidden_event_end = + CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); @@ -3777,10 +3792,10 @@ if (timing && timing->UnloadEventStart().is_null() && timing->UnloadEventEnd().is_null()) { DCHECK(!timing->NavigationStart().is_null()); - const TimeTicks unload_event_start = CurrentTimeTicks(); + const base::TimeTicks unload_event_start = CurrentTimeTicks(); timing->MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); - const TimeTicks unload_event_end = CurrentTimeTicks(); + const base::TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); @@ -3796,11 +3811,11 @@ } void Document::DispatchFreezeEvent() { - const TimeTicks freeze_event_start = CurrentTimeTicks(); + const base::TimeTicks freeze_event_start = CurrentTimeTicks(); SetFreezingInProgress(true); DispatchEvent(*Event::Create(event_type_names::kFreeze)); SetFreezingInProgress(false); - const TimeTicks freeze_event_end = CurrentTimeTicks(); + const base::TimeTicks freeze_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, freeze_histogram, ("DocumentEventTiming.FreezeDuration", 0, 10000000, 50)); freeze_histogram.CountMicroseconds(freeze_event_end - freeze_event_start); @@ -6165,7 +6180,7 @@ // on cache access since that could lead to huge caches being kept alive // indefinitely by something innocuous like JS setting .innerHTML repeatedly // on a timer. - element_data_cache_clear_timer_.StartOneShot(TimeDelta::FromSeconds(10), + element_data_cache_clear_timer_.StartOneShot(base::TimeDelta::FromSeconds(10), FROM_HERE); // Parser should have picked up all preloads by now @@ -7006,7 +7021,7 @@ void Document::CheckLoadEventSoon() { if (GetFrame() && !load_event_delay_timer_.IsActive()) - load_event_delay_timer_.StartOneShot(TimeDelta(), FROM_HERE); + load_event_delay_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } bool Document::IsDelayingLoadEvent() { @@ -7030,7 +7045,7 @@ // FIXME: Remove this timer once we don't need to compute layout to load // plugins. if (!plugin_loading_timer_.IsActive()) - plugin_loading_timer_.StartOneShot(TimeDelta(), FROM_HERE); + plugin_loading_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void Document::PluginLoadingTimerFired(TimerBase*) { @@ -7367,7 +7382,7 @@ // We add a slight delay because this could be called rapidly. if (!did_associate_form_controls_timer_.IsActive()) { did_associate_form_controls_timer_.StartOneShot( - TimeDelta::FromMilliseconds(300), FROM_HERE); + base::TimeDelta::FromMilliseconds(300), FROM_HERE); } } @@ -8177,6 +8192,10 @@ loader->GetUseCounterHelper().ClearMeasurementForTesting(feature); } +void Document::Dispose() { + navigation_initiator_bindings_.CloseAllBindings(); +} + template class CORE_TEMPLATE_EXPORT Supplement<Document>; } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/document.h b/third_party/blink/renderer/core/dom/document.h index b04c1a2..271b16c4 100644 --- a/third_party/blink/renderer/core/dom/document.h +++ b/third_party/blink/renderer/core/dom/document.h
@@ -251,6 +251,7 @@ public mojom::blink::NavigationInitiator { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(Document); + USING_PRE_FINALIZER(Document, Dispose); public: // Factory for web-exposed Document constructor. The argument document must be @@ -1717,6 +1718,8 @@ Element* new_focused_element); void DisplayNoneChangedForFrame(); + void Dispose(); + DocumentLifecycle lifecycle_; bool evaluate_media_queries_on_style_recalc_;
diff --git a/third_party/blink/renderer/core/dom/document_parser_timing.cc b/third_party/blink/renderer/core/dom/document_parser_timing.cc index 044ea56..49395e9 100644 --- a/third_party/blink/renderer/core/dom/document_parser_timing.cc +++ b/third_party/blink/renderer/core/dom/document_parser_timing.cc
@@ -44,7 +44,7 @@ } void DocumentParserTiming::RecordParserBlockedOnScriptLoadDuration( - TimeDelta duration, + base::TimeDelta duration, bool script_inserted_via_document_write) { if (parser_detached_ || parser_start_.is_null() || !parser_stop_.is_null()) return; @@ -55,7 +55,7 @@ } void DocumentParserTiming::RecordParserBlockedOnScriptExecutionDuration( - TimeDelta duration, + base::TimeDelta duration, bool script_inserted_via_document_write) { if (parser_detached_ || parser_start_.is_null() || !parser_stop_.is_null()) return;
diff --git a/third_party/blink/renderer/core/dom/document_parser_timing.h b/third_party/blink/renderer/core/dom/document_parser_timing.h index 98dbc0b1..c015baa4 100644 --- a/third_party/blink/renderer/core/dom/document_parser_timing.h +++ b/third_party/blink/renderer/core/dom/document_parser_timing.h
@@ -51,7 +51,7 @@ // called multiple times, once for each time the parser yields on a script // load. void RecordParserBlockedOnScriptLoadDuration( - TimeDelta duration, + base::TimeDelta duration, bool script_inserted_via_document_write); // Record a duration of time that the parser spent executing a script. @@ -59,19 +59,19 @@ // was inserted via document.write. This may be called multiple times, once // for each time the parser executes a script. void RecordParserBlockedOnScriptExecutionDuration( - TimeDelta duration, + base::TimeDelta duration, bool script_inserted_via_document_write); // The getters below return monotonically-increasing time, or zero if the // given parser event has not yet occurred. See the comments for // MonotonicallyIncreasingTime in platform/wtf/time.h for additional details. - TimeTicks ParserStart() const { return parser_start_; } - TimeTicks ParserStop() const { return parser_stop_; } + base::TimeTicks ParserStart() const { return parser_start_; } + base::TimeTicks ParserStop() const { return parser_stop_; } // Returns the sum of all blocking script load durations reported via // recordParseBlockedOnScriptLoadDuration. - TimeDelta ParserBlockedOnScriptLoadDuration() const { + base::TimeDelta ParserBlockedOnScriptLoadDuration() const { return parser_blocked_on_script_load_duration_; } @@ -79,13 +79,13 @@ // document.write reported via recordParseBlockedOnScriptLoadDuration. Note // that some uncommon cases are not currently covered by this method. See // crbug/600711 for details. - TimeDelta ParserBlockedOnScriptLoadFromDocumentWriteDuration() const { + base::TimeDelta ParserBlockedOnScriptLoadFromDocumentWriteDuration() const { return parser_blocked_on_script_load_from_document_write_duration_; } // Returns the sum of all script execution durations reported via // recordParseBlockedOnScriptExecutionDuration. - TimeDelta ParserBlockedOnScriptExecutionDuration() const { + base::TimeDelta ParserBlockedOnScriptExecutionDuration() const { return parser_blocked_on_script_execution_duration_; } @@ -93,7 +93,8 @@ // document.write reported via recordParseBlockedOnScriptExecutionDuration. // Note that some uncommon cases are not currently covered by this method. See // crbug/600711 for details. - TimeDelta ParserBlockedOnScriptExecutionFromDocumentWriteDuration() const { + base::TimeDelta ParserBlockedOnScriptExecutionFromDocumentWriteDuration() + const { return parser_blocked_on_script_execution_from_document_write_duration_; } @@ -102,12 +103,13 @@ private: void NotifyDocumentParserTimingChanged(); - TimeTicks parser_start_; - TimeTicks parser_stop_; - TimeDelta parser_blocked_on_script_load_duration_; - TimeDelta parser_blocked_on_script_load_from_document_write_duration_; - TimeDelta parser_blocked_on_script_execution_duration_; - TimeDelta parser_blocked_on_script_execution_from_document_write_duration_; + base::TimeTicks parser_start_; + base::TimeTicks parser_stop_; + base::TimeDelta parser_blocked_on_script_load_duration_; + base::TimeDelta parser_blocked_on_script_load_from_document_write_duration_; + base::TimeDelta parser_blocked_on_script_execution_duration_; + base::TimeDelta + parser_blocked_on_script_execution_from_document_write_duration_; bool parser_detached_ = false; DISALLOW_COPY_AND_ASSIGN(DocumentParserTiming); };
diff --git a/third_party/blink/renderer/core/dom/document_statistics_collector.cc b/third_party/blink/renderer/core/dom/document_statistics_collector.cc index 308b4f94..8e196e7 100644 --- a/third_party/blink/renderer/core/dom/document_statistics_collector.cc +++ b/third_party/blink/renderer/core/dom/document_statistics_collector.cc
@@ -205,7 +205,7 @@ features.is_mobile_friendly = IsMobileFriendly(document); - TimeTicks start_time = CurrentTimeTicks(); + base::TimeTicks start_time = CurrentTimeTicks(); // This should be cheap since collectStatistics is only called right after // layout. @@ -215,7 +215,7 @@ CollectFeatures(*body, features); features.open_graph = HasOpenGraphArticle(*head); - TimeDelta elapsed_time = CurrentTimeTicks() - start_time; + base::TimeDelta elapsed_time = CurrentTimeTicks() - start_time; DEFINE_STATIC_LOCAL(CustomCountHistogram, distillability_histogram, ("WebCore.DistillabilityUs", 1, 1000000, 50));
diff --git a/third_party/blink/renderer/core/dom/document_timing.h b/third_party/blink/renderer/core/dom/document_timing.h index 5aed897..e7bd49ec 100644 --- a/third_party/blink/renderer/core/dom/document_timing.h +++ b/third_party/blink/renderer/core/dom/document_timing.h
@@ -48,16 +48,16 @@ void MarkFirstLayout(); // These return monotonically-increasing time. - TimeTicks DomLoading() const { return dom_loading_; } - TimeTicks DomInteractive() const { return dom_interactive_; } - TimeTicks DomContentLoadedEventStart() const { + base::TimeTicks DomLoading() const { return dom_loading_; } + base::TimeTicks DomInteractive() const { return dom_interactive_; } + base::TimeTicks DomContentLoadedEventStart() const { return dom_content_loaded_event_start_; } - TimeTicks DomContentLoadedEventEnd() const { + base::TimeTicks DomContentLoadedEventEnd() const { return dom_content_loaded_event_end_; } - TimeTicks DomComplete() const { return dom_complete_; } - TimeTicks FirstLayout() const { return first_layout_; } + base::TimeTicks DomComplete() const { return dom_complete_; } + base::TimeTicks FirstLayout() const { return first_layout_; } void Trace(Visitor*); @@ -65,12 +65,12 @@ LocalFrame* GetFrame() const; void NotifyDocumentTimingChanged(); - TimeTicks dom_loading_; - TimeTicks dom_interactive_; - TimeTicks dom_content_loaded_event_start_; - TimeTicks dom_content_loaded_event_end_; - TimeTicks dom_complete_; - TimeTicks first_layout_; + base::TimeTicks dom_loading_; + base::TimeTicks dom_interactive_; + base::TimeTicks dom_content_loaded_event_start_; + base::TimeTicks dom_content_loaded_event_end_; + base::TimeTicks dom_complete_; + base::TimeTicks first_layout_; Member<Document> document_; };
diff --git a/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h b/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h index 6a469ca..a2b872f 100644 --- a/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h +++ b/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h
@@ -21,12 +21,12 @@ } inline DOMHighResTimeStamp ConvertTimeTicksToDOMHighResTimeStamp( - TimeTicks time) { - return (time - TimeTicks()).InMillisecondsF(); + base::TimeTicks time) { + return (time - base::TimeTicks()).InMillisecondsF(); } inline DOMHighResTimeStamp ConvertTimeDeltaToDOMHighResTimeStamp( - TimeDelta delta) { + base::TimeDelta delta) { return delta.InMillisecondsF(); }
diff --git a/third_party/blink/renderer/core/dom/events/event.cc b/third_party/blink/renderer/core/dom/events/event.cc index 8e133a5..e3853943 100644 --- a/third_party/blink/renderer/core/dom/events/event.cc +++ b/third_party/blink/renderer/core/dom/events/event.cc
@@ -65,7 +65,7 @@ Event::Event(const AtomicString& event_type, Bubbles bubbles, Cancelable cancelable, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : Event(event_type, bubbles, cancelable, @@ -86,7 +86,7 @@ Bubbles bubbles, Cancelable cancelable, ComposedMode composed_mode, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : type_(event_type), bubbles_(bubbles == Bubbles::kYes), cancelable_(cancelable == Cancelable::kYes), @@ -109,7 +109,7 @@ Event::Event(const AtomicString& event_type, const EventInit* initializer, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : Event(event_type, initializer->bubbles() ? Bubbles::kYes : Bubbles::kNo, initializer->cancelable() ? Cancelable::kYes : Cancelable::kNo,
diff --git a/third_party/blink/renderer/core/dom/events/event.h b/third_party/blink/renderer/core/dom/events/event.h index caf97646..ba3b63d 100644 --- a/third_party/blink/renderer/core/dom/events/event.h +++ b/third_party/blink/renderer/core/dom/events/event.h
@@ -111,18 +111,18 @@ Bubbles, Cancelable, ComposedMode, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); Event(const AtomicString& type, Bubbles, Cancelable, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); Event(const AtomicString& type, Bubbles, Cancelable, ComposedMode = ComposedMode::kScoped); Event(const AtomicString& type, const EventInit*, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); Event(const AtomicString& type, const EventInit* init) : Event(type, init, CurrentTimeTicks()) {} ~Event() override; @@ -185,7 +185,7 @@ // using the platform timestamp (see |platform_time_stamp_|). // For more info see http://crbug.com/160524 double timeStamp(ScriptState*) const; - TimeTicks PlatformTimeStamp() const { return platform_time_stamp_; } + base::TimeTicks PlatformTimeStamp() const { return platform_time_stamp_; } void stopPropagation() { propagation_stopped_ = true; } void SetStopPropagation(bool stop_propagation) { @@ -356,7 +356,7 @@ // The monotonic platform time in seconds, for input events it is the // event timestamp provided by the host OS and reported in the original // WebInputEvent instance. - TimeTicks platform_time_stamp_; + base::TimeTicks platform_time_stamp_; }; #define DEFINE_EVENT_TYPE_CASTS(typeName) \
diff --git a/third_party/blink/renderer/core/dom/idle_deadline.cc b/third_party/blink/renderer/core/dom/idle_deadline.cc index 9a97ccb..49077ce4 100644 --- a/third_party/blink/renderer/core/dom/idle_deadline.cc +++ b/third_party/blink/renderer/core/dom/idle_deadline.cc
@@ -11,14 +11,14 @@ namespace blink { -IdleDeadline::IdleDeadline(TimeTicks deadline, CallbackType callback_type) +IdleDeadline::IdleDeadline(base::TimeTicks deadline, CallbackType callback_type) : deadline_(deadline), callback_type_(callback_type), clock_(base::DefaultTickClock::GetInstance()) {} double IdleDeadline::timeRemaining() const { - TimeDelta time_remaining = deadline_ - clock_->NowTicks(); - if (time_remaining < TimeDelta() || + base::TimeDelta time_remaining = deadline_ - clock_->NowTicks(); + if (time_remaining < base::TimeDelta() || ThreadScheduler::Current()->ShouldYieldForHighPriorityWork()) { return 0; }
diff --git a/third_party/blink/renderer/core/dom/idle_deadline.h b/third_party/blink/renderer/core/dom/idle_deadline.h index 23593a6..834c6eb22 100644 --- a/third_party/blink/renderer/core/dom/idle_deadline.h +++ b/third_party/blink/renderer/core/dom/idle_deadline.h
@@ -28,7 +28,7 @@ kMaxValue = kCalledByTimeout }; - IdleDeadline(TimeTicks deadline, CallbackType); + IdleDeadline(base::TimeTicks deadline, CallbackType); double timeRemaining() const; @@ -41,7 +41,7 @@ void SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; } private: - TimeTicks deadline_; + base::TimeTicks deadline_; CallbackType callback_type_; const base::TickClock* clock_; };
diff --git a/third_party/blink/renderer/core/dom/idle_deadline_test.cc b/third_party/blink/renderer/core/dom/idle_deadline_test.cc index 6510db9f..8116102 100644 --- a/third_party/blink/renderer/core/dom/idle_deadline_test.cc +++ b/third_party/blink/renderer/core/dom/idle_deadline_test.cc
@@ -86,20 +86,20 @@ TEST_F(IdleDeadlineTest, DeadlineInFuture) { auto* deadline = MakeGarbageCollected<IdleDeadline>( - TimeTicks() + TimeDelta::FromSecondsD(1.25), + base::TimeTicks() + base::TimeDelta::FromSecondsD(1.25), IdleDeadline::CallbackType::kCalledWhenIdle); deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock()); - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); // Note: the deadline is computed with reduced resolution. EXPECT_FLOAT_EQ(250.0, deadline->timeRemaining()); } TEST_F(IdleDeadlineTest, DeadlineInPast) { auto* deadline = MakeGarbageCollected<IdleDeadline>( - TimeTicks() + TimeDelta::FromSecondsD(0.75), + base::TimeTicks() + base::TimeDelta::FromSecondsD(0.75), IdleDeadline::CallbackType::kCalledWhenIdle); deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock()); - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); EXPECT_FLOAT_EQ(0, deadline->timeRemaining()); } @@ -108,10 +108,10 @@ ScopedSchedulerOverrider scheduler_overrider(&scheduler); auto* deadline = MakeGarbageCollected<IdleDeadline>( - TimeTicks() + TimeDelta::FromSecondsD(1.25), + base::TimeTicks() + base::TimeDelta::FromSecondsD(1.25), IdleDeadline::CallbackType::kCalledWhenIdle); deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock()); - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); EXPECT_FLOAT_EQ(0, deadline->timeRemaining()); }
diff --git a/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc b/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc index 4d47f46..8cd44b5 100644 --- a/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc +++ b/third_party/blink/renderer/core/dom/scripted_idle_task_controller.cc
@@ -34,7 +34,7 @@ static void IdleTaskFired( scoped_refptr<IdleRequestCallbackWrapper> callback_wrapper, - TimeTicks deadline) { + base::TimeTicks deadline) { if (ScriptedIdleTaskController* controller = callback_wrapper->Controller()) { // If we are going to yield immediately, reschedule the callback for @@ -122,7 +122,7 @@ DCHECK(idle_task); CallbackId id = NextCallbackId(); - TimeTicks queue_timestamp = TimeTicks::Now(); + base::TimeTicks queue_timestamp = base::TimeTicks::Now(); uint32_t timeout_millis = options->timeout(); idle_tasks_.Set(id, MakeGarbageCollected<QueuedIdleTask>( idle_task, queue_timestamp, timeout_millis)); @@ -153,7 +153,7 @@ FROM_HERE, WTF::Bind(&internal::IdleRequestCallbackWrapper::TimeoutFired, callback_wrapper), - TimeDelta::FromMilliseconds(timeout_millis)); + base::TimeDelta::FromMilliseconds(timeout_millis)); } } @@ -170,7 +170,7 @@ void ScriptedIdleTaskController::CallbackFired( CallbackId id, - TimeTicks deadline, + base::TimeTicks deadline, IdleDeadline::CallbackType callback_type) { if (!idle_tasks_.Contains(id)) return; @@ -190,7 +190,7 @@ void ScriptedIdleTaskController::RunCallback( CallbackId id, - TimeTicks deadline, + base::TimeTicks deadline, IdleDeadline::CallbackType callback_type) { DCHECK(!paused_); @@ -205,8 +205,8 @@ IdleTask* idle_task = queued_idle_task->task(); DCHECK(idle_task); - TimeTicks now = CurrentTimeTicks(); - TimeDelta allotted_time = std::max(deadline - now, TimeDelta()); + base::TimeTicks now = CurrentTimeTicks(); + base::TimeDelta allotted_time = std::max(deadline - now, base::TimeDelta()); probe::AsyncTask async_task(GetExecutionContext(), idle_task); probe::UserCallback probe(GetExecutionContext(), "requestIdleCallback", @@ -268,7 +268,7 @@ void ScriptedIdleTaskController::RecordIdleTaskMetrics( QueuedIdleTask* queued_idle_task, - TimeTicks run_timestamp, + base::TimeTicks run_timestamp, IdleDeadline::CallbackType callback_type) { UMA_HISTOGRAM_ENUMERATION( "WebCore.ScriptedIdleTaskController.IdleTaskCallbackType", callback_type); @@ -290,7 +290,7 @@ ScriptedIdleTaskController::QueuedIdleTask::QueuedIdleTask( IdleTask* idle_task, - TimeTicks queue_timestamp, + base::TimeTicks queue_timestamp, uint32_t timeout_millis) : task_(idle_task), queue_timestamp_(queue_timestamp),
diff --git a/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h b/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h index b5803ff..4138b60 100644 --- a/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h +++ b/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h
@@ -83,26 +83,26 @@ void ContextLifecycleStateChanged(mojom::FrameLifecycleState) override; void CallbackFired(CallbackId, - TimeTicks deadline, + base::TimeTicks deadline, IdleDeadline::CallbackType); private: class QueuedIdleTask : public GarbageCollectedFinalized<QueuedIdleTask> { public: QueuedIdleTask(IdleTask*, - TimeTicks queue_timestamp, + base::TimeTicks queue_timestamp, uint32_t timeout_millis); virtual ~QueuedIdleTask() = default; virtual void Trace(Visitor*); IdleTask* task() { return task_; } - TimeTicks queue_timestamp() const { return queue_timestamp_; } + base::TimeTicks queue_timestamp() const { return queue_timestamp_; } uint32_t timeout_millis() const { return timeout_millis_; } private: Member<IdleTask> task_; - TimeTicks queue_timestamp_; + base::TimeTicks queue_timestamp_; uint32_t timeout_millis_; }; @@ -121,10 +121,12 @@ !WTF::IsHashTraitsEmptyValue<Traits, CallbackId>(id); } - void RunCallback(CallbackId, TimeTicks deadline, IdleDeadline::CallbackType); + void RunCallback(CallbackId, + base::TimeTicks deadline, + IdleDeadline::CallbackType); void RecordIdleTaskMetrics(QueuedIdleTask*, - TimeTicks run_timestamp, + base::TimeTicks run_timestamp, IdleDeadline::CallbackType); ThreadScheduler* scheduler_; // Not owned.
diff --git a/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc b/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc index 445fffe..6148dac 100644 --- a/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc +++ b/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc
@@ -78,7 +78,7 @@ void SetV8Isolate(v8::Isolate* isolate) override {} - void RunIdleTask() { std::move(idle_task_).Run(TimeTicks()); } + void RunIdleTask() { std::move(idle_task_).Run(base::TimeTicks()); } bool HasIdleTask() const { return !!idle_task_; } private:
diff --git a/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc b/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc index f58b598..561d8784 100644 --- a/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc +++ b/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc
@@ -122,9 +122,9 @@ // reset it so it gets the Now() of the mock clock. token->ResetTimestampForTesting(); EXPECT_TRUE(token->HasGestures()); - test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75)); + test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75)); EXPECT_TRUE(token->HasGestures()); - test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75)); + test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75)); EXPECT_FALSE(token->HasGestures()); } @@ -141,15 +141,15 @@ // clock, reset it so it gets the Now() of the mock clock. token->ResetTimestampForTesting(); EXPECT_TRUE(token->HasGestures()); - test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75)); + test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75)); EXPECT_TRUE(token->HasGestures()); } { UserGestureIndicator user_gesture_scope(token.get()); - test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75)); + test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75)); EXPECT_TRUE(token->HasGestures()); - test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75)); + test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75)); EXPECT_FALSE(token->HasGestures()); } }
diff --git a/third_party/blink/renderer/core/editing/editing_style.cc b/third_party/blink/renderer/core/editing/editing_style.cc index 5999546..0ba2281d 100644 --- a/third_party/blink/renderer/core/editing/editing_style.cc +++ b/third_party/blink/renderer/core/editing/editing_style.cc
@@ -100,7 +100,7 @@ static const Vector<const CSSProperty*>& AllEditingProperties() { DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { - CSSProperty::FilterEnabledCSSPropertiesIntoVector( + CSSProperty::FilterWebExposedCSSPropertiesIntoVector( kStaticEditingProperties, base::size(kStaticEditingProperties), properties); for (wtf_size_t index = 0; index < properties.size(); index++) { @@ -116,7 +116,7 @@ static const Vector<const CSSProperty*>& InheritableEditingProperties() { DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { - CSSProperty::FilterEnabledCSSPropertiesIntoVector( + CSSProperty::FilterWebExposedCSSPropertiesIntoVector( kStaticEditingProperties, base::size(kStaticEditingProperties), properties); for (wtf_size_t index = 0; index < properties.size();) { @@ -704,7 +704,7 @@ static const Vector<const CSSProperty*>& BlockPropertiesVector() { DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ()); if (properties.IsEmpty()) { - CSSProperty::FilterEnabledCSSPropertiesIntoVector( + CSSProperty::FilterWebExposedCSSPropertiesIntoVector( kStaticBlockProperties, base::size(kStaticBlockProperties), properties); } return properties;
diff --git a/third_party/blink/renderer/core/editing/finder/find_task_controller.cc b/third_party/blink/renderer/core/editing/finder/find_task_controller.cc index 6a4da37..49dddafc 100644 --- a/third_party/blink/renderer/core/editing/finder/find_task_controller.cc +++ b/third_party/blink/renderer/core/editing/finder/find_task_controller.cc
@@ -22,7 +22,8 @@ namespace { const int kFindingTimeoutMS = 100; -constexpr TimeDelta kFindTaskTestTimeout = TimeDelta::FromSeconds(10); +constexpr base::TimeDelta kFindTaskTestTimeout = + base::TimeDelta::FromSeconds(10); } // namespace class FindTaskController::IdleFindTask @@ -73,9 +74,9 @@ PositionInFlatTree(), 0 /* match_count */); } - const TimeDelta time_available = - TimeDelta::FromMillisecondsD(deadline->timeRemaining()); - const TimeTicks start_time = CurrentTimeTicks(); + const base::TimeDelta time_available = + base::TimeDelta::FromMillisecondsD(deadline->timeRemaining()); + const base::TimeTicks start_time = CurrentTimeTicks(); Document& document = *controller_->GetLocalFrame()->GetDocument(); PositionInFlatTree search_start = @@ -147,7 +148,7 @@ break; } - const TimeDelta time_spent = CurrentTimeTicks() - start_time; + const base::TimeDelta time_spent = CurrentTimeTicks() - start_time; UMA_HISTOGRAM_TIMES("WebCore.FindInPage.ScopingTime", time_spent - time_available);
diff --git a/third_party/blink/renderer/core/editing/frame_caret.cc b/third_party/blink/renderer/core/editing/frame_caret.cc index b078ed88..f326a95 100644 --- a/third_party/blink/renderer/core/editing/frame_caret.cc +++ b/third_party/blink/renderer/core/editing/frame_caret.cc
@@ -116,7 +116,7 @@ if (caret_blink_timer_->IsActive()) return; - TimeDelta blink_interval = LayoutTheme::GetTheme().CaretBlinkInterval(); + base::TimeDelta blink_interval = LayoutTheme::GetTheme().CaretBlinkInterval(); if (!blink_interval.is_zero()) caret_blink_timer_->StartRepeating(blink_interval, FROM_HERE);
diff --git a/third_party/blink/renderer/core/editing/frame_caret_test.cc b/third_party/blink/renderer/core/editing/frame_caret_test.cc index afbee505e..11464cf 100644 --- a/third_party/blink/renderer/core/editing/frame_caret_test.cc +++ b/third_party/blink/renderer/core/editing/frame_caret_test.cc
@@ -43,7 +43,7 @@ caret.RecreateCaretBlinkTimerForTesting(task_runner.get()); const double kInterval = 10; LayoutTheme::GetTheme().SetCaretBlinkInterval( - TimeDelta::FromSecondsD(kInterval)); + base::TimeDelta::FromSecondsD(kInterval)); GetDocument().GetPage()->GetFocusController().SetActive(true); GetDocument().GetPage()->GetFocusController().SetFocused(true); GetDocument().body()->SetInnerHTMLFromString("<textarea>");
diff --git a/third_party/blink/renderer/core/editing/link_selection_test.cc b/third_party/blink/renderer/core/editing/link_selection_test.cc index 46b3e4f..5f0e04c 100644 --- a/third_party/blink/renderer/core/editing/link_selection_test.cc +++ b/third_party/blink/renderer/core/editing/link_selection_test.cc
@@ -191,7 +191,7 @@ ->LocalFrameRoot() .GetEventHandler() .ScheduleCursorUpdate(); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(50)); + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50)); const auto& cursor = main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting(); EXPECT_EQ(ui::CursorType::kHand, cursor.GetType()); @@ -203,7 +203,7 @@ ->LocalFrameRoot() .GetEventHandler() .ScheduleCursorUpdate(); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(50)); + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50)); const auto& cursor = main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting(); EXPECT_EQ(ui::CursorType::kPointer, cursor.GetType()); @@ -216,7 +216,7 @@ ->LocalFrameRoot() .GetEventHandler() .ScheduleCursorUpdate(); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(50)); + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50)); const auto& cursor = main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting(); EXPECT_EQ(ui::CursorType::kIBeam, cursor.GetType()); @@ -235,7 +235,7 @@ frame->GetPage()->GetContextMenuController().ClearContextMenu(); frame->LocalFrameRoot().GetEventHandler().ScheduleCursorUpdate(); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(50)); + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50)); const auto& cursor = main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting(); EXPECT_EQ(ui::CursorType::kHand, cursor.GetType());
diff --git a/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc b/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc index d0cb5f6..bcc19596 100644 --- a/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc +++ b/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc
@@ -28,13 +28,15 @@ namespace { -constexpr TimeDelta kColdModeTimerInterval = TimeDelta::FromMilliseconds(1000); -constexpr TimeDelta kConsecutiveColdModeTimerInterval = - TimeDelta::FromMilliseconds(200); +constexpr base::TimeDelta kColdModeTimerInterval = + base::TimeDelta::FromMilliseconds(1000); +constexpr base::TimeDelta kConsecutiveColdModeTimerInterval = + base::TimeDelta::FromMilliseconds(200); const int kHotModeRequestTimeoutMS = 200; const int kInvalidHandle = -1; const int kDummyHandleForForcedInvocation = -2; -constexpr TimeDelta kIdleSpellcheckTestTimeout = TimeDelta::FromSeconds(10); +constexpr base::TimeDelta kIdleSpellcheckTestTimeout = + base::TimeDelta::FromSeconds(10); } // namespace @@ -140,9 +142,9 @@ return; DCHECK(!cold_mode_timer_.IsActive()); - TimeDelta interval = state_ == State::kInColdModeInvocation - ? kConsecutiveColdModeTimerInterval - : kColdModeTimerInterval; + base::TimeDelta interval = state_ == State::kInColdModeInvocation + ? kConsecutiveColdModeTimerInterval + : kColdModeTimerInterval; cold_mode_timer_.StartOneShot(interval, FROM_HERE); state_ = State::kColdModeTimerStarted; }
diff --git a/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc b/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc index 05bea66..f6f1c7b 100644 --- a/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc +++ b/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc
@@ -198,8 +198,8 @@ if (!request) return false; - const TimeTicks current_request_time = CurrentTimeTicks(); - if (request_num == 0 && last_request_time_ > TimeTicks()) { + const base::TimeTicks current_request_time = CurrentTimeTicks(); + if (request_num == 0 && last_request_time_ > base::TimeTicks()) { UMA_HISTOGRAM_TIMES("WebCore.SpellChecker.RequestInterval", current_request_time - last_request_time_); } @@ -297,7 +297,7 @@ ClearProcessingRequest(); if (!request_queue_.IsEmpty()) - timer_to_process_queued_request_.StartOneShot(TimeDelta(), FROM_HERE); + timer_to_process_queued_request_.StartOneShot(base::TimeDelta(), FROM_HERE); } void SpellCheckRequester::DidCheckSucceed(
diff --git a/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h b/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h index 8a219668..c1c3508 100644 --- a/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h +++ b/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h
@@ -121,7 +121,7 @@ int last_request_sequence_; int last_processed_sequence_; - TimeTicks last_request_time_; + base::TimeTicks last_request_time_; TaskRunnerTimer<SpellCheckRequester> timer_to_process_queued_request_;
diff --git a/third_party/blink/renderer/core/events/drag_event.cc b/third_party/blink/renderer/core/events/drag_event.cc index 429daf9..fcfbedd 100644 --- a/third_party/blink/renderer/core/events/drag_event.cc +++ b/third_party/blink/renderer/core/events/drag_event.cc
@@ -15,7 +15,7 @@ DragEvent::DragEvent(const AtomicString& type, const DragEventInit* initializer, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType synthetic_event_type) : MouseEvent(type, initializer, platform_time_stamp, synthetic_event_type), data_transfer_(initializer->getDataTransfer()) {}
diff --git a/third_party/blink/renderer/core/events/drag_event.h b/third_party/blink/renderer/core/events/drag_event.h index 11a6c43..a315016 100644 --- a/third_party/blink/renderer/core/events/drag_event.h +++ b/third_party/blink/renderer/core/events/drag_event.h
@@ -21,7 +21,7 @@ static DragEvent* Create(const AtomicString& type, const DragEventInit* initializer, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType synthetic_event_type) { return MakeGarbageCollected<DragEvent>( type, initializer, platform_time_stamp, synthetic_event_type); @@ -36,7 +36,7 @@ DragEvent(); DragEvent(const AtomicString& type, const DragEventInit*, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType); DataTransfer* getDataTransfer() const override {
diff --git a/third_party/blink/renderer/core/events/mouse_event.cc b/third_party/blink/renderer/core/events/mouse_event.cc index 79c75c3..9ad164b 100644 --- a/third_party/blink/renderer/core/events/mouse_event.cc +++ b/third_party/blink/renderer/core/events/mouse_event.cc
@@ -119,7 +119,7 @@ MouseEvent* MouseEvent::Create(const AtomicString& event_type, const MouseEventInit* initializer, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType synthetic_event_type, WebMenuSourceType menu_source_type) { return MakeGarbageCollected<MouseEvent>( @@ -157,8 +157,9 @@ initializer->setButtons( MouseEvent::WebInputEventModifiersToButtons(modifiers)); - TimeTicks timestamp = underlying_event ? underlying_event->PlatformTimeStamp() - : CurrentTimeTicks(); + base::TimeTicks timestamp = underlying_event + ? underlying_event->PlatformTimeStamp() + : CurrentTimeTicks(); MouseEvent* created_event = MakeGarbageCollected<MouseEvent>( event_type, initializer, timestamp, synthetic_type); @@ -183,7 +184,7 @@ MouseEvent::MouseEvent(const AtomicString& event_type, const MouseEventInit* initializer, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType synthetic_event_type, WebMenuSourceType menu_source_type) : UIEventWithKeyState(event_type, initializer, platform_time_stamp),
diff --git a/third_party/blink/renderer/core/events/mouse_event.h b/third_party/blink/renderer/core/events/mouse_event.h index e5afe20b..f232a81 100644 --- a/third_party/blink/renderer/core/events/mouse_event.h +++ b/third_party/blink/renderer/core/events/mouse_event.h
@@ -55,7 +55,7 @@ static MouseEvent* Create(const AtomicString& event_type, const MouseEventInit*, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType, WebMenuSourceType); @@ -70,7 +70,7 @@ MouseEvent(const AtomicString& type, const MouseEventInit*, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, SyntheticEventType = kRealOrIndistinguishable, WebMenuSourceType = kMenuSourceNone); MouseEvent(const AtomicString& type, const MouseEventInit* init)
diff --git a/third_party/blink/renderer/core/events/pointer_event.cc b/third_party/blink/renderer/core/events/pointer_event.cc index a7501d9..7cd8a98 100644 --- a/third_party/blink/renderer/core/events/pointer_event.cc +++ b/third_party/blink/renderer/core/events/pointer_event.cc
@@ -12,7 +12,7 @@ PointerEvent::PointerEvent(const AtomicString& type, const PointerEventInit* initializer, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : MouseEvent(type, initializer, platform_time_stamp), pointer_id_(0), width_(0), @@ -111,7 +111,7 @@ return predicted_events_; } -TimeTicks PointerEvent::OldestPlatformTimeStamp() const { +base::TimeTicks PointerEvent::OldestPlatformTimeStamp() const { if (coalesced_events_.size() > 0) { // Assume that time stamps of coalesced events are in ascending order. return coalesced_events_[0]->PlatformTimeStamp();
diff --git a/third_party/blink/renderer/core/events/pointer_event.h b/third_party/blink/renderer/core/events/pointer_event.h index 2afd951b..1eef5f1 100644 --- a/third_party/blink/renderer/core/events/pointer_event.h +++ b/third_party/blink/renderer/core/events/pointer_event.h
@@ -16,7 +16,7 @@ public: static PointerEvent* Create(const AtomicString& type, const PointerEventInit* initializer, - TimeTicks platform_time_stamp) { + base::TimeTicks platform_time_stamp) { return MakeGarbageCollected<PointerEvent>(type, initializer, platform_time_stamp); } @@ -27,7 +27,7 @@ PointerEvent(const AtomicString&, const PointerEventInit*, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); PointerId pointerId() const { return pointer_id_; } double width() const { return width_; } @@ -63,7 +63,7 @@ HeapVector<Member<PointerEvent>> getCoalescedEvents(); HeapVector<Member<PointerEvent>> getPredictedEvents(); - TimeTicks OldestPlatformTimeStamp() const; + base::TimeTicks OldestPlatformTimeStamp() const; DispatchEventResult DispatchEvent(EventDispatcher&) override;
diff --git a/third_party/blink/renderer/core/events/pointer_event_factory.cc b/third_party/blink/renderer/core/events/pointer_event_factory.cc index 5f2791ff..5168b09 100644 --- a/third_party/blink/renderer/core/events/pointer_event_factory.cc +++ b/third_party/blink/renderer/core/events/pointer_event_factory.cc
@@ -342,7 +342,7 @@ PointerEvent* PointerEventFactory::CreatePointerCancelEvent( const int pointer_id, - TimeTicks platfrom_time_stamp) { + base::TimeTicks platfrom_time_stamp) { DCHECK(pointer_id_mapping_.Contains(pointer_id)); pointer_id_mapping_.Set( pointer_id,
diff --git a/third_party/blink/renderer/core/events/pointer_event_factory.h b/third_party/blink/renderer/core/events/pointer_event_factory.h index 6e895db..897ffd6 100644 --- a/third_party/blink/renderer/core/events/pointer_event_factory.h +++ b/third_party/blink/renderer/core/events/pointer_event_factory.h
@@ -38,7 +38,7 @@ LocalDOMWindow* view); PointerEvent* CreatePointerCancelEvent(const PointerId pointer_id, - TimeTicks platfrom_time_stamp); + base::TimeTicks platfrom_time_stamp); // For creating raw update events in chorded button case. PointerEvent* CreatePointerRawUpdateEvent(PointerEvent*);
diff --git a/third_party/blink/renderer/core/events/ui_event.cc b/third_party/blink/renderer/core/events/ui_event.cc index fbb2d01b..8b67e72 100644 --- a/third_party/blink/renderer/core/events/ui_event.cc +++ b/third_party/blink/renderer/core/events/ui_event.cc
@@ -33,7 +33,7 @@ Bubbles bubbles, Cancelable cancelable, ComposedMode composed_mode, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, AbstractView* view_arg, int detail_arg, InputDeviceCapabilities* source_capabilities_arg) @@ -48,7 +48,7 @@ UIEvent::UIEvent(const AtomicString& event_type, const UIEventInit* initializer, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : Event(event_type, initializer, platform_time_stamp), view_(initializer->view()), detail_(initializer->detail()),
diff --git a/third_party/blink/renderer/core/events/ui_event.h b/third_party/blink/renderer/core/events/ui_event.h index 2f0757d..7ad0643 100644 --- a/third_party/blink/renderer/core/events/ui_event.h +++ b/third_party/blink/renderer/core/events/ui_event.h
@@ -51,13 +51,13 @@ Bubbles, Cancelable, ComposedMode, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, AbstractView*, int detail, InputDeviceCapabilities* source_capabilities); UIEvent(const AtomicString&, const UIEventInit*, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); UIEvent(const AtomicString& type, const UIEventInit* init) : UIEvent(type, init, CurrentTimeTicks()) {} ~UIEvent() override;
diff --git a/third_party/blink/renderer/core/events/ui_event_with_key_state.cc b/third_party/blink/renderer/core/events/ui_event_with_key_state.cc index 9860d401..de489e9 100644 --- a/third_party/blink/renderer/core/events/ui_event_with_key_state.cc +++ b/third_party/blink/renderer/core/events/ui_event_with_key_state.cc
@@ -31,7 +31,7 @@ AbstractView* view, int detail, WebInputEvent::Modifiers modifiers, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, InputDeviceCapabilities* source_capabilities) : UIEvent(type, bubbles, @@ -45,7 +45,7 @@ UIEventWithKeyState::UIEventWithKeyState(const AtomicString& type, const EventModifierInit* initializer, - TimeTicks platform_time_stamp) + base::TimeTicks platform_time_stamp) : UIEvent(type, initializer, platform_time_stamp), modifiers_(0) { if (initializer->ctrlKey()) modifiers_ |= WebInputEvent::kControlKey;
diff --git a/third_party/blink/renderer/core/events/ui_event_with_key_state.h b/third_party/blink/renderer/core/events/ui_event_with_key_state.h index 0962cb93..d2374e2 100644 --- a/third_party/blink/renderer/core/events/ui_event_with_key_state.h +++ b/third_party/blink/renderer/core/events/ui_event_with_key_state.h
@@ -72,11 +72,11 @@ AbstractView*, int detail, WebInputEvent::Modifiers, - TimeTicks platform_time_stamp, + base::TimeTicks platform_time_stamp, InputDeviceCapabilities* source_capabilities = nullptr); UIEventWithKeyState(const AtomicString& type, const EventModifierInit* initializer, - TimeTicks platform_time_stamp); + base::TimeTicks platform_time_stamp); UIEventWithKeyState(const AtomicString& type, const EventModifierInit* initializer) : UIEventWithKeyState(type, initializer, CurrentTimeTicks()) {}
diff --git a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc index 9c2a348..5d66d200 100644 --- a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc +++ b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
@@ -296,7 +296,7 @@ // client after WebAssociatedURLLoader::loadAsynchronously has returned to the // caller. if (did_fail_) - error_timer_.StartOneShot(TimeDelta(), FROM_HERE); + error_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void WebAssociatedURLLoaderImpl::ClientAdapter::NotifyError(TimerBase* timer) {
diff --git a/third_party/blink/renderer/core/exported/web_frame_serializer.cc b/third_party/blink/renderer/core/exported/web_frame_serializer.cc index 0f0dc6f..11e15b0 100644 --- a/third_party/blink/renderer/core/exported/web_frame_serializer.cc +++ b/third_party/blink/renderer/core/exported/web_frame_serializer.cc
@@ -408,7 +408,7 @@ scoped_refptr<RawData> buffer = RawData::Create(); MHTMLArchive::GenerateMHTMLHeader( boundary, document->Url(), document->title(), - document->SuggestedMIMEType(), WTF::Time::Now(), *buffer->MutableData()); + document->SuggestedMIMEType(), base::Time::Now(), *buffer->MutableData()); return WebThreadSafeData(buffer); }
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index 0bbd397..795fd6c8 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -10355,7 +10355,7 @@ ImageResource* resource = img_document->CachedImageResourceDeprecated(); EXPECT_TRUE(resource); - EXPECT_NE(TimeTicks(), resource->LoadResponseEnd()); + EXPECT_NE(base::TimeTicks(), resource->LoadResponseEnd()); DocumentLoader* loader = document->Loader();
diff --git a/third_party/blink/renderer/core/exported/web_view_test.cc b/third_party/blink/renderer/core/exported/web_view_test.cc index fee6033..322fc90 100644 --- a/third_party/blink/renderer/core/exported/web_view_test.cc +++ b/third_party/blink/renderer/core/exported/web_view_test.cc
@@ -5238,7 +5238,7 @@ ASSERT_NE(nullptr, document); base::TimeTicks start_time = test_task_runner_->NowTicks(); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5251,7 +5251,7 @@ key_event1.dom_key = ui::DomKey::FromCharacter(' '); key_event1.windows_key_code = VKEY_SPACE; key_event1.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event1)); @@ -5266,7 +5266,7 @@ WebInputEvent::GetStaticTimeStampForTests()); key_event2.dom_key = ui::DomKey::FromCharacter(' '); key_event2.windows_key_code = VKEY_SPACE; - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(60)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(60)); key_event2.SetTimeStamp(test_task_runner_->NowTicks()); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event2)); @@ -5290,7 +5290,7 @@ Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5303,11 +5303,11 @@ key_event1.dom_key = ui::DomKey::FromCharacter(' '); key_event1.windows_key_code = VKEY_SPACE; key_event1.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event1)); - TimeTicks longest_input_timestamp = test_task_runner_->NowTicks(); + base::TimeTicks longest_input_timestamp = test_task_runner_->NowTicks(); WebKeyboardEvent key_event2(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, @@ -5315,7 +5315,7 @@ key_event2.dom_key = ui::DomKey::FromCharacter(' '); key_event2.windows_key_code = VKEY_SPACE; key_event2.SetTimeStamp(longest_input_timestamp); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event2)); @@ -5325,7 +5325,7 @@ key_event3.dom_key = ui::DomKey::FromCharacter(' '); key_event3.windows_key_code = VKEY_SPACE; key_event3.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event3)); @@ -5337,7 +5337,7 @@ } TEST_F(WebViewTest, InputDelayReported) { - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); WebViewImpl* web_view = web_view_helper_.Initialize(); @@ -5352,7 +5352,7 @@ ASSERT_NE(nullptr, document); GetTestInteractiveDetector(*document); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); HistogramTester histogram_tester; WebKeyboardEvent key_event1(WebInputEvent::kRawKeyDown, @@ -5361,7 +5361,7 @@ key_event1.dom_key = ui::DomKey::FromCharacter(' '); key_event1.windows_key_code = VKEY_SPACE; key_event1.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event1)); @@ -5371,7 +5371,7 @@ key_event2.dom_key = ui::DomKey::FromCharacter(' '); key_event2.windows_key_code = VKEY_SPACE; key_event2.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event2)); @@ -5381,7 +5381,7 @@ key_event3.dom_key = ui::DomKey::FromCharacter(' '); key_event3.windows_key_code = VKEY_SPACE; key_event3.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event3)); @@ -5416,7 +5416,7 @@ Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5428,9 +5428,9 @@ WebInputEvent::GetStaticTimeStampForTests()); key_event1.dom_key = ui::DomKey::FromCharacter(' '); key_event1.windows_key_code = VKEY_SPACE; - TimeTicks key_event1_time = test_task_runner_->NowTicks(); + base::TimeTicks key_event1_time = test_task_runner_->NowTicks(); key_event1.SetTimeStamp(key_event1_time); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event1)); @@ -5440,11 +5440,11 @@ key_event2.dom_key = ui::DomKey::FromCharacter(' '); key_event2.windows_key_code = VKEY_SPACE; key_event2.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); web_view->SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); // Total input delay is >300ms. web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event2)); @@ -5470,7 +5470,7 @@ Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5481,7 +5481,7 @@ key_event.dom_key = ui::DomKey::FromCharacter(' '); key_event.windows_key_code = VKEY_SPACE; key_event.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event)); @@ -5503,7 +5503,7 @@ Document* document = main_frame->GetDocument(); ASSERT_NE(nullptr, document); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5511,18 +5511,18 @@ EXPECT_TRUE(interactive_detector->GetLongestInputDelay().is_zero()); web_view->SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100)); web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1)); WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown, WebInputEvent::kNoModifiers, WebInputEvent::GetStaticTimeStampForTests()); key_event.dom_key = ui::DomKey::FromCharacter(' '); key_event.windows_key_code = VKEY_SPACE; - TimeTicks key_event_time = test_task_runner_->NowTicks(); + base::TimeTicks key_event_time = test_task_runner_->NowTicks(); key_event.SetTimeStamp(key_event_time); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event)); @@ -5552,7 +5552,7 @@ ASSERT_NE(nullptr, document); base::TimeTicks start_time = test_task_runner_->NowTicks(); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70)); InteractiveDetector* interactive_detector = GetTestInteractiveDetector(*document); @@ -5564,7 +5564,7 @@ // Set this to the left button, needed for testing to behave properly. pointer_down.SetModifiers(WebInputEvent::kLeftButtonDown); pointer_down.button = WebPointerProperties::Button::kLeft; - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(pointer_down)); @@ -5576,7 +5576,7 @@ WebPointerEvent pointer_up( WebInputEvent::kPointerUp, WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(60)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(60)); pointer_up.SetTimeStamp(test_task_runner_->NowTicks()); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(pointer_up)); @@ -5594,7 +5594,7 @@ public: MockClockAdvancingWebFrameClient( scoped_refptr<base::TestMockTimeTaskRunner> task_runner, - TimeDelta event_handling_delay) + base::TimeDelta event_handling_delay) : task_runner_(std::move(task_runner)), event_handling_delay_(event_handling_delay) {} // WebLocalFrameClient overrides: @@ -5607,15 +5607,15 @@ private: scoped_refptr<base::TestMockTimeTaskRunner> task_runner_; - TimeDelta event_handling_delay_; + base::TimeDelta event_handling_delay_; }; // Check that the input delay is correctly reported to the document. TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) { // Page load timing logic depends on the time not being zero. - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1)); MockClockAdvancingWebFrameClient frame_client( - test_task_runner_, TimeDelta::FromMilliseconds(6000)); + test_task_runner_, base::TimeDelta::FromMilliseconds(6000)); WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client); WebURL base_url = url_test_helpers::ToKURL("http://example.com/"); frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), @@ -5644,12 +5644,13 @@ key_event.windows_key_code = VKEY_SPACE; key_event.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5000)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(5000)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event)); - TimeDelta first_input_delay = interactive_detector->GetFirstInputDelay(); + base::TimeDelta first_input_delay = + interactive_detector->GetFirstInputDelay(); EXPECT_EQ(5000, first_input_delay.InMillisecondsF()); web_view_helper_.Reset(); // Remove dependency on locally scoped client. @@ -5658,9 +5659,9 @@ // Check that the longest input delay is correctly reported to the document. TEST_F(WebViewTest, LongestInputDelayExcludesProcessingTime) { // Page load timing logic depends on the time not being zero. - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1)); MockClockAdvancingWebFrameClient frame_client( - test_task_runner_, TimeDelta::FromMilliseconds(6000)); + test_task_runner_, base::TimeDelta::FromMilliseconds(6000)); WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client); WebURL base_url = url_test_helpers::ToKURL("http://example.com/"); frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(), @@ -5688,12 +5689,13 @@ key_event.windows_key_code = VKEY_SPACE; key_event.SetTimeStamp(test_task_runner_->NowTicks()); - test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5000)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(5000)); web_view->MainFrameWidget()->HandleInputEvent( WebCoalescedInputEvent(key_event)); - TimeDelta longest_input_delay = interactive_detector->GetLongestInputDelay(); + base::TimeDelta longest_input_delay = + interactive_detector->GetLongestInputDelay(); EXPECT_EQ(5000, longest_input_delay.InMillisecondsF()); web_view_helper_.Reset(); // Remove dependency on locally scoped client.
diff --git a/third_party/blink/renderer/core/fetch/fetch_response_data.h b/third_party/blink/renderer/core/fetch/fetch_response_data.h index e2f07660..3f2df87 100644 --- a/third_party/blink/renderer/core/fetch/fetch_response_data.h +++ b/third_party/blink/renderer/core/fetch/fetch_response_data.h
@@ -74,7 +74,7 @@ // returns |m_buffer|. BodyStreamBuffer* InternalBuffer() const; String InternalMIMEType() const; - Time ResponseTime() const { return response_time_; } + base::Time ResponseTime() const { return response_time_; } String CacheStorageCacheName() const { return cache_storage_cache_name_; } const WebHTTPHeaderSet& CorsExposedHeaderNames() const { return cors_exposed_header_names_; @@ -92,7 +92,9 @@ status_message_ = status_message; } void SetMimeType(const String& type) { mime_type_ = type; } - void SetResponseTime(Time response_time) { response_time_ = response_time; } + void SetResponseTime(base::Time response_time) { + response_time_ = response_time; + } void SetCacheStorageCacheName(const String& cache_storage_cache_name) { cache_storage_cache_name_ = cache_storage_cache_name; } @@ -122,7 +124,7 @@ Member<FetchResponseData> internal_response_; Member<BodyStreamBuffer> buffer_; String mime_type_; - Time response_time_; + base::Time response_time_; String cache_storage_cache_name_; WebHTTPHeaderSet cors_exposed_header_names_;
diff --git a/third_party/blink/renderer/core/frame/dom_timer.cc b/third_party/blink/renderer/core/frame/dom_timer.cc index 419c2da..32e3bea 100644 --- a/third_party/blink/renderer/core/frame/dom_timer.cc +++ b/third_party/blink/renderer/core/frame/dom_timer.cc
@@ -37,17 +37,18 @@ namespace blink { -static const TimeDelta kMaxIntervalForUserGestureForwarding = - TimeDelta::FromMilliseconds(1000); // One second matches Gecko. +static const base::TimeDelta kMaxIntervalForUserGestureForwarding = + base::TimeDelta::FromMilliseconds(1000); // One second matches Gecko. static const int kMaxTimerNestingLevel = 5; // Chromium uses a minimum timer interval of 4ms. We'd like to go // lower; however, there are poorly coded websites out there which do // create CPU-spinning loops. Using 4ms prevents the CPU from // spinning too busily and provides a balance between CPU spinning and // the smallest possible interval timer. -static constexpr TimeDelta kMinimumInterval = TimeDelta::FromMilliseconds(4); +static constexpr base::TimeDelta kMinimumInterval = + base::TimeDelta::FromMilliseconds(4); -static inline bool ShouldForwardUserGesture(TimeDelta interval, +static inline bool ShouldForwardUserGesture(base::TimeDelta interval, int nesting_level) { if (RuntimeEnabledFeatures::UserActivationV2Enabled()) return false; @@ -59,7 +60,7 @@ int DOMTimer::Install(ExecutionContext* context, ScheduledAction* action, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot) { int timeout_id = context->Timers()->InstallNewTimeout(context, action, timeout, single_shot); @@ -78,7 +79,7 @@ DOMTimer::DOMTimer(ExecutionContext* context, ScheduledAction* action, - TimeDelta interval, + base::TimeDelta interval, bool single_shot, int timeout_id) : ContextLifecycleObserver(context), @@ -93,8 +94,8 @@ user_gesture_token_ = UserGestureIndicator::CurrentToken(); } - TimeDelta interval_milliseconds = - std::max(TimeDelta::FromMilliseconds(1), interval); + base::TimeDelta interval_milliseconds = + std::max(base::TimeDelta::FromMilliseconds(1), interval); if (interval_milliseconds < kMinimumInterval && nesting_level_ >= kMaxTimerNestingLevel) interval_milliseconds = kMinimumInterval;
diff --git a/third_party/blink/renderer/core/frame/dom_timer.h b/third_party/blink/renderer/core/frame/dom_timer.h index 58da7f4..a22e03c 100644 --- a/third_party/blink/renderer/core/frame/dom_timer.h +++ b/third_party/blink/renderer/core/frame/dom_timer.h
@@ -51,13 +51,13 @@ // its ID. static int Install(ExecutionContext*, ScheduledAction*, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot); static void RemoveByID(ExecutionContext*, int timeout_id); DOMTimer(ExecutionContext*, ScheduledAction*, - TimeDelta interval, + base::TimeDelta interval, bool single_shot, int timeout_id); ~DOMTimer() override;
diff --git a/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc b/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc index 5d10ef3..e874cf3 100644 --- a/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc +++ b/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc
@@ -19,7 +19,7 @@ int DOMTimerCoordinator::InstallNewTimeout(ExecutionContext* context, ScheduledAction* action, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot) { // FIXME: DOMTimers depends heavily on ExecutionContext. Decouple them. DCHECK_EQ(context->Timers(), this);
diff --git a/third_party/blink/renderer/core/frame/dom_timer_coordinator.h b/third_party/blink/renderer/core/frame/dom_timer_coordinator.h index c5597af..af5011cd 100644 --- a/third_party/blink/renderer/core/frame/dom_timer_coordinator.h +++ b/third_party/blink/renderer/core/frame/dom_timer_coordinator.h
@@ -32,7 +32,7 @@ // Creates and installs a new timer. Returns the assigned ID. int InstallNewTimeout(ExecutionContext*, ScheduledAction*, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot); // Removes and disposes the timer with the specified ID, if any. This may
diff --git a/third_party/blink/renderer/core/frame/frame_serializer.cc b/third_party/blink/renderer/core/frame/frame_serializer.cc index 979d4c2..e713ffe 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -408,7 +408,7 @@ TRACE_EVENT2("page-serialization", "FrameSerializer::serializeCSSStyleSheet", "type", "CSS", "url", url.ElidedString().Utf8()); // Only report UMA metric if this is not a reentrant CSS serialization call. - TimeTicks css_start_time; + base::TimeTicks css_start_time; if (!is_serializing_css_) { is_serializing_css_ = true; css_start_time = CurrentTimeTicks(); @@ -448,7 +448,7 @@ for (unsigned i = 0; i < style_sheet.length(); ++i) SerializeCSSRule(style_sheet.item(i)); - if (css_start_time != TimeTicks()) { + if (css_start_time != base::TimeTicks()) { is_serializing_css_ = false; DEFINE_STATIC_LOCAL(CustomCountHistogram, css_histogram, ("PageSerialization.SerializationTime.CSSElement", 0,
diff --git a/third_party/blink/renderer/core/frame/local_dom_window.cc b/third_party/blink/renderer/core/frame/local_dom_window.cc index ae0a6c2f..fec615d 100644 --- a/third_party/blink/renderer/core/frame/local_dom_window.cc +++ b/third_party/blink/renderer/core/frame/local_dom_window.cc
@@ -115,7 +115,8 @@ namespace blink { // Timeout for link preloads to be used after window.onload -static constexpr TimeDelta kUnusedPreloadTimeout = TimeDelta::FromSeconds(3); +static constexpr base::TimeDelta kUnusedPreloadTimeout = + base::TimeDelta::FromSeconds(3); static void UpdateSuddenTerminationStatus( LocalDOMWindow* dom_window,
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index 5facf55..2f71a5d 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -514,9 +514,9 @@ void LocalFrame::DidResume() { if (GetDocument()) { - const TimeTicks resume_event_start = CurrentTimeTicks(); + const base::TimeTicks resume_event_start = CurrentTimeTicks(); GetDocument()->DispatchEvent(*Event::Create(event_type_names::kResume)); - const TimeTicks resume_event_end = CurrentTimeTicks(); + const base::TimeTicks resume_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, resume_histogram, ("DocumentEventTiming.ResumeDuration", 0, 10000000, 50));
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc index 6b9c43b0..4c14918 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
@@ -129,7 +129,8 @@ clock_ = clock; } -void LocalFrameUkmAggregator::RecordForcedStyleLayoutUMA(TimeDelta& duration) { +void LocalFrameUkmAggregator::RecordForcedStyleLayoutUMA( + base::TimeDelta& duration) { if (!calls_to_next_forced_style_layout_uma_) { auto& record = absolute_metric_records_[kForcedStyleAndLayout]; record.uma_counter->CountMicroseconds(duration); @@ -142,9 +143,9 @@ } void LocalFrameUkmAggregator::RecordSample(size_t metric_index, - TimeTicks start, - TimeTicks end) { - TimeDelta duration = end - start; + base::TimeTicks start, + base::TimeTicks end) { + base::TimeDelta duration = end - start; // Accumulate for UKM and record the UMA DCHECK_LT(metric_index, absolute_metric_records_.size()); @@ -169,8 +170,8 @@ } } -void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(TimeTicks start, - TimeTicks end) { +void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(base::TimeTicks start, + base::TimeTicks end) { // Any of the early out's in LocalFrameView::UpdateLifecyclePhases // will mean we are not in a main frame update. Recording is triggered // higher in the stack, so we cannot know to avoid calling this method. @@ -182,7 +183,7 @@ } in_main_frame_update_ = false; - TimeDelta duration = end - start; + base::TimeDelta duration = end - start; // Record UMA primary_metric_.uma_counter->CountMicroseconds(duration);
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h index 8bb2bfa..ce0bd5d 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h
@@ -175,10 +175,11 @@ // Modify this array if the UMA ratio metrics should be bucketed in a // different way. - static const Vector<TimeDelta>& bucket_thresholds() { + static const Vector<base::TimeDelta>& bucket_thresholds() { // Leaky construction to avoid exit-time destruction. - static const Vector<TimeDelta>* thresholds = new Vector<TimeDelta>{ - TimeDelta::FromMilliseconds(1), TimeDelta::FromMilliseconds(5)}; + static const Vector<base::TimeDelta>* thresholds = + new Vector<base::TimeDelta>{base::TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(5)}; return *thresholds; } @@ -204,7 +205,7 @@ scoped_refptr<LocalFrameUkmAggregator> aggregator_; const size_t metric_index_; const base::TickClock* clock_; - const TimeTicks start_time_; + const base::TimeTicks start_time_; DISALLOW_COPY_AND_ASSIGN(ScopedUkmHierarchicalTimer); }; @@ -220,12 +221,14 @@ // sub-metrics and generates UMA samples. UKM is only reported when // BeginMainFrame() returned true. All counters are cleared when this method // is called. - void RecordEndOfFrameMetrics(TimeTicks start, TimeTicks end); + void RecordEndOfFrameMetrics(base::TimeTicks start, base::TimeTicks end); // Record a sample for a sub-metric. This should only be used when // a ScopedUkmHierarchicalTimer cannot be used (such as when the timed // interval does not fall inside a single calling function). - void RecordSample(size_t metric_index, TimeTicks start, TimeTicks end); + void RecordSample(size_t metric_index, + base::TimeTicks start, + base::TimeTicks end); // Mark the beginning of a main frame update. void BeginMainFrame(); @@ -242,9 +245,9 @@ // Accumulated at each sample, then reset with a call to // RecordEndOfFrameMetrics. - TimeDelta interval_duration; + base::TimeDelta interval_duration; - void reset() { interval_duration = TimeDelta(); } + void reset() { interval_duration = base::TimeDelta(); } }; struct MainFramePercentageRecord { @@ -252,9 +255,9 @@ // Accumulated at each sample, then reset with a call to // RecordEndOfFrameMetrics. - TimeDelta interval_duration; + base::TimeDelta interval_duration; - void reset() { interval_duration = TimeDelta(); } + void reset() { interval_duration = base::TimeDelta(); } }; void UpdateEventTimeAndRecordEventIfNeeded(); @@ -263,7 +266,7 @@ unsigned SampleFramesToNextEvent(); // Implements throttling of the ForcedStyleAndLayoutUMA metric. - void RecordForcedStyleLayoutUMA(TimeDelta& duration); + void RecordForcedStyleLayoutUMA(base::TimeDelta& duration); // To test event sampling. This and all future intervals will be the given // frame count, until this is called again.
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc index f4826968..a9bef6df 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc
@@ -100,7 +100,7 @@ return; // There is no BeginMainFrame, so no metrics get recorded. - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(10)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(10)); ResetAggregator(); EXPECT_EQ(recorder().sources_count(), 0u); @@ -124,7 +124,7 @@ auto timer = aggregator().GetScopedTimer(i % LocalFrameUkmAggregator::kCount); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_for_step)); + base::TimeDelta::FromMilliseconds(millisecond_for_step)); } aggregator().RecordEndOfFrameMetrics(start_time, Now()); @@ -167,10 +167,10 @@ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) { auto timer = aggregator().GetScopedTimer(i); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); } test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); aggregator().RecordEndOfFrameMetrics(start_time, Now()); // We should have a sample after the very first step, regardless of the @@ -186,10 +186,10 @@ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) { auto timer = aggregator().GetScopedTimer(i); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); } test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); aggregator().RecordEndOfFrameMetrics(start_time, Now()); VerifyEntries(1u, millisecond_per_frame, millisecond_per_step, @@ -203,10 +203,10 @@ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) { auto timer = aggregator().GetScopedTimer(i); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); } test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); aggregator().RecordEndOfFrameMetrics(start_time, Now()); VerifyEntries(2u, millisecond_per_frame, millisecond_per_step, @@ -218,10 +218,10 @@ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) { auto timer = aggregator().GetScopedTimer(i); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); } test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); aggregator().RecordEndOfFrameMetrics(start_time, Now()); // Should be no more samples. @@ -234,10 +234,10 @@ for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) { auto timer = aggregator().GetScopedTimer(i); test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); } test_task_runner_->FastForwardBy( - TimeDelta::FromMilliseconds(millisecond_per_step)); + base::TimeDelta::FromMilliseconds(millisecond_per_step)); aggregator().RecordEndOfFrameMetrics(start_time, Now()); // We should have 3 more events, once for the prior interval and 2 for the
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 43e745a..8df2406 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -277,7 +277,7 @@ : nullptr)), main_thread_scrolling_reasons_(0), forced_layout_stack_depth_(0), - forced_layout_start_time_(TimeTicks()), + forced_layout_start_time_(base::TimeTicks()), paint_frame_count_(0), unique_id_(NewUniqueObjectId()), layout_shift_tracker_(std::make_unique<LayoutShiftTracker>(this)), @@ -1779,7 +1779,7 @@ DCHECK(!IsInPerformLayout()); if (update_plugins_timer_.IsActive() || part_update_set_.IsEmpty()) return; - update_plugins_timer_.StartOneShot(TimeDelta(), FROM_HERE); + update_plugins_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void LocalFrameView::PerformPostLayoutTasks() {
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.h b/third_party/blink/renderer/core/frame/local_frame_view.h index c0febf0..6a43354 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.h +++ b/third_party/blink/renderer/core/frame/local_frame_view.h
@@ -105,9 +105,9 @@ struct LifecycleData { LifecycleData() {} - LifecycleData(TimeTicks start_time_arg, int count_arg) + LifecycleData(base::TimeTicks start_time_arg, int count_arg) : start_time(start_time_arg), count(count_arg) {} - TimeTicks start_time; + base::TimeTicks start_time; // The number of lifecycles that have occcurred since the first one, // inclusive, on a given LocalFrameRoot. unsigned count = 0; @@ -987,7 +987,7 @@ scoped_refptr<LocalFrameUkmAggregator> ukm_aggregator_; unsigned forced_layout_stack_depth_; - TimeTicks forced_layout_start_time_; + base::TimeTicks forced_layout_start_time_; Member<PrintContext> print_context_;
diff --git a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc index 96fa0ee..e88b08b 100644 --- a/third_party/blink/renderer/core/frame/mhtml_archive_test.cc +++ b/third_party/blink/renderer/core/frame/mhtml_archive_test.cc
@@ -63,7 +63,7 @@ public: MHTMLArchiveTest() { file_path_ = test::CoreTestDataPath("frameserializer/css/"); - mhtml_date_ = WTF::Time::FromJsTime(1520551829000); + mhtml_date_ = base::Time::FromJsTime(1520551829000); mhtml_date_header_ = String::FromUTF8("Thu, 8 Mar 2018 23:30:29 -0000"); } @@ -184,7 +184,7 @@ Vector<char>& mhtml_data() { return mhtml_data_; } - WTF::Time mhtml_date() const { return mhtml_date_; } + base::Time mhtml_date() const { return mhtml_date_; } const String& mhtml_date_header() const { return mhtml_date_header_; } void CheckLoadResult(const KURL url, @@ -213,7 +213,7 @@ String file_path_; Vector<SerializedResource> resources_; Vector<char> mhtml_data_; - WTF::Time mhtml_date_; + base::Time mhtml_date_; String mhtml_date_header_; };
diff --git a/third_party/blink/renderer/core/frame/performance_monitor.cc b/third_party/blink/renderer/core/frame/performance_monitor.cc index 938bad3..4785438 100644 --- a/third_party/blink/renderer/core/frame/performance_monitor.cc +++ b/third_party/blink/renderer/core/frame/performance_monitor.cc
@@ -23,7 +23,8 @@ namespace blink { namespace { -constexpr auto kLongTaskSubTaskThreshold = TimeDelta::FromMilliseconds(12); +constexpr auto kLongTaskSubTaskThreshold = + base::TimeDelta::FromMilliseconds(12); } // namespace void PerformanceMonitor::BypassLongCompileThresholdOnceForTesting() { @@ -256,7 +257,7 @@ if (!enabled_ || thresholds_[kLongTask].is_zero()) return; - TimeDelta v8_compile_duration = probe.Duration(); + base::TimeDelta v8_compile_duration = probe.Duration(); if (bypass_long_compile_threshold_) { bypass_long_compile_threshold_ = false; @@ -312,9 +313,9 @@ // Reset everything for regular and nested tasks. script_depth_ = 0; layout_depth_ = 0; - per_task_style_and_layout_time_ = TimeDelta(); + per_task_style_and_layout_time_ = base::TimeDelta(); user_callback_ = nullptr; - v8_compile_start_time_ = TimeTicks(); + v8_compile_start_time_ = base::TimeTicks(); sub_task_attributions_.clear(); }
diff --git a/third_party/blink/renderer/core/frame/performance_monitor.h b/third_party/blink/renderer/core/frame/performance_monitor.h index 02fa676..7f1e3a1 100644 --- a/third_party/blink/renderer/core/frame/performance_monitor.h +++ b/third_party/blink/renderer/core/frame/performance_monitor.h
@@ -142,12 +142,12 @@ Frame* observer_frame); bool enabled_ = false; - TimeDelta per_task_style_and_layout_time_; + base::TimeDelta per_task_style_and_layout_time_; unsigned script_depth_ = 0; unsigned layout_depth_ = 0; unsigned user_callback_depth_ = 0; const void* user_callback_; - TimeTicks v8_compile_start_time_; + base::TimeTicks v8_compile_start_time_; SubTaskAttribution::EntriesVector sub_task_attributions_;
diff --git a/third_party/blink/renderer/core/frame/reporting_context.cc b/third_party/blink/renderer/core/frame/reporting_context.cc index 2c9e87c7..08124e6 100644 --- a/third_party/blink/renderer/core/frame/reporting_context.cc +++ b/third_party/blink/renderer/core/frame/reporting_context.cc
@@ -156,7 +156,7 @@ const DeprecationReportBody* body = static_cast<DeprecationReportBody*>(report->body()); base::Optional<base::Time> anticipated_removal = - WTF::Time::FromDoubleT(body->anticipatedRemoval(is_null)); + base::Time::FromDoubleT(body->anticipatedRemoval(is_null)); if (is_null) anticipated_removal = base::nullopt; GetReportingService()->QueueDeprecationReport(
diff --git a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc index 128ec1ae..51e3b0f 100644 --- a/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc +++ b/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
@@ -146,7 +146,7 @@ ScheduledAction* action = ScheduledAction::Create( script_state, execution_context, handler, arguments); return DOMTimer::Install(execution_context, action, - TimeDelta::FromMilliseconds(timeout), true); + base::TimeDelta::FromMilliseconds(timeout), true); } int WindowOrWorkerGlobalScope::setTimeout( @@ -189,7 +189,7 @@ ScheduledAction* action = ScheduledAction::Create(script_state, execution_context, handler); return DOMTimer::Install(execution_context, action, - TimeDelta::FromMilliseconds(timeout), true); + base::TimeDelta::FromMilliseconds(timeout), true); } int WindowOrWorkerGlobalScope::setInterval( @@ -204,7 +204,7 @@ ScheduledAction* action = ScheduledAction::Create( script_state, execution_context, handler, arguments); return DOMTimer::Install(execution_context, action, - TimeDelta::FromMilliseconds(timeout), false); + base::TimeDelta::FromMilliseconds(timeout), false); } int WindowOrWorkerGlobalScope::setInterval( @@ -242,7 +242,7 @@ ScheduledAction* action = ScheduledAction::Create(script_state, execution_context, handler); return DOMTimer::Install(execution_context, action, - TimeDelta::FromMilliseconds(timeout), false); + base::TimeDelta::FromMilliseconds(timeout), false); } void WindowOrWorkerGlobalScope::clearTimeout(EventTarget& event_target,
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc index ddb496c6..9a65f3a 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc +++ b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc
@@ -34,10 +34,10 @@ namespace { // small slack period between deadline and current time for safety -constexpr TimeDelta kCreateBlobSlackBeforeDeadline = - TimeDelta::FromMilliseconds(1); -constexpr TimeDelta kEncodeRowSlackBeforeDeadline = - TimeDelta::FromMicroseconds(100); +constexpr base::TimeDelta kCreateBlobSlackBeforeDeadline = + base::TimeDelta::FromMilliseconds(1); +constexpr base::TimeDelta kEncodeRowSlackBeforeDeadline = + base::TimeDelta::FromMicroseconds(100); /* The value is based on user statistics on Nov 2017. */ #if (defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN)) @@ -59,17 +59,18 @@ const double kIdleTaskCompleteTimeoutDelayMs = 9000.0; #endif -bool IsCreateBlobDeadlineNearOrPassed(TimeTicks deadline) { +bool IsCreateBlobDeadlineNearOrPassed(base::TimeTicks deadline) { return CurrentTimeTicks() >= deadline - kCreateBlobSlackBeforeDeadline; } -bool IsEncodeRowDeadlineNearOrPassed(TimeTicks deadline, size_t image_width) { +bool IsEncodeRowDeadlineNearOrPassed(base::TimeTicks deadline, + size_t image_width) { // Rough estimate of the row encoding time in micro seconds. We will consider // a slack time later to not pass the idle task deadline. int row_encode_time_us = 1000 * (kIdleTaskCompleteTimeoutDelayMs / 4000.0) * (image_width / 4000.0); - TimeDelta row_encode_time_delta = - TimeDelta::FromMicroseconds(row_encode_time_us); + base::TimeDelta row_encode_time_delta = + base::TimeDelta::FromMicroseconds(row_encode_time_us); return CurrentTimeTicks() >= deadline - row_encode_time_delta - kEncodeRowSlackBeforeDeadline; } @@ -80,7 +81,7 @@ } void RecordInitiateEncodingTimeHistogram(ImageEncodingMimeType mime_type, - TimeDelta elapsed_time) { + base::TimeDelta elapsed_time) { if (mime_type == kMimeTypePng) { UmaHistogramMicrosecondsTimes( "Blink.Canvas.ToBlob.InitiateEncodingDelay.PNG", elapsed_time); @@ -91,7 +92,7 @@ } void RecordCompleteEncodingTimeHistogram(ImageEncodingMimeType mime_type, - TimeDelta elapsed_time) { + base::TimeDelta elapsed_time) { if (mime_type == kMimeTypePng) { UmaHistogramMicrosecondsTimes( "Blink.Canvas.ToBlob.CompleteEncodingDelay.PNG", elapsed_time); @@ -102,7 +103,7 @@ } void RecordScaledDurationHistogram(ImageEncodingMimeType mime_type, - TimeDelta elapsed_time, + base::TimeDelta elapsed_time, float width, float height) { float sqrt_pixels = std::sqrt(width) * std::sqrt(height); @@ -133,7 +134,7 @@ scoped_refptr<StaticBitmapImage> image, const ImageEncodeOptions* options, ToBlobFunctionType function_type, - TimeTicks start_time, + base::TimeTicks start_time, ExecutionContext* context, ScriptPromiseResolver* resolver) : CanvasAsyncBlobCreator(image, @@ -149,7 +150,7 @@ const ImageEncodeOptions* options, ToBlobFunctionType function_type, V8BlobCallback* callback, - TimeTicks start_time, + base::TimeTicks start_time, ExecutionContext* context, ScriptPromiseResolver* resolver) : fail_encoder_initialization_for_test_(false), @@ -349,7 +350,7 @@ } void CanvasAsyncBlobCreator::InitiateEncoding(double quality, - TimeTicks deadline) { + base::TimeTicks deadline) { if (idle_task_status_ == kIdleTaskSwitchedToImmediateTask) { return; } @@ -369,7 +370,7 @@ IdleEncodeRows(deadline); } -void CanvasAsyncBlobCreator::IdleEncodeRows(TimeTicks deadline) { +void CanvasAsyncBlobCreator::IdleEncodeRows(base::TimeTicks deadline) { if (idle_task_status_ == kIdleTaskSwitchedToImmediateTask) { return; } @@ -392,7 +393,7 @@ num_rows_completed_ = src_data_.height(); idle_task_status_ = kIdleTaskCompleted; - TimeDelta elapsed_time = + base::TimeDelta elapsed_time = WTF::CurrentTimeTicks() - schedule_idle_task_start_time_; RecordCompleteEncodingTimeHistogram(mime_type_, elapsed_time); if (IsCreateBlobDeadlineNearOrPassed(deadline)) { @@ -585,7 +586,7 @@ double delay_ms) { context_->GetTaskRunner(TaskType::kCanvasBlobSerialization) ->PostDelayedTask(location, std::move(task), - TimeDelta::FromMillisecondsD(delay_ms)); + base::TimeDelta::FromMillisecondsD(delay_ms)); } void CanvasAsyncBlobCreator::Trace(Visitor* visitor) {
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h index 615d58f5..ab32d861 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h +++ b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h
@@ -59,14 +59,14 @@ CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>, const ImageEncodeOptions* options, ToBlobFunctionType function_type, - TimeTicks start_time, + base::TimeTicks start_time, ExecutionContext*, ScriptPromiseResolver*); CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>, const ImageEncodeOptions*, ToBlobFunctionType, V8BlobCallback*, - TimeTicks start_time, + base::TimeTicks start_time, ExecutionContext*, ScriptPromiseResolver* = nullptr); virtual ~CanvasAsyncBlobCreator(); @@ -90,7 +90,7 @@ ImageEncodingMimeType); // Methods are virtual for unit testing virtual void ScheduleInitiateEncoding(double quality); - virtual void IdleEncodeRows(TimeTicks deadline); + virtual void IdleEncodeRows(base::TimeTicks deadline); virtual void PostDelayedTaskToCurrentThread(const base::Location&, base::OnceClosure, double delay_ms); @@ -98,7 +98,7 @@ virtual void CreateBlobAndReturnResult(); virtual void CreateNullAndReturnResult(); - void InitiateEncoding(double quality, TimeTicks deadline); + void InitiateEncoding(double quality, base::TimeTicks deadline); protected: IdleTaskStatus idle_task_status_; @@ -123,8 +123,8 @@ sk_sp<SkData> png_data_helper_; // Chrome metrics use - TimeTicks start_time_; - TimeTicks schedule_idle_task_start_time_; + base::TimeTicks start_time_; + base::TimeTicks schedule_idle_task_start_time_; bool static_bitmap_image_loaded_; // Used when CanvasAsyncBlobCreator runs on main thread only
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc index 88fa1db3..4b0d877 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc +++ b/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc
@@ -31,7 +31,7 @@ CanvasAsyncBlobCreator::GetImageEncodeOptionsForMimeType(mime_type), kHTMLCanvasToBlobCallback, nullptr, - TimeTicks(), + base::TimeTicks(), document, nullptr) { if (fail_encoder_initialization) @@ -102,10 +102,10 @@ Thread::Current()->GetTaskRunner()->PostTask( FROM_HERE, WTF::Bind(&MockCanvasAsyncBlobCreatorWithoutComplete::InitiateEncoding, - WrapPersistent(this), quality, TimeTicks::Max())); + WrapPersistent(this), quality, base::TimeTicks::Max())); } - void IdleEncodeRows(TimeTicks deadline) override { + void IdleEncodeRows(base::TimeTicks deadline) override { // Deliberately make idleEncodeRows do nothing so that idle task never // completes } @@ -292,7 +292,7 @@ source_bitmap_image, options, CanvasAsyncBlobCreator::ToBlobFunctionType:: kHTMLCanvasConvertToBlobPromise, - TimeTicks(), &GetDocument(), nullptr); + base::TimeTicks(), &GetDocument(), nullptr); ASSERT_TRUE(async_blob_creator->EncodeImageForConvertToBlobTest()); sk_sp<SkData> sk_data = SkData::MakeWithCopy(
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc index 339405da..810bef07 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc +++ b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
@@ -207,7 +207,7 @@ return ScriptPromise(); } - TimeTicks start_time = WTF::CurrentTimeTicks(); + base::TimeTicks start_time = WTF::CurrentTimeTicks(); scoped_refptr<StaticBitmapImage> image_bitmap = RenderingContext()->GetImage(kPreferNoAcceleration); if (image_bitmap) {
diff --git a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc index fc7da9da..30bbf9efa 100644 --- a/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc +++ b/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc
@@ -145,8 +145,6 @@ unsigned HTMLCanvasElement::global_accelerated_context_count_ = 0; HTMLCanvasElement::~HTMLCanvasElement() { - if (surface_layer_bridge_ && surface_layer_bridge_->GetCcLayer()) - GraphicsLayer::UnregisterContentsLayer(surface_layer_bridge_->GetCcLayer()); v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory( -externally_allocated_memory_); } @@ -180,6 +178,19 @@ global_accelerated_context_count_--; } global_gpu_memory_usage_ -= gpu_memory_usage_; + + if (surface_layer_bridge_) { + if (surface_layer_bridge_->GetCcLayer()) { + GraphicsLayer::UnregisterContentsLayer( + surface_layer_bridge_->GetCcLayer()); + } + // Observer has to be cleared out at this point. Otherwise the + // SurfaceLayerBridge may call back into the observer which is undefined + // behavior. In the worst case, the dead canvas element re-adds itself into + // a data structure which may crash at a later point in time. See + // https://crbug.com/976577. + surface_layer_bridge_->ClearObserver(); + } } void HTMLCanvasElement::ParseAttribute( @@ -934,7 +945,7 @@ return; } - TimeTicks start_time = WTF::CurrentTimeTicks(); + base::TimeTicks start_time = WTF::CurrentTimeTicks(); double quality = kUndefinedQualityValue; if (!quality_argument.IsEmpty()) { v8::Local<v8::Value> v8_value = quality_argument.V8Value();
diff --git a/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc b/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc index 417a85c..0221f293 100644 --- a/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc +++ b/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc
@@ -98,7 +98,7 @@ DidChooseValue(dialog_value); else DidCancelChooser(); - EndChooser(); + client_ = nullptr; } bool ExternalDateTimeChooser::IsShowingDateTimeChooserUI() const { @@ -128,6 +128,7 @@ } void ExternalDateTimeChooser::EndChooser() { + DCHECK(client_); DateTimeChooserClient* client = client_; client_ = nullptr; client->DidEndChooser();
diff --git a/third_party/blink/renderer/core/html/forms/external_date_time_chooser_test.cc b/third_party/blink/renderer/core/html/forms/external_date_time_chooser_test.cc new file mode 100644 index 0000000..57be376 --- /dev/null +++ b/third_party/blink/renderer/core/html/forms/external_date_time_chooser_test.cc
@@ -0,0 +1,61 @@ +// Copyright 2019 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 "third_party/blink/renderer/core/html/forms/external_date_time_chooser.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/html/forms/date_time_chooser_client.h" +#include "third_party/blink/renderer/core/html/forms/html_input_element.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" + +namespace blink { + +class ExternalDateTimeChooserTest : public testing::Test {}; + +class TestDateTimeChooserClient final + : public GarbageCollectedFinalized<TestDateTimeChooserClient>, + public DateTimeChooserClient { + USING_GARBAGE_COLLECTED_MIXIN(TestDateTimeChooserClient); + + public: + explicit TestDateTimeChooserClient(Element* element) : element_(element) {} + ~TestDateTimeChooserClient() override {} + + void Trace(Visitor* visitor) override { + visitor->Trace(element_); + visitor->Trace(date_time_chooser_); + DateTimeChooserClient::Trace(visitor); + } + + void SetDateTimeChooser(DateTimeChooser* date_time_chooser) { + date_time_chooser_ = date_time_chooser; + } + + private: + // DateTimeChooserClient functions: + Element& OwnerElement() const override { return *element_; } + void DidChooseValue(const String&) override {} + void DidChooseValue(double value) override { + if (date_time_chooser_) + date_time_chooser_->EndChooser(); + } + void DidEndChooser() override {} + + Member<Element> element_; + Member<DateTimeChooser> date_time_chooser_; +}; + +// This is a regression test for crbug.com/974646. EndChooser can cause a crash +// when it's called twice because |client_| was already nullptr. +TEST_F(ExternalDateTimeChooserTest, EndChooserShouldNotCrash) { + ScopedInputMultipleFieldsUIForTest input_multiple_fields_ui(false); + auto* document = MakeGarbageCollected<Document>(); + auto* element = document->CreateRawElement(html_names::kInputTag); + auto* client = MakeGarbageCollected<TestDateTimeChooserClient>(element); + auto* external_date_time_chooser = ExternalDateTimeChooser::Create(client); + client->SetDateTimeChooser(external_date_time_chooser); + external_date_time_chooser->ResponseHandler(true, 0); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc index 91ecc914..8d0e81e 100644 --- a/third_party/blink/renderer/core/html/forms/external_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/external_popup_menu.cc
@@ -123,7 +123,7 @@ synthetic_event_ = std::make_unique<WebMouseEvent>(); *synthetic_event_ = *static_cast<const WebMouseEvent*>(current_event); synthetic_event_->SetType(WebInputEvent::kMouseUp); - dispatch_event_timer_.StartOneShot(TimeDelta(), FROM_HERE); + dispatch_event_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); // FIXME: show() is asynchronous. If preparing a popup is slow and a // user released the mouse button before showing the popup, mouseup and // click events are correctly dispatched. Dispatching the synthetic
diff --git a/third_party/blink/renderer/core/html/forms/search_input_type.cc b/third_party/blink/renderer/core/html/forms/search_input_type.cc index edcf51c..3236fa9 100644 --- a/third_party/blink/renderer/core/html/forms/search_input_type.cc +++ b/third_party/blink/renderer/core/html/forms/search_input_type.cc
@@ -115,7 +115,7 @@ // After typing the first key, we wait 500ms. // After the second key, 400ms, then 300, then 200 from then on. unsigned step = std::min(length, 4u) - 1; - TimeDelta timeout = TimeDelta::FromMilliseconds(500 - 100 * step); + base::TimeDelta timeout = base::TimeDelta::FromMilliseconds(500 - 100 * step); search_event_timer_.StartOneShot(timeout, FROM_HERE); }
diff --git a/third_party/blink/renderer/core/html/forms/type_ahead.cc b/third_party/blink/renderer/core/html/forms/type_ahead.cc index 1327ff7..d1593e0 100644 --- a/third_party/blink/renderer/core/html/forms/type_ahead.cc +++ b/third_party/blink/renderer/core/html/forms/type_ahead.cc
@@ -37,7 +37,7 @@ TypeAhead::TypeAhead(TypeAheadDataSource* data_source) : data_source_(data_source), repeating_char_(0) {} -constexpr TimeDelta kTypeAheadTimeout = TimeDelta::FromSecondsD(1); +constexpr base::TimeDelta kTypeAheadTimeout = base::TimeDelta::FromSecondsD(1); static String StripLeadingWhiteSpace(const String& string) { unsigned length = string.length(); @@ -123,7 +123,7 @@ bool TypeAhead::HasActiveSession(const KeyboardEvent& event) { if (!last_type_time_) return false; - TimeDelta delta = event.PlatformTimeStamp() - *last_type_time_; + base::TimeDelta delta = event.PlatformTimeStamp() - *last_type_time_; return delta <= kTypeAheadTimeout; }
diff --git a/third_party/blink/renderer/core/html/forms/type_ahead.h b/third_party/blink/renderer/core/html/forms/type_ahead.h index b022fae5..cefa090 100644 --- a/third_party/blink/renderer/core/html/forms/type_ahead.h +++ b/third_party/blink/renderer/core/html/forms/type_ahead.h
@@ -67,7 +67,7 @@ private: TypeAheadDataSource* data_source_; // platform timestamp of last keyboard event in seconds - base::Optional<TimeTicks> last_type_time_; + base::Optional<base::TimeTicks> last_type_time_; UChar repeating_char_; StringBuilder buffer_; };
diff --git a/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc b/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc index e468bea..d88f5f7 100644 --- a/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc +++ b/third_party/blink/renderer/core/html/imports/html_import_tree_root.cc
@@ -55,7 +55,7 @@ DCHECK(document_); if (recalc_timer_.IsActive() || !document_->IsActive()) return; - recalc_timer_.StartOneShot(TimeDelta(), FROM_HERE); + recalc_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } HTMLImportChild* HTMLImportTreeRoot::Add(HTMLImportChild* child) {
diff --git a/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc b/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc index 647028a..c70a6e2d 100644 --- a/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc +++ b/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc
@@ -285,10 +285,10 @@ DCHECK(has_above_the_fold_been_set_); - TimeDelta visible_load_delay = + base::TimeDelta visible_load_delay = time_when_first_load_finished_ - time_when_first_visible_; - if (visible_load_delay < TimeDelta()) - visible_load_delay = TimeDelta(); + if (visible_load_delay < base::TimeDelta()) + visible_load_delay = base::TimeDelta(); switch (element_->GetDocument() .GetFrame()
diff --git a/third_party/blink/renderer/core/html/lazy_load_frame_observer.h b/third_party/blink/renderer/core/html/lazy_load_frame_observer.h index 5aef9962..7562d75b 100644 --- a/third_party/blink/renderer/core/html/lazy_load_frame_observer.h +++ b/third_party/blink/renderer/core/html/lazy_load_frame_observer.h
@@ -88,9 +88,9 @@ bool has_above_the_fold_been_set_ = false; // Set when the frame first becomes visible (i.e. appears in the viewport). - TimeTicks time_when_first_visible_; + base::TimeTicks time_when_first_visible_; // Set when the first load event is dispatched for the frame. - TimeTicks time_when_first_load_finished_; + base::TimeTicks time_when_first_load_finished_; // Keeps track of whether the frame was initially recorded as having been // deferred, so that the appropriate histograms can be recorded if the frame
diff --git a/third_party/blink/renderer/core/html/lazy_load_image_observer.cc b/third_party/blink/renderer/core/html/lazy_load_image_observer.cc index 72d92475..484571b 100644 --- a/third_party/blink/renderer/core/html/lazy_load_image_observer.cc +++ b/third_party/blink/renderer/core/html/lazy_load_image_observer.cc
@@ -171,7 +171,7 @@ visible_load_time_metrics.record_visibility_metrics = false; visibility_metrics_observer_->unobserve(image_element); - TimeDelta visible_load_delay; + base::TimeDelta visible_load_delay; if (!visible_load_time_metrics.time_when_first_visible.is_null()) { visible_load_delay = CurrentTimeTicks() - visible_load_time_metrics.time_when_first_visible;
diff --git a/third_party/blink/renderer/core/html/lazy_load_image_observer.h b/third_party/blink/renderer/core/html/lazy_load_image_observer.h index 4e79100a..4d3ea5d 100644 --- a/third_party/blink/renderer/core/html/lazy_load_image_observer.h +++ b/third_party/blink/renderer/core/html/lazy_load_image_observer.h
@@ -30,7 +30,7 @@ bool record_visibility_metrics = false; // Set when the image first becomes visible (i.e. appears in the viewport). - TimeTicks time_when_first_visible; + base::TimeTicks time_when_first_visible; }; LazyLoadImageObserver();
diff --git a/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc b/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc index 7b94089..33cfa4b 100644 --- a/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc +++ b/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc
@@ -25,10 +25,11 @@ namespace { -constexpr TimeDelta kMaxOffscreenDurationUma = TimeDelta::FromHours(1); +constexpr base::TimeDelta kMaxOffscreenDurationUma = + base::TimeDelta::FromHours(1); constexpr int32_t kOffscreenDurationUmaBucketCount = 50; -constexpr TimeDelta kMaxWaitTimeUma = TimeDelta::FromSeconds(30); +constexpr base::TimeDelta kMaxWaitTimeUma = base::TimeDelta::FromSeconds(30); constexpr int32_t kWaitTimeBucketCount = 50; // Returns a int64_t with the following structure: @@ -69,7 +70,7 @@ } void AutoplayUmaHelper::OnAutoplayInitiated(AutoplaySource source) { - base::Optional<TimeDelta> autoplay_wait_time; + base::Optional<base::TimeDelta> autoplay_wait_time; if (!load_start_time_.is_null()) autoplay_wait_time = CurrentTimeTicks() - load_start_time_; DEFINE_STATIC_LOCAL(EnumerationHistogram, video_histogram, @@ -100,12 +101,12 @@ if (source == AutoplaySource::kAttribute) { UMA_HISTOGRAM_CUSTOM_TIMES("Media.Video.Autoplay.Attribute.WaitTime", *autoplay_wait_time, - TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1), kMaxWaitTimeUma, kWaitTimeBucketCount); } else if (source == AutoplaySource::kMethod) { UMA_HISTOGRAM_CUSTOM_TIMES("Media.Video.Autoplay.PlayMethod.WaitTime", *autoplay_wait_time, - TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1), kMaxWaitTimeUma, kWaitTimeBucketCount); } } @@ -115,12 +116,12 @@ if (source == AutoplaySource::kAttribute) { UMA_HISTOGRAM_CUSTOM_TIMES("Media.Audio.Autoplay.Attribute.WaitTime", *autoplay_wait_time, - TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1), kMaxWaitTimeUma, kWaitTimeBucketCount); } else if (source == AutoplaySource::kMethod) { UMA_HISTOGRAM_CUSTOM_TIMES("Media.Audio.Autoplay.PlayMethod.WaitTime", *autoplay_wait_time, - TimeDelta::FromMilliseconds(1), + base::TimeDelta::FromMilliseconds(1), kMaxWaitTimeUma, kWaitTimeBucketCount); } } @@ -355,12 +356,13 @@ UMA_HISTOGRAM_CUSTOM_TIMES( "Media.Video.Autoplay.Muted.PlayMethod.OffscreenDuration", - muted_video_autoplay_offscreen_duration_, TimeDelta::FromMilliseconds(1), - kMaxOffscreenDurationUma, kOffscreenDurationUmaBucketCount); + muted_video_autoplay_offscreen_duration_, + base::TimeDelta::FromMilliseconds(1), kMaxOffscreenDurationUma, + kOffscreenDurationUmaBucketCount); muted_video_offscreen_duration_intersection_observer_->disconnect(); muted_video_offscreen_duration_intersection_observer_ = nullptr; - muted_video_autoplay_offscreen_duration_ = TimeDelta(); + muted_video_autoplay_offscreen_duration_ = base::TimeDelta(); MaybeUnregisterMediaElementPauseListener(); MaybeUnregisterContextDestroyedObserver(); }
diff --git a/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h b/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h index fdce3cc..152ee9c 100644 --- a/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h +++ b/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h
@@ -120,10 +120,10 @@ // The recording stops whenever the playback pauses or the page is unloaded. // The starting time of autoplaying muted video. - TimeTicks muted_video_autoplay_offscreen_start_time_; + base::TimeTicks muted_video_autoplay_offscreen_start_time_; // The duration an autoplaying muted video has been in offscreen. - TimeDelta muted_video_autoplay_offscreen_duration_; + base::TimeDelta muted_video_autoplay_offscreen_duration_; // Whether an autoplaying muted video is visible. bool is_visible_; @@ -134,7 +134,7 @@ Member<IntersectionObserver> muted_video_offscreen_duration_intersection_observer_; - TimeTicks load_start_time_; + base::TimeTicks load_start_time_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/html/media/html_media_element.cc b/third_party/blink/renderer/core/html/media/html_media_element.cc index 9860a85..436394c 100644 --- a/third_party/blink/renderer/core/html/media/html_media_element.cc +++ b/third_party/blink/renderer/core/html/media/html_media_element.cc
@@ -32,6 +32,7 @@ #include "base/auto_reset.h" #include "base/debug/crash_logging.h" #include "base/memory/ptr_util.h" +#include "base/time/time.h" #include "media/base/logging_override_if_enabled.h" #include "third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_client.h" #include "third_party/blink/public/platform/platform.h" @@ -107,7 +108,6 @@ #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/math_extras.h" -#include "third_party/blink/renderer/platform/wtf/time.h" #ifndef LOG_MEDIA_EVENTS // Default to not logging events because so many are generated they can @@ -712,7 +712,7 @@ void HTMLMediaElement::RemovedFrom(ContainerNode& insertion_point) { DVLOG(3) << "removedFrom(" << (void*)this << ", " << insertion_point << ")"; - removed_from_document_timer_.StartOneShot(TimeDelta(), FROM_HERE); + removed_from_document_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); HTMLElement::RemovedFrom(insertion_point); } @@ -735,14 +735,14 @@ pending_action_flags_ |= kLoadTextTrackResource; if (!load_timer_.IsActive()) - load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void HTMLMediaElement::ScheduleNextSourceChild() { // Schedule the timer to try the next <source> element WITHOUT resetting state // ala invokeLoadAlgorithm. pending_action_flags_ |= kLoadMediaResource; - load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void HTMLMediaElement::ScheduleEvent(const AtomicString& event_name) { @@ -1328,7 +1328,7 @@ ChangeNetworkStateFromLoadingToIdle(); // 3. Queue a task to set the element's delaying-the-load-event // flag to false. This stops delaying the load event. - deferred_load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + deferred_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); // 4. Wait for the task to be run. deferred_load_state_ = kWaitingForStopDelayingLoadEventTask; // Continued in executeDeferredLoad(). @@ -1504,7 +1504,7 @@ previous_progress_time_ = WTF::CurrentTime(); // 350ms is not magic, it is in the spec! - progress_event_timer_.StartRepeating(TimeDelta::FromMilliseconds(350), + progress_event_timer_.StartRepeating(base::TimeDelta::FromMilliseconds(350), FROM_HERE); } @@ -2655,8 +2655,8 @@ // The spec says to fire periodic timeupdate events (those sent while playing) // every "15 to 250ms", we choose the slowest frequency -static const TimeDelta kMaxTimeupdateEventFrequency = - TimeDelta::FromMilliseconds(250); +static const base::TimeDelta kMaxTimeupdateEventFrequency = + base::TimeDelta::FromMilliseconds(250); void HTMLMediaElement::StartPlaybackProgressTimer() { if (playback_progress_timer_.IsActive()) @@ -2733,7 +2733,7 @@ media_source_->OnTrackChanged(track); if (!audio_tracks_timer_.IsActive()) - audio_tracks_timer_.StartOneShot(TimeDelta(), FROM_HERE); + audio_tracks_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void HTMLMediaElement::AudioTracksTimerFired(TimerBase*) {
diff --git a/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc b/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc index c7ad8c31..78f797a 100644 --- a/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc +++ b/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc
@@ -19,7 +19,8 @@ namespace { -constexpr TimeDelta kCheckFullscreenInterval = TimeDelta::FromSeconds(1); +constexpr base::TimeDelta kCheckFullscreenInterval = + base::TimeDelta::FromSeconds(1); constexpr float kMostlyFillViewportThresholdOfOccupationProportion = 0.85f; constexpr float kMostlyFillViewportThresholdOfVisibleProportion = 0.75f;
diff --git a/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc b/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc index 580ef9d1..fabd7e4e 100644 --- a/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc +++ b/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc
@@ -14,10 +14,11 @@ namespace { -constexpr TimeDelta kStyleChangeTransitionDuration = - TimeDelta::FromMilliseconds(200); -constexpr TimeDelta kHiddenAnimationDuration = TimeDelta::FromMilliseconds(300); -constexpr TimeDelta kShowToastDuration = TimeDelta::FromSeconds(5); +constexpr base::TimeDelta kStyleChangeTransitionDuration = + base::TimeDelta::FromMilliseconds(200); +constexpr base::TimeDelta kHiddenAnimationDuration = + base::TimeDelta::FromMilliseconds(300); +constexpr base::TimeDelta kShowToastDuration = base::TimeDelta::FromSeconds(5); } // namespace
diff --git a/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc b/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc index 17a3f6f8..5159cdf 100644 --- a/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc +++ b/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc
@@ -20,10 +20,10 @@ namespace { -constexpr TimeDelta kPictureInPictureStyleChangeTransitionDuration = - TimeDelta::FromMilliseconds(200); -constexpr TimeDelta kPictureInPictureHiddenAnimationSeconds = - TimeDelta::FromMilliseconds(300); +constexpr base::TimeDelta kPictureInPictureStyleChangeTransitionDuration = + base::TimeDelta::FromMilliseconds(200); +constexpr base::TimeDelta kPictureInPictureHiddenAnimationSeconds = + base::TimeDelta::FromMilliseconds(300); } // namespace
diff --git a/third_party/blink/renderer/core/html/parser/html_document_parser.cc b/third_party/blink/renderer/core/html/parser/html_document_parser.cc index 2cde1b90..a1463f3 100644 --- a/third_party/blink/renderer/core/html/parser/html_document_parser.cc +++ b/third_party/blink/renderer/core/html/parser/html_document_parser.cc
@@ -1220,7 +1220,7 @@ void HTMLDocumentParser::DocumentElementAvailable() { TRACE_EVENT0("blink,loading", "HTMLDocumentParser::DocumentElementAvailable"); - TimeDelta delta; + base::TimeDelta delta; if (!appcache_queueing_start_time_.is_null()) { delta = CurrentTimeTicks() - appcache_queueing_start_time_; }
diff --git a/third_party/blink/renderer/core/html/parser/html_document_parser.h b/third_party/blink/renderer/core/html/parser/html_document_parser.h index 07dba79..eb38afe 100644 --- a/third_party/blink/renderer/core/html/parser/html_document_parser.h +++ b/third_party/blink/renderer/core/html/parser/html_document_parser.h
@@ -248,7 +248,7 @@ base::WeakPtr<BackgroundHTMLParser> background_parser_; Member<HTMLResourcePreloader> preloader_; PreloadRequestStream queued_preloads_; - TimeTicks appcache_queueing_start_time_; + base::TimeTicks appcache_queueing_start_time_; // If this is non-null, then there is a meta CSP token somewhere in the // speculation buffer. Preloads will be deferred until a token matching this
diff --git a/third_party/blink/renderer/core/html/track/html_track_element.cc b/third_party/blink/renderer/core/html/track/html_track_element.cc index 52747a1..66efed10d 100644 --- a/third_party/blink/renderer/core/html/track/html_track_element.cc +++ b/third_party/blink/renderer/core/html/track/html_track_element.cc
@@ -163,7 +163,7 @@ // 4. Run the remainder of these steps in parallel, allowing whatever caused // these steps to run to continue. - load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); // 5. Top: Await a stable state. The synchronous section consists of the // following steps. (The steps in the synchronous section are marked with [X])
diff --git a/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc b/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc index 28fe0d2..98cd16e 100644 --- a/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc +++ b/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc
@@ -69,7 +69,7 @@ constexpr float kLineHeight = 5.33; // Default scrolling animation time period (s). -constexpr TimeDelta kScrollTime = TimeDelta::FromMilliseconds(433); +constexpr base::TimeDelta kScrollTime = base::TimeDelta::FromMilliseconds(433); bool IsNonPercentage(double value, const char* method, @@ -401,7 +401,8 @@ if (scroll_timer_.IsActive()) return; - TimeDelta duration = IsScrollingRegion() ? kScrollTime : TimeDelta(); + base::TimeDelta duration = + IsScrollingRegion() ? kScrollTime : base::TimeDelta(); scroll_timer_.StartOneShot(duration, FROM_HERE); }
diff --git a/third_party/blink/renderer/core/input/event_handler.cc b/third_party/blink/renderer/core/input/event_handler.cc index a1f929f..85eb8fa 100644 --- a/third_party/blink/renderer/core/input/event_handler.cc +++ b/third_party/blink/renderer/core/input/event_handler.cc
@@ -127,8 +127,8 @@ // The amount of time to wait for a cursor update on style and layout changes // Set to 50Hz, no need to be faster than common screen refresh rate -static constexpr TimeDelta kCursorUpdateInterval = - TimeDelta::FromMilliseconds(20); +static constexpr base::TimeDelta kCursorUpdateInterval = + base::TimeDelta::FromMilliseconds(20); static const int kMaximumCursorSize = 128; @@ -144,7 +144,8 @@ // The minimum amount of time an element stays active after a ShowPress // This is roughly 9 frames, which should be long enough to be noticeable. -constexpr TimeDelta kMinimumActiveInterval = TimeDelta::FromSecondsD(0.15); +constexpr base::TimeDelta kMinimumActiveInterval = + base::TimeDelta::FromSecondsD(0.15); EventHandler::EventHandler(LocalFrame& frame) : frame_(frame), @@ -1733,7 +1734,7 @@ HitTestRequest::HitTestRequestType hit_type = gesture_manager_->GetHitTypeForGestureType(gesture_event.GetType()); - TimeDelta active_interval; + base::TimeDelta active_interval; bool should_keep_active_for_min_interval = false; if (read_only) { hit_type |= HitTestRequest::kReadOnly; @@ -2019,7 +2020,7 @@ // TODO(https://crbug.com/668758): Use a normal BeginFrame update for this. if (!hover_timer_.IsActive() && !mouse_event_manager_->IsMousePositionUnknown()) - hover_timer_.StartOneShot(TimeDelta(), FROM_HERE); + hover_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void EventHandler::ScheduleCursorUpdate() {
diff --git a/third_party/blink/renderer/core/input/event_handler.h b/third_party/blink/renderer/core/input/event_handler.h index 5d04f0e..9000231 100644 --- a/third_party/blink/renderer/core/input/event_handler.h +++ b/third_party/blink/renderer/core/input/event_handler.h
@@ -471,7 +471,7 @@ // It is ok we only record last_show_press_timestamp_ in root frame since // root frame will have subframe as active element if subframe has active // element. - base::Optional<WTF::TimeTicks> last_show_press_timestamp_; + base::Optional<base::TimeTicks> last_show_press_timestamp_; Member<Element> last_deferred_tap_element_; // Set on GestureTapDown if unique_touch_event_id_ matches cached adjusted
diff --git a/third_party/blink/renderer/core/input/event_handler_test.cc b/third_party/blink/renderer/core/input/event_handler_test.cc index 0fd3e70..650bba71 100644 --- a/third_party/blink/renderer/core/input/event_handler_test.cc +++ b/third_party/blink/renderer/core/input/event_handler_test.cc
@@ -1452,7 +1452,7 @@ EXPECT_TRUE(iframe_doc->GetActiveElement()); // The active will cancel after 15ms. - test::RunDelayedTasks(TimeDelta::FromSecondsD(0.2)); + test::RunDelayedTasks(base::TimeDelta::FromSecondsD(0.2)); EXPECT_FALSE(GetDocument().GetActiveElement()); EXPECT_FALSE(iframe_doc->GetActiveElement()); }
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.cc b/third_party/blink/renderer/core/input/mouse_event_manager.cc index bccaac6..61348ac 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.cc +++ b/third_party/blink/renderer/core/input/mouse_event_manager.cc
@@ -84,23 +84,23 @@ // The amount of time to wait before sending a fake mouse event triggered // during a scroll. -constexpr TimeDelta kFakeMouseMoveIntervalDuringScroll = - TimeDelta::FromMilliseconds(100); +constexpr base::TimeDelta kFakeMouseMoveIntervalDuringScroll = + base::TimeDelta::FromMilliseconds(100); // The amount of time to wait before sending a fake mouse event on style and // layout changes sets to 50Hz, same as common screen refresh rate. -constexpr TimeDelta kFakeMouseMoveIntervalAfterLayoutChange = - TimeDelta::FromMilliseconds(20); +constexpr base::TimeDelta kFakeMouseMoveIntervalAfterLayoutChange = + base::TimeDelta::FromMilliseconds(20); // TODO(crbug.com/653490): Read these values from the OS. #if defined(OS_MACOSX) const int kDragThresholdX = 3; const int kDragThresholdY = 3; -constexpr TimeDelta kTextDragDelay = TimeDelta::FromSecondsD(0.15); +constexpr base::TimeDelta kTextDragDelay = base::TimeDelta::FromSecondsD(0.15); #else const int kDragThresholdX = 4; const int kDragThresholdY = 4; -constexpr TimeDelta kTextDragDelay = TimeDelta::FromSecondsD(0.0); +constexpr base::TimeDelta kTextDragDelay = base::TimeDelta::FromSecondsD(0.0); #endif } // namespace @@ -132,7 +132,7 @@ click_element_ = nullptr; mouse_down_element_ = nullptr; mouse_down_pos_ = IntPoint(); - mouse_down_timestamp_ = TimeTicks(); + mouse_down_timestamp_ = base::TimeTicks(); mouse_down_ = WebMouseEvent(); svg_pan_ = false; drag_start_pos_ = PhysicalOffset(); @@ -673,7 +673,7 @@ // during a scroll. This avoids a potential source of scroll jank. // Or dispatch a fake mouse move to update hover states when the layout // changes. - TimeDelta interval = + base::TimeDelta interval = update_hover_reason == MouseEventManager::UpdateHoverReason::kScrollOffsetChanged ? kFakeMouseMoveIntervalDuringScroll
diff --git a/third_party/blink/renderer/core/input/mouse_event_manager.h b/third_party/blink/renderer/core/input/mouse_event_manager.h index dd339b4..18ad3a3 100644 --- a/third_party/blink/renderer/core/input/mouse_event_manager.h +++ b/third_party/blink/renderer/core/input/mouse_event_manager.h
@@ -248,7 +248,7 @@ Member<Element> mouse_down_element_; IntPoint mouse_down_pos_; // In our view's coords. - TimeTicks mouse_down_timestamp_; + base::TimeTicks mouse_down_timestamp_; WebMouseEvent mouse_down_; PhysicalOffset drag_start_pos_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc index 0c65cee..d45e364 100644 --- a/third_party/blink/renderer/core/inspector/inspector_css_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_css_agent.cc
@@ -1136,7 +1136,7 @@ for (CSSPropertyID property_id : CSSPropertyIDList()) { const CSSProperty& property_class = CSSProperty::Get(resolveCSSPropertyID(property_id)); - if (!property_class.IsEnabled() || property_class.IsShorthand() || + if (!property_class.IsWebExposed() || property_class.IsShorthand() || !property_class.IsProperty()) continue; (*style)->emplace_back(
diff --git a/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc b/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc index b893efba..b53e403 100644 --- a/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc
@@ -126,7 +126,7 @@ Element* element) { style_attr_invalidated_elements_.insert(element); if (!timer_.IsActive()) - timer_.StartOneShot(TimeDelta(), FROM_HERE); + timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void InspectorRevalidateDOMTask::OnTimer(TimerBase*) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc index 21b0e05..ca139ca 100644 --- a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
@@ -317,7 +317,7 @@ *virtual_time_ticks_base_ms = 0; } else { *virtual_time_ticks_base_ms = - (virtual_time_base_ticks_ - WTF::TimeTicks()).InMillisecondsF(); + (virtual_time_base_ticks_ - base::TimeTicks()).InMillisecondsF(); } return response; @@ -333,8 +333,8 @@ if (new_policy.virtual_time_budget_ms) { TRACE_EVENT_ASYNC_BEGIN1("renderer.scheduler", "VirtualTimeBudget", this, "budget", *new_policy.virtual_time_budget_ms); - WTF::TimeDelta budget_amount = - WTF::TimeDelta::FromMillisecondsD(*new_policy.virtual_time_budget_ms); + base::TimeDelta budget_amount = + base::TimeDelta::FromMillisecondsD(*new_policy.virtual_time_budget_ms); web_local_frame_->View()->Scheduler()->GrantVirtualTimeBudget( budget_amount, WTF::Bind(&InspectorEmulationAgent::VirtualTimeBudgetExpired,
diff --git a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h index 6b699173..4150a23a 100644 --- a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
@@ -107,7 +107,7 @@ void ApplyVirtualTimePolicy(const PendingVirtualTimePolicy& new_policy); Member<WebLocalFrameImpl> web_local_frame_; - WTF::TimeTicks virtual_time_base_ticks_; + base::TimeTicks virtual_time_base_ticks_; std::unique_ptr<TimeZoneController::TimeZoneOverride> timezone_override_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc b/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc index 0b9a417..6f7c750 100644 --- a/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc
@@ -535,14 +535,14 @@ FloatRect rect; if (clip_rect.isJust()) ParseRect(clip_rect.fromJust(), &rect); - auto timings = - snapshot->Profile(min_repeat_count.fromMaybe(1), - TimeDelta::FromSecondsD(min_duration.fromMaybe(0)), - clip_rect.isJust() ? &rect : nullptr); + auto timings = snapshot->Profile( + min_repeat_count.fromMaybe(1), + base::TimeDelta::FromSecondsD(min_duration.fromMaybe(0)), + clip_rect.isJust() ? &rect : nullptr); *out_timings = std::make_unique<Array<Array<double>>>(); for (const auto& row : timings) { auto out_row = std::make_unique<protocol::Array<double>>(); - for (TimeDelta delta : row) + for (base::TimeDelta delta : row) out_row->emplace_back(delta.InSecondsF()); (*out_timings)->emplace_back(std::move(out_row)); }
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index 425ee244..7f029b4 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -1030,12 +1030,13 @@ resources_data_->AddPendingEncodedDataLength(request_id, encoded_data_length); } -void InspectorNetworkAgent::DidFinishLoading(uint64_t identifier, - DocumentLoader* loader, - TimeTicks monotonic_finish_time, - int64_t encoded_data_length, - int64_t decoded_body_length, - bool should_report_corb_blocking) { +void InspectorNetworkAgent::DidFinishLoading( + uint64_t identifier, + DocumentLoader* loader, + base::TimeTicks monotonic_finish_time, + int64_t encoded_data_length, + int64_t decoded_body_length, + bool should_report_corb_blocking) { String request_id = IdentifiersFactory::RequestId(loader, identifier); NetworkResourcesData::ResourceData const* resource_data = resources_data_->Data(request_id); @@ -1060,7 +1061,7 @@ monotonic_finish_time = CurrentTimeTicks(); is_handling_sync_xhr_ = false; - // TODO(npm): Use TimeTicks in Network.h. + // TODO(npm): Use base::TimeTicks in Network.h. GetFrontend()->loadingFinished( request_id, monotonic_finish_time.since_origin().InSecondsF(), encoded_data_length, should_report_corb_blocking); @@ -1073,7 +1074,7 @@ Resource* resource) { // Update the response and finish loading DidReceiveResourceResponse(identifier, loader, response, resource); - DidFinishLoading(identifier, loader, TimeTicks(), + DidFinishLoading(identifier, loader, base::TimeTicks(), WebURLLoaderClient::kUnknownEncodedDataLength, 0, false); }
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.h b/third_party/blink/renderer/core/inspector/inspector_network_agent.h index 6be907a..df0f5327 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.h
@@ -127,7 +127,7 @@ size_t encoded_data_length); void DidFinishLoading(uint64_t identifier, DocumentLoader*, - TimeTicks monotonic_finish_time, + base::TimeTicks monotonic_finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking);
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index 0df9657..c8ed469 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -1014,7 +1014,7 @@ SetInspectTool(MakeGarbageCollected<ShowViewSizeTool>()); resize_timer_active_ = true; resize_timer_.Stop(); - resize_timer_.StartOneShot(TimeDelta::FromSeconds(1), FROM_HERE); + resize_timer_.StartOneShot(base::TimeDelta::FromSeconds(1), FROM_HERE); } void InspectorOverlayAgent::Dispatch(const String& message) { @@ -1028,7 +1028,7 @@ // the main page layout to avoid document lifecycle issues caused by // Microtask::PerformCheckpoint() called when we rebuild the overlay page. resize_timer_.Stop(); - resize_timer_.StartOneShot(TimeDelta::FromSeconds(0), FROM_HERE); + resize_timer_.StartOneShot(base::TimeDelta::FromSeconds(0), FROM_HERE); return; } ScheduleUpdate();
diff --git a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc index d6084eb..628c4c3a 100644 --- a/third_party/blink/renderer/core/inspector/inspector_page_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_page_agent.cc
@@ -587,33 +587,34 @@ continue; DocumentLoadTiming& timing = loader->GetTiming(); - TimeTicks commit_timestamp = timing.ResponseEnd(); + base::TimeTicks commit_timestamp = timing.ResponseEnd(); if (!commit_timestamp.is_null()) { LifecycleEvent(frame, loader, "commit", commit_timestamp.since_origin().InSecondsF()); } - TimeTicks domcontentloaded_timestamp = + base::TimeTicks domcontentloaded_timestamp = document->GetTiming().DomContentLoadedEventEnd(); if (!domcontentloaded_timestamp.is_null()) { LifecycleEvent(frame, loader, "DOMContentLoaded", domcontentloaded_timestamp.since_origin().InSecondsF()); } - TimeTicks load_timestamp = timing.LoadEventEnd(); + base::TimeTicks load_timestamp = timing.LoadEventEnd(); if (!load_timestamp.is_null()) { LifecycleEvent(frame, loader, "load", load_timestamp.since_origin().InSecondsF()); } IdlenessDetector* idleness_detector = frame->GetIdlenessDetector(); - TimeTicks network_almost_idle_timestamp = + base::TimeTicks network_almost_idle_timestamp = idleness_detector->GetNetworkAlmostIdleTime(); if (!network_almost_idle_timestamp.is_null()) { LifecycleEvent(frame, loader, "networkAlmostIdle", network_almost_idle_timestamp.since_origin().InSecondsF()); } - TimeTicks network_idle_timestamp = idleness_detector->GetNetworkIdleTime(); + base::TimeTicks network_idle_timestamp = + idleness_detector->GetNetworkIdleTime(); if (!network_idle_timestamp.is_null()) { LifecycleEvent(frame, loader, "networkIdle", network_idle_timestamp.since_origin().InSecondsF());
diff --git a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc index 6f822fe..c553b0b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc
@@ -51,11 +51,11 @@ void InspectorPerformanceAgent::InnerEnable() { instrumenting_agents_->AddInspectorPerformanceAgent(this); Thread::Current()->AddTaskTimeObserver(this); - layout_start_ticks_ = TimeTicks(); - recalc_style_start_ticks_ = TimeTicks(); - task_start_ticks_ = TimeTicks(); - script_start_ticks_ = TimeTicks(); - v8compile_start_ticks_ = TimeTicks(); + layout_start_ticks_ = base::TimeTicks(); + recalc_style_start_ticks_ = base::TimeTicks(); + task_start_ticks_ = base::TimeTicks(); + script_start_ticks_ = base::TimeTicks(); + v8compile_start_ticks_ = base::TimeTicks(); thread_time_origin_ = GetThreadTimeNow(); } @@ -111,12 +111,12 @@ return Response::OK(); } -TimeTicks InspectorPerformanceAgent::GetTimeTicksNow() { +base::TimeTicks InspectorPerformanceAgent::GetTimeTicksNow() { return use_thread_ticks_.Get() ? GetThreadTimeNow() : base::subtle::TimeTicksNowIgnoringOverride(); } -TimeTicks InspectorPerformanceAgent::GetThreadTimeNow() { +base::TimeTicks InspectorPerformanceAgent::GetThreadTimeNow() { return base::TimeTicks() + base::TimeDelta::FromMicroseconds( base::ThreadTicks::Now().since_origin().InMicroseconds()); @@ -145,7 +145,7 @@ } // Page performance metrics. - TimeTicks now = GetTimeTicksNow(); + base::TimeTicks now = GetTimeTicksNow(); AppendMetric(result.get(), "LayoutCount", static_cast<double>(layout_count_)); AppendMetric(result.get(), "RecalcStyleCount", static_cast<double>(recalc_style_count_)); @@ -153,30 +153,30 @@ AppendMetric(result.get(), "RecalcStyleDuration", recalc_style_duration_.InSecondsF()); - TimeDelta script_duration = script_duration_; + base::TimeDelta script_duration = script_duration_; if (!script_start_ticks_.is_null()) script_duration += now - script_start_ticks_; AppendMetric(result.get(), "ScriptDuration", script_duration.InSecondsF()); - TimeDelta v8compile_duration = v8compile_duration_; + base::TimeDelta v8compile_duration = v8compile_duration_; if (!v8compile_start_ticks_.is_null()) v8compile_duration += now - v8compile_start_ticks_; AppendMetric(result.get(), "V8CompileDuration", v8compile_duration.InSecondsF()); - TimeDelta task_duration = task_duration_; + base::TimeDelta task_duration = task_duration_; if (!task_start_ticks_.is_null()) task_duration += now - task_start_ticks_; AppendMetric(result.get(), "TaskDuration", task_duration.InSecondsF()); // Compute task time not accounted for by other metrics. - TimeDelta other_tasks_duration = + base::TimeDelta other_tasks_duration = task_duration - (script_duration + recalc_style_duration_ + layout_duration_); AppendMetric(result.get(), "TaskOtherDuration", other_tasks_duration.InSecondsF()); - TimeDelta thread_time = GetThreadTimeNow() - thread_time_origin_; + base::TimeDelta thread_time = GetThreadTimeNow() - thread_time_origin_; AppendMetric(result.get(), "ThreadTime", thread_time.InSecondsF()); v8::HeapStatistics heap_statistics; @@ -228,7 +228,7 @@ if (--script_call_depth_) return; script_duration_ += GetTimeTicksNow() - script_start_ticks_; - script_start_ticks_ = TimeTicks(); + script_start_ticks_ = base::TimeTicks(); } void InspectorPerformanceAgent::Will(const probe::CallFunction& probe) { @@ -252,10 +252,10 @@ } void InspectorPerformanceAgent::Did(const probe::RecalculateStyle& probe) { - TimeDelta delta = GetTimeTicksNow() - recalc_style_start_ticks_; + base::TimeDelta delta = GetTimeTicksNow() - recalc_style_start_ticks_; recalc_style_duration_ += delta; recalc_style_count_++; - recalc_style_start_ticks_ = TimeTicks(); + recalc_style_start_ticks_ = base::TimeTicks(); // Exclude nested style re-calculations from script and layout duration. if (!script_start_ticks_.is_null()) @@ -272,10 +272,10 @@ void InspectorPerformanceAgent::Did(const probe::UpdateLayout& probe) { if (--layout_depth_) return; - TimeDelta delta = GetTimeTicksNow() - layout_start_ticks_; + base::TimeDelta delta = GetTimeTicksNow() - layout_start_ticks_; layout_duration_ += delta; layout_count_++; - layout_start_ticks_ = TimeTicks(); + layout_start_ticks_ = base::TimeTicks(); // Exclude nested layout update from script and style re-calculations // duration. @@ -292,7 +292,7 @@ void InspectorPerformanceAgent::Did(const probe::V8Compile& probe) { v8compile_duration_ += GetTimeTicksNow() - v8compile_start_ticks_; - v8compile_start_ticks_ = TimeTicks(); + v8compile_start_ticks_ = base::TimeTicks(); } // Will/DidProcessTask() ignore caller provided times to ensure time domain @@ -305,7 +305,7 @@ base::TimeTicks end_time) { if (!task_start_ticks_.is_null()) task_duration_ += GetTimeTicksNow() - task_start_ticks_; - task_start_ticks_ = TimeTicks(); + task_start_ticks_ = base::TimeTicks(); } void InspectorPerformanceAgent::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/core/inspector/inspector_performance_agent.h b/third_party/blink/renderer/core/inspector/inspector_performance_agent.h index 9202700..48ed7f5f 100644 --- a/third_party/blink/renderer/core/inspector/inspector_performance_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_performance_agent.h
@@ -67,21 +67,21 @@ void ScriptStarts(); void ScriptEnds(); void InnerEnable(); - TimeTicks GetTimeTicksNow(); - TimeTicks GetThreadTimeNow(); + base::TimeTicks GetTimeTicksNow(); + base::TimeTicks GetThreadTimeNow(); Member<InspectedFrames> inspected_frames_; - TimeDelta layout_duration_; - TimeTicks layout_start_ticks_; - TimeDelta recalc_style_duration_; - TimeTicks recalc_style_start_ticks_; - TimeDelta script_duration_; - TimeTicks script_start_ticks_; - TimeDelta task_duration_; - TimeTicks task_start_ticks_; - TimeDelta v8compile_duration_; - TimeTicks v8compile_start_ticks_; - TimeTicks thread_time_origin_; + base::TimeDelta layout_duration_; + base::TimeTicks layout_start_ticks_; + base::TimeDelta recalc_style_duration_; + base::TimeTicks recalc_style_start_ticks_; + base::TimeDelta script_duration_; + base::TimeTicks script_start_ticks_; + base::TimeDelta task_duration_; + base::TimeTicks task_start_ticks_; + base::TimeDelta v8compile_duration_; + base::TimeTicks v8compile_start_ticks_; + base::TimeTicks thread_time_origin_; uint64_t layout_count_ = 0; uint64_t recalc_style_count_ = 0; int script_call_depth_ = 0;
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index 9bdc8c0..c11673d 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -156,7 +156,7 @@ void InspectorTraceEvents::DidFinishLoading(uint64_t identifier, DocumentLoader* loader, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking) { @@ -176,7 +176,7 @@ TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish", TRACE_EVENT_SCOPE_THREAD, "data", inspector_resource_finish_event::Data( - loader, identifier, TimeTicks(), true, 0, 0)); + loader, identifier, base::TimeTicks(), true, 0, 0)); } void InspectorTraceEvents::Will(const probe::ExecuteScript&) {} @@ -841,7 +841,7 @@ std::unique_ptr<TracedValue> inspector_resource_finish_event::Data( DocumentLoader* loader, uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, bool did_fail, int64_t encoded_data_length, int64_t decoded_body_length) { @@ -875,7 +875,7 @@ std::unique_ptr<TracedValue> inspector_timer_install_event::Data( ExecutionContext* context, int timer_id, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot) { std::unique_ptr<TracedValue> value = GenericTimerData(context, timer_id); value->SetDouble("timeout", timeout.InMillisecondsF());
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.h b/third_party/blink/renderer/core/inspector/inspector_trace_events.h index 938ed14..a1a9977d7 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.h +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.h
@@ -104,7 +104,7 @@ uint64_t data_length); void DidFinishLoading(uint64_t identifier, DocumentLoader*, - TimeTicks monotonic_finish_time, + base::TimeTicks monotonic_finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); @@ -298,7 +298,7 @@ namespace inspector_resource_finish_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, bool did_fail, int64_t encoded_data_length, int64_t decoded_body_length); @@ -307,7 +307,7 @@ namespace inspector_timer_install_event { std::unique_ptr<TracedValue> Data(ExecutionContext*, int timer_id, - TimeDelta timeout, + base::TimeDelta timeout, bool single_shot); }
diff --git a/third_party/blink/renderer/core/inspector/thread_debugger.cc b/third_party/blink/renderer/core/inspector/thread_debugger.cc index e50cda9..675108b 100644 --- a/third_party/blink/renderer/core/inspector/thread_debugger.cc +++ b/third_party/blink/renderer/core/inspector/thread_debugger.cc
@@ -493,7 +493,7 @@ &ThreadDebugger::OnTimer); TaskRunnerTimer<ThreadDebugger>* timer_ptr = timer.get(); timers_.push_back(std::move(timer)); - timer_ptr->StartRepeating(TimeDelta::FromSecondsD(interval), FROM_HERE); + timer_ptr->StartRepeating(base::TimeDelta::FromSecondsD(interval), FROM_HERE); } void ThreadDebugger::cancelTimer(void* data) {
diff --git a/third_party/blink/renderer/core/layout/layout_progress.cc b/third_party/blink/renderer/core/layout/layout_progress.cc index ebc3235..25c8830 100644 --- a/third_party/blink/renderer/core/layout/layout_progress.cc +++ b/third_party/blink/renderer/core/layout/layout_progress.cc
@@ -61,7 +61,7 @@ double LayoutProgress::AnimationProgress() const { if (!animating_) return 0; - TimeDelta elapsed = CurrentTimeTicks() - animation_start_time_; + base::TimeDelta elapsed = CurrentTimeTicks() - animation_start_time_; return (elapsed % animation_duration_).InSecondsF() / animation_duration_.InSecondsF(); } @@ -92,7 +92,7 @@ LayoutTheme::GetTheme().AnimationRepeatIntervalForProgressBar(); bool animating = !IsDeterminate() && StyleRef().HasAppearance() && - animation_duration_ > TimeDelta(); + animation_duration_ > base::TimeDelta(); if (animating == animating_) return;
diff --git a/third_party/blink/renderer/core/layout/layout_progress.h b/third_party/blink/renderer/core/layout/layout_progress.h index ab8a0cbd..7430461 100644 --- a/third_party/blink/renderer/core/layout/layout_progress.h +++ b/third_party/blink/renderer/core/layout/layout_progress.h
@@ -58,9 +58,9 @@ void UpdateAnimationState(); double position_; - TimeTicks animation_start_time_; - TimeDelta animation_repeat_interval_; - TimeDelta animation_duration_; + base::TimeTicks animation_start_time_; + base::TimeDelta animation_repeat_interval_; + base::TimeDelta animation_duration_; bool animating_; TaskRunnerTimer<LayoutProgress> animation_timer_;
diff --git a/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h b/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h index f158bb4..01595041 100644 --- a/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h +++ b/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h
@@ -60,11 +60,11 @@ .ShouldSnapBackToDragOrigin(scrollbar, event); } - TimeDelta InitialAutoscrollTimerDelay() override { + base::TimeDelta InitialAutoscrollTimerDelay() override { return ScrollbarTheme::DeprecatedStaticGetTheme() .InitialAutoscrollTimerDelay(); } - TimeDelta AutoscrollTimerDelay() override { + base::TimeDelta AutoscrollTimerDelay() override { return ScrollbarTheme::DeprecatedStaticGetTheme().AutoscrollTimerDelay(); }
diff --git a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc index 95114d6..b394179 100644 --- a/third_party/blink/renderer/core/layout/layout_shift_tracker.cc +++ b/third_party/blink/renderer/core/layout/layout_shift_tracker.cc
@@ -25,7 +25,8 @@ namespace blink { -static constexpr TimeDelta kTimerDelay = TimeDelta::FromMilliseconds(500); +static constexpr base::TimeDelta kTimerDelay = + base::TimeDelta::FromMilliseconds(500); static const float kRegionGranularitySteps = 60.0; // TODO: Vary by Finch experiment parameter. static const float kSweepLineRegionGranularity = 1.0;
diff --git a/third_party/blink/renderer/core/layout/layout_text.cc b/third_party/blink/renderer/core/layout/layout_text.cc index bc19a3c..a522759 100644 --- a/third_party/blink/renderer/core/layout/layout_text.cc +++ b/third_party/blink/renderer/core/layout/layout_text.cc
@@ -103,9 +103,9 @@ void RestartWithNewText(unsigned last_typed_character_offset) { last_typed_character_offset_ = last_typed_character_offset; if (Settings* settings = layout_text_->GetDocument().GetSettings()) { - StartOneShot( - TimeDelta::FromSecondsD(settings->GetPasswordEchoDurationInSeconds()), - FROM_HERE); + StartOneShot(base::TimeDelta::FromSecondsD( + settings->GetPasswordEchoDurationInSeconds()), + FROM_HERE); } } void Invalidate() { last_typed_character_offset_ = -1; }
diff --git a/third_party/blink/renderer/core/layout/layout_theme.cc b/third_party/blink/renderer/core/layout/layout_theme.cc index c827173..f217d34 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.cc +++ b/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -446,12 +446,12 @@ void LayoutTheme::AdjustMenuListStyle(ComputedStyle&, Element*) const {} -TimeDelta LayoutTheme::AnimationRepeatIntervalForProgressBar() const { - return TimeDelta(); +base::TimeDelta LayoutTheme::AnimationRepeatIntervalForProgressBar() const { + return base::TimeDelta(); } -TimeDelta LayoutTheme::AnimationDurationForProgressBar() const { - return TimeDelta(); +base::TimeDelta LayoutTheme::AnimationDurationForProgressBar() const { + return base::TimeDelta(); } bool LayoutTheme::ShouldHaveSpinButton(HTMLInputElement* input_element) const { @@ -489,14 +489,14 @@ Page::PlatformColorsChanged(); } -void LayoutTheme::SetCaretBlinkInterval(TimeDelta interval) { +void LayoutTheme::SetCaretBlinkInterval(base::TimeDelta interval) { caret_blink_interval_ = interval; } -TimeDelta LayoutTheme::CaretBlinkInterval() const { +base::TimeDelta LayoutTheme::CaretBlinkInterval() const { // Disable the blinking caret in web test mode, as it introduces // a race condition for the pixel tests. http://b/1198440 - return WebTestSupport::IsRunningWebTest() ? TimeDelta() + return WebTestSupport::IsRunningWebTest() ? base::TimeDelta() : caret_blink_interval_; }
diff --git a/third_party/blink/renderer/core/layout/layout_theme.h b/third_party/blink/renderer/core/layout/layout_theme.h index bd2d5aa..86168e3 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.h +++ b/third_party/blink/renderer/core/layout/layout_theme.h
@@ -180,8 +180,8 @@ } virtual void PlatformColorsDidChange(); - void SetCaretBlinkInterval(TimeDelta); - virtual TimeDelta CaretBlinkInterval() const; + void SetCaretBlinkInterval(base::TimeDelta); + virtual base::TimeDelta CaretBlinkInterval() const; // System fonts and colors for CSS. virtual void SystemFont(CSSValueID system_font_id, @@ -222,9 +222,9 @@ virtual void AdjustProgressBarBounds(ComputedStyle& style) const {} // Returns the repeat interval of the animation for the progress bar. - virtual TimeDelta AnimationRepeatIntervalForProgressBar() const; + virtual base::TimeDelta AnimationRepeatIntervalForProgressBar() const; // Returns the duration of the animation for the progress bar. - virtual TimeDelta AnimationDurationForProgressBar() const; + virtual base::TimeDelta AnimationDurationForProgressBar() const; // Returns size of one slider tick mark for a horizontal track. // For vertical tracks we rotate it and use it. i.e. Width is always length @@ -355,7 +355,8 @@ Color custom_focus_ring_color_; bool has_custom_focus_ring_color_; - TimeDelta caret_blink_interval_ = TimeDelta::FromMilliseconds(500); + base::TimeDelta caret_blink_interval_ = + base::TimeDelta::FromMilliseconds(500); // This color is expected to be drawn on a semi-transparent overlay, // making it more transparent than its alpha value indicates.
diff --git a/third_party/blink/renderer/core/layout/layout_theme_default.cc b/third_party/blink/renderer/core/layout/layout_theme_default.cc index 9fcf1da..327fe540 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_default.cc +++ b/third_party/blink/renderer/core/layout/layout_theme_default.cc
@@ -52,7 +52,7 @@ unsigned LayoutThemeDefault::inactive_selection_background_color_ = 0xffc8c8c8; unsigned LayoutThemeDefault::inactive_selection_foreground_color_ = 0xff323232; -TimeDelta LayoutThemeDefault::caret_blink_interval_; +base::TimeDelta LayoutThemeDefault::caret_blink_interval_; LayoutThemeDefault::LayoutThemeDefault() : LayoutTheme(), painter_(*this) { caret_blink_interval_ = LayoutTheme::CaretBlinkInterval(); @@ -387,14 +387,15 @@ // The following values come from the defaults of GTK+. // constexpr int kProgressAnimationFrames = 10; -constexpr TimeDelta kProgressAnimationInterval = - TimeDelta::FromMilliseconds(125); +constexpr base::TimeDelta kProgressAnimationInterval = + base::TimeDelta::FromMilliseconds(125); -TimeDelta LayoutThemeDefault::AnimationRepeatIntervalForProgressBar() const { +base::TimeDelta LayoutThemeDefault::AnimationRepeatIntervalForProgressBar() + const { return kProgressAnimationInterval; } -TimeDelta LayoutThemeDefault::AnimationDurationForProgressBar() const { +base::TimeDelta LayoutThemeDefault::AnimationDurationForProgressBar() const { return kProgressAnimationInterval * kProgressAnimationFrames * 2; // "2" for back and forth }
diff --git a/third_party/blink/renderer/core/layout/layout_theme_default.h b/third_party/blink/renderer/core/layout/layout_theme_default.h index 10150906..6fad09eb 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_default.h +++ b/third_party/blink/renderer/core/layout/layout_theme_default.h
@@ -111,8 +111,8 @@ void AdjustMenuListStyle(ComputedStyle&, Element*) const override; void AdjustMenuListButtonStyle(ComputedStyle&, Element*) const override; - TimeDelta AnimationRepeatIntervalForProgressBar() const override; - TimeDelta AnimationDurationForProgressBar() const override; + base::TimeDelta AnimationRepeatIntervalForProgressBar() const override; + base::TimeDelta AnimationDurationForProgressBar() const override; // These methods define the padding for the MenuList's inner block. int PopupInternalPaddingStart(const ComputedStyle&) const override; @@ -145,7 +145,7 @@ int MenuListInternalPadding(const ComputedStyle&, int padding) const; static const RGBA32 kDefaultTapHighlightColor = 0x2e000000; // 18% black. - static TimeDelta caret_blink_interval_; + static base::TimeDelta caret_blink_interval_; static unsigned active_selection_background_color_; static unsigned active_selection_foreground_color_;
diff --git a/third_party/blink/renderer/core/layout/layout_theme_mac.h b/third_party/blink/renderer/core/layout/layout_theme_mac.h index 8ef37025..87bd2a9 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_mac.h +++ b/third_party/blink/renderer/core/layout/layout_theme_mac.h
@@ -86,9 +86,9 @@ bool PopsMenuBySpaceKey() const final { return true; } // Returns the repeat interval of the animation for the progress bar. - TimeDelta AnimationRepeatIntervalForProgressBar() const override; + base::TimeDelta AnimationRepeatIntervalForProgressBar() const override; // Returns the duration of the animation for the progress bar. - TimeDelta AnimationDurationForProgressBar() const override; + base::TimeDelta AnimationDurationForProgressBar() const override; Color SystemColor(CSSValueID) const override; @@ -153,8 +153,8 @@ // We estimate the animation rate of a Mac OS X progress bar is 33 fps. // Hard code the value here because we haven't found API for it. - static constexpr TimeDelta kProgressAnimationFrameRate = - TimeDelta::FromMilliseconds(33); + static constexpr base::TimeDelta kProgressAnimationFrameRate = + base::TimeDelta::FromMilliseconds(33); // Mac OS X progress bar animation seems to have 256 frames. static constexpr double kProgressAnimationNumFrames = 256;
diff --git a/third_party/blink/renderer/core/layout/layout_theme_mac.mm b/third_party/blink/renderer/core/layout/layout_theme_mac.mm index 501d389..b759ec74 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_mac.mm +++ b/third_party/blink/renderer/core/layout/layout_theme_mac.mm
@@ -678,13 +678,13 @@ return kSizes; } -constexpr TimeDelta LayoutThemeMac::kProgressAnimationFrameRate; +constexpr base::TimeDelta LayoutThemeMac::kProgressAnimationFrameRate; -TimeDelta LayoutThemeMac::AnimationRepeatIntervalForProgressBar() const { +base::TimeDelta LayoutThemeMac::AnimationRepeatIntervalForProgressBar() const { return kProgressAnimationFrameRate; } -TimeDelta LayoutThemeMac::AnimationDurationForProgressBar() const { +base::TimeDelta LayoutThemeMac::AnimationDurationForProgressBar() const { return kProgressAnimationNumFrames * kProgressAnimationFrameRate; }
diff --git a/third_party/blink/renderer/core/layout/layout_view.cc b/third_party/blink/renderer/core/layout/layout_view.cc index e4cc98ba..773c214 100644 --- a/third_party/blink/renderer/core/layout/layout_view.cc +++ b/third_party/blink/renderer/core/layout/layout_view.cc
@@ -73,7 +73,7 @@ allows_child_frame_content_(allows_child_frame_content) {} ~HitTestLatencyRecorder() { - TimeDelta duration = CurrentTimeTicks() - start_; + base::TimeDelta duration = CurrentTimeTicks() - start_; if (allows_child_frame_content_) { DEFINE_STATIC_LOCAL(CustomCountHistogram, recursive_latency_histogram, ("Event.Latency.HitTestRecursive", 0, 10000000, 100)); @@ -86,7 +86,7 @@ } private: - TimeTicks start_; + base::TimeTicks start_; bool allows_child_frame_content_; };
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc index a2ebfbb..4c1c7ee 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc
@@ -99,10 +99,13 @@ return false; // Check a character in text content after |fragment_| comes from same // layout text of |fragment_|. - const NGOffsetMapping& mapping = - *NGOffsetMapping::GetFor(fragment_->GetLayoutObject()); + const NGOffsetMapping* mapping = + NGOffsetMapping::GetFor(fragment_->GetLayoutObject()); + // TODO(kojii): There's not much we can do for dirty-tree. crbug.com/946004 + if (!mapping) + return false; const base::span<const NGOffsetMappingUnit> mapping_units = - mapping.GetMappingUnitsForTextContentOffsetRange( + mapping->GetMappingUnitsForTextContentOffsetRange( text_fragment.EndOffset(), text_fragment.EndOffset() + 1); if (mapping_units.begin() == mapping_units.end()) return false;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc index 9fd60d2..17410fb 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
@@ -2145,26 +2145,16 @@ builder.SetAdjoiningFloatTypes(container_builder_.AdjoiningFloatTypes()); } - LayoutUnit space_available; if (ConstraintSpace().HasBlockFragmentation()) { - space_available = ConstraintSpace().FragmentainerSpaceAtBfcStart(); - // If a block establishes a new formatting context we must know our - // position in the formatting context, and are able to adjust the + LayoutUnit new_bfc_block_offset; + // If a block establishes a new formatting context, we must know our + // position in the formatting context, to be able to adjust the // fragmentation line. if (is_new_fc) - space_available -= child_data.bfc_offset_estimate.block_offset; - - // The policy regarding collapsing block-start margin with the fragmentainer - // block-start is the same throughout the entire fragmentainer (although it - // really only matters at the beginning of each fragmentainer, we don't need - // to bother to check whether we're actually at the start). - builder.SetSeparateLeadingFragmentainerMargins( - ConstraintSpace().HasSeparateLeadingFragmentainerMargins()); - builder.SetFragmentainerBlockSize( - ConstraintSpace().FragmentainerBlockSize()); - builder.SetFragmentainerSpaceAtBfcStart(space_available); - builder.SetFragmentationType(ConstraintSpace().BlockFragmentationType()); + new_bfc_block_offset = child_data.bfc_offset_estimate.block_offset; + SetupFragmentation(ConstraintSpace(), new_bfc_block_offset, &builder); } + return builder.ToConstraintSpace(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index 9e015da..c054761 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -70,9 +70,9 @@ callback(&algorithm); } -inline void DetermineAlgorithmAndRun( - const NGLayoutAlgorithmParams& params, - const std::function<void(NGLayoutAlgorithmOperations*)>& callback) { +template <typename Callback> +inline void DetermineAlgorithmAndRun(const NGLayoutAlgorithmParams& params, + const Callback& callback) { const ComputedStyle& style = params.node.Style(); const LayoutBox& box = *params.node.GetLayoutBox(); if (box.IsLayoutNGFlexibleBox()) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc index e3127d0..ea675b4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
@@ -78,11 +78,7 @@ DCHECK(parent_space.HasBlockFragmentation()); DCHECK_EQ(style.GetWritingMode(), parent_space.GetWritingMode()); - LayoutUnit fragmentation_offset = - parent_space.FragmentainerSpaceAtBfcStart() - *origin_block_offset; - builder.SetFragmentainerBlockSize(parent_space.FragmentainerBlockSize()); - builder.SetFragmentainerSpaceAtBfcStart(fragmentation_offset); - builder.SetFragmentationType(parent_space.BlockFragmentationType()); + SetupFragmentation(parent_space, *origin_block_offset, &builder); } else { builder.SetFragmentationType(NGFragmentationType::kFragmentNone); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc index 9c556e34..9fd9dd4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
@@ -7,6 +7,7 @@ #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h" +#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" namespace blink { @@ -111,4 +112,23 @@ return !child.IsFloating() && !child.IsOutOfFlowPositioned(); } +void SetupFragmentation(const NGConstraintSpace& parent_space, + LayoutUnit new_bfc_block_offset, + NGConstraintSpaceBuilder* builder) { + DCHECK(parent_space.HasBlockFragmentation()); + + LayoutUnit space_available = + parent_space.FragmentainerSpaceAtBfcStart() - new_bfc_block_offset; + + // The policy regarding collapsing block-start margin with the fragmentainer + // block-start is the same throughout the entire fragmentainer (although it + // really only matters at the beginning of each fragmentainer, we don't need + // to bother to check whether we're actually at the start). + builder->SetSeparateLeadingFragmentainerMargins( + parent_space.HasSeparateLeadingFragmentainerMargins()); + builder->SetFragmentainerBlockSize(parent_space.FragmentainerBlockSize()); + builder->SetFragmentainerSpaceAtBfcStart(space_available); + builder->SetFragmentationType(parent_space.BlockFragmentationType()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h index 31ead905..0656d92 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
@@ -71,6 +71,16 @@ return token && !token->IsBreakBefore(); } +// Set up a child's constraint space builder for block fragmentation. The child +// participates in the same fragmentation context as parent_space. If the child +// establishes a new formatting context, new_bfc_block_offset must be set to the +// offset from the parent block formatting context, or, if the parent formatting +// context starts in a previous fragmentainer; the offset from the current +// fragmentainer block-start. +void SetupFragmentation(const NGConstraintSpace& parent_space, + LayoutUnit new_bfc_block_offset, + NGConstraintSpaceBuilder*); + } // namespace blink #endif // NGFragmentationUtils_h
diff --git a/third_party/blink/renderer/core/layout/scrollbars_test.cc b/third_party/blink/renderer/core/layout/scrollbars_test.cc index 2fc54f3..01e0a4c8 100644 --- a/third_party/blink/renderer/core/layout/scrollbars_test.cc +++ b/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -185,7 +185,7 @@ // Some task queues may have repeating v8 tasks that run forever so we impose // a hard (virtual) time limit. - void RunTasksForPeriod(TimeDelta delay) { + void RunTasksForPeriod(base::TimeDelta delay) { TimeAdvance(); scheduler::GetSingleThreadTaskRunnerForTesting()->PostDelayedTask( FROM_HERE, @@ -1332,7 +1332,8 @@ TEST_F(ScrollbarsTestWithVirtualTimer, TestNonCompositedOverlayScrollbarsFade) { #endif TimeAdvance(); - constexpr TimeDelta kMockOverlayFadeOutDelay = TimeDelta::FromSeconds(5); + constexpr base::TimeDelta kMockOverlayFadeOutDelay = + base::TimeDelta::FromSeconds(5); ScrollbarTheme& theme = GetScrollbarTheme(); // This test relies on mock overlay scrollbars. @@ -1416,7 +1417,7 @@ RunTasksForPeriod(kMockOverlayFadeOutDelay); EXPECT_TRUE(scrollable_area->ScrollbarsHiddenIfOverlay()); - mock_overlay_theme.SetOverlayScrollbarFadeOutDelay(TimeDelta()); + mock_overlay_theme.SetOverlayScrollbarFadeOutDelay(base::TimeDelta()); } typedef bool TestParamOverlayScrollbar; @@ -1444,8 +1445,8 @@ } } void GetOverlayScrollbarStyle(ScrollbarStyle* style) override { - style->fade_out_delay = TimeDelta(); - style->fade_out_duration = TimeDelta(); + style->fade_out_delay = base::TimeDelta(); + style->fade_out_duration = base::TimeDelta(); style->thumb_thickness = 3; style->scrollbar_margin = 0; style->color = SkColorSetARGB(128, 64, 64, 64); @@ -2481,7 +2482,7 @@ SimRequest request("https://example.com/test.html", "text/html"); LoadURL("https://example.com/test.html"); - RunTasksForPeriod(TimeDelta::FromMilliseconds(1000)); + RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000)); request.Complete(R"HTML( <!DOCTYPE html> <style> @@ -2527,15 +2528,15 @@ ASSERT_EQ(scrollbar->PressedPart(), ScrollbarPart::kForwardButtonEndPart); // Wait for 2 delay. - RunTasksForPeriod(TimeDelta::FromMilliseconds(1000)); - RunTasksForPeriod(TimeDelta::FromMilliseconds(1000)); + RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000)); + RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000)); // Change #big size. MainFrame().ExecuteScript(WebScriptSource( "document.getElementById('big').style.height = '1000px';")); Compositor().BeginFrame(); - RunTasksForPeriod(TimeDelta::FromMilliseconds(1000)); - RunTasksForPeriod(TimeDelta::FromMilliseconds(1000)); + RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000)); + RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000)); // Verify that the scrollbar autopress timer requested some scrolls via // gestures. The button was pressed for 2 seconds and the timer fires
diff --git a/third_party/blink/renderer/core/loader/document_load_timing.cc b/third_party/blink/renderer/core/loader/document_load_timing.cc index fdf9dba..2a5fee8 100644 --- a/third_party/blink/renderer/core/loader/document_load_timing.cc +++ b/third_party/blink/renderer/core/loader/document_load_timing.cc
@@ -68,23 +68,25 @@ } void DocumentLoadTiming::EnsureReferenceTimesSet() { - if (reference_wall_time_.is_zero()) - reference_wall_time_ = TimeDelta::FromSecondsD(clock_->Now().ToDoubleT()); + if (reference_wall_time_.is_zero()) { + reference_wall_time_ = + base::TimeDelta::FromSecondsD(clock_->Now().ToDoubleT()); + } if (reference_monotonic_time_.is_null()) reference_monotonic_time_ = tick_clock_->NowTicks(); } -TimeDelta DocumentLoadTiming::MonotonicTimeToZeroBasedDocumentTime( - TimeTicks monotonic_time) const { +base::TimeDelta DocumentLoadTiming::MonotonicTimeToZeroBasedDocumentTime( + base::TimeTicks monotonic_time) const { if (monotonic_time.is_null() || reference_monotonic_time_.is_null()) - return TimeDelta(); + return base::TimeDelta(); return monotonic_time - reference_monotonic_time_; } -TimeDelta DocumentLoadTiming::MonotonicTimeToPseudoWallTime( - TimeTicks monotonic_time) const { +base::TimeDelta DocumentLoadTiming::MonotonicTimeToPseudoWallTime( + base::TimeTicks monotonic_time) const { if (monotonic_time.is_null() || reference_monotonic_time_.is_null()) - return TimeDelta(); + return base::TimeDelta(); return monotonic_time + reference_wall_time_ - reference_monotonic_time_; } @@ -118,7 +120,7 @@ return data; } -void DocumentLoadTiming::SetNavigationStart(TimeTicks navigation_start) { +void DocumentLoadTiming::SetNavigationStart(base::TimeTicks navigation_start) { // |m_referenceMonotonicTime| and |m_referenceWallTime| represent // navigationStart. We must set these to the current time if they haven't // been set yet in order to have a valid reference time in both units. @@ -136,7 +138,7 @@ NotifyDocumentTimingChanged(); } -void DocumentLoadTiming::SetInputStart(TimeTicks input_start) { +void DocumentLoadTiming::SetInputStart(base::TimeTicks input_start) { input_start_ = input_start; NotifyDocumentTimingChanged(); } @@ -156,7 +158,7 @@ !redirected_security_origin->CanRequest(redirecting_url); } -void DocumentLoadTiming::SetRedirectStart(TimeTicks redirect_start) { +void DocumentLoadTiming::SetRedirectStart(base::TimeTicks redirect_start) { redirect_start_ = redirect_start; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "redirectStart", redirect_start_, "frame", @@ -164,7 +166,7 @@ NotifyDocumentTimingChanged(); } -void DocumentLoadTiming::SetRedirectEnd(TimeTicks redirect_end) { +void DocumentLoadTiming::SetRedirectEnd(base::TimeTicks redirect_end) { redirect_end_ = redirect_end; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "redirectEnd", redirect_end_, "frame", @@ -172,7 +174,7 @@ NotifyDocumentTimingChanged(); } -void DocumentLoadTiming::MarkUnloadEventStart(TimeTicks start_time) { +void DocumentLoadTiming::MarkUnloadEventStart(base::TimeTicks start_time) { unload_event_start_ = start_time; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "unloadEventStart", start_time, "frame", @@ -180,7 +182,7 @@ NotifyDocumentTimingChanged(); } -void DocumentLoadTiming::MarkUnloadEventEnd(TimeTicks end_time) { +void DocumentLoadTiming::MarkUnloadEventEnd(base::TimeTicks end_time) { unload_event_end_ = end_time; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "unloadEventEnd", end_time, "frame", ToTraceValue(GetFrame())); @@ -191,7 +193,7 @@ SetFetchStart(tick_clock_->NowTicks()); } -void DocumentLoadTiming::SetFetchStart(TimeTicks fetch_start) { +void DocumentLoadTiming::SetFetchStart(base::TimeTicks fetch_start) { fetch_start_ = fetch_start; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "fetchStart", fetch_start_, "frame", @@ -199,7 +201,7 @@ NotifyDocumentTimingChanged(); } -void DocumentLoadTiming::SetResponseEnd(TimeTicks response_end) { +void DocumentLoadTiming::SetResponseEnd(base::TimeTicks response_end) { response_end_ = response_end; TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "responseEnd", response_end_, "frame",
diff --git a/third_party/blink/renderer/core/loader/document_load_timing.h b/third_party/blink/renderer/core/loader/document_load_timing.h index 20d973c8..4a3583a 100644 --- a/third_party/blink/renderer/core/loader/document_load_timing.h +++ b/third_party/blink/renderer/core/loader/document_load_timing.h
@@ -49,29 +49,29 @@ public: explicit DocumentLoadTiming(DocumentLoader&); - TimeDelta MonotonicTimeToZeroBasedDocumentTime(TimeTicks) const; - TimeDelta MonotonicTimeToPseudoWallTime(TimeTicks) const; + base::TimeDelta MonotonicTimeToZeroBasedDocumentTime(base::TimeTicks) const; + base::TimeDelta MonotonicTimeToPseudoWallTime(base::TimeTicks) const; void MarkNavigationStart(); - void SetNavigationStart(TimeTicks); + void SetNavigationStart(base::TimeTicks); - void SetInputStart(TimeTicks); + void SetInputStart(base::TimeTicks); void AddRedirect(const KURL& redirecting_url, const KURL& redirected_url); - void SetRedirectStart(TimeTicks); - void SetRedirectEnd(TimeTicks); + void SetRedirectStart(base::TimeTicks); + void SetRedirectEnd(base::TimeTicks); void SetRedirectCount(uint16_t value) { redirect_count_ = value; } void SetHasCrossOriginRedirect(bool value) { has_cross_origin_redirect_ = value; } - void MarkUnloadEventStart(TimeTicks); - void MarkUnloadEventEnd(TimeTicks); + void MarkUnloadEventStart(base::TimeTicks); + void MarkUnloadEventEnd(base::TimeTicks); void MarkFetchStart(); - void SetFetchStart(TimeTicks); + void SetFetchStart(base::TimeTicks); - void SetResponseEnd(TimeTicks); + void SetResponseEnd(base::TimeTicks); void MarkLoadEventStart(); void MarkLoadEventEnd(); @@ -80,23 +80,25 @@ has_same_origin_as_previous_document_ = value; } - TimeTicks InputStart() const { return input_start_; } - TimeTicks NavigationStart() const { return navigation_start_; } - TimeTicks UnloadEventStart() const { return unload_event_start_; } - TimeTicks UnloadEventEnd() const { return unload_event_end_; } - TimeTicks RedirectStart() const { return redirect_start_; } - TimeTicks RedirectEnd() const { return redirect_end_; } + base::TimeTicks InputStart() const { return input_start_; } + base::TimeTicks NavigationStart() const { return navigation_start_; } + base::TimeTicks UnloadEventStart() const { return unload_event_start_; } + base::TimeTicks UnloadEventEnd() const { return unload_event_end_; } + base::TimeTicks RedirectStart() const { return redirect_start_; } + base::TimeTicks RedirectEnd() const { return redirect_end_; } uint16_t RedirectCount() const { return redirect_count_; } - TimeTicks FetchStart() const { return fetch_start_; } - TimeTicks ResponseEnd() const { return response_end_; } - TimeTicks LoadEventStart() const { return load_event_start_; } - TimeTicks LoadEventEnd() const { return load_event_end_; } + base::TimeTicks FetchStart() const { return fetch_start_; } + base::TimeTicks ResponseEnd() const { return response_end_; } + base::TimeTicks LoadEventStart() const { return load_event_start_; } + base::TimeTicks LoadEventEnd() const { return load_event_end_; } bool HasCrossOriginRedirect() const { return has_cross_origin_redirect_; } bool HasSameOriginAsPreviousDocument() const { return has_same_origin_as_previous_document_; } - TimeTicks ReferenceMonotonicTime() const { return reference_monotonic_time_; } + base::TimeTicks ReferenceMonotonicTime() const { + return reference_monotonic_time_; + } void Trace(blink::Visitor*); @@ -110,19 +112,19 @@ LocalFrame* GetFrame() const; std::unique_ptr<TracedValue> GetNavigationStartTracingData() const; - TimeTicks reference_monotonic_time_; - TimeDelta reference_wall_time_; - TimeTicks input_start_; - TimeTicks navigation_start_; - TimeTicks unload_event_start_; - TimeTicks unload_event_end_; - TimeTicks redirect_start_; - TimeTicks redirect_end_; + base::TimeTicks reference_monotonic_time_; + base::TimeDelta reference_wall_time_; + base::TimeTicks input_start_; + base::TimeTicks navigation_start_; + base::TimeTicks unload_event_start_; + base::TimeTicks unload_event_end_; + base::TimeTicks redirect_start_; + base::TimeTicks redirect_end_; uint16_t redirect_count_; - TimeTicks fetch_start_; - TimeTicks response_end_; - TimeTicks load_event_start_; - TimeTicks load_event_end_; + base::TimeTicks fetch_start_; + base::TimeTicks response_end_; + base::TimeTicks load_event_start_; + base::TimeTicks load_event_end_; bool has_cross_origin_redirect_; bool has_same_origin_as_previous_document_;
diff --git a/third_party/blink/renderer/core/loader/document_load_timing_test.cc b/third_party/blink/renderer/core/loader/document_load_timing_test.cc index a524ad0..12ac1d7 100644 --- a/third_party/blink/renderer/core/loader/document_load_timing_test.cc +++ b/third_party/blink/renderer/core/loader/document_load_timing_test.cc
@@ -23,7 +23,7 @@ embedder_navigation_start)); double real_wall_time = CurrentTime(); - TimeDelta adjusted_wall_time = + base::TimeDelta adjusted_wall_time = timing.MonotonicTimeToPseudoWallTime(timing.NavigationStart()); EXPECT_NEAR(adjusted_wall_time.InSecondsF(), real_wall_time + delta, .001); @@ -45,13 +45,13 @@ // dominated by the navigationStartDelta, but similar to currentTime(). timing.MarkLoadEventEnd(); double real_wall_load_event_end = CurrentTime(); - TimeDelta adjusted_load_event_end = + base::TimeDelta adjusted_load_event_end = timing.MonotonicTimeToPseudoWallTime(timing.LoadEventEnd()); EXPECT_NEAR(adjusted_load_event_end.InSecondsF(), real_wall_load_event_end, .001); - TimeDelta adjusted_navigation_start = + base::TimeDelta adjusted_navigation_start = timing.MonotonicTimeToPseudoWallTime(timing.NavigationStart()); EXPECT_NEAR( (adjusted_load_event_end - adjusted_navigation_start).InSecondsF(),
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index 91b90d9..ee3c4eb 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -548,7 +548,7 @@ } void DocumentLoader::BodyLoadingFinished( - TimeTicks completion_time, + base::TimeTicks completion_time, int64_t total_encoded_data_length, int64_t total_encoded_body_length, int64_t total_decoded_body_length, @@ -618,7 +618,7 @@ params_ = nullptr; } -void DocumentLoader::FinishedLoading(TimeTicks finish_time) { +void DocumentLoader::FinishedLoading(base::TimeTicks finish_time) { body_loader_.reset(); virtual_time_pauser_.UnpauseVirtualTime(); @@ -678,7 +678,7 @@ // In any way, by this point we should have already committed. DCHECK_GE(state_, kCommitted); - TimeTicks response_end_time = finish_time; + base::TimeTicks response_end_time = finish_time; if (response_end_time.is_null()) response_end_time = time_of_last_data_received_; if (response_end_time.is_null())
diff --git a/third_party/blink/renderer/core/loader/document_loader.h b/third_party/blink/renderer/core/loader/document_loader.h index 254a14d..02f29915 100644 --- a/third_party/blink/renderer/core/loader/document_loader.h +++ b/third_party/blink/renderer/core/loader/document_loader.h
@@ -337,7 +337,7 @@ ContentSecurityPolicy* CreateCSP(const ResourceResponse&, const String& origin_policy_string); void StartLoadingInternal(); - void FinishedLoading(TimeTicks finish_time); + void FinishedLoading(base::TimeTicks finish_time); void CancelLoadAfterCSPDenied(const ResourceResponse&); enum class HistoryNavigationType { @@ -367,7 +367,7 @@ // WebNavigationBodyLoader::Client void BodyCodeCacheReceived(base::span<const uint8_t>) override; void BodyDataReceived(base::span<const char> data) override; - void BodyLoadingFinished(TimeTicks completion_time, + void BodyLoadingFinished(base::TimeTicks completion_time, int64_t total_encoded_data_length, int64_t total_encoded_body_length, int64_t total_decoded_body_length, @@ -440,7 +440,7 @@ DocumentLoadTiming document_load_timing_; - TimeTicks time_of_last_data_received_; + base::TimeTicks time_of_last_data_received_; Member<ApplicationCacheHost> application_cache_host_;
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.cc b/third_party/blink/renderer/core/loader/frame_fetch_context.cc index c1d5f86..d60d57e 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.cc
@@ -649,7 +649,7 @@ mojom::FeaturePolicyFeature::kClientHintRTT, resource_origin))) && ShouldSendClientHint(mojom::WebClientHintsType::kRtt, hints_preferences, enabled_hints)) { - base::Optional<TimeDelta> http_rtt = + base::Optional<base::TimeDelta> http_rtt = GetNetworkStateNotifier().GetWebHoldbackHttpRtt(); if (!http_rtt) { http_rtt = GetNetworkStateNotifier().HttpRtt();
diff --git a/third_party/blink/renderer/core/loader/http_equiv.cc b/third_party/blink/renderer/core/loader/http_equiv.cc index af0137a..9d81ae54 100644 --- a/third_party/blink/renderer/core/loader/http_equiv.cc +++ b/third_party/blink/renderer/core/loader/http_equiv.cc
@@ -57,7 +57,7 @@ // Notifies content settings client of persistent client hint headers. void NotifyPersistentClientHintsToContentSettingsClient(Document& document) { - TimeDelta persist_duration = + base::TimeDelta persist_duration = document.GetFrame()->GetClientHintsPreferences().GetPersistDuration(); if (persist_duration.InSeconds() <= 0) return;
diff --git a/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc b/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc index 7e52798..d5ccaf2 100644 --- a/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc +++ b/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc
@@ -124,7 +124,7 @@ navigate_task_handle_ = PostDelayedCancellableTask( *document_->GetTaskRunner(TaskType::kInternalLoading), FROM_HERE, WTF::Bind(&HttpRefreshScheduler::NavigateTask, WrapWeakPersistent(this)), - TimeDelta::FromSecondsD(refresh_->delay)); + base::TimeDelta::FromSecondsD(refresh_->delay)); probe::FrameScheduledNavigation(document_->GetFrame(), refresh_->url, refresh_->delay, refresh_->reason);
diff --git a/third_party/blink/renderer/core/loader/idleness_detector.cc b/third_party/blink/renderer/core/loader/idleness_detector.cc index bd75d24..91439c37 100644 --- a/third_party/blink/renderer/core/loader/idleness_detector.cc +++ b/third_party/blink/renderer/core/loader/idleness_detector.cc
@@ -26,8 +26,8 @@ namespace blink { -constexpr TimeDelta IdlenessDetector::kNetworkQuietWindow; -constexpr TimeDelta IdlenessDetector::kNetworkQuietWatchdog; +constexpr base::TimeDelta IdlenessDetector::kNetworkQuietWindow; +constexpr base::TimeDelta IdlenessDetector::kNetworkQuietWatchdog; void IdlenessDetector::Shutdown() { Stop(); @@ -37,10 +37,10 @@ void IdlenessDetector::WillCommitLoad() { in_network_2_quiet_period_ = false; in_network_0_quiet_period_ = false; - network_2_quiet_ = TimeTicks(); - network_0_quiet_ = TimeTicks(); - network_2_quiet_start_time_ = TimeTicks(); - network_0_quiet_start_time_ = TimeTicks(); + network_2_quiet_ = base::TimeTicks(); + network_0_quiet_ = base::TimeTicks(); + network_2_quiet_start_time_ = base::TimeTicks(); + network_0_quiet_start_time_ = base::TimeTicks(); } void IdlenessDetector::DomContentLoadedEventFired() { @@ -54,8 +54,8 @@ in_network_2_quiet_period_ = true; in_network_0_quiet_period_ = true; - network_2_quiet_ = TimeTicks(); - network_0_quiet_ = TimeTicks(); + network_2_quiet_ = base::TimeTicks(); + network_0_quiet_ = base::TimeTicks(); OnDidLoadResource(); } @@ -72,9 +72,9 @@ int request_count = fetcher->ActiveRequestCount() + 1; // If we are above the allowed number of active requests, reset timers. if (in_network_2_quiet_period_ && request_count > 2) - network_2_quiet_ = TimeTicks(); + network_2_quiet_ = base::TimeTicks(); if (in_network_0_quiet_period_ && request_count > 0) - network_0_quiet_ = TimeTicks(); + network_0_quiet_ = base::TimeTicks(); } // This function is called when the number of active connections is decreased. @@ -98,7 +98,7 @@ if (request_count > 2) return; - TimeTicks timestamp = g_clock->NowTicks(); + base::TimeTicks timestamp = g_clock->NowTicks(); // Arriving at =2 updates the quiet_2 base timestamp. // Arriving at <2 sets the quiet_2 base timestamp only if // it was not already set. @@ -121,7 +121,7 @@ } } -TimeTicks IdlenessDetector::GetNetworkAlmostIdleTime() { +base::TimeTicks IdlenessDetector::GetNetworkAlmostIdleTime() { return network_2_quiet_start_time_; } @@ -132,13 +132,13 @@ return false; if (network_2_quiet_start_time_.is_null()) return false; - TimeTicks current_time = TimeTicks::Now(); + base::TimeTicks current_time = base::TimeTicks::Now(); if (current_time - network_2_quiet_start_time_ <= network_quiet_window_) return false; return true; } -TimeTicks IdlenessDetector::GetNetworkIdleTime() { +base::TimeTicks IdlenessDetector::GetNetworkIdleTime() { return network_0_quiet_start_time_; } @@ -170,7 +170,7 @@ } } in_network_2_quiet_period_ = false; - network_2_quiet_ = TimeTicks(); + network_2_quiet_ = base::TimeTicks(); } if (in_network_0_quiet_period_ && !network_0_quiet_.is_null() && @@ -181,7 +181,7 @@ FirstMeaningfulPaintDetector::From(*local_frame_->GetDocument()) .OnNetwork0Quiet(); in_network_0_quiet_period_ = false; - network_0_quiet_ = TimeTicks(); + network_0_quiet_ = base::TimeTicks(); } if (!in_network_0_quiet_period_ && !in_network_2_quiet_period_) @@ -207,7 +207,7 @@ if (!g_clock) g_clock = base::DefaultTickClock::GetInstance(); if (local_frame->GetSettings()) { - network_quiet_window_ = TimeDelta::FromSecondsD( + network_quiet_window_ = base::TimeDelta::FromSecondsD( local_frame->GetSettings()->GetNetworkQuietTimeout()); } }
diff --git a/third_party/blink/renderer/core/loader/idleness_detector.h b/third_party/blink/renderer/core/loader/idleness_detector.h index 2288eb7a..b215436 100644 --- a/third_party/blink/renderer/core/loader/idleness_detector.h +++ b/third_party/blink/renderer/core/loader/idleness_detector.h
@@ -39,8 +39,8 @@ void OnWillSendRequest(ResourceFetcher*); void OnDidLoadResource(); - TimeTicks GetNetworkAlmostIdleTime(); - TimeTicks GetNetworkIdleTime(); + base::TimeTicks GetNetworkAlmostIdleTime(); + base::TimeTicks GetNetworkIdleTime(); bool NetworkIsAlmostIdle(); // The caller owns the |clock| which must outlive the IdlenessDetector. @@ -53,9 +53,10 @@ // The page is quiet if there are no more than 2 active network requests for // this duration of time. - static constexpr TimeDelta kNetworkQuietWindow = - TimeDelta::FromMilliseconds(500); - static constexpr TimeDelta kNetworkQuietWatchdog = TimeDelta::FromSeconds(2); + static constexpr base::TimeDelta kNetworkQuietWindow = + base::TimeDelta::FromMilliseconds(500); + static constexpr base::TimeDelta kNetworkQuietWatchdog = + base::TimeDelta::FromSeconds(2); static constexpr int kNetworkQuietMaximumConnections = 2; // TaskTimeObserver implementation. @@ -72,13 +73,13 @@ bool in_network_0_quiet_period_ = true; bool in_network_2_quiet_period_ = true; - TimeDelta network_quiet_window_ = kNetworkQuietWindow; + base::TimeDelta network_quiet_window_ = kNetworkQuietWindow; // Store the accumulated time of network quiet. - TimeTicks network_0_quiet_; - TimeTicks network_2_quiet_; + base::TimeTicks network_0_quiet_; + base::TimeTicks network_2_quiet_; // Record the actual start time of network quiet. - TimeTicks network_0_quiet_start_time_; - TimeTicks network_2_quiet_start_time_; + base::TimeTicks network_0_quiet_start_time_; + base::TimeTicks network_2_quiet_start_time_; TaskRunnerTimer<IdlenessDetector> network_quiet_timer_; DISALLOW_COPY_AND_ASSIGN(IdlenessDetector);
diff --git a/third_party/blink/renderer/core/loader/interactive_detector.cc b/third_party/blink/renderer/core/loader/interactive_detector.cc index 016389e..6f353fd5 100644 --- a/third_party/blink/renderer/core/loader/interactive_detector.cc +++ b/third_party/blink/renderer/core/loader/interactive_detector.cc
@@ -18,7 +18,7 @@ // Required length of main thread and network quiet window for determining // Time to Interactive. -constexpr auto kTimeToInteractiveWindow = TimeDelta::FromSeconds(5); +constexpr auto kTimeToInteractiveWindow = base::TimeDelta::FromSeconds(5); // Network is considered "quiet" if there are no more than 2 active network // requests for this duration of time. constexpr int kNetworkQuietMaximumConnections = 2; @@ -59,7 +59,7 @@ initially_hidden_(document.hidden()) {} void InteractiveDetector::SetNavigationStartTime( - TimeTicks navigation_start_time) { + base::TimeTicks navigation_start_time) { // Should not set nav start twice. DCHECK(page_event_times_.nav_start.is_null()); @@ -70,7 +70,7 @@ LongTaskDetector::Instance().RegisterObserver(this); page_event_times_.nav_start = navigation_start_time; - TimeTicks initial_timer_fire_time = + base::TimeTicks initial_timer_fire_time = navigation_start_time + kTimeToInteractiveWindow; active_main_thread_quiet_window_start_ = navigation_start_time; @@ -88,24 +88,25 @@ return network_activity_checker_->GetActiveConnections(); } -void InteractiveDetector::StartOrPostponeCITimer(TimeTicks timer_fire_time) { +void InteractiveDetector::StartOrPostponeCITimer( + base::TimeTicks timer_fire_time) { // This function should never be called after Time To Interactive is // reached. DCHECK(interactive_time_.is_null()); // We give 1ms extra padding to the timer fire time to prevent floating point // arithmetic pitfalls when comparing window sizes. - timer_fire_time += TimeDelta::FromMilliseconds(1); + timer_fire_time += base::TimeDelta::FromMilliseconds(1); // Return if there is an active timer scheduled to fire later than // |timer_fire_time|. if (timer_fire_time < time_to_interactive_timer_fire_time_) return; - TimeDelta delay = timer_fire_time - clock_->NowTicks(); + base::TimeDelta delay = timer_fire_time - clock_->NowTicks(); time_to_interactive_timer_fire_time_ = timer_fire_time; - if (delay <= TimeDelta()) { + if (delay <= base::TimeDelta()) { // This argument of this function is never used and only there to fulfill // the API contract. nullptr should work fine. TimeToInteractiveTimerFired(nullptr); @@ -114,50 +115,51 @@ } } -TimeTicks InteractiveDetector::GetInteractiveTime() const { +base::TimeTicks InteractiveDetector::GetInteractiveTime() const { // TODO(crbug.com/808685) Simplify FMP and TTI input invalidation. return page_event_times_.first_meaningful_paint_invalidated - ? TimeTicks() + ? base::TimeTicks() : interactive_time_; } -TimeTicks InteractiveDetector::GetInteractiveDetectionTime() const { +base::TimeTicks InteractiveDetector::GetInteractiveDetectionTime() const { // TODO(crbug.com/808685) Simplify FMP and TTI input invalidation. return page_event_times_.first_meaningful_paint_invalidated - ? TimeTicks() + ? base::TimeTicks() : interactive_detection_time_; } -TimeTicks InteractiveDetector::GetFirstInvalidatingInputTime() const { +base::TimeTicks InteractiveDetector::GetFirstInvalidatingInputTime() const { return page_event_times_.first_invalidating_input; } -TimeDelta InteractiveDetector::GetFirstInputDelay() const { +base::TimeDelta InteractiveDetector::GetFirstInputDelay() const { return page_event_times_.first_input_delay; } -TimeTicks InteractiveDetector::GetFirstInputTimestamp() const { +base::TimeTicks InteractiveDetector::GetFirstInputTimestamp() const { return page_event_times_.first_input_timestamp; } -TimeDelta InteractiveDetector::GetLongestInputDelay() const { +base::TimeDelta InteractiveDetector::GetLongestInputDelay() const { return page_event_times_.longest_input_delay; } -TimeTicks InteractiveDetector::GetLongestInputTimestamp() const { +base::TimeTicks InteractiveDetector::GetLongestInputTimestamp() const { return page_event_times_.longest_input_timestamp; } -bool InteractiveDetector::PageWasBackgroundedSinceEvent(TimeTicks event_time) { +bool InteractiveDetector::PageWasBackgroundedSinceEvent( + base::TimeTicks event_time) { DCHECK(GetSupplementable()); if (GetSupplementable()->hidden()) { return true; } bool curr_hidden = initially_hidden_; - TimeTicks visibility_start = page_event_times_.nav_start; + base::TimeTicks visibility_start = page_event_times_.nav_start; for (auto change_event : visibility_change_events_) { - TimeTicks visibility_end = change_event.timestamp; + base::TimeTicks visibility_end = change_event.timestamp; if (curr_hidden && event_time < visibility_end) { // [event_time, now] intersects a backgrounded range. return true; @@ -171,8 +173,8 @@ void InteractiveDetector::HandleForInputDelay( const Event& event, - TimeTicks event_platform_timestamp, - TimeTicks processing_start) { + base::TimeTicks event_platform_timestamp, + base::TimeTicks processing_start) { DCHECK(event.isTrusted()); // This only happens sometimes on tests unrelated to InteractiveDetector. It @@ -199,8 +201,8 @@ return; // These variables track the values which will be reported to histograms. - TimeDelta delay; - TimeTicks event_timestamp; + base::TimeDelta delay; + base::TimeTicks event_timestamp; if (event.type() == event_type_names::kPointerup) { // PointerUp by itself is not considered a significant input. if (pending_pointerdown_timestamp_.is_null()) @@ -248,7 +250,8 @@ GetSupplementable()->Loader()->DidChangePerformanceTiming(); } -void InteractiveDetector::BeginNetworkQuietPeriod(TimeTicks current_time) { +void InteractiveDetector::BeginNetworkQuietPeriod( + base::TimeTicks current_time) { // Value of 0.0 indicates there is no currently actively network quiet window. DCHECK(active_network_quiet_window_start_.is_null()); active_network_quiet_window_start_ = current_time; @@ -256,7 +259,7 @@ StartOrPostponeCITimer(current_time + kTimeToInteractiveWindow); } -void InteractiveDetector::EndNetworkQuietPeriod(TimeTicks current_time) { +void InteractiveDetector::EndNetworkQuietPeriod(base::TimeTicks current_time) { DCHECK(!active_network_quiet_window_start_.is_null()); if (current_time - active_network_quiet_window_start_ >= @@ -264,31 +267,31 @@ network_quiet_windows_.emplace_back(active_network_quiet_window_start_, current_time); } - active_network_quiet_window_start_ = TimeTicks(); + active_network_quiet_window_start_ = base::TimeTicks(); } // The optional opt_current_time, if provided, saves us a call to // clock_->NowTicks(). void InteractiveDetector::UpdateNetworkQuietState( double request_count, - base::Optional<TimeTicks> opt_current_time) { + base::Optional<base::TimeTicks> opt_current_time) { if (request_count <= kNetworkQuietMaximumConnections && active_network_quiet_window_start_.is_null()) { // Not using `value_or(clock_->NowTicks())` here because arguments to // functions are eagerly evaluated, which always call clock_->NowTicks. - TimeTicks current_time = + base::TimeTicks current_time = opt_current_time ? opt_current_time.value() : clock_->NowTicks(); BeginNetworkQuietPeriod(current_time); } else if (request_count > kNetworkQuietMaximumConnections && !active_network_quiet_window_start_.is_null()) { - TimeTicks current_time = + base::TimeTicks current_time = opt_current_time ? opt_current_time.value() : clock_->NowTicks(); EndNetworkQuietPeriod(current_time); } } void InteractiveDetector::OnResourceLoadBegin( - base::Optional<TimeTicks> load_begin_time) { + base::Optional<base::TimeTicks> load_begin_time) { if (!GetSupplementable()) return; if (!interactive_time_.is_null()) @@ -301,7 +304,7 @@ // The optional load_finish_time, if provided, saves us a call to // clock_->NowTicks. void InteractiveDetector::OnResourceLoadEnd( - base::Optional<TimeTicks> load_finish_time) { + base::Optional<base::TimeTicks> load_finish_time) { if (!GetSupplementable()) return; if (!interactive_time_.is_null()) @@ -309,12 +312,12 @@ UpdateNetworkQuietState(ActiveConnections(), load_finish_time); } -void InteractiveDetector::OnLongTaskDetected(TimeTicks start_time, - TimeTicks end_time) { +void InteractiveDetector::OnLongTaskDetected(base::TimeTicks start_time, + base::TimeTicks end_time) { // We should not be receiving long task notifications after Time to // Interactive has already been reached. DCHECK(interactive_time_.is_null()); - TimeDelta quiet_window_length = + base::TimeDelta quiet_window_length = start_time - active_main_thread_quiet_window_start_; if (quiet_window_length >= kTimeToInteractiveWindow) { main_thread_quiet_windows_.emplace_back( @@ -325,7 +328,7 @@ } void InteractiveDetector::OnFirstMeaningfulPaintDetected( - TimeTicks fmp_time, + base::TimeTicks fmp_time, FirstMeaningfulPaintDetector::HadUserInput user_input_before_fmp) { DCHECK(page_event_times_.first_meaningful_paint .is_null()); // Should not set FMP twice. @@ -341,7 +344,7 @@ } } -void InteractiveDetector::OnDomContentLoadedEnd(TimeTicks dcl_end_time) { +void InteractiveDetector::OnDomContentLoadedEnd(base::TimeTicks dcl_end_time) { // InteractiveDetector should only receive the first DCL event. DCHECK(page_event_times_.dom_content_loaded_end.is_null()); page_event_times_.dom_content_loaded_end = dcl_end_time; @@ -349,7 +352,7 @@ } void InteractiveDetector::OnInvalidatingInputEvent( - TimeTicks invalidation_time) { + base::TimeTicks invalidation_time) { if (!page_event_times_.first_invalidating_input.is_null()) return; @@ -373,12 +376,12 @@ return; // Value of 0.0 indicates there is currently no active timer. - time_to_interactive_timer_fire_time_ = TimeTicks(); + time_to_interactive_timer_fire_time_ = base::TimeTicks(); CheckTimeToInteractiveReached(); } void InteractiveDetector::AddCurrentlyActiveQuietIntervals( - TimeTicks current_time) { + base::TimeTicks current_time) { // Network is currently quiet. if (!active_network_quiet_window_start_.is_null()) { if (current_time - active_network_quiet_window_start_ >= @@ -412,7 +415,8 @@ } } -TimeTicks InteractiveDetector::FindInteractiveCandidate(TimeTicks lower_bound) { +base::TimeTicks InteractiveDetector::FindInteractiveCandidate( + base::TimeTicks lower_bound) { // Main thread iterator. auto it_mt = main_thread_quiet_windows_.begin(); // Network iterator. @@ -444,10 +448,10 @@ } // At this point we know we have a non-empty overlap after lower_bound. - TimeTicks overlap_start = + base::TimeTicks overlap_start = std::max({it_mt->Low(), it_net->Low(), lower_bound}); - TimeTicks overlap_end = std::min(it_mt->High(), it_net->High()); - TimeDelta overlap_duration = overlap_end - overlap_start; + base::TimeTicks overlap_end = std::min(it_mt->High(), it_net->High()); + base::TimeDelta overlap_duration = overlap_end - overlap_start; if (overlap_duration >= kTimeToInteractiveWindow) { return std::max(lower_bound, it_mt->Low()); } @@ -462,7 +466,7 @@ } // Time To Interactive candidate not found. - return TimeTicks(); + return base::TimeTicks(); } void InteractiveDetector::CheckTimeToInteractiveReached() { @@ -475,7 +479,7 @@ page_event_times_.dom_content_loaded_end.is_null()) return; - const TimeTicks current_time = clock_->NowTicks(); + const base::TimeTicks current_time = clock_->NowTicks(); if (current_time - page_event_times_.first_meaningful_paint < kTimeToInteractiveWindow) { // Too close to FMP to determine Time to Interactive. @@ -483,7 +487,7 @@ } AddCurrentlyActiveQuietIntervals(current_time); - const TimeTicks interactive_candidate = + const base::TimeTicks interactive_candidate = FindInteractiveCandidate(page_event_times_.first_meaningful_paint); RemoveCurrentlyActiveQuietIntervals();
diff --git a/third_party/blink/renderer/core/loader/interactive_detector.h b/third_party/blink/renderer/core/loader/interactive_detector.h index 56f66a1..ce47be3 100644 --- a/third_party/blink/renderer/core/loader/interactive_detector.h +++ b/third_party/blink/renderer/core/loader/interactive_detector.h
@@ -69,51 +69,51 @@ // Calls to CurrentTimeTicksInSeconds is expensive, so we try not to call it // unless we really have to. If we already have the event time available, we // pass it in as an argument. - void OnResourceLoadBegin(base::Optional<TimeTicks> load_begin_time); - void OnResourceLoadEnd(base::Optional<TimeTicks> load_finish_time); + void OnResourceLoadBegin(base::Optional<base::TimeTicks> load_begin_time); + void OnResourceLoadEnd(base::Optional<base::TimeTicks> load_finish_time); - void SetNavigationStartTime(TimeTicks navigation_start_time); + void SetNavigationStartTime(base::TimeTicks navigation_start_time); void OnFirstMeaningfulPaintDetected( - TimeTicks fmp_time, + base::TimeTicks fmp_time, FirstMeaningfulPaintDetector::HadUserInput user_input_before_fmp); - void OnDomContentLoadedEnd(TimeTicks dcl_time); - void OnInvalidatingInputEvent(TimeTicks invalidation_time); + void OnDomContentLoadedEnd(base::TimeTicks dcl_time); + void OnInvalidatingInputEvent(base::TimeTicks invalidation_time); void OnPageHiddenChanged(bool is_hidden); // Returns Interactive Time if already detected, or 0.0 otherwise. - TimeTicks GetInteractiveTime() const; + base::TimeTicks GetInteractiveTime() const; // Returns the time when page interactive was detected. The detection time can // be useful to make decisions about metric invalidation in scenarios like tab // backgrounding. - TimeTicks GetInteractiveDetectionTime() const; + base::TimeTicks GetInteractiveDetectionTime() const; // Returns the first time interactive detector received a significant input // that may cause observers to discard the interactive time value. - TimeTicks GetFirstInvalidatingInputTime() const; + base::TimeTicks GetFirstInvalidatingInputTime() const; // The duration between the hardware timestamp and being queued on the main // thread for the first click, tap, key press, cancelable touchstart, or // pointer down followed by a pointer up. - TimeDelta GetFirstInputDelay() const; + base::TimeDelta GetFirstInputDelay() const; // The timestamp of the event whose delay is reported by GetFirstInputDelay(). - TimeTicks GetFirstInputTimestamp() const; + base::TimeTicks GetFirstInputTimestamp() const; // Queueing Time of the meaningful input event with longest delay. Meaningful // input events are click, tap, key press, cancellable touchstart, or pointer // down followed by a pointer up. - TimeDelta GetLongestInputDelay() const; + base::TimeDelta GetLongestInputDelay() const; // The timestamp of the event whose delay is reported by // GetLongestInputDelay(). - TimeTicks GetLongestInputTimestamp() const; + base::TimeTicks GetLongestInputTimestamp() const; // Process an input event, updating first_input_delay and // first_input_timestamp if needed. void HandleForInputDelay(const Event&, - TimeTicks event_platform_timestamp, - TimeTicks processing_start); + base::TimeTicks event_platform_timestamp, + base::TimeTicks processing_start); // ContextLifecycleObserver void ContextDestroyed(ExecutionContext*) override; @@ -130,57 +130,57 @@ const base::TickClock* clock_; - TimeTicks interactive_time_; - TimeTicks interactive_detection_time_; + base::TimeTicks interactive_time_; + base::TimeTicks interactive_detection_time_; // Page event times that Interactive Detector depends on. - // Null TimeTicks values indicate the event has not been detected yet. + // Null base::TimeTicks values indicate the event has not been detected yet. struct { - TimeTicks first_meaningful_paint; - TimeTicks dom_content_loaded_end; - TimeTicks nav_start; - TimeTicks first_invalidating_input; - TimeDelta first_input_delay; - TimeDelta longest_input_delay; - TimeTicks first_input_timestamp; - TimeTicks longest_input_timestamp; + base::TimeTicks first_meaningful_paint; + base::TimeTicks dom_content_loaded_end; + base::TimeTicks nav_start; + base::TimeTicks first_invalidating_input; + base::TimeDelta first_input_delay; + base::TimeDelta longest_input_delay; + base::TimeTicks first_input_timestamp; + base::TimeTicks longest_input_timestamp; bool first_meaningful_paint_invalidated = false; } page_event_times_; struct VisibilityChangeEvent { - TimeTicks timestamp; + base::TimeTicks timestamp; bool was_hidden; }; // Stores sufficiently long quiet windows on main thread and network. - std::vector<WTF::PODInterval<TimeTicks>> main_thread_quiet_windows_; - std::vector<WTF::PODInterval<TimeTicks>> network_quiet_windows_; + std::vector<WTF::PODInterval<base::TimeTicks>> main_thread_quiet_windows_; + std::vector<WTF::PODInterval<base::TimeTicks>> network_quiet_windows_; // Start times of currently active main thread and network quiet windows. - // Null TimeTicks values indicate main thread or network is not quiet at the - // moment. - TimeTicks active_main_thread_quiet_window_start_; - TimeTicks active_network_quiet_window_start_; + // Null base::TimeTicks values indicate main thread or network is not quiet at + // the moment. + base::TimeTicks active_main_thread_quiet_window_start_; + base::TimeTicks active_network_quiet_window_start_; // Adds currently active quiet main thread and network quiet windows to the // vectors. Should be called before calling // FindInteractiveCandidate. - void AddCurrentlyActiveQuietIntervals(TimeTicks current_time); + void AddCurrentlyActiveQuietIntervals(base::TimeTicks current_time); // Undoes AddCurrentlyActiveQuietIntervals. void RemoveCurrentlyActiveQuietIntervals(); std::unique_ptr<NetworkActivityChecker> network_activity_checker_; int ActiveConnections(); - void BeginNetworkQuietPeriod(TimeTicks current_time); - void EndNetworkQuietPeriod(TimeTicks current_time); + void BeginNetworkQuietPeriod(base::TimeTicks current_time); + void EndNetworkQuietPeriod(base::TimeTicks current_time); // Updates current network quietness tracking information. Opens and closes // network quiet windows as necessary. void UpdateNetworkQuietState(double request_count, - base::Optional<TimeTicks> current_time); + base::Optional<base::TimeTicks> current_time); TaskRunnerTimer<InteractiveDetector> time_to_interactive_timer_; - TimeTicks time_to_interactive_timer_fire_time_; - void StartOrPostponeCITimer(TimeTicks timer_fire_time); + base::TimeTicks time_to_interactive_timer_fire_time_; + void StartOrPostponeCITimer(base::TimeTicks timer_fire_time); void TimeToInteractiveTimerFired(TimerBase*); void CheckTimeToInteractiveReached(); void OnTimeToInteractiveDetected(); @@ -189,17 +189,18 @@ bool initially_hidden_; // Returns true if page was ever backgrounded in the range // [event_time, CurrentTimeTicks()]. - bool PageWasBackgroundedSinceEvent(TimeTicks event_time); + bool PageWasBackgroundedSinceEvent(base::TimeTicks event_time); // Finds a window of length kTimeToInteractiveWindowSeconds after lower_bound // such that both main thread and network are quiet. Returns the end of last // long task before that quiet window, or lower_bound, whichever is bigger - // this is called the Interactive Candidate. Returns 0.0 if no such quiet // window is found. - TimeTicks FindInteractiveCandidate(TimeTicks lower_bound); + base::TimeTicks FindInteractiveCandidate(base::TimeTicks lower_bound); // LongTaskObserver implementation - void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) override; + void OnLongTaskDetected(base::TimeTicks start_time, + base::TimeTicks end_time) override; // The duration between the hardware timestamp and when we received the event // for the previous pointer down. Only non-zero if we've received a pointer
diff --git a/third_party/blink/renderer/core/loader/interactive_detector_test.cc b/third_party/blink/renderer/core/loader/interactive_detector_test.cc index a56285be..16d4116c 100644 --- a/third_party/blink/renderer/core/loader/interactive_detector_test.cc +++ b/third_party/blink/renderer/core/loader/interactive_detector_test.cc
@@ -67,7 +67,7 @@ protected: InteractiveDetector* GetDetector() { return detector_; } - TimeTicks GetDummyTaskEndTime() { return dummy_task_end_time_; } + base::TimeTicks GetDummyTaskEndTime() { return dummy_task_end_time_; } NetworkActivityCheckerForTest* GetNetworkActivityChecker() { // We know in this test context that network_activity_checker_ is an @@ -76,36 +76,38 @@ detector_->network_activity_checker_.get()); } - void SimulateNavigationStart(TimeTicks nav_start_time) { + void SimulateNavigationStart(base::TimeTicks nav_start_time) { RunTillTimestamp(nav_start_time); detector_->SetNavigationStartTime(nav_start_time); } - void SimulateLongTask(TimeTicks start, TimeTicks end) { - CHECK(end - start >= TimeDelta::FromSecondsD(0.05)); + void SimulateLongTask(base::TimeTicks start, base::TimeTicks end) { + CHECK(end - start >= base::TimeDelta::FromSecondsD(0.05)); RunTillTimestamp(end); detector_->OnLongTaskDetected(start, end); } - void SimulateDOMContentLoadedEnd(TimeTicks dcl_time) { + void SimulateDOMContentLoadedEnd(base::TimeTicks dcl_time) { RunTillTimestamp(dcl_time); detector_->OnDomContentLoadedEnd(dcl_time); } - void SimulateFMPDetected(TimeTicks fmp_time, TimeTicks detection_time) { + void SimulateFMPDetected(base::TimeTicks fmp_time, + base::TimeTicks detection_time) { RunTillTimestamp(detection_time); detector_->OnFirstMeaningfulPaintDetected( fmp_time, FirstMeaningfulPaintDetector::kNoUserInput); } - void SimulateInteractiveInvalidatingInput(TimeTicks timestamp) { + void SimulateInteractiveInvalidatingInput(base::TimeTicks timestamp) { RunTillTimestamp(timestamp); detector_->OnInvalidatingInputEvent(timestamp); } - void RunTillTimestamp(TimeTicks target_time) { - TimeTicks current_time = Now(); - platform_->RunForPeriod(std::max(TimeDelta(), target_time - current_time)); + void RunTillTimestamp(base::TimeTicks target_time) { + base::TimeTicks current_time = Now(); + platform_->RunForPeriod( + std::max(base::TimeDelta(), target_time - current_time)); } int GetActiveConnections() { @@ -116,14 +118,14 @@ GetNetworkActivityChecker()->SetActiveConnections(active_connections); } - void SimulateResourceLoadBegin(TimeTicks load_begin_time) { + void SimulateResourceLoadBegin(base::TimeTicks load_begin_time) { RunTillTimestamp(load_begin_time); detector_->OnResourceLoadBegin(load_begin_time); // ActiveConnections is incremented after detector runs OnResourceLoadBegin; SetActiveConnections(GetActiveConnections() + 1); } - void SimulateResourceLoadEnd(TimeTicks load_finish_time) { + void SimulateResourceLoadEnd(base::TimeTicks load_finish_time) { RunTillTimestamp(load_finish_time); int active_connections = GetActiveConnections(); SetActiveConnections(active_connections - 1); @@ -132,7 +134,9 @@ base::TimeTicks Now() { return platform_->test_task_runner()->NowTicks(); } - TimeTicks GetInteractiveTime() { return detector_->GetInteractiveTime(); } + base::TimeTicks GetInteractiveTime() { + return detector_->GetInteractiveTime(); + } ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler> platform_; @@ -140,7 +144,7 @@ private: Persistent<InteractiveDetector> detector_; std::unique_ptr<DummyPageHolder> dummy_page_holder_; - TimeTicks dummy_task_end_time_; + base::TimeTicks dummy_task_end_time_; }; // Note: The tests currently assume kTimeToInteractiveWindowSeconds is 5 @@ -156,375 +160,396 @@ // The name shows the ordering of these events in the test. TEST_F(InteractiveDetectorTest, FMP_DCL_FmpDetect) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(5), - /* detection_time */ t0 + TimeDelta::FromSeconds(7)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(5), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(7)); // Run until 5 seconds after FMP. - RunTillTimestamp((t0 + TimeDelta::FromSeconds(5)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(5)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // Reached TTI at FMP. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5)); } TEST_F(InteractiveDetectorTest, DCL_FMP_FmpDetect) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(5)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(7)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(5)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(7)); // Run until 5 seconds after FMP. - RunTillTimestamp((t0 + TimeDelta::FromSeconds(3)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(3)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // Reached TTI at DCL. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5)); } TEST_F(InteractiveDetectorTest, InstantDetectionAtFmpDetectIfPossible) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(5)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(10)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(5)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(10)); // Although we just detected FMP, the FMP timestamp is more than // kTimeToInteractiveWindowSeconds earlier. We should instantaneously // detect that we reached TTI at DCL. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5)); } TEST_F(InteractiveDetectorTest, FmpDetectFiresAfterLateLongTask) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(9), - t0 + TimeDelta::FromSecondsD(9.1)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(10)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(9), + t0 + base::TimeDelta::FromSecondsD(9.1)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(10)); // There is a 5 second quiet window after fmp_time - the long task is 6s // seconds after fmp_time. We should instantly detect we reached TTI at FMP. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(3)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(3)); } TEST_F(InteractiveDetectorTest, FMP_FmpDetect_DCL) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(5)); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(9)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(5)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(9)); // TTI reached at DCL. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(9)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(9)); } TEST_F(InteractiveDetectorTest, LongTaskBeforeFMPDoesNotAffectTTI) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3)); - SimulateLongTask(t0 + TimeDelta::FromSecondsD(5.1), - t0 + TimeDelta::FromSecondsD(5.2)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(8), - /* detection_time */ t0 + TimeDelta::FromSeconds(9)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3)); + SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(5.1), + t0 + base::TimeDelta::FromSecondsD(5.2)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(8), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(9)); // Run till 5 seconds after FMP. - RunTillTimestamp((t0 + TimeDelta::FromSeconds(8)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(8)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at FMP. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8)); } TEST_F(InteractiveDetectorTest, DCLDoesNotResetTimer) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(5), - t0 + TimeDelta::FromSecondsD(5.1)); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(8)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(5), + t0 + base::TimeDelta::FromSecondsD(5.1)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(8)); // Run till 5 seconds after long task end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(5.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(5.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI Reached at DCL. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8)); } TEST_F(InteractiveDetectorTest, DCL_FMP_FmpDetect_LT) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(4), - /* detection_time */ t0 + TimeDelta::FromSeconds(5)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(4), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(5)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Run till 5 seconds after long task end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at long task end. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1)); } TEST_F(InteractiveDetectorTest, DCL_FMP_LT_FmpDetect) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(5)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(5)); // Run till 5 seconds after long task end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at long task end. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1)); } TEST_F(InteractiveDetectorTest, FMP_FmpDetect_LT_DCL) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(8)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(8)); // Run till 5 seconds after long task end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at DCL. Note that we do not need to wait for DCL + 5 seconds. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8)); } TEST_F(InteractiveDetectorTest, DclIsMoreThan5sAfterFMP) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(10)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(10)); // Have not reached TTI yet. - EXPECT_EQ(GetInteractiveTime(), TimeTicks()); - SimulateLongTask(t0 + TimeDelta::FromSeconds(11), - t0 + TimeDelta::FromSecondsD(11.1)); // Long task 2. + EXPECT_EQ(GetInteractiveTime(), base::TimeTicks()); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(11), + t0 + base::TimeDelta::FromSecondsD(11.1)); // Long task 2. // Run till long task 2 end + 5 seconds. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(11.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(11.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at long task 2 end. - EXPECT_EQ(GetInteractiveTime(), (t0 + TimeDelta::FromSecondsD(11.1))); + EXPECT_EQ(GetInteractiveTime(), (t0 + base::TimeDelta::FromSecondsD(11.1))); } TEST_F(InteractiveDetectorTest, NetworkBusyBlocksTTIEvenWhenMainThreadQuiet) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateResourceLoadBegin(t0 + - TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); SimulateResourceLoadBegin( - t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy. - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. - SimulateResourceLoadEnd(t0 + - TimeDelta::FromSecondsD(12.2)); // Network quiet. + t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD( + 3.5)); // Request 3 start. Network busy. + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateResourceLoadEnd( + t0 + base::TimeDelta::FromSecondsD(12.2)); // Network quiet. // Network busy kept page from reaching TTI.. - EXPECT_EQ(GetInteractiveTime(), TimeTicks()); - SimulateLongTask(t0 + TimeDelta::FromSeconds(13), - t0 + TimeDelta::FromSecondsD(13.1)); // Long task 2. + EXPECT_EQ(GetInteractiveTime(), base::TimeTicks()); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(13), + t0 + base::TimeDelta::FromSecondsD(13.1)); // Long task 2. // Run till 5 seconds after long task 2 end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(13.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); - EXPECT_EQ(GetInteractiveTime(), (t0 + TimeDelta::FromSecondsD(13.1))); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(13.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); + EXPECT_EQ(GetInteractiveTime(), (t0 + base::TimeDelta::FromSecondsD(13.1))); } TEST_F(InteractiveDetectorTest, LongEnoughQuietWindowBetweenFMPAndFmpDetect) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateLongTask(t0 + TimeDelta::FromSecondsD(2.1), - t0 + TimeDelta::FromSecondsD(2.2)); // Long task 1. - SimulateLongTask(t0 + TimeDelta::FromSecondsD(8.2), - t0 + TimeDelta::FromSecondsD(8.3)); // Long task 2. - SimulateResourceLoadBegin(t0 + - TimeDelta::FromSecondsD(8.4)); // Request 2 start. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(2.1), + t0 + base::TimeDelta::FromSecondsD(2.2)); // Long task 1. + SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(8.2), + t0 + base::TimeDelta::FromSecondsD(8.3)); // Long task 2. SimulateResourceLoadBegin( - t0 + TimeDelta::FromSecondsD(8.5)); // Request 3 start. Network busy. - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(10)); + t0 + base::TimeDelta::FromSecondsD(8.4)); // Request 2 start. + SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD( + 8.5)); // Request 3 start. Network busy. + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(10)); // Even though network is currently busy and we have long task finishing // recently, we should be able to detect that the page already achieved TTI at // FMP. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(3)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(3)); } TEST_F(InteractiveDetectorTest, NetworkBusyEndIsNotTTI) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateResourceLoadBegin(t0 + - TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); SimulateResourceLoadBegin( - t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy. - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. - SimulateLongTask(t0 + TimeDelta::FromSeconds(13), - t0 + TimeDelta::FromSecondsD(13.1)); // Long task 2. - SimulateResourceLoadEnd(t0 + TimeDelta::FromSeconds(14)); // Network quiet. + t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD( + 3.5)); // Request 3 start. Network busy. + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(13), + t0 + base::TimeDelta::FromSecondsD(13.1)); // Long task 2. + SimulateResourceLoadEnd(t0 + + base::TimeDelta::FromSeconds(14)); // Network quiet. // Run till 5 seconds after network busy end. - RunTillTimestamp((t0 + TimeDelta::FromSeconds(14)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(14)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at long task 2 end, NOT at network busy end. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(13.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(13.1)); } TEST_F(InteractiveDetectorTest, LateLongTaskWithLateFMPDetection) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateResourceLoadBegin(t0 + - TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); SimulateResourceLoadBegin( - t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy. - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. - SimulateResourceLoadEnd(t0 + TimeDelta::FromSeconds(8)); // Network quiet. - SimulateLongTask(t0 + TimeDelta::FromSeconds(14), - t0 + TimeDelta::FromSecondsD(14.1)); // Long task 2. - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(20)); + t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start. + SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD( + 3.5)); // Request 3 start. Network busy. + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateResourceLoadEnd(t0 + + base::TimeDelta::FromSeconds(8)); // Network quiet. + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(14), + t0 + base::TimeDelta::FromSecondsD(14.1)); // Long task 2. + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(20)); // TTI reached at long task 1 end, NOT at long task 2 end. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1)); } TEST_F(InteractiveDetectorTest, IntermittentNetworkBusyBlocksTTI) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. SimulateResourceLoadBegin( - t0 + TimeDelta::FromSecondsD(7.9)); // Active connections: 2 + t0 + base::TimeDelta::FromSecondsD(7.9)); // Active connections: 2 // Network busy start. SimulateResourceLoadBegin( - t0 + TimeDelta::FromSeconds(8)); // Active connections: 3. + t0 + base::TimeDelta::FromSeconds(8)); // Active connections: 3. // Network busy end. SimulateResourceLoadEnd( - t0 + TimeDelta::FromSecondsD(8.5)); // Active connections: 2. + t0 + base::TimeDelta::FromSecondsD(8.5)); // Active connections: 2. // Network busy start. SimulateResourceLoadBegin( - t0 + TimeDelta::FromSeconds(11)); // Active connections: 3. + t0 + base::TimeDelta::FromSeconds(11)); // Active connections: 3. // Network busy end. SimulateResourceLoadEnd( - t0 + TimeDelta::FromSeconds(12)); // Active connections: 2. - SimulateLongTask(t0 + TimeDelta::FromSeconds(14), - t0 + TimeDelta::FromSecondsD(14.1)); // Long task 2. + t0 + base::TimeDelta::FromSeconds(12)); // Active connections: 2. + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(14), + t0 + base::TimeDelta::FromSecondsD(14.1)); // Long task 2. // Run till 5 seconds after long task 2 end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(14.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(14.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // TTI reached at long task 2 end. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(14.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(14.1)); } TEST_F(InteractiveDetectorTest, InvalidatingUserInput) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); - SimulateInteractiveInvalidatingInput(t0 + TimeDelta::FromSeconds(5)); - SimulateLongTask(t0 + TimeDelta::FromSeconds(7), - t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1. + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); + SimulateInteractiveInvalidatingInput(t0 + base::TimeDelta::FromSeconds(5)); + SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7), + t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1. // Run till 5 seconds after long task 2 end. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // We still detect interactive time on the blink side even if there is an // invalidating user input. Page Load Metrics filters out this value in the // browser process for UMA reporting. - EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1)); + EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1)); EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(), - t0 + TimeDelta::FromSeconds(5)); + t0 + base::TimeDelta::FromSeconds(5)); } TEST_F(InteractiveDetectorTest, InvalidatingUserInputClampedAtNavStart) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3), - /* detection_time */ t0 + TimeDelta::FromSeconds(4)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateFMPDetected( + /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3), + /* detection_time */ t0 + base::TimeDelta::FromSeconds(4)); // Invalidating input timestamp is earlier than navigation start. - SimulateInteractiveInvalidatingInput(t0 - TimeDelta::FromSeconds(10)); + SimulateInteractiveInvalidatingInput(t0 - base::TimeDelta::FromSeconds(10)); // Run till 5 seconds after FMP. - RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); EXPECT_EQ(GetInteractiveTime(), - t0 + TimeDelta::FromSeconds(3)); // TTI at FMP. + t0 + base::TimeDelta::FromSeconds(3)); // TTI at FMP. // Invalidating input timestamp is clamped at navigation start. EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(), t0); } TEST_F(InteractiveDetectorTest, InvalidatedFMP) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); SimulateNavigationStart(t0); // Network is forever quiet for this test. SetActiveConnections(1); - SimulateInteractiveInvalidatingInput(t0 + TimeDelta::FromSeconds(1)); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - RunTillTimestamp(t0 + TimeDelta::FromSeconds(4)); // FMP Detection time. + SimulateInteractiveInvalidatingInput(t0 + base::TimeDelta::FromSeconds(1)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + RunTillTimestamp(t0 + + base::TimeDelta::FromSeconds(4)); // FMP Detection time. GetDetector()->OnFirstMeaningfulPaintDetected( - t0 + TimeDelta::FromSeconds(3), + t0 + base::TimeDelta::FromSeconds(3), FirstMeaningfulPaintDetector::kHadUserInput); // Run till 5 seconds after FMP. - RunTillTimestamp((t0 + TimeDelta::FromSeconds(3)) + - TimeDelta::FromSecondsD(5.0 + 0.1)); + RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(3)) + + base::TimeDelta::FromSecondsD(5.0 + 0.1)); // Since FMP was invalidated, we do not have TTI or TTI Detection Time. - EXPECT_EQ(GetInteractiveTime(), TimeTicks()); + EXPECT_EQ(GetInteractiveTime(), base::TimeTicks()); EXPECT_EQ( GetDetector()->GetInteractiveDetectionTime().since_origin().InSecondsF(), 0.0); // Invalidating input timestamp is available. EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(), - t0 + TimeDelta::FromSeconds(1)); + t0 + base::TimeDelta::FromSeconds(1)); } TEST_F(InteractiveDetectorTest, TaskLongerThan5sBlocksTTI) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); GetDetector()->SetNavigationStartTime(t0); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateFMPDetected(t0 + TimeDelta::FromSeconds(3), - t0 + TimeDelta::FromSeconds(4)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateFMPDetected(t0 + base::TimeDelta::FromSeconds(3), + t0 + base::TimeDelta::FromSeconds(4)); // Post a task with 6 seconds duration. Thread::Current()->GetTaskRunner()->PostTask( @@ -539,12 +564,12 @@ } TEST_F(InteractiveDetectorTest, LongTaskAfterTTIDoesNothing) { - TimeTicks t0 = Now(); + base::TimeTicks t0 = Now(); GetDetector()->SetNavigationStartTime(t0); - SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2)); - SimulateFMPDetected(t0 + TimeDelta::FromSeconds(3), - t0 + TimeDelta::FromSeconds(4)); + SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2)); + SimulateFMPDetected(t0 + base::TimeDelta::FromSeconds(3), + t0 + base::TimeDelta::FromSeconds(4)); // Long task 1. Thread::Current()->GetTaskRunner()->PostTask( @@ -553,7 +578,7 @@ platform_->RunUntilIdle(); - TimeTicks long_task_1_end_time = GetDummyTaskEndTime(); + base::TimeTicks long_task_1_end_time = GetDummyTaskEndTime(); // We should be able to detect TTI 5s after the end of long task. platform_->RunForPeriodSeconds(5.1); EXPECT_EQ(GetDetector()->GetInteractiveTime(), long_task_1_end_time);
diff --git a/third_party/blink/renderer/core/loader/long_task_detector.h b/third_party/blink/renderer/core/loader/long_task_detector.h index f98bc1d43..47c68ff 100644 --- a/third_party/blink/renderer/core/loader/long_task_detector.h +++ b/third_party/blink/renderer/core/loader/long_task_detector.h
@@ -18,7 +18,8 @@ public: virtual ~LongTaskObserver() = default; - virtual void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) = 0; + virtual void OnLongTaskDetected(base::TimeTicks start_time, + base::TimeTicks end_time) = 0; }; // LongTaskDetector detects tasks longer than kLongTaskThreshold and notifies
diff --git a/third_party/blink/renderer/core/loader/long_task_detector_test.cc b/third_party/blink/renderer/core/loader/long_task_detector_test.cc index c40748e8..da8092b2 100644 --- a/third_party/blink/renderer/core/loader/long_task_detector_test.cc +++ b/third_party/blink/renderer/core/loader/long_task_detector_test.cc
@@ -21,11 +21,12 @@ USING_GARBAGE_COLLECTED_MIXIN(TestLongTaskObserver); public: - TimeTicks last_long_task_start; - TimeTicks last_long_task_end; + base::TimeTicks last_long_task_start; + base::TimeTicks last_long_task_end; // LongTaskObserver implementation. - void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) override { + void OnLongTaskDetected(base::TimeTicks start_time, + base::TimeTicks end_time) override { last_long_task_start = start_time; last_long_task_end = end_time; } @@ -48,9 +49,9 @@ // of tasks. platform_->RunForPeriodSeconds(1); } - TimeTicks DummyTaskStartTime() { return dummy_task_start_time_; } + base::TimeTicks DummyTaskStartTime() { return dummy_task_start_time_; } - TimeTicks DummyTaskEndTime() { return dummy_task_end_time_; } + base::TimeTicks DummyTaskEndTime() { return dummy_task_end_time_; } void SimulateTask(base::TimeDelta duration) { Thread::Current()->GetTaskRunner()->PostTask( @@ -63,8 +64,8 @@ platform_; private: - TimeTicks dummy_task_start_time_; - TimeTicks dummy_task_end_time_; + base::TimeTicks dummy_task_start_time_; + base::TimeTicks dummy_task_end_time_; }; TEST_F(LongTaskDetectorTest, DeliversLongTaskNotificationOnlyWhenRegistered) { @@ -72,12 +73,12 @@ MakeGarbageCollected<TestLongTaskObserver>(); SimulateTask(LongTaskDetector::kLongTaskThreshold + base::TimeDelta::FromMilliseconds(10)); - EXPECT_EQ(long_task_observer->last_long_task_end, TimeTicks()); + EXPECT_EQ(long_task_observer->last_long_task_end, base::TimeTicks()); LongTaskDetector::Instance().RegisterObserver(long_task_observer); SimulateTask(LongTaskDetector::kLongTaskThreshold + base::TimeDelta::FromMilliseconds(10)); - TimeTicks long_task_end_when_registered = DummyTaskEndTime(); + base::TimeTicks long_task_end_when_registered = DummyTaskEndTime(); EXPECT_EQ(long_task_observer->last_long_task_start, DummyTaskStartTime()); EXPECT_EQ(long_task_observer->last_long_task_end, long_task_end_when_registered); @@ -97,7 +98,7 @@ LongTaskDetector::Instance().RegisterObserver(long_task_observer); SimulateTask(LongTaskDetector::kLongTaskThreshold - base::TimeDelta::FromMilliseconds(10)); - EXPECT_EQ(long_task_observer->last_long_task_end, TimeTicks()); + EXPECT_EQ(long_task_observer->last_long_task_end, base::TimeTicks()); SimulateTask(LongTaskDetector::kLongTaskThreshold + base::TimeDelta::FromMilliseconds(10)); @@ -113,7 +114,7 @@ SimulateTask(LongTaskDetector::kLongTaskThreshold + base::TimeDelta::FromMilliseconds(10)); - TimeTicks long_task_end_when_registered = DummyTaskEndTime(); + base::TimeTicks long_task_end_when_registered = DummyTaskEndTime(); EXPECT_EQ(long_task_observer->last_long_task_start, DummyTaskStartTime()); EXPECT_EQ(long_task_observer->last_long_task_end, long_task_end_when_registered);
diff --git a/third_party/blink/renderer/core/loader/resource/font_resource.cc b/third_party/blink/renderer/core/loader/resource/font_resource.cc index 2ef8f16..36e5b47 100644 --- a/third_party/blink/renderer/core/loader/resource/font_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/font_resource.cc
@@ -44,8 +44,10 @@ // https://tabatkins.github.io/specs/css-font-display/#font-display-desc // TODO(toyoshim): Revisit short limit value once cache-aware font display is // launched. crbug.com/570205 -constexpr TimeDelta kFontLoadWaitShort = TimeDelta::FromMilliseconds(100); -constexpr TimeDelta kFontLoadWaitLong = TimeDelta::FromMilliseconds(3000); +constexpr base::TimeDelta kFontLoadWaitShort = + base::TimeDelta::FromMilliseconds(100); +constexpr base::TimeDelta kFontLoadWaitLong = + base::TimeDelta::FromMilliseconds(3000); enum FontPackageFormat { kPackageFormatUnknown,
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource.cc b/third_party/blink/renderer/core/loader/resource/image_resource.cc index 7fdb5d8d3..c2e6ae6 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource.cc
@@ -62,7 +62,7 @@ // The amount of time to wait before informing the clients that the image has // been updated (in seconds). This effectively throttles invalidations that // result from new data arriving for this image. -constexpr auto kFlushDelay = TimeDelta::FromSeconds(1); +constexpr auto kFlushDelay = base::TimeDelta::FromSeconds(1); } // namespace @@ -83,7 +83,7 @@ private: const KURL& Url() const override { return resource_->Url(); } - TimeTicks LoadResponseEnd() const override { + base::TimeTicks LoadResponseEnd() const override { return resource_->LoadResponseEnd(); } bool IsSchedulingReload() const override { @@ -351,13 +351,13 @@ if (!is_pending_flushing_) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = Loader()->GetLoadingTaskRunner(); - TimeTicks now = CurrentTimeTicks(); + base::TimeTicks now = CurrentTimeTicks(); if (last_flush_time_.is_null()) last_flush_time_ = now; DCHECK_LE(last_flush_time_, now); - TimeDelta flush_delay = - std::max(TimeDelta(), last_flush_time_ - now + kFlushDelay); + base::TimeDelta flush_delay = + std::max(base::TimeDelta(), last_flush_time_ - now + kFlushDelay); task_runner->PostDelayedTask(FROM_HERE, WTF::Bind(&ImageResource::FlushImageIfNeeded, WrapWeakPersistent(this)), @@ -419,7 +419,7 @@ GetContent()->NotifyStartLoad(); } -void ImageResource::Finish(TimeTicks load_finish_time, +void ImageResource::Finish(base::TimeTicks load_finish_time, base::SingleThreadTaskRunner* task_runner) { if (multipart_parser_) { if (!ErrorOccurred())
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource.h b/third_party/blink/renderer/core/loader/resource/image_resource.h index 7533e6b9..ff6d0fb 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource.h +++ b/third_party/blink/renderer/core/loader/resource/image_resource.h
@@ -89,7 +89,8 @@ void NotifyStartLoad() override; void ResponseReceived(const ResourceResponse&) override; void AppendData(const char*, size_t) override; - void Finish(TimeTicks finish_time, base::SingleThreadTaskRunner*) override; + void Finish(base::TimeTicks finish_time, + base::SingleThreadTaskRunner*) override; void FinishAsError(const ResourceError&, base::SingleThreadTaskRunner*) override; @@ -172,7 +173,7 @@ }; PlaceholderOption placeholder_option_; - TimeTicks last_flush_time_; + base::TimeTicks last_flush_time_; bool is_during_finish_as_error_ = false;
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_content.cc b/third_party/blink/renderer/core/loader/resource/image_resource_content.cc index 1a9981b..cdc6fbc 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_content.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource_content.cc
@@ -41,7 +41,7 @@ private: const KURL& Url() const override { return url_; } - TimeTicks LoadResponseEnd() const override { return TimeTicks(); } + base::TimeTicks LoadResponseEnd() const override { return base::TimeTicks(); } bool IsSchedulingReload() const override { return false; } const ResourceResponse& GetResponse() const override { return response_; } bool ShouldShowPlaceholder() const override { return false; } @@ -655,7 +655,7 @@ return info_->Url(); } -TimeTicks ImageResourceContent::LoadResponseEnd() const { +base::TimeTicks ImageResourceContent::LoadResponseEnd() const { return info_->LoadResponseEnd(); }
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_content.h b/third_party/blink/renderer/core/loader/resource/image_resource_content.h index bc2551c..7c91be4 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_content.h +++ b/third_party/blink/renderer/core/loader/resource/image_resource_content.h
@@ -109,7 +109,7 @@ // Redirecting methods to Resource. const KURL& Url() const; - TimeTicks LoadResponseEnd() const; + base::TimeTicks LoadResponseEnd() const; bool IsAccessAllowed(); const ResourceResponse& GetResponse() const; base::Optional<ResourceError> GetResourceError() const;
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_info.h b/third_party/blink/renderer/core/loader/resource/image_resource_info.h index f08d66a..1a8a9ec 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_info.h +++ b/third_party/blink/renderer/core/loader/resource/image_resource_info.h
@@ -29,7 +29,7 @@ public: ~ImageResourceInfo() = default; virtual const KURL& Url() const = 0; - virtual TimeTicks LoadResponseEnd() const = 0; + virtual base::TimeTicks LoadResponseEnd() const = 0; virtual bool IsSchedulingReload() const = 0; virtual const ResourceResponse& GetResponse() const = 0; virtual bool ShouldShowPlaceholder() const = 0;
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc index f8e0facb4..99fe809 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
@@ -232,7 +232,7 @@ WrappedResourceResponse(resource_response)); image_resource->Loader()->DidReceiveData(data, kDataLength); image_resource->Loader()->DidFinishLoading( - TimeTicks(), kDataLength, kDataLength, kDataLength, false, + base::TimeTicks(), kDataLength, kDataLength, kDataLength, false, std::vector<network::cors::PreflightTimingInfo>()); // Checks |imageResource|'s status after reloading. @@ -289,7 +289,7 @@ reinterpret_cast<const char*>(kJpegImage), kJpegImageSubrangeWithDimensionsLength); image_resource->Loader()->DidFinishLoading( - TimeTicks(), kJpegImageSubrangeWithDimensionsLength, + base::TimeTicks(), kJpegImageSubrangeWithDimensionsLength, kJpegImageSubrangeWithDimensionsLength, kJpegImageSubrangeWithDimensionsLength, false, std::vector<network::cors::PreflightTimingInfo>()); @@ -333,8 +333,9 @@ image_resource->Loader()->DidReceiveData( reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage)); image_resource->Loader()->DidFinishLoading( - TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), sizeof(kJpegImage), - false, std::vector<network::cors::PreflightTimingInfo>()); + base::TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), + sizeof(kJpegImage), false, + std::vector<network::cors::PreflightTimingInfo>()); // Checks that |imageResource| is successfully loaded, // showing a non-placeholder image. @@ -432,7 +433,7 @@ // This part finishes. The image is created, callbacks are sent, and the data // buffer is cleared. image_resource->Loader()->DidFinishLoading( - TimeTicks(), 0, 0, 0, false, + base::TimeTicks(), 0, 0, 0, false, std::vector<network::cors::PreflightTimingInfo>()); EXPECT_TRUE(image_resource->ResourceBuffer()); EXPECT_FALSE(image_resource->ErrorOccurred()); @@ -478,7 +479,7 @@ sizeof(kJpegImage)); image_resource->AppendData(kBoundary, strlen(kBoundary)); image_resource->Loader()->DidFinishLoading( - TimeTicks(), 0, 0, 0, false, + base::TimeTicks(), 0, 0, 0, false, std::vector<network::cors::PreflightTimingInfo>()); EXPECT_TRUE(image_resource->GetContent()->HasImage()); EXPECT_TRUE(image_resource->GetContent()->GetImage()->IsBitmapImage()); @@ -1044,7 +1045,7 @@ EXPECT_EQ(0, observer->ImageChangedCount()); image_resource->Loader()->DidFinishLoading( - TimeTicks(), 0, 0, 0, false, + base::TimeTicks(), 0, 0, 0, false, std::vector<network::cors::PreflightTimingInfo>()); EXPECT_EQ(ResourceStatus::kDecodeError, image_resource->GetStatus()); @@ -1090,7 +1091,7 @@ EXPECT_EQ(0, observer->ImageChangedCount()); image_resource->Loader()->DidFinishLoading( - TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength, + base::TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength, kJpegImageSubrangeWithoutDimensionsLength, kJpegImageSubrangeWithoutDimensionsLength, false, std::vector<network::cors::PreflightTimingInfo>()); @@ -1319,7 +1320,7 @@ EXPECT_EQ(0, observer->ImageChangedCount()); image_resource->Loader()->DidFinishLoading( - TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength, + base::TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength, kJpegImageSubrangeWithoutDimensionsLength, kJpegImageSubrangeWithoutDimensionsLength, false, std::vector<network::cors::PreflightTimingInfo>()); @@ -1462,8 +1463,9 @@ image_resource->Loader()->DidReceiveData( reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage)); image_resource->Loader()->DidFinishLoading( - TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), sizeof(kJpegImage), - false, std::vector<network::cors::PreflightTimingInfo>()); + base::TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), + sizeof(kJpegImage), false, + std::vector<network::cors::PreflightTimingInfo>()); EXPECT_EQ(ResourceStatus::kCached, image_resource->GetStatus()); EXPECT_EQ(sizeof(kJpegImage), image_resource->EncodedSize());
diff --git a/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc b/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc index 33cad926..c684aa74 100644 --- a/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc +++ b/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc
@@ -220,7 +220,7 @@ void ResourceLoadObserverForFrame::DidFinishLoading( uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking,
diff --git a/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h b/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h index 830a636c..aadefc6 100644 --- a/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h +++ b/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h
@@ -48,7 +48,7 @@ int transfer_size_diff) override; void DidDownloadToBlob(uint64_t identifier, BlobDataHandle*) override; void DidFinishLoading(uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking,
diff --git a/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc b/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc index f22358f..b44f94ff 100644 --- a/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc +++ b/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc
@@ -85,7 +85,7 @@ void ResourceLoadObserverForWorker::DidFinishLoading( uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking,
diff --git a/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h b/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h index 42ad3ba..b18ad04 100644 --- a/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h +++ b/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h
@@ -45,7 +45,7 @@ int transfer_size_diff) override; void DidDownloadToBlob(uint64_t identifier, BlobDataHandle*) override; void DidFinishLoading(uint64_t identifier, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking,
diff --git a/third_party/blink/renderer/core/loader/text_track_loader.cc b/third_party/blink/renderer/core/loader/text_track_loader.cc index 95e6fb9..0c16de8 100644 --- a/third_party/blink/renderer/core/loader/text_track_loader.cc +++ b/third_party/blink/renderer/core/loader/text_track_loader.cc
@@ -97,7 +97,7 @@ } if (!cue_load_timer_.IsActive()) - cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); CancelLoad(); } @@ -131,14 +131,14 @@ return; new_cues_available_ = true; - cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); } void TextTrackLoader::FileFailedToParse() { state_ = kFailed; if (!cue_load_timer_.IsActive()) - cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE); + cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); CancelLoad(); }
diff --git a/third_party/blink/renderer/core/loader/threadable_loader.cc b/third_party/blink/renderer/core/loader/threadable_loader.cc index b736daf..3adca3d 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader.cc +++ b/third_party/blink/renderer/core/loader/threadable_loader.cc
@@ -469,13 +469,13 @@ ThreadableLoader::~ThreadableLoader() {} -void ThreadableLoader::SetTimeout(const TimeDelta& timeout) { +void ThreadableLoader::SetTimeout(const base::TimeDelta& timeout) { timeout_ = timeout; - // |request_started_| <= TimeTicks() indicates loading is either not yet + // |request_started_| <= base::TimeTicks() indicates loading is either not yet // started or is already finished, and thus we don't need to do anything with // timeout_timer_. - if (request_started_ <= TimeTicks()) { + if (request_started_ <= base::TimeTicks()) { DCHECK(!timeout_timer_.IsActive()); return; } @@ -490,8 +490,9 @@ // was initially sent, however other uses of this method may need to // behave differently, in which case this should be re-arranged somehow. if (!timeout_.is_zero()) { - TimeDelta elapsed_time = CurrentTimeTicks() - request_started_; - TimeDelta resolved_time = std::max(timeout_ - elapsed_time, TimeDelta()); + base::TimeDelta elapsed_time = CurrentTimeTicks() - request_started_; + base::TimeDelta resolved_time = + std::max(timeout_ - elapsed_time, base::TimeDelta()); timeout_timer_.StartOneShot(resolved_time, FROM_HERE); } } @@ -523,7 +524,7 @@ void ThreadableLoader::Clear() { client_ = nullptr; timeout_timer_.Stop(); - request_started_ = TimeTicks(); + request_started_ = base::TimeTicks(); if (GetResource()) checker_.WillRemoveClient(); ClearResource();
diff --git a/third_party/blink/renderer/core/loader/threadable_loader.h b/third_party/blink/renderer/core/loader/threadable_loader.h index 6c639a60..a682fda 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader.h +++ b/third_party/blink/renderer/core/loader/threadable_loader.h
@@ -121,7 +121,7 @@ // time the request started. // // Passing a timeout of zero means there should be no timeout. - void SetTimeout(const TimeDelta& timeout); + void SetTimeout(const base::TimeDelta& timeout); void Cancel(); @@ -213,7 +213,7 @@ Member<ExecutionContext> execution_context_; Member<ResourceFetcher> resource_fetcher_; - TimeDelta timeout_; + base::TimeDelta timeout_; // Some items may be overridden by m_forceDoNotAllowStoredCredentials and // m_securityOrigin. In such a case, build a ResourceLoaderOptions with // up-to-date values from them and this variable, and use it. @@ -256,7 +256,8 @@ HTTPHeaderMap request_headers_; TaskRunnerTimer<ThreadableLoader> timeout_timer_; - TimeTicks request_started_; // Time an asynchronous fetch request is started + base::TimeTicks + request_started_; // Time an asynchronous fetch request is started // Max number of times that this ThreadableLoader can follow. int redirect_limit_;
diff --git a/third_party/blink/renderer/core/page/autoscroll_controller.cc b/third_party/blink/renderer/core/page/autoscroll_controller.cc index 5296c51..df7cdfe 100644 --- a/third_party/blink/renderer/core/page/autoscroll_controller.cc +++ b/third_party/blink/renderer/core/page/autoscroll_controller.cc
@@ -44,7 +44,7 @@ // Delay time in second for start autoscroll if pointer is in border edge of // scrollable element. -constexpr TimeDelta kAutoscrollDelay = TimeDelta::FromSecondsD(0.2); +constexpr base::TimeDelta kAutoscrollDelay = base::TimeDelta::FromSecondsD(0.2); static const int kNoMiddleClickAutoscrollRadius = 15; @@ -166,7 +166,7 @@ void AutoscrollController::UpdateDragAndDrop(Node* drop_target_node, const FloatPoint& event_position, - TimeTicks event_time) { + base::TimeTicks event_time) { if (!drop_target_node || !drop_target_node->GetLayoutObject()) { StopAutoscroll(); return;
diff --git a/third_party/blink/renderer/core/page/autoscroll_controller.h b/third_party/blink/renderer/core/page/autoscroll_controller.h index 77752f54..9264fd19 100644 --- a/third_party/blink/renderer/core/page/autoscroll_controller.h +++ b/third_party/blink/renderer/core/page/autoscroll_controller.h
@@ -81,7 +81,7 @@ void UpdateAutoscrollLayoutObject(); void UpdateDragAndDrop(Node* target_node, const FloatPoint& event_position, - TimeTicks event_time); + base::TimeTicks event_time); // Middle-click autoscroll. void StartMiddleClickAutoscroll(LocalFrame*, @@ -110,7 +110,7 @@ LayoutBox* autoscroll_layout_object_ = nullptr; LayoutBox* pressed_layout_object_ = nullptr; PhysicalOffset drag_and_drop_autoscroll_reference_position_; - TimeTicks drag_and_drop_autoscroll_start_time_; + base::TimeTicks drag_and_drop_autoscroll_start_time_; // Middle-click autoscroll. FloatPoint middle_click_autoscroll_start_pos_global_;
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc index d6549af..908b16b 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc
@@ -85,8 +85,8 @@ TRACE_EVENT_SCOPE_THREAD, "did_scroll_into_view", did_non_zero_scroll_); - WTF::TimeDelta time_to_scroll_into_view(first_scroll_into_view_time_ - - create_time_); + base::TimeDelta time_to_scroll_into_view(first_scroll_into_view_time_ - + create_time_); UMA_HISTOGRAM_TIMES("TextFragmentAnchor.TimeToScrollIntoView", time_to_scroll_into_view); TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h index baebecf..6ca8ff6 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h
@@ -46,8 +46,8 @@ int match_count_ = 0; bool ambiguous_match_ = false; bool scroll_cancelled_ = false; - WTF::TimeTicks create_time_; - WTF::TimeTicks first_scroll_into_view_time_; + base::TimeTicks create_time_; + base::TimeTicks first_scroll_into_view_time_; bool did_non_zero_scroll_ = false; };
diff --git a/third_party/blink/renderer/core/page/validation_message_client_impl.cc b/third_party/blink/renderer/core/page/validation_message_client_impl.cc index 1566385..fa294261 100644 --- a/third_party/blink/renderer/core/page/validation_message_client_impl.cc +++ b/third_party/blink/renderer/core/page/validation_message_client_impl.cc
@@ -69,8 +69,8 @@ message_ = message; page_->GetChromeClient().RegisterPopupOpeningObserver(this); constexpr auto kMinimumTimeToShowValidationMessage = - TimeDelta::FromSeconds(5); - constexpr auto kTimePerCharacter = TimeDelta::FromMilliseconds(50); + base::TimeDelta::FromSeconds(5); + constexpr auto kTimePerCharacter = base::TimeDelta::FromMilliseconds(50); finish_time_ = CurrentTimeTicks() + std::max(kMinimumTimeToShowValidationMessage, @@ -114,7 +114,8 @@ &ValidationMessageClientImpl::Reset); // This should be equal to or larger than transition duration of // #container.hiding in validation_bubble.css. - const TimeDelta kHidingAnimationDuration = TimeDelta::FromSecondsD(0.13333); + const base::TimeDelta kHidingAnimationDuration = + base::TimeDelta::FromSecondsD(0.13333); timer_->StartOneShot(kHidingAnimationDuration, FROM_HERE); } @@ -131,7 +132,7 @@ timer_ = nullptr; current_anchor_ = nullptr; message_ = String(); - finish_time_ = TimeTicks(); + finish_time_ = base::TimeTicks(); overlay_ = nullptr; overlay_delegate_ = nullptr; page_->GetChromeClient().UnregisterPopupOpeningObserver(this);
diff --git a/third_party/blink/renderer/core/page/validation_message_client_impl.h b/third_party/blink/renderer/core/page/validation_message_client_impl.h index 5ca11d34..ead9a0d 100644 --- a/third_party/blink/renderer/core/page/validation_message_client_impl.h +++ b/third_party/blink/renderer/core/page/validation_message_client_impl.h
@@ -79,7 +79,7 @@ Member<Page> page_; Member<const Element> current_anchor_; String message_; - TimeTicks finish_time_; + base::TimeTicks finish_time_; std::unique_ptr<TimerBase> timer_; std::unique_ptr<FrameOverlay> overlay_; // Raw pointer. This pointer is valid unless overlay_ is nullptr.
diff --git a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc index f4a9a8f..80d6fee 100644 --- a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc +++ b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc
@@ -96,7 +96,7 @@ return; had_user_input_before_provisional_first_meaningful_paint_ = had_user_input_; - provisional_first_meaningful_paint_swap_ = TimeTicks(); + provisional_first_meaningful_paint_swap_ = base::TimeTicks(); RegisterNotifySwapTime(PaintEvent::kProvisionalFirstMeaningfulPaint); } @@ -129,7 +129,7 @@ network2_quiet_reached_ = true; if (!provisional_first_meaningful_paint_.is_null()) { - TimeTicks first_meaningful_paint2_quiet_swap; + base::TimeTicks first_meaningful_paint2_quiet_swap; // Enforce FirstContentfulPaint <= FirstMeaningfulPaint. if (provisional_first_meaningful_paint_ < paint_timing_->FirstContentfulPaintRendered()) { @@ -256,14 +256,14 @@ } void FirstMeaningfulPaintDetector::NotifyFirstContentfulPaint( - TimeTicks swap_stamp) { + base::TimeTicks swap_stamp) { if (defer_first_meaningful_paint_ != kDeferFirstContentfulPaintNotSet) return; SetFirstMeaningfulPaint(swap_stamp); } void FirstMeaningfulPaintDetector::SetFirstMeaningfulPaint( - TimeTicks swap_stamp) { + base::TimeTicks swap_stamp) { DCHECK(paint_timing_->FirstMeaningfulPaint().is_null()); DCHECK(!swap_stamp.is_null()); DCHECK(network2_quiet_reached_);
diff --git a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h index 350ee72d..fbc401d0 100644 --- a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h +++ b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h
@@ -41,7 +41,7 @@ void NotifyInputEvent(); void NotifyPaint(); void ReportSwapTime(PaintEvent, WebWidgetClient::SwapResult, base::TimeTicks); - void NotifyFirstContentfulPaint(TimeTicks swap_stamp); + void NotifyFirstContentfulPaint(base::TimeTicks swap_stamp); void OnNetwork0Quiet(); void OnNetwork2Quiet(); @@ -65,7 +65,7 @@ int ActiveConnections(); void ReportHistograms(); void RegisterNotifySwapTime(PaintEvent); - void SetFirstMeaningfulPaint(TimeTicks swap_stamp); + void SetFirstMeaningfulPaint(base::TimeTicks swap_stamp); bool next_paint_is_meaningful_ = false; HadUserInput had_user_input_ = kNoUserInput; @@ -73,16 +73,16 @@ kNoUserInput; Member<PaintTiming> paint_timing_; - TimeTicks provisional_first_meaningful_paint_; - TimeTicks provisional_first_meaningful_paint_swap_; + base::TimeTicks provisional_first_meaningful_paint_; + base::TimeTicks provisional_first_meaningful_paint_swap_; double max_significance_so_far_ = 0.0; double accumulated_significance_while_having_blank_text_ = 0.0; unsigned prev_layout_object_count_ = 0; bool seen_first_meaningful_paint_candidate_ = false; bool network0_quiet_reached_ = false; bool network2_quiet_reached_ = false; - TimeTicks first_meaningful_paint0_quiet_; - TimeTicks first_meaningful_paint2_quiet_; + base::TimeTicks first_meaningful_paint0_quiet_; + base::TimeTicks first_meaningful_paint2_quiet_; unsigned outstanding_swap_promise_count_ = 0; DeferFirstMeaningfulPaint defer_first_meaningful_paint_ = kDoNotDefer; DISALLOW_COPY_AND_ASSIGN(FirstMeaningfulPaintDetector);
diff --git a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc index 5cea8fab..2151827 100644 --- a/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc +++ b/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc
@@ -18,7 +18,7 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase { protected: void SetUp() override { - platform_->AdvanceClock(TimeDelta::FromSeconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromSeconds(1)); const base::TickClock* test_clock = platform_->test_task_runner()->GetMockTickClock(); FirstMeaningfulPaintDetector::SetTickClockForTesting(test_clock); @@ -35,8 +35,8 @@ base::TimeTicks Now() { return platform_->test_task_runner()->NowTicks(); } - TimeTicks AdvanceClockAndGetTime() { - platform_->AdvanceClock(TimeDelta::FromSeconds(1)); + base::TimeTicks AdvanceClockAndGetTime() { + platform_->AdvanceClock(base::TimeDelta::FromSeconds(1)); return Now(); } @@ -46,7 +46,7 @@ } void SimulateLayoutAndPaint(int new_elements) { - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); StringBuilder builder; for (int i = 0; i < new_elements; i++) builder.Append("<span>a</span>"); @@ -74,20 +74,20 @@ void SimulateUserInput() { Detector().NotifyInputEvent(); } void ClearFirstPaintSwapPromise() { - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); GetPaintTiming().ReportSwapTime( PaintEvent::kFirstPaint, WebWidgetClient::SwapResult::kDidSwap, Now()); } void ClearFirstContentfulPaintSwapPromise() { - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); GetPaintTiming().ReportSwapTime(PaintEvent::kFirstContentfulPaint, WebWidgetClient::SwapResult::kDidSwap, Now()); } void ClearProvisionalFirstMeaningfulPaintSwapPromise() { - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); ClearProvisionalFirstMeaningfulPaintSwapPromise(Now()); } @@ -120,7 +120,7 @@ SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U); SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); } TEST_F(FirstMeaningfulPaintDetectorTest, OneLayout) { @@ -128,8 +128,8 @@ SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_paint = AdvanceClockAndGetTime(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + base::TimeTicks after_paint = AdvanceClockAndGetTime(); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); SimulateNetworkStable(); EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_paint); } @@ -139,11 +139,11 @@ SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_layout1 = AdvanceClockAndGetTime(); + base::TimeTicks after_layout1 = AdvanceClockAndGetTime(); SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_layout2 = AdvanceClockAndGetTime(); + base::TimeTicks after_layout2 = AdvanceClockAndGetTime(); SimulateNetworkStable(); EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_layout1); EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_layout2); @@ -154,7 +154,7 @@ SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_layout1 = AdvanceClockAndGetTime(); + base::TimeTicks after_layout1 = AdvanceClockAndGetTime(); SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U); SimulateNetworkStable(); @@ -165,19 +165,21 @@ TEST_F(FirstMeaningfulPaintDetectorTest, FirstMeaningfulPaintCandidate) { MarkFirstContentfulPaintAndClearSwapPromise(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), + base::TimeTicks()); SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_paint = AdvanceClockAndGetTime(); + base::TimeTicks after_paint = AdvanceClockAndGetTime(); // The first candidate gets ignored. - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), + base::TimeTicks()); SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); // The second candidate gets reported. EXPECT_GT(GetPaintTiming().FirstMeaningfulPaintCandidate(), after_paint); - TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate(); + base::TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate(); // The third candidate gets ignored since we already saw the first candidate. SimulateLayoutAndPaint(20); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); @@ -188,17 +190,19 @@ TEST_F(FirstMeaningfulPaintDetectorTest, OnlyOneFirstMeaningfulPaintCandidateBeforeNetworkStable) { MarkFirstContentfulPaintAndClearSwapPromise(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks()); - TimeTicks before_paint = AdvanceClockAndGetTime(); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), + base::TimeTicks()); + base::TimeTicks before_paint = AdvanceClockAndGetTime(); SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); // The first candidate is initially ignored. - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), + base::TimeTicks()); SimulateNetworkStable(); // The networkStable then promotes the first candidate. EXPECT_GT(GetPaintTiming().FirstMeaningfulPaintCandidate(), before_paint); - TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate(); + base::TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate(); // The second candidate is then ignored. SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U); @@ -212,10 +216,10 @@ EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); MarkFirstContentfulPaintAndClearSwapPromise(); SimulateNetworkStable(); - EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); } TEST_F(FirstMeaningfulPaintDetectorTest, @@ -224,7 +228,7 @@ SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); MarkFirstContentfulPaintAndClearSwapPromise(); SimulateNetworkStable(); EXPECT_GE(GetPaintTiming().FirstMeaningfulPaint(), @@ -236,9 +240,9 @@ SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); - TimeTicks after_first_paint = AdvanceClockAndGetTime(); + base::TimeTicks after_first_paint = AdvanceClockAndGetTime(); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_first_paint_swap = AdvanceClockAndGetTime(); + base::TimeTicks after_first_paint_swap = AdvanceClockAndGetTime(); SimulateNetwork2Quiet(); SimulateLayoutAndPaint(10); @@ -246,7 +250,7 @@ SimulateNetwork0Quiet(); // The first paint is FirstMeaningfulPaint. - EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_first_paint); EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_first_paint_swap); } @@ -257,13 +261,13 @@ SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_first_paint = AdvanceClockAndGetTime(); + base::TimeTicks after_first_paint = AdvanceClockAndGetTime(); SimulateNetwork0Quiet(); SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - TimeTicks after_second_paint = AdvanceClockAndGetTime(); + base::TimeTicks after_second_paint = AdvanceClockAndGetTime(); SimulateNetwork2Quiet(); // The second paint is FirstMeaningfulPaint. @@ -279,7 +283,7 @@ EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); } TEST_F(FirstMeaningfulPaintDetectorTest, UserInteractionBeforeFirstPaint) { @@ -289,7 +293,7 @@ EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); SimulateNetworkStable(); - EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); } TEST_F(FirstMeaningfulPaintDetectorTest, @@ -298,9 +302,9 @@ SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); } TEST_F(FirstMeaningfulPaintDetectorTest, @@ -308,21 +312,21 @@ MarkFirstContentfulPaintAndClearSwapPromise(); SimulateLayoutAndPaint(1); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 2U); // Having outstanding swap promises should defer setting FMP. SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); // Clearing the first swap promise should have no effect on FMP. ClearProvisionalFirstMeaningfulPaintSwapPromise(); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); - TimeTicks after_first_swap = AdvanceClockAndGetTime(); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); + base::TimeTicks after_first_swap = AdvanceClockAndGetTime(); // Clearing the last outstanding swap promise should set FMP. ClearProvisionalFirstMeaningfulPaintSwapPromise(); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U); - EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_first_swap); } @@ -332,14 +336,14 @@ SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); ClearProvisionalFirstMeaningfulPaintSwapPromise(); - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); GetPaintTiming().MarkFirstContentfulPaint(); // FCP > FMP candidate, but still waiting for FCP swap. SimulateNetworkStable(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); // Trigger notifying the detector about the FCP swap. ClearFirstContentfulPaintSwapPromise(); - EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), GetPaintTiming().FirstContentfulPaint()); } @@ -352,14 +356,14 @@ // Simulate only network 2-quiet so provisional FMP will be set on next // layout. - TimeTicks pre_stable_timestamp = AdvanceClockAndGetTime(); - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + base::TimeTicks pre_stable_timestamp = AdvanceClockAndGetTime(); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); SimulateNetwork2Quiet(); - EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); // Force another FMP candidate while there is a pending swap promise and the // network 2-quiet FMP non-swap timestamp is set. - platform_->AdvanceClock(TimeDelta::FromMilliseconds(1)); + platform_->AdvanceClock(base::TimeDelta::FromMilliseconds(1)); SimulateLayoutAndPaint(10); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U); @@ -368,7 +372,7 @@ // non-swap timestamp is used. ClearProvisionalFirstMeaningfulPaintSwapPromise(pre_stable_timestamp); EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U); - EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks()); + EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks()); EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), pre_stable_timestamp); }
diff --git a/third_party/blink/renderer/core/paint/image_element_timing.cc b/third_party/blink/renderer/core/paint/image_element_timing.cc index 1d6942f..6082998 100644 --- a/third_party/blink/renderer/core/paint/image_element_timing.cc +++ b/third_party/blink/renderer/core/paint/image_element_timing.cc
@@ -142,8 +142,8 @@ performance->ShouldBufferEntries())) { // Create an entry with a |startTime| of 0. performance->AddElementTiming( - ImagePaintString(), url.GetString(), intersection_rect, TimeTicks(), - cached_image.LoadResponseEnd(), attr, + ImagePaintString(), url.GetString(), intersection_rect, + base::TimeTicks(), cached_image.LoadResponseEnd(), attr, cached_image.IntrinsicSize(kDoNotRespectImageOrientation), id, element); }
diff --git a/third_party/blink/renderer/core/paint/image_element_timing.h b/third_party/blink/renderer/core/paint/image_element_timing.h index 33014d7..1482e47 100644 --- a/third_party/blink/renderer/core/paint/image_element_timing.h +++ b/third_party/blink/renderer/core/paint/image_element_timing.h
@@ -81,7 +81,7 @@ public: ElementTimingInfo(const String& url, const FloatRect& rect, - const TimeTicks& response_end, + const base::TimeTicks& response_end, const AtomicString& identifier, const IntSize& intrinsic_size, const AtomicString& id, @@ -99,7 +99,7 @@ String url; FloatRect rect; - TimeTicks response_end; + base::TimeTicks response_end; AtomicString identifier; IntSize intrinsic_size; AtomicString id;
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc index 651ce56..b957e3bc 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc
@@ -128,11 +128,11 @@ ->UpdateCandidate(); } - TimeTicks LargestPaintStoredResult() { + base::TimeTicks LargestPaintStoredResult() { return GetPaintTimingDetector().largest_image_paint_time_; } - static constexpr TimeDelta kQuantumOfTime = + static constexpr base::TimeDelta kQuantumOfTime = base::TimeDelta::FromMilliseconds(10); void SimulatePassOfTime() { @@ -209,7 +209,7 @@ std::string base_url_; }; -constexpr TimeDelta ImagePaintTimingDetectorTest::kQuantumOfTime; +constexpr base::TimeDelta ImagePaintTimingDetectorTest::kQuantumOfTime; TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_NoImage) { SetBodyInnerHTML(R"HTML( @@ -474,32 +474,34 @@ image->setAttribute("id", "target"); GetDocument().getElementById("parent")->AppendChild(image); SetImageAndPaint("target", 5, 5); - test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1)); UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); ImageRecord* record; record = FindLargestPaintCandidate(); EXPECT_TRUE(record); // UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() moves time forward // kQuantumOfTime so we should take that into account. - EXPECT_EQ(record->paint_time, - base::TimeTicks() + TimeDelta::FromSecondsD(1) + kQuantumOfTime); + EXPECT_EQ( + record->paint_time, + base::TimeTicks() + base::TimeDelta::FromSecondsD(1) + kQuantumOfTime); GetDocument().getElementById("parent")->RemoveChild(image); - test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1)); UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); record = FindLargestPaintCandidate(); EXPECT_FALSE(record); GetDocument().getElementById("parent")->AppendChild(image); SetImageAndPaint("target", 5, 5); - test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1)); UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); record = FindLargestPaintCandidate(); EXPECT_TRUE(record); // UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() moves time forward // kQuantumOfTime so we should take that into account. - EXPECT_EQ(record->paint_time, - base::TimeTicks() + TimeDelta::FromSecondsD(1) + kQuantumOfTime); + EXPECT_EQ( + record->paint_time, + base::TimeTicks() + base::TimeDelta::FromSecondsD(1) + kQuantumOfTime); } // This is to prove that a swap time is assigned only to nodes of the frame who @@ -535,7 +537,7 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_UpdateResultWhenLargestChanged) { - TimeTicks time1 = test_task_runner_->NowTicks(); + base::TimeTicks time1 = test_task_runner_->NowTicks(); SetBodyInnerHTML(R"HTML( <div id="parent"> <img id="target1"></img> @@ -544,15 +546,15 @@ )HTML"); SetImageAndPaint("target1", 5, 5); UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); - TimeTicks time2 = test_task_runner_->NowTicks(); - TimeTicks result1 = LargestPaintStoredResult(); + base::TimeTicks time2 = test_task_runner_->NowTicks(); + base::TimeTicks result1 = LargestPaintStoredResult(); EXPECT_GE(result1, time1); EXPECT_GE(time2, result1); SetImageAndPaint("target2", 10, 10); UpdateAllLifecyclePhasesAndInvokeCallbackIfAny(); - TimeTicks time3 = test_task_runner_->NowTicks(); - TimeTicks result2 = LargestPaintStoredResult(); + base::TimeTicks time3 = test_task_runner_->NowTicks(); + base::TimeTicks result2 = LargestPaintStoredResult(); EXPECT_GE(result2, time2); EXPECT_GE(time3, result2); }
diff --git a/third_party/blink/renderer/core/paint/link_highlight_impl.cc b/third_party/blink/renderer/core/paint/link_highlight_impl.cc index 9f0eecf..ff5e365d 100644 --- a/third_party/blink/renderer/core/paint/link_highlight_impl.cc +++ b/third_party/blink/renderer/core/paint/link_highlight_impl.cc
@@ -346,8 +346,8 @@ is_animating_ = true; // FIXME: Should duration be configurable? - constexpr auto kFadeDuration = TimeDelta::FromMilliseconds(100); - constexpr auto kMinPreFadeDuration = TimeDelta::FromMilliseconds(100); + constexpr auto kFadeDuration = base::TimeDelta::FromMilliseconds(100); + constexpr auto kMinPreFadeDuration = base::TimeDelta::FromMilliseconds(100); auto curve = std::make_unique<CompositorFloatAnimationCurve>(); @@ -358,8 +358,9 @@ CompositorFloatKeyframe(0, kStartOpacity, timing_function)); // Make sure we have displayed for at least minPreFadeDuration before starting // to fade out. - TimeDelta extra_duration_required = std::max( - TimeDelta(), kMinPreFadeDuration - (CurrentTimeTicks() - start_time_)); + base::TimeDelta extra_duration_required = + std::max(base::TimeDelta(), + kMinPreFadeDuration - (CurrentTimeTicks() - start_time_)); if (!extra_duration_required.is_zero()) { curve->AddKeyframe(CompositorFloatKeyframe( extra_duration_required.InSecondsF(), kStartOpacity, timing_function));
diff --git a/third_party/blink/renderer/core/paint/link_highlight_impl.h b/third_party/blink/renderer/core/paint/link_highlight_impl.h index 3085cb6..8ff77311 100644 --- a/third_party/blink/renderer/core/paint/link_highlight_impl.h +++ b/third_party/blink/renderer/core/paint/link_highlight_impl.h
@@ -150,7 +150,7 @@ bool geometry_needs_update_; bool is_animating_; - TimeTicks start_time_; + base::TimeTicks start_time_; CompositorElementId element_id_; };
diff --git a/third_party/blink/renderer/core/paint/paint_timing.cc b/third_party/blink/renderer/core/paint/paint_timing.cc index 9f5a5c1..5487c5f 100644 --- a/third_party/blink/renderer/core/paint/paint_timing.cc +++ b/third_party/blink/renderer/core/paint/paint_timing.cc
@@ -81,7 +81,7 @@ RegisterNotifySwapTime(PaintEvent::kFirstImagePaint); } -void PaintTiming::SetFirstMeaningfulPaintCandidate(TimeTicks timestamp) { +void PaintTiming::SetFirstMeaningfulPaintCandidate(base::TimeTicks timestamp) { if (!first_meaningful_paint_candidate_.is_null()) return; first_meaningful_paint_candidate_ = timestamp; @@ -91,7 +91,7 @@ } void PaintTiming::SetFirstMeaningfulPaint( - TimeTicks swap_stamp, + base::TimeTicks swap_stamp, FirstMeaningfulPaintDetector::HadUserInput had_input) { DCHECK(first_meaningful_paint_swap_.is_null()); DCHECK(!swap_stamp.is_null()); @@ -162,14 +162,14 @@ GetSupplementable()->Loader()->DidChangePerformanceTiming(); } -void PaintTiming::SetFirstPaint(TimeTicks stamp) { +void PaintTiming::SetFirstPaint(base::TimeTicks stamp) { if (!first_paint_.is_null()) return; first_paint_ = stamp; RegisterNotifySwapTime(PaintEvent::kFirstPaint); } -void PaintTiming::SetFirstContentfulPaint(TimeTicks stamp) { +void PaintTiming::SetFirstContentfulPaint(base::TimeTicks stamp) { if (!first_contentful_paint_.is_null()) return; SetFirstPaint(stamp); @@ -232,7 +232,7 @@ } } -void PaintTiming::SetFirstPaintSwap(TimeTicks stamp) { +void PaintTiming::SetFirstPaintSwap(base::TimeTicks stamp) { DCHECK(first_paint_swap_.is_null()); first_paint_swap_ = stamp; probe::PaintTiming(GetSupplementable(), "firstPaint", @@ -243,7 +243,7 @@ NotifyPaintTimingChanged(); } -void PaintTiming::SetFirstContentfulPaintSwap(TimeTicks stamp) { +void PaintTiming::SetFirstContentfulPaintSwap(base::TimeTicks stamp) { DCHECK(first_contentful_paint_swap_.is_null()); TRACE_EVENT_INSTANT_WITH_TIMESTAMP0("loading", "FirstContentfulPaint", TRACE_EVENT_SCOPE_GLOBAL, stamp); @@ -259,7 +259,7 @@ fmp_detector_->NotifyFirstContentfulPaint(first_contentful_paint_swap_); } -void PaintTiming::SetFirstImagePaintSwap(TimeTicks stamp) { +void PaintTiming::SetFirstImagePaintSwap(base::TimeTicks stamp) { DCHECK(first_image_paint_swap_.is_null()); first_image_paint_swap_ = stamp; probe::PaintTiming(GetSupplementable(), "firstImagePaint",
diff --git a/third_party/blink/renderer/core/paint/paint_timing.h b/third_party/blink/renderer/core/paint/paint_timing.h index 7dd65a90..ad414a3 100644 --- a/third_party/blink/renderer/core/paint/paint_timing.h +++ b/third_party/blink/renderer/core/paint/paint_timing.h
@@ -58,9 +58,9 @@ // contentful paint hasn't been recorded yet. void MarkFirstImagePaint(); - void SetFirstMeaningfulPaintCandidate(TimeTicks timestamp); + void SetFirstMeaningfulPaintCandidate(base::TimeTicks timestamp); void SetFirstMeaningfulPaint( - TimeTicks swap_stamp, + base::TimeTicks swap_stamp, FirstMeaningfulPaintDetector::HadUserInput had_input); void NotifyPaint(bool is_first_paint, bool text_painted, bool image_painted); @@ -70,21 +70,21 @@ // FirstPaint returns the first time that anything was painted for the // current document. - TimeTicks FirstPaint() const { return first_paint_swap_; } + base::TimeTicks FirstPaint() const { return first_paint_swap_; } // FirstContentfulPaint returns the first time that 'contentful' content was // painted. For instance, the first time that text or image content was // painted. - TimeTicks FirstContentfulPaint() const { + base::TimeTicks FirstContentfulPaint() const { return first_contentful_paint_swap_; } // FirstImagePaint returns the first time that image content was painted. - TimeTicks FirstImagePaint() const { return first_image_paint_swap_; } + base::TimeTicks FirstImagePaint() const { return first_image_paint_swap_; } // FirstMeaningfulPaint returns the first time that page's primary content // was painted. - TimeTicks FirstMeaningfulPaint() const { + base::TimeTicks FirstMeaningfulPaint() const { return first_meaningful_paint_swap_; } @@ -92,7 +92,7 @@ // paint to qualify as the potentially first meaningful paint. Unlike // firstMeaningfulPaint, this signal is available in real time, but it may be // an optimistic (i.e., too early) estimate. - TimeTicks FirstMeaningfulPaintCandidate() const { + base::TimeTicks FirstMeaningfulPaintCandidate() const { return first_meaningful_paint_candidate_; } @@ -122,42 +122,42 @@ // or Set*() methods to make sure that first paint is marked as part of // marking first contentful paint, or that first contentful paint is marked as // part of marking first text/image paint, for example. - void SetFirstPaint(TimeTicks stamp); + void SetFirstPaint(base::TimeTicks stamp); // setFirstContentfulPaint will also set first paint time if first paint // time has not yet been recorded. - void SetFirstContentfulPaint(TimeTicks stamp); + void SetFirstContentfulPaint(base::TimeTicks stamp); // Set*Swap() are called when the SwapPromise is fulfilled and the swap // timestamp is available. These methods will record trace events, update Web // Perf API (FP and FCP only), and notify that paint timing has changed, which // triggers UMAs and UKMS. // |stamp| is the swap timestamp used for tracing, UMA, UKM, and Web Perf API. - void SetFirstPaintSwap(TimeTicks stamp); - void SetFirstContentfulPaintSwap(TimeTicks stamp); - void SetFirstImagePaintSwap(TimeTicks stamp); + void SetFirstPaintSwap(base::TimeTicks stamp); + void SetFirstContentfulPaintSwap(base::TimeTicks stamp); + void SetFirstImagePaintSwap(base::TimeTicks stamp); void RegisterNotifySwapTime(PaintEvent); void ReportUserInputHistogram( FirstMeaningfulPaintDetector::HadUserInput had_input); - TimeTicks FirstPaintRendered() const { return first_paint_; } + base::TimeTicks FirstPaintRendered() const { return first_paint_; } - TimeTicks FirstContentfulPaintRendered() const { + base::TimeTicks FirstContentfulPaintRendered() const { return first_contentful_paint_; } // TODO(crbug/738235): Non first_*_swap_ variables are only being tracked to // compute deltas for reporting histograms and should be removed once we // confirm the deltas and discrepancies look reasonable. - TimeTicks first_paint_; - TimeTicks first_paint_swap_; - TimeTicks first_image_paint_; - TimeTicks first_image_paint_swap_; - TimeTicks first_contentful_paint_; - TimeTicks first_contentful_paint_swap_; - TimeTicks first_meaningful_paint_swap_; - TimeTicks first_meaningful_paint_candidate_; + base::TimeTicks first_paint_; + base::TimeTicks first_paint_swap_; + base::TimeTicks first_image_paint_; + base::TimeTicks first_image_paint_swap_; + base::TimeTicks first_contentful_paint_; + base::TimeTicks first_contentful_paint_swap_; + base::TimeTicks first_meaningful_paint_swap_; + base::TimeTicks first_meaningful_paint_candidate_; Member<FirstMeaningfulPaintDetector> fmp_detector_;
diff --git a/third_party/blink/renderer/core/paint/text_element_timing.cc b/third_party/blink/renderer/core/paint/text_element_timing.cc index a556064..294a42e 100644 --- a/third_party/blink/renderer/core/paint/text_element_timing.cc +++ b/third_party/blink/renderer/core/paint/text_element_timing.cc
@@ -81,7 +81,7 @@ DEFINE_STATIC_LOCAL(const AtomicString, kTextPaint, ("text-paint")); performance_->AddElementTiming( kTextPaint, g_empty_string, record->element_timing_rect_, - record->paint_time, TimeTicks(), attr, IntSize(), id, element); + record->paint_time, base::TimeTicks(), attr, IntSize(), id, element); } }
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc index 8b7bd52..0c59367 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
@@ -27,7 +27,7 @@ namespace { // Calculate metrics candidate every 1 second after the first text pre-paint. -constexpr TimeDelta kTimerDelay = TimeDelta::FromSeconds(1); +constexpr base::TimeDelta kTimerDelay = base::TimeDelta::FromSeconds(1); constexpr size_t kTextNodeNumberLimit = 5000; bool LargeTextFirst(const base::WeakPtr<TextRecord>& a,
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc index c502f39..14c45e9 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
@@ -64,7 +64,7 @@ test_task_runner_->NowTicks()); } - TimeTicks LargestPaintStoredResult() { + base::TimeTicks LargestPaintStoredResult() { return GetPaintTimingDetector().largest_text_paint_time_; } @@ -230,22 +230,22 @@ } TEST_F(TextPaintTimingDetectorTest, UpdateResultWhenCandidateChanged) { - TimeTicks time1 = NowTicks(); + base::TimeTicks time1 = NowTicks(); SetBodyInnerHTML(R"HTML( <div>small text</div> )HTML"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); UpdateCandidate(); - TimeTicks time2 = NowTicks(); - TimeTicks first_largest = LargestPaintStoredResult(); + base::TimeTicks time2 = NowTicks(); + base::TimeTicks first_largest = LargestPaintStoredResult(); EXPECT_GE(first_largest, time1); EXPECT_GE(time2, first_largest); AppendDivElementToBody("a long-long-long text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); UpdateCandidate(); - TimeTicks time3 = NowTicks(); - TimeTicks second_largest = LargestPaintStoredResult(); + base::TimeTicks time3 = NowTicks(); + base::TimeTicks second_largest = LargestPaintStoredResult(); EXPECT_GE(second_largest, time2); EXPECT_GE(time3, second_largest); } @@ -282,19 +282,19 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportFirstPaintTime) { base::TimeTicks start_time = NowTicks(); - AdvanceClock(TimeDelta::FromSecondsD(1)); + AdvanceClock(base::TimeDelta::FromSecondsD(1)); SetBodyInnerHTML(R"HTML( )HTML"); Element* text = AppendDivElementToBody("text"); UpdateAllLifecyclePhasesAndSimulateSwapTime(); - AdvanceClock(TimeDelta::FromSecondsD(1)); + AdvanceClock(base::TimeDelta::FromSecondsD(1)); text->setAttribute(html_names::kStyleAttr, AtomicString("position:fixed;left:30px")); UpdateAllLifecyclePhasesAndSimulateSwapTime(); - AdvanceClock(TimeDelta::FromSecondsD(1)); + AdvanceClock(base::TimeDelta::FromSecondsD(1)); TextRecord* record = TextRecordOfLargestTextPaint(); EXPECT_TRUE(record); - EXPECT_EQ(record->paint_time, start_time + TimeDelta::FromSecondsD(1)); + EXPECT_EQ(record->paint_time, start_time + base::TimeDelta::FromSecondsD(1)); } TEST_F(TextPaintTimingDetectorTest,
diff --git a/third_party/blink/renderer/core/probe/core_probes.cc b/third_party/blink/renderer/core/probe/core_probes.cc index f0277aa..25cf12f 100644 --- a/third_party/blink/renderer/core/probe/core_probes.cc +++ b/third_party/blink/renderer/core/probe/core_probes.cc
@@ -47,19 +47,19 @@ } } // namespace -TimeTicks ProbeBase::CaptureStartTime() const { +base::TimeTicks ProbeBase::CaptureStartTime() const { if (start_time_.is_null()) start_time_ = CurrentTimeTicks(); return start_time_; } -TimeTicks ProbeBase::CaptureEndTime() const { +base::TimeTicks ProbeBase::CaptureEndTime() const { if (end_time_.is_null()) end_time_ = CurrentTimeTicks(); return end_time_; } -TimeDelta ProbeBase::Duration() const { +base::TimeDelta ProbeBase::Duration() const { DCHECK(!start_time_.is_null()); return CaptureEndTime() - start_time_; }
diff --git a/third_party/blink/renderer/core/probe/core_probes.h b/third_party/blink/renderer/core/probe/core_probes.h index fd04373..841b31d4 100644 --- a/third_party/blink/renderer/core/probe/core_probes.h +++ b/third_party/blink/renderer/core/probe/core_probes.h
@@ -56,13 +56,13 @@ STACK_ALLOCATED(); public: - TimeTicks CaptureStartTime() const; - TimeTicks CaptureEndTime() const; - TimeDelta Duration() const; + base::TimeTicks CaptureStartTime() const; + base::TimeTicks CaptureEndTime() const; + base::TimeDelta Duration() const; private: - mutable TimeTicks start_time_; - mutable TimeTicks end_time_; + mutable base::TimeTicks start_time_; + mutable base::TimeTicks end_time_; }; class CORE_EXPORT AsyncTask {
diff --git a/third_party/blink/renderer/core/probe/core_probes.pidl b/third_party/blink/renderer/core/probe/core_probes.pidl index f170f74..da978b1 100644 --- a/third_party/blink/renderer/core/probe/core_probes.pidl +++ b/third_party/blink/renderer/core/probe/core_probes.pidl
@@ -97,7 +97,7 @@ void DidReceiveData(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const char* data, uint64_t data_length); void DidReceiveBlob(CoreProbeSink*, uint64_t identifier, DocumentLoader*, BlobDataHandle*); void DidReceiveEncodedDataLength(CoreProbeSink*, DocumentLoader* loader, uint64_t identifier, size_t encoded_data_length); - void DidFinishLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); + void DidFinishLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); void DidReceiveCorsRedirectResponse(ExecutionContext*, uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); void DidFailLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const ResourceError&); void WillSendEventSourceRequest(ExecutionContext*);
diff --git a/third_party/blink/renderer/core/scheduler/throttling_test.cc b/third_party/blink/renderer/core/scheduler/throttling_test.cc index 2420d3ba..f3e336e9 100644 --- a/third_party/blink/renderer/core/scheduler/throttling_test.cc +++ b/third_party/blink/renderer/core/scheduler/throttling_test.cc
@@ -48,7 +48,7 @@ // Run delayed tasks for 1 second. All tasks should be completed // with throttling disabled. - test::RunDelayedTasks(TimeDelta::FromSeconds(1)); + test::RunDelayedTasks(base::TimeDelta::FromSeconds(1)); EXPECT_THAT(ConsoleMessages(), ElementsAre("called f", "called f", "called f", "called f", "called f")); @@ -74,7 +74,7 @@ GetDocument().GetPage()->GetPageScheduler()->SetPageVisible(false); // Make sure that we run no more than one task a second. - test::RunDelayedTasks(TimeDelta::FromMilliseconds(3000)); + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(3000)); EXPECT_THAT( ConsoleMessages(), AnyOf(ElementsAre("called f", "called f", "called f"),
diff --git a/third_party/blink/renderer/core/scheduler/virtual_time_test.cc b/third_party/blink/renderer/core/scheduler/virtual_time_test.cc index 2174623..5773236 100644 --- a/third_party/blink/renderer/core/scheduler/virtual_time_test.cc +++ b/third_party/blink/renderer/core/scheduler/virtual_time_test.cc
@@ -70,7 +70,7 @@ FROM_HERE, WTF::Bind(&VirtualTimeTest::StopVirtualTimeAndExitRunLoop, WTF::Unretained(this)), - TimeDelta::FromMillisecondsD(delay_ms)); + base::TimeDelta::FromMillisecondsD(delay_ms)); test::EnterRunLoop(); } };
diff --git a/third_party/blink/renderer/core/script/layered_api_module.h b/third_party/blink/renderer/core/script/layered_api_module.h index 6223f63..cef1eb7 100644 --- a/third_party/blink/renderer/core/script/layered_api_module.h +++ b/third_party/blink/renderer/core/script/layered_api_module.h
@@ -17,6 +17,7 @@ kBlank, kElementsSwitch, kKvStorage, + kToast, kVirtualScroller, };
diff --git a/third_party/blink/renderer/core/script/layered_api_resources.h b/third_party/blink/renderer/core/script/layered_api_resources.h index 1396b74..3f2c821 100644 --- a/third_party/blink/renderer/core/script/layered_api_resources.h +++ b/third_party/blink/renderer/core/script/layered_api_resources.h
@@ -39,6 +39,8 @@ {"kv-storage/index.mjs", IDR_LAYERED_API_KV_STORAGE_INDEX_MJS, Module::kKvStorage}, + {"toast/index.mjs", IDR_LAYERED_API_TOAST_INDEX_MJS, Module::kToast}, + {"virtual-scroller/index.mjs", IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS, Module::kVirtualScroller}, {"virtual-scroller/item-source.mjs",
diff --git a/third_party/blink/renderer/core/script/modulator_impl_base.cc b/third_party/blink/renderer/core/script/modulator_impl_base.cc index 2143f15..899b8e7d 100644 --- a/third_party/blink/renderer/core/script/modulator_impl_base.cc +++ b/third_party/blink/renderer/core/script/modulator_impl_base.cc
@@ -66,6 +66,8 @@ GetExecutionContext()); case layered_api::Module::kElementsSwitch: return RuntimeEnabledFeatures::BuiltInModuleSwitchElementEnabled(); + case layered_api::Module::kToast: + return RuntimeEnabledFeatures::BuiltInModuleAllEnabled(); } } @@ -80,6 +82,9 @@ UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleSwitchImported); break; + case layered_api::Module::kToast: + UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleToast); + break; case layered_api::Module::kVirtualScroller: UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleVirtualScroller);
diff --git a/third_party/blink/renderer/core/script/pending_script.cc b/third_party/blink/renderer/core/script/pending_script.cc index 2c86293..fde788a 100644 --- a/third_party/blink/renderer/core/script/pending_script.cc +++ b/third_party/blink/renderer/core/script/pending_script.cc
@@ -72,7 +72,7 @@ DCHECK(!IsWatchingForLoad()); starting_position_ = TextPosition::BelowRangePosition(); - parser_blocking_load_start_time_ = TimeTicks(); + parser_blocking_load_start_time_ = base::TimeTicks(); DisposeInternal(); element_ = nullptr; @@ -172,7 +172,7 @@ const bool was_canceled = WasCanceled(); const bool is_external = IsExternal(); const bool created_during_document_write = WasCreatedDuringDocumentWrite(); - const TimeTicks parser_blocking_load_start_time = + const base::TimeTicks parser_blocking_load_start_time = ParserBlockingLoadStartTime(); const bool is_controlled_by_script_runner = IsControlledByScriptRunner(); ScriptElementBase* element = element_; @@ -192,7 +192,7 @@ bool was_canceled, bool is_external, bool created_during_document_write, - TimeTicks parser_blocking_load_start_time, + base::TimeTicks parser_blocking_load_start_time, bool is_controlled_by_script_runner) { Document& element_document = element->GetDocument(); Document* context_document = element_document.ContextDocument(); @@ -204,7 +204,7 @@ return; } - if (parser_blocking_load_start_time > TimeTicks()) { + if (parser_blocking_load_start_time > base::TimeTicks()) { DocumentParserTiming::From(element_document) .RecordParserBlockedOnScriptLoadDuration( CurrentTimeTicks() - parser_blocking_load_start_time, @@ -214,7 +214,7 @@ if (was_canceled) return; - TimeTicks script_exec_start_time = CurrentTimeTicks(); + base::TimeTicks script_exec_start_time = CurrentTimeTicks(); { if (element->ElementHasDuplicateAttributes()) {
diff --git a/third_party/blink/renderer/core/script/pending_script.h b/third_party/blink/renderer/core/script/pending_script.h index 8892e413..08b44d08 100644 --- a/third_party/blink/renderer/core/script/pending_script.h +++ b/third_party/blink/renderer/core/script/pending_script.h
@@ -73,7 +73,7 @@ // Returns the time the load of this script started blocking the parser, or // zero if this script hasn't yet blocked the parser, in // monotonicallyIncreasingTime. - TimeTicks ParserBlockingLoadStartTime() const { + base::TimeTicks ParserBlockingLoadStartTime() const { return parser_blocking_load_start_time_; } @@ -153,7 +153,7 @@ bool was_canceled, bool is_external, bool created_during_document_write, - TimeTicks parser_blocking_load_start_time, + base::TimeTicks parser_blocking_load_start_time, bool is_controlled_by_script_runner); // |m_element| must points to the corresponding ScriptLoader's @@ -162,7 +162,7 @@ Member<ScriptElementBase> element_; TextPosition starting_position_; // Only used for inline script tags. - TimeTicks parser_blocking_load_start_time_; + base::TimeTicks parser_blocking_load_start_time_; ScriptSchedulingType scheduling_type_ = ScriptSchedulingType::kNotSet;
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py b/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py index 3c26ba1..cee21a2 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py +++ b/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py
@@ -9,12 +9,13 @@ def _CommonChecks(input_api, output_api): results = [] # We don't apply eslint to virtual-scroller/, which is not developed here. - # TODO(tkent): kv-storage/.eslintrc.js specifies babel-eslint parser, which + # TODO(tkent): kv-storage/.eslintrc.js and toast/.eslintrc.js specify babel-eslint parser, which # is not in third_party/node/node_modules/. mjs_files = input_api.AffectedFiles( file_filter=lambda f: (f.LocalPath().endswith('.mjs') and - not 'virtual-scroller' in f.LocalPath() and - not 'kv-storage' in f.LocalPath()), + not '/virtual-scroller/' in f.LocalPath() and + not '/kv-storage/' in f.LocalPath() and + not '/toast/' in f.LocalPath()), include_deletes=False) if not mjs_files: return results
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp b/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp index 17360d14..7b97d28 100644 --- a/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp +++ b/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp
@@ -11,6 +11,7 @@ <include name="IDR_LAYERED_API_KV_STORAGE_ASYNC_ITERATOR_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_KV_STORAGE_IDB_UTILS_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/idb_utils.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_KV_STORAGE_INDEX_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> + <include name="IDR_LAYERED_API_TOAST_INDEX_MJS" file="../renderer/core/script/resources/layered_api/toast/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_ITEM_SOURCE_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs" type="BINDATA" skip_minify="true" compress="gzip"/> <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_REPEATER_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/toast/.eslintrc.js b/third_party/blink/renderer/core/script/resources/layered_api/toast/.eslintrc.js new file mode 100644 index 0000000..8f9a676 --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/toast/.eslintrc.js
@@ -0,0 +1,338 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module.exports = { + root: true, + env: { + es6: true, + browser: true + }, + 'parser': 'babel-eslint', + parserOptions: { + sourceType: 'module', + ecmaVersion: 2019 + }, + rules: { + 'for-direction': 'error', + 'getter-return': 'error', + 'no-async-promise-executor': 'error', + 'no-await-in-loop': 'error', + 'no-compare-neg-zero': 'error', + 'no-cond-assign': ['error', 'except-parens'], + 'no-console': 'error', + 'no-constant-condition': ['error', {checkLoops: false}], + 'no-control-regex': 'error', + 'no-debugger': 'error', + 'no-dupe-args': 'error', + 'no-dupe-keys': 'error', + 'no-duplicate-case': 'error', + 'no-empty': 'error', + 'no-empty-character-class': 'error', + 'no-ex-assign': 'error', + 'no-extra-boolean-cast': 'error', + 'no-extra-parens': [ + 'error', + 'all', + { + conditionalAssign: false, + nestedBinaryExpressions: false, + returnAssign: false + } + ], + 'no-extra-semi': 'error', + 'no-func-assign': 'error', + 'no-inner-declarations': 'off', + 'no-invalid-regexp': 'error', + 'no-irregular-whitespace': 'error', + 'no-misleading-character-class': 'error', + 'no-obj-calls': 'error', + 'no-prototype-builtins': 'error', + 'no-regex-spaces': 'error', + 'no-sparse-arrays': 'error', + 'no-template-curly-in-string': 'error', + 'no-unexpected-multiline': 'error', + 'no-unreachable': 'error', + 'no-unsafe-finally': 'off', + 'no-unsafe-negation': 'error', + 'use-isnan': 'error', + 'valid-typeof': 'error', + 'accessor-pairs': 'error', + 'array-callback-return': 'error', + 'block-scoped-var': 'off', + 'class-methods-use-this': 'off', + 'complexity': 'off', + 'consistent-return': 'error', + 'curly': ['error', 'all'], + 'default-case': 'off', + 'dot-location': ['error', 'property'], + 'dot-notation': 'error', + 'eqeqeq': 'error', + 'guard-for-in': 'off', + 'no-alert': 'error', + 'no-caller': 'error', + 'no-case-declarations': 'error', + 'no-div-regex': 'off', + 'no-else-return': 'error', + 'no-empty-function': 'off', + 'no-empty-pattern': 'error', + 'no-eq-null': 'error', + 'no-eval': 'error', + 'no-extend-native': 'error', + 'no-extra-bind': 'error', + 'no-extra-label': 'error', + 'no-fallthrough': 'error', + 'no-floating-decimal': 'error', + 'no-global-assign': 'error', + 'no-implicit-coercion': 'error', + 'no-implicit-globals': 'error', + 'no-implied-eval': 'error', + 'no-invalid-this': 'error', + 'no-iterator': 'error', + 'no-labels': ['error', {allowLoop: true}], + 'no-lone-blocks': 'error', + 'no-loop-func': 'error', + 'no-magic-numbers': ['error', {ignore: [0, 1]}], + 'no-multi-spaces': ['error', {ignoreEOLComments: true}], + 'no-multi-str': 'error', + 'no-new': 'error', + 'no-new-func': 'error', + 'no-new-wrappers': 'error', + 'no-octal': 'error', + 'no-octal-escape': 'error', + 'no-param-reassign': 'off', + 'no-process-env': 'error', + 'no-proto': 'error', + 'no-redeclare': 'error', + 'no-restricted-properties': 'off', + 'no-return-assign': ['error', 'except-parens'], + 'no-return-await': 'error', + 'no-script-url': 'off', + 'no-self-assign': 'error', + 'no-self-compare': 'error', + 'no-sequences': 'error', + 'no-throw-literal': 'error', + 'no-unmodified-loop-condition': 'error', + 'no-unused-expressions': 'error', + 'no-unused-labels': 'error', + 'no-useless-call': 'error', + 'no-useless-concat': 'error', + 'no-useless-escape': 'error', + 'no-useless-return': 'error', + 'no-void': 'error', + 'no-warning-comments': 'off', + 'no-with': 'error', + 'prefer-promise-reject-errors': 'error', + 'radix': ['error', 'as-needed'], + 'require-await': 'off', + 'vars-on-top': 'off', + 'wrap-iife': ['error', 'outside'], + 'yoda': ['error', 'never'], + 'strict': ['error', 'global'], + 'init-declarations': 'off', + 'no-delete-var': 'error', + 'no-label-var': 'error', + 'no-restricted-globals': 'off', + 'no-shadow': 'error', + 'no-shadow-restricted-names': 'error', + 'no-undef': 'error', + 'no-undef-init': 'error', + 'no-undefined': 'off', + 'no-unused-vars': 'error', + 'no-use-before-define': ['error', 'nofunc'], + 'callback-return': 'off', + 'global-require': 'error', + 'handle-callback-err': 'error', + 'no-buffer-constructor': 'error', + 'no-mixed-requires': ['error', true], + 'no-new-require': 'error', + 'no-path-concat': 'error', + 'no-process-exit': 'error', + 'no-restricted-modules': 'off', + 'no-sync': 'off', + 'array-bracket-newline': ['error', {multiline: true}], + 'array-bracket-spacing': ['error', 'never'], + 'array-element-newline': 'off', + 'block-spacing': ['error', 'always'], + 'brace-style': [ + 'error', + '1tbs', + {allowSingleLine: false} + ], + camelcase: ['error', {properties: 'always'}], + 'capitalized-comments': 'off', + 'comma-dangle': ['error', 'always-multiline'], + 'comma-spacing': [ + 'error', + { + before: false, + after: true + } + ], + 'comma-style': ['error', 'last'], + 'computed-property-spacing': ['error', 'never'], + 'consistent-this': 'off', + 'eol-last': 'error', + 'func-call-spacing': ['error', 'never'], + 'func-name-matching': 'error', + 'func-names': 'off', + 'func-style': ['error', 'declaration'], + 'function-paren-newline': 'off', + 'id-blacklist': 'off', + 'id-length': 'off', + 'id-match': 'off', + indent: 'off', // not really compatible with clang-format + 'jsx-quotes': 'off', + 'key-spacing': [ + 'error', + { + beforeColon: false, + afterColon: true, + mode: 'strict' + } + ], + 'keyword-spacing': [ + 'error', + { + before: true, + after: true + } + ], + 'line-comment-position': 'off', + 'linebreak-style': ['error', 'unix'], + 'lines-around-comment': 'off', + 'max-depth': 'off', + 'max-len': 'off', + 'max-lines': 'off', + 'max-nested-callbacks': 'off', + 'max-params': 'off', + 'max-statements': 'off', + 'max-statements-per-line': ['error', {max: 1}], + 'multiline-ternary': ['error', 'always-multiline'], + 'new-cap': 'error', + 'new-parens': 'error', + 'newline-per-chained-call': 'off', + 'no-array-constructor': 'error', + 'no-bitwise': 'off', + 'no-continue': 'off', + 'no-inline-comments': 'off', + 'no-lonely-if': 'error', + 'no-mixed-operators': [ + 'error', + { + groups: [ + ['&', '|', '^', '~', '<<', '>>', '>>>'], + ['==', '!=', '===', '!==', '>', '>=', '<', '<='], + ['&&', '||'], + ['in', 'instanceof'] + ] + } + ], + 'no-mixed-spaces-and-tabs': 'error', + 'no-multi-assign': 'off', + 'no-multiple-empty-lines': 'error', + 'no-negated-condition': 'off', + 'no-nested-ternary': 'error', + 'no-new-object': 'error', + 'no-plusplus': 'off', + 'no-restricted-syntax': 'off', + 'no-tabs': 'error', + 'no-ternary': 'off', + 'no-trailing-spaces': 'error', + 'no-underscore-dangle': 'off', + 'no-unneeded-ternary': 'error', + 'no-whitespace-before-property': 'error', + 'nonblock-statement-body-position': 'error', + 'object-curly-newline': ['error', {consistent: true}], + 'object-curly-spacing': ['error', 'never'], + 'object-property-newline': 'off', + 'one-var': ['error', 'never'], + 'one-var-declaration-per-line': ['error', 'initializations'], + 'operator-assignment': ['error', 'always'], + 'operator-linebreak': ['error', 'after'], + 'padded-blocks': ['error', 'never'], + 'padding-line-between-statements': 'off', + 'quote-props': ['error', 'as-needed'], + quotes: [ + 'error', + 'single', + { + avoidEscape: true, + allowTemplateLiterals: true + } + ], + semi: ['error', 'always'], + 'semi-spacing': 'error', + 'semi-style': 'error', + 'sort-keys': 'off', + 'sort-vars': 'off', + 'space-before-blocks': ['error', 'always'], + 'space-before-function-paren': [ + 'error', + { + anonymous: 'always', + named: 'never' + } + ], + 'space-in-parens': ['error', 'never'], + 'space-infix-ops': 'error', + 'space-unary-ops': [ + 'error', + { + words: true, + nonwords: false + } + ], + 'spaced-comment': ['error', 'always'], + 'switch-colon-spacing': 'error', + 'template-tag-spacing': 'error', + 'unicode-bom': 'error', + 'wrap-regex': 'off', + 'arrow-body-style': 'off', + 'arrow-parens': ['error', 'as-needed'], + 'arrow-spacing': 'error', + 'constructor-super': 'error', + 'generator-star-spacing': ['error', 'neither'], + 'no-class-assign': 'error', + 'no-confusing-arrow': 'off', + 'no-const-assign': 'error', + 'no-dupe-class-members': 'error', + 'no-duplicate-imports': 'error', + 'no-new-symbol': 'error', + 'no-restricted-imports': 'off', + 'no-this-before-super': 'error', + 'no-useless-computed-key': 'error', + 'no-useless-constructor': 'error', + 'no-useless-rename': 'error', + 'no-var': 'error', + 'object-shorthand': 'error', + 'prefer-arrow-callback': 'error', + 'prefer-const': ['error', {ignoreReadBeforeAssign: true}], + 'prefer-destructuring': [ + 'error', + { + VariableDeclarator: { + array: false, + object: true + }, + AssignmentExpression: { + array: false, + object: false + } + }, + { + enforceForRenamedProperties: false + } + ], + 'prefer-numeric-literals': 'error', + 'prefer-rest-params': 'error', + 'prefer-spread': 'error', + 'prefer-template': 'off', + 'require-yield': 'error', + 'rest-spread-spacing': 'error', + 'sort-imports': 'off', + 'symbol-description': 'error', + 'template-curly-spacing': ['error', 'never'], + 'yield-star-spacing': ['error', 'after'] + } +};
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/toast/OWNERS b/third_party/blink/renderer/core/script/resources/layered_api/toast/OWNERS new file mode 100644 index 0000000..d76cdfa --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/toast/OWNERS
@@ -0,0 +1 @@ +fergal@chromium.org
diff --git a/third_party/blink/renderer/core/script/resources/layered_api/toast/index.mjs b/third_party/blink/renderer/core/script/resources/layered_api/toast/index.mjs new file mode 100644 index 0000000..d79d4e4 --- /dev/null +++ b/third_party/blink/renderer/core/script/resources/layered_api/toast/index.mjs
@@ -0,0 +1,114 @@ +/** + * Copyright 2019 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. + * + * @fileoverview This file defines the class for the Standard Toast LAPI + * and the accompanying showToast() function. + * EXPLAINER: https://github.com/jackbsteinberg/std-toast + * TEST PATH: /chromium/src/third_party/blink/web_tests/external/wpt/std-toast/* + * @package + */ + +const DEFAULT_DURATION = 2000; + +function stylesheetFactory() { + let stylesheet; + return function generate() { + if (!stylesheet) { + stylesheet = new CSSStyleSheet(); + stylesheet.replaceSync(` + :host { + position: fixed; + bottom: 0; + right: 0; + z-index: 1; + background-color: #FFFFFF; + color: #000000; + font-size: 20px; + border-color: #000000; + border-style: solid; + border-width: 2px; + border-radius: 2.5px; + padding: 10px; + margin: 10px; + } + + :host(:not([open])) { + display: none; + } + `); + } + return stylesheet; + }; +} + +const generateStylesheet = stylesheetFactory(); + +export class StdToastElement extends HTMLElement { + static observedAttributes = ['open']; + #shadow = this.attachShadow({mode: 'closed'}); + #timeoutID; + + constructor(message = '') { + super(); + + this.#shadow.adoptedStyleSheets = [generateStylesheet()]; + + this.#shadow.innerHTML = `<slot></slot>`; + if (!this.textContent) { + this.textContent = `${message}`; + } + } + + show({duration = DEFAULT_DURATION} = {}) { + this.setAttribute('open', ''); + clearTimeout(this.#timeoutID); + this.#timeoutID = setTimeout(() => { + this.removeAttribute('open'); + }, duration); + } + + hide() { + this.removeAttribute('open'); + } + + toggle(force) { + this.toggleAttribute('open', force); + } + + get open() { + return this.hasAttribute('open'); + } + + set open(val) { + this.toggleAttribute('open', Boolean(val)); + } + + attributeChangedCallback(name, oldValue, newValue) { + switch (name) { + case 'open': + if (newValue !== null && oldValue === null) { + this.dispatchEvent(new Event('show')); + } else if (newValue === null) { + this.dispatchEvent(new Event('hide')); + clearTimeout(this.#timeoutID); + this.#timeoutID = null; + } + break; + } + } +} +customElements.define('std-toast', StdToastElement); + +delete StdToastElement.prototype.attributeChangedCallback; +delete StdToastElement.prototype.observedAttributes; +delete StdToastElement.prototype.connectedCallback; + +export function showToast(message, options) { + const toast = new StdToastElement(message); + document.body.append(toast); + toast.show(options); + + return toast; +}
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator.cc b/third_party/blink/renderer/core/scroll/scroll_animator.cc index 60f4fd9..45c0dae 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator.cc +++ b/third_party/blink/renderer/core/scroll/scroll_animator.cc
@@ -187,7 +187,7 @@ // of sending to the compositor. if (run_state_ == RunState::kRunningOnMainThread) { animation_curve_->UpdateTarget( - TimeDelta::FromSecondsD(time_function_() - start_time_), + base::TimeDelta::FromSecondsD(time_function_() - start_time_), CompositorOffsetFromBlinkOffset(target_offset)); // Schedule an animation for this scrollable area even though we are @@ -359,7 +359,7 @@ // ::adjustScrollOffsetAnimation should have made the necessary // adjustment to the curve. animation_curve_->UpdateTarget( - TimeDelta::FromSecondsD(time_function_() - start_time_), + base::TimeDelta::FromSecondsD(time_function_() - start_time_), CompositorOffsetFromBlinkOffset(target_offset_)); }
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm b/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm index efa24b2..c0d33d0 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm +++ b/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm
@@ -315,7 +315,7 @@ start_time_ = WTF::CurrentTime(); // Set the framerate of the animation. NSAnimation uses a default // framerate of 60 Hz, so use that here. - timer_.StartRepeating(TimeDelta::FromSecondsD(1.0 / 60.0), FROM_HERE); + timer_.StartRepeating(base::TimeDelta::FromSecondsD(1.0 / 60.0), FROM_HERE); } void Stop() { timer_.Stop(); } @@ -1058,7 +1058,7 @@ *task_runner_, FROM_HERE, WTF::Bind(&ScrollAnimatorMac::InitialScrollbarPaintTask, WrapWeakPersistent(this)), - TimeDelta::FromMilliseconds(1)); + base::TimeDelta::FromMilliseconds(1)); } bool ScrollAnimatorMac::ScrollbarPaintTimerIsActive() const {
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area.cc b/third_party/blink/renderer/core/scroll/scrollable_area.cc index c44e3e79..fef4876a 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area.cc +++ b/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -676,7 +676,7 @@ SetScrollbarsHiddenIfOverlay(false); needs_show_scrollbar_layers_ = true; - const TimeDelta time_until_disable = + const base::TimeDelta time_until_disable = GetPageScrollbarTheme().OverlayScrollbarFadeOutDelay() + GetPageScrollbarTheme().OverlayScrollbarFadeOutDuration();
diff --git a/third_party/blink/renderer/core/scroll/scrollable_area_test.cc b/third_party/blink/renderer/core/scroll/scrollable_area_test.cc index 60a16bdf..40ce515 100644 --- a/third_party/blink/renderer/core/scroll/scrollable_area_test.cc +++ b/third_party/blink/renderer/core/scroll/scrollable_area_test.cc
@@ -285,7 +285,7 @@ ScrollbarThemeOverlayMock& theme = (ScrollbarThemeOverlayMock&)scrollable_area->GetPageScrollbarTheme(); - theme.SetOverlayScrollbarFadeOutDelay(TimeDelta::FromSeconds(1)); + theme.SetOverlayScrollbarFadeOutDelay(base::TimeDelta::FromSeconds(1)); Scrollbar* scrollbar = Scrollbar::CreateForTesting( scrollable_area, kHorizontalScrollbar, kRegularScrollbar, &theme);
diff --git a/third_party/blink/renderer/core/scroll/scrollbar.cc b/third_party/blink/renderer/core/scroll/scrollbar.cc index 6ef80ec6..5ed8c6d 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar.cc +++ b/third_party/blink/renderer/core/scroll/scrollbar.cc
@@ -182,7 +182,7 @@ return PressedPos() >= thumb_pos && PressedPos() < thumb_pos + thumb_length; } -void Scrollbar::AutoscrollPressedPart(TimeDelta delay) { +void Scrollbar::AutoscrollPressedPart(base::TimeDelta delay) { if (!scrollable_area_) return; @@ -219,7 +219,7 @@ } } -void Scrollbar::StartTimerIfNeeded(TimeDelta delay) { +void Scrollbar::StartTimerIfNeeded(base::TimeDelta delay) { // Don't do anything for the thumb. if (pressed_part_ == kThumbPart) return;
diff --git a/third_party/blink/renderer/core/scroll/scrollbar.h b/third_party/blink/renderer/core/scroll/scrollbar.h index cc71633..e265f7e 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar.h +++ b/third_party/blink/renderer/core/scroll/scrollbar.h
@@ -196,9 +196,9 @@ protected: void AutoscrollTimerFired(TimerBase*); - void StartTimerIfNeeded(TimeDelta delay); + void StartTimerIfNeeded(base::TimeDelta delay); void StopTimerIfNeeded(); - void AutoscrollPressedPart(TimeDelta delay); + void AutoscrollPressedPart(base::TimeDelta delay); bool HandleTapGesture(); bool IsScrollGestureInjectionEnabled() const; void InjectScrollGestureForPressedPart(WebInputEvent::Type gesture_type);
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme.cc b/third_party/blink/renderer/core/scroll/scrollbar_theme.cc index 008b4bfd..798a062 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme.cc +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
@@ -252,14 +252,14 @@ #endif } -TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDelay() const { +base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDelay() const { // On Mac, fading is controlled by the painting code in ScrollAnimatorMac. - return TimeDelta(); + return base::TimeDelta(); } -TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDuration() const { +base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDuration() const { // On Mac, fading is controlled by the painting code in ScrollAnimatorMac. - return TimeDelta(); + return base::TimeDelta(); } int ScrollbarTheme::ThumbPosition(const Scrollbar& scrollbar, @@ -362,12 +362,12 @@ } } -TimeDelta ScrollbarTheme::InitialAutoscrollTimerDelay() { - return TimeDelta::FromMilliseconds(250); +base::TimeDelta ScrollbarTheme::InitialAutoscrollTimerDelay() { + return base::TimeDelta::FromMilliseconds(250); } -TimeDelta ScrollbarTheme::AutoscrollTimerDelay() { - return TimeDelta::FromMilliseconds(50); +base::TimeDelta ScrollbarTheme::AutoscrollTimerDelay() { + return base::TimeDelta::FromMilliseconds(50); } ScrollbarTheme& ScrollbarTheme::DeprecatedStaticGetTheme() {
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme.h b/third_party/blink/renderer/core/scroll/scrollbar_theme.h index f78733d8..9aaa655 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme.h +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme.h
@@ -117,8 +117,8 @@ int ThumbPosition(const Scrollbar& scrollbar) { return ThumbPosition(scrollbar, scrollbar.CurrentPos()); } - virtual TimeDelta OverlayScrollbarFadeOutDelay() const; - virtual TimeDelta OverlayScrollbarFadeOutDuration() const; + virtual base::TimeDelta OverlayScrollbarFadeOutDelay() const; + virtual base::TimeDelta OverlayScrollbarFadeOutDuration() const; // The position the thumb would have, relative to the track, at the specified // scroll position. virtual int ThumbPosition(const Scrollbar&, float scroll_position); @@ -181,8 +181,8 @@ return std::numeric_limits<int>::max(); } - virtual TimeDelta InitialAutoscrollTimerDelay(); - virtual TimeDelta AutoscrollTimerDelay(); + virtual base::TimeDelta InitialAutoscrollTimerDelay(); + virtual base::TimeDelta AutoscrollTimerDelay(); virtual IntRect ConstrainTrackRectToTrackPieces(const Scrollbar&, const IntRect& rect) {
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h index 16ff4a8c..7ddc6472 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h
@@ -53,8 +53,8 @@ // Mac queues up scrollbar paint timers. bool ShouldDisableInvisibleScrollbars() const override { return false; } - TimeDelta InitialAutoscrollTimerDelay() override; - TimeDelta AutoscrollTimerDelay() override; + base::TimeDelta InitialAutoscrollTimerDelay() override; + base::TimeDelta AutoscrollTimerDelay() override; void PaintTickmarks(GraphicsContext&, const Scrollbar&,
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm index be8b87df..d74831d 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm
@@ -168,12 +168,12 @@ ScrollbarThemeMac::~ScrollbarThemeMac() { } -TimeDelta ScrollbarThemeMac::InitialAutoscrollTimerDelay() { - return TimeDelta::FromSecondsD(s_initial_button_delay); +base::TimeDelta ScrollbarThemeMac::InitialAutoscrollTimerDelay() { + return base::TimeDelta::FromSecondsD(s_initial_button_delay); } -TimeDelta ScrollbarThemeMac::AutoscrollTimerDelay() { - return TimeDelta::FromSecondsD(s_autoscroll_button_delay); +base::TimeDelta ScrollbarThemeMac::AutoscrollTimerDelay() { + return base::TimeDelta::FromSecondsD(s_autoscroll_button_delay); } bool ScrollbarThemeMac::ShouldDragDocumentInsteadOfThumb(
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc index 7258f03..2fdf0676 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc
@@ -82,22 +82,22 @@ return true; } -TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDelay() const { +base::TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDelay() const { // TODO(bokan): Unit tests run without a theme engine. This is normally fine // because they expect to use ScrollbarThemeMock which doesn't use a theme // engine. If overlays are turned on though, this class is used even if mock // scrollbars are on. We should either provide mock out a web theme engine for // unit tests or provide a mock version of this class. if (!Platform::Current()->ThemeEngine()) - return TimeDelta(); + return base::TimeDelta(); WebThemeEngine::ScrollbarStyle style; Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style); return style.fade_out_delay; } -TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDuration() const { +base::TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDuration() const { if (!Platform::Current()->ThemeEngine()) - return TimeDelta(); + return base::TimeDelta(); WebThemeEngine::ScrollbarStyle style; Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style); return style.fade_out_duration;
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h index 2fecb975..7ab2f4a 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h
@@ -56,8 +56,8 @@ int ScrollbarThickness(ScrollbarControlSize) override; int ScrollbarMargin() const override; bool UsesOverlayScrollbars() const override; - TimeDelta OverlayScrollbarFadeOutDelay() const override; - TimeDelta OverlayScrollbarFadeOutDuration() const override; + base::TimeDelta OverlayScrollbarFadeOutDelay() const override; + base::TimeDelta OverlayScrollbarFadeOutDuration() const override; int ThumbLength(const Scrollbar&) override;
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h index 342bae02..ef3b6f2e 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h
@@ -40,12 +40,16 @@ ScrollbarThemeOverlayMock() : ScrollbarThemeOverlay(3, 4, kDisallowHitTest, Color(128, 128, 128)) {} - TimeDelta OverlayScrollbarFadeOutDelay() const override { return delay_; } - TimeDelta OverlayScrollbarFadeOutDuration() const override { - return TimeDelta(); + base::TimeDelta OverlayScrollbarFadeOutDelay() const override { + return delay_; + } + base::TimeDelta OverlayScrollbarFadeOutDuration() const override { + return base::TimeDelta(); } - void SetOverlayScrollbarFadeOutDelay(TimeDelta delay) { delay_ = delay; } + void SetOverlayScrollbarFadeOutDelay(base::TimeDelta delay) { + delay_ = delay; + } void PaintThumb(GraphicsContext& gc, const Scrollbar& scrollbar, @@ -63,7 +67,7 @@ int MinimumThumbLength(const Scrollbar&) override { return 7; } private: - TimeDelta delay_; + base::TimeDelta delay_; bool IsMockTheme() const final { return true; } };
diff --git a/third_party/blink/renderer/core/svg/animation/smil_time_container.cc b/third_party/blink/renderer/core/svg/animation/smil_time_container.cc index 3139f43..b11557be 100644 --- a/third_party/blink/renderer/core/svg/animation/smil_time_container.cc +++ b/third_party/blink/renderer/core/svg/animation/smil_time_container.cc
@@ -39,8 +39,8 @@ namespace blink { -static constexpr TimeDelta kAnimationPolicyOnceDuration = - TimeDelta::FromSeconds(3); +static constexpr base::TimeDelta kAnimationPolicyOnceDuration = + base::TimeDelta::FromSeconds(3); SMILTimeContainer::SMILTimeContainer(SVGSVGElement& owner) : presentation_time_(0), @@ -273,7 +273,8 @@ FrameSchedulingState frame_scheduling_state) { DCHECK(frame_scheduling_state == kSynchronizeAnimations || frame_scheduling_state == kFutureAnimationFrame); - wakeup_timer_.StartOneShot(TimeDelta::FromSecondsD(delay_time), FROM_HERE); + wakeup_timer_.StartOneShot(base::TimeDelta::FromSecondsD(delay_time), + FROM_HERE); frame_scheduling_state_ = frame_scheduling_state; }
diff --git a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc index 6112e8b1..559f63fa 100644 --- a/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc +++ b/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc
@@ -1267,6 +1267,10 @@ is_scheduled_ = true; } +const AttrNameToTrustedType& SVGSMILElement::GetCheckedAttributeTypes() const { + return SVGURIReference::GetCheckedAttributeTypes(); +} + void SVGSMILElement::Trace(blink::Visitor* visitor) { visitor->Trace(target_element_); visitor->Trace(target_id_observer_);
diff --git a/third_party/blink/renderer/core/svg/animation/svg_smil_element.h b/third_party/blink/renderer/core/svg/animation/svg_smil_element.h index 5ff56d7..99e646e 100644 --- a/third_party/blink/renderer/core/svg/animation/svg_smil_element.h +++ b/third_party/blink/renderer/core/svg/animation/svg_smil_element.h
@@ -125,6 +125,8 @@ virtual bool IsSVGDiscardElement() const { return false; } + const AttrNameToTrustedType& GetCheckedAttributeTypes() const override; + void Trace(blink::Visitor*) override; protected:
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc b/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc index 05898236..92cb5a7 100644 --- a/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc +++ b/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc
@@ -38,8 +38,8 @@ namespace blink { -static constexpr TimeDelta kAnimationFrameDelay = - TimeDelta::FromSecondsD(1.0 / 60); +static constexpr base::TimeDelta kAnimationFrameDelay = + base::TimeDelta::FromSecondsD(1.0 / 60); SVGImageChromeClient::SVGImageChromeClient(SVGImage* image) : image_(image), @@ -104,7 +104,7 @@ // animations, but prefer a fixed, jittery, frame-delay if there're any // animations. Checking for pending/active animations could be more // stringent. - TimeDelta fire_time; + base::TimeDelta fire_time; if (image_->MaybeAnimated()) { if (IsSuspended()) return;
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc b/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc index 2f868074..90f51f29 100644 --- a/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc +++ b/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc
@@ -114,7 +114,7 @@ // Fire the timer/trigger a frame update. Since the observer always returns // true for shouldPauseAnimation, this will result in the timeline being // suspended. - test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) + + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) + timer->NextFireInterval()); EXPECT_TRUE(chrome_client.IsSuspended()); EXPECT_FALSE(timer->IsActive()); @@ -148,7 +148,7 @@ // Fire the timer/trigger a frame update. The timeline will remain // suspended and no frame will be scheduled. - test::RunDelayedTasks(TimeDelta::FromMillisecondsD(1) + + test::RunDelayedTasks(base::TimeDelta::FromMillisecondsD(1) + timer->NextFireInterval()); EXPECT_TRUE(chrome_client.IsSuspended()); EXPECT_FALSE(timer->IsActive()); @@ -226,7 +226,7 @@ // Wait for the next animation frame to be triggered, and then trigger a new // frame. The image animation timeline should be running. - test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) + + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) + timer->NextFireInterval()); Compositor().BeginFrame(); @@ -236,7 +236,7 @@ // fire. This should suspend the image animation. (Suspend the image's // animation timeline.) WebView().SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) + + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) + timer->NextFireInterval()); EXPECT_TRUE(svg_image_chrome_client.IsSuspended()); @@ -244,7 +244,7 @@ // Set page visibility to 'visible' - this should schedule a new animation // frame and resume the image animation. WebView().SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false); - test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) + + test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) + timer->NextFireInterval()); Compositor().BeginFrame();
diff --git a/third_party/blink/renderer/core/svg/svg_uri_reference.cc b/third_party/blink/renderer/core/svg/svg_uri_reference.cc index 3153f223..47221fbc 100644 --- a/third_party/blink/renderer/core/svg/svg_uri_reference.cc +++ b/third_party/blink/renderer/core/svg/svg_uri_reference.cc
@@ -151,7 +151,7 @@ observer = nullptr; } -const AttrNameToTrustedType& SVGURIReference::GetCheckedAttributeTypes() const { +const AttrNameToTrustedType& SVGURIReference::GetCheckedAttributeTypes() { DEFINE_STATIC_LOCAL( AttrNameToTrustedType, attribute_map, ({
diff --git a/third_party/blink/renderer/core/svg/svg_uri_reference.h b/third_party/blink/renderer/core/svg/svg_uri_reference.h index b15cb9d5..8d24052 100644 --- a/third_party/blink/renderer/core/svg/svg_uri_reference.h +++ b/third_party/blink/renderer/core/svg/svg_uri_reference.h
@@ -81,7 +81,7 @@ // JS API SVGAnimatedHref* href() const { return href_.Get(); } - const AttrNameToTrustedType& GetCheckedAttributeTypes() const; + static const AttrNameToTrustedType& GetCheckedAttributeTypes(); void Trace(blink::Visitor*) override;
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index d564613..59043da3 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -3324,7 +3324,7 @@ return document_->Loader() ->GetTiming() .MonotonicTimeToZeroBasedDocumentTime( - base::TimeTicks() + TimeDelta::FromSecondsD(platform_time)) + base::TimeTicks() + base::TimeDelta::FromSecondsD(platform_time)) .InSecondsF(); }
diff --git a/third_party/blink/renderer/core/testing/sim/sim_network.cc b/third_party/blink/renderer/core/testing/sim/sim_network.cc index 0dfea38c..5caecb4 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_network.cc +++ b/third_party/blink/renderer/core/testing/sim/sim_network.cc
@@ -77,7 +77,7 @@ } void SimNetwork::DidFinishLoading(WebURLLoaderClient* client, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t total_encoded_data_length, int64_t total_encoded_body_length, int64_t total_decoded_body_length) {
diff --git a/third_party/blink/renderer/core/testing/sim/sim_network.h b/third_party/blink/renderer/core/testing/sim/sim_network.h index 56f424d..0257c16 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_network.h +++ b/third_party/blink/renderer/core/testing/sim/sim_network.h
@@ -46,7 +46,7 @@ int64_t total_encoded_body_length, int64_t total_decoded_body_length) override; void DidFinishLoading(WebURLLoaderClient*, - TimeTicks finish_time, + base::TimeTicks finish_time, int64_t total_encoded_data_length, int64_t total_encoded_body_length, int64_t total_decoded_body_length) override;
diff --git a/third_party/blink/renderer/core/testing/sim/sim_request.cc b/third_party/blink/renderer/core/testing/sim/sim_request.cc index c1b021d..ea81814 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_request.cc +++ b/third_party/blink/renderer/core/testing/sim/sim_request.cc
@@ -99,8 +99,8 @@ } else { // TODO(esprehn): Is claiming a request time of 0 okay for tests? client_->DidFinishLoading( - TimeTicks(), total_encoded_data_length_, total_encoded_data_length_, - total_encoded_data_length_, false, + base::TimeTicks(), total_encoded_data_length_, + total_encoded_data_length_, total_encoded_data_length_, false, std::vector<network::cors::PreflightTimingInfo>()); } }
diff --git a/third_party/blink/renderer/core/timing/event_timing.cc b/third_party/blink/renderer/core/timing/event_timing.cc index 3110fb11..7bb1018 100644 --- a/third_party/blink/renderer/core/timing/event_timing.cc +++ b/third_party/blink/renderer/core/timing/event_timing.cc
@@ -59,8 +59,8 @@ return false; } -EventTiming::EventTiming(TimeTicks processing_start, - TimeTicks event_timestamp, +EventTiming::EventTiming(base::TimeTicks processing_start, + base::TimeTicks event_timestamp, WindowPerformance* performance) : processing_start_(processing_start), event_timestamp_(event_timestamp), @@ -79,7 +79,7 @@ if (!should_report_for_event_timing && !should_log_event) return nullptr; - TimeTicks event_timestamp = + base::TimeTicks event_timestamp = event.IsPointerEvent() ? ToPointerEvent(&event)->OldestPlatformTimeStamp() : event.PlatformTimeStamp();
diff --git a/third_party/blink/renderer/core/timing/event_timing.h b/third_party/blink/renderer/core/timing/event_timing.h index 329cb08..a6d7eef4 100644 --- a/third_party/blink/renderer/core/timing/event_timing.h +++ b/third_party/blink/renderer/core/timing/event_timing.h
@@ -28,8 +28,8 @@ // Returns an object only if the event is relevant for the EventTiming API. static std::unique_ptr<EventTiming> Create(LocalDOMWindow*, const Event&); - explicit EventTiming(TimeTicks processing_start, - TimeTicks event_timestamp, + explicit EventTiming(base::TimeTicks processing_start, + base::TimeTicks event_timestamp, WindowPerformance* performance); // Notifies the Performance object that the event has been dispatched. @@ -40,9 +40,9 @@ private: // The time the first event handler or default action started to execute. - TimeTicks processing_start_; + base::TimeTicks processing_start_; // The event timestamp to be used in EventTiming and in histograms. - TimeTicks event_timestamp_; + base::TimeTicks event_timestamp_; Persistent<WindowPerformance> performance_; DISALLOW_COPY_AND_ASSIGN(EventTiming);
diff --git a/third_party/blink/renderer/core/timing/memory_info.cc b/third_party/blink/renderer/core/timing/memory_info.cc index 5ebb0ae..4cfde32 100644 --- a/third_party/blink/renderer/core/timing/memory_info.cc +++ b/third_party/blink/renderer/core/timing/memory_info.cc
@@ -43,8 +43,10 @@ namespace blink { -static constexpr TimeDelta kTwentyMinutes = TimeDelta::FromMinutes(20); -static constexpr TimeDelta kFiftyMs = TimeDelta::FromMilliseconds(50); +static constexpr base::TimeDelta kTwentyMinutes = + base::TimeDelta::FromMinutes(20); +static constexpr base::TimeDelta kFiftyMs = + base::TimeDelta::FromMilliseconds(50); static void GetHeapSize(HeapInfo& info) { v8::HeapStatistics heap_statistics; @@ -86,10 +88,10 @@ // to make it more difficult for attackers to compare memory usage before // and after some event. We limit to once every 50 ms in the Precise case to // avoid exposing precise GC timings. - TimeTicks now = clock_->NowTicks(); - TimeDelta delta_allowed = precision == MemoryInfo::Precision::Bucketized - ? kTwentyMinutes - : kFiftyMs; + base::TimeTicks now = clock_->NowTicks(); + base::TimeDelta delta_allowed = + precision == MemoryInfo::Precision::Bucketized ? kTwentyMinutes + : kFiftyMs; if (!last_update_time_.has_value() || now - last_update_time_.value() >= delta_allowed) { Update(precision); @@ -111,7 +113,7 @@ QuantizeMemorySize(info_.total_js_heap_size_without_external_memory); } - base::Optional<TimeTicks> last_update_time_; + base::Optional<base::TimeTicks> last_update_time_; const base::TickClock* clock_; HeapInfo info_;
diff --git a/third_party/blink/renderer/core/timing/memory_info_test.cc b/third_party/blink/renderer/core/timing/memory_info_test.cc index b0670efc..e930aa6 100644 --- a/third_party/blink/renderer/core/timing/memory_info_test.cc +++ b/third_party/blink/renderer/core/timing/memory_info_test.cc
@@ -240,9 +240,9 @@ } TEST_F(MemoryInfoTest, ZeroTime) { - // In this test, we make sure that even if the current TimeTicks() value is - // very close to 0, we still obtain memory information from the first call to - // MemoryInfo::Create. + // In this test, we make sure that even if the current base::TimeTicks() value + // is very close to 0, we still obtain memory information from the first call + // to MemoryInfo::Create. MemoryInfoTestScopedMockTime mock_time(MemoryInfo::Precision::Precise); mock_time.AdvanceClock(base::TimeDelta::FromMicroseconds(100)); V8TestingScope scope;
diff --git a/third_party/blink/renderer/core/timing/performance.cc b/third_party/blink/renderer/core/timing/performance.cc index e84fb2b..b8bf26f8 100644 --- a/third_party/blink/renderer/core/timing/performance.cc +++ b/third_party/blink/renderer/core/timing/performance.cc
@@ -95,7 +95,7 @@ constexpr size_t kDefaultLayoutJankBufferSize = 150; Performance::Performance( - TimeTicks time_origin, + base::TimeTicks time_origin, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : resource_timing_buffer_size_limit_(kDefaultResourceTimingBufferSize), event_timing_buffer_max_size_(kDefaultEventTimingBufferSize), @@ -456,7 +456,7 @@ result.last_redirect_end_time = last_chained_timing->ReceiveHeadersEnd(); } else { result.allow_redirect_details = false; - result.last_redirect_end_time = TimeTicks(); + result.last_redirect_end_time = base::TimeTicks(); } if (!result.allow_redirect_details) { // TODO(https://crbug.com/817691): There was previously a DCHECK that @@ -470,7 +470,7 @@ } } else { result.allow_redirect_details = false; - result.last_redirect_end_time = TimeTicks(); + result.last_redirect_end_time = base::TimeTicks(); } result.transfer_size = info.TransferSize(); @@ -505,7 +505,8 @@ } if (!resource_timing_buffer_full_event_pending_) { resource_timing_buffer_full_event_pending_ = true; - resource_timing_buffer_full_timer_.StartOneShot(TimeDelta(), FROM_HERE); + resource_timing_buffer_full_timer_.StartOneShot(base::TimeDelta(), + FROM_HERE); } resource_timing_secondary_buffer_.push_back(entry); } @@ -606,17 +607,17 @@ DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull)); } -void Performance::AddFirstPaintTiming(TimeTicks start_time) { +void Performance::AddFirstPaintTiming(base::TimeTicks start_time) { AddPaintTiming(PerformancePaintTiming::PaintType::kFirstPaint, start_time); } -void Performance::AddFirstContentfulPaintTiming(TimeTicks start_time) { +void Performance::AddFirstContentfulPaintTiming(base::TimeTicks start_time) { AddPaintTiming(PerformancePaintTiming::PaintType::kFirstContentfulPaint, start_time); } void Performance::AddPaintTiming(PerformancePaintTiming::PaintType type, - TimeTicks start_time) { + base::TimeTicks start_time) { PerformanceEntry* entry = MakeGarbageCollected<PerformancePaintTiming>( type, MonotonicTimeToDOMHighResTimeStamp(start_time)); // Always buffer First Paint & First Contentful Paint. @@ -633,8 +634,8 @@ } void Performance::AddLongTaskTiming( - TimeTicks start_time, - TimeTicks end_time, + base::TimeTicks start_time, + base::TimeTicks end_time, const AtomicString& name, const String& frame_src, const String& frame_id, @@ -881,7 +882,7 @@ void Performance::ActivateObserver(PerformanceObserver& observer) { if (active_observers_.IsEmpty()) - deliver_observations_timer_.StartOneShot(TimeDelta(), FROM_HERE); + deliver_observations_timer_.StartOneShot(base::TimeDelta(), FROM_HERE); active_observers_.insert(&observer); } @@ -919,8 +920,8 @@ // static DOMHighResTimeStamp Performance::MonotonicTimeToDOMHighResTimeStamp( - TimeTicks time_origin, - TimeTicks monotonic_time, + base::TimeTicks time_origin, + base::TimeTicks monotonic_time, bool allow_negative_value) { // Avoid exposing raw platform timestamps. if (monotonic_time.is_null() || time_origin.is_null()) @@ -935,7 +936,7 @@ } DOMHighResTimeStamp Performance::MonotonicTimeToDOMHighResTimeStamp( - TimeTicks monotonic_time) const { + base::TimeTicks monotonic_time) const { return MonotonicTimeToDOMHighResTimeStamp(time_origin_, monotonic_time, false /* allow_negative_value */); } @@ -985,7 +986,7 @@ return unix_at_zero_monotonic_.value(); } -TimeTicks Performance::UnifiedClock::NowTicks() const { +base::TimeTicks Performance::UnifiedClock::NowTicks() const { return tick_clock_->NowTicks(); }
diff --git a/third_party/blink/renderer/core/timing/performance.h b/third_party/blink/renderer/core/timing/performance.h index 03562a19..712410d2 100644 --- a/third_party/blink/renderer/core/timing/performance.h +++ b/third_party/blink/renderer/core/timing/performance.h
@@ -104,15 +104,15 @@ static double ClampTimeResolution(double time_seconds); static DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp( - TimeTicks time_origin, - TimeTicks monotonic_time, + base::TimeTicks time_origin, + base::TimeTicks monotonic_time, bool allow_negative_value); // Translate given platform monotonic time in seconds into a high resolution // DOMHighResTimeStamp in milliseconds. The result timestamp is relative to // document's time origin and has a time resolution that is safe for // exposing to web. - DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp(TimeTicks) const; + DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp(base::TimeTicks) const; DOMHighResTimeStamp now() const; // High Resolution Time Level 3 timeOrigin. @@ -142,8 +142,8 @@ kResourcetimingbufferfull) void AddLongTaskTiming( - TimeTicks start_time, - TimeTicks end_time, + base::TimeTicks start_time, + base::TimeTicks end_time, const AtomicString& name, const String& culprit_frame_src, const String& culprit_frame_id, @@ -168,9 +168,9 @@ void NotifyNavigationTimingToObservers(); - void AddFirstPaintTiming(TimeTicks start_time); + void AddFirstPaintTiming(base::TimeTicks start_time); - void AddFirstContentfulPaintTiming(TimeTicks start_time); + void AddFirstContentfulPaintTiming(base::TimeTicks start_time); bool IsElementTimingBufferFull() const; void AddElementTimingBuffer(PerformanceElementTiming&); @@ -288,7 +288,7 @@ UnifiedClock(const base::Clock* clock, const base::TickClock* tick_clock) : clock_(clock), tick_clock_(tick_clock) {} DOMHighResTimeStamp GetUnixAtZeroMonotonic() const; - TimeTicks NowTicks() const; + base::TimeTicks NowTicks() const; private: const base::Clock* clock_; @@ -301,7 +301,8 @@ void ResetTimeOriginForTesting(base::TimeTicks time_origin); private: - void AddPaintTiming(PerformancePaintTiming::PaintType, TimeTicks start_time); + void AddPaintTiming(PerformancePaintTiming::PaintType, + base::TimeTicks start_time); PerformanceMeasure* MeasureInternal( ScriptState*, @@ -322,7 +323,7 @@ PerformanceEntry::EntryType type); protected: - Performance(TimeTicks time_origin, + Performance(base::TimeTicks time_origin, scoped_refptr<base::SingleThreadTaskRunner>); // Expect WindowPerformance to override this method, @@ -360,7 +361,7 @@ Member<PerformanceEntry> first_contentful_paint_timing_; Member<PerformanceEventTiming> first_input_timing_; - TimeTicks time_origin_; + base::TimeTicks time_origin_; const UnifiedClock* unified_clock_; PerformanceEntryTypeMask observer_filter_options_;
diff --git a/third_party/blink/renderer/core/timing/performance_navigation_timing.cc b/third_party/blink/renderer/core/timing/performance_navigation_timing.cc index 909fd410..07534734 100644 --- a/third_party/blink/renderer/core/timing/performance_navigation_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_navigation_timing.cc
@@ -19,7 +19,7 @@ PerformanceNavigationTiming::PerformanceNavigationTiming( LocalFrame* frame, ResourceTimingInfo* info, - TimeTicks time_origin, + base::TimeTicks time_origin, const WebVector<WebServerTimingInfo>& server_timing) : PerformanceResourceTiming( info ? AtomicString(
diff --git a/third_party/blink/renderer/core/timing/performance_navigation_timing.h b/third_party/blink/renderer/core/timing/performance_navigation_timing.h index 5889f9e..8a9488e 100644 --- a/third_party/blink/renderer/core/timing/performance_navigation_timing.h +++ b/third_party/blink/renderer/core/timing/performance_navigation_timing.h
@@ -33,7 +33,7 @@ public: PerformanceNavigationTiming(LocalFrame*, ResourceTimingInfo*, - TimeTicks time_origin, + base::TimeTicks time_origin, const WebVector<WebServerTimingInfo>&); // Attributes inheritted from PerformanceEntry.
diff --git a/third_party/blink/renderer/core/timing/performance_observer_test.cc b/third_party/blink/renderer/core/timing/performance_observer_test.cc index 709417f7..3ce2de72 100644 --- a/third_party/blink/renderer/core/timing/performance_observer_test.cc +++ b/third_party/blink/renderer/core/timing/performance_observer_test.cc
@@ -21,7 +21,7 @@ class MockPerformance : public Performance { public: explicit MockPerformance(ScriptState* script_state) - : Performance(TimeTicks(), + : Performance(base::TimeTicks(), ExecutionContext::From(script_state) ->GetTaskRunner(TaskType::kPerformanceTimeline)) {} ~MockPerformance() override = default;
diff --git a/third_party/blink/renderer/core/timing/performance_resource_timing.cc b/third_party/blink/renderer/core/timing/performance_resource_timing.cc index 6ab95ff..d2bf374 100644 --- a/third_party/blink/renderer/core/timing/performance_resource_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_resource_timing.cc
@@ -44,7 +44,7 @@ PerformanceResourceTiming::PerformanceResourceTiming( const WebResourceTimingInfo& info, - TimeTicks time_origin, + base::TimeTicks time_origin, const AtomicString& initiator_type) : PerformanceEntry(info.name, Performance::MonotonicTimeToDOMHighResTimeStamp( @@ -80,7 +80,7 @@ // This constructor is for PerformanceNavigationTiming. PerformanceResourceTiming::PerformanceResourceTiming( const AtomicString& name, - TimeTicks time_origin, + base::TimeTicks time_origin, const WebVector<WebServerTimingInfo>& server_timing) : PerformanceEntry(name, 0.0, 0.0), time_origin_(time_origin), @@ -235,7 +235,7 @@ return domainLookupEnd(); // connectStart includes any DNS time, so we may need to trim that off. - TimeTicks connect_start = timing->ConnectStart(); + base::TimeTicks connect_start = timing->ConnectStart(); if (!timing->DnsEnd().is_null()) connect_start = timing->DnsEnd(); @@ -292,7 +292,7 @@ if (!timing) return requestStart(); - TimeTicks response_start = timing->ReceiveHeadersStart(); + base::TimeTicks response_start = timing->ReceiveHeadersStart(); if (response_start.is_null()) response_start = timing->ReceiveHeadersEnd(); if (response_start.is_null())
diff --git a/third_party/blink/renderer/core/timing/performance_resource_timing.h b/third_party/blink/renderer/core/timing/performance_resource_timing.h index 4b1e849..7a76c4a 100644 --- a/third_party/blink/renderer/core/timing/performance_resource_timing.h +++ b/third_party/blink/renderer/core/timing/performance_resource_timing.h
@@ -52,10 +52,10 @@ // This constructor is for PerformanceNavigationTiming. // Related doc: https://goo.gl/uNecAj. PerformanceResourceTiming(const AtomicString& name, - TimeTicks time_origin, + base::TimeTicks time_origin, const WebVector<WebServerTimingInfo>&); PerformanceResourceTiming(const WebResourceTimingInfo&, - TimeTicks time_origin, + base::TimeTicks time_origin, const AtomicString& initiator_type); ~PerformanceResourceTiming() override; @@ -90,7 +90,7 @@ virtual AtomicString AlpnNegotiatedProtocol() const; virtual AtomicString ConnectionInfo() const; - TimeTicks TimeOrigin() const { return time_origin_; } + base::TimeTicks TimeOrigin() const { return time_origin_; } private: static AtomicString GetNextHopProtocol( @@ -109,10 +109,10 @@ AtomicString initiator_type_; AtomicString alpn_negotiated_protocol_; AtomicString connection_info_; - TimeTicks time_origin_; + base::TimeTicks time_origin_; scoped_refptr<ResourceLoadTiming> timing_; - TimeTicks last_redirect_end_time_; - TimeTicks response_end_; + base::TimeTicks last_redirect_end_time_; + base::TimeTicks response_end_; uint64_t transfer_size_ = 0; uint64_t encoded_body_size_ = 0; uint64_t decoded_body_size_ = 0;
diff --git a/third_party/blink/renderer/core/timing/performance_test.cc b/third_party/blink/renderer/core/timing/performance_test.cc index 2c238e1a..1c726e0 100644 --- a/third_party/blink/renderer/core/timing/performance_test.cc +++ b/third_party/blink/renderer/core/timing/performance_test.cc
@@ -25,7 +25,7 @@ class TestPerformance : public Performance { public: explicit TestPerformance(ScriptState* script_state) - : Performance(TimeTicks(), + : Performance(base::TimeTicks(), ExecutionContext::From(script_state) ->GetTaskRunner(TaskType::kPerformanceTimeline)) {} ~TestPerformance() override = default;
diff --git a/third_party/blink/renderer/core/timing/performance_timing.cc b/third_party/blink/renderer/core/timing/performance_timing.cc index 7f59574..8bc7afe 100644 --- a/third_party/blink/renderer/core/timing/performance_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_timing.cc
@@ -52,7 +52,7 @@ // Legacy support for NT1(https://www.w3.org/TR/navigation-timing/). namespace blink { -static uint64_t ToIntegerMilliseconds(TimeDelta duration) { +static uint64_t ToIntegerMilliseconds(base::TimeDelta duration) { // TODO(npm): add histograms to understand when/why |duration| is sometimes // negative. double clamped_seconds = @@ -141,7 +141,7 @@ // This will be zero when a DNS request is not performed. Rather than // exposing a special value that indicates no DNS, we "backfill" with // fetchStart. - TimeTicks dns_start = timing->DnsStart(); + base::TimeTicks dns_start = timing->DnsStart(); if (dns_start.is_null()) return fetchStart(); @@ -156,7 +156,7 @@ // This will be zero when a DNS request is not performed. Rather than // exposing a special value that indicates no DNS, we "backfill" with // domainLookupStart. - TimeTicks dns_end = timing->DnsEnd(); + base::TimeTicks dns_end = timing->DnsEnd(); if (dns_end.is_null()) return domainLookupStart(); @@ -175,7 +175,7 @@ // connectStart will be zero when a network request is not made. Rather than // exposing a special value that indicates no new connection, we "backfill" // with domainLookupEnd. - TimeTicks connect_start = timing->ConnectStart(); + base::TimeTicks connect_start = timing->ConnectStart(); if (connect_start.is_null() || loader->GetResponse().ConnectionReused()) return domainLookupEnd(); @@ -200,7 +200,7 @@ // connectEnd will be zero when a network request is not made. Rather than // exposing a special value that indicates no new connection, we "backfill" // with connectStart. - TimeTicks connect_end = timing->ConnectEnd(); + base::TimeTicks connect_end = timing->ConnectEnd(); if (connect_end.is_null() || loader->GetResponse().ConnectionReused()) return connectStart(); @@ -216,7 +216,7 @@ if (!timing) return 0; - TimeTicks ssl_start = timing->SslStart(); + base::TimeTicks ssl_start = timing->SslStart(); if (ssl_start.is_null()) return 0; @@ -237,7 +237,7 @@ if (!timing) return requestStart(); - TimeTicks response_start = timing->ReceiveHeadersStart(); + base::TimeTicks response_start = timing->ReceiveHeadersStart(); if (response_start.is_null()) response_start = timing->ReceiveHeadersEnd(); if (response_start.is_null()) @@ -622,7 +622,7 @@ } uint64_t PerformanceTiming::MonotonicTimeToIntegerMilliseconds( - TimeTicks time) const { + base::TimeTicks time) const { const DocumentLoadTiming* timing = GetDocumentLoadTiming(); if (!timing) return 0;
diff --git a/third_party/blink/renderer/core/timing/performance_timing.h b/third_party/blink/renderer/core/timing/performance_timing.h index 841737f..717e20a8 100644 --- a/third_party/blink/renderer/core/timing/performance_timing.h +++ b/third_party/blink/renderer/core/timing/performance_timing.h
@@ -150,7 +150,7 @@ void Trace(blink::Visitor*) override; - uint64_t MonotonicTimeToIntegerMilliseconds(TimeTicks) const; + uint64_t MonotonicTimeToIntegerMilliseconds(base::TimeTicks) const; std::unique_ptr<TracedValue> GetNavigationTracingData();
diff --git a/third_party/blink/renderer/core/timing/profiler_group.cc b/third_party/blink/renderer/core/timing/profiler_group.cc index a0bc711a..3da3bb5 100644 --- a/third_party/blink/renderer/core/timing/profiler_group.cc +++ b/third_party/blink/renderer/core/timing/profiler_group.cc
@@ -25,7 +25,8 @@ #if defined(OS_WIN) // On Windows, assume we have the coarsest possible timer. -static constexpr int kBaseSampleIntervalMs = Time::kMinLowResolutionThresholdMs; +static constexpr int kBaseSampleIntervalMs = + base::Time::kMinLowResolutionThresholdMs; #else // Default to a 10ms base sampling interval on other platforms. // TODO(acomminos): Reevaluate based on empirical overhead. @@ -56,7 +57,7 @@ cpu_profiler_->SetUsePreciseSampling(false); #endif // defined(OS_WIN) cpu_profiler_->SetSamplingInterval(kBaseSampleIntervalMs * - Time::kMicrosecondsPerMillisecond); + base::Time::kMicrosecondsPerMillisecond); } Profiler* ProfilerGroup::CreateProfiler(ScriptState* script_state,
diff --git a/third_party/blink/renderer/core/timing/sub_task_attribution.cc b/third_party/blink/renderer/core/timing/sub_task_attribution.cc index e7079af..caaaa0e 100644 --- a/third_party/blink/renderer/core/timing/sub_task_attribution.cc +++ b/third_party/blink/renderer/core/timing/sub_task_attribution.cc
@@ -8,8 +8,8 @@ SubTaskAttribution::SubTaskAttribution(const AtomicString& sub_task_name, const String& script_url, - TimeTicks start_time, - TimeDelta duration) + base::TimeTicks start_time, + base::TimeDelta duration) : sub_task_name_(sub_task_name), script_url_(script_url), start_time_(start_time),
diff --git a/third_party/blink/renderer/core/timing/sub_task_attribution.h b/third_party/blink/renderer/core/timing/sub_task_attribution.h index af084e9..af4faeb 100644 --- a/third_party/blink/renderer/core/timing/sub_task_attribution.h +++ b/third_party/blink/renderer/core/timing/sub_task_attribution.h
@@ -23,12 +23,12 @@ SubTaskAttribution(const AtomicString& sub_task_name, const String& script_url, - TimeTicks start_time, - TimeDelta duration); + base::TimeTicks start_time, + base::TimeDelta duration); inline AtomicString subTaskName() const { return sub_task_name_; } inline String scriptURL() const { return script_url_; } - inline TimeTicks startTime() const { return start_time_; } - inline TimeDelta duration() const { return duration_; } + inline base::TimeTicks startTime() const { return start_time_; } + inline base::TimeDelta duration() const { return duration_; } inline DOMHighResTimeStamp highResStartTime() const { return high_res_start_time_; @@ -46,8 +46,8 @@ private: AtomicString sub_task_name_; String script_url_; - TimeTicks start_time_; - TimeDelta duration_; + base::TimeTicks start_time_; + base::TimeDelta duration_; DOMHighResTimeStamp high_res_start_time_; DOMHighResTimeStamp high_res_duration_; };
diff --git a/third_party/blink/renderer/core/timing/window_performance.cc b/third_party/blink/renderer/core/timing/window_performance.cc index d1ce721..47a7ead4 100644 --- a/third_party/blink/renderer/core/timing/window_performance.cc +++ b/third_party/blink/renderer/core/timing/window_performance.cc
@@ -119,14 +119,14 @@ } // namespace -static TimeTicks ToTimeOrigin(LocalDOMWindow* window) { +static base::TimeTicks ToTimeOrigin(LocalDOMWindow* window) { Document* document = window->document(); if (!document) - return TimeTicks(); + return base::TimeTicks(); DocumentLoader* loader = document->Loader(); if (!loader) - return TimeTicks(); + return base::TimeTicks(); return loader->GetTiming().ReferenceMonotonicTime(); } @@ -328,9 +328,9 @@ } void WindowPerformance::RegisterEventTiming(const AtomicString& event_type, - TimeTicks start_time, - TimeTicks processing_start, - TimeTicks processing_end, + base::TimeTicks start_time, + base::TimeTicks processing_start, + base::TimeTicks processing_end, bool cancelable) { // |start_time| could be null in some tests that inject input. DCHECK(!processing_start.is_null()); @@ -357,7 +357,7 @@ } void WindowPerformance::ReportEventTimings(WebWidgetClient::SwapResult result, - TimeTicks timestamp) { + base::TimeTicks timestamp) { DOMHighResTimeStamp end_time = MonotonicTimeToDOMHighResTimeStamp(timestamp); bool event_timing_enabled = RuntimeEnabledFeatures::EventTimingEnabled(GetExecutionContext()); @@ -395,8 +395,8 @@ void WindowPerformance::AddElementTiming(const AtomicString& name, const String& url, const FloatRect& rect, - TimeTicks start_time, - TimeTicks response_end, + base::TimeTicks start_time, + base::TimeTicks response_end, const AtomicString& identifier, const IntSize& intrinsic_size, const AtomicString& id,
diff --git a/third_party/blink/renderer/core/timing/window_performance.h b/third_party/blink/renderer/core/timing/window_performance.h index 0bb1ee8..7166693 100644 --- a/third_party/blink/renderer/core/timing/window_performance.h +++ b/third_party/blink/renderer/core/timing/window_performance.h
@@ -71,16 +71,16 @@ // promise to calculate the |duration| attribute when such promise is // resolved. void RegisterEventTiming(const AtomicString& event_type, - TimeTicks start_time, - TimeTicks processing_start, - TimeTicks processing_end, + base::TimeTicks start_time, + base::TimeTicks processing_start, + base::TimeTicks processing_end, bool cancelable); void AddElementTiming(const AtomicString& name, const String& url, const FloatRect& rect, - TimeTicks start_time, - TimeTicks response_end, + base::TimeTicks start_time, + base::TimeTicks response_end, const AtomicString& identifier, const IntSize& intrinsic_size, const AtomicString& id, @@ -111,7 +111,7 @@ // Method called once swap promise is resolved. It will add all event timings // that have not been added since the last swap promise. void ReportEventTimings(WebWidgetClient::SwapResult result, - TimeTicks timestamp); + base::TimeTicks timestamp); void DispatchFirstInputTiming(PerformanceEventTiming* entry);
diff --git a/third_party/blink/renderer/core/timing/window_performance_test.cc b/third_party/blink/renderer/core/timing/window_performance_test.cc index 24ea996..ba7e86d 100644 --- a/third_party/blink/renderer/core/timing/window_performance_test.cc +++ b/third_party/blink/renderer/core/timing/window_performance_test.cc
@@ -23,8 +23,8 @@ namespace { -TimeTicks GetTimeOrigin() { - return TimeTicks() + TimeDelta::FromSeconds(500); +base::TimeTicks GetTimeOrigin() { + return base::TimeTicks() + base::TimeDelta::FromSeconds(500); } } // namespace @@ -63,7 +63,7 @@ base::TimeTicks(), base::TimeTicks() + base::TimeDelta::FromSeconds(1)); } - void SimulateSwapPromise(TimeTicks timestamp) { + void SimulateSwapPromise(base::TimeTicks timestamp) { performance_->ReportEventTimings(WebWidgetClient::SwapResult::kDidSwap, timestamp); } @@ -200,15 +200,15 @@ V8TestingScope scope; auto initial_offset = test_task_runner_->NowTicks().since_origin().InSecondsF(); - test_task_runner_->FastForwardBy(GetTimeOrigin() - TimeTicks()); + test_task_runner_->FastForwardBy(GetTimeOrigin() - base::TimeTicks()); DummyExceptionStateForTesting exception_state; - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(2)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2)); for (int i = 0; i < 8; i++) { performance_->mark(scope.GetScriptState(), AtomicString::Number(i), exception_state); } - test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(2)); + test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2)); for (int i = 8; i < 17; i++) { performance_->mark(scope.GetScriptState(), AtomicString::Number(i), exception_state); @@ -229,12 +229,16 @@ ScopedEventTimingForTest event_timing(true); EXPECT_TRUE(page_holder_->GetFrame().Loader().GetDocumentLoader()); - TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSecondsD(1.1); - TimeTicks processing_start = GetTimeOrigin() + TimeDelta::FromSecondsD(3.3); - TimeTicks processing_end = GetTimeOrigin() + TimeDelta::FromSecondsD(3.8); + base::TimeTicks start_time = + GetTimeOrigin() + base::TimeDelta::FromSecondsD(1.1); + base::TimeTicks processing_start = + GetTimeOrigin() + base::TimeDelta::FromSecondsD(3.3); + base::TimeTicks processing_end = + GetTimeOrigin() + base::TimeDelta::FromSecondsD(3.8); performance_->RegisterEventTiming("click", start_time, processing_start, processing_end, false); - TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromSecondsD(6.0); + base::TimeTicks swap_time = + GetTimeOrigin() + base::TimeDelta::FromSecondsD(6.0); SimulateSwapPromise(swap_time); EXPECT_EQ(1u, performance_->getEntriesByName("click", "event").size()); performance_->clearEventTimings(); @@ -262,19 +266,24 @@ TEST_F(WindowPerformanceTest, Expose100MsEvents) { ScopedEventTimingForTest event_timing(true); - TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSeconds(1); - TimeTicks processing_start = start_time + TimeDelta::FromMilliseconds(10); - TimeTicks processing_end = processing_start + TimeDelta::FromMilliseconds(10); + base::TimeTicks start_time = + GetTimeOrigin() + base::TimeDelta::FromSeconds(1); + base::TimeTicks processing_start = + start_time + base::TimeDelta::FromMilliseconds(10); + base::TimeTicks processing_end = + processing_start + base::TimeDelta::FromMilliseconds(10); performance_->RegisterEventTiming("mousedown", start_time, processing_start, processing_end, false); - TimeTicks start_time2 = start_time + TimeDelta::FromMicroseconds(200); + base::TimeTicks start_time2 = + start_time + base::TimeDelta::FromMicroseconds(200); performance_->RegisterEventTiming("click", start_time2, processing_start, processing_end, false); // The swap time is 100.1 ms after |start_time| but only 99.9 ms after // |start_time2|. - TimeTicks swap_time = start_time + TimeDelta::FromMicroseconds(100100); + base::TimeTicks swap_time = + start_time + base::TimeDelta::FromMicroseconds(100100); SimulateSwapPromise(swap_time); // Only the longer event should have been reported. EXPECT_EQ(1u, performance_->getEntriesByType("event").size()); @@ -285,22 +294,23 @@ TEST_F(WindowPerformanceTest, EventTimingDuration) { ScopedEventTimingForTest event_timing(true); - TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromMilliseconds(1000); - TimeTicks processing_start = - GetTimeOrigin() + TimeDelta::FromMilliseconds(1001); - TimeTicks processing_end = - GetTimeOrigin() + TimeDelta::FromMilliseconds(1002); + base::TimeTicks start_time = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1000); + base::TimeTicks processing_start = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1001); + base::TimeTicks processing_end = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1002); performance_->RegisterEventTiming("click", start_time, processing_start, processing_end, false); - TimeTicks short_swap_time = - GetTimeOrigin() + TimeDelta::FromMilliseconds(1003); + base::TimeTicks short_swap_time = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1003); SimulateSwapPromise(short_swap_time); EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size()); performance_->RegisterEventTiming("click", start_time, processing_start, processing_end, true); - TimeTicks long_swap_time = - GetTimeOrigin() + TimeDelta::FromMilliseconds(2000); + base::TimeTicks long_swap_time = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2000); SimulateSwapPromise(long_swap_time); EXPECT_EQ(1u, performance_->getEntriesByName("click", "event").size()); @@ -318,14 +328,18 @@ size_t num_events = 10; for (size_t i = 0; i < num_events; ++i) { - TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSeconds(i); - TimeTicks processing_start = start_time + TimeDelta::FromMilliseconds(100); - TimeTicks processing_end = start_time + TimeDelta::FromMilliseconds(200); + base::TimeTicks start_time = + GetTimeOrigin() + base::TimeDelta::FromSeconds(i); + base::TimeTicks processing_start = + start_time + base::TimeDelta::FromMilliseconds(100); + base::TimeTicks processing_end = + start_time + base::TimeDelta::FromMilliseconds(200); performance_->RegisterEventTiming("click", start_time, processing_start, processing_end, false); EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size()); } - TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromSeconds(num_events); + base::TimeTicks swap_time = + GetTimeOrigin() + base::TimeDelta::FromSeconds(num_events); SimulateSwapPromise(swap_time); EXPECT_EQ(num_events, performance_->getEntriesByName("click", "event").size()); @@ -344,9 +358,9 @@ // firstInput does not have a |duration| threshold so use close values. performance_->RegisterEventTiming( input.event_type, GetTimeOrigin(), - GetTimeOrigin() + TimeDelta::FromMilliseconds(1), - GetTimeOrigin() + TimeDelta::FromMilliseconds(2), false); - SimulateSwapPromise(GetTimeOrigin() + TimeDelta::FromMilliseconds(3)); + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1), + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2), false); + SimulateSwapPromise(GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3)); PerformanceEntryVector firstInputs = performance_->getEntriesByType("firstInput"); EXPECT_GE(1u, firstInputs.size()); @@ -362,10 +376,10 @@ for (const auto& event : several_events) { performance_->RegisterEventTiming( event, GetTimeOrigin(), - GetTimeOrigin() + TimeDelta::FromMilliseconds(1), - GetTimeOrigin() + TimeDelta::FromMilliseconds(2), false); + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1), + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2), false); } - SimulateSwapPromise(GetTimeOrigin() + TimeDelta::FromMilliseconds(3)); + SimulateSwapPromise(GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3)); ASSERT_EQ(1u, performance_->getEntriesByType("firstInput").size()); EXPECT_EQ("mousedown", performance_->getEntriesByType("firstInput")[0]->name()); @@ -373,10 +387,13 @@ // Test that pointerdown followed by pointerup works as a 'firstInput'. TEST_F(WindowPerformanceTest, FirstPointerUp) { - TimeTicks start_time = GetTimeOrigin(); - TimeTicks processing_start = GetTimeOrigin() + TimeDelta::FromMilliseconds(1); - TimeTicks processing_end = GetTimeOrigin() + TimeDelta::FromMilliseconds(2); - TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromMilliseconds(3); + base::TimeTicks start_time = GetTimeOrigin(); + base::TimeTicks processing_start = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1); + base::TimeTicks processing_end = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2); + base::TimeTicks swap_time = + GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3); performance_->RegisterEventTiming("pointerdown", start_time, processing_start, processing_end, false); SimulateSwapPromise(swap_time);
diff --git a/third_party/blink/renderer/core/workers/worker_thread.cc b/third_party/blink/renderer/core/workers/worker_thread.cc index 6bbe756c..14f6f3f 100644 --- a/third_party/blink/renderer/core/workers/worker_thread.cc +++ b/third_party/blink/renderer/core/workers/worker_thread.cc
@@ -69,7 +69,8 @@ namespace { // TODO(nhiroki): Adjust the delay based on UMA. -constexpr TimeDelta kForcibleTerminationDelay = TimeDelta::FromSeconds(2); +constexpr base::TimeDelta kForcibleTerminationDelay = + base::TimeDelta::FromSeconds(2); } // namespace
diff --git a/third_party/blink/renderer/core/workers/worker_thread.h b/third_party/blink/renderer/core/workers/worker_thread.h index 9b41af3..45790f6 100644 --- a/third_party/blink/renderer/core/workers/worker_thread.h +++ b/third_party/blink/renderer/core/workers/worker_thread.h
@@ -366,7 +366,7 @@ ThreadState thread_state_ GUARDED_BY(mutex_) = ThreadState::kNotStarted; ExitCode exit_code_ GUARDED_BY(mutex_) = ExitCode::kNotTerminated; - TimeDelta forcible_termination_delay_; + base::TimeDelta forcible_termination_delay_; scoped_refptr<InspectorTaskRunner> inspector_task_runner_; base::UnguessableToken devtools_worker_token_;
diff --git a/third_party/blink/renderer/core/workers/worker_thread_test.cc b/third_party/blink/renderer/core/workers/worker_thread_test.cc index 26897d1..072b9761 100644 --- a/third_party/blink/renderer/core/workers/worker_thread_test.cc +++ b/third_party/blink/renderer/core/workers/worker_thread_test.cc
@@ -188,7 +188,7 @@ ParentExecutionContextTaskRunners::Create()); } - void SetForcibleTerminationDelay(TimeDelta forcible_termination_delay) { + void SetForcibleTerminationDelay(base::TimeDelta forcible_termination_delay) { worker_thread_->forcible_termination_delay_ = forcible_termination_delay; } @@ -329,7 +329,7 @@ } TEST_F(WorkerThreadTest, AsyncTerminate_WhileTaskIsRunning) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCallsForWorkerForciblyTerminated(); @@ -365,7 +365,7 @@ TEST_F(WorkerThreadTest, AsyncTerminateAndThenSyncTerminate_WhileTaskIsRunning) { - SetForcibleTerminationDelay(TimeDelta::FromMilliseconds(10)); + SetForcibleTerminationDelay(base::TimeDelta::FromMilliseconds(10)); ExpectReportingCallsForWorkerForciblyTerminated(); StartWithSourceCodeNotToFinish(); @@ -384,7 +384,7 @@ } TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); EXPECT_CALL(*reporting_proxy_, DidCreateWorkerGlobalScope(_)).Times(1); @@ -458,7 +458,7 @@ } TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunning) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCalls(); @@ -531,7 +531,7 @@ // Tests terminating a worker when debugger is paused. TEST_F(WorkerThreadTest, MAYBE_TerminateWhileWorkerPausedByDebugger) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCallsForWorkerForciblyTerminated(); @@ -552,7 +552,7 @@ } TEST_F(WorkerThreadTest, MAYBE_TerminateFrozenScript) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCallsForWorkerForciblyTerminated(); @@ -580,7 +580,7 @@ } TEST_F(WorkerThreadTest, MAYBE_NestedPauseFreeze) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCallsForWorkerForciblyTerminated(); @@ -619,7 +619,7 @@ } TEST_F(WorkerThreadTest, MAYBE_NestedPauseFreezeNoInterrupts) { - constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10); + constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10); SetForcibleTerminationDelay(kDelay); ExpectReportingCalls();
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc index 4579ba6..e9f8f3b 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -475,7 +475,7 @@ return; } - timeout_ = TimeDelta::FromMilliseconds(timeout); + timeout_ = base::TimeDelta::FromMilliseconds(timeout); // From http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute: // Note: This implies that the timeout attribute can be set while fetching is
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h index a77bc7a..54f9ce9 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h
@@ -304,7 +304,7 @@ // Not converted to ASCII lowercase. Must be lowered later or compared // using case insensitive comparison functions if needed. AtomicString mime_type_override_; - TimeDelta timeout_; + base::TimeDelta timeout_; Member<Blob> response_blob_; TaskHandle pending_abort_event_;
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc index 1dbea17..318a2492 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc
@@ -40,8 +40,8 @@ namespace blink { -static constexpr TimeDelta kMinimumProgressEventDispatchingInterval = - TimeDelta::FromMilliseconds(50); // 50 ms per specification. +static constexpr base::TimeDelta kMinimumProgressEventDispatchingInterval = + base::TimeDelta::FromMilliseconds(50); // 50 ms per specification. XMLHttpRequestProgressEventThrottle::DeferredEvent::DeferredEvent() { Clear();
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index c1cc5f9..27393090 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -327,6 +327,8 @@ "mediacapturefromelement/html_audio_element_capturer_source_unittest.cc", "mediacapturefromelement/html_video_element_capturer_source_unittest.cc", "mediarecorder/audio_track_recorder_unittest.cc", + "mediarecorder/media_recorder_handler_unittest.cc", + "mediarecorder/video_track_recorder_unittest.cc", "mediastream/media_constraints_test.cc", "mediastream/media_devices_test.cc", "mediastream/media_stream_constraints_util_sets_test.cc",
diff --git a/third_party/blink/renderer/modules/media_capabilities/DEPS b/third_party/blink/renderer/modules/media_capabilities/DEPS index 56cf584..70ac253 100644 --- a/third_party/blink/renderer/modules/media_capabilities/DEPS +++ b/third_party/blink/renderer/modules/media_capabilities/DEPS
@@ -8,4 +8,5 @@ "-third_party/blink/renderer/modules", "+third_party/blink/renderer/modules/encryptedmedia", "+third_party/blink/renderer/modules/media_capabilities", + "+third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h", ]
diff --git a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc index b0dd2df..a99fce0f 100644 --- a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc +++ b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
@@ -21,7 +21,6 @@ #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_encrypted_media_client.h" #include "third_party/blink/public/platform/web_encrypted_media_request.h" -#include "third_party/blink/public/platform/web_media_recorder_handler.h" #include "third_party/blink/public/platform/web_transmission_encoding_info_handler.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -41,6 +40,7 @@ #include "third_party/blink/renderer/modules/media_capabilities/media_configuration.h" #include "third_party/blink/renderer/modules/media_capabilities/media_decoding_configuration.h" #include "third_party/blink/renderer/modules/media_capabilities/media_encoding_configuration.h" +#include "third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/to_v8.h" #include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h" @@ -737,7 +737,7 @@ } if (configuration->type() == "record") { - if (auto handler = Platform::Current()->CreateMediaRecorderHandler( + if (auto handler = MediaRecorderHandler::Create( ExecutionContext::From(script_state) ->GetTaskRunner(TaskType::kInternalMediaRealTime))) { handler->EncodingInfo(ToWebMediaConfiguration(configuration),
diff --git a/third_party/blink/renderer/modules/mediarecorder/BUILD.gn b/third_party/blink/renderer/modules/mediarecorder/BUILD.gn index 55c31af8..832d6976 100644 --- a/third_party/blink/renderer/modules/mediarecorder/BUILD.gn +++ b/third_party/blink/renderer/modules/mediarecorder/BUILD.gn
@@ -2,7 +2,14 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/buildflag_header.gni") import("//third_party/blink/renderer/modules/modules.gni") +import("//third_party/webrtc/webrtc.gni") + +buildflag_header("buildflags") { + header = "buildflags.h" + flags = [ "RTC_USE_H264=$rtc_use_h264" ] +} blink_modules_sources("mediarecorder") { sources = [ @@ -18,9 +25,29 @@ "blob_event.h", "media_recorder.cc", "media_recorder.h", + "media_recorder_handler.cc", + "media_recorder_handler.h", + "vea_encoder.cc", + "vea_encoder.h", + "video_track_recorder.cc", + "video_track_recorder.h", + "vpx_encoder.cc", + "vpx_encoder.h", ] deps = [ + ":buildflags", + "//third_party/libvpx", + "//third_party/libyuv", "//third_party/opus", ] + + if (rtc_use_h264) { + sources += [ + "h264_encoder.cc", + "h264_encoder.h", + ] + + deps += [ "//third_party/openh264:encoder" ] + } }
diff --git a/third_party/blink/renderer/modules/mediarecorder/DEPS b/third_party/blink/renderer/modules/mediarecorder/DEPS index 58c32c7..2e96f7b 100644 --- a/third_party/blink/renderer/modules/mediarecorder/DEPS +++ b/third_party/blink/renderer/modules/mediarecorder/DEPS
@@ -1,5 +1,11 @@ include_rules = [ + "+base/containers/queue.h", + "+base/strings/string_piece.h", + "+base/task_runner_util.h", + "+base/threading/thread_task_runner_handle.h", + "+cc/paint", "+media", + "+skia/ext/platform_canvas.h", "-third_party/blink/renderer/modules", "+third_party/blink/renderer/modules/event_modules.h", "+third_party/blink/renderer/modules/event_target_modules.h", @@ -7,6 +13,10 @@ "+third_party/blink/renderer/modules/mediarecorder", "+third_party/blink/renderer/modules/mediastream", '+third_party/opus', + "+third_party/libvpx", + "+third_party/libyuv", + "+third_party/openh264/src/codec/api/svc", + "+ui/gfx/geometry", ] specific_include_rules = {
diff --git a/third_party/blink/renderer/modules/mediarecorder/README.md b/third_party/blink/renderer/modules/mediarecorder/README.md index 14cdb05..c8cd593b0 100644 --- a/third_party/blink/renderer/modules/mediarecorder/README.md +++ b/third_party/blink/renderer/modules/mediarecorder/README.md
@@ -53,12 +53,11 @@ ## Implementation in Chromium -This API is structured around the [MediaRecorder class], which owns a platform's -`WebMediaRecorderHandler` -- implemented by [`MediaRecorderHandler`] in content -which in turn owns a number of `VideoTrackRecorder`/`AudioTrackRecorder`s and a -single `WebmMuxer`. [`VideoTrackRecorder`]s are codec specific and encapsulate -the necessary resources to get the job done. All this is illustrated in the -[diagram] below. +This API is structured around the [MediaRecorder class], which owns a +[`MediaRecorderHandler`] which in turn owns a number of +`VideoTrackRecorder`/`AudioTrackRecorder`s and a single `WebmMuxer`. +[`VideoTrackRecorder`]s are codec specific and encapsulate the necessary resources +to get the job done. All this is illustrated in the [diagram] below. [MediaRecorder class]: https://w3c.github.io/mediacapture-record/#mediarecorder-api
diff --git a/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.cc b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.cc index 455f6c3..88bcbf4 100644 --- a/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.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 "third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.h" #include "base/macros.h" #include "media/base/audio_bus.h"
diff --git a/third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.h similarity index 88% rename from third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h rename to third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.h index 2112137..c714628b 100644 --- a/third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h +++ b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.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 THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_ -#define THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_ #include <memory> #include "base/macros.h" #include "base/threading/thread_checker.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_audio_sink.h" -#include "third_party/blink/public/platform/web_common.h" #include "third_party/blink/public/platform/web_media_stream_track.h" +#include "third_party/blink/renderer/modules/modules_export.h" namespace media { class AudioBus; @@ -30,7 +30,7 @@ // the "capture thread"). It owns an internal thread to use for encoding, on // which lives an AudioTrackEncoder with its own threading subtleties, see the // implementation file. -class BLINK_MODULES_EXPORT AudioTrackRecorder : public WebMediaStreamAudioSink { +class MODULES_EXPORT AudioTrackRecorder : public WebMediaStreamAudioSink { public: enum class CodecId { // Do not change the order of codecs. Add new ones right before LAST. @@ -93,4 +93,4 @@ } // namespace blink -#endif // THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_AUDIO_TRACK_RECORDER_H_
diff --git a/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder_unittest.cc b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder_unittest.cc index 22b1df20..c1dc7ef 100644 --- a/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder_unittest.cc +++ b/third_party/blink/renderer/modules/mediarecorder/audio_track_recorder_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 "third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.h" #include <stdint.h>
diff --git a/content/renderer/media_recorder/h264_encoder.cc b/third_party/blink/renderer/modules/mediarecorder/h264_encoder.cc similarity index 82% rename from content/renderer/media_recorder/h264_encoder.cc rename to third_party/blink/renderer/modules/mediarecorder/h264_encoder.cc index 924dfdf..fafd90c 100644 --- a/content/renderer/media_recorder/h264_encoder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/h264_encoder.cc
@@ -2,21 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/h264_encoder.h" +#include "third_party/blink/renderer/modules/mediarecorder/h264_encoder.h" -#include <string> - -#include "base/bind.h" -#include "base/threading/thread.h" -#include "base/trace_event/trace_event.h" #include "media/base/video_frame.h" +#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/openh264/src/codec/api/svc/codec_app_def.h" #include "third_party/openh264/src/codec/api/svc/codec_def.h" #include "ui/gfx/geometry/size.h" using media::VideoFrame; -namespace content { +namespace blink { void H264Encoder::ISVCEncoderDeleter::operator()(ISVCEncoder* codec) { if (!codec) @@ -27,10 +28,9 @@ } // static -void H264Encoder::ShutdownEncoder(std::unique_ptr<base::Thread> encoding_thread, +void H264Encoder::ShutdownEncoder(std::unique_ptr<Thread> encoding_thread, ScopedISVCEncoderPtr encoder) { - DCHECK(encoding_thread->IsRunning()); - encoding_thread->Stop(); + DCHECK(encoding_thread); // Both |encoding_thread| and |encoder| will be destroyed at end-of-scope. } @@ -41,14 +41,14 @@ : Encoder(on_encoded_video_callback, bits_per_second, std::move(task_runner)) { - DCHECK(encoding_thread_->IsRunning()); + DCHECK(encoding_thread_); } H264Encoder::~H264Encoder() { - main_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&H264Encoder::ShutdownEncoder, std::move(encoding_thread_), - std::move(openh264_encoder_))); + PostCrossThreadTask(*main_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&H264Encoder::ShutdownEncoder, + std::move(encoding_thread_), + std::move(openh264_encoder_))); } void H264Encoder::EncodeOnEncodingTaskRunner( @@ -105,11 +105,13 @@ } const bool is_key_frame = info.eFrameType == videoFrameTypeIDR; - origin_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(OnFrameEncodeCompleted, on_encoded_video_callback_, - video_params, std::move(data), nullptr, capture_timestamp, - is_key_frame)); + PostCrossThreadTask( + *origin_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce( + OnFrameEncodeCompleted, + WTF::Passed(CrossThreadBind(on_encoded_video_callback_)), + video_params, std::move(data), nullptr, capture_timestamp, + is_key_frame)); } void H264Encoder::ConfigureEncoderOnEncodingTaskRunner(const gfx::Size& size) { @@ -183,4 +185,4 @@ openh264_encoder_->SetOption(ENCODER_OPTION_DATAFORMAT, &pixel_format); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/h264_encoder.h b/third_party/blink/renderer/modules/mediarecorder/h264_encoder.h similarity index 78% rename from content/renderer/media_recorder/h264_encoder.h rename to third_party/blink/renderer/modules/mediarecorder/h264_encoder.h index 3e20e3f..2ac951a 100644 --- a/content/renderer/media_recorder/h264_encoder.h +++ b/third_party/blink/renderer/modules/mediarecorder/h264_encoder.h
@@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_MEDIA_RECORDER_H264_ENCODER_H_ -#define CONTENT_RENDERER_MEDIA_RECORDER_H264_ENCODER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_H264_ENCODER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_H264_ENCODER_H_ #include "base/single_thread_task_runner.h" -#include "content/public/common/buildflags.h" +#include "third_party/blink/renderer/modules/mediarecorder/buildflags.h" #if !BUILDFLAG(RTC_USE_H264) #error RTC_USE_H264 should be defined. #endif // #if BUILDFLAG(RTC_USE_H264) #include "base/time/time.h" -#include "content/renderer/media_recorder/video_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" #include "third_party/openh264/src/codec/api/svc/codec_api.h" -namespace content { +namespace blink { // Class encapsulating all openh264 interactions for H264 encoding. class H264Encoder final : public VideoTrackRecorder::Encoder { @@ -26,7 +26,7 @@ }; typedef std::unique_ptr<ISVCEncoder, ISVCEncoderDeleter> ScopedISVCEncoderPtr; - static void ShutdownEncoder(std::unique_ptr<base::Thread> encoding_thread, + static void ShutdownEncoder(std::unique_ptr<Thread> encoding_thread, ScopedISVCEncoderPtr encoder); H264Encoder( @@ -55,6 +55,6 @@ DISALLOW_COPY_AND_ASSIGN(H264Encoder); }; -} // namespace content +} // namespace blink -#endif // CONTENT_RENDERER_MEDIA_RECORDER_H264_ENCODER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_H264_ENCODER_H_
diff --git a/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc b/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc index b6aec7ff..934867060 100644 --- a/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder.cc
@@ -173,7 +173,7 @@ return; } DCHECK(stream_->getTracks().size()); - recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler( + recorder_handler_ = MediaRecorderHandler::Create( context->GetTaskRunner(TaskType::kInternalMediaRealTime)); DCHECK(recorder_handler_); @@ -294,9 +294,8 @@ bool MediaRecorder::isTypeSupported(ExecutionContext* context, const String& type) { - std::unique_ptr<WebMediaRecorderHandler> handler = - Platform::Current()->CreateMediaRecorderHandler( - context->GetTaskRunner(TaskType::kInternalMediaRealTime)); + std::unique_ptr<MediaRecorderHandler> handler = MediaRecorderHandler::Create( + context->GetTaskRunner(TaskType::kInternalMediaRealTime)); if (!handler) return false;
diff --git a/third_party/blink/renderer/modules/mediarecorder/media_recorder.h b/third_party/blink/renderer/modules/mediarecorder/media_recorder.h index f1b6d01..f57dc2b 100644 --- a/third_party/blink/renderer/modules/mediarecorder/media_recorder.h +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder.h
@@ -6,11 +6,11 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_MEDIA_RECORDER_H_ #include <memory> -#include "third_party/blink/public/platform/web_media_recorder_handler.h" #include "third_party/blink/public/platform/web_media_recorder_handler_client.h" #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/modules/event_target_modules.h" +#include "third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h" #include "third_party/blink/renderer/modules/mediarecorder/media_recorder_options.h" #include "third_party/blink/renderer/modules/mediastream/media_stream.h" #include "third_party/blink/renderer/modules/modules_export.h" @@ -104,7 +104,7 @@ std::unique_ptr<BlobData> blob_data_; - std::unique_ptr<WebMediaRecorderHandler> recorder_handler_; + std::unique_ptr<MediaRecorderHandler> recorder_handler_; HeapVector<Member<Event>> scheduled_events_; };
diff --git a/content/renderer/media_recorder/media_recorder_handler.cc b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc similarity index 74% rename from content/renderer/media_recorder/media_recorder_handler.cc rename to third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc index 97715db..d913d04 100644 --- a/content/renderer/media_recorder/media_recorder_handler.cc +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.cc
@@ -2,16 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/media_recorder_handler.h" +#include "third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h" #include <utility> -#include "base/bind.h" -#include "base/location.h" #include "base/logging.h" -#include "base/stl_util.h" -#include "base/strings/string_tokenizer.h" -#include "base/strings/string_util.h" #include "base/system/sys_info.h" #include "media/base/audio_bus.h" #include "media/base/audio_codecs.h" @@ -28,14 +23,14 @@ #include "third_party/blink/public/platform/modules/mediastream/webrtc_uma_histograms.h" #include "third_party/blink/public/platform/web_media_recorder_handler_client.h" #include "third_party/blink/public/platform/web_media_stream_source.h" -#include "third_party/blink/public/platform/web_string.h" -#include "third_party/blink/public/web/modules/mediarecorder/audio_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/buildflags.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" using base::TimeDelta; using base::TimeTicks; -using base::ToLowerASCII; -namespace content { +namespace blink { namespace { @@ -67,14 +62,13 @@ return media::kUnknownVideoCodec; } -media::AudioCodec CodecIdToMediaAudioCodec( - blink::AudioTrackRecorder::CodecId id) { +media::AudioCodec CodecIdToMediaAudioCodec(AudioTrackRecorder::CodecId id) { switch (id) { - case blink::AudioTrackRecorder::CodecId::PCM: + case AudioTrackRecorder::CodecId::PCM: return media::kCodecPCM; - case blink::AudioTrackRecorder::CodecId::OPUS: + case AudioTrackRecorder::CodecId::OPUS: return media::kCodecOpus; - case blink::AudioTrackRecorder::CodecId::LAST: + case AudioTrackRecorder::CodecId::LAST: return media::kUnknownAudioCodec; } NOTREACHED() << "Unsupported audio codec"; @@ -83,49 +77,52 @@ // Extracts the first recognised CodecId of |codecs| or CodecId::LAST if none // of them is known. -VideoTrackRecorder::CodecId VideoStringToCodecId( - const blink::WebString& codecs) { - const std::string& codecs_str = ToLowerASCII(codecs.Utf8()); +VideoTrackRecorder::CodecId VideoStringToCodecId(const String& codecs) { + String codecs_str = codecs.LowerASCII(); - if (codecs_str.find("vp8") != std::string::npos) + if (codecs_str.Find("vp8") != kNotFound) return VideoTrackRecorder::CodecId::VP8; - if (codecs_str.find("vp9") != std::string::npos) + if (codecs_str.Find("vp9") != kNotFound) return VideoTrackRecorder::CodecId::VP9; #if BUILDFLAG(RTC_USE_H264) - if (codecs_str.find("h264") != std::string::npos || - codecs_str.find("avc1") != std::string::npos) + if (codecs_str.Find("h264") != kNotFound || + codecs_str.Find("avc1") != kNotFound) return VideoTrackRecorder::CodecId::H264; #endif return VideoTrackRecorder::CodecId::LAST; } -blink::AudioTrackRecorder::CodecId AudioStringToCodecId( - const blink::WebString& codecs) { - const std::string& codecs_str = ToLowerASCII(codecs.Utf8()); +AudioTrackRecorder::CodecId AudioStringToCodecId(const String& codecs) { + String codecs_str = codecs.LowerASCII(); - if (codecs_str.find("opus") != std::string::npos) - return blink::AudioTrackRecorder::CodecId::OPUS; - if (codecs_str.find("pcm") != std::string::npos) - return blink::AudioTrackRecorder::CodecId::PCM; + if (codecs_str.Find("opus") != kNotFound) + return AudioTrackRecorder::CodecId::OPUS; + if (codecs_str.Find("pcm") != kNotFound) + return AudioTrackRecorder::CodecId::PCM; - return blink::AudioTrackRecorder::CodecId::LAST; + return AudioTrackRecorder::CodecId::LAST; } } // anonymous namespace +std::unique_ptr<MediaRecorderHandler> MediaRecorderHandler::Create( + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + return std::make_unique<MediaRecorderHandler>(std::move(task_runner)); +} + MediaRecorderHandler::MediaRecorderHandler( scoped_refptr<base::SingleThreadTaskRunner> task_runner) : video_bits_per_second_(0), audio_bits_per_second_(0), video_codec_id_(VideoTrackRecorder::CodecId::LAST), - audio_codec_id_(blink::AudioTrackRecorder::CodecId::LAST), + audio_codec_id_(AudioTrackRecorder::CodecId::LAST), recording_(false), client_(nullptr), task_runner_(std::move(task_runner)), weak_factory_(this) {} MediaRecorderHandler::~MediaRecorderHandler() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); // Send a |last_in_slice| to our |client_|. if (client_) { client_->WriteData( @@ -134,20 +131,18 @@ } } -bool MediaRecorderHandler::CanSupportMimeType( - const blink::WebString& web_type, - const blink::WebString& web_codecs) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); - // An empty |web_type| means MediaRecorderHandler can choose its preferred - // codecs. - if (web_type.IsEmpty()) +bool MediaRecorderHandler::CanSupportMimeType(const String& type, + const String& web_codecs) { + DCHECK(IsMainThread()); + // An empty |type| means MediaRecorderHandler can choose its preferred codecs. + if (type.IsEmpty()) return true; - const std::string type(web_type.Utf8()); - const bool video = base::EqualsCaseInsensitiveASCII(type, "video/webm") || - base::EqualsCaseInsensitiveASCII(type, "video/x-matroska"); + const bool video = + !CodePointCompareIgnoringASCIICase(type, "video/webm") || + !CodePointCompareIgnoringASCIICase(type, "video/x-matroska"); const bool audio = - video ? false : (base::EqualsCaseInsensitiveASCII(type, "audio/webm")); + video ? false : (!CodePointCompareIgnoringASCIICase(type, "audio/webm")); if (!video && !audio) return false; @@ -176,7 +171,8 @@ for (const auto& codec : codecs_list) { auto* const* found = std::find_if( &codecs[0], &codecs[codecs_count], [&codec](const char* name) { - return base::EqualsCaseInsensitiveASCII(codec, name); + return !CodePointCompareIgnoringASCIICase( + String::FromUTF8(codec.c_str()), name); }); if (found == &codecs[codecs_count]) return false; @@ -184,17 +180,16 @@ return true; } -bool MediaRecorderHandler::Initialize( - blink::WebMediaRecorderHandlerClient* client, - const blink::WebMediaStream& media_stream, - const blink::WebString& type, - const blink::WebString& codecs, - int32_t audio_bits_per_second, - int32_t video_bits_per_second) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); +bool MediaRecorderHandler::Initialize(WebMediaRecorderHandlerClient* client, + const WebMediaStream& media_stream, + const String& type, + const String& codecs, + int32_t audio_bits_per_second, + int32_t video_bits_per_second) { + DCHECK(IsMainThread()); // Save histogram data so we can see how much MediaStream Recorder is used. // The histogram counts the number of calls to the JS API. - UpdateWebRTCMethodCount(blink::WebRTCAPIName::kMediaStreamRecorder); + UpdateWebRTCMethodCount(WebRTCAPIName::kMediaStreamRecorder); if (!CanSupportMimeType(type, codecs)) { DLOG(ERROR) << "Unsupported " << type.Utf8() << ";codecs=" << codecs.Utf8(); @@ -212,12 +207,12 @@ << static_cast<int>(video_codec_id_); // Do the same for the audio codec(s). - const blink::AudioTrackRecorder::CodecId audio_codec_id = + const AudioTrackRecorder::CodecId audio_codec_id = AudioStringToCodecId(codecs); - audio_codec_id_ = (audio_codec_id != blink::AudioTrackRecorder::CodecId::LAST) + audio_codec_id_ = (audio_codec_id != AudioTrackRecorder::CodecId::LAST) ? audio_codec_id - : blink::AudioTrackRecorder::GetPreferredCodecId(); - DVLOG_IF(1, audio_codec_id == blink::AudioTrackRecorder::CodecId::LAST) + : AudioTrackRecorder::GetPreferredCodecId(); + DVLOG_IF(1, audio_codec_id == AudioTrackRecorder::CodecId::LAST) << "Falling back to preferred audio codec id " << static_cast<int>(audio_codec_id_); @@ -231,7 +226,7 @@ } bool MediaRecorderHandler::Start(int timeslice) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); DCHECK(!recording_); DCHECK(!media_stream_.IsNull()); DCHECK(timeslice_.is_zero()); @@ -249,14 +244,12 @@ } const bool use_video_tracks = - !video_tracks_.empty() && - video_tracks_[0].Source().GetReadyState() != - blink::WebMediaStreamSource::kReadyStateEnded; - const bool use_audio_tracks = - !audio_tracks_.empty() && - blink::MediaStreamAudioTrack::From(audio_tracks_[0]) && - audio_tracks_[0].Source().GetReadyState() != - blink::WebMediaStreamSource::kReadyStateEnded; + !video_tracks_.empty() && video_tracks_[0].Source().GetReadyState() != + WebMediaStreamSource::kReadyStateEnded; + const bool use_audio_tracks = !audio_tracks_.empty() && + MediaStreamAudioTrack::From(audio_tracks_[0]) && + audio_tracks_[0].Source().GetReadyState() != + WebMediaStreamSource::kReadyStateEnded; if (!use_video_tracks && !use_audio_tracks) { LOG(WARNING) << __func__ << ": no tracks to be recorded."; @@ -267,8 +260,8 @@ new media::WebmMuxer(CodecIdToMediaVideoCodec(video_codec_id_), CodecIdToMediaAudioCodec(audio_codec_id_), use_video_tracks, use_audio_tracks, - base::Bind(&MediaRecorderHandler::WriteData, - weak_factory_.GetWeakPtr()))); + WTF::BindRepeating(&MediaRecorderHandler::WriteData, + weak_factory_.GetWeakPtr()))); if (use_video_tracks) { // TODO(mcasas): The muxer API supports only one video track. Extend it to @@ -276,12 +269,12 @@ LOG_IF(WARNING, video_tracks_.size() > 1u) << "Recording multiple video tracks is not implemented. " << "Only recording first video track."; - const blink::WebMediaStreamTrack& video_track = video_tracks_[0]; + const WebMediaStreamTrack& video_track = video_tracks_[0]; if (video_track.IsNull()) return false; const VideoTrackRecorder::OnEncodedVideoCB on_encoded_video_cb = - media::BindToCurrentLoop(base::Bind( + media::BindToCurrentLoop(WTF::BindRepeating( &MediaRecorderHandler::OnEncodedVideo, weak_factory_.GetWeakPtr())); video_recorders_.emplace_back(new VideoTrackRecorder( @@ -295,15 +288,15 @@ LOG_IF(WARNING, audio_tracks_.size() > 1u) << "Recording multiple audio" << " tracks is not implemented. Only recording first audio track."; - const blink::WebMediaStreamTrack& audio_track = audio_tracks_[0]; + const WebMediaStreamTrack& audio_track = audio_tracks_[0]; if (audio_track.IsNull()) return false; - const blink::AudioTrackRecorder::OnEncodedAudioCB on_encoded_audio_cb = + const AudioTrackRecorder::OnEncodedAudioCB on_encoded_audio_cb = media::BindToCurrentLoop(base::Bind( &MediaRecorderHandler::OnEncodedAudio, weak_factory_.GetWeakPtr())); - audio_recorders_.emplace_back(new blink::AudioTrackRecorder( + audio_recorders_.emplace_back(new AudioTrackRecorder( audio_codec_id_, audio_track, std::move(on_encoded_audio_cb), audio_bits_per_second_)); } @@ -313,7 +306,7 @@ } void MediaRecorderHandler::Stop() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); // Don't check |recording_| since we can go directly from pause() to stop(). weak_factory_.InvalidateWeakPtrs(); @@ -325,7 +318,7 @@ } void MediaRecorderHandler::Pause() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); DCHECK(recording_); recording_ = false; for (const auto& video_recorder : video_recorders_) @@ -337,7 +330,7 @@ } void MediaRecorderHandler::Resume() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); DCHECK(!recording_); recording_ = true; for (const auto& video_recorder : video_recorders_) @@ -349,19 +342,19 @@ } void MediaRecorderHandler::EncodingInfo( - const blink::WebMediaConfiguration& configuration, + const WebMediaConfiguration& configuration, OnMediaCapabilitiesEncodingInfoCallback callback) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); DCHECK(configuration.video_configuration || configuration.audio_configuration); - std::unique_ptr<blink::WebMediaCapabilitiesInfo> info( - new blink::WebMediaCapabilitiesInfo()); + std::unique_ptr<WebMediaCapabilitiesInfo> info( + new WebMediaCapabilitiesInfo()); // TODO(mcasas): Support the case when both video and audio configurations are // specified: https://crbug.com/709181. - blink::WebString mime_type; - blink::WebString codec; + String mime_type; + String codec; if (configuration.video_configuration) { mime_type = configuration.video_configuration->mime_type; codec = configuration.video_configuration->codec; @@ -402,27 +395,27 @@ std::move(callback).Run(std::move(info)); } -blink::WebString MediaRecorderHandler::ActualMimeType() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); +String MediaRecorderHandler::ActualMimeType() { + DCHECK(IsMainThread()); DCHECK(client_) << __func__ << " should be called after Initialize()"; const bool has_video_tracks = !media_stream_.VideoTracks().empty(); const bool has_audio_tracks = !media_stream_.AudioTracks().empty(); if (!has_video_tracks && !has_audio_tracks) - return blink::WebString(); + return String(); - std::string mime_type; + StringBuilder mime_type; if (!has_video_tracks && has_audio_tracks) { - mime_type.append("audio/webm;codecs="); + mime_type.Append("audio/webm;codecs="); } else { switch (video_codec_id_) { case VideoTrackRecorder::CodecId::VP8: case VideoTrackRecorder::CodecId::VP9: - mime_type.append("video/webm;codecs="); + mime_type.Append("video/webm;codecs="); break; #if BUILDFLAG(RTC_USE_H264) case VideoTrackRecorder::CodecId::H264: - mime_type.append("video/x-matroska;codecs="); + mime_type.Append("video/x-matroska;codecs="); break; #endif case VideoTrackRecorder::CodecId::LAST: @@ -433,39 +426,39 @@ if (has_video_tracks) { switch (video_codec_id_) { case VideoTrackRecorder::CodecId::VP8: - mime_type.append("vp8"); + mime_type.Append("vp8"); break; case VideoTrackRecorder::CodecId::VP9: - mime_type.append("vp9"); + mime_type.Append("vp9"); break; #if BUILDFLAG(RTC_USE_H264) case VideoTrackRecorder::CodecId::H264: - mime_type.append("avc1"); + mime_type.Append("avc1"); break; #endif case VideoTrackRecorder::CodecId::LAST: - DCHECK_NE(audio_codec_id_, blink::AudioTrackRecorder::CodecId::LAST); + DCHECK_NE(audio_codec_id_, AudioTrackRecorder::CodecId::LAST); } } if (has_video_tracks && has_audio_tracks) { if (video_codec_id_ != VideoTrackRecorder::CodecId::LAST && - audio_codec_id_ != blink::AudioTrackRecorder::CodecId::LAST) { - mime_type.append(","); + audio_codec_id_ != AudioTrackRecorder::CodecId::LAST) { + mime_type.Append(","); } } if (has_audio_tracks) { switch (audio_codec_id_) { - case blink::AudioTrackRecorder::CodecId::OPUS: - mime_type.append("opus"); + case AudioTrackRecorder::CodecId::OPUS: + mime_type.Append("opus"); break; - case blink::AudioTrackRecorder::CodecId::PCM: - mime_type.append("pcm"); + case AudioTrackRecorder::CodecId::PCM: + mime_type.Append("pcm"); break; - case blink::AudioTrackRecorder::CodecId::LAST: + case AudioTrackRecorder::CodecId::LAST: DCHECK_NE(video_codec_id_, VideoTrackRecorder::CodecId::LAST); } } - return blink::WebString::FromUTF8(mime_type); + return mime_type.ToString(); } void MediaRecorderHandler::OnEncodedVideo( @@ -474,7 +467,7 @@ std::unique_ptr<std::string> encoded_alpha, TimeTicks timestamp, bool is_key_frame) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); if (UpdateTracksAndCheckIfChanged()) { client_->OnError("Amount of tracks in MediaStream has changed."); @@ -494,7 +487,7 @@ const media::AudioParameters& params, std::unique_ptr<std::string> encoded_data, base::TimeTicks timestamp) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); if (UpdateTracksAndCheckIfChanged()) { client_->OnError("Amount of tracks in MediaStream has changed."); @@ -510,7 +503,7 @@ } void MediaRecorderHandler::WriteData(base::StringPiece data) { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); const TimeTicks now = TimeTicks::Now(); // Non-buffered mode does not need to check timestamps. if (timeslice_.is_zero()) { @@ -528,9 +521,9 @@ } bool MediaRecorderHandler::UpdateTracksAndCheckIfChanged() { - DCHECK(main_render_thread_checker_.CalledOnValidThread()); + DCHECK(IsMainThread()); - blink::WebVector<blink::WebMediaStreamTrack> video_tracks, audio_tracks; + WebVector<WebMediaStreamTrack> video_tracks, audio_tracks; video_tracks = media_stream_.VideoTracks(); audio_tracks = media_stream_.AudioTracks(); @@ -582,4 +575,4 @@ recorder->OnSetFormat(params); } -} // namespace content +} // namespace blink
diff --git a/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h new file mode 100644 index 0000000..6ed56c8 --- /dev/null +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h
@@ -0,0 +1,146 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_MEDIA_RECORDER_HANDLER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_MEDIA_RECORDER_HANDLER_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" +#include "base/strings/string_piece.h" +#include "base/threading/thread_checker.h" +#include "third_party/blink/public/platform/web_media_stream.h" +#include "third_party/blink/public/platform/web_vector.h" +#include "third_party/blink/renderer/modules/mediarecorder/audio_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" + +namespace media { +class AudioBus; +class AudioParameters; +class VideoFrame; +class WebmMuxer; +} // namespace media + +namespace blink { + +struct WebMediaCapabilitiesInfo; +struct WebMediaConfiguration; +class WebMediaRecorderHandlerClient; + +// MediaRecorderHandler orchestrates the creation, lifetime management and +// mapping between: +// - MediaStreamTrack(s) providing data, +// - {Audio,Video}TrackRecorders encoding that data, +// - a WebmMuxer class multiplexing encoded data into a WebM container, and +// - a single recorder client receiving this contained data. +// All methods are called on the same thread as construction and destruction, +// i.e. the Main Render thread. (Note that a BindToCurrentLoop is used to +// guarantee this, since VideoTrackRecorder sends back frames on IO thread.) +class MODULES_EXPORT MediaRecorderHandler { + public: + static std::unique_ptr<MediaRecorderHandler> Create( + scoped_refptr<base::SingleThreadTaskRunner> task_runner); + + explicit MediaRecorderHandler( + scoped_refptr<base::SingleThreadTaskRunner> task_runner); + ~MediaRecorderHandler(); + + // MediaRecorder API isTypeSupported(), which boils down to + // CanSupportMimeType() [1] "If true is returned from this method, it only + // indicates that the MediaRecorder implementation is capable of recording + // Blob objects for the specified MIME type. Recording may still fail if + // sufficient resources are not available to support the concrete media + // encoding." + // [1] https://w3c.github.io/mediacapture-record/MediaRecorder.html#methods + bool CanSupportMimeType(const String& type, const String& web_codecs); + bool Initialize(WebMediaRecorderHandlerClient* client, + const WebMediaStream& media_stream, + const String& type, + const String& codecs, + int32_t audio_bits_per_second, + int32_t video_bits_per_second); + bool Start(int timeslice); + void Stop(); + void Pause(); + void Resume(); + + // Implements WICG Media Capabilities encodingInfo() call for local encoding. + // https://wicg.github.io/media-capabilities/#media-capabilities-interface + using OnMediaCapabilitiesEncodingInfoCallback = + base::OnceCallback<void(std::unique_ptr<WebMediaCapabilitiesInfo>)>; + void EncodingInfo(const WebMediaConfiguration& configuration, + OnMediaCapabilitiesEncodingInfoCallback cb); + String ActualMimeType(); + + private: + friend class MediaRecorderHandlerTest; + + // Called to indicate there is encoded video data available. |encoded_alpha| + // represents the encode output of alpha channel when available, can be + // nullptr otherwise. + // TODO(crbug.com/960665): Replace std::string with WTF::String + void OnEncodedVideo(const media::WebmMuxer::VideoParameters& params, + std::unique_ptr<std::string> encoded_data, + std::unique_ptr<std::string> encoded_alpha, + base::TimeTicks timestamp, + bool is_key_frame); + // TODO(crbug.com/960665): Replace std::string with WTF::String + void OnEncodedAudio(const media::AudioParameters& params, + std::unique_ptr<std::string> encoded_data, + base::TimeTicks timestamp); + void WriteData(base::StringPiece data); + + // Updates |video_tracks_|,|audio_tracks_| and returns true if any changed. + bool UpdateTracksAndCheckIfChanged(); + + void OnVideoFrameForTesting(scoped_refptr<media::VideoFrame> frame, + const base::TimeTicks& timestamp); + void OnAudioBusForTesting(const media::AudioBus& audio_bus, + const base::TimeTicks& timestamp); + void SetAudioFormatForTesting(const media::AudioParameters& params); + + // Sanitized video and audio bitrate settings passed on initialize(). + int32_t video_bits_per_second_; + int32_t audio_bits_per_second_; + + // Video Codec, VP8 is used by default. + VideoTrackRecorder::CodecId video_codec_id_; + + // Audio Codec, OPUS is used by default. + AudioTrackRecorder::CodecId audio_codec_id_; + + // |client_| has no notion of time, thus may configure us via start(timeslice) + // to notify it after a certain |timeslice_| has passed. We use a moving + // |slice_origin_timestamp_| to track those time chunks. + base::TimeDelta timeslice_; + base::TimeTicks slice_origin_timestamp_; + + bool recording_; + WebMediaStream media_stream_; // The MediaStream being recorded. + WebVector<WebMediaStreamTrack> video_tracks_; + WebVector<WebMediaStreamTrack> audio_tracks_; + + // |client_| is a weak pointer, and is valid for the lifetime of this object. + WebMediaRecorderHandlerClient* client_; + + Vector<std::unique_ptr<VideoTrackRecorder>> video_recorders_; + Vector<std::unique_ptr<AudioTrackRecorder>> audio_recorders_; + + // Worker class doing the actual Webm Muxing work. + std::unique_ptr<media::WebmMuxer> webm_muxer_; + + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + + base::WeakPtrFactory<MediaRecorderHandler> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(MediaRecorderHandler); +}; + +} // namespace blink +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_MEDIA_RECORDER_HANDLER_H_
diff --git a/content/renderer/media_recorder/media_recorder_handler_unittest.cc b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler_unittest.cc similarity index 78% rename from content/renderer/media_recorder/media_recorder_handler_unittest.cc rename to third_party/blink/renderer/modules/mediarecorder/media_recorder_handler_unittest.cc index ee44ed5..80a3061 100644 --- a/content/renderer/media_recorder/media_recorder_handler_unittest.cc +++ b/third_party/blink/renderer/modules/mediarecorder/media_recorder_handler_unittest.cc
@@ -8,11 +8,7 @@ #include "base/macros.h" #include "base/run_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_task_environment.h" #include "base/time/time.h" -#include "content/child/child_process.h" -#include "content/renderer/media_recorder/media_recorder_handler.h" #include "media/audio/simple_sources.h" #include "media/base/audio_bus.h" #include "media/base/video_frame.h" @@ -20,24 +16,26 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_media_recorder_handler_client.h" -#include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_registry.h" -#include "third_party/blink/public/web/web_heap.h" +#include "third_party/blink/renderer/modules/mediarecorder/media_recorder_handler.h" +#include "third_party/blink/renderer/platform/heap/thread_state.h" +#include "third_party/blink/renderer/platform/testing/io_task_runner_testing_platform_support.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" using ::testing::_; using ::testing::AtLeast; -using ::testing::InSequence; using ::testing::Gt; +using ::testing::InSequence; using ::testing::Lt; using ::testing::Mock; using ::testing::TestWithParam; using ::testing::ValuesIn; -using blink::WebString; +namespace blink { -namespace content { - -ACTION_P(RunClosure, closure) { +// Using RunClosure5 instead of RunClosure to avoid symbol collisions in jumbo +// builds. +ACTION_P(RunClosure5, closure) { closure.Run(); } @@ -76,9 +74,7 @@ public blink::WebMediaRecorderHandlerClient { public: MediaRecorderHandlerTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI), - media_recorder_handler_(new MediaRecorderHandler( + : media_recorder_handler_(new MediaRecorderHandler( blink::scheduler::GetSingleThreadTaskRunnerForTesting())), audio_source_(kTestAudioChannels, 440 /* freq */, @@ -90,7 +86,7 @@ ~MediaRecorderHandlerTest() { registry_.reset(); - blink::WebHeap::CollectAllGarbageForTesting(); + ThreadState::Current()->CollectAllGarbageForTesting(); } MOCK_METHOD4(WriteData, void(const char*, size_t, bool, double)); @@ -98,10 +94,10 @@ bool recording() const { return media_recorder_handler_->recording_; } bool hasVideoRecorders() const { - return !media_recorder_handler_->video_recorders_.empty(); + return !media_recorder_handler_->video_recorders_.IsEmpty(); } bool hasAudioRecorders() const { - return !media_recorder_handler_->audio_recorders_.empty(); + return !media_recorder_handler_->audio_recorders_.IsEmpty(); } void OnVideoFrameForTesting(scoped_refptr<media::VideoFrame> frame) { @@ -137,10 +133,8 @@ return bus; } - // A ChildProcess and a MessageLoopForUI are both needed to fool the Tracks - // and Sources in |registry_| into believing they are on the right threads. - const base::test::ScopedTaskEnvironment scoped_task_environment_; - const ChildProcess child_process_; + ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform_; + blink::MockMediaStreamRegistry registry_; // The Class under test. Needs to be scoped_ptr to force its destruction. @@ -156,26 +150,26 @@ // Checks that canSupportMimeType() works as expected, by sending supported // combinations and unsupported ones. TEST_F(MediaRecorderHandlerTest, CanSupportMimeType) { - const WebString unsupported_mime_type(WebString::FromASCII("video/mpeg")); + const String unsupported_mime_type("video/mpeg"); EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType( - unsupported_mime_type, WebString())); + unsupported_mime_type, String())); - const WebString mime_type_video(WebString::FromASCII("video/webm")); - EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(mime_type_video, - WebString())); - const WebString mime_type_video_uppercase(WebString::FromASCII("video/WEBM")); + const String mime_type_video("video/webm"); + EXPECT_TRUE( + media_recorder_handler_->CanSupportMimeType(mime_type_video, String())); + const String mime_type_video_uppercase("video/WEBM"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( - mime_type_video_uppercase, WebString())); - const WebString example_good_codecs_1(WebString::FromASCII("vp8")); + mime_type_video_uppercase, String())); + const String example_good_codecs_1("vp8"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_video, example_good_codecs_1)); - const WebString example_good_codecs_2(WebString::FromASCII("vp9,opus")); + const String example_good_codecs_2("vp9,opus"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_video, example_good_codecs_2)); - const WebString example_good_codecs_3(WebString::FromASCII("VP9,opus")); + const String example_good_codecs_3("VP9,opus"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_video, example_good_codecs_3)); - const WebString example_good_codecs_4(WebString::FromASCII("H264")); + const String example_good_codecs_4("H264"); #if BUILDFLAG(RTC_USE_H264) EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_video, example_good_codecs_4)); @@ -184,24 +178,24 @@ mime_type_video, example_good_codecs_4)); #endif - const WebString example_unsupported_codecs_1(WebString::FromASCII("daala")); + const String example_unsupported_codecs_1("daala"); EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType( mime_type_video, example_unsupported_codecs_1)); - const WebString mime_type_audio(WebString::FromASCII("audio/webm")); - EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType(mime_type_audio, - WebString())); - const WebString example_good_codecs_5(WebString::FromASCII("opus")); + const String mime_type_audio("audio/webm"); + EXPECT_TRUE( + media_recorder_handler_->CanSupportMimeType(mime_type_audio, String())); + const String example_good_codecs_5("opus"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_audio, example_good_codecs_5)); - const WebString example_good_codecs_6(WebString::FromASCII("OpUs")); + const String example_good_codecs_6("OpUs"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_audio, example_good_codecs_6)); - const WebString example_good_codecs_7(WebString::FromASCII("pcm")); + const String example_good_codecs_7("pcm"); EXPECT_TRUE(media_recorder_handler_->CanSupportMimeType( mime_type_audio, example_good_codecs_7)); - const WebString example_unsupported_codecs_2(WebString::FromASCII("vorbis")); + const String example_unsupported_codecs_2("vorbis"); EXPECT_FALSE(media_recorder_handler_->CanSupportMimeType( mime_type_audio, example_unsupported_codecs_2)); } @@ -209,8 +203,8 @@ // Checks that the initialization-destruction sequence works fine. TEST_P(MediaRecorderHandlerTest, InitializeStartStop) { AddTracks(); - const WebString mime_type(WebString::FromASCII(GetParam().mime_type)); - const WebString codecs(WebString::FromASCII(GetParam().codecs)); + const String mime_type(GetParam().mime_type); + const String codecs(GetParam().codecs); EXPECT_TRUE(media_recorder_handler_->Initialize(this, registry_.test_stream(), mime_type, codecs, 0, 0)); EXPECT_FALSE(recording()); @@ -242,8 +236,8 @@ AddTracks(); - const WebString mime_type(WebString::FromASCII(GetParam().mime_type)); - const WebString codecs(WebString::FromASCII(GetParam().codecs)); + const String mime_type(GetParam().mime_type); + const String codecs(GetParam().codecs); EXPECT_TRUE(media_recorder_handler_->Initialize(this, registry_.test_stream(), mime_type, codecs, 0, 0)); EXPECT_TRUE(media_recorder_handler_->Start(0)); @@ -262,7 +256,7 @@ .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); OnVideoFrameForTesting(video_frame); run_loop.Run(); @@ -279,7 +273,7 @@ .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); OnVideoFrameForTesting(video_frame); run_loop.Run(); @@ -299,13 +293,13 @@ .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(quit_closure)); + .WillOnce(RunClosure5(quit_closure)); if (GetParam().encoder_supports_alpha) { EXPECT_CALL(*this, WriteData(_, Lt(kEncodedSizeThreshold), _, _)) .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); } OnVideoFrameForTesting(alpha_frame); @@ -332,8 +326,8 @@ AddTracks(); - const WebString mime_type(WebString::FromASCII(GetParam().mime_type)); - const WebString codecs(WebString::FromASCII(GetParam().codecs)); + const String mime_type(GetParam().mime_type); + const String codecs(GetParam().codecs); EXPECT_TRUE(media_recorder_handler_->Initialize(this, registry_.test_stream(), mime_type, codecs, 0, 0)); EXPECT_TRUE(media_recorder_handler_->Start(0)); @@ -358,7 +352,7 @@ .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i) OnAudioBusForTesting(*audio_bus1); @@ -375,7 +369,7 @@ .Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); for (int i = 0; i < kRatioOpusToTestAudioBuffers; ++i) OnAudioBusForTesting(*audio_bus2); @@ -397,8 +391,8 @@ AddTracks(); - const WebString mime_type(WebString::FromASCII(GetParam().mime_type)); - const WebString codecs(WebString::FromASCII(GetParam().codecs)); + const String mime_type(GetParam().mime_type); + const String codecs(GetParam().codecs); EXPECT_TRUE(media_recorder_handler_->Initialize(this, registry_.test_stream(), mime_type, codecs, 0, 0)); EXPECT_TRUE(media_recorder_handler_->Start(0)); @@ -414,7 +408,7 @@ EXPECT_CALL(*this, WriteData(_, _, _, _)).Times(AtLeast(1)); EXPECT_CALL(*this, WriteData(_, Gt(kEncodedSizeThreshold), _, _)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); OnVideoFrameForTesting(video_frame); run_loop.Run(); @@ -428,7 +422,7 @@ EXPECT_CALL(*this, WriteData(_, _, _, _)).Times(0); EXPECT_CALL(*this, OnError(_)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure5(std::move(quit_closure))); OnVideoFrameForTesting(video_frame); run_loop.Run(); @@ -442,25 +436,27 @@ // Checks the ActualMimeType() versus the expected. TEST_P(MediaRecorderHandlerTest, ActualMimeType) { AddTracks(); - const WebString mime_type(WebString::FromASCII(GetParam().mime_type)); - const WebString codecs(WebString::FromASCII(GetParam().codecs)); + const String mime_type(GetParam().mime_type); + const String codecs(GetParam().codecs); EXPECT_TRUE(media_recorder_handler_->Initialize(this, registry_.test_stream(), mime_type, codecs, 0, 0)); - std::string actual_mime_type(GetParam().mime_type); - actual_mime_type.append(";codecs="); + StringBuilder actual_mime_type; + actual_mime_type.Append(GetParam().mime_type); + actual_mime_type.Append(";codecs="); if (strlen(GetParam().codecs) != 0u) - actual_mime_type.append(GetParam().codecs); + actual_mime_type.Append(GetParam().codecs); else if (GetParam().has_video) - actual_mime_type.append("vp8"); + actual_mime_type.Append("vp8"); else if (GetParam().has_audio) - actual_mime_type.append("opus"); + actual_mime_type.Append("opus"); - EXPECT_EQ(media_recorder_handler_->ActualMimeType().Utf8(), actual_mime_type); + EXPECT_EQ(media_recorder_handler_->ActualMimeType(), + actual_mime_type.ToString()); // Expect a last call on destruction, with size 0 and |lastInSlice| true. EXPECT_CALL(*this, WriteData(nullptr, 0, true, _)).Times(1); media_recorder_handler_.reset(); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/vea_encoder.cc b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc similarity index 86% rename from content/renderer/media_recorder/vea_encoder.cc rename to third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc index 18514ca..697d21b 100644 --- a/content/renderer/media_recorder/vea_encoder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc
@@ -2,25 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/vea_encoder.h" +#include "third_party/blink/renderer/modules/mediarecorder/vea_encoder.h" #include <string> -#include "base/bind.h" -#include "base/containers/queue.h" #include "base/metrics/histogram_macros.h" -#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h" -#include "content/renderer/render_thread_impl.h" #include "media/base/bind_to_current_loop.h" #include "media/base/video_frame.h" +#include "media/video/gpu_video_accelerator_factories.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/libyuv/include/libyuv.h" #include "ui/gfx/geometry/size.h" using media::VideoFrame; -using video_track_recorder::kVEAEncoderMinResolutionWidth; using video_track_recorder::kVEAEncoderMinResolutionHeight; +using video_track_recorder::kVEAEncoderMinResolutionWidth; -namespace content { +namespace blink { namespace { @@ -42,13 +42,13 @@ media::VideoCodecProfile codec, const gfx::Size& size, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - auto encoder = base::WrapRefCounted( + auto encoder = base::AdoptRef( new VEAEncoder(on_encoded_video_callback, on_error_callback, bits_per_second, codec, size, std::move(task_runner))); - encoder->encoding_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&VEAEncoder::ConfigureEncoderOnEncodingTaskRunner, encoder, - size)); + PostCrossThreadTask( + *encoder->encoding_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&VEAEncoder::ConfigureEncoderOnEncodingTaskRunner, + encoder, size)); return encoder; } @@ -63,8 +63,8 @@ bits_per_second > 0 ? bits_per_second : size.GetArea() * kVEADefaultBitratePerPixel, std::move(task_runner), - RenderThreadImpl::current()->GetGpuFactories()->GetTaskRunner()), - gpu_factories_(RenderThreadImpl::current()->GetGpuFactories()), + Platform::Current()->GetGpuFactories()->GetTaskRunner()), + gpu_factories_(Platform::Current()->GetGpuFactories()), codec_(codec), error_notified_(false), num_frames_after_keyframe_(0), @@ -84,16 +84,18 @@ base::WaitableEvent release_waiter( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); - // base::Unretained is safe because the class will be alive until + // CrossThreadUnretained is safe because the class will be alive until // |release_waiter| is signaled. // TODO(emircan): Consider refactoring media::VideoEncodeAccelerator to avoid // using naked pointers and using DeleteSoon() here, see // http://crbug.com/701627. // It is currently unsafe because |video_encoder_| might be in use on another // function on |encoding_task_runner_|, see http://crbug.com/701030. - encoding_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&VEAEncoder::DestroyOnEncodingTaskRunner, - base::Unretained(this), &release_waiter)); + PostCrossThreadTask( + *encoding_task_runner_, FROM_HERE, + CrossThreadBindOnce(&VEAEncoder::DestroyOnEncodingTaskRunner, + CrossThreadUnretained(this), + CrossThreadUnretained(&release_waiter))); release_waiter.Wait(); } @@ -115,7 +117,7 @@ } for (size_t i = 0; i < output_buffers_.size(); ++i) - UseOutputBitstreamBufferId(i); + UseOutputBitstreamBufferId(static_cast<int32_t>(i)); } void VEAEncoder::BitstreamBufferReady( @@ -139,11 +141,15 @@ const auto front_frame = frames_in_encode_.front(); frames_in_encode_.pop(); - origin_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(OnFrameEncodeCompleted, on_encoded_video_callback_, - front_frame.first, std::move(data), nullptr, - front_frame.second, metadata.key_frame)); + + PostCrossThreadTask( + *origin_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce( + OnFrameEncodeCompleted, + WTF::Passed(CrossThreadBind(on_encoded_video_callback_)), + front_frame.first, std::move(data), nullptr, front_frame.second, + metadata.key_frame)); + UseOutputBitstreamBufferId(bitstream_buffer_id); } @@ -189,7 +195,7 @@ } // Drop frames if RequireBitstreamBuffers() hasn't been called. - if (output_buffers_.empty() || vea_requested_input_coded_size_.IsEmpty()) { + if (output_buffers_.IsEmpty() || vea_requested_input_coded_size_.IsEmpty()) { // TODO(emircan): Investigate if resetting encoder would help. DVLOG(3) << "Might drop frame."; last_frame_.reset(new std::pair<scoped_refptr<VideoFrame>, base::TimeTicks>( @@ -241,8 +247,8 @@ return; } video_frame->AddDestructionObserver(media::BindToCurrentLoop( - base::Bind(&VEAEncoder::FrameFinished, this, - base::Passed(std::move(input_buffer))))); + WTF::BindRepeating(&VEAEncoder::FrameFinished, WrapRefCounted(this), + WTF::Passed(std::move(input_buffer))))); libyuv::I420Copy(frame->visible_data(media::VideoFrame::kYPlane), frame->stride(media::VideoFrame::kYPlane), frame->visible_data(media::VideoFrame::kUPlane), @@ -287,4 +293,4 @@ async_waiter->Signal(); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/vea_encoder.h b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.h similarity index 85% rename from content/renderer/media_recorder/vea_encoder.h rename to third_party/blink/renderer/modules/mediarecorder/vea_encoder.h index 2ef80c76..7b17147 100644 --- a/content/renderer/media_recorder/vea_encoder.h +++ b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.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 CONTENT_RENDERER_MEDIA_RECORDER_VEA_ENCODER_H_ -#define CONTENT_RENDERER_MEDIA_RECORDER_VEA_ENCODER_H_ - -#include <queue> +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VEA_ENCODER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VEA_ENCODER_H_ #include "base/containers/queue.h" #include "base/single_thread_task_runner.h" -#include "content/renderer/media_recorder/video_track_recorder.h" #include "media/video/video_encode_accelerator.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" +#include "third_party/blink/renderer/platform/wtf/time.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" #include "ui/gfx/geometry/size.h" namespace base { @@ -21,7 +21,7 @@ class GpuVideoAcceleratorFactories; } // namespace media -namespace content { +namespace blink { // Class encapsulating VideoEncodeAccelerator interactions. // This class is created and destroyed on its owner thread. All other methods @@ -80,9 +80,10 @@ std::unique_ptr<media::VideoEncodeAccelerator> video_encoder_; // Shared memory buffers for output with the VEA. - std::vector<std::unique_ptr<base::SharedMemory>> output_buffers_; + Vector<std::unique_ptr<base::SharedMemory>> output_buffers_; // Shared memory buffers for output with the VEA as FIFO. + // TODO(crbug.com/960665): Replace with a WTF equivalent. base::queue<std::unique_ptr<base::SharedMemory>> input_buffers_; // Tracks error status. @@ -98,6 +99,7 @@ gfx::Size vea_requested_input_coded_size_; // Frames and corresponding timestamps in encode as FIFO. + // TODO(crbug.com/960665): Replace with a WTF equivalent. base::queue<VideoParamsAndTimestamp> frames_in_encode_; // Number of encoded frames produced consecutively without a keyframe. @@ -110,6 +112,6 @@ const VideoTrackRecorder::OnErrorCB on_error_callback_; }; -} // namespace content +} // namespace blink -#endif // CONTENT_RENDERER_MEDIA_RECORDER_VEA_ENCODER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VEA_ENCODER_H_
diff --git a/content/renderer/media_recorder/video_track_recorder.cc b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.cc similarity index 78% rename from content/renderer/media_recorder/video_track_recorder.cc rename to third_party/blink/renderer/modules/mediarecorder/video_track_recorder.cc index 8eedba3d..60582086 100644 --- a/content/renderer/media_recorder/video_track_recorder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.cc
@@ -2,42 +2,41 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/video_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" -#include <map> -#include <utility> - -#include "base/bind.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" -#include "base/stl_util.h" #include "base/task_runner_util.h" -#include "base/threading/thread.h" #include "base/threading/thread_task_runner_handle.h" -#include "base/time/time.h" +#include "build/build_config.h" #include "cc/paint/skia_paint_canvas.h" -#include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h" -#include "content/renderer/media_recorder/vea_encoder.h" -#include "content/renderer/media_recorder/vpx_encoder.h" -#include "content/renderer/render_thread_impl.h" #include "media/base/bind_to_current_loop.h" #include "media/base/video_frame.h" #include "media/base/video_util.h" +#include "media/muxers/webm_muxer.h" #include "media/renderers/paint_canvas_video_renderer.h" -#include "services/viz/public/cpp/gpu/context_provider_command_buffer.h" +#include "media/video/gpu_video_accelerator_factories.h" #include "skia/ext/platform_canvas.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h" +#include "third_party/blink/renderer/modules/mediarecorder/buildflags.h" +#include "third_party/blink/renderer/modules/mediarecorder/vea_encoder.h" +#include "third_party/blink/renderer/modules/mediarecorder/vpx_encoder.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/libyuv/include/libyuv.h" #include "ui/gfx/geometry/size.h" #if BUILDFLAG(RTC_USE_H264) -#include "content/renderer/media_recorder/h264_encoder.h" +#include "third_party/blink/renderer/modules/mediarecorder/h264_encoder.h" #endif // #if BUILDFLAG(RTC_USE_H264) using media::VideoFrame; -using video_track_recorder::kVEAEncoderMinResolutionWidth; using video_track_recorder::kVEAEncoderMinResolutionHeight; +using video_track_recorder::kVEAEncoderMinResolutionWidth; -namespace content { +namespace blink { libyuv::RotationMode MediaVideoRotationToRotationMode( media::VideoRotation rotation) { @@ -85,15 +84,13 @@ // Obtains video encode accelerator's supported profiles. media::VideoEncodeAccelerator::SupportedProfiles GetVEASupportedProfiles() { - content::RenderThreadImpl* const render_thread_impl = - content::RenderThreadImpl::current(); - if (!render_thread_impl) { + if (!Platform::Current()) { DVLOG(2) << "Couldn't access the render thread"; return media::VideoEncodeAccelerator::SupportedProfiles(); } media::GpuVideoAcceleratorFactories* const gpu_factories = - render_thread_impl->GetGpuFactories(); + Platform::Current()->GetGpuFactories(); if (!gpu_factories || !gpu_factories->IsGpuVideoAcceleratorEnabled()) { DVLOG(2) << "Couldn't initialize GpuVideoAcceleratorFactories"; return media::VideoEncodeAccelerator::SupportedProfiles(); @@ -130,8 +127,17 @@ << ", max_framerate: " << supported_profile.max_framerate_numerator << "/" << supported_profile.max_framerate_denominator; - supported_profiles_[codec_id_and_profile.codec_id].push_back( - supported_profile); + auto iter = supported_profiles_.find(codec_id_and_profile.codec_id); + if (iter == supported_profiles_.end()) { + auto result = supported_profiles_.insert( + codec_id_and_profile.codec_id, + media::VideoEncodeAccelerator::SupportedProfiles()); + result.stored_value->value.push_back(supported_profile); + } else { + iter->value.push_back(supported_profile); + } + if (preferred_codec_id_ == CodecId::LAST) + preferred_codec_id_ = codec_id_and_profile.codec_id; } } } @@ -141,9 +147,10 @@ VideoTrackRecorder::CodecId VideoTrackRecorder::CodecEnumerator::GetPreferredCodecId() const { - if (supported_profiles_.empty()) + if (preferred_codec_id_ == CodecId::LAST) return CodecId::VP8; - return supported_profiles_.begin()->first; + + return preferred_codec_id_; } media::VideoCodecProfile @@ -152,7 +159,7 @@ const auto profile = supported_profiles_.find(codec); return profile == supported_profiles_.end() ? media::VIDEO_CODEC_PROFILE_UNKNOWN - : profile->second.front().profile; + : profile->value.front().profile; } media::VideoEncodeAccelerator::SupportedProfiles @@ -160,7 +167,7 @@ const auto profile = supported_profiles_.find(codec); return profile == supported_profiles_.end() ? media::VideoEncodeAccelerator::SupportedProfiles() - : profile->second; + : profile->value; } VideoTrackRecorder::Counter::Counter() : count_(0u), weak_factory_(this) {} @@ -194,9 +201,11 @@ DCHECK(!on_encoded_video_callback_.is_null()); if (encoding_task_runner_) return; - encoding_thread_.reset(new base::Thread("EncodingThread")); - encoding_thread_->Start(); - encoding_task_runner_ = encoding_thread_->task_runner(); + + encoding_thread_ = Thread::CreateThread( + ThreadCreationParams(WebThreadType::kVideoEncoderThread)); + + encoding_task_runner_ = encoding_thread_->GetTaskRunner(); } VideoTrackRecorder::Encoder::~Encoder() { @@ -213,6 +222,7 @@ // Cache the thread sending frames on first frame arrival. if (!origin_task_runner_.get()) origin_task_runner_ = base::ThreadTaskRunnerHandle::Get(); + DCHECK(origin_task_runner_->BelongsToCurrentThread()); if (paused_) return; @@ -231,9 +241,12 @@ } if (video_frame->HasTextures()) { - main_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Encoder::RetrieveFrameOnMainThread, this, - std::move(video_frame), capture_timestamp)); + PostCrossThreadTask( + *main_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&Encoder::RetrieveFrameOnMainThread, + WrapRefCounted(this), std::move(video_frame), + capture_timestamp)); + return; } @@ -248,15 +261,16 @@ video_frame->natural_size()); } wrapped_frame->AddDestructionObserver(media::BindToCurrentLoop( - base::BindOnce(&VideoTrackRecorder::Counter::DecreaseCount, - num_frames_in_encode_->GetWeakPtr()))); - wrapped_frame->AddDestructionObserver(base::BindOnce( - [](scoped_refptr<VideoFrame> video_frame) {}, std::move(video_frame))); + WTF::BindRepeating(&VideoTrackRecorder::Counter::DecreaseCount, + num_frames_in_encode_->GetWeakPtr()))); + wrapped_frame->AddDestructionObserver(ConvertToBaseCallback(CrossThreadBind( + [](scoped_refptr<VideoFrame> video_frame) {}, std::move(video_frame)))); num_frames_in_encode_->IncreaseCount(); - encoding_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Encoder::EncodeOnEncodingTaskRunner, this, - wrapped_frame, capture_timestamp)); + PostCrossThreadTask(*encoding_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&Encoder::EncodeOnEncodingTaskRunner, + WrapRefCounted(this), wrapped_frame, + capture_timestamp)); } void VideoTrackRecorder::Encoder::RetrieveFrameOnMainThread( @@ -266,9 +280,10 @@ scoped_refptr<media::VideoFrame> frame; - // |context_provider| is null if the GPU process has crashed or isn't there. - viz::ContextProviderCommandBuffer* const context_provider = - RenderThreadImpl::current()->SharedMainThreadContextProvider().get(); + // |context_provider| is null if the GPU process has crashed or isn't there + std::unique_ptr<WebGraphicsContext3DProvider> context_provider = + Platform::Current()->CreateSharedOffscreenGraphicsContext3DProvider(); + if (!context_provider) { // Send black frames (yuv = {0, 127, 127}). frame = media::VideoFrame::CreateColorFrame( @@ -309,7 +324,8 @@ if (!video_renderer_) video_renderer_.reset(new media::PaintCanvasVideoRenderer); - video_renderer_->Copy(video_frame.get(), canvas_.get(), context_provider); + context_provider->CopyVideoFrame(video_renderer_.get(), video_frame.get(), + canvas_.get()); SkPixmap pixmap; if (!bitmap_.peekPixels(&pixmap)) { @@ -338,20 +354,21 @@ } } - encoding_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Encoder::EncodeOnEncodingTaskRunner, this, - frame, capture_timestamp)); + PostCrossThreadTask( + *encoding_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&Encoder::EncodeOnEncodingTaskRunner, + WrapRefCounted(this), frame, capture_timestamp)); } // static void VideoTrackRecorder::Encoder::OnFrameEncodeCompleted( - const VideoTrackRecorder::OnEncodedVideoCB& on_encoded_video_cb, + const OnEncodedVideoInternalCB& on_encoded_video_cb, const media::WebmMuxer::VideoParameters& params, std::unique_ptr<std::string> data, std::unique_ptr<std::string> alpha_data, base::TimeTicks capture_timestamp, bool keyframe) { - DVLOG(1) << (keyframe ? "" : "non ") << "keyframe "<< data->length() << "B, " + DVLOG(1) << (keyframe ? "" : "non ") << "keyframe " << data->length() << "B, " << capture_timestamp << " ms"; on_encoded_video_cb.Run(params, std::move(data), std::move(alpha_data), capture_timestamp, keyframe); @@ -359,8 +376,9 @@ void VideoTrackRecorder::Encoder::SetPaused(bool paused) { if (!encoding_task_runner_->BelongsToCurrentThread()) { - encoding_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Encoder::SetPaused, this, paused)); + PostCrossThreadTask( + *encoding_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&Encoder::SetPaused, WrapRefCounted(this), paused)); return; } paused_ = paused; @@ -408,7 +426,7 @@ VideoTrackRecorder::VideoTrackRecorder( CodecId codec, - const blink::WebMediaStreamTrack& track, + const WebMediaStreamTrack& track, const OnEncodedVideoCB& on_encoded_video_callback, int32_t bits_per_second, scoped_refptr<base::SingleThreadTaskRunner> main_task_runner) @@ -420,21 +438,21 @@ DCHECK(!track_.IsNull()); DCHECK(track_.GetPlatformTrack()); - initialize_encoder_callback_ = base::Bind( + initialize_encoder_callback_ = WTF::BindRepeating( &VideoTrackRecorder::InitializeEncoder, weak_ptr_factory_.GetWeakPtr(), codec, on_encoded_video_callback, bits_per_second); // InitializeEncoder() will be called on Render Main thread. - blink::MediaStreamVideoSink::ConnectToTrack( + MediaStreamVideoSink::ConnectToTrack( track_, - media::BindToCurrentLoop(base::Bind(initialize_encoder_callback_, - true /* allow_vea_encoder */)), + media::BindToCurrentLoop(WTF::BindRepeating( + initialize_encoder_callback_, true /* allow_vea_encoder */)), false); } VideoTrackRecorder::~VideoTrackRecorder() { DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_); - blink::MediaStreamVideoSink::DisconnectFromTrack(); + MediaStreamVideoSink::DisconnectFromTrack(); track_.Reset(); } @@ -483,7 +501,7 @@ if (encoder_) return; - blink::MediaStreamVideoSink::DisconnectFromTrack(); + MediaStreamVideoSink::DisconnectFromTrack(); const gfx::Size& input_size = frame->visible_rect().size(); if (allow_vea_encoder && CanUseAcceleratedEncoder(codec, input_size.width(), @@ -493,23 +511,23 @@ GetCodecEnumerator()->GetFirstSupportedVideoCodecProfile(codec); encoder_ = VEAEncoder::Create( on_encoded_video_callback, - media::BindToCurrentLoop(base::Bind(&VideoTrackRecorder::OnError, - weak_ptr_factory_.GetWeakPtr())), + media::BindToCurrentLoop(WTF::BindRepeating( + &VideoTrackRecorder::OnError, weak_ptr_factory_.GetWeakPtr())), bits_per_second, vea_profile, input_size, main_task_runner_); } else { UMA_HISTOGRAM_BOOLEAN("Media.MediaRecorder.VEAUsed", false); switch (codec) { #if BUILDFLAG(RTC_USE_H264) case CodecId::H264: - encoder_ = new H264Encoder(on_encoded_video_callback, bits_per_second, - main_task_runner_); + encoder_ = base::MakeRefCounted<H264Encoder>( + on_encoded_video_callback, bits_per_second, main_task_runner_); break; #endif case CodecId::VP8: case CodecId::VP9: - encoder_ = - new VpxEncoder(codec == CodecId::VP9, on_encoded_video_callback, - bits_per_second, main_task_runner_); + encoder_ = base::MakeRefCounted<VpxEncoder>( + codec == CodecId::VP9, on_encoded_video_callback, bits_per_second, + main_task_runner_); break; default: NOTREACHED() << "Unsupported codec " << static_cast<int>(codec); @@ -520,9 +538,10 @@ encoder_->SetPaused(should_pause_encoder_on_initialization_); // StartFrameEncode() will be called on Render IO thread. - blink::MediaStreamVideoSink::ConnectToTrack( + MediaStreamVideoSink::ConnectToTrack( track_, - base::Bind(&VideoTrackRecorder::Encoder::StartFrameEncode, encoder_), + ConvertToBaseCallback(CrossThreadBind( + &VideoTrackRecorder::Encoder::StartFrameEncode, encoder_)), false); } @@ -532,13 +551,13 @@ // InitializeEncoder() will be called to reinitialize encoder on Render Main // thread. - blink::MediaStreamVideoSink::DisconnectFromTrack(); + MediaStreamVideoSink::DisconnectFromTrack(); encoder_ = nullptr; - blink::MediaStreamVideoSink::ConnectToTrack( + MediaStreamVideoSink::ConnectToTrack( track_, - media::BindToCurrentLoop(base::Bind(initialize_encoder_callback_, - false /*allow_vea_encoder*/)), + media::BindToCurrentLoop(WTF::BindRepeating(initialize_encoder_callback_, + false /*allow_vea_encoder*/)), false); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/video_track_recorder.h b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h similarity index 78% rename from content/renderer/media_recorder/video_track_recorder.h rename to third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h index 6e10eb16..3911420 100644 --- a/content/renderer/media_recorder/video_track_recorder.h +++ b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h
@@ -2,23 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_ -#define CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VIDEO_TRACK_RECORDER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VIDEO_TRACK_RECORDER_H_ #include <memory> -#include "base/containers/flat_map.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_checker.h" -#include "content/common/content_export.h" -#include "content/public/common/buildflags.h" +#include "base/time/time.h" +#include "build/build_config.h" #include "media/muxers/webm_muxer.h" #include "media/video/video_encode_accelerator.h" #include "third_party/blink/public/platform/web_media_stream_track.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_sink.h" +#include "third_party/blink/renderer/modules/mediarecorder/buildflags.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/hash_map.h" +#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h" #include "third_party/skia/include/core/SkBitmap.h" namespace base { @@ -44,7 +48,20 @@ #endif } // namespace video_track_recorder -namespace content { +namespace WTF { + +template <> +struct CrossThreadCopier<media::WebmMuxer::VideoParameters> { + STATIC_ONLY(CrossThreadCopier); + using Type = media::WebmMuxer::VideoParameters; + static Type Copy(Type pointer) { return pointer; } +}; + +} // namespace WTF + +namespace blink { + +class Thread; // VideoTrackRecorder is a MediaStreamVideoSink that encodes the video frames // received from a Stream Video Track. This class is constructed and used on a @@ -52,7 +69,7 @@ // MediaStreamVideo* classes that are constructed/configured on Main Render // thread but that pass frames on Render IO thread. It has an internal Encoder // with its own threading subtleties, see the implementation file. -class CONTENT_EXPORT VideoTrackRecorder : public blink::MediaStreamVideoSink { +class MODULES_EXPORT VideoTrackRecorder : public MediaStreamVideoSink { public: // Do not change the order of codecs; add new ones right before LAST. enum class CodecId { @@ -64,13 +81,13 @@ LAST }; - using OnEncodedVideoCB = - base::Callback<void(const media::WebmMuxer::VideoParameters& params, - std::unique_ptr<std::string> encoded_data, - std::unique_ptr<std::string> encoded_alpha, - base::TimeTicks capture_timestamp, - bool is_key_frame)>; - using OnErrorCB = base::Closure; + using OnEncodedVideoCB = base::RepeatingCallback<void( + const media::WebmMuxer::VideoParameters& params, + std::unique_ptr<std::string> encoded_data, + std::unique_ptr<std::string> encoded_alpha, + base::TimeTicks capture_timestamp, + bool is_key_frame)>; + using OnErrorCB = base::RepeatingClosure; // Wraps a counter in a class in order to enable use of base::WeakPtr<>. // See https://crbug.com/859610 for why this was added. @@ -102,13 +119,14 @@ // namely configuration, encoding (which might take some time) and // destruction. This task runner can be passed on the creation. If nothing is // passed, a new encoding thread is created and used. - class Encoder : public base::RefCountedThreadSafe<Encoder> { + class Encoder : public WTF::ThreadSafeRefCounted<Encoder> { public: - Encoder(const OnEncodedVideoCB& on_encoded_video_callback, - int32_t bits_per_second, - scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, - scoped_refptr<base::SingleThreadTaskRunner> encoding_task_runner = - nullptr); + Encoder( + const VideoTrackRecorder::OnEncodedVideoCB& on_encoded_video_callback, + int32_t bits_per_second, + scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, + scoped_refptr<base::SingleThreadTaskRunner> encoding_task_runner = + nullptr); // Start encoding |frame|, returning via |on_encoded_video_callback_|. This // call will also trigger an encode configuration upon first frame arrival @@ -121,8 +139,15 @@ void RetrieveFrameOnMainThread(scoped_refptr<media::VideoFrame> video_frame, base::TimeTicks capture_timestamp); + using OnEncodedVideoInternalCB = WTF::CrossThreadFunction<void( + const media::WebmMuxer::VideoParameters& params, + std::unique_ptr<std::string> encoded_data, + std::unique_ptr<std::string> encoded_alpha, + base::TimeTicks capture_timestamp, + bool is_key_frame)>; + static void OnFrameEncodeCompleted( - const VideoTrackRecorder::OnEncodedVideoCB& on_encoded_video_cb, + const OnEncodedVideoInternalCB& on_encoded_video_cb, const media::WebmMuxer::VideoParameters& params, std::unique_ptr<std::string> data, std::unique_ptr<std::string> alpha_data, @@ -133,7 +158,7 @@ virtual bool CanEncodeAlphaChannel(); protected: - friend class base::RefCountedThreadSafe<Encoder>; + friend class WTF::ThreadSafeRefCounted<Encoder>; friend class VideoTrackRecorderTest; // This destructor may run on either |main_task_runner|, @@ -162,7 +187,7 @@ scoped_refptr<base::SingleThreadTaskRunner> encoding_task_runner_; // Optional thread for encoding. Active for the lifetime of VpxEncoder. - std::unique_ptr<base::Thread> encoding_thread_; + std::unique_ptr<Thread> encoding_thread_; // While |paused_|, frames are not encoded. Used only from // |encoding_thread_|. @@ -190,7 +215,7 @@ // Class to encapsulate the enumeration of CodecIds/VideoCodecProfiles // supported by the VEA underlying platform. Provides methods to query the // preferred CodecId and to check if a given CodecId is supported. - class CONTENT_EXPORT CodecEnumerator { + class MODULES_EXPORT CodecEnumerator { public: CodecEnumerator(const media::VideoEncodeAccelerator::SupportedProfiles& vea_supported_profiles); @@ -212,8 +237,9 @@ private: // VEA-supported profiles grouped by CodecId. - base::flat_map<CodecId, media::VideoEncodeAccelerator::SupportedProfiles> + HashMap<CodecId, media::VideoEncodeAccelerator::SupportedProfiles> supported_profiles_; + CodecId preferred_codec_id_ = CodecId::LAST; DISALLOW_COPY_AND_ASSIGN(CodecEnumerator); }; @@ -231,7 +257,7 @@ VideoTrackRecorder( CodecId codec, - const blink::WebMediaStreamTrack& track, + const WebMediaStreamTrack& track, const OnEncodedVideoCB& on_encoded_video_cb, int32_t bits_per_second, scoped_refptr<base::SingleThreadTaskRunner> main_task_runner); @@ -257,14 +283,14 @@ THREAD_CHECKER(main_thread_checker_); // We need to hold on to the Blink track to remove ourselves on dtor. - blink::WebMediaStreamTrack track_; + WebMediaStreamTrack track_; // Inner class to encode using whichever codec is configured. scoped_refptr<Encoder> encoder_; - base::Callback<void(bool allow_vea_encoder, - scoped_refptr<media::VideoFrame> frame, - base::TimeTicks capture_time)> + base::RepeatingCallback<void(bool allow_vea_encoder, + scoped_refptr<media::VideoFrame> frame, + base::TimeTicks capture_time)> initialize_encoder_callback_; bool should_pause_encoder_on_initialization_; @@ -276,5 +302,6 @@ DISALLOW_COPY_AND_ASSIGN(VideoTrackRecorder); }; -} // namespace content -#endif // CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_ +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VIDEO_TRACK_RECORDER_H_
diff --git a/content/renderer/media_recorder/video_track_recorder_unittest.cc b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder_unittest.cc similarity index 85% rename from content/renderer/media_recorder/video_track_recorder_unittest.cc rename to third_party/blink/renderer/modules/mediarecorder/video_track_recorder_unittest.cc index 540a622..b6a3abd 100644 --- a/content/renderer/media_recorder/video_track_recorder_unittest.cc +++ b/third_party/blink/renderer/modules/mediarecorder/video_track_recorder_unittest.cc
@@ -2,36 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/video_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" -#include <stddef.h> - -#include <memory> -#include <string> - -#include "base/bind.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/run_loop.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_task_environment.h" -#include "base/threading/thread_task_runner_handle.h" -#include "content/child/child_process.h" #include "media/base/video_codecs.h" #include "media/base/video_frame.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/web/modules/mediastream/media_stream_video_source.h" #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h" #include "third_party/blink/public/web/modules/mediastream/mock_media_stream_video_source.h" #include "third_party/blink/public/web/web_heap.h" +#include "third_party/blink/renderer/modules/mediarecorder/buildflags.h" +#include "third_party/blink/renderer/platform/testing/io_task_runner_testing_platform_support.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/time.h" using media::VideoFrame; -using video_track_recorder::kVEAEncoderMinResolutionWidth; using video_track_recorder::kVEAEncoderMinResolutionHeight; +using video_track_recorder::kVEAEncoderMinResolutionWidth; using ::testing::_; using ::testing::DoAll; @@ -42,17 +36,19 @@ using ::testing::TestWithParam; using ::testing::ValuesIn; -namespace content { +namespace blink { -ACTION_P(RunClosure, closure) { +// Using RunClosure4 instead of RunClosure to avoid symbol collisions in jumbo +// builds. +ACTION_P(RunClosure4, closure) { closure.Run(); } const VideoTrackRecorder::CodecId kTrackRecorderTestCodec[] = { - VideoTrackRecorder::CodecId::VP8, - VideoTrackRecorder::CodecId::VP9 + VideoTrackRecorder::CodecId::VP8, VideoTrackRecorder::CodecId::VP9 #if BUILDFLAG(RTC_USE_H264) - , VideoTrackRecorder::CodecId::H264 + , + VideoTrackRecorder::CodecId::H264 #endif }; const gfx::Size kTrackRecorderTestSize[] = { @@ -65,28 +61,22 @@ : public TestWithParam< testing::tuple<VideoTrackRecorder::CodecId, gfx::Size, bool>> { public: - VideoTrackRecorderTest() - : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::UI), - mock_source_(new blink::MockMediaStreamVideoSource()) { - const blink::WebString webkit_track_id( - blink::WebString::FromASCII("dummy")); - blink_source_.Initialize(webkit_track_id, - blink::WebMediaStreamSource::kTypeVideo, + VideoTrackRecorderTest() : mock_source_(new MockMediaStreamVideoSource()) { + const WebString webkit_track_id(WebString::FromASCII("dummy")); + blink_source_.Initialize(webkit_track_id, WebMediaStreamSource::kTypeVideo, webkit_track_id, false /*remote*/); blink_source_.SetPlatformSource(base::WrapUnique(mock_source_)); blink_track_.Initialize(blink_source_); - track_ = new blink::MediaStreamVideoTrack( - mock_source_, - blink::WebPlatformMediaStreamSource::ConstraintsCallback(), + track_ = new MediaStreamVideoTrack( + mock_source_, WebPlatformMediaStreamSource::ConstraintsCallback(), true /* enabled */); blink_track_.SetPlatformTrack(base::WrapUnique(track_)); // Paranoia checks. EXPECT_EQ(blink_track_.Source().GetPlatformSource(), blink_source_.GetPlatformSource()); - EXPECT_TRUE(blink::scheduler::GetSingleThreadTaskRunnerForTesting() + EXPECT_TRUE(scheduler::GetSingleThreadTaskRunnerForTesting() ->BelongsToCurrentThread()); } @@ -94,19 +84,17 @@ blink_track_.Reset(); blink_source_.Reset(); video_track_recorder_.reset(); - blink::WebHeap::CollectAllGarbageForTesting(); - // VideoTrackRecorder::Encoder::~Encoder may post a DeleteSoon(), which - // may cause ASAN to detect a memory leak if we don't wait. - scoped_task_environment_.RunUntilIdle(); + WebHeap::CollectAllGarbageForTesting(); } void InitializeRecorder(VideoTrackRecorder::CodecId codec) { video_track_recorder_.reset(new VideoTrackRecorder( codec, blink_track_, - base::Bind(&VideoTrackRecorderTest::OnEncodedVideo, - base::Unretained(this)), + ConvertToBaseCallback( + CrossThreadBind(&VideoTrackRecorderTest::OnEncodedVideo, + CrossThreadUnretained(this))), 0 /* bits_per_second */, - blink::scheduler::GetSingleThreadTaskRunnerForTesting())); + scheduler::GetSingleThreadTaskRunnerForTesting())); } MOCK_METHOD5(DoOnEncodedVideo, @@ -126,7 +114,7 @@ } void Encode(scoped_refptr<VideoFrame> frame, base::TimeTicks capture_time) { - EXPECT_TRUE(blink::scheduler::GetSingleThreadTaskRunnerForTesting() + EXPECT_TRUE(scheduler::GetSingleThreadTaskRunnerForTesting() ->BelongsToCurrentThread()); video_track_recorder_->OnVideoFrameForTesting(std::move(frame), capture_time); @@ -138,26 +126,20 @@ return video_track_recorder_->encoder_->CanEncodeAlphaChannel(); } - bool HasEncoderInstance() { - return video_track_recorder_->encoder_.get() != nullptr; - } + bool HasEncoderInstance() { return video_track_recorder_->encoder_.get(); } uint32_t NumFramesInEncode() { return video_track_recorder_->encoder_->num_frames_in_encode_->count(); } - // A ChildProcess is needed to fool the Tracks and Sources into believing they - // are on the right threads. A ScopedTaskEnvironment must be instantiated - // before ChildProcess to prevent it from leaking a ThreadPoolInstance. - base::test::ScopedTaskEnvironment scoped_task_environment_; - const ChildProcess child_process_; + ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform_; // All members are non-const due to the series of initialize() calls needed. // |mock_source_| is owned by |blink_source_|, |track_| by |blink_track_|. - blink::MockMediaStreamVideoSource* mock_source_; - blink::WebMediaStreamSource blink_source_; - blink::MediaStreamVideoTrack* track_; - blink::WebMediaStreamTrack blink_track_; + MockMediaStreamVideoSource* mock_source_; + WebMediaStreamSource blink_source_; + MediaStreamVideoTrack* track_; + WebMediaStreamTrack blink_track_; std::unique_ptr<VideoTrackRecorder> video_track_recorder_; @@ -225,7 +207,7 @@ .Times(1) .WillOnce(DoAll(SaveArg<1>(&third_frame_encoded_data), SaveArg<2>(&third_frame_encoded_alpha), - RunClosure(std::move(quit_closure)))); + RunClosure4(std::move(quit_closure)))); Encode(video_frame2, base::TimeTicks::Now()); run_loop.Run(); @@ -267,7 +249,7 @@ base::Closure quit_closure = run_loop.QuitClosure(); EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure4(std::move(quit_closure))); Encode(video_frame, base::TimeTicks::Now()); run_loop.Run(); @@ -304,7 +286,7 @@ EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, false)) .Times(1) .WillOnce(DoAll(SaveArg<2>(&third_frame_encoded_alpha), - RunClosure(std::move(quit_closure)))); + RunClosure4(std::move(quit_closure)))); Encode(alpha_frame, base::TimeTicks::Now()); run_loop.Run(); @@ -336,7 +318,7 @@ base::Closure quit_closure = run_loop.QuitClosure(); EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure4(std::move(quit_closure))); Encode(video_frame, base::TimeTicks::Now()); run_loop.Run(); @@ -360,7 +342,7 @@ base::BindOnce(set_to_true, &frame_is_destroyed)); EXPECT_CALL(*this, DoOnEncodedVideo(_, _, _, _, true)) .Times(1) - .WillOnce(RunClosure(std::move(quit_closure))); + .WillOnce(RunClosure4(std::move(quit_closure))); Encode(video_frame, base::TimeTicks::Now()); video_frame = nullptr; run_loop.Run(); @@ -462,4 +444,4 @@ emulator.GetFirstSupportedVideoCodecProfile(CodecId::VP8)); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/vpx_encoder.cc b/third_party/blink/renderer/modules/mediarecorder/vpx_encoder.cc similarity index 86% rename from content/renderer/media_recorder/vpx_encoder.cc rename to third_party/blink/renderer/modules/mediarecorder/vpx_encoder.cc index 052d2977..ff57dda 100644 --- a/content/renderer/media_recorder/vpx_encoder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/vpx_encoder.cc
@@ -2,22 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/media_recorder/vpx_encoder.h" +#include "third_party/blink/renderer/modules/mediarecorder/vpx_encoder.h" #include <algorithm> -#include <string> -#include "base/bind.h" #include "base/system/sys_info.h" -#include "base/threading/thread.h" -#include "base/trace_event/trace_event.h" #include "media/base/video_frame.h" +#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" +#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" #include "ui/gfx/geometry/size.h" using media::VideoFrame; using media::VideoFrameMetadata; -namespace content { +namespace blink { void VpxEncoder::VpxCodecDeleter::operator()(vpx_codec_ctx_t* codec) { if (!codec) @@ -35,10 +36,9 @@ } // static -void VpxEncoder::ShutdownEncoder(std::unique_ptr<base::Thread> encoding_thread, +void VpxEncoder::ShutdownEncoder(std::unique_ptr<Thread> encoding_thread, ScopedVpxCodecCtxPtr encoder) { - DCHECK(encoding_thread->IsRunning()); - encoding_thread->Stop(); + DCHECK(encoding_thread); // Both |encoding_thread| and |encoder| will be destroyed at end-of-scope. } @@ -53,14 +53,14 @@ use_vp9_(use_vp9) { codec_config_.g_timebase.den = 0; // Not initialized. alpha_codec_config_.g_timebase.den = 0; // Not initialized. - DCHECK(encoding_thread_->IsRunning()); + DCHECK(encoding_thread_); } VpxEncoder::~VpxEncoder() { - main_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&VpxEncoder::ShutdownEncoder, std::move(encoding_thread_), - std::move(encoder_))); + PostCrossThreadTask( + *main_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce(&VpxEncoder::ShutdownEncoder, + std::move(encoding_thread_), std::move(encoder_))); } bool VpxEncoder::CanEncodeAlphaChannel() { @@ -73,7 +73,7 @@ DCHECK(encoding_task_runner_->BelongsToCurrentThread()); const gfx::Size frame_size = frame->visible_rect().size(); - base::TimeDelta duration = EstimateFrameDuration(*frame); + TimeDelta duration = EstimateFrameDuration(*frame); const media::WebmMuxer::VideoParameters video_params(frame); if (!IsInitialized(codec_config_) || @@ -96,10 +96,10 @@ v_plane_offset_ = media::VideoFrame::PlaneSize( frame->format(), VideoFrame::kUPlane, frame_size) .GetArea(); - alpha_dummy_planes_.resize( + alpha_dummy_planes_.resize(SafeCast<wtf_size_t>( v_plane_offset_ + media::VideoFrame::PlaneSize( frame->format(), VideoFrame::kVPlane, frame_size) - .GetArea()); + .GetArea())); // It is more expensive to encode 0x00, so use 0x80 instead. std::fill(alpha_dummy_planes_.begin(), alpha_dummy_planes_.end(), 0x80); } @@ -124,18 +124,21 @@ DoEncode(alpha_encoder_.get(), frame_size, frame->data(VideoFrame::kAPlane), frame->visible_data(VideoFrame::kAPlane), frame->stride(VideoFrame::kAPlane), alpha_dummy_planes_.data(), - u_plane_stride_, alpha_dummy_planes_.data() + v_plane_offset_, - v_plane_stride_, duration, keyframe, alpha_data.get(), - &alpha_keyframe); + SafeCast<int>(u_plane_stride_), + alpha_dummy_planes_.data() + v_plane_offset_, + SafeCast<int>(v_plane_stride_), duration, keyframe, + alpha_data.get(), &alpha_keyframe); DCHECK_EQ(keyframe, alpha_keyframe); } frame = nullptr; - origin_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(OnFrameEncodeCompleted, on_encoded_video_callback_, - video_params, std::move(data), std::move(alpha_data), - capture_timestamp, keyframe)); + PostCrossThreadTask( + *origin_task_runner_.get(), FROM_HERE, + CrossThreadBindOnce( + OnFrameEncodeCompleted, + WTF::Passed(CrossThreadBind(on_encoded_video_callback_)), + video_params, std::move(data), std::move(alpha_data), + capture_timestamp, keyframe)); } void VpxEncoder::DoEncode(vpx_codec_ctx_t* const encoder, @@ -147,7 +150,7 @@ int u_stride, uint8_t* const v_plane, int v_stride, - const base::TimeDelta& duration, + const TimeDelta& duration, bool force_keyframe, std::string* const output_data, bool* const keyframe) { @@ -171,7 +174,8 @@ // entirely on |predicted_frame_duration|. const vpx_codec_err_t ret = vpx_codec_encode(encoder, &vpx_image, 0 /* pts */, - duration.InMicroseconds(), flags, VPX_DL_REALTIME); + static_cast<unsigned long>(duration.InMicroseconds()), + flags, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << vpx_codec_err_to_string(ret) << ", #" << vpx_codec_error(encoder) << " -" << vpx_codec_error_detail(encoder); @@ -179,7 +183,7 @@ *keyframe = false; vpx_codec_iter_t iter = nullptr; const vpx_codec_cx_pkt_t* pkt = nullptr; - while ((pkt = vpx_codec_get_cx_data(encoder, &iter)) != nullptr) { + while ((pkt = vpx_codec_get_cx_data(encoder, &iter))) { if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) continue; output_data->assign(static_cast<char*>(pkt->data.frame.buf), @@ -285,7 +289,7 @@ return codec_config.g_timebase.den != 0; } -base::TimeDelta VpxEncoder::EstimateFrameDuration(const VideoFrame& frame) { +TimeDelta VpxEncoder::EstimateFrameDuration(const VideoFrame& frame) { DCHECK(encoding_task_runner_->BelongsToCurrentThread()); using base::TimeDelta; @@ -309,4 +313,4 @@ std::max(predicted_frame_duration, kMinFrameDuration)); } -} // namespace content +} // namespace blink
diff --git a/content/renderer/media_recorder/vpx_encoder.h b/third_party/blink/renderer/modules/mediarecorder/vpx_encoder.h similarity index 84% rename from content/renderer/media_recorder/vpx_encoder.h rename to third_party/blink/renderer/modules/mediarecorder/vpx_encoder.h index 8b3445c..07a0f2d 100644 --- a/content/renderer/media_recorder/vpx_encoder.h +++ b/third_party/blink/renderer/modules/mediarecorder/vpx_encoder.h
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_MEDIA_RECORDER_VPX_ENCODER_H_ -#define CONTENT_RENDERER_MEDIA_RECORDER_VPX_ENCODER_H_ - -#include <vector> +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VPX_ENCODER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VPX_ENCODER_H_ #include "base/single_thread_task_runner.h" -#include "content/renderer/media_recorder/video_track_recorder.h" +#include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" +#include "third_party/blink/renderer/platform/wtf/time.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" -namespace content { +namespace blink { // Class encapsulating all libvpx interactions for VP8/VP9 encoding. class VpxEncoder final : public VideoTrackRecorder::Encoder { @@ -25,7 +25,7 @@ typedef std::unique_ptr<vpx_codec_ctx_t, VpxCodecDeleter> ScopedVpxCodecCtxPtr; - static void ShutdownEncoder(std::unique_ptr<base::Thread> encoding_thread, + static void ShutdownEncoder(std::unique_ptr<Thread> encoding_thread, ScopedVpxCodecCtxPtr encoder); VpxEncoder( @@ -77,7 +77,7 @@ vpx_codec_enc_cfg_t alpha_codec_config_; ScopedVpxCodecCtxPtr alpha_encoder_; - std::vector<uint8_t> alpha_dummy_planes_; + Vector<uint8_t> alpha_dummy_planes_; size_t v_plane_offset_; size_t u_plane_stride_; size_t v_plane_stride_; @@ -91,6 +91,6 @@ DISALLOW_COPY_AND_ASSIGN(VpxEncoder); }; -} // namespace content +} // namespace blink -#endif // CONTENT_RENDERER_MEDIA_RECORDER_VPX_ENCODER_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VPX_ENCODER_H_
diff --git a/third_party/blink/renderer/modules/mediasession/media_metadata.idl b/third_party/blink/renderer/modules/mediasession/media_metadata.idl index 5456a5d4..ea374ffd 100644 --- a/third_party/blink/renderer/modules/mediasession/media_metadata.idl +++ b/third_party/blink/renderer/modules/mediasession/media_metadata.idl
@@ -5,6 +5,7 @@ // https://wicg.github.io/mediasession/#the-mediametadata-interface [ + Exposed=Window, ConstructorCallWith=ScriptState, Constructor(optional MediaMetadataInit metadata), RaisesException=Constructor,
diff --git a/third_party/blink/renderer/modules/mediasession/media_session.idl b/third_party/blink/renderer/modules/mediasession/media_session.idl index 9ba8c54..a3b12ac 100644 --- a/third_party/blink/renderer/modules/mediasession/media_session.idl +++ b/third_party/blink/renderer/modules/mediasession/media_session.idl
@@ -26,6 +26,7 @@ callback MediaSessionActionHandler = void (); [ + Exposed=Window, RuntimeEnabled=MediaSession ] interface MediaSession { [Measure] attribute MediaMetadata? metadata;
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_content_test.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_content_test.cc index 9f5d3ec..b378cd4 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_content_test.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_content_test.cc
@@ -7,7 +7,6 @@ #include <cmath> #include <string> -#include "base/stl_util.h" #include "media/base/limits.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/modules/mediastream/web_platform_media_stream_source.h"
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device.cc index b9086a6..4122604 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device.cc
@@ -10,7 +10,6 @@ #include <utility> #include <vector> -#include "base/stl_util.h" #include "media/base/limits.h" #include "media/mojo/interfaces/display_media_information.mojom-blink.h" #include "third_party/blink/public/platform/web_media_constraints.h"
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc index b37e9a5..4a40229 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device_test.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/optional.h" -#include "base/stl_util.h" #include "media/base/limits.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_media_constraints.h"
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc b/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc index 9c25b81..60f651b6 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_source.cc
@@ -14,7 +14,6 @@ #include "base/feature_list.h" #include "base/logging.h" #include "base/macros.h" -#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom-blink.h" #include "third_party/blink/public/platform/platform.h"
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_video_track.cc b/third_party/blink/renderer/modules/mediastream/media_stream_video_track.cc index 98e3b4d7..9b0876f 100644 --- a/third_party/blink/renderer/modules/mediastream/media_stream_video_track.cc +++ b/third_party/blink/renderer/modules/mediastream/media_stream_video_track.cc
@@ -11,7 +11,6 @@ #include "base/location.h" #include "base/macros.h" #include "base/single_thread_task_runner.h" -#include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "media/base/bind_to_current_loop.h"
diff --git a/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc b/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc index 3edc36d..5850afc 100644 --- a/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc +++ b/third_party/blink/renderer/modules/mediastream/video_track_adapter.cc
@@ -17,7 +17,6 @@ #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" -#include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "media/base/bind_to_current_loop.h" @@ -40,12 +39,6 @@ STATIC_ONLY(CrossThreadCopier); }; -template <> -struct CrossThreadCopier<gfx::Size> - : public CrossThreadCopierPassThrough<gfx::Size> { - STATIC_ONLY(CrossThreadCopier); -}; - } // namespace WTF namespace blink {
diff --git a/third_party/blink/renderer/modules/nfc/nfc_push_options.idl b/third_party/blink/renderer/modules/nfc/nfc_push_options.idl index c7c78fb5..637eb64f 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_push_options.idl +++ b/third_party/blink/renderer/modules/nfc/nfc_push_options.idl
@@ -10,4 +10,5 @@ NFCPushTarget target = "any"; unrestricted double timeout; // in ms boolean ignoreRead = true; + NDEFCompatibility compatibility = "nfc-forum"; };
diff --git a/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc b/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc index b4c1352..25c3a40 100644 --- a/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc +++ b/third_party/blink/renderer/modules/nfc/nfc_type_converters.cc
@@ -18,6 +18,7 @@ #include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" +using device::mojom::blink::NDEFCompatibility; using device::mojom::blink::NDEFMessage; using device::mojom::blink::NDEFMessagePtr; using device::mojom::blink::NDEFRecord; @@ -213,26 +214,19 @@ const blink::NFCPushOptions* pushOptions) { // https://w3c.github.io/web-nfc/#the-nfcpushoptions-dictionary // Default values for NFCPushOptions dictionary are: - // target = 'any', timeout = Infinity, ignoreRead = true + // target = 'any', timeout = Infinity, ignoreRead = true, + // compatibility = "nfc-forum" NFCPushOptionsPtr pushOptionsPtr = NFCPushOptions::New(); - - if (pushOptions->hasTarget()) { - pushOptionsPtr->target = - blink::StringToNFCPushTarget(pushOptions->target()); - } else { - pushOptionsPtr->target = NFCPushTarget::ANY; - } + pushOptionsPtr->target = blink::StringToNFCPushTarget(pushOptions->target()); + pushOptionsPtr->ignore_read = pushOptions->ignoreRead(); + pushOptionsPtr->compatibility = + blink::StringToNDEFCompatibility(pushOptions->compatibility()); if (pushOptions->hasTimeout()) pushOptionsPtr->timeout = pushOptions->timeout(); else pushOptionsPtr->timeout = std::numeric_limits<double>::infinity(); - if (pushOptions->hasIgnoreRead()) - pushOptionsPtr->ignore_read = pushOptions->ignoreRead(); - else - pushOptionsPtr->ignore_read = true; - return pushOptionsPtr; }
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 3ae30c6..bfb8fa2 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -510,7 +510,6 @@ "exported/web_media_player_client.cc", "exported/web_media_player_encrypted_media_client.cc", "exported/web_media_player_source.cc", - "exported/web_media_recorder_handler.cc", "exported/web_media_stream.cc", "exported/web_media_stream_audio_sink.cc", "exported/web_media_stream_source.cc",
diff --git a/third_party/blink/renderer/platform/exported/platform.cc b/third_party/blink/renderer/platform/exported/platform.cc index a6c398e..8b7723c 100644 --- a/third_party/blink/renderer/platform/exported/platform.cc +++ b/third_party/blink/renderer/platform/exported/platform.cc
@@ -43,7 +43,6 @@ #include "third_party/blink/public/platform/interface_provider.h" #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" #include "third_party/blink/public/platform/web_graphics_context_3d_provider.h" -#include "third_party/blink/public/platform/web_media_recorder_handler.h" #include "third_party/blink/public/platform/web_media_stream_center.h" #include "third_party/blink/public/platform/web_prerendering_support.h" #include "third_party/blink/public/platform/web_rtc_certificate_generator.h" @@ -350,11 +349,6 @@ return nullptr; } -std::unique_ptr<WebMediaRecorderHandler> Platform::CreateMediaRecorderHandler( - scoped_refptr<base::SingleThreadTaskRunner>) { - return nullptr; -} - std::unique_ptr<WebRTCCertificateGenerator> Platform::CreateRTCCertificateGenerator() { return nullptr;
diff --git a/third_party/blink/renderer/platform/exported/web_media_recorder_handler.cc b/third_party/blink/renderer/platform/exported/web_media_recorder_handler.cc deleted file mode 100644 index 2f0e772..0000000 --- a/third_party/blink/renderer/platform/exported/web_media_recorder_handler.cc +++ /dev/null
@@ -1,9 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "third_party/blink/public/platform/web_media_recorder_handler.h" - -// This file just includes WebMediaPlayerClient.h, to make sure -// MSVC compiler does not fail linking with LNK2019 due to unresolved -// constructor/destructor and should be in Source/platform/exported.
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc index 0ca9fb3..1fb261e 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc
@@ -94,6 +94,9 @@ viz::TestSharedImageInterface* SharedImageInterface() override { return GetTestContextProvider()->SharedImageInterface(); } + void CopyVideoFrame(media::PaintCanvasVideoRenderer* video_render, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) override {} private: cc::StubDecodeCache stub_image_decode_cache_;
diff --git a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h index a060336..1b42676 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h +++ b/third_party/blink/renderer/platform/graphics/gpu/drawing_buffer_test_helpers.h
@@ -67,6 +67,9 @@ viz::TestSharedImageInterface* SharedImageInterface() override { return &test_shared_image_interface_; } + void CopyVideoFrame(media::PaintCanvasVideoRenderer* video_render, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) override {} private: cc::StubDecodeCache image_decode_cache_;
diff --git a/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h b/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h index f5c0f6b..cb226ec9 100644 --- a/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h +++ b/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h
@@ -71,6 +71,9 @@ viz::TestSharedImageInterface* SharedImageInterface() override { return &test_shared_image_interface_; } + void CopyVideoFrame(media::PaintCanvasVideoRenderer* video_render, + media::VideoFrame* video_frame, + cc::PaintCanvas* canvas) override {} private: cc::StubDecodeCache stub_image_decode_cache_;
diff --git a/third_party/blink/renderer/platform/heap/heap_page.cc b/third_party/blink/renderer/platform/heap/heap_page.cc index 63c84cd..398a426 100644 --- a/third_party/blink/renderer/platform/heap/heap_page.cc +++ b/third_party/blink/renderer/platform/heap/heap_page.cc
@@ -1467,7 +1467,6 @@ DiscardPages(start_of_gap + sizeof(FreeListEntry), PayloadEnd()); #endif } - return start_of_gap == Payload(); } @@ -1696,6 +1695,7 @@ return nullptr; HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>( object_start_bit_map()->FindHeader(address)); + DCHECK(header->IsValidOrZapped()); if (header->IsFree()) return nullptr; DCHECK_LT(0u, header->GcInfoIndex());
diff --git a/third_party/blink/renderer/platform/heap/member.h b/third_party/blink/renderer/platform/heap/member.h index fe98bdd..fb58e1abc 100644 --- a/third_party/blink/renderer/platform/heap/member.h +++ b/third_party/blink/renderer/platform/heap/member.h
@@ -46,20 +46,15 @@ DCHECK(creation_thread_state_ || !pointer); } } + void CheckPointer(T* pointer) { if (!pointer) return; - // HashTable can store a special value (which is not aligned to the - // allocation granularity) to Member<> to represent a deleted entry. - // Thus we treat a pointer that is not aligned to the granularity - // as a valid pointer. - if (reinterpret_cast<intptr_t>(pointer) % kAllocationGranularity) - return; + ThreadState* current = ThreadState::Current(); + DCHECK(current); if (tracenessConfiguration != TracenessMemberConfiguration::kUntraced) { - ThreadState* current = ThreadState::Current(); - DCHECK(current); - // m_creationThreadState may be null when this is used in a heap + // creation_thread_state_ may be null when this is used in a heap // collection which initialized the Member with memset and the // constructor wasn't called. if (creation_thread_state_) { @@ -72,20 +67,14 @@ } } -#if defined(ADDRESS_SANITIZER) - // TODO(haraken): What we really want to check here is that the pointer - // is a traceable object. In other words, the pointer is either of: - // - // (a) a pointer to the head of an on-heap object. - // (b) a pointer to the head of an on-heap mixin object. - // - // We can check it by calling ThreadHeap::isHeapObjectAlive(pointer), - // but we cannot call it here because it requires to include T.h. - // So we currently only try to implement the check for (a), but do - // not insist that T's definition is in scope. - if (IsFullyDefined<T>::value && !IsGarbageCollectedMixin<T>::value) - HeapObjectHeader::CheckFromPayload(pointer); -#endif // ADDRESS_SANITIZER + if (current->IsSweepingInProgress()) { + // During sweeping the object start bitmap is invalid. Check the header + // when the type is available and not pointing to a mixin. + if (IsFullyDefined<T>::value && !IsGarbageCollectedMixin<T>::value) + HeapObjectHeader::CheckFromPayload(pointer); + } else { + DCHECK(HeapObjectHeader::FromInnerAddress(pointer)); + } } private: @@ -217,6 +206,10 @@ void CheckPointer() { #if DCHECK_IS_ON() + // Should not be called for deleted hash table values. A value can be + // propagated here if a MemberBase containing the deleted value is copied. + if (IsHashTableDeletedValue()) + return; pointer_verifier_.CheckPointer(raw_); #endif // DCHECK_IS_ON() }
diff --git a/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc b/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc index 3f38fc8a..c46bd551 100644 --- a/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc +++ b/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc
@@ -39,6 +39,7 @@ case WebThreadType::kUnspecifiedWorkerThread: case WebThreadType::kTestThread: case WebThreadType::kAudioEncoderThread: + case WebThreadType::kVideoEncoderThread: return scheduling_metrics::ThreadType::kRendererOtherBlinkThread; case WebThreadType::kCount: NOTREACHED();
diff --git a/third_party/blink/renderer/platform/web_thread_type.cc b/third_party/blink/renderer/platform/web_thread_type.cc index 4a4b21d..053cf32 100644 --- a/third_party/blink/renderer/platform/web_thread_type.cc +++ b/third_party/blink/renderer/platform/web_thread_type.cc
@@ -41,6 +41,8 @@ return "test thread"; case WebThreadType::kAudioEncoderThread: return "Audio encoder thread"; + case WebThreadType::kVideoEncoderThread: + return "Video encoder thread"; case WebThreadType::kCount: NOTREACHED(); return nullptr;
diff --git a/third_party/blink/renderer/platform/wtf/cross_thread_copier.h b/third_party/blink/renderer/platform/wtf/cross_thread_copier.h index b80cc66..75ddf96 100644 --- a/third_party/blink/renderer/platform/wtf/cross_thread_copier.h +++ b/third_party/blink/renderer/platform/wtf/cross_thread_copier.h
@@ -57,6 +57,10 @@ template <typename T> class sk_sp; +namespace gfx { +class Size; +} + namespace WTF { template <typename T> @@ -274,6 +278,12 @@ } }; +template <> +struct CrossThreadCopier<gfx::Size> + : public CrossThreadCopierPassThrough<gfx::Size> { + STATIC_ONLY(CrossThreadCopier); +}; + } // namespace WTF #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_CROSS_THREAD_COPIER_H_
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 7cf8fe06..9f1b967b 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -594,8 +594,16 @@ ], 'allowed': [ 'base::data', + # TODO(crbug.com/960665): Remove it once it is replaced with a WTF equivalent. + 'base::queue', + + 'base::SharedMemory', + 'base::StringPiece', + 'base::ThreadTaskRunnerHandle', 'media::.+', 'libopus::.+', + 'libyuv::.+', + 'video_track_recorder::.+', ] }, {
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 091f806..182f8494 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1374,7 +1374,7 @@ crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/dynamic/remove-block-from-content-between-spanners.html [ Failure Crash Timeout ] crbug.com/636993 virtual/layout_ng_experimental/fast/multicol/dynamic/remove-inline-and-spanner-after-spanner-foreignObject.html [ Pass Crash Timeout ] -crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/flowthread-with-floats-destroyed-crash.html [ Crash ] +crbug.com/591099 virtual/layout_ng_experimental/fast/multicol/flowthread-with-floats-destroyed-crash.html [ Crash Pass ] crbug.com/797591 virtual/layout_ng_experimental/fast/multicol/regular-block-becomes-multicol.html [ Failure ] crbug.com/797591 virtual/layout_ng_experimental/fast/multicol/newmulticol/regular-block-becomes-multicol.html [ Failure ] @@ -1873,8 +1873,8 @@ crbug.com/591099 virtual/layout_ng_experimental/fragmentation/auto-scrollbar-shrink-to-fit.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/avoid-break-inside-first-child.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/avoid-break-inside-first-child-nested.html [ Failure ] -crbug.com/591099 virtual/layout_ng_experimental/fragmentation/become-unfragmented-with-lines.html [ Crash ] -crbug.com/591099 virtual/layout_ng_experimental/fragmentation/become-unfragmented-with-unbreakable-blocks.html [ Crash ] +crbug.com/591099 virtual/layout_ng_experimental/fragmentation/become-unfragmented-with-lines.html [ Crash Pass ] +crbug.com/591099 virtual/layout_ng_experimental/fragmentation/become-unfragmented-with-unbreakable-blocks.html [ Crash Pass ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/block-after-float-first-child.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/border-spacing-break-before-unbreakable-row.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/fragmentation/break-in-first-table-row-only.html [ Failure ] @@ -5686,7 +5686,7 @@ # See also crbug.com/907150 crbug.com/667560 http/tests/devtools/console-cross-origin-iframe-logging.js [ Pass Failure Timeout ] -crbug.com/907412 [ Mac10.13 ] external/wpt/domxpath/xml_xpath_runner.html [ Pass Timeout ] +crbug.com/907412 external/wpt/domxpath/xml_xpath_runner.html [ Pass Timeout ] #Sheriff 2018-11-22 crbug.com/907862 [ Mac10.13 ] gamepad/multiple-event-listeners.html [ Pass Failure ] @@ -6245,3 +6245,7 @@ # Flaky on Linux crbug.com/974660 [ Linux ] http/tests/devtools/elements/highlight/highlight-node-vertical-rl.js [ Pass Failure ] + +# Failing on windows with lazy-feedback-allocation feature in V8. See the bug +# for more details. +crbug.com/976587 [ Win ] netinfo/gc-unused-listeners.html [ Pass Failure ]
diff --git a/third_party/blink/web_tests/WebDriverExpectations b/third_party/blink/web_tests/WebDriverExpectations index f57323d..1a6b757 100644 --- a/third_party/blink/web_tests/WebDriverExpectations +++ b/third_party/blink/web_tests/WebDriverExpectations
@@ -3,6 +3,7 @@ # separate runner, run_webdriver_tests.py. Thus this is a separate # expectation file from TestExpectations. # ====== New tests from wpt-importer added here ====== +crbug.com/626703 [ Linux ] external/wpt/webdriver/tests/switch_to_window/alerts.py>>test_retain_tab_modal_status [ Failure ] crbug.com/626703 [ Linux ] external/wpt/webdriver/tests/minimize_window/minimize.py>>test_fully_exit_fullscreen [ Failure ] crbug.com/626703 [ Linux ] external/wpt/webdriver/tests/permissions/set.py>>test_set_to_state[realmSetting2-denied] [ Failure ] crbug.com/626703 [ Linux ] external/wpt/webdriver/tests/perform_actions/pointer_contextmenu.py>>test_control_click[\ue009-ctrlKey] [ Failure ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index 9a917be..3615e8c1 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -151568,6 +151568,9 @@ "html/browsers/browsing-the-web/history-traversal/001-2.html": [ [] ], + "html/browsers/browsing-the-web/history-traversal/api-availability-expected.txt": [ + [] + ], "html/browsers/browsing-the-web/history-traversal/browsing_context_name-0.html": [ [] ], @@ -151616,6 +151619,12 @@ "html/browsers/browsing-the-web/history-traversal/resources/a.html": [ [] ], + "html/browsers/browsing-the-web/history-traversal/resources/api-availability-1.html": [ + [] + ], + "html/browsers/browsing-the-web/history-traversal/resources/api-availability-2.html": [ + [] + ], "html/browsers/browsing-the-web/history-traversal/resources/b.html": [ [] ], @@ -152585,7 +152594,34 @@ "html/browsers/windows/resources/window-opener.html": [ [] ], - "html/cross-origin-opener/new_window_same_site.html.headers": [ + "html/cross-origin-opener/common.sub.js": [ + [] + ], + "html/cross-origin-opener/new_window_null.tentative-expected.txt": [ + [] + ], + "html/cross-origin-opener/new_window_same_origin.tentative-expected.txt": [ + [] + ], + "html/cross-origin-opener/new_window_same_origin.tentative.html.headers": [ + [] + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative-expected.txt": [ + [] + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html.headers": [ + [] + ], + "html/cross-origin-opener/new_window_same_site.tentative-expected.txt": [ + [] + ], + "html/cross-origin-opener/new_window_same_site.tentative.html.headers": [ + [] + ], + "html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html.headers": [ + [] + ], + "html/cross-origin-opener/resources/coop_window.py": [ [] ], "html/cross-origin-opener/resources/postback.sub.html": [ @@ -215778,12 +215814,6 @@ {} ] ], - "element-timing/observe-large-image.html": [ - [ - "element-timing/observe-large-image.html", - {} - ] - ], "element-timing/observe-multiple-images.html": [ [ "element-timing/observe-multiple-images.html", @@ -230087,6 +230117,12 @@ {} ] ], + "html/browsers/browsing-the-web/history-traversal/api-availability.html": [ + [ + "html/browsers/browsing-the-web/history-traversal/api-availability.html", + {} + ] + ], "html/browsers/browsing-the-web/history-traversal/browsing_context_name.html": [ [ "html/browsers/browsing-the-web/history-traversal/browsing_context_name.html", @@ -232131,9 +232167,33 @@ {} ] ], - "html/cross-origin-opener/new_window_same_site.html": [ + "html/cross-origin-opener/new_window_null.tentative.html": [ [ - "html/cross-origin-opener/new_window_same_site.html", + "html/cross-origin-opener/new_window_null.tentative.html", + {} + ] + ], + "html/cross-origin-opener/new_window_same_origin.tentative.html": [ + [ + "html/cross-origin-opener/new_window_same_origin.tentative.html", + {} + ] + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html": [ + [ + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html", + {} + ] + ], + "html/cross-origin-opener/new_window_same_site.tentative.html": [ + [ + "html/cross-origin-opener/new_window_same_site.tentative.html", + {} + ] + ], + "html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html": [ + [ + "html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html", {} ] ], @@ -307181,6 +307241,12 @@ {} ] ], + "webdriver/tests/switch_to_window/alerts.py": [ + [ + "webdriver/tests/switch_to_window/alerts.py", + {} + ] + ], "webdriver/tests/switch_to_window/switch.py": [ [ "webdriver/tests/switch_to_window/switch.py", @@ -312611,7 +312677,7 @@ "testharness" ], "IndexedDB/idbfactory_open2.htm": [ - "e4d54ee0a1318211a84a51dfb742230bcbc83c14", + "ba72b78eea0c894c22d4a10b4e6a1dfc863ba3ce", "testharness" ], "IndexedDB/idbfactory_open3.htm": [ @@ -312619,11 +312685,11 @@ "testharness" ], "IndexedDB/idbfactory_open4.htm": [ - "15ca666b816a0b6f574907e92c98830940f996e9", + "9571d825be9d05b747acd2d76ce1e5346ce70df1", "testharness" ], "IndexedDB/idbfactory_open5.htm": [ - "d9460bb7eda403f8374a4dd8d40f2f0a40386fb1", + "eef37efcfcbb6a372c9b92f39b32822c565eba56", "testharness" ], "IndexedDB/idbfactory_open6.htm": [ @@ -317907,7 +317973,7 @@ "testharness" ], "content-security-policy/generic/generic-0_2.html": [ - "ecfeaf66cb590ed0e882ef23280d3907a56a1be3", + "4f295441cdb728152bb5a6be182e577a986242bc", "testharness" ], "content-security-policy/generic/generic-0_2_2.sub.html": [ @@ -317919,15 +317985,15 @@ "testharness" ], "content-security-policy/generic/generic-0_8.sub.html": [ - "79edff25e31a40a0bc9e262416c606712380a59b", + "a9a76c825e58f1fa61da75a285b4b2abf4707427", "testharness" ], "content-security-policy/generic/generic-0_8_1.sub.html": [ - "e8ce23415f7aca1a3b5ccfc6fc637730eee8d835", + "a0b74160c4ffe1ba1f1513cd3ed0df8835d551f2", "testharness" ], "content-security-policy/generic/generic-0_9.sub.html": [ - "150876c917d4b1db47e8cc7faefee6d7ad709aa6", + "f7f7f0db25696b88e9a56fc4da3b209ea5c5d6fb", "testharness" ], "content-security-policy/generic/negativeTests.js": [ @@ -317935,7 +318001,7 @@ "support" ], "content-security-policy/generic/no-default-src.sub.html": [ - "5f5c8cb369b41fcdffb1c199608d5c36404ba4d3", + "9a89ec05ad00f3122680cc7aace96999610bf195", "testharness" ], "content-security-policy/generic/no-default-src.sub.html.sub.headers": [ @@ -317963,7 +318029,7 @@ "support" ], "content-security-policy/generic/positiveTest.js": [ - "63c99919623e396a41870273e35e3e8999a712f0", + "15053e055d6fb085556aea01507edf21f14f347a", "support" ], "content-security-policy/generic/support/304-response.py": [ @@ -318751,7 +318817,7 @@ "support" ], "content-security-policy/reporting/report-only-in-meta.sub.html": [ - "04b968807c60ce7b50d1811bcd79db74c8b60279", + "574c218b427d9ba64e61244b1a189d3504493f82", "testharness" ], "content-security-policy/reporting/report-only-in-meta.sub.html.sub.headers": [ @@ -318787,7 +318853,7 @@ "support" ], "content-security-policy/reporting/report-uri-from-child-frame.html": [ - "92b1e1be5438f43f44d9f29e34283b51ec8d9f70", + "1be496194b637b74efdfc6c3dcc27dd1e6dd896d", "testharness" ], "content-security-policy/reporting/report-uri-from-inline-javascript.html": [ @@ -319371,7 +319437,7 @@ "support" ], "content-security-policy/script-src/support/worker-importscripts.js": [ - "0204de32cf19f32232d4e1bc79d4b8defa82932d", + "0ae53e7877a6d1d218ba67bb66849294a3912fa8", "support" ], "content-security-policy/script-src/support/worker-importscripts.js.sub.headers": [ @@ -319543,7 +319609,7 @@ "testharness" ], "content-security-policy/style-src/inline-style-allowed-while-cloning-objects.sub.html": [ - "7fdd5f6fb0c5bc50fe1fe84715c785d1d5380feb", + "7c95f47aff880d5818331b5020dacf39a5fc6839", "testharness" ], "content-security-policy/style-src/inline-style-allowed.sub.html": [ @@ -320315,7 +320381,7 @@ "testharness" ], "cookie-store/serviceworker_cookieStore_subscriptions.js": [ - "9913bf3aa2c1d091e882b3dc9d8e23f55a1e26ed", + "225e58266e2e0210299f9defef1d28eaeeb9403c", "support" ], "cookie-store/serviceworker_cookieStore_subscriptions.tentative.https.html": [ @@ -320323,7 +320389,7 @@ "testharness" ], "cookie-store/serviceworker_cookieStore_subscriptions_basic.js": [ - "08eef8498023573b855f4074f8af66da68f95ae9", + "4a5ee5eed962f65c21ad794d02e7452ff56046a0", "support" ], "cookie-store/serviceworker_cookieStore_subscriptions_basic.tentative.https.html": [ @@ -320331,7 +320397,7 @@ "testharness" ], "cookie-store/serviceworker_cookieStore_subscriptions_empty.js": [ - "d355055d08aef8f570c82f1a2473109f3a5b1ff8", + "de521caddd8763b1d30e1c0bfcf2feea98e7bc06", "support" ], "cookie-store/serviceworker_cookieStore_subscriptions_empty.tentative.https.html": [ @@ -320339,7 +320405,7 @@ "testharness" ], "cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.js": [ - "1a5b67df35320eff43877c7c20822d8110bfc4ca", + "8784af7e6e80824711a9e20e39af33617b0a87b7", "support" ], "cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.tentative.https.html": [ @@ -320347,7 +320413,7 @@ "testharness" ], "cookie-store/serviceworker_cookieStore_subscriptions_mismatch.js": [ - "d7230051234708ce047ea880cd3092d535c35e03", + "12759a2e3ae9c40cb301482f093fb5b30b63cfbc", "support" ], "cookie-store/serviceworker_cookieStore_subscriptions_mismatch.tentative.https.html": [ @@ -407170,10 +407236,6 @@ "0c67130dcc356ee7da9b3e2e10127352af7d169e", "testharness" ], - "element-timing/observe-large-image.html": [ - "e907452d82f2ce7a603e4728faa2062f55f4cce8", - "testharness" - ], "element-timing/observe-multiple-images.html": [ "8a5fa0bb89a31f1bb1d1a277edb1b8102680a4bf", "testharness" @@ -413998,6 +414060,14 @@ "8db1d2788c04b0fb85f79cc023969b2ee4e4079f", "testharness" ], + "html/browsers/browsing-the-web/history-traversal/api-availability-expected.txt": [ + "8676e6ed8abab677631fa87c21b6ac770422d669", + "support" + ], + "html/browsers/browsing-the-web/history-traversal/api-availability.html": [ + "2f7d3fafdf7da02173c89c345879cdf972540485", + "testharness" + ], "html/browsers/browsing-the-web/history-traversal/browsing_context_name-0.html": [ "5cbab71a5eaac4fd789a470cca2538225589a497", "support" @@ -414114,6 +414184,14 @@ "55b73e1153593683092a3a331e815bca5ba23da2", "support" ], + "html/browsers/browsing-the-web/history-traversal/resources/api-availability-1.html": [ + "2c311687500942a9bde2860b072513f61408e4ef", + "support" + ], + "html/browsers/browsing-the-web/history-traversal/resources/api-availability-2.html": [ + "420e5092bc5b3f724fd69b7d56165bab48032519", + "support" + ], "html/browsers/browsing-the-web/history-traversal/resources/b.html": [ "8f2fc900ddac31e8463cf31bd6821e4cd8276da4", "support" @@ -416706,20 +416784,72 @@ "7407248ffe9fe3da977275c2192e31e3db9fc8a9", "testharness" ], - "html/cross-origin-opener/new_window_same_site.html": [ - "b75f7ff7a646addffca73e7fc47539e88293d2ed", + "html/cross-origin-opener/common.sub.js": [ + "a73a95aba8625230b84e917eba6b469be5459cc8", + "support" + ], + "html/cross-origin-opener/new_window_null.tentative-expected.txt": [ + "23c0e6d998e1122db6d14be1cb0967e32611e33b", + "support" + ], + "html/cross-origin-opener/new_window_null.tentative.html": [ + "35a42fd2f0963f886324ac7ca01d5b45cdc1588e", "testharness" ], - "html/cross-origin-opener/new_window_same_site.html.headers": [ + "html/cross-origin-opener/new_window_same_origin.tentative-expected.txt": [ + "89b66e08c1e2a6f5b6930eae9e2b6033b75a0419", + "support" + ], + "html/cross-origin-opener/new_window_same_origin.tentative.html": [ + "6bbb37cafca07cec641e925b9d06d803b3cf2ae8", + "testharness" + ], + "html/cross-origin-opener/new_window_same_origin.tentative.html.headers": [ + "46ad58d83bf6e98913ca4c564b7acb8f19fa0093", + "support" + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative-expected.txt": [ + "c3c202582ed3b12ff85fd5585042eba57a5302f8", + "support" + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html": [ + "bbd55130d7a903bf24fb8d2e3660131009d4b42d", + "testharness" + ], + "html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html.headers": [ + "a19f4400cea33a60c99807330704a23ee363b146", + "support" + ], + "html/cross-origin-opener/new_window_same_site.tentative-expected.txt": [ + "45625379e26a59677cec01f93288723a90044848", + "support" + ], + "html/cross-origin-opener/new_window_same_site.tentative.html": [ + "e1efac12d02e26ca4db9f43f660155e9d916b531", + "testharness" + ], + "html/cross-origin-opener/new_window_same_site.tentative.html.headers": [ "34bd099a302f893f92586241ea38aac812bf28d0", "support" ], + "html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html": [ + "d81506f434b70d9b66d0f8aa41d845c1541ae8a8", + "testharness" + ], + "html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html.headers": [ + "ab7b28948150ff64101ef080b0d9c7cc9a6a34d2", + "support" + ], + "html/cross-origin-opener/resources/coop_window.py": [ + "b24d6d55a9a368057376436c0e2692a9ed27a1da", + "support" + ], "html/cross-origin-opener/resources/postback.sub.html": [ "ee08bab4d55ed45523ae862f65a41b29046fba69", "support" ], "html/cross-origin-opener/resources/window.sub.html": [ - "7c72f87c3ddd8996991a87721076a95a85c272d9", + "524efe2588d08e77419cda38319f4b1fbcfdea3c", "support" ], "html/cross-origin-opener/resources/window.sub.html.headers": [ @@ -468383,7 +468513,7 @@ "support" ], "tools/serve/serve.py": [ - "1fc617474a2374de7784e557445d3d00f8f870e6", + "45634934c37b5b839275361d5ffc8b223d9f922a", "support" ], "tools/serve/test_functional.py": [ @@ -476699,7 +476829,7 @@ "support" ], "webdriver/tests/accept_alert/accept.py": [ - "a111f103bf142b4041f2a8d1c6017de79b54560e", + "d8211841d5c799b6f85d46b71bd3eb3a7ab99f52", "wdspec" ], "webdriver/tests/add_cookie/__init__.py": [ @@ -476783,7 +476913,7 @@ "support" ], "webdriver/tests/dismiss_alert/dismiss.py": [ - "c0efc38b47fd8b5d3d9fcf89a4dd803a9d38ec2f", + "bcff3a32af34b95bb23db6ad93770224226b7633", "wdspec" ], "webdriver/tests/element_clear/__init__.py": [ @@ -477019,7 +477149,7 @@ "support" ], "webdriver/tests/get_alert_text/get.py": [ - "2327abce3a4d266f0d14d8929c2ba58fedd3e441", + "d6fdda2d1ed08ecceb5863d78ce915c19d4846fb", "wdspec" ], "webdriver/tests/get_current_url/__init__.py": [ @@ -477566,6 +477696,10 @@ "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", "support" ], + "webdriver/tests/switch_to_window/alerts.py": [ + "e3a3342449912dafafaac1bec7bf90f98b29c44c", + "wdspec" + ], "webdriver/tests/switch_to_window/switch.py": [ "907be66a149e8196c87760544140636d9625bbb9", "wdspec"
diff --git a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open2.htm b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open2.htm index e4d54ee..ba72b78e 100644 --- a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open2.htm +++ b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open2.htm
@@ -6,12 +6,13 @@ <script src=support.js></script> <script> - var open_rq = createdb(async_test(), 'database_name', 13); + var database_name = document.location + '-database_name'; + var open_rq = createdb(async_test(), database_name, 13); open_rq.onupgradeneeded = function(e) {}; open_rq.onsuccess = function(e) { var db = e.target.result; - assert_equals(db.name, 'database_name', 'db.name'); + assert_equals(db.name, database_name, 'db.name'); assert_equals(db.version, 13, 'db.version'); this.done(); }
diff --git a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open4.htm b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open4.htm index 15ca666..9571d825 100644 --- a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open4.htm +++ b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open4.htm
@@ -6,7 +6,7 @@ <script src=support.js></script> <script> - var open_rq = createdb(async_test(), 'database_name'); + var open_rq = createdb(async_test(), document.location + '-database_name'); open_rq.onupgradeneeded = function(e) { assert_equals(e.target.result.version, 1, "db.version");
diff --git a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open5.htm b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open5.htm index d9460bb7..eef37ef 100644 --- a/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open5.htm +++ b/third_party/blink/web_tests/external/wpt/IndexedDB/idbfactory_open5.htm
@@ -6,7 +6,7 @@ <script src=support.js></script> <script> - var open_rq = createdb(async_test(), 'database_name'); + var open_rq = createdb(async_test(), document.location + '-database_name'); open_rq.onupgradeneeded = function() {}; open_rq.onsuccess = function(e) {
diff --git a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions.js b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions.js index 9913bf3a..225e582 100644 --- a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions.js +++ b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions.js
@@ -9,12 +9,18 @@ // The subscribeToChanges calls are not done in parallel on purpose. Having // multiple in-flight requests introduces failure modes aside from the // cookie change logic that this test aims to cover. - await cookieStore.subscribeToChanges([ - { name: 'cookie-name1', matchType: 'equals', url: '/scope/path1' }]); - await cookieStore.subscribeToChanges([ - { }, // Test the default values for subscription properties. - { name: 'cookie-prefix', matchType: 'starts-with' }, - ]); + try { + await cookieStore.subscribeToChanges([ + { name: 'cookie-name1', matchType: 'equals', url: '/scope/path1' }]); + await cookieStore.subscribeToChanges([ + { }, // Test the default values for subscription properties. + { name: 'cookie-prefix', matchType: 'starts-with' }, + ]); + + // If the worker enters the "redundant" state, the UA may terminate it + // before all tests have been reported to the client. Stifle errors in + // order to avoid this and ensure all tests are consistently reported. + } catch (err) {} })()); });
diff --git a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_basic.js b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_basic.js index 08eef8498..4a5ee5ee 100644 --- a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_basic.js +++ b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_basic.js
@@ -6,8 +6,14 @@ self.addEventListener('install', (event) => { event.waitUntil((async () => { - await cookieStore.subscribeToChanges([ - { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + try { + await cookieStore.subscribeToChanges([ + { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + + // If the worker enters the "redundant" state, the UA may terminate it + // before all tests have been reported to the client. Stifle errors in + // order to avoid this and ensure all tests are consistently reported. + } catch (err) {} })()); });
diff --git a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_empty.js b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_empty.js index d355055..de521ca 100644 --- a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_empty.js +++ b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_empty.js
@@ -6,7 +6,13 @@ self.addEventListener('install', (event) => { event.waitUntil((async () => { - await cookieStore.subscribeToChanges([]); + try { + await cookieStore.subscribeToChanges([]); + + // If the worker enters the "redundant" state, the UA may terminate it + // before all tests have been reported to the client. Stifle errors in + // order to avoid this and ensure all tests are consistently reported. + } catch (err) {} })()); });
diff --git a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.js b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.js index 1a5b67df..8784af7 100644 --- a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.js +++ b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_eventhandler_attribute.js
@@ -6,8 +6,14 @@ self.addEventListener('install', (event) => { event.waitUntil((async () => { - await cookieStore.subscribeToChanges([ - { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + try { + await cookieStore.subscribeToChanges([ + { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + + // If the worker enters the "redundant" state, the UA may terminate it + // before all tests have been reported to the client. Stifle errors in + // order to avoid this and ensure all tests are consistently reported. + } catch (err) {} })()); });
diff --git a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_mismatch.js b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_mismatch.js index d723005..12759a2 100644 --- a/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_mismatch.js +++ b/third_party/blink/web_tests/external/wpt/cookie-store/serviceworker_cookieStore_subscriptions_mismatch.js
@@ -6,8 +6,14 @@ self.addEventListener('install', (event) => { event.waitUntil((async () => { - await cookieStore.subscribeToChanges([ - { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + try { + await cookieStore.subscribeToChanges([ + { name: 'cookie-name', matchType: 'equals', url: '/scope/path' }]); + + // If the worker enters the "redundant" state, the UA may terminate it + // before all tests have been reported to the client. Stifle errors in + // order to avoid this and ensure all tests are consistently reported. + } catch (err) {} })()); });
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability-expected.txt b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability-expected.txt new file mode 100644 index 0000000..8676e6ed --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL API availability following history traversal Cannot read property 'history' of null +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability.html new file mode 100644 index 0000000..2f7d3fa --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/api-availability.html
@@ -0,0 +1,22 @@ +<!doctype html> +<title>API availability following history traversal</title> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<p>Test requires popup blocker disabled</p> +<div id=log></div> +<script> +var t = async_test(); +var hasNavigated = false; +var child; +t.step(function() { + child = window.open("resources/api-availability-1.html"); + t.add_cleanup(function() { + child.close(); + }); +}); +navigate = t.step_func(function() { + hasNavigated = true; + child.location = child.location.href.replace("api-availability-1.html", "api-availability-2.html"); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-1.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-1.html new file mode 100644 index 0000000..2c311687 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-1.html
@@ -0,0 +1,31 @@ +<!doctype html> +<title>API availability following history traversal - 1</title> +<script> +var controller = opener; +var t = controller.t; +var assert_not_equals = controller.assert_not_equals; + +t.step(function() { + // If this document is discarded as a result of navigation, then this script + // will be executed a second time. The semantics this test intends to verify + // cannot be observed under these conditions, the discarding is not itself a + // violation. Silently pass the test in that case. + if (controller.hasNavigated) { + t.done(); + return; + } + + t.step_timeout(function() { + assert_not_equals(window.history, null, 'history'); + assert_not_equals(window.localStorage, null, 'localStorage'); + assert_not_equals(window.location, null, 'location'); + assert_not_equals(window.navigator, null, 'navigator'); + assert_not_equals(window.opener, null, 'opener'); + assert_not_equals(window.sessionStorage, null, 'sessionStorage'); + + t.done(); + }, 1000); + + controller.navigate(); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-2.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-2.html new file mode 100644 index 0000000..420e5092b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/history-traversal/resources/api-availability-2.html
@@ -0,0 +1,3 @@ +<!doctype html> +<title>API availability following history traversal - 2</title> +<body onload="history.back()"></body>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/common.sub.js b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/common.sub.js new file mode 100644 index 0000000..a73a95ab --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/common.sub.js
@@ -0,0 +1,28 @@ +const SAME_ORIGIN = {origin: get_host_info().HTTP_ORIGIN, name: "SAME_ORIGIN"}; +const SAME_SITE = {origin: get_host_info().HTTP_REMOTE_ORIGIN, name: "SAME_SITE"}; +const CROSS_ORIGIN = {origin: get_host_info().HTTP_NOTSAMESITE_ORIGIN, name: "CROSS_ORIGIN"} + +function coop_test(t, host, coop, channelName, hasOpener) { + let bc = new BroadcastChannel(channelName); + bc.onmessage = t.step_func_done((event) => { + let payload = event.data; + assert_equals(payload.name, hasOpener ? channelName : ""); + assert_equals(payload.opener, hasOpener); + }); + + let w = window.open(`${host.origin}/html/cross-origin-opener/resources/coop_window.py?path=window.sub.html&coop=${escape(coop)}&channel=${channelName}`, channelName); + + // w will be closed by its postback iframe. When out of process, + // window.close() does not work. + t.add_cleanup(() => w.close()); +} + +function run_coop_tests(mainTest, testArray) { + for (let test of tests) { + async_test(t => { + coop_test(t, test[0], test[1], + `${mainTest}_to_${test[0].name}_${test[1].replace(/ /g,"-")}`, + test[2]); + }, `${mainTest} document opening popup to ${test[0].origin} with COOP: "${test[1]}"`); + } +}
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative-expected.txt new file mode 100644 index 0000000..23c0e6d9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS null document opening popup to http://web-platform.test:8001 with COOP: "" +PASS null document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL null document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "null_to_SAME_ORIGIN_same-site" +FAIL null document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_SAME_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL null document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "null_to_SAME_ORIGIN_same-origin" +FAIL null document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS null document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS null document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL null document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "null_to_SAME_SITE_same-site" +FAIL null document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_SAME_SITE_same-site-unsafe-allow-outgoing" +FAIL null document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "null_to_SAME_SITE_same-origin" +FAIL null document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS null document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS null document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL null document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "null_to_CROSS_ORIGIN_same-site" +FAIL null document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL null document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "null_to_CROSS_ORIGIN_same-origin" +FAIL null document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "null_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative.html new file mode 100644 index 0000000..35a42fd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_null.tentative.html
@@ -0,0 +1,38 @@ +<!doctype html> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src="/common/get-host-info.sub.js"></script> + +<script src="common.sub.js"></script> + +<div id=log></div> +<script> + +let tests = [ + // popup Origin, popup COOP, expect opener + [SAME_ORIGIN, "", true], + [SAME_ORIGIN, "jibberish", true], + [SAME_ORIGIN, "same-site", false], + [SAME_ORIGIN, "same-site unsafe-allow-outgoing", false], + [SAME_ORIGIN, "same-origin", false], + [SAME_ORIGIN, "same-origin unsafe-allow-outgoing", false], + + [SAME_SITE, "", true], + [SAME_SITE, "jibberish", true], + [SAME_SITE, "same-site", false], + [SAME_SITE, "same-site unsafe-allow-outgoing", false], + [SAME_SITE, "same-origin", false], + [SAME_SITE, "same-origin unsafe-allow-outgoing", false], + + [CROSS_ORIGIN, "", true], + [CROSS_ORIGIN, "jibberish", true], + [CROSS_ORIGIN, "same-site", false], + [CROSS_ORIGIN, "same-site unsafe-allow-outgoing", false], + [CROSS_ORIGIN, "same-origin", false], + [CROSS_ORIGIN, "same-origin unsafe-allow-outgoing", false], +]; + +run_coop_tests("null", tests); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative-expected.txt new file mode 100644 index 0000000..89b66e0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +FAIL same-origin document opening popup to http://web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-origin_to_SAME_ORIGIN_" +FAIL same-origin document opening popup to http://web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-origin_to_SAME_ORIGIN_jibberish" +FAIL same-origin document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_to_SAME_ORIGIN_same-site" +FAIL same-origin document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_SAME_ORIGIN_same-site-unsafe-allow-outgoing" +PASS same-origin document opening popup to http://web-platform.test:8001 with COOP: "same-origin" +FAIL same-origin document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-origin_to_SAME_SITE_" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-origin_to_SAME_SITE_jibberish" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_to_SAME_SITE_same-site" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_SAME_SITE_same-site-unsafe-allow-outgoing" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-origin_to_SAME_SITE_same-origin" +FAIL same-origin document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_jibberish" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_same-site" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_same-origin" +FAIL same-origin document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html new file mode 100644 index 0000000..6bbb37c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html
@@ -0,0 +1,38 @@ +<!doctype html> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src="/common/get-host-info.sub.js"></script> + +<script src="common.sub.js"></script> + +<div id=log></div> +<script> + +let tests = [ + // popup Origin, popup COOP, expect opener + [SAME_ORIGIN, "", false], + [SAME_ORIGIN, "jibberish", false], + [SAME_ORIGIN, "same-site", false], + [SAME_ORIGIN, "same-site unsafe-allow-outgoing", false], + [SAME_ORIGIN, "same-origin", true], + [SAME_ORIGIN, "same-origin unsafe-allow-outgoing", false], + + [SAME_SITE, "", false], + [SAME_SITE, "jibberish", false], + [SAME_SITE, "same-site", false], + [SAME_SITE, "same-site unsafe-allow-outgoing", false], + [SAME_SITE, "same-origin", false], + [SAME_SITE, "same-origin unsafe-allow-outgoing", false], + + [CROSS_ORIGIN, "", false], + [CROSS_ORIGIN, "jibberish", false], + [CROSS_ORIGIN, "same-site", false], + [CROSS_ORIGIN, "same-site unsafe-allow-outgoing", false], + [CROSS_ORIGIN, "same-origin", false], + [CROSS_ORIGIN, "same-origin unsafe-allow-outgoing", false], +]; + +run_coop_tests("same-origin", tests); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html.headers b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html.headers new file mode 100644 index 0000000..46ad58d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin.tentative.html.headers
@@ -0,0 +1 @@ +Cross-Origin-Opener-Policy: same-origin
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..c3c2025 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_SITE_same-site" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_SITE_same-site-unsafe-allow-outgoing" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-origin_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-origin_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html new file mode 100644 index 0000000..bbd5513 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html
@@ -0,0 +1,38 @@ +<!doctype html> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src="/common/get-host-info.sub.js"></script> + +<script src="common.sub.js"></script> + +<div id=log></div> +<script> + +let tests = [ + // popup Origin, popup COOP, expect opener + [SAME_ORIGIN, "", true], + [SAME_ORIGIN, "jibberish", true], + [SAME_ORIGIN, "same-site", false], + [SAME_ORIGIN, "same-site unsafe-allow-outgoing", false], + [SAME_ORIGIN, "same-origin", false], + [SAME_ORIGIN, "same-origin unsafe-allow-outgoing", true], + + [SAME_SITE, "", true], + [SAME_SITE, "jibberish", true], + [SAME_SITE, "same-site", false], + [SAME_SITE, "same-site unsafe-allow-outgoing", false], + [SAME_SITE, "same-origin", false], + [SAME_SITE, "same-origin unsafe-allow-outgoing", false], + + [CROSS_ORIGIN, "", true], + [CROSS_ORIGIN, "jibberish", true], + [CROSS_ORIGIN, "same-site", false], + [CROSS_ORIGIN, "same-site unsafe-allow-outgoing", false], + [CROSS_ORIGIN, "same-origin", false], + [CROSS_ORIGIN, "same-origin unsafe-allow-outgoing", false], +]; + +run_coop_tests("same-origin_unsafe-allow-outgoing", tests); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html.headers b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html.headers new file mode 100644 index 0000000..a19f4400 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_origin_unsafe_allow_outgoing.tentative.html.headers
@@ -0,0 +1 @@ +Cross-Origin-Opener-Policy: same-origin unsafe-allow-outgoing
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.html deleted file mode 100644 index b75f7ff..0000000 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!doctype html> -<meta charset=utf-8> -<script src=/resources/testharness.js></script> -<script src=/resources/testharnessreport.js></script> -<script src="/common/get-host-info.sub.js"></script> - -<script> - -const CHANNEL_NAME = "new_window_same_site"; - -async_test(t => { - let w = window.open(`${get_host_info().HTTP_REMOTE_ORIGIN}/html/cross-origin-opener/resources/window.sub.html?channel=${CHANNEL_NAME}`, "window_name", "height=200,width=250"); - - // w will be closed by its postback iframe. When out of process, - // window.close() does not work. - t.add_cleanup(() => w.close()); - - let bc = new BroadcastChannel(CHANNEL_NAME); - bc.onmessage = t.step_func_done((event) => { - let payload = event.data; - assert_equals(payload.name, "window_name"); - assert_equals(payload.opener, true); - }); -}, "same-site policy works"); - -</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative-expected.txt new file mode 100644 index 0000000..4562537 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +FAIL same-site document opening popup to http://web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-site_to_SAME_ORIGIN_" +FAIL same-site document opening popup to http://web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-site_to_SAME_ORIGIN_jibberish" +PASS same-site document opening popup to http://web-platform.test:8001 with COOP: "same-site" +FAIL same-site document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_SAME_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_to_SAME_ORIGIN_same-origin" +FAIL same-site document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +FAIL same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-site_to_SAME_SITE_" +FAIL same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-site_to_SAME_SITE_jibberish" +PASS same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" +FAIL same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_SAME_SITE_same-site-unsafe-allow-outgoing" +FAIL same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_to_SAME_SITE_same-origin" +FAIL same-site document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_jibberish" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_same-site" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_same-origin" +FAIL same-site document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative.html new file mode 100644 index 0000000..e1efac1 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative.html
@@ -0,0 +1,38 @@ +<!doctype html> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src="/common/get-host-info.sub.js"></script> + +<script src="common.sub.js"></script> + +<div id=log></div> +<script> + +let tests = [ + // popup Origin, popup COOP, expect opener + [SAME_ORIGIN, "", false], + [SAME_ORIGIN, "jibberish", false], + [SAME_ORIGIN, "same-site", true], + [SAME_ORIGIN, "same-site unsafe-allow-outgoing", false], + [SAME_ORIGIN, "same-origin", false], + [SAME_ORIGIN, "same-origin unsafe-allow-outgoing", false], + + [SAME_SITE, "", false], + [SAME_SITE, "jibberish", false], + [SAME_SITE, "same-site", true], + [SAME_SITE, "same-site unsafe-allow-outgoing", false], + [SAME_SITE, "same-origin", false], + [SAME_SITE, "same-origin unsafe-allow-outgoing", false], + + [CROSS_ORIGIN, "", false], + [CROSS_ORIGIN, "jibberish", false], + [CROSS_ORIGIN, "same-site", false], + [CROSS_ORIGIN, "same-site unsafe-allow-outgoing", false], + [CROSS_ORIGIN, "same-origin", false], + [CROSS_ORIGIN, "same-origin unsafe-allow-outgoing", false], +]; + +run_coop_tests("same-site", tests); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.html.headers b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative.html.headers similarity index 100% rename from third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.html.headers rename to third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site.tentative.html.headers
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html new file mode 100644 index 0000000..d81506f4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html
@@ -0,0 +1,38 @@ +<!doctype html> +<meta charset=utf-8> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script src="/common/get-host-info.sub.js"></script> + +<script src="common.sub.js"></script> + +<div id=log></div> +<script> + +let tests = [ + // popup Origin, popup COOP, expect opener + [SAME_ORIGIN, "", true], + [SAME_ORIGIN, "jibberish", true], + [SAME_ORIGIN, "same-site", false], + [SAME_ORIGIN, "same-site unsafe-allow-outgoing", true], + [SAME_ORIGIN, "same-origin", false], + [SAME_ORIGIN, "same-origin unsafe-allow-outgoing", false], + + [SAME_SITE, "", true], + [SAME_SITE, "jibberish", true], + [SAME_SITE, "same-site", false], + [SAME_SITE, "same-site unsafe-allow-outgoing", true], + [SAME_SITE, "same-origin", false], + [SAME_SITE, "same-origin unsafe-allow-outgoing", false], + + [CROSS_ORIGIN, "", true], + [CROSS_ORIGIN, "jibberish", true], + [CROSS_ORIGIN, "same-site", false], + [CROSS_ORIGIN, "same-site unsafe-allow-outgoing", false], + [CROSS_ORIGIN, "same-origin", false], + [CROSS_ORIGIN, "same-origin unsafe-allow-outgoing", false], +]; + +run_coop_tests("same-site_unsafe-allow-outgoing", tests); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html.headers b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html.headers new file mode 100644 index 0000000..ab7b289 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative.html.headers
@@ -0,0 +1 @@ +Cross-Origin-Opener-Policy: same-site unsafe-allow-outgoing
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/coop_window.py b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/coop_window.py new file mode 100644 index 0000000..b24d6d55 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/coop_window.py
@@ -0,0 +1,10 @@ +import urllib +import os.path + +def main(request, response): + coop = request.GET.first('coop') + if coop: + response.headers.set('Cross-Origin-Opener-Policy', urllib.unquote(coop)) + + path = os.path.join(os.path.dirname(__file__), request.GET.first('path')) + response.content = open(path, mode='rb').read()
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/window.sub.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/window.sub.html index 7c72f87..524efe2 100644 --- a/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/window.sub.html +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-opener/resources/window.sub.html
@@ -2,17 +2,17 @@ <meta charset=utf-8> <script src="/common/get-host-info.sub.js"></script> -<div id="status"> </div> <script type="text/javascript"> - let iframe = document.createElement("iframe"); - iframe.onload = () => { - let payload = { name: self.name, opener: !!self.opener }; - iframe.contentWindow.postMessage(payload, "*"); - }; - let channelName = new URL(location).searchParams.get("channel"); - iframe.src = `${get_host_info().HTTP_ORIGIN}/html/cross-origin-opener/resources/postback.sub.html?channel=${channelName}`; - document.body.appendChild(iframe); - + window.addEventListener('load', function() { + let iframe = document.createElement("iframe"); + iframe.onload = () => { + let payload = { name: self.name, opener: !!self.opener }; + iframe.contentWindow.postMessage(payload, "*"); + }; + let channelName = new URL(location).searchParams.get("channel"); + iframe.src = `${get_host_info().HTTP_ORIGIN}/html/cross-origin-opener/resources/postback.sub.html?channel=${channelName}`; + document.body.appendChild(iframe); + }); </script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/META.yml b/third_party/blink/web_tests/external/wpt/std-toast/META.yml new file mode 100644 index 0000000..c54357a0 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/META.yml
@@ -0,0 +1,5 @@ +spec: https://github.com/jackbsteinberg/std-toast +suggested_reviewers: + - domenic + - fergald + - jackbsteinberg
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/attributes.html b/third_party/blink/web_tests/external/wpt/std-toast/attributes.html new file mode 100644 index 0000000..9bfc65c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/attributes.html
@@ -0,0 +1,116 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Toast: attribute tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<main></main> + +<script type="module"> +import { testToastElement, assertToastShown, assertToastNotShown, testToastElementAsync } from './resources/helpers.js'; + +testToastElement((toast) => { + toast.setAttribute('open', ''); + assertToastShown(toast); +}, 'setting `open` on a hidden toast shows the toast'); + +testToastElement((toast) => { + toast.setAttribute('open', false); + assertToastShown(toast); +}, 'setting `open` to false on a hidden toast shows the toast, because of string conversion'); + +testToastElement((toast) => { + toast.show(); + toast.setAttribute('open', 'test'); + assertToastShown(toast); +}, 'setting `open` on a shown toast does nothing'); + +testToastElement((toast) => { + toast.show(); + toast.setAttribute('open', 'test'); + toast.setAttribute('open', 'test'); + assertToastShown(toast); +}, 'resetting `open` on a shown toast does nothing'); + +testToastElement((toast) => { + toast.show(); + toast.setAttribute('open', false); + assertToastShown(toast); +}, 'setting `open` to false on a shown toast does nothing, because of string conversion'); + +testToastElement((toast) => { + toast.show(); + toast.removeAttribute('open'); + assertToastNotShown(toast); +}, 'removing `open` hides the toast'); + +testToastElement((toast) => { + toast.show(); + assert_true(toast.hasAttribute('open')); +}, 'showing the toast adds open attribute'); + +testToastElement((toast) => { + toast.show(); + toast.hide(); + assert_false(toast.hasAttribute('open')); +}, 'hiding the toast removes open attribute'); + +testToastElement((toast) => { + toast.toggleAttribute('open'); + assert_true(toast.hasAttribute('open')); +}, 'toggling `open` on a hidden toast sets the open attribute'); + +testToastElement((toast) => { + toast.toggleAttribute('open'); + toast.toggleAttribute('open'); + assert_false(toast.hasAttribute('open')); +}, 'toggling `open` twice leaves the toast with no open attribute'); + +testToastElement((toast) => { + assert_false(toast.open); +}, 'the `toast.open` boolean is false for a hidden toast'); + +testToastElement((toast) => { + toast.show(); + assert_true(toast.open); +}, 'the `toast.open` boolean is true for a shown toast'); + +testToastElement((toast) => { + toast.open = true; + assertToastShown(toast); + assert_equals(toast.getAttribute('open'), ''); +}, 'setting `toast.open` to true on a hidden toast will show the toast'); + +testToastElement((toast) => { + toast.show(); + toast.open = false; + assertToastNotShown(toast); +}, 'setting `toast.open` to false on a shown toast will hide the toast'); + +testToastElement((toast) => { + toast.open = 'truthy!'; + assertToastShown(toast); + assert_equals(toast.getAttribute('open'), ''); +}, 'setting `toast.open` to some truthy value on a hidden toast will show the toast'); + +testToastElement((toast) => { + toast.show(); + toast.open = ''; + assertToastNotShown(toast); +}, 'setting `toast.open` to some falsy value on a shown toast will hide the toast'); + +testToastElement((toast) => { + toast.toggleAttribute('open'); + assert_true(toast.open); +}, 'toggling `open` on a hidden toast sets `toast.open` to true'); + +testToastElementAsync((t, toast) => { + toast.toggleAttribute('open', true); + + t.step_timeout(() => { + assertToastShown(toast); + t.done(); + }, 2000); +}, 'toggling open attribute does not start timeout'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/events-open.html b/third_party/blink/web_tests/external/wpt/std-toast/events-open.html new file mode 100644 index 0000000..5442b36d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/events-open.html
@@ -0,0 +1,73 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Toast: Event tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<main></main> + +<script type="module"> +import { testToastElement, EventCollector } from './resources/helpers.js'; + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('show', (e) => { + counter.getCallback()(e); + }); + toast.open = true; + + assert_equals(counter.getCount(), 1); +}, 'setting open to true on a hidden toast triggers the `show` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.open = true; + toast.addEventListener('show', counter.getCallback()); + toast.open = true; + + assert_equals(counter.getCount(), 0); +}, 'setting open to true on a shown toast does not trigger the `show` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('hide', counter.getCallback()); + toast.open = false; + + assert_equals(counter.getCount(), 0); +}, 'setting open to false on a hidden toast does not trigger the `hide` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.show(); + toast.addEventListener('hide', counter.getCallback()); + toast.open = false; + + assert_equals(counter.getCount(), 1); +}, 'setting open to false on a shown toast triggers the `hide` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('show', counter.getCallback()); + toast.open = true; + toast.open = true; + + assert_equals(counter.getCount(), 1); +}, 'setting open to true twice only triggers the `show` event once'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.show(); + toast.addEventListener('hide', counter.getCallback()); + toast.open = false; + toast.open = false; + + assert_equals(counter.getCount(), 1); +}, 'setting open to false twice only triggers the `hide` event once'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/events-showhide.html b/third_party/blink/web_tests/external/wpt/std-toast/events-showhide.html new file mode 100644 index 0000000..73f1df4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/events-showhide.html
@@ -0,0 +1,98 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Toast: Event tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<main></main> + +<script type="module"> +import { testToastElement, EventCollector } from './resources/helpers.js'; + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('show', counter.getCallback()); + toast.show(); + + assert_equals(counter.getCount(), 1); +}, 'calling `show()` on a hidden toast triggers the `show` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.show(); + toast.addEventListener('show', counter.getCallback()); + toast.show(); + + assert_equals(counter.getCount(), 0); +}, 'calling `show()` on a shown toast does not trigger the `show` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('hide', counter.getCallback()); + toast.hide(); + + assert_equals(counter.getCount(), 0); +}, 'calling `hide()` on a hidden toast does not trigger the `hide` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.show(); + toast.addEventListener('hide', counter.getCallback()); + toast.hide(); + + assert_equals(counter.getCount(), 1); +}, 'calling `hide()` on a shown toast triggers the `hide` event'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.addEventListener('show', counter.getCallback()); + toast.show(); + toast.show(); + + assert_equals(counter.getCount(), 1); +}, 'calling `show()` twice only triggers the `show` event once'); + +testToastElement((toast) => { + const counter = new EventCollector(); + + toast.show(); + toast.addEventListener('hide', counter.getCallback()); + toast.hide(); + toast.hide(); + + assert_equals(counter.getCount(), 1); +}, 'calling `hide()` twice only triggers the `hide` event once'); + +testToastElement((toast) => { + const events = new EventCollector(); + + toast.addEventListener('show', events.getCallback()); + + toast.show(); + toast.hide(); + toast.show(); + + assert_equals(events.getCount(), 2); + assert_not_equals(events.getEvents()[0], events.getEvents()[1]); +}, "separate openings trigger different `show` events"); + +testToastElement((toast) => { + const events = new EventCollector(); + + toast.addEventListener('hide', events.getCallback()); + + toast.show(); + toast.hide(); + toast.show(); + toast.hide(); + + assert_equals(events.getCount(), 2); + assert_not_equals(events.getEvents()[0], events.getEvents()[1]); +}, "separate closings trigger different `hide` events"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/methods.html b/third_party/blink/web_tests/external/wpt/std-toast/methods.html new file mode 100644 index 0000000..7ce0e5a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/methods.html
@@ -0,0 +1,125 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Toast: method tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<main></main> +<div></div> + +<script type="module"> +import { testToastElement, assertToastShown, assertToastNotShown, testToastElementAsync } from './resources/helpers.js'; + +testToastElement((toast) => { + toast.show(); + + assertToastShown(toast); +}, 'calling `show()` on a hidden toast opens and displays it'); + +testToastElement((toast) => { + toast.toggleAttribute('open'); + toast.show(); + + assertToastShown(toast); +}, 'calling `show()` on a shown toast does nothing'); + +testToastElement((toast) => { + toast.toggleAttribute('open'); + toast.hide(); + + assertToastNotShown(toast); +}, 'calling `hide()` on a shown toast hides the toast'); + +testToastElement((toast) => { + toast.hide(); + + assertToastNotShown(toast); +}, 'calling `hide()` on a hidden toast does nothing'); + +testToastElement((toast) => { + toast.toggle(); + + assertToastShown(toast); +}, 'calling `toggle()` on a hidden toast shows the toast'); + +testToastElement((toast) => { + toast.show(); + toast.toggle(); + + assertToastNotShown(toast); +}, 'calling `toggle()` on a shown toast hides the toast'); + +testToastElement((toast) => { + toast.toggle(true); + + assertToastShown(toast); +}, 'calling `toggle()` with `force` parameter set to true on a hidden opens the toast'); + +testToastElement((toast) => { + toast.show(); + toast.toggle(true); + + assertToastShown(toast); +}, 'calling `toggle()` with `force` parameter set to true on a shown toast does not close the toast'); + +testToastElement((toast) => { + toast.toggle(false); + + assertToastNotShown(toast); +}, 'calling `toggle()` with `force` parameter set to false on a hidden toast does not open the toast'); + +testToastElement((toast) => { + toast.show(); + toast.toggle(false); + + assertToastNotShown(toast); +}, 'calling `toggle()` with `force` parameter set to false on a shown toast closes the toast'); + +testToastElementAsync((t, toast) => { + toast.show(); + + // time = 999 + t.step_timeout(() => { + assertToastShown(toast); + toast.show(); + + // time = 2000 + t.step_timeout(() => { + assertToastShown(toast); + + // time = 3000 + t.step_timeout(() => { + assertToastNotShown(toast); + t.done(); + }, 1000); + }, 1001); + }, 999); +}, 'calling `show()` twice resets the timeout'); + +testToastElementAsync((t, toast) => { + toast.show(); + + // time = 999 + t.step_timeout(() => { + assertToastShown(toast); + toast.hide(); + + // time = 1000 + t.step_timeout(() => { + assertToastNotShown(toast); + + // time = 1500 + t.step_timeout(() => { + toast.show(); + + // time = 2500 + t.step_timeout(() => { + assertToastShown(toast); + t.done(); + }, 1000); + }, 500); + }, 1); + }, 999); +}, 'calling `hide()` clears the timeout'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/options.html b/third_party/blink/web_tests/external/wpt/std-toast/options.html new file mode 100644 index 0000000..bd091a12 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/options.html
@@ -0,0 +1,74 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<meta name="timeout" content="long"> +<title>Toast: showToast tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> +</body> + +<script type="module"> +import { showToast, StdToastElement } from 'std:toast'; +import { assertToastNotShown, assertToastShown } from './resources/helpers.js'; + +// message +test(() => { + const toast = new StdToastElement(false); + document.body.appendChild(toast); + + assert_equals(toast.textContent, 'false'); +}), 'passing false as message converts to the string `false`'; + +test(() => { + const toast = new StdToastElement('<p>rich text</p>'); + document.body.appendChild(toast); + + assert_equals(toast.textContent, '<p>rich text</p>'); + assert_equals(toast.querySelector('p'), null); +}, 'passing markup to the constructor does not pass through the markup behaviors'); + +test(() => { + const toastString = '<std-toast id="test">test</std-toast>'; + document.body.innerHTML = toastString; + const toast = document.body.querySelector('#test'); + + assert_equals(toast.textContent, 'test'); +}, 'HTML created toast has `test` as its text content'); + +// duration +async_test(t => { + const toast = showToast('message'); + + t.step_timeout(() => { + assertToastShown(toast); + }, 1999); + + t.step_timeout(() => { + assertToastNotShown(toast); + t.done(); + }, 2000); + + t.add_cleanup(function() { + toast.remove(); + }); +}, 'showToast closes after default duration of 2000ms'); + +async_test(t => { + const toast = showToast('message', {duration: 1000}); + + t.step_timeout(() => { + assertToastShown(toast); + }, 999); + + t.step_timeout(() => { + assertToastNotShown(toast); + t.done(); + }, 1000); + + t.add_cleanup(function() { + toast.remove(); + }); +}, 'showToast closes after user specified 1000ms'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js b/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js new file mode 100644 index 0000000..60068bb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/resources/helpers.js
@@ -0,0 +1,70 @@ +import { showToast, StdToastElement } from 'std:toast'; + +// helper functions to keep tests from bleeding into each other + +const runTest = (testFn, name, toast) => { + try { + test(() => { + testFn(toast); + }, name); + } finally { + toast.remove(); + } +}; + +const runTestAsync = (testFn, name, toast) => { + async_test(t => { + testFn(t, toast); + t.add_cleanup(() => { + toast.remove(); + }); + }, name); +}; + +export const testToastElement = (testFn, name) => { + const toast = new StdToastElement('Message', {}); + document.querySelector('main').appendChild(toast); + + runTest(testFn, name, toast); +}; + +export const testToastElementAsync = (testFn, name) => { + const toast = new StdToastElement('Message', {}); + document.querySelector('main').appendChild(toast); + + runTestAsync(testFn, name, toast); +}; + +export const testShowToast = (testFn, name) => { + const toast = showToast("message"); + + runTest(testFn, name, toast); +}; + +export const assertToastShown = (toast) => { + assert_not_equals(window.getComputedStyle(toast).display, 'none'); + assert_true(toast.hasAttribute('open')); + assert_true(toast.open); +}; + +export const assertToastNotShown = (toast) => { + assert_equals(window.getComputedStyle(toast).display, 'none'); + assert_false(toast.hasAttribute('open')); + assert_false(toast.open); +}; + +export class EventCollector { + events = []; + + getCallback() { + return (e) => {this.events.push(e)}; + } + + getCount() { + return this.events.length; + } + + getEvents() { + return this.events; + } +}
diff --git a/third_party/blink/web_tests/external/wpt/std-toast/show-toast.html b/third_party/blink/web_tests/external/wpt/std-toast/show-toast.html new file mode 100644 index 0000000..0733181 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/std-toast/show-toast.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Toast: showToast tests</title> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<body> +</body> + +<script type="module"> +import { showToast, StdToastElement } from 'std:toast'; +import { testShowToast, assertToastNotShown, assertToastShown } from './resources/helpers.js'; + +testShowToast((toast) => { + assert_true(toast != null); + assert_true(toast instanceof StdToastElement); +}, 'showToast creates and returns a toast'); + +testShowToast((toast) => { + assert_true(document.querySelector('std-toast') === toast); +}, 'showToast puts the toast in the DOM'); + +testShowToast((toast) => { + assertToastShown(toast); +}, 'showToast displays the toast by default'); + +testShowToast((toast) => { + toast.hide(); + + assertToastNotShown(toast); +}, 'hiding showToast immediately does not display it'); + +testShowToast((toast) => { + toast.show(); + + assertToastShown(toast); +}, 'calling show after showToast does nothing'); + +testShowToast((toast) => { + let toast2; + try { + toast2 = showToast('message2'); + + assert_not_equals(toast, toast2); + } + finally { + toast2.remove(); + } +}, 'calling showToast multiple times creates multiple different toasts'); + +test(() => { + const toast = showToast('test'); + assert_equals(toast.textContent, 'test'); +}, 'showToast created toast has `test` as its text content'); + +test(() => { + const toast = showToast('<p>rich text</p>'); + + assert_equals(toast.textContent, '<p>rich text</p>'); + assert_equals(toast.querySelector('p'), null); +}, 'passing markup to showToast does not pass through the markup behaviors'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Element-setAttributeNS.tentative.html b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Element-setAttributeNS.tentative.html index 4bb9569..76a639a 100644 --- a/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Element-setAttributeNS.tentative.html +++ b/third_party/blink/web_tests/external/wpt/trusted-types/block-string-assignment-to-Element-setAttributeNS.tentative.html
@@ -44,11 +44,12 @@ // TrustedURL. // There a number of affected elements, and there are several ways to set // a namespaced attribute. Let's iterate over all combinations. - // TODO(vogelheim): Also SMIL timed elements. const xlink = "http://www.w3.org/1999/xlink"; const svg = "http://www.w3.org/2000/svg"; - const elems = [ "a", "feImage", "filter", "image", "linearGradient", - "mpath", "pattern", "radialGradient", "textPath", "use" ]; + const elems = [ "a", "animate", "animateMotion", "animateTransform", + "discard", "feImage", "filter", "image", "linearGradient", + "mpath", "pattern", "radialGradient", "set", "textPath", + "use" ]; // There are multiple ways to set a namespaced attribute. Let's encapsulate // each in a function. @@ -114,9 +115,9 @@ }, "Test synchronized, namespaced attributes."); // svg:script xlink:href=... expects a TrustedScriptURL. - let elem = document.createElementNS(svg, "script"); // Assigning a TrustedScriptURL works. test(t => { + let elem = document.createElementNS(svg, "script"); elem.setAttributeNS(xlink, "href", script_url); assert_equals("" + RESULTS.ScriptURL, elem.getAttributeNodeNS(xlink, "href").value); @@ -124,6 +125,7 @@ // Assigning things that ought to not work. test(t => { + let elem = document.createElementNS(svg, "script"); const values = [ "abc", null, url, html, script ]; for (const v of values) { assert_throws(new TypeError(), _ => {
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/accept_alert/accept.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/accept_alert/accept.py index a111f10..d821184 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/accept_alert/accept.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/accept_alert/accept.py
@@ -1,5 +1,8 @@ +from webdriver.error import NoSuchAlertException + from tests.support.asserts import assert_error, assert_success from tests.support.inline import inline +from tests.support.sync import Poll def accept_alert(session): @@ -43,3 +46,16 @@ response = accept_alert(session) assert_success(response) assert session.execute_script("return window.result") == "Federer" + + +def test_unexpected_alert(session): + session.execute_script("window.setTimeout(function() { window.alert('Hello'); }, 100);") + wait = Poll( + session, + timeout=5, + ignored_exceptions=NoSuchAlertException, + message="No user prompt with text 'Hello' detected") + wait.until(lambda s: s.alert.text == "Hello") + + response = accept_alert(session) + assert_success(response)
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/dismiss_alert/dismiss.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/dismiss_alert/dismiss.py index c0efc38..bcff3a3 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/dismiss_alert/dismiss.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/dismiss_alert/dismiss.py
@@ -1,5 +1,8 @@ +from webdriver.error import NoSuchAlertException + from tests.support.asserts import assert_error, assert_success from tests.support.inline import inline +from tests.support.sync import Poll def dismiss_alert(session): @@ -43,3 +46,16 @@ response = dismiss_alert(session) assert_success(response) assert session.execute_script("return window.result") is None + + +def test_unexpected_alert(session): + session.execute_script("setTimeout(function() { alert('Hello'); }, 100);") + wait = Poll( + session, + timeout=5, + ignored_exceptions=NoSuchAlertException, + message="No user prompt with text 'Hello' detected") + wait.until(lambda s: s.alert.text == "Hello") + + response = dismiss_alert(session) + assert_success(response)
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/get_alert_text/get.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/get_alert_text/get.py index 2327abc..d6fdda2d 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/get_alert_text/get.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/get_alert_text/get.py
@@ -1,5 +1,8 @@ +from webdriver.error import NoSuchAlertException + from tests.support.asserts import assert_error, assert_success from tests.support.inline import inline +from tests.support.sync import Poll def get_alert_text(session): @@ -48,3 +51,16 @@ prompt_text = response.body["value"] assert isinstance(prompt_text, basestring) assert prompt_text == "Enter Your Name: " + + +def test_unexpected_alert(session): + session.execute_script("setTimeout(function() { alert('Hello'); }, 100);") + wait = Poll( + session, + timeout=5, + ignored_exceptions=NoSuchAlertException, + message="No user prompt with text 'Hello' detected") + wait.until(lambda s: s.alert.text == "Hello") + + response = get_alert_text(session) + assert_success(response)
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py new file mode 100644 index 0000000..e3a33424 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/switch_to_window/alerts.py
@@ -0,0 +1,32 @@ +import pytest + +from webdriver import error + +from tests.support.asserts import assert_success +from tests.support.inline import inline + + +def switch_to_window(session, handle): + return session.transport.send( + "POST", "session/{session_id}/window".format(**vars(session)), + {"handle": handle}) + + +def test_retain_tab_modal_status(session, create_window): + handle = session.window_handle + + new_handle = create_window() + response = switch_to_window(session, new_handle) + assert_success(response) + + session.url = inline("<script>window.alert('Hello');</script>") + assert session.alert.text == "Hello" + response = switch_to_window(session, handle) + assert_success(response) + + with pytest.raises(error.NoSuchAlertException): + session.alert.text == "Hello" + response = switch_to_window(session, new_handle) + assert_success(response) + + assert session.alert.text == "Hello"
diff --git a/third_party/blink/web_tests/nfc/push.html b/third_party/blink/web_tests/nfc/push.html index 6bb386b6..5a6d231 100644 --- a/third_party/blink/web_tests/nfc/push.html +++ b/third_party/blink/web_tests/nfc/push.html
@@ -150,7 +150,7 @@ nfc_test(async () => { await navigator.nfc.push(test_text_data); assertNFCPushOptionsEqual(createNFCPushOptions('any', Infinity, true), - mockNFC.pushOptions()); + mockNFC.pushOptions(), 'any'); }, 'Check that default NFCPushOptions values are correctly set.'); nfc_test(async () => {
diff --git a/third_party/blink/web_tests/nfc/resources/nfc-helpers.js b/third_party/blink/web_tests/nfc/resources/nfc-helpers.js index 51a13a1..35b9072 100644 --- a/third_party/blink/web_tests/nfc/resources/nfc-helpers.js +++ b/third_party/blink/web_tests/nfc/resources/nfc-helpers.js
@@ -43,8 +43,8 @@ return record; } -function createNFCPushOptions(target, timeout, ignoreRead) { - return { target, timeout, ignoreRead }; +function createNFCPushOptions(target, timeout, ignoreRead, compatibility) { + return { target, timeout, ignoreRead, compatibility}; } function createNFCReaderOptions(url, recordType, mediaType, compatibility) { @@ -220,6 +220,11 @@ assert_equals(toMojoNFCPushTarget(provided.target), received.target); else assert_equals(received.target, device.mojom.NFCPushTarget.ANY); + + if (provided.compatibility !== undefined) + assert_equals(toMojoNDEFCompatibility(provided.compatibility), received.compatibility); + else + assert_equals(received.compatibility, device.mojom.NDEFCompatibility.NFC_FORUM); } // Compares NFCReaderOptions structures that were provided to API and
diff --git a/third_party/blink/web_tests/platform/linux/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/linux/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/linux/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.11/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-mac10.12/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/fullscreen/api/element-request-fullscreen-and-move-to-iframe-manual-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/fullscreen/api/element-request-fullscreen-and-move-to-iframe-manual-expected.txt new file mode 100644 index 0000000..b4e9af13 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/external/wpt/fullscreen/api/element-request-fullscreen-and-move-to-iframe-manual-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +Harness Error. harness_status.status = 1 , harness_status.message = fullscreen error +PASS Element#requestFullscreen() followed by moving the element into an iframe +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/win/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/win/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/win/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/win7/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt b/third_party/blink/web_tests/platform/win7/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt new file mode 100644 index 0000000..4c79453 --- /dev/null +++ b/third_party/blink/web_tests/platform/win7/external/wpt/html/cross-origin-opener/new_window_same_site_unsafe_allow_outgoing.tentative-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_ORIGIN_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-site" +PASS same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://www1.web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_SAME_SITE_same-origin-unsafe-allow-outgoing" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "" +PASS same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "jibberish" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-site unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-site-unsafe-allow-outgoing" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin" +FAIL same-site_unsafe-allow-outgoing document opening popup to http://not-web-platform.test:8001 with COOP: "same-origin unsafe-allow-outgoing" assert_equals: expected "" but got "same-site_unsafe-allow-outgoing_to_CROSS_ORIGIN_same-origin-unsafe-allow-outgoing" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/platform/win7/virtual/blink-cors/http/tests/security/isolatedWorld/bypass-main-world-csp-iframes-expected.txt b/third_party/blink/web_tests/platform/win7/virtual/blink-cors/http/tests/security/isolatedWorld/bypass-main-world-csp-iframes-expected.txt deleted file mode 100644 index 6ebbb8b..0000000 --- a/third_party/blink/web_tests/platform/win7/virtual/blink-cors/http/tests/security/isolatedWorld/bypass-main-world-csp-iframes-expected.txt +++ /dev/null
@@ -1,27 +0,0 @@ -ALERT: Running test #6 - -CONSOLE ERROR: line 28: Refused to frame 'http://127.0.0.1:8000/security/isolatedWorld/resources/iframe.php?test=6' because it violates the following Content Security Policy directive: "frame-src 'none'". - -ALERT: Running test #5 - -CONSOLE ERROR: Refused to frame 'http://127.0.0.1:8000/security/isolatedWorld/resources/iframe.php?test=5' because it violates the following Content Security Policy directive: "frame-src 'none'". - -ALERT: Running test #4 - -ALERT: Starting to bypass main world's CSP: -ALERT: iframe loaded in test #4 -ALERT: Running test #3 - -CONSOLE ERROR: line 28: Refused to frame 'http://127.0.0.1:8000/security/isolatedWorld/resources/iframe.php?test=3' because it violates the following Content Security Policy directive: "frame-src 'none'". - -ALERT: Running test #2 - -CONSOLE ERROR: line 28: Refused to frame 'http://127.0.0.1:8000/security/isolatedWorld/resources/iframe.php?test=2.5' because it violates the following Content Security Policy directive: "frame-src 'none'". - -ALERT: Running test #1 - -CONSOLE ERROR: line 28: Refused to frame 'http://127.0.0.1:8000/security/isolatedWorld/resources/iframe.php?test=1' because it violates the following Content Security Policy directive: "frame-src 'none'". - -ALERT: Running test #0 - - This test ensures that iframes loaded from isolated worlds marked with their own Content Security Policy aren't affected by the page's content security policy. Extensions, for example, should be able to load any resource they like.
diff --git a/third_party/closure_compiler/externs/chrome_extensions.js b/third_party/closure_compiler/externs/chrome_extensions.js index b75ba26..5d9e021 100644 --- a/third_party/closure_compiler/externs/chrome_extensions.js +++ b/third_party/closure_compiler/externs/chrome_extensions.js
@@ -2315,6 +2315,29 @@ chrome.enterprise.platformKeys.removeCertificate = function( tokenId, certificate, opt_callback) {}; +/** + * reportingPrivate is a Private API for reporting Chrome browser status to + * admin console. + * @see https://cs.chromium.org/chromium/src/chrome/common/extensions/api/enterprise_reporting_private.idl + */ +chrome.enterprise.reportingPrivate = {}; + +/** + * Uploads the status of Chrome browser to the admin console by sending + * request to the DMServer. Sets runtime.lastError on failure. + * @param {!Object} report Object to report to admin console. + * @param {(function(): void)=} callback Called back when this operation is + * finished. + */ +chrome.enterprise.reportingPrivate.uploadChromeDesktopReport = function( + report, callback) {}; + +/** + * Gets the identity of device that Chrome browser is running on. The ID is + * retrieved from the local device and used by the Google admin console. + * @param {(function(!string): void)=} callback Called with the device ID. + */ +chrome.enterprise.reportingPrivate.getDeviceId = function(callback) {}; /** * @see https://developer.chrome.com/extensions/extension.html @@ -4201,6 +4224,43 @@ TtsEvent.prototype.errorMessage; +/** + * The speech options for the TTS engine. + * @record + * @see https://developer.chrome.com/apps/tts#type-TtsOptions + */ +function TtsOptions() {} + +/** @type {boolean|undefined} */ +TtsOptions.prototype.enqueue; + +/** @type {string|undefined} */ +TtsOptions.prototype.voiceName; + +/** @type {string|undefined} */ +TtsOptions.prototype.extensionId; + +/** @type {string|undefined} */ +TtsOptions.prototype.lang; + +/** @type {number|undefined} */ +TtsOptions.prototype.rate; + +/** @type {number|undefined} */ +TtsOptions.prototype.pitch; + +/** @type {number|undefined} */ +TtsOptions.prototype.volume; + +/** @type {!Array<string>|undefined} */ +TtsOptions.prototype.requiredEventTypes; + +/** @type {!Array<string>|undefined} */ +TtsOptions.prototype.desiredEventTypes; + +/** @type {!function(!TtsEvent)|undefined} */ +TtsOptions.prototype.onEvent; + /** * A description of a voice available for speech synthesis. @@ -4252,11 +4312,11 @@ * well-formed SSML document. Speech engines that do not support SSML will * strip away the tags and speak the text. The maximum length of the text is * 32,768 characters. - * @param {Object=} opt_options The speech options. - * @param {function()=} opt_callback Called right away, before speech finishes. + * @param {TtsOptions=} options The speech options. + * @param {function()=} callback Called right away, before speech finishes. * @return {undefined} */ -chrome.tts.speak = function(utterance, opt_options, opt_callback) {}; +chrome.tts.speak = function(utterance, options, callback) {}; /** @@ -10078,6 +10138,126 @@ /** @type {!ChromeStringStringEvent} */ chrome.networkingPrivate.onPortalDetectionCompleted; +/** + * safeBrowsingPrivate is a Private API for observing events and retrieving a + * referrer chain. + * @see https://cs.chromium.org/chromium/src/chrome/common/extensions/api/safe_browsing_private.idl + */ +chrome.safeBrowsingPrivate = {}; + +/** + * @enum {string} + */ +chrome.safeBrowsingPrivate.URLType = { + EVENT_URL: '', + LANDING_PAGE: '', + LANDING_REFERRER: '', + CLIENT_REDIRECT: '', + RECENT_NAVIGATION: '', + REFERRER: '', +}; + +/** + * @enum {string} + */ +chrome.safeBrowsingPrivate.NavigationInitiation = { + BROWSER_INITIATED: '', + RENDERER_INITIATED_WITHOUT_USER_GESTURE: '', + RENDERER_INITIATED_WITH_USER_GESTURE: '', +}; + +/** + * @typedef {{ + * url: string, + * userName: string, + * isPhishingUrl: boolean + * }} + */ +chrome.safeBrowsingPrivate.PolicySpecifiedPasswordReuse; + +/** + * @typedef {{ + * url: string, + * fileName: string, + * downloadDigestSha256: string, + * userName: string + * }} + */ +chrome.safeBrowsingPrivate.DangerousDownloadInfo; + +/** + * @typedef {{ + * url: string, + * reason: string, + * netErrorCode: (string|undefined), + * userName: string + * }} + */ +chrome.safeBrowsingPrivate.InterstitialInfo; + +/** + * @typedef {{ + * url: (string|undefined) + * }} + */ +chrome.safeBrowsingPrivate.ServerRedirect; + +/** + * @typedef {{ + * url: string, + * mainFrameUrl: (string|undefined), + * urlType: !chrome.safeBrowsingPrivate.URLType, + * ipAddresses: (!Array<string>|undefined), + * referrerUrl: (string|undefined), + * referrerMainFrameUrl: (string|undefined), + * isRetargeting: (boolean|undefined), + * navigationTimeMs: (number|undefined), + * serverRedirectChain: + * (!Array<!chrome.safeBrowsingPrivate.ServerRedirect>|undefined), + * navigationInitiation: + * (!chrome.safeBrowsingPrivate.NavigationInitiation|undefined), + * maybeLaunchedByExternalApp: (boolean|undefined) + * }} + */ +chrome.safeBrowsingPrivate.ReferrerChainEntry; + +/** + * Gets referrer chain for the specified tab. + * @param {number} tabId Id of the tab from which to retrieve the referrer. + * @param {function(!Array<!chrome.safeBrowsingPrivate.ReferrerChainEntry>):void} + * callback Called with the list of referrer chain entries. + */ +chrome.safeBrowsingPrivate.getReferrerChain = function(tabId, callback) {}; + +/** + * Fired when Chrome detects a reuse of a policy specified password. + * @type {!ChromeObjectEvent} + */ +chrome.safeBrowsingPrivate.onPolicySpecifiedPasswordReuseDetected; + +/** + * Fired when the user changed their policy specified password. + * @type {!ChromeStringEvent} + */ +chrome.safeBrowsingPrivate.onPolicySpecifiedPasswordChanged; + +/** + * Fired when the user opened a dangerous download. + * @type {!ChromeObjectEvent} + */ +chrome.safeBrowsingPrivate.onDangerousDownloadOpened; + +/** + * Fired when a security interstitial is shown to the user. + * @type {!ChromeObjectEvent} + */ +chrome.safeBrowsingPrivate.onSecurityInterstitialShown; + +/** + * Fired when the user clicked-through a security interstitial. + * @type {!ChromeObjectEvent} + */ +chrome.safeBrowsingPrivate.onSecurityInterstitialProceeded; /** * WARNING(2014/08/14): This API is still under active initial development and @@ -11125,3 +11305,70 @@ * @see https://developer.chrome.com/extensions/declarativeContent#event-onPageChanged */ chrome.declarativeContent.onPageChanged; + +/** + * @see https://developer.chrome.com/extensions/instanceID + * @const + */ +chrome.instanceID = {}; + +/** + * @param {function(string)} callback + * @see https://developer.chrome.com/extensions/instanceID#method-getID + */ +chrome.instanceID.getID = function(callback) {}; + +/** + * @param {function(number)} callback + * @see https://developer.chrome.com/extensions/instanceID#method-getCreationTime + */ +chrome.instanceID.getCreationTime = function(callback) {}; + +/** + * @typedef {{ + * authorizedEntity: string, + * scope: string, + * options: (!Object|undefined) + * }} + */ +chrome.instanceID.GetTokenParams; + +/** + * @param {!chrome.instanceID.GetTokenParams} getTokenParams + * @param {function(string)} callback + * @see https://developer.chrome.com/extensions/instanceID#method-getToken + */ +chrome.instanceID.getToken = function(getTokenParams, callback) {}; + +/** + * @typedef {{ + * authorizedEntity: string, + * scope: string, + * }} + */ +chrome.instanceID.DeleteTokenParams; + +/** + * @param {!chrome.instanceID.DeleteTokenParams} deleteTokenParams + * @param {function()} callback + * @see https://developer.chrome.com/extensions/instanceID#method-deleteToken + */ +chrome.instanceID.deleteToken = function(deleteTokenParams, callback) {}; + +/** + * @param {function()} callback + * @see https://developer.chrome.com/extensions/instanceID#method-deleteID + */ +chrome.instanceID.deleteID = function(callback) {}; + +/** + * @const + * @see https://developer.chrome.com/extensions/instanceID#event-onTokenRefresh + */ +chrome.instanceID.onTokenRefresh = {}; + +/** + * @param {function()} callback + * @see https://developer.chrome.com/extensions/instanceID#event-onTokenRefresh + */ +chrome.instanceID.onTokenRefresh.addListener = function(callback) {};
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 8198823..8d2d58a 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -514,6 +514,11 @@ 'windows-sdk-multirel': 'release_bot_x86_minimal_symbols', }, + 'client.openscreen.chromium': { + 'chromium_linux64_debug': 'debug_bot', + 'chromium_mac_debug': 'debug_bot', + }, + 'client.v8.chromium': { 'Linux - Future': 'v8_future_release_bot', 'Linux - Future (dbg)': 'v8_future_debug_bot',
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 38b0368..a21e7ed 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -15896,6 +15896,10 @@ </action> <action name="PageLoadInIncognito" not_user_triggered="true"> + <obsolete> + Removed 06/2019, replaced with Navigation.MainFrameProfileType histogram to + cover all profile types in a commom context. + </obsolete> <owner>dullweber@chromium.org</owner> <owner>msramek@chromium.org</owner> <description>A page was loaded in incognito mode.</description>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index e883d390..876ebf8 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -23676,6 +23676,7 @@ <int value="2923" label="FeaturePolicySemicolonSeparatedDeclarations"/> <int value="2924" label="V8CallSiteAPIGetFunctionSloppyCall"/> <int value="2925" label="V8CallSiteAPIGetThisSloppyCall"/> + <int value="2926" label="BuiltInModuleToast"/> </enum> <enum name="FeaturePolicyAllowlistType">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index fc495e3d..8b745ff 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -43061,13 +43061,16 @@ </histogram> <histogram name="FirstRun.Sentinel.Created" enum="FirstRunSentinelResult" - expires_after="M77"> + expires_after="M87"> <owner>jlebel@chromium.org</owner> + <owner>chrome-signin-team@google.com</owner> <summary>Result of sentinel file has been written.</summary> </histogram> -<histogram name="FirstRun.Sentinel.CreatedFileError" enum="PlatformFileError"> +<histogram name="FirstRun.Sentinel.CreatedFileError" enum="PlatformFileError" + expires_after="M87"> <owner>jlebel@chromium.org</owner> + <owner>chrome-signin-team@google.com</owner> <summary>File error when the sentinel file was not written.</summary> </histogram> @@ -43842,8 +43845,9 @@ </histogram> <histogram name="Geolocation.AuthorizationActionExistingUser" - enum="GeolocationAuthorizationAction" expires_after="M77"> - <owner>mvanouwerkerk@chromium.org</owner> + enum="GeolocationAuthorizationAction" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary> Records the action performed by an existing user when prompted to authorize the use of location by Chrome. @@ -43851,8 +43855,9 @@ </histogram> <histogram name="Geolocation.AuthorizationActionNewUser" - enum="GeolocationAuthorizationAction" expires_after="M77"> - <owner>mvanouwerkerk@chromium.org</owner> + enum="GeolocationAuthorizationAction" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary> Records the action performed by a new user when prompted to authorize the use of location by Chrome. @@ -43860,8 +43865,9 @@ </histogram> <histogram name="Geolocation.GeolocationDispatcherHostImpl.EnableHighAccuracy" - enum="BooleanEnabled" expires_after="M77"> - <owner>mvanouwerkerk@chromium.org</owner> + enum="BooleanEnabled" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary> Whether high accuracy geolocation information was requested. </summary> @@ -43929,13 +43935,15 @@ </histogram> <histogram name="Geolocation.LocationUpdate.ErrorCode" - enum="GeopositionErrorCode" expires_after="M77"> - <owner>mvanouwerkerk@chromium.org</owner> + enum="GeopositionErrorCode" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary>Error code for the geoposition sent to the renderers.</summary> </histogram> <histogram name="Geolocation.NetworkLocationRequest.AccessPoints"> - <owner>mvanouwerkerk@chromium.org</owner> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary> The number of WiFi access points used to determine geolocation. </summary> @@ -43943,13 +43951,15 @@ <histogram name="Geolocation.NetworkLocationRequest.Event" enum="NetworkLocationRequestEvent"> - <owner>mvanouwerkerk@chromium.org</owner> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary>Events in NetworkLocationRequest.</summary> </histogram> <histogram name="Geolocation.NetworkLocationRequest.ResponseCode" units="HTTP response code"> - <owner>mvanouwerkerk@chromium.org</owner> + <owner>mattreynolds@chromium.org</owner> + <owner>device-dev@chromium.org</owner> <summary>Http response codes in NetworkLocationRequest.</summary> </histogram> @@ -44010,7 +44020,8 @@ </histogram> <histogram name="Geolocation.Timeout"> - <owner>mvanouwerkerk@chromium.org</owner> + <owner>mattreynolds@chromium.org</owner> + <owner>deviceapi-team@google.com</owner> <summary> Counts Geolocation request timeout values, bucketing by timeout duration. This is recorded for all requests upon creation, see @@ -44018,8 +44029,9 @@ </summary> </histogram> -<histogram name="Geolocation.TimeoutExpired" expires_after="M77"> - <owner>mvanouwerkerk@chromium.org</owner> +<histogram name="Geolocation.TimeoutExpired" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>deviceapi-team@google.com</owner> <summary> Counts Geolocation request timeout expirations, bucketing by timeout duration. This means no position was received within the allowed time from @@ -64522,6 +64534,16 @@ </summary> </histogram> +<histogram name="Navigation.MainFrameProfileType" enum="BrowserProfileType" + expires_after="M85"> + <owner>rhalavati@chromium.org</owner> + <owner>chrome-privacy-core@google.com</owner> + <summary> + The browser profile type for each main-frame navigation, recorded after + navigation completion, including NTP. + </summary> +</histogram> + <histogram name="Navigation.MainFrameScheme" enum="NavigationScheme"> <owner>elawrence@chromium.org</owner> <owner>estark@chromium.org</owner> @@ -75334,8 +75356,9 @@ <summary>All HTTP status codes seen during WebSocket handshakes.</summary> </histogram> -<histogram name="Net.Wifi.InterfaceCount" expires_after="2019-10-01"> - <owner>mvanouwerkerk@chromium.org</owner> +<histogram name="Net.Wifi.InterfaceCount" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>deviceapi-team@google.com</owner> <summary> The number of Wi-fi adapters on the computer. Because the histogram is logged each time Chrome performs a Wi-fi scan, it's better to see results in @@ -75343,13 +75366,15 @@ </summary> </histogram> -<histogram name="Net.Wifi.LbsLatency" units="ms" expires_after="2019-10-01"> - <owner>mvanouwerkerk@chromium.org</owner> +<histogram name="Net.Wifi.LbsLatency" units="ms" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>deviceapi-team@google.com</owner> <summary>The time that a request to Location Based Services takes.</summary> </histogram> -<histogram name="Net.Wifi.ScanLatency" units="ms" expires_after="2019-10-01"> - <owner>mvanouwerkerk@chromium.org</owner> +<histogram name="Net.Wifi.ScanLatency" units="ms" expires_after="2020-02-01"> + <owner>mattreynolds@chromium.org</owner> + <owner>deviceapi-team@google.com</owner> <summary>The time that a Wi-fi scan takes.</summary> </histogram> @@ -80976,7 +81001,8 @@ </histogram> <histogram name="Notifications.Database.DeleteBeforeWriteResult" - enum="NotificationDatabaseStatus" expires_after="M77"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of deleting notification data from the Web @@ -80986,7 +81012,8 @@ </histogram> <histogram name="Notifications.Database.DeleteResult" - enum="NotificationDatabaseStatus" expires_after="M77"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of deleting notification data from the Web @@ -80995,7 +81022,8 @@ </histogram> <histogram name="Notifications.Database.DeleteServiceWorkerRegistrationResult" - enum="NotificationDatabaseStatus"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of deleting all notification data associated @@ -81004,7 +81032,8 @@ </histogram> <histogram name="Notifications.Database.DestroyResult" - enum="NotificationDatabaseStatus" expires_after="M77"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of destroying the Web Notification database @@ -81013,7 +81042,8 @@ </histogram> <histogram name="Notifications.Database.OpenAfterCorruptionResult" - enum="NotificationDatabaseStatus" expires_after="M77"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of opening the Web Notification database @@ -81022,7 +81052,8 @@ </histogram> <histogram name="Notifications.Database.OpenResult" - enum="NotificationDatabaseStatus"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of opening the Web Notification database. @@ -81030,7 +81061,8 @@ </histogram> <histogram name="Notifications.Database.ReadForServiceWorkerResult" - enum="NotificationDatabaseStatus" expires_after="M77"> + enum="NotificationDatabaseStatus" expires_after="M88"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of reading data of all notifications @@ -81062,6 +81094,7 @@ <histogram name="Notifications.Database.ReadResult" enum="NotificationDatabaseStatus"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of reading data of a single notification @@ -81071,6 +81104,7 @@ <histogram name="Notifications.Database.WriteResult" enum="NotificationDatabaseStatus"> + <owner>knollr@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> Records the result status codes of writing data for a notification to the @@ -81118,7 +81152,7 @@ </histogram> <histogram name="Notifications.ExtensionNotificationActionCount" - units="buttons" expires_after="M77"> + units="buttons" expires_after="M80"> <owner>dewittj@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81130,6 +81164,10 @@ <histogram name="Notifications.ExtensionNotificationIdLength" units="characters" expires_after="M77"> + <obsolete> + Removed in June 2019 because this was measuring risk for a feature that has + now been implemented and shipped. + </obsolete> <owner>peter@chromium.org</owner> <summary> The length, in characters, of the id given to an extension notification. @@ -81141,7 +81179,7 @@ </histogram> <histogram name="Notifications.ExtensionNotificationType" - enum="ExtensionNotificationType" expires_after="M77"> + enum="ExtensionNotificationType" expires_after="M80"> <owner>dewittj@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81534,7 +81572,7 @@ </histogram> <histogram name="Notifications.Windows.HandleEventStatus" - enum="WindowsNotificationHandleEventStatus" expires_after="M77"> + enum="WindowsNotificationHandleEventStatus" expires_after="M87"> <owner>finnur@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81544,7 +81582,7 @@ </histogram> <histogram name="Notifications.Windows.HistoryStatus" - enum="WindowsNotificationHistoryStatus" expires_after="M77"> + enum="WindowsNotificationHistoryStatus" expires_after="M87"> <owner>finnur@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81591,7 +81629,7 @@ </histogram> <histogram name="Notifications.Windows.OnDismissedStatus" - enum="WindowsNotificationOnDismissedStatus" expires_after="M77"> + enum="WindowsNotificationOnDismissedStatus" expires_after="M87"> <owner>chengx@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81601,7 +81639,7 @@ </histogram> <histogram name="Notifications.Windows.OnFailedStatus" - enum="WindowsNotificationOnFailedStatus" expires_after="M77"> + enum="WindowsNotificationOnFailedStatus" expires_after="M87"> <owner>chengx@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -81703,8 +81741,8 @@ </histogram> <histogram name="Notifications.XPCConnectionEvent" enum="XPCConnectionEvent" - expires_after="M77"> - <owner>beverloo@chromium.org</owner> + expires_after="M87"> + <owner>peter@chromium.org</owner> <owner>rsesek@chromium.org</owner> <summary> Mac only. Records the different events of a Notification XPC connection. @@ -91261,7 +91299,7 @@ </histogram> <histogram name="PasswordManager.DeleteUndecryptableLoginsReturnValue" - enum="DeleteCorruptedPasswordsResult" expires_after="M77"> + enum="DeleteCorruptedPasswordsResult" expires_after="M82"> <owner>vasilii@chromium.org</owner> <summary> Records the return value of the DeleteUndecryptableLogins method in the @@ -117399,7 +117437,7 @@ </histogram> <histogram name="ServiceWorker.NotificationCloseEvent.Time" units="ms" - expires_after="M77"> + expires_after="M87"> <owner>nsatragno@chromium.org</owner> <owner>peter@chromium.org</owner> <summary> @@ -128486,7 +128524,7 @@ <histogram name="Sync.Crypto.CustomPassphraseKeyDerivationMethodOnNewPassphrase" - enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M77"> + enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M79"> <owner>vitaliii@chromium.org</owner> <owner>treib@chromium.org</owner> <summary> @@ -128499,7 +128537,7 @@ <histogram name="Sync.Crypto.CustomPassphraseKeyDerivationMethodOnSuccessfulDecryption" - enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M77"> + enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M79"> <owner>vitaliii@chromium.org</owner> <owner>treib@chromium.org</owner> <summary> @@ -128512,7 +128550,7 @@ </histogram> <histogram name="Sync.Crypto.CustomPassphraseKeyDerivationMethodStateOnStartup" - enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M77"> + enum="SyncCustomPassphraseKeyDerivationMethodState" expires_after="M79"> <owner>vitaliii@chromium.org</owner> <owner>treib@chromium.org</owner> <summary> @@ -135997,7 +136035,7 @@ </histogram> <histogram name="UMA.FileMetricsProvider.AccessResult" - enum="FileMetricsProviderAccessResult" expires_after="M77"> + enum="FileMetricsProviderAccessResult" expires_after="M87"> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary> @@ -136100,7 +136138,7 @@ </histogram> <histogram name="UMA.FileMetricsProvider.InitialAccessResult" - enum="FileMetricsProviderAccessResult" expires_after="M77"> + enum="FileMetricsProviderAccessResult" expires_after="M87"> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary> @@ -136111,6 +136149,9 @@ <histogram name="UMA.FileMetricsProvider.InitialCheckTime.File" units="ms" expires_after="M77"> + <obsolete> + Access times are consistently on the order of a few ms. Removed 2019/06. + </obsolete> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary> @@ -136133,6 +136174,9 @@ </histogram> <histogram name="UMA.FileMetricsProvider.InitialSnapshotTime.File" units="ms"> + <obsolete> + Access times are consistently on the order of a few ms. Removed 2019/06. + </obsolete> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary> @@ -136155,6 +136199,9 @@ </histogram> <histogram name="UMA.FileMetricsProvider.SnapshotTime.File" units="ms"> + <obsolete> + Access times are consistently on the order of a few ms. Removed 2019/06. + </obsolete> <owner>asvitkine@chromium.org</owner> <owner>bcwhite@chromium.org</owner> <summary>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 31eb507..06402e9a 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -5268,6 +5268,12 @@ nearest 10. </summary> </metric> + <metric name="ThirdPartyCookieBlockingEnabledForSite"> + <summary> + Records whether third party cookie blocking was enabled for a site. Only + recorded for users who enabled the cookie controls ui. + </summary> + </metric> <metric name="WasCached"> <summary> Set to 1 if the main resource was served from cache.
diff --git a/ui/aura/window_tree_host.cc b/ui/aura/window_tree_host.cc index 490d9e8..42b0da8 100644 --- a/ui/aura/window_tree_host.cc +++ b/ui/aura/window_tree_host.cc
@@ -259,8 +259,7 @@ } ui::EventDispatchDetails WindowTreeHost::DispatchKeyEventPostIME( - ui::KeyEvent* event, - DispatchKeyEventPostIMECallback callback) { + ui::KeyEvent* event) { // If dispatch to IME is already disabled we shouldn't reach here. DCHECK(!dispatcher_->should_skip_ime()); dispatcher_->set_skip_ime(true); @@ -269,7 +268,6 @@ event_sink()->OnEventFromSource(event); if (!dispatch_details.dispatcher_destroyed) dispatcher_->set_skip_ime(false); - RunDispatchKeyEventPostIMECallback(event, std::move(callback)); return dispatch_details; }
diff --git a/ui/aura/window_tree_host.h b/ui/aura/window_tree_host.h index 701e0af..29f19ad 100644 --- a/ui/aura/window_tree_host.h +++ b/ui/aura/window_tree_host.h
@@ -172,9 +172,7 @@ void SetSharedInputMethod(ui::InputMethod* input_method); // Overridden from ui::internal::InputMethodDelegate: - ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* event, - DispatchKeyEventPostIMECallback callback) final; + ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* event) final; // Overridden from ui::EventSource: ui::EventSink* GetEventSink() override;
diff --git a/ui/base/ime/BUILD.gn b/ui/base/ime/BUILD.gn index ce594dc..1336e3c 100644 --- a/ui/base/ime/BUILD.gn +++ b/ui/base/ime/BUILD.gn
@@ -65,7 +65,6 @@ "input_method.h", "input_method_base.cc", "input_method_base.h", - "input_method_delegate.cc", "input_method_delegate.h", "input_method_keyboard_controller.h", "input_method_keyboard_controller_observer.h",
diff --git a/ui/base/ime/chromeos/BUILD.gn b/ui/base/ime/chromeos/BUILD.gn index 3675b426..a76249de 100644 --- a/ui/base/ime/chromeos/BUILD.gn +++ b/ui/base/ime/chromeos/BUILD.gn
@@ -53,6 +53,7 @@ deps = [ "//chromeos/constants", "//chromeos/ime:gencode", + "//chromeos/services/ime/public/mojom", "//chromeos/system", "//third_party/icu", "//ui/base",
diff --git a/ui/base/ime/chromeos/DEPS b/ui/base/ime/chromeos/DEPS index 85d250d..6f29feb 100644 --- a/ui/base/ime/chromeos/DEPS +++ b/ui/base/ime/chromeos/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+chromeos/constants", "+chromeos/ime", + "+chromeos/services/ime/public/mojom", "+ui/chromeos/strings", "+ui/ozone/public", ]
diff --git a/ui/base/ime/chromeos/input_method_chromeos.cc b/ui/base/ime/chromeos/input_method_chromeos.cc index a9db88f..29d4257 100644 --- a/ui/base/ime/chromeos/input_method_chromeos.cc +++ b/ui/base/ime/chromeos/input_method_chromeos.cc
@@ -30,32 +30,6 @@ #include "ui/gfx/geometry/rect.h" namespace ui { -namespace { - -void RunAckCallbackFromPostImeCallback( - InputMethodChromeOS::AckCallback callback, - bool handled, - bool stopped_propagation) { - if (callback) - std::move(callback).Run(handled); -} - -void RunImeCallbackIfValid( - internal::InputMethodDelegate::DispatchKeyEventPostIMECallback callback, - bool handled, - bool stopped_propagation) { - if (!callback) - return; - std::move(callback).Run(handled, stopped_propagation); -} - -internal::InputMethodDelegate::DispatchKeyEventPostIMECallback -CreateResultCallbackFromAckCallback(InputMethodChromeOS::AckCallback callback) { - return base::BindOnce(&RunAckCallbackFromPostImeCallback, - std::move(callback)); -} - -} // namespace // InputMethodChromeOS implementation ----------------------------------------- InputMethodChromeOS::InputMethodChromeOS( @@ -90,17 +64,8 @@ InputMethodChromeOS::PendingSetCompositionRange::~PendingSetCompositionRange() = default; -void InputMethodChromeOS::DispatchKeyEventAsync(ui::KeyEvent* event, - AckCallback ack_callback) { - ignore_result(DispatchKeyEventInternal(event, std::move(ack_callback))); -} - -ui::EventDispatchDetails InputMethodChromeOS::DispatchKeyEventInternal( - ui::KeyEvent* event, - AckCallback ack_callback) { - ResultCallback result_callback = - CreateResultCallbackFromAckCallback(std::move(ack_callback)); - +ui::EventDispatchDetails InputMethodChromeOS::DispatchKeyEvent( + ui::KeyEvent* event) { DCHECK(event->IsKeyEvent()); DCHECK(!(event->flags() & ui::EF_IS_SYNTHESIZED)); @@ -149,7 +114,7 @@ // TODO(shuchen): Eventually, the language input keys should be handed // over to the IME extension to process. And IMF can handle if the IME // extension didn't handle. - return DispatchKeyEventPostIME(event, std::move(result_callback)); + return DispatchKeyEventPostIME(event); } } } @@ -164,36 +129,26 @@ if (ExecuteCharacterComposer(*event)) { // Treating as PostIME event if character composer handles key event and // generates some IME event, - return ProcessKeyEventPostIME(event, std::move(result_callback), false, + return ProcessKeyEventPostIME(event, false, /* handled */ true, /* stopped_propagation */ true); } - return ProcessUnfilteredKeyPressEvent(event, std::move(result_callback)); + return ProcessUnfilteredKeyPressEvent(event); } - return DispatchKeyEventPostIME(event, std::move(result_callback)); + return DispatchKeyEventPostIME(event); } handling_key_event_ = true; GetEngine()->ProcessKeyEvent( - *event, base::BindOnce(&InputMethodChromeOS::KeyEventDoneCallback, + *event, base::BindOnce(&InputMethodChromeOS::ProcessKeyEventDone, weak_ptr_factory_.GetWeakPtr(), // Pass the ownership of the new copied event. - base::Owned(new ui::KeyEvent(*event)), - std::move(result_callback))); + base::Owned(new ui::KeyEvent(*event)))); return ui::EventDispatchDetails(); } -void InputMethodChromeOS::KeyEventDoneCallback(ui::KeyEvent* event, - ResultCallback result_callback, - bool is_handled) { - ignore_result( - ProcessKeyEventDone(event, std::move(result_callback), is_handled)); -} - -ui::EventDispatchDetails InputMethodChromeOS::ProcessKeyEventDone( - ui::KeyEvent* event, - ResultCallback result_callback, - bool is_handled) { +void InputMethodChromeOS::ProcessKeyEventDone(ui::KeyEvent* event, + bool is_handled) { DCHECK(event); if (event->type() == ET_KEY_PRESSED) { if (is_handled) { @@ -206,23 +161,11 @@ is_handled = ExecuteCharacterComposer(*event); } } - ui::EventDispatchDetails details; if (event->type() == ET_KEY_PRESSED || event->type() == ET_KEY_RELEASED) { - details = - ProcessKeyEventPostIME(event, std::move(result_callback), false, - is_handled, /* stopped_propagation */ false); + ignore_result(ProcessKeyEventPostIME(event, false, is_handled, + /* stopped_propagation */ false)); } handling_key_event_ = false; - return details; -} - -ui::EventDispatchDetails InputMethodChromeOS::DispatchKeyEvent( - ui::KeyEvent* event) { - return DispatchKeyEventInternal(event, AckCallback()); -} - -AsyncKeyDispatcher* InputMethodChromeOS::GetAsyncKeyDispatcher() { - return this; } void InputMethodChromeOS::OnTextInputTypeChanged( @@ -436,7 +379,6 @@ ui::EventDispatchDetails InputMethodChromeOS::ProcessKeyEventPostIME( ui::KeyEvent* event, - ResultCallback result_callback, bool skip_process_filtered, bool handled, bool stopped_propagation) { @@ -444,55 +386,47 @@ if (!client) { // As ibus works asynchronously, there is a chance that the focused client // loses focus before this method gets called. - return DispatchKeyEventPostIME(event, std::move(result_callback)); + return DispatchKeyEventPostIME(event); } + if (event->type() == ET_KEY_PRESSED && handled && !skip_process_filtered) { + ui::EventDispatchDetails dispatch_details = + ProcessFilteredKeyPressEvent(event); + if (event->stopped_propagation()) { + ResetContext(); + return dispatch_details; + } + } ui::EventDispatchDetails dispatch_details; - if (event->type() == ET_KEY_PRESSED && handled && !skip_process_filtered) - return ProcessFilteredKeyPressEvent(event, std::move(result_callback)); // In case the focus was changed by the key event. The |context_| should have // been reset when the focused window changed. - if (client != GetTextInputClient()) { - RunImeCallbackIfValid(std::move(result_callback), /* handled */ false, - /* stopped_propagation*/ false); + if (client != GetTextInputClient()) return dispatch_details; - } + if (HasInputMethodResult()) ProcessInputMethodResult(event, handled); // In case the focus was changed when sending input method results to the // focused window. - if (client != GetTextInputClient()) { - RunImeCallbackIfValid(std::move(result_callback), /* handled */ false, - /* stopped_propagation */ false); + if (client != GetTextInputClient()) return dispatch_details; - } - if (handled) { - RunImeCallbackIfValid(std::move(result_callback), - /* handled */ true, stopped_propagation); + if (handled) return dispatch_details; // IME handled the key event. do not forward. - } if (event->type() == ET_KEY_PRESSED) - return ProcessUnfilteredKeyPressEvent(event, std::move(result_callback)); + return ProcessUnfilteredKeyPressEvent(event); if (event->type() == ET_KEY_RELEASED) - return DispatchKeyEventPostIME(event, std::move(result_callback)); + return DispatchKeyEventPostIME(event); return dispatch_details; } ui::EventDispatchDetails InputMethodChromeOS::ProcessFilteredKeyPressEvent( - ui::KeyEvent* event, - ResultCallback result_callback) { - auto callback = base::Bind( - &InputMethodChromeOS::PostProcessFilteredKeyPressEvent, - weak_ptr_factory_.GetWeakPtr(), base::Owned(new ui::KeyEvent(*event)), - GetTextInputClient(), Passed(&result_callback)); - + ui::KeyEvent* event) { if (NeedInsertChar()) - return DispatchKeyEventPostIME(event, std::move(callback)); + return DispatchKeyEventPostIME(event); ui::KeyEvent fabricated_event(ET_KEY_PRESSED, VKEY_PROCESSKEY, @@ -501,54 +435,19 @@ event->GetDomKey(), event->time_stamp()); ui::EventDispatchDetails dispatch_details = - DispatchKeyEventPostIME(&fabricated_event, std::move(callback)); + DispatchKeyEventPostIME(&fabricated_event); if (fabricated_event.stopped_propagation()) event->StopPropagation(); return dispatch_details; } -void InputMethodChromeOS::PostProcessFilteredKeyPressEvent( - ui::KeyEvent* event, - TextInputClient* prev_client, - ResultCallback result_callback, - bool handled, - bool stopped_propagation) { - // In case the focus was changed by the key event. - if (GetTextInputClient() != prev_client) - return; - - if (stopped_propagation) { - ResetContext(); - RunImeCallbackIfValid(std::move(result_callback), handled, - /* stopped_propagation */ true); - return; - } - ignore_result(ProcessKeyEventPostIME(event, std::move(result_callback), true, - true, false)); -} - ui::EventDispatchDetails InputMethodChromeOS::ProcessUnfilteredKeyPressEvent( - ui::KeyEvent* event, - ResultCallback result_callback) { - return DispatchKeyEventPostIME( - event, - base::BindOnce(&InputMethodChromeOS::PostProcessUnfilteredKeyPressEvent, - weak_ptr_factory_.GetWeakPtr(), - base::Owned(new ui::KeyEvent(*event)), - GetTextInputClient(), std::move(result_callback))); -} - -void InputMethodChromeOS::PostProcessUnfilteredKeyPressEvent( - ui::KeyEvent* event, - TextInputClient* prev_client, - ResultCallback result_callback, - bool handled, - bool stopped_propagation) { - if (stopped_propagation) { + ui::KeyEvent* event) { + TextInputClient* prev_client = GetTextInputClient(); + ui::EventDispatchDetails details = DispatchKeyEventPostIME(event); + if (event->stopped_propagation()) { ResetContext(); - RunImeCallbackIfValid(std::move(result_callback), handled, - /* stopped_propagation */ true); - return; + return details; } // We shouldn't dispatch the character anymore if the key event dispatch @@ -559,11 +458,8 @@ // page. // We should return here not to send the Tab key event to RWHV. TextInputClient* client = GetTextInputClient(); - if (!client || client != prev_client) { - RunImeCallbackIfValid(std::move(result_callback), /* handled */ false, - /* stopped_propagation */ false); - return; - } + if (!client || client != prev_client) + return details; // If a key event was not filtered by |context_| and |character_composer_|, // then it means the key event didn't generate any result text. So we need @@ -571,9 +467,7 @@ uint16_t ch = event->GetCharacter(); if (ch) client->InsertChar(*event); - - RunImeCallbackIfValid(std::move(result_callback), handled, - stopped_propagation); + return details; } void InputMethodChromeOS::ProcessInputMethodResult(ui::KeyEvent* event,
diff --git a/ui/base/ime/chromeos/input_method_chromeos.h b/ui/base/ime/chromeos/input_method_chromeos.h index 4d18710b..23fb226 100644 --- a/ui/base/ime/chromeos/input_method_chromeos.h +++ b/ui/base/ime/chromeos/input_method_chromeos.h
@@ -28,21 +28,15 @@ // A ui::InputMethod implementation for ChromeOS. class COMPONENT_EXPORT(UI_BASE_IME_CHROMEOS) InputMethodChromeOS - : public InputMethodBase, - public AsyncKeyDispatcher { + : public InputMethodBase { public: explicit InputMethodChromeOS(internal::InputMethodDelegate* delegate); ~InputMethodChromeOS() override; using AckCallback = base::OnceCallback<void(bool)>; - // Overridden from AsyncKeyDispatcher: - void DispatchKeyEventAsync(ui::KeyEvent* event, - AckCallback ack_callback) override; - // Overridden from InputMethod: ui::EventDispatchDetails DispatchKeyEvent(ui::KeyEvent* event) override; - AsyncKeyDispatcher* GetAsyncKeyDispatcher() override; void OnTextInputTypeChanged(const TextInputClient* client) override; void OnCaretBoundsChanged(const TextInputClient* client) override; void CancelComposition(const TextInputClient* client) override; @@ -68,7 +62,6 @@ // Process a key returned from the input method. virtual ui::EventDispatchDetails ProcessKeyEventPostIME( ui::KeyEvent* event, - ResultCallback result_callback, bool skip_process_filtered, bool handled, bool stopped_propagation) WARN_UNUSED_RESULT; @@ -91,9 +84,6 @@ std::vector<ui::ImeTextSpan> text_spans; }; - ui::EventDispatchDetails DispatchKeyEventInternal(ui::KeyEvent* event, - AckCallback ack_callback); - // Asks the client to confirm current composition text. void ConfirmCompositionText(); @@ -105,28 +95,12 @@ // A VKEY_PROCESSKEY may be dispatched to the EventTargets. // It returns the result of whether the event has been stopped propagation // when dispatching post IME. - ui::EventDispatchDetails ProcessFilteredKeyPressEvent( - ui::KeyEvent* event, - ResultCallback result_callback) WARN_UNUSED_RESULT; - - // Post processes a key event that was already filtered by the input method. - void PostProcessFilteredKeyPressEvent(ui::KeyEvent* event, - TextInputClient* prev_client, - ResultCallback result_callback, - bool handled, - bool stopped_propagation); + ui::EventDispatchDetails ProcessFilteredKeyPressEvent(ui::KeyEvent* event) + WARN_UNUSED_RESULT; // Processes a key event that was not filtered by the input method. - ui::EventDispatchDetails ProcessUnfilteredKeyPressEvent( - ui::KeyEvent* event, - ResultCallback result_callback) WARN_UNUSED_RESULT; - - // Post processes a key event that was unfiltered by the input method. - void PostProcessUnfilteredKeyPressEvent(ui::KeyEvent* event, - TextInputClient* prev_client, - ResultCallback result_callback, - bool handled, - bool stopped_propagation); + ui::EventDispatchDetails ProcessUnfilteredKeyPressEvent(ui::KeyEvent* event) + WARN_UNUSED_RESULT; // Sends input method result caused by the given key event to the focused text // input client. @@ -153,14 +127,8 @@ // Hides the composition text. void HidePreeditText(); - // Callback function for IMEEngineHandlerInterface::ProcessKeyEvent. - void KeyEventDoneCallback(ui::KeyEvent* event, - ResultCallback result_callback, - bool is_handled); - ui::EventDispatchDetails ProcessKeyEventDone(ui::KeyEvent* event, - ResultCallback result_callback, - bool is_handled) - WARN_UNUSED_RESULT; + // Called from the engine when it completes processing. + void ProcessKeyEventDone(ui::KeyEvent* event, bool is_handled); // Returns whether an non-password input field is focused. bool IsNonPasswordInputFieldFocused();
diff --git a/ui/base/ime/chromeos/input_method_chromeos_unittest.cc b/ui/base/ime/chromeos/input_method_chromeos_unittest.cc index b9f3b2f..799ea08 100644 --- a/ui/base/ime/chromeos/input_method_chromeos_unittest.cc +++ b/ui/base/ime/chromeos/input_method_chromeos_unittest.cc
@@ -74,14 +74,12 @@ // Overridden from InputMethodChromeOS: ui::EventDispatchDetails ProcessKeyEventPostIME( ui::KeyEvent* key_event, - ResultCallback result_callback, bool skip_process_filtered, bool handled, bool stopped_propagation) override { ui::EventDispatchDetails details = InputMethodChromeOS::ProcessKeyEventPostIME( - key_event, std::move(result_callback), skip_process_filtered, - handled, stopped_propagation); + key_event, skip_process_filtered, handled, stopped_propagation); if (!skip_process_filtered) { process_key_event_post_ime_args_.event = *key_event; process_key_event_post_ime_args_.handled = handled; @@ -209,29 +207,6 @@ void(const std::string&, uint32_t, uint32_t, uint32_t)); }; -class CachingInputMethodDelegate : public internal::InputMethodDelegate { - public: - CachingInputMethodDelegate() = default; - ~CachingInputMethodDelegate() override = default; - - std::queue<DispatchKeyEventPostIMECallback>& callbacks() { - return callbacks_; - } - - // internal::InputMethodDelegate: - EventDispatchDetails DispatchKeyEventPostIME( - KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) override { - callbacks_.emplace(std::move(callback)); - return EventDispatchDetails(); - } - - private: - std::queue<DispatchKeyEventPostIMECallback> callbacks_; - - DISALLOW_COPY_AND_ASSIGN(CachingInputMethodDelegate); -}; - class InputMethodChromeOSTest : public internal::InputMethodDelegate, public testing::Test, public DummyTextInputClient { @@ -257,13 +232,7 @@ IMEBridge::Get()->SetCandidateWindowHandler( mock_ime_candidate_window_handler_.get()); - internal::InputMethodDelegate* ime_delegate = this; - if (ShouldCreateCachingInputMethodDelegate()) { - caching_input_method_delegate_ = - std::make_unique<CachingInputMethodDelegate>(); - ime_delegate = caching_input_method_delegate_.get(); - } - ime_ = std::make_unique<TestableInputMethodChromeOS>(ime_delegate); + ime_ = std::make_unique<TestableInputMethodChromeOS>(this); ime_->SetFocusedTextInputClient(this); // InputMethodManager owns and delete it in InputMethodManager::Shutdown(). @@ -288,12 +257,10 @@ // Overridden from ui::internal::InputMethodDelegate: ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* event, - DispatchKeyEventPostIMECallback callback) override { + ui::KeyEvent* event) override { dispatched_key_event_ = *event; if (stop_propagation_post_ime_) event->StopPropagation(); - RunDispatchKeyEventPostIMECallback(event, std::move(callback)); return ui::EventDispatchDetails(); } @@ -361,12 +328,8 @@ } protected: - virtual bool ShouldCreateCachingInputMethodDelegate() { return false; } - std::unique_ptr<TestableInputMethodChromeOS> ime_; - std::unique_ptr<CachingInputMethodDelegate> caching_input_method_delegate_; - // Copy of the dispatched key event. ui::KeyEvent dispatched_key_event_; @@ -946,8 +909,7 @@ EXPECT_EQ(kFlags, key_event->flags()); EXPECT_EQ(0, ime_->process_key_event_post_ime_call_count()); - (static_cast<IMEInputContextHandlerInterface*>(ime_.get())) - ->CommitText("A"); + static_cast<IMEInputContextHandlerInterface*>(ime_.get())->CommitText("A"); EXPECT_EQ(0, inserted_char_); @@ -1068,9 +1030,7 @@ 0, DomKey::DeadKeyFromCombiningCharacter('^'), EventTimeForNow()); - ime_->ProcessKeyEventPostIME( - &eventA, InputMethodDelegate::DispatchKeyEventPostIMECallback(), false, - true, true); + ime_->ProcessKeyEventPostIME(&eventA, false, true, true); const ui::KeyEvent& key_event = dispatched_key_event_; @@ -1104,101 +1064,4 @@ EXPECT_FALSE(input_method_manager_->state()->is_jp_ime()); } -class InputMethodChromeOSAsyncTest : public InputMethodChromeOSTest { - public: - InputMethodChromeOSAsyncTest() = default; - ~InputMethodChromeOSAsyncTest() override = default; - - protected: - // InputMethodChromeOSTest: - bool ShouldCreateCachingInputMethodDelegate() override { return true; } - - private: - DISALLOW_COPY_AND_ASSIGN(InputMethodChromeOSAsyncTest); -}; - -TEST_F(InputMethodChromeOSAsyncTest, StopPropagation) { - KeyEvent event(ET_KEY_PRESSED, VKEY_A, EF_NONE); - - // As CachingInputMethodDelegate doesn't immediately dispatch, the callback - // should not be run immediately. - bool async_callback_run = false; - bool async_callback_handled_result = false; - ime_->DispatchKeyEventAsync(&event, - base::BindLambdaForTesting([&](bool handled) { - async_callback_handled_result = handled; - async_callback_run = true; - })); - EXPECT_FALSE(async_callback_run); - ASSERT_EQ(1u, caching_input_method_delegate_->callbacks().size()); - - // Run the queued callback in the delegate, which should then notify the - // callback supplied to DispatchKeyEvent(). - auto callback = - std::move(caching_input_method_delegate_->callbacks().front()); - caching_input_method_delegate_->callbacks().pop(); - std::move(callback).Run(/* handled */ true, /* stopped_propagation */ true); - EXPECT_TRUE(async_callback_run); - EXPECT_TRUE(async_callback_handled_result); - - // Because |stopped_propagation| was false, no character should be inserted. - EXPECT_FALSE(inserted_char_); -} - -TEST_F(InputMethodChromeOSAsyncTest, DidNotStopPropagation) { - KeyEvent event(ET_KEY_PRESSED, VKEY_A, EF_NONE); - - // As CachingInputMethodDelegate doesn't immediately dispatch, the callback - // should not be run immediately. - bool async_callback_run = false; - bool async_callback_handled_result = false; - ime_->DispatchKeyEventAsync(&event, - base::BindLambdaForTesting([&](bool handled) { - async_callback_handled_result = handled; - async_callback_run = true; - })); - EXPECT_FALSE(async_callback_run); - ASSERT_EQ(1u, caching_input_method_delegate_->callbacks().size()); - - // Run the queued callback in the delegate, which should then notify the - // callback supplied to DispatchKeyEvent(). - auto callback = - std::move(caching_input_method_delegate_->callbacks().front()); - caching_input_method_delegate_->callbacks().pop(); - std::move(callback).Run(/* handled */ true, /* stopped_propagation */ false); - EXPECT_TRUE(async_callback_run); - EXPECT_TRUE(async_callback_handled_result); - - // Because |stopped_propagation| was true, a character should be inserted. - EXPECT_TRUE(inserted_char_); -} - -TEST_F(InputMethodChromeOSAsyncTest, UnhandledAndDidNotStopPropatation) { - KeyEvent event(ET_KEY_PRESSED, VKEY_A, EF_NONE); - - // As CachingInputMethodDelegate doesn't immediately dispatch, the callback - // should not be run immediately. - bool async_callback_run = false; - bool async_callback_handled_result = false; - ime_->DispatchKeyEventAsync(&event, - base::BindLambdaForTesting([&](bool handled) { - async_callback_handled_result = handled; - async_callback_run = true; - })); - EXPECT_FALSE(async_callback_run); - ASSERT_EQ(1u, caching_input_method_delegate_->callbacks().size()); - - // Run the queued callback in the delegate, which should then notify the - // callback supplied to DispatchKeyEvent(). - auto callback = - std::move(caching_input_method_delegate_->callbacks().front()); - caching_input_method_delegate_->callbacks().pop(); - std::move(callback).Run(/* handled */ false, /* stopped_propagation */ false); - EXPECT_TRUE(async_callback_run); - EXPECT_FALSE(async_callback_handled_result); - - // Because |stopped_propagation| was true, a character should be inserted. - EXPECT_TRUE(inserted_char_); -} - } // namespace ui
diff --git a/ui/base/ime/chromeos/input_method_manager.h b/ui/base/ime/chromeos/input_method_manager.h index ecb06c5..2df18043 100644 --- a/ui/base/ime/chromeos/input_method_manager.h +++ b/ui/base/ime/chromeos/input_method_manager.h
@@ -14,6 +14,8 @@ #include "base/component_export.h" #include "base/memory/ref_counted.h" +#include "chromeos/services/ime/public/mojom/input_engine.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/base/ime/chromeos/input_method_descriptor.h" #include "ui/base/ime/chromeos/public/interfaces/ime_keyset.mojom.h" @@ -294,6 +296,11 @@ // Activates the input method property specified by the |key|. virtual void ActivateInputMethodMenuItem(const std::string& key) = 0; + // Connects a receiver to the InputEngineManager instance. + virtual void ConnectInputEngineManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> + receiver) = 0; + virtual bool IsISOLevel5ShiftUsedByCurrentInputMethod() const = 0; virtual bool IsAltGrUsedByCurrentInputMethod() const = 0;
diff --git a/ui/base/ime/chromeos/mock_ime_engine_handler.h b/ui/base/ime/chromeos/mock_ime_engine_handler.h index 6bffecf..8af256d 100644 --- a/ui/base/ime/chromeos/mock_ime_engine_handler.h +++ b/ui/base/ime/chromeos/mock_ime_engine_handler.h
@@ -21,6 +21,7 @@ MockIMEEngineHandler(); ~MockIMEEngineHandler() override; + // ui::IMEEngineHandlerInterface: void FocusIn(const InputContext& input_context) override; void FocusOut() override; void Enable(const std::string& component_id) override;
diff --git a/ui/base/ime/chromeos/mock_input_method_manager.cc b/ui/base/ime/chromeos/mock_input_method_manager.cc index cad118e..570c59b9 100644 --- a/ui/base/ime/chromeos/mock_input_method_manager.cc +++ b/ui/base/ime/chromeos/mock_input_method_manager.cc
@@ -149,6 +149,9 @@ void MockInputMethodManager::ActivateInputMethodMenuItem( const std::string& key) {} +void MockInputMethodManager::ConnectInputEngineManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) {} + bool MockInputMethodManager::IsISOLevel5ShiftUsedByCurrentInputMethod() const { return false; }
diff --git a/ui/base/ime/chromeos/mock_input_method_manager.h b/ui/base/ime/chromeos/mock_input_method_manager.h index 2a1a8f5..98cbd0f1 100644 --- a/ui/base/ime/chromeos/mock_input_method_manager.h +++ b/ui/base/ime/chromeos/mock_input_method_manager.h
@@ -98,6 +98,9 @@ std::unique_ptr<InputMethodDescriptors> GetSupportedInputMethods() const override; void ActivateInputMethodMenuItem(const std::string& key) override; + void ConnectInputEngineManager( + mojo::PendingReceiver<chromeos::ime::mojom::InputEngineManager> receiver) + override; bool IsISOLevel5ShiftUsedByCurrentInputMethod() const override; bool IsAltGrUsedByCurrentInputMethod() const override; ImeKeyboard* GetImeKeyboard() override;
diff --git a/ui/base/ime/dummy_input_method.cc b/ui/base/ime/dummy_input_method.cc index da1fdfa..4e3dff4 100644 --- a/ui/base/ime/dummy_input_method.cc +++ b/ui/base/ime/dummy_input_method.cc
@@ -45,10 +45,6 @@ return ui::EventDispatchDetails(); } -AsyncKeyDispatcher* DummyInputMethod::GetAsyncKeyDispatcher() { - return nullptr; -} - void DummyInputMethod::OnTextInputTypeChanged(const TextInputClient* client) { }
diff --git a/ui/base/ime/dummy_input_method.h b/ui/base/ime/dummy_input_method.h index 2702187..9865876 100644 --- a/ui/base/ime/dummy_input_method.h +++ b/ui/base/ime/dummy_input_method.h
@@ -32,7 +32,6 @@ void DetachTextInputClient(TextInputClient* client) override; TextInputClient* GetTextInputClient() const override; ui::EventDispatchDetails DispatchKeyEvent(ui::KeyEvent* event) override; - AsyncKeyDispatcher* GetAsyncKeyDispatcher() override; void OnTextInputTypeChanged(const TextInputClient* client) override; void OnCaretBoundsChanged(const TextInputClient* client) override; void CancelComposition(const TextInputClient* client) override;
diff --git a/ui/base/ime/fuchsia/input_method_fuchsia.cc b/ui/base/ime/fuchsia/input_method_fuchsia.cc index 34d7c0a..f3d0e1a2 100644 --- a/ui/base/ime/fuchsia/input_method_fuchsia.cc +++ b/ui/base/ime/fuchsia/input_method_fuchsia.cc
@@ -8,7 +8,6 @@ #include <memory> #include <utility> -#include "base/bind_helpers.h" #include "base/fuchsia/service_directory_client.h" #include "ui/base/ime/text_input_client.h" #include "ui/events/base_event_utils.h" @@ -43,11 +42,10 @@ // If no text input client, do nothing. if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event, base::NullCallback()); + return DispatchKeyEventPostIME(event); // Insert the character. - ui::EventDispatchDetails dispatch_details = - DispatchKeyEventPostIME(event, base::NullCallback()); + ui::EventDispatchDetails dispatch_details = DispatchKeyEventPostIME(event); if (!event->stopped_propagation() && !dispatch_details.dispatcher_destroyed && event->type() == ET_KEY_PRESSED && GetTextInputClient()) { const uint16_t ch = event->GetCharacter();
diff --git a/ui/base/ime/input_method.h b/ui/base/ime/input_method.h index 85eeef83..b400ece 100644 --- a/ui/base/ime/input_method.h +++ b/ui/base/ime/input_method.h
@@ -28,7 +28,6 @@ class InputMethodDelegate; } // namespace internal -class AsyncKeyDispatcher; class InputMethodKeyboardController; class InputMethodObserver; class KeyEvent; @@ -108,12 +107,6 @@ virtual ui::EventDispatchDetails DispatchKeyEvent(ui::KeyEvent* event) WARN_UNUSED_RESULT = 0; - // Gets the async key dispatcher interface which is used to dispatch key - // events with a callback. Some platforms (e.g. ChromeOS) require a callback - // to dispatch the key event, so DispatchKeyEvent() doesn't match the need. - // Returns null on platforms that aren't async. - virtual AsyncKeyDispatcher* GetAsyncKeyDispatcher() = 0; - // Called by the focused client whenever its text input type is changed. // Before calling this method, the focused client must confirm or clear // existing composition text and call InputMethod::CancelComposition() when @@ -193,16 +186,6 @@ bool track_key_events_for_testing_; }; -// An interface to support dispatch key event with a callback. -// This is required on certain platforms, e.g. ChromeOS. -class AsyncKeyDispatcher { - public: - // Dispatches a key event with a callback to receive the result of whether - // the event is handled by the input method. - virtual void DispatchKeyEventAsync(ui::KeyEvent* event, - base::OnceCallback<void(bool)> cb) = 0; -}; - } // namespace ui #endif // UI_BASE_IME_INPUT_METHOD_H_
diff --git a/ui/base/ime/input_method_base.cc b/ui/base/ime/input_method_base.cc index b621ced..8096412 100644 --- a/ui/base/ime/input_method_base.cc +++ b/ui/base/ime/input_method_base.cc
@@ -86,10 +86,6 @@ text_input_client_->EnsureCaretNotInRect(keyboard_bounds_); } -AsyncKeyDispatcher* InputMethodBase::GetAsyncKeyDispatcher() { - return nullptr; -} - void InputMethodBase::OnTextInputTypeChanged(const TextInputClient* client) { if (!IsTextInputClientFocused(client)) return; @@ -163,16 +159,9 @@ } ui::EventDispatchDetails InputMethodBase::DispatchKeyEventPostIME( - ui::KeyEvent* event, - ResultCallback result_callback) const { - if (delegate_) { - return delegate_->DispatchKeyEventPostIME(event, - std::move(result_callback)); - } - - if (result_callback) - std::move(result_callback).Run(false, false); - return EventDispatchDetails(); + ui::KeyEvent* event) const { + return delegate_ ? delegate_->DispatchKeyEventPostIME(event) + : ui::EventDispatchDetails(); } void InputMethodBase::NotifyTextInputStateChanged( @@ -222,7 +211,7 @@ bool InputMethodBase::SendFakeProcessKeyEvent(bool pressed) const { KeyEvent evt(pressed ? ET_KEY_PRESSED : ET_KEY_RELEASED, pressed ? VKEY_PROCESSKEY : VKEY_UNKNOWN, EF_IME_FABRICATED_KEY); - ignore_result(DispatchKeyEventPostIME(&evt, base::NullCallback())); + ignore_result(DispatchKeyEventPostIME(&evt)); return evt.stopped_propagation(); }
diff --git a/ui/base/ime/input_method_base.h b/ui/base/ime/input_method_base.h index fb57c53..d6c0f534 100644 --- a/ui/base/ime/input_method_base.h +++ b/ui/base/ime/input_method_base.h
@@ -52,7 +52,6 @@ void DetachTextInputClient(TextInputClient* client) override; TextInputClient* GetTextInputClient() const override; void SetOnScreenKeyboardBounds(const gfx::Rect& new_bounds) override; - AsyncKeyDispatcher* GetAsyncKeyDispatcher() override; // If a derived class overrides this method, it should call parent's // implementation. @@ -73,9 +72,6 @@ InputMethodKeyboardController* GetInputMethodKeyboardController() override; protected: - // See InputMethodDelegate for details on this. - using ResultCallback = base::OnceCallback<void(bool, bool)>; - explicit InputMethodBase(internal::InputMethodDelegate* delegate); InputMethodBase(internal::InputMethodDelegate* delegate, std::unique_ptr<InputMethodKeyboardController> controller); @@ -120,11 +116,8 @@ // input type is not TEXT_INPUT_TYPE_NONE. void OnInputMethodChanged() const; - // See InputMethodDelegate::DispatchKeyEventPostIME(() for details on - // callback. virtual ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* event, - ResultCallback result_callback) const WARN_UNUSED_RESULT; + ui::KeyEvent* event) const WARN_UNUSED_RESULT; // Convenience method to notify all observers of TextInputClient changes. void NotifyTextInputStateChanged(const TextInputClient* client);
diff --git a/ui/base/ime/input_method_delegate.cc b/ui/base/ime/input_method_delegate.cc deleted file mode 100644 index a0e165d..0000000 --- a/ui/base/ime/input_method_delegate.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2018 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 "ui/base/ime/input_method_delegate.h" - -#include "ui/events/event.h" - -namespace ui { -namespace internal { - -// static -void InputMethodDelegate::RunDispatchKeyEventPostIMECallback( - KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) { - if (!callback) - return; - std::move(callback).Run(key_event->handled(), - key_event->stopped_propagation()); -} - -} // namespace internal -} // namespace ui
diff --git a/ui/base/ime/input_method_delegate.h b/ui/base/ime/input_method_delegate.h index c6c238cf..2a81f6c 100644 --- a/ui/base/ime/input_method_delegate.h +++ b/ui/base/ime/input_method_delegate.h
@@ -5,7 +5,6 @@ #ifndef UI_BASE_IME_INPUT_METHOD_DELEGATE_H_ #define UI_BASE_IME_INPUT_METHOD_DELEGATE_H_ -#include "base/callback.h" #include "base/component_export.h" namespace ui { @@ -22,22 +21,9 @@ public: virtual ~InputMethodDelegate() {} - using DispatchKeyEventPostIMECallback = base::OnceCallback<void(bool, bool)>; // Dispatch a key event already processed by the input method. Returns the - // status of processing, as well as running the callback |callback| with the - // result of processing. |callback| may be run asynchronously (if the - // delegate does processing async). Subclasses can use - // RunDispatchKeyEventPostIMECallback() to run the callback. |callback| is - // supplied two booleans that correspond to event->handled() and - // event->stopped_propagation(). - virtual EventDispatchDetails DispatchKeyEventPostIME( - KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) = 0; - - protected: - static void RunDispatchKeyEventPostIMECallback( - KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback); + // status of processing. + virtual EventDispatchDetails DispatchKeyEventPostIME(KeyEvent* key_event) = 0; }; } // namespace internal
diff --git a/ui/base/ime/input_method_minimal.cc b/ui/base/ime/input_method_minimal.cc index fb00879..98b1cd0 100644 --- a/ui/base/ime/input_method_minimal.cc +++ b/ui/base/ime/input_method_minimal.cc
@@ -6,7 +6,6 @@ #include <stdint.h> -#include "base/bind_helpers.h" #include "ui/base/ime/text_input_client.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" @@ -24,11 +23,10 @@ // If no text input client, do nothing. if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event, base::NullCallback()); + return DispatchKeyEventPostIME(event); // Insert the character. - ui::EventDispatchDetails dispatch_details = - DispatchKeyEventPostIME(event, base::NullCallback()); + ui::EventDispatchDetails dispatch_details = DispatchKeyEventPostIME(event); if (!event->stopped_propagation() && !dispatch_details.dispatcher_destroyed && event->type() == ET_KEY_PRESSED && GetTextInputClient()) { const uint16_t ch = event->GetCharacter();
diff --git a/ui/base/ime/input_method_minimal_unittest.cc b/ui/base/ime/input_method_minimal_unittest.cc index f8d2a506..787815aa 100644 --- a/ui/base/ime/input_method_minimal_unittest.cc +++ b/ui/base/ime/input_method_minimal_unittest.cc
@@ -21,11 +21,9 @@ ~InputMethodDelegateForTesting() override {} ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) override { + ui::KeyEvent* key_event) override { if (!propagation_post_ime_) key_event->StopPropagation(); - RunDispatchKeyEventPostIMECallback(key_event, std::move(callback)); return ui::EventDispatchDetails(); }
diff --git a/ui/base/ime/linux/input_method_auralinux.cc b/ui/base/ime/linux/input_method_auralinux.cc index 45066f81..0393ec85 100644 --- a/ui/base/ime/linux/input_method_auralinux.cc +++ b/ui/base/ime/linux/input_method_auralinux.cc
@@ -6,7 +6,6 @@ #include "base/auto_reset.h" #include "base/bind.h" -#include "base/bind_helpers.h" #include "base/environment.h" #include "ui/base/ime/ime_bridge.h" #include "ui/base/ime/ime_engine_handler_interface.h" @@ -56,12 +55,11 @@ // If no text input client, do nothing. if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event, base::NullCallback()); + return DispatchKeyEventPostIME(event); if (!event->HasNativeEvent() && sending_key_event()) { // Faked key events that are sent from input.ime.sendKeyEvents. - ui::EventDispatchDetails details = - DispatchKeyEventPostIME(event, base::NullCallback()); + ui::EventDispatchDetails details = DispatchKeyEventPostIME(event); if (details.dispatcher_destroyed || details.target_destroyed || event->stopped_propagation()) { return details; @@ -139,7 +137,7 @@ ui::EventDispatchDetails details; if (event->type() == ui::ET_KEY_PRESSED && filtered) { if (NeedInsertChar()) - details = DispatchKeyEventPostIME(event, base::NullCallback()); + details = DispatchKeyEventPostIME(event); else if (HasInputMethodResult()) details = SendFakeProcessKeyEvent(event); if (details.dispatcher_destroyed) @@ -198,7 +196,7 @@ composition_ = CompositionText(); if (!filtered) { - details = DispatchKeyEventPostIME(event, base::NullCallback()); + details = DispatchKeyEventPostIME(event); if (details.dispatcher_destroyed) { if (should_stop_propagation) event->StopPropagation(); @@ -445,8 +443,7 @@ ui::EventDispatchDetails InputMethodAuraLinux::SendFakeProcessKeyEvent( ui::KeyEvent* event) const { KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_PROCESSKEY, event->flags()); - ui::EventDispatchDetails details = - DispatchKeyEventPostIME(&key_event, base::NullCallback()); + ui::EventDispatchDetails details = DispatchKeyEventPostIME(&key_event); if (key_event.stopped_propagation()) event->StopPropagation(); return details;
diff --git a/ui/base/ime/linux/input_method_auralinux_unittest.cc b/ui/base/ime/linux/input_method_auralinux_unittest.cc index ad01a466..11581c8 100644 --- a/ui/base/ime/linux/input_method_auralinux_unittest.cc +++ b/ui/base/ime/linux/input_method_auralinux_unittest.cc
@@ -171,8 +171,7 @@ ~InputMethodDelegateForTesting() override {} ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* key_event, - DispatchKeyEventPostIMECallback callback) override { + ui::KeyEvent* key_event) override { std::string action; switch (key_event->type()) { case ET_KEY_PRESSED: @@ -188,7 +187,6 @@ ss << key_event->key_code(); action += std::string(ss.str()); TestResult::GetInstance()->RecordAction(base::ASCIIToUTF16(action)); - RunDispatchKeyEventPostIMECallback(key_event, std::move(callback)); return ui::EventDispatchDetails(); }
diff --git a/ui/base/ime/mac/input_method_mac.mm b/ui/base/ime/mac/input_method_mac.mm index d7a6cd89..ea0ff878 100644 --- a/ui/base/ime/mac/input_method_mac.mm +++ b/ui/base/ime/mac/input_method_mac.mm
@@ -6,8 +6,6 @@ #import <Cocoa/Cocoa.h> -#include "base/bind_helpers.h" - namespace ui { InputMethodMac::InputMethodMac(internal::InputMethodDelegate* delegate) @@ -18,7 +16,7 @@ ui::EventDispatchDetails InputMethodMac::DispatchKeyEvent(ui::KeyEvent* event) { // This is used on Mac only to dispatch events post-IME. - return DispatchKeyEventPostIME(event, base::NullCallback()); + return DispatchKeyEventPostIME(event); } void InputMethodMac::OnCaretBoundsChanged(const TextInputClient* client) {
diff --git a/ui/base/ime/mock_input_method.cc b/ui/base/ime/mock_input_method.cc index 733cd97..17555ca 100644 --- a/ui/base/ime/mock_input_method.cc +++ b/ui/base/ime/mock_input_method.cc
@@ -45,11 +45,7 @@ ui::EventDispatchDetails MockInputMethod::DispatchKeyEvent( ui::KeyEvent* event) { - return delegate_->DispatchKeyEventPostIME(event, base::NullCallback()); -} - -AsyncKeyDispatcher* MockInputMethod::GetAsyncKeyDispatcher() { - return nullptr; + return delegate_->DispatchKeyEventPostIME(event); } void MockInputMethod::OnFocus() {
diff --git a/ui/base/ime/mock_input_method.h b/ui/base/ime/mock_input_method.h index d343865f..2d72e99a 100644 --- a/ui/base/ime/mock_input_method.h +++ b/ui/base/ime/mock_input_method.h
@@ -44,7 +44,6 @@ void DetachTextInputClient(TextInputClient* client) override; TextInputClient* GetTextInputClient() const override; ui::EventDispatchDetails DispatchKeyEvent(ui::KeyEvent* event) override; - AsyncKeyDispatcher* GetAsyncKeyDispatcher() override; void OnTextInputTypeChanged(const TextInputClient* client) override; void OnCaretBoundsChanged(const TextInputClient* client) override; void CancelComposition(const TextInputClient* client) override;
diff --git a/ui/base/ime/win/input_method_win_base.cc b/ui/base/ime/win/input_method_win_base.cc index 3b7a46b8..9d01493 100644 --- a/ui/base/ime/win/input_method_win_base.cc +++ b/ui/base/ime/win/input_method_win_base.cc
@@ -10,7 +10,6 @@ #include "base/auto_reset.h" #include "base/bind.h" -#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/win/windows_version.h" @@ -492,8 +491,7 @@ ui::KeyEvent* event, const std::vector<MSG>* char_msgs) { DCHECK(event); - ui::EventDispatchDetails details = - DispatchKeyEventPostIME(event, base::NullCallback()); + ui::EventDispatchDetails details = DispatchKeyEventPostIME(event); if (details.dispatcher_destroyed || details.target_destroyed || event->stopped_propagation()) { return details;
diff --git a/ui/base/ime/win/tsf_text_store.cc b/ui/base/ime/win/tsf_text_store.cc index 3cfcb46d..44c6954 100644 --- a/ui/base/ime/win/tsf_text_store.cc +++ b/ui/base/ime/win/tsf_text_store.cc
@@ -11,7 +11,6 @@ #include <algorithm> -#include "base/bind_helpers.h" #include "base/win/scoped_variant.h" #include "ui/base/ime/text_input_client.h" #include "ui/base/ime/win/tsf_input_scope.h" @@ -825,8 +824,7 @@ ui::KeyEvent key_event = KeyEventFromMSG(key_event_MSG); if (input_method_delegate_) { - input_method_delegate_->DispatchKeyEventPostIME(&key_event, - base::NullCallback()); + input_method_delegate_->DispatchKeyEventPostIME(&key_event); } }
diff --git a/ui/base/ime/win/tsf_text_store_unittest.cc b/ui/base/ime/win/tsf_text_store_unittest.cc index 8b19659..79c1215d 100644 --- a/ui/base/ime/win/tsf_text_store_unittest.cc +++ b/ui/base/ime/win/tsf_text_store_unittest.cc
@@ -75,9 +75,7 @@ class MockInputMethodDelegate : public internal::InputMethodDelegate { public: ~MockInputMethodDelegate() {} - MOCK_METHOD2(DispatchKeyEventPostIME, - EventDispatchDetails(KeyEvent*, - base::OnceCallback<void(bool, bool)>)); + MOCK_METHOD1(DispatchKeyEventPostIME, EventDispatchDetails(KeyEvent*)); }; class MockStoreACPSink : public ITextStoreACPSink { @@ -1510,9 +1508,7 @@ SetHasCompositionText(true); } - ui::EventDispatchDetails DispatchKeyEventPostIME1( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME1(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -1559,17 +1555,13 @@ SetHasCompositionText(true); } - ui::EventDispatchDetails DispatchKeyEventPostIME2( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME2(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_RELEASED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); } - ui::EventDispatchDetails DispatchKeyEventPostIME3a( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME3a(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -1594,9 +1586,7 @@ SetHasCompositionText(false); } - ui::EventDispatchDetails DispatchKeyEventPostIME3b( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME3b(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_RELEASED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -1622,7 +1612,7 @@ .WillOnce(Invoke(&callback, &KeyEventTestCallback::InsertText2)) .WillOnce(Invoke(&callback, &KeyEventTestCallback::InsertText3)); - EXPECT_CALL(input_method_delegate_, DispatchKeyEventPostIME(_, _)) + EXPECT_CALL(input_method_delegate_, DispatchKeyEventPostIME(_)) .WillOnce( Invoke(&callback, &KeyEventTestCallback::DispatchKeyEventPostIME1)) .WillOnce( @@ -2452,9 +2442,7 @@ return S_OK; } - ui::EventDispatchDetails DispatchKeyEventPostIME1( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME1(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -2499,17 +2487,13 @@ return S_OK; } - ui::EventDispatchDetails DispatchKeyEventPostIME2a( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME2a(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_RELEASED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); } - ui::EventDispatchDetails DispatchKeyEventPostIME2b( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME2b(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -2547,9 +2531,7 @@ return S_OK; } - ui::EventDispatchDetails DispatchKeyEventPostIME3( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME3(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_RELEASED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -2576,9 +2558,7 @@ return S_OK; } - ui::EventDispatchDetails DispatchKeyEventPostIME4( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME4(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -2613,17 +2593,13 @@ return S_OK; } - ui::EventDispatchDetails DispatchKeyEventPostIME5a( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME5a(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_RELEASED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); } - ui::EventDispatchDetails DispatchKeyEventPostIME5b( - KeyEvent* key, - base::OnceCallback<void(bool, bool)> ack_callback) { + ui::EventDispatchDetails DispatchKeyEventPostIME5b(KeyEvent* key) { EXPECT_EQ(ui::ET_KEY_PRESSED, key->type()); EXPECT_EQ(VKEY_PROCESSKEY, key->key_code()); return ui::EventDispatchDetails(); @@ -2676,7 +2652,7 @@ .WillOnce( Invoke(&callback, &RegressionTestCallback::SetCompositionText5)); - EXPECT_CALL(input_method_delegate_, DispatchKeyEventPostIME(_, _)) + EXPECT_CALL(input_method_delegate_, DispatchKeyEventPostIME(_)) .WillOnce( Invoke(&callback, &RegressionTestCallback::DispatchKeyEventPostIME1)) .WillOnce(
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js index 63b23a66..e87f4f14 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
@@ -397,13 +397,20 @@ const menu = event.menu; // Set focus asynchronously to give time for menu "show" event to finish and // have all items set up before focusing. - setTimeout(() => menu.focusSelectedItem(), 0); + setTimeout(() => { + if (!menu.hidden) { + menu.focusSelectedItem(); + } + }, 0); } /** @param {!Event} event */ onContextMenuHide_(event) { if (this.lastFocusedElement_) { - this.lastFocusedElement_.focus(); + const activeElement = document.activeElement; + if (activeElement && activeElement.tagName === 'BODY') { + this.lastFocusedElement_.focus(); + } this.lastFocusedElement_ = null; } }
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index 0b40479c..bf0e7c0 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -323,6 +323,13 @@ ] } + if (is_android || is_fuchsia || is_win) { + sources += [ + "font_fallback_skia_impl.cc", + "font_fallback_skia_impl.h", + ] + } + if (!is_ios) { sources += [ "bidi_line_iterator.cc",
diff --git a/ui/gfx/font_fallback_skia.cc b/ui/gfx/font_fallback_skia.cc index 3a2904e..2a87842 100644 --- a/ui/gfx/font_fallback_skia.cc +++ b/ui/gfx/font_fallback_skia.cc
@@ -10,12 +10,8 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" -#include "third_party/icu/source/common/unicode/uchar.h" -#include "third_party/icu/source/common/unicode/uscript.h" -#include "third_party/icu/source/common/unicode/utf16.h" -#include "third_party/skia/include/core/SkFontMgr.h" -#include "third_party/skia/include/core/SkTypeface.h" #include "ui/gfx/font.h" +#include "ui/gfx/font_fallback_skia_impl.h" namespace gfx { @@ -32,64 +28,15 @@ if (text.empty()) return false; - sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); + std::string skia_family_name = + GetFallbackFontFamilyNameSkia(font, locale, text); - const char* bcp47_locales[] = {locale.c_str()}; - int num_locales = locale.empty() ? 0 : 1; - const char** locales = locale.empty() ? nullptr : bcp47_locales; + if (skia_family_name.empty()) + return false; - const int font_weight = (font.GetWeight() == Font::Weight::INVALID) - ? static_cast<int>(Font::Weight::NORMAL) - : static_cast<int>(font.GetWeight()); - const bool italic = (font.GetStyle() & Font::ITALIC) != 0; - SkFontStyle skia_style( - font_weight, SkFontStyle::kNormal_Width, - italic ? SkFontStyle::kItalic_Slant : SkFontStyle::kUpright_Slant); - - std::set<SkFontID> tested_typeface; - SkString skia_family_name; - size_t fewest_missing_glyphs = text.length() + 1; - - size_t offset = 0; - while (offset < text.length()) { - UChar32 code_point; - U16_NEXT(text.data(), offset, text.length(), code_point); - - sk_sp<SkTypeface> typeface(font_mgr->matchFamilyStyleCharacter( - font.GetFontName().c_str(), skia_style, locales, num_locales, - code_point)); - // If the typeface is not found or was already tested, skip it. - if (!typeface || !tested_typeface.insert(typeface->uniqueID()).second) - continue; - - // Validate that every character has a known glyph in the font. - size_t missing_glyphs = 0; - size_t i = 0; - while (i < text.length()) { - UChar32 c; - U16_NEXT(text.data(), i, text.length(), c); - if (typeface->unicharToGlyph(c) == 0) - ++missing_glyphs; - } - - if (missing_glyphs < fewest_missing_glyphs) { - fewest_missing_glyphs = missing_glyphs; - typeface->getFamilyName(&skia_family_name); - } - - // The font is a valid fallback font for the given text. - if (missing_glyphs == 0) - break; - } - - if (!skia_family_name.isEmpty()) { - *result = - Font(std::string(skia_family_name.c_str(), skia_family_name.size()), - font.GetFontSize()); - return true; - } - - return false; + *result = Font(std::string(skia_family_name.c_str(), skia_family_name.size()), + font.GetFontSize()); + return true; } } // namespace gfx
diff --git a/ui/gfx/font_fallback_skia_impl.cc b/ui/gfx/font_fallback_skia_impl.cc new file mode 100644 index 0000000..11870a6 --- /dev/null +++ b/ui/gfx/font_fallback_skia_impl.cc
@@ -0,0 +1,76 @@ +// Copyright 2019 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 "ui/gfx/font_fallback_skia_impl.h" + +#include <set> +#include <string> + +#include "third_party/icu/source/common/unicode/uchar.h" +#include "third_party/icu/source/common/unicode/utf16.h" +#include "third_party/skia/include/core/SkFontMgr.h" +#include "third_party/skia/include/core/SkTypeface.h" + +namespace gfx { + +std::string GetFallbackFontFamilyNameSkia(const Font& template_font, + const std::string& locale, + base::StringPiece16 text) { + if (text.empty()) + return std::string(); + + sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); + + const char* bcp47_locales[] = {locale.c_str()}; + int num_locales = locale.empty() ? 0 : 1; + const char** locales = locale.empty() ? nullptr : bcp47_locales; + + const int font_weight = (template_font.GetWeight() == Font::Weight::INVALID) + ? static_cast<int>(Font::Weight::NORMAL) + : static_cast<int>(template_font.GetWeight()); + const bool italic = (template_font.GetStyle() & Font::ITALIC) != 0; + SkFontStyle skia_style( + font_weight, SkFontStyle::kNormal_Width, + italic ? SkFontStyle::kItalic_Slant : SkFontStyle::kUpright_Slant); + + std::set<SkFontID> tested_typeface; + SkString skia_family_name; + size_t fewest_missing_glyphs = text.length() + 1; + + size_t offset = 0; + while (offset < text.length()) { + UChar32 code_point; + U16_NEXT(text.data(), offset, text.length(), code_point); + + sk_sp<SkTypeface> typeface(font_mgr->matchFamilyStyleCharacter( + template_font.GetFontName().c_str(), skia_style, locales, num_locales, + code_point)); + // If the typeface is not found or was already tested, skip it. + if (!typeface || !tested_typeface.insert(typeface->uniqueID()).second) + continue; + + // Validate that every character has a known glyph in the font. + size_t missing_glyphs = 0; + size_t i = 0; + while (i < text.length()) { + UChar32 c; + U16_NEXT(text.data(), i, text.length(), c); + if (typeface->unicharToGlyph(c) == 0) + ++missing_glyphs; + } + + if (missing_glyphs < fewest_missing_glyphs) { + fewest_missing_glyphs = missing_glyphs; + typeface->getFamilyName(&skia_family_name); + } + + // The font is a valid fallback font for the given text. + if (missing_glyphs == 0) + break; + } + + return skia_family_name.c_str(); +} + +} // namespace gfx
diff --git a/ui/gfx/font_fallback_skia_impl.h b/ui/gfx/font_fallback_skia_impl.h new file mode 100644 index 0000000..2284c780 --- /dev/null +++ b/ui/gfx/font_fallback_skia_impl.h
@@ -0,0 +1,20 @@ +// Copyright 2019 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 UI_GFX_FONT_FALLBACK_SKIA_IMPL_H_ +#define UI_GFX_FONT_FALLBACK_SKIA_IMPL_H_ + +#include <string> + +#include "base/strings/string_piece.h" +#include "ui/gfx/font.h" + +namespace gfx { + +std::string GetFallbackFontFamilyNameSkia(const Font& template_font, + const std::string& locale, + base::StringPiece16 text); +} + +#endif // UI_GFX_FONT_FALLBACK_SKIA_IMPL_H_
diff --git a/ui/gfx/font_fallback_win.cc b/ui/gfx/font_fallback_win.cc index 9c4a340..0e266b9 100644 --- a/ui/gfx/font_fallback_win.cc +++ b/ui/gfx/font_fallback_win.cc
@@ -26,8 +26,7 @@ #include "base/win/scoped_gdi_object.h" #include "ui/gfx/font.h" #include "ui/gfx/font_fallback.h" -#include "ui/gfx/win/direct_write.h" -#include "ui/gfx/win/text_analysis_source.h" +#include "ui/gfx/font_fallback_skia_impl.h" namespace gfx { @@ -188,233 +187,10 @@ CachedFontLinkSettings::~CachedFontLinkSettings() { } -struct MetaFileEnumState { - DWORD current_font_handle = 0; - std::map<DWORD, std::string> font_handle_map; - base::StringPiece16 expected_text; - std::string fallback_font_name; - bool found_fallback = false; -}; - -// Callback to |EnumEnhMetaFile()| to intercept font creation. -int CALLBACK MetaFileEnumProc(HDC hdc, - HANDLETABLE* table, - CONST ENHMETARECORD* record, - int table_entries, - LPARAM param_state) { - // The MetaFileEnumProc() is called for every record produced in the metafile. - // The following code is processing the records and keep track of active - // objects in MetaFileEnumState struct. The state machine recognizes fonts - // creation, select object, delete object and text output. The fallback font - // is the active font when the expected text is outputted. - MetaFileEnumState* state = reinterpret_cast<MetaFileEnumState*>(param_state); - if (record->iType == EMR_EXTCREATEFONTINDIRECTW) { - const EMREXTCREATEFONTINDIRECTW* create_font_record = - reinterpret_cast<const EMREXTCREATEFONTINDIRECTW*>(record); - DWORD handle = create_font_record->ihFont; - if (create_font_record->elfw.elfLogFont.lfFaceName[0]) { - state->font_handle_map[handle] = - base::UTF16ToUTF8(create_font_record->elfw.elfLogFont.lfFaceName); - } else { - // The font has no name. Removing the object from the set of known - // objects to avoid reporting the previous object has the fallback font. - DCHECK(!create_font_record->elfw.elfFullName[0]); - state->font_handle_map.erase(handle); - } - } else if (record->iType == EMR_SELECTOBJECT) { - const EMRSELECTOBJECT* select_record = - reinterpret_cast<const EMRSELECTOBJECT*>(record); - state->current_font_handle = select_record->ihObject; - } else if (record->iType == EMR_DELETEOBJECT) { - const EMRSELECTOBJECT* delete_record = - reinterpret_cast<const EMRDELETEOBJECT*>(record); - state->font_handle_map.erase(delete_record->ihObject); - } else if (record->iType == EMR_EXTTEXTOUTW) { - const EMREXTTEXTOUTW* textout_record = - reinterpret_cast<const EMREXTTEXTOUTW*>(record); - - // Retrieve the text displayed. The outputted text can be retrieved after - // the record structure; the record contains a bytes offset to the beginning - // of the text. - const wchar_t* raw_chars = reinterpret_cast<const wchar_t*>( - reinterpret_cast<const uint8_t*>(textout_record) + - textout_record->emrtext.offString); - const int text_length = textout_record->emrtext.nChars; - base::StringPiece16 text(raw_chars, text_length); - - if (text == state->expected_text) { - // The expected text is displayed. Collect the current font information. - auto it = state->font_handle_map.find(state->current_font_handle); - if (it != state->font_handle_map.end()) - state->fallback_font_name = it->second; - state->found_fallback = !state->fallback_font_name.empty(); - } else if (text != L" ") { - // Output of a space may be used for text alignment. If any other text is - // outputted, the code returns a failure and stop processing records. - return 0; - } - } - - // This function must return a nonzero value to continue enumeration; to stop - // enumeration, it must return zero. - return 1; -} - -// Retrieve the font family name for the DWrite font |mapped_font|. The font -// family name is the non-localized name. On failure, returns false. -bool GetFontFamilyNameFromDWriteFont(IDWriteFont* mapped_font, - std::string* result) { - Microsoft::WRL::ComPtr<IDWriteFontFamily> font_family; - HRESULT hr = mapped_font->GetFontFamily(&font_family); - if (FAILED(hr)) - return false; - - Microsoft::WRL::ComPtr<IDWriteLocalizedStrings> family_names; - hr = font_family->GetFamilyNames(&family_names); - if (FAILED(hr)) - return false; - - // Index zero is the non localized family name. - constexpr UINT32 locale_index = 0; - - // Retrieve the family name string length. - UINT32 name_length = 0; - hr = family_names->GetStringLength(locale_index, &name_length); - if (FAILED(hr)) - return false; - - // Size of the string must include the ending NUL character. - name_length += 1; - - std::unique_ptr<wchar_t[]> family_name_for_locale(new wchar_t[name_length]); - hr = family_names->GetString(locale_index, family_name_for_locale.get(), - name_length); - if (FAILED(hr)) - return false; - - *result = base::WideToUTF8(family_name_for_locale.get()); - return true; -} - } // namespace namespace internal { -// The |GetUniscribeFallbackFont| try to find fallback font by using the Windows -// uniscribe API. -// -// Adapted from WebKit's |FontCache::GetFontDataForCharacters()|. -// Uniscribe doesn't expose a method to query fallback fonts, so this works by -// drawing the text to an EMF object with Uniscribe's ScriptStringOut and then -// inspecting the EMF object to figure out which font Uniscribe used. -// -// DirectWrite in Windows 8.1 provides a cleaner alternative: -// http://msdn.microsoft.com/en-us/library/windows/desktop/dn280480.aspx -// -// Example of a EMR script: -// EMR_HEADER -// EMR_EXTCREATEFONTINDIRECTW ID:1 (Set Font Segoe UI) -// EMR_SELECTOBJECT ID:1 -// EMR_EXTCREATEFONTINDIRECTW ID:2 (Set Font Gadugi) -// EMR_SELECTOBJECT ID:2 -// EMR_SELECTOBJECT ID:1 -// EMR_DELETEOBJECT ID:2 -// EMR_EXTCREATEFONTINDIRECTW ID:2 (Set Font Gadugi) -// EMR_SELECTOBJECT ID:2 -// EMR_SELECTOBJECT ID:1 -// EMR_EXTTEXTOUTW " " -// EMR_SETTEXTALIGN -// EMR_SETBKMODE -// EMR_MOVETOEX -// EMR_SETTEXTALIGN -// EMR_SELECTOBJECT ID:2 -// EMR_EXTTEXTOUTW "..." -// EMR_SELECTOBJECT ID:1 -// EMR_MOVETOEX -// EMR_SETTEXTALIGN -// MR_SETBKMODE -// EMR_DELETEOBJECT ID:2 -// EMR_EOF -bool GetUniscribeFallbackFont(const Font& font, - const std::string& locale, - base::StringPiece16 text, - Font* result) { - static HDC hdc = CreateCompatibleDC(NULL); - - // TODO(etienneb): Support locale with uniscribe font fallback. - - // The length passed to |ScriptStringAnalyse| must be at least 1. - if (text.empty()) - return false; - - // Use a meta file to intercept the fallback font chosen by Uniscribe. - HDC meta_file_dc = CreateEnhMetaFile(hdc, NULL, NULL, NULL); - if (!meta_file_dc) - return false; - - // Extracts |fonts| properties. - const DWORD italic = (font.GetStyle() & Font::ITALIC) ? TRUE : FALSE; - const DWORD underline = (font.GetStyle() & Font::UNDERLINE) ? TRUE : FALSE; - // The font mapper matches its absolute value against the character height of - // the available fonts. - const int height = -font.GetFontSize(); - - // Select the primary font which force a mapping to a physical font. - base::win::ScopedHFONT primary_font(::CreateFont( - height, 0, 0, 0, static_cast<int>(font.GetWeight()), italic, underline, - FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, - DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, - base::UTF8ToUTF16(font.GetFontName()).c_str())); - SelectObject(meta_file_dc, primary_font.get()); - - // Run the script analysis. - SCRIPT_STRING_ANALYSIS script_analysis; - HRESULT hresult = - ScriptStringAnalyse(meta_file_dc, text.data(), text.length(), 0, -1, - SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK, - 0, NULL, NULL, NULL, NULL, NULL, &script_analysis); - - if (SUCCEEDED(hresult)) { - hresult = ScriptStringOut(script_analysis, 0, 0, 0, NULL, 0, 0, FALSE); - ScriptStringFree(&script_analysis); - } - - MetaFileEnumState state; - state.expected_text = text; - - HENHMETAFILE meta_file = CloseEnhMetaFile(meta_file_dc); - if (SUCCEEDED(hresult)) { - BOOL eumeration_success = - EnumEnhMetaFile(0, meta_file, MetaFileEnumProc, &state, NULL); - // If the enumeration didn't succeed, we are assuming there are unknown - // command and the fallback font can't be determined. - if (eumeration_success != TRUE) { - state.fallback_font_name = ""; - state.found_fallback = false; - } - } - DeleteEnhMetaFile(meta_file); - - // Same font, no fallback font required. - if (state.fallback_font_name == font.GetFontName()) { - state.fallback_font_name.clear(); - state.found_fallback = false; - } - - // The uniscribe code is selecting the 'Microsoft Sans Serif' as a last-resort - // font when it's unable to determine a valid fallback font. - if (state.fallback_font_name == "Microsoft Sans Serif") { - state.fallback_font_name.clear(); - state.found_fallback = false; - } - - // Create the resulting fallback font. - if (state.found_fallback) - *result = Font(state.fallback_font_name, font.GetFontSize()); - - return state.found_fallback; -} - void ParseFontLinkEntry(const std::string& entry, std::string* filename, std::string* font_name) { @@ -481,58 +257,13 @@ if (text.find(kNulCharacter) != base::StringPiece16::npos) return false; - Microsoft::WRL::ComPtr<IDWriteFactory> factory; - gfx::win::CreateDWriteFactory(factory.GetAddressOf()); - Microsoft::WRL::ComPtr<IDWriteFactory2> factory2; - factory.CopyTo(factory2.GetAddressOf()); - if (!factory2) { - // IDWriteFactory2 is not available before Win8.1 - return internal::GetUniscribeFallbackFont(font, locale, text, result); - } + std::string skia_fallback_family = + GetFallbackFontFamilyNameSkia(font, locale, text); - Microsoft::WRL::ComPtr<IDWriteFontFallback> fallback; - if (FAILED(factory2->GetSystemFontFallback(fallback.GetAddressOf()))) + if (skia_fallback_family.empty()) return false; - base::string16 locale16 = base::UTF8ToUTF16(locale); - - Microsoft::WRL::ComPtr<IDWriteNumberSubstitution> number_substitution; - if (FAILED(factory2->CreateNumberSubstitution( - DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, locale16.c_str(), - true /* ignoreUserOverride */, number_substitution.GetAddressOf()))) { - return false; - } - - uint32_t mapped_length = 0; - Microsoft::WRL::ComPtr<IDWriteFont> mapped_font; - float scale = 0; - Microsoft::WRL::ComPtr<IDWriteTextAnalysisSource> text_analysis; - DWRITE_READING_DIRECTION reading_direction = - base::i18n::IsRTL() ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT - : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT; - if (FAILED(gfx::win::TextAnalysisSource::Create( - &text_analysis, base::string16(text.data(), text.length()), - locale16.c_str(), number_substitution.Get(), reading_direction))) { - return false; - } - base::string16 original_name = base::UTF8ToUTF16(font.GetFontName()); - DWRITE_FONT_STYLE font_style = DWRITE_FONT_STYLE_NORMAL; - if (font.GetStyle() & Font::ITALIC) - font_style = DWRITE_FONT_STYLE_ITALIC; - if (FAILED(fallback->MapCharacters( - text_analysis.Get(), 0, text.length(), nullptr, original_name.c_str(), - static_cast<DWRITE_FONT_WEIGHT>(font.GetWeight()), font_style, - DWRITE_FONT_STRETCH_NORMAL, &mapped_length, &mapped_font, &scale))) { - return false; - } - if (!mapped_font) - return false; - - std::string family_name; - if (!GetFontFamilyNameFromDWriteFont(mapped_font.Get(), &family_name)) - return false; - - *result = Font(family_name, font.GetFontSize() * scale); + *result = Font(skia_fallback_family, font.GetFontSize()); return true; }
diff --git a/ui/gfx/font_fallback_win_unittest.cc b/ui/gfx/font_fallback_win_unittest.cc index a00f6c8c..b1a79edf 100644 --- a/ui/gfx/font_fallback_win_unittest.cc +++ b/ui/gfx/font_fallback_win_unittest.cc
@@ -34,26 +34,16 @@ DISALLOW_COPY_AND_ASSIGN(FontFallbackWinTest); }; -enum class FallbackFontFn { DEFAULT, UNISCRIBE }; - // Options to parameterized unittests. struct FallbackFontTestOption { - FallbackFontFn fallback_font = FallbackFontFn::DEFAULT; bool ignore_get_fallback_failure = false; bool skip_code_point_validation = false; bool skip_fallback_fonts_validation = false; }; -// Options for tests that fully validate the GetFallbackFont(...) parameters. -const FallbackFontTestOption default_fallback_option = { - FallbackFontFn::DEFAULT}; -const FallbackFontTestOption uniscribe_fallback_option = { - FallbackFontFn::UNISCRIBE}; +const FallbackFontTestOption default_fallback_option = {false, false, false}; // Options for tests that does not validate the GetFallbackFont(...) parameters. -const FallbackFontTestOption untested_default_fallback_option = { - FallbackFontFn::DEFAULT, true, true, true}; -const FallbackFontTestOption untested_uniscribe_fallback_option = { - FallbackFontFn::UNISCRIBE, true, true, true}; +const FallbackFontTestOption untested_fallback_option = {true, true, true}; // A font test case for the parameterized unittests. struct FallbackFontTestCase { @@ -74,32 +64,16 @@ static std::string ParamInfoToString( ::testing::TestParamInfo<FallbackFontTestParamInfo> param_info) { const FallbackFontTestCase& test_case = std::get<0>(param_info.param); - const FallbackFontTestOption& options = std::get<1>(param_info.param); - std::string script_name = uscript_getName(test_case.script); - - std::string fallback_fn; - if (options.fallback_font == FallbackFontFn::DEFAULT) - fallback_fn = "DEFAULT"; - else if (options.fallback_font == FallbackFontFn::UNISCRIBE) - fallback_fn = "UNISCRIBE"; - - return base::StringPrintf("%s_%s", script_name.c_str(), - fallback_fn.c_str()); + return uscript_getName(test_case.script); } void SetUp() override { std::tie(test_case_, test_option_) = GetParam(); } protected: bool GetFallbackFont(const Font& font, Font* result) { - if (test_option_.fallback_font == FallbackFontFn::DEFAULT) { - return gfx::GetFallbackFont(font, kDefaultApplicationLocale, - test_case_.text, result); - } else if (test_option_.fallback_font == FallbackFontFn::UNISCRIBE) { - return internal::GetUniscribeFallbackFont(font, kDefaultApplicationLocale, - test_case_.text, result); - } - return false; + return gfx::GetFallbackFont(font, kDefaultApplicationLocale, + test_case_.text, result); } bool EnsuresScriptSupportCodePoints(const base::string16& text, @@ -201,15 +175,6 @@ EXPECT_EQ("Meiryo UI Italic", font_names[3]); } -TEST_F(FontFallbackWinTest, EmptyStringUniscribeFallback) { - Font base_font; - Font fallback_font; - bool result = - internal::GetUniscribeFallbackFont(base_font, kDefaultApplicationLocale, - base::StringPiece16(), &fallback_font); - EXPECT_FALSE(result); -} - TEST_F(FontFallbackWinTest, EmptyStringFallback) { Font base_font; Font fallback_font; @@ -339,20 +304,13 @@ } } -FallbackFontTestCase kGetUniscribeFontFallbackTests[] = { - {USCRIPT_ARABIC, L"\u062A\u062D", {"Segoe UI", "Tahoma"}}, - {USCRIPT_DEVANAGARI, L"\u0905\u0906", {"Mangal", "Nirmala UI"}}, - {USCRIPT_GURMUKHI, L"\u0A21\u0A22", {"Raavi", "Nirmala UI"}}, - {USCRIPT_NEW_TAI_LUE, L"\u1981\u1982", {"Microsoft New Tai Lue"}}, -}; - // A list of script and the fallback font on a default windows installation. // This list may need to be updated if fonts or operating systems are // upgraded. constexpr bool kWin10Only = true; FallbackFontTestCase kGetFontFallbackTests[] = { {USCRIPT_ARABIC, L"\u062A\u062D", {"Segoe UI", "Tahoma"}}, - {USCRIPT_ARMENIAN, L"\u0540\u0541", {"Segoe UI", "Tahoma"}}, + {USCRIPT_ARMENIAN, L"\u0540\u0541", {"Segoe UI", "Tahoma", "Sylfaen"}}, {USCRIPT_BENGALI, L"\u09B8\u09AE", {"Nirmala UI", "Vrinda"}}, {USCRIPT_BRAILLE, L"\u2870\u2871", {"Segoe UI Symbol"}}, {USCRIPT_BUGINESE, L"\u1A00\u1A01", {"Leelawadee UI"}, kWin10Only}, @@ -515,20 +473,10 @@ return result; } -// Ensures that Uniscribe fallback font gives known results. The uniscribe -// fallback is only used on windows 7. For the purpose of tests coverage, we -// are validating its behavior on every windows version. -INSTANTIATE_TEST_SUITE_P( - Uniscribe, - GetFallbackFontTest, - testing::Combine(testing::ValuesIn(kGetUniscribeFontFallbackTests), - testing::Values(uniscribe_fallback_option)), - GetFallbackFontTest::ParamInfoToString); - // Ensures that the default fallback font gives known results. The test // is validating that a known fallback font is given for a given text and font. INSTANTIATE_TEST_SUITE_P( - Default, + KnownExpectedFonts, GetFallbackFontTest, testing::Combine(testing::ValuesIn(kGetFontFallbackTests), testing::Values(default_fallback_option)), @@ -543,7 +491,6 @@ Glyphs, GetFallbackFontTest, testing::Combine(testing::ValuesIn(GetSampleFontTestCases()), - testing::Values(untested_default_fallback_option, - untested_uniscribe_fallback_option)), + testing::Values(untested_fallback_option)), GetFallbackFontTest::ParamInfoToString); } // namespace gfx
diff --git a/ui/gfx/text_elider_unittest.cc b/ui/gfx/text_elider_unittest.cc index 7ebaec08..aee7409 100644 --- a/ui/gfx/text_elider_unittest.cc +++ b/ui/gfx/text_elider_unittest.cc
@@ -117,12 +117,12 @@ } TEST(TextEliderTest, ElideEmailMoreSpace) { - const int test_width_factors[] = { - 100, - 10000, - 1000000, + const int test_widths_extra_spaces[] = { + 10, + 1000, + 100000, }; - const std::string test_emails[] = { + const char* test_emails[] = { "a@c", "test@email.com", "short@verysuperdupperlongdomain.com", @@ -130,14 +130,14 @@ }; const FontList font_list; - for (size_t i = 0; i < base::size(test_width_factors); ++i) { - const int test_width = - font_list.GetExpectedTextWidth(test_width_factors[i]); - for (size_t j = 0; j < base::size(test_emails); ++j) { + for (const auto* test_email : test_emails) { + const base::string16 test_email16 = UTF8ToUTF16(test_email); + const int mimimum_width = GetStringWidth(test_email16, font_list); + for (int extra_space : test_widths_extra_spaces) { // Extra space is available: the email should not be elided. - const base::string16 test_email = UTF8ToUTF16(test_emails[j]); - EXPECT_EQ(test_email, - ElideText(test_email, font_list, test_width, ELIDE_EMAIL)); + EXPECT_EQ(test_email16, + ElideText(test_email16, font_list, mimimum_width + extra_space, + ELIDE_EMAIL)); } } }
diff --git a/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.cc b/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.cc index 6de24d7f..231d590 100644 --- a/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.cc +++ b/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.cc
@@ -11,19 +11,137 @@ #include "base/macros.h" #include "base/memory/shared_memory_mapping.h" #include "base/memory/unsafe_shared_memory_region.h" +#include "base/numerics/checked_math.h" #include "base/posix/eintr_wrapper.h" +#include "third_party/skia/include/core/SkRegion.h" +#include "ui/gfx/skia_util.h" #include "ui/gfx/vsync_provider.h" #include "ui/ozone/platform/wayland/gpu/wayland_buffer_manager_gpu.h" namespace ui { -namespace { - -void DeleteSharedMemoryMapping(void* pixels, void* context) { - delete static_cast<base::WritableSharedMemoryMapping*>(context); +size_t CalculateStride(int width) { + base::CheckedNumeric<size_t> stride(width); + stride *= 4; + return stride.ValueOrDie(); } -} // namespace +class WaylandCanvasSurface::SharedMemoryBuffer { + public: + SharedMemoryBuffer(uint32_t buffer_id, + gfx::AcceleratedWidget widget, + WaylandBufferManagerGpu* buffer_manager) + : buffer_id_(buffer_id), + widget_(widget), + buffer_manager_(buffer_manager) { + DCHECK(buffer_manager_); + } + ~SharedMemoryBuffer() { buffer_manager_->DestroyBuffer(widget_, buffer_id_); } + + // Returns SkSurface, which the client can use to write to this buffer. + sk_sp<SkSurface> sk_surface() const { return sk_surface_; } + + // Tells clients if the buffer is busy and cannot be reused. Set on + // CommitBuffer() and reset on OnSubmissionCompleted() call. + bool busy() const { return busy_; } + + // Returns the id of the buffer. + uint32_t buffer_id() const { return buffer_id_; } + + // Initializes the shared memory and asks Wayland to import a shared memory + // based wl_buffer, which can be attached to a surface and have its contents + // shown on a screen. + bool Initialize(const gfx::Size& size) { + base::CheckedNumeric<size_t> checked_length(size.width()); + checked_length *= size.height(); + checked_length *= 4; + if (!checked_length.IsValid()) + return false; + + base::UnsafeSharedMemoryRegion shm_region = + base::UnsafeSharedMemoryRegion::Create(checked_length.ValueOrDie()); + if (!shm_region.IsValid()) + return false; + + shm_mapping_ = shm_region.Map(); + if (!shm_mapping_.IsValid()) + return false; + + base::subtle::PlatformSharedMemoryRegion platform_shm = + base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( + std::move(shm_region)); + base::subtle::ScopedFDPair fd_pair = platform_shm.PassPlatformHandle(); + buffer_manager_->CreateShmBasedBuffer(widget_, std::move(fd_pair.fd), + checked_length.ValueOrDie(), size, + buffer_id_); + + sk_surface_ = SkSurface::MakeRasterDirect( + SkImageInfo::MakeN32Premul(size.width(), size.height()), + shm_mapping_.memory(), CalculateStride(size.width())); + if (!sk_surface_) + return false; + + dirty_region_.setRect(gfx::RectToSkIRect(gfx::Rect(size))); + return true; + } + + void CommitBuffer(const gfx::Rect& damage) { + DCHECK(!busy_); + busy_ = true; + + buffer_manager_->CommitBuffer(widget_, buffer_id_, damage); + } + + void OnSubmissionCompleted() { + DCHECK(busy_); + busy_ = false; + } + + void UpdateDirtyRegion(const gfx::Rect& damage, SkRegion::Op op) { + SkIRect sk_damage = gfx::RectToSkIRect(damage); + dirty_region_.op(sk_damage, op); + } + + void CopyDirtyRegionFrom(SharedMemoryBuffer* buffer) { + DCHECK_NE(this, buffer); + const size_t stride = CalculateStride(sk_surface_->width()); + for (SkRegion::Iterator i(dirty_region_); !i.done(); i.next()) { + uint8_t* dst_ptr = + static_cast<uint8_t*>(shm_mapping_.memory()) + + i.rect().x() * SkColorTypeBytesPerPixel(kN32_SkColorType) + + i.rect().y() * stride; + buffer->sk_surface_->readPixels( + SkImageInfo::MakeN32Premul(i.rect().width(), i.rect().height()), + dst_ptr, stride, i.rect().x(), i.rect().y()); + } + dirty_region_.setEmpty(); + } + + private: + // The id of the buffer this surface is backed. + const uint32_t buffer_id_; + + // The widget this buffer is created for. + const gfx::AcceleratedWidget widget_; + + // Non-owned pointer to the buffer manager on the gpu process/thread side. + WaylandBufferManagerGpu* const buffer_manager_; + + // Shared memory for the buffer. + base::WritableSharedMemoryMapping shm_mapping_; + + // The SkSurface the clients can draw to show the surface on screen. + sk_sp<SkSurface> sk_surface_; + + // The region of the buffer that's not up-to-date. + SkRegion dirty_region_; + + // Says if the buffer is busy or not. The value must be reset when the buffer + // manager acknowledges a swap. + bool busy_ = false; + + DISALLOW_COPY_AND_ASSIGN(SharedMemoryBuffer); +}; WaylandCanvasSurface::WaylandCanvasSurface( WaylandBufferManagerGpu* buffer_manager, @@ -34,45 +152,30 @@ WaylandCanvasSurface::~WaylandCanvasSurface() { buffer_manager_->UnregisterSurface(widget_); - - if (sk_surface_) - buffer_manager_->DestroyBuffer(widget_, buffer_id_); } sk_sp<SkSurface> WaylandCanvasSurface::GetSurface() { - if (sk_surface_) - return sk_surface_; - DCHECK(!size_.IsEmpty()); + DCHECK(!current_buffer_); + // TODO(msisov): Restrict the number of buffers that can be created per one + // canvas surface. + for (const auto& buffer : buffers_) { + if (buffer->busy()) + continue; + current_buffer_ = buffer.get(); + } - size_t length = size_.width() * size_.height() * 4; - base::UnsafeSharedMemoryRegion shm_region = - base::UnsafeSharedMemoryRegion::Create(length); - if (!shm_region.IsValid()) - return nullptr; + if (!current_buffer_) { + auto buffer = CreateSharedMemoryBuffer(); + if (!buffer) { + DCHECK(!current_buffer_); + return nullptr; + } + current_buffer_ = buffer.get(); + buffers_.push_back(std::move(buffer)); + } - base::WritableSharedMemoryMapping shm_mapping = shm_region.Map(); - if (!shm_mapping.IsValid()) - return nullptr; - - base::subtle::PlatformSharedMemoryRegion platform_shm = - base::UnsafeSharedMemoryRegion::TakeHandleForSerialization( - std::move(shm_region)); - base::subtle::ScopedFDPair fd_pair = platform_shm.PassPlatformHandle(); - buffer_manager_->CreateShmBasedBuffer(widget_, std::move(fd_pair.fd), length, - size_, ++buffer_id_); - - auto shm_mapping_on_heap = - std::make_unique<base::WritableSharedMemoryMapping>( - std::move(shm_mapping)); - sk_surface_ = SkSurface::MakeRasterDirectReleaseProc( - SkImageInfo::MakeN32Premul(size_.width(), size_.height()), - shm_mapping_on_heap->memory(), size_.width() * 4, - &DeleteSharedMemoryMapping, shm_mapping_on_heap.get(), nullptr); - if (!sk_surface_) - return nullptr; - - ignore_result(shm_mapping_on_heap.release()); - return sk_surface_; + DCHECK(current_buffer_ && !current_buffer_->busy()); + return current_buffer_->sk_surface(); } void WaylandCanvasSurface::ResizeCanvas(const gfx::Size& viewport_size) { @@ -82,15 +185,36 @@ // by allocating buffers rounded up to larger sizes, and then reusing them if // the new size still fits (but still reallocate if the new size is much // smaller than the old size). - if (sk_surface_) { - sk_surface_.reset(); - buffer_manager_->DestroyBuffer(widget_, buffer_id_); + if (!buffers_.empty()) { + buffers_.clear(); + current_buffer_ = nullptr; + previous_buffer_ = nullptr; } size_ = viewport_size; } void WaylandCanvasSurface::PresentCanvas(const gfx::Rect& damage) { - buffer_manager_->CommitBuffer(widget_, buffer_id_, damage); + DCHECK(current_buffer_); + // The buffer has been updated. Thus, the |damage| can be subtracted from its + // dirty region. + current_buffer_->UpdateDirtyRegion(damage, SkRegion::kDifference_Op); + + // Make sure the buffer is up-to-date by copying the outdated region from the + // previous buffer. + if (previous_buffer_ && previous_buffer_ != current_buffer_) + current_buffer_->CopyDirtyRegionFrom(previous_buffer_); + + // As long as the |current_buffer_| has been updated, add dirty region to + // other buffers to make sure their regions will be updated with up-to-date + // content. + for (auto& buffer : buffers_) { + if (buffer.get() != current_buffer_) + buffer->UpdateDirtyRegion(damage, SkRegion::kUnion_Op); + } + + current_buffer_->CommitBuffer(damage); + previous_buffer_ = current_buffer_; + current_buffer_ = nullptr; } std::unique_ptr<gfx::VSyncProvider> @@ -103,7 +227,13 @@ void WaylandCanvasSurface::OnSubmission(uint32_t buffer_id, const gfx::SwapResult& swap_result) { - NOTIMPLEMENTED_LOG_ONCE(); + auto buffer_it = std::find_if( + buffers_.begin(), buffers_.end(), + [buffer_id](auto& buffer) { return buffer->buffer_id() == buffer_id; }); + // Upper layer does not care about the submission result, and the buffer may + // be destroyed by this time (when the surface is resized, for example). + if (buffer_it != buffers_.end()) + buffer_it->get()->OnSubmissionCompleted(); } void WaylandCanvasSurface::OnPresentation( @@ -113,4 +243,13 @@ NOTIMPLEMENTED_LOG_ONCE(); } +std::unique_ptr<WaylandCanvasSurface::SharedMemoryBuffer> +WaylandCanvasSurface::CreateSharedMemoryBuffer() { + DCHECK(!size_.IsEmpty()); + + auto canvas_buffer = std::make_unique<SharedMemoryBuffer>( + ++buffer_id_, widget_, buffer_manager_); + return canvas_buffer->Initialize(size_) ? std::move(canvas_buffer) : nullptr; +} + } // namespace ui
diff --git a/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.h b/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.h index baa29a8b..fef7aea 100644 --- a/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.h +++ b/ui/ozone/platform/wayland/gpu/wayland_canvas_surface.h
@@ -19,6 +19,10 @@ class WaylandBufferManagerGpu; +// Returns SkSurface, which must be used to write to a shared memory region. It +// is guaranteed that the returned SkSurface is not backed by the shared memory +// region used by a Wayland compositor. Instead, a new SkSurface will be +// returned and the client can write to it without resulting in tearing. class WaylandCanvasSurface : public SurfaceOzoneCanvas, public WaylandSurfaceGpu { public: @@ -33,19 +37,32 @@ std::unique_ptr<gfx::VSyncProvider> CreateVSyncProvider() override; private: + // Internal helper class, which creates a shared memory region, asks the + // WaylandBufferManager to import a wl_buffer, and creates an SkSurface, which + // is backed by that shared region. + class SharedMemoryBuffer; + // WaylandSurfaceGpu overrides: void OnSubmission(uint32_t buffer_id, const gfx::SwapResult& swap_result) override; void OnPresentation(uint32_t buffer_id, const gfx::PresentationFeedback& feedback) override; - void OnGetSizeForWidget(const gfx::Size& widget_size) { size_ = widget_size; } + sk_sp<SkSurface> GetNextSurface(); + std::unique_ptr<SharedMemoryBuffer> CreateSharedMemoryBuffer(); WaylandBufferManagerGpu* const buffer_manager_; const gfx::AcceleratedWidget widget_; gfx::Size size_; - sk_sp<SkSurface> sk_surface_; + std::vector<std::unique_ptr<SharedMemoryBuffer>> buffers_; + + // Currently used buffer. Set on GetSurface() and released on PresentCanvas() + // call. + SharedMemoryBuffer* current_buffer_ = nullptr; + + // Previously used buffer. Set on PresentCanvas(). + SharedMemoryBuffer* previous_buffer_ = nullptr; // The id of the current existing buffer. Even though, there can only be one // buffer (SkSurface) at a time, the buffer manager on the browser process
diff --git a/ui/views/cocoa/native_widget_mac_ns_window_host.h b/ui/views/cocoa/native_widget_mac_ns_window_host.h index a7a8f529..528ec88 100644 --- a/ui/views/cocoa/native_widget_mac_ns_window_host.h +++ b/ui/views/cocoa/native_widget_mac_ns_window_host.h
@@ -364,9 +364,7 @@ void OnDidChangeFocus(View* focused_before, View* focused_now) override; // ui::internal::InputMethodDelegate: - ui::EventDispatchDetails DispatchKeyEventPostIME( - ui::KeyEvent* key, - DispatchKeyEventPostIMECallback callback) override; + ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* key) override; // ui::AccessibilityFocusOverrider::Client: id GetAccessibilityFocusedUIElement() override;
diff --git a/ui/views/cocoa/native_widget_mac_ns_window_host.mm b/ui/views/cocoa/native_widget_mac_ns_window_host.mm index 143cb56..95f1c6ce 100644 --- a/ui/views/cocoa/native_widget_mac_ns_window_host.mm +++ b/ui/views/cocoa/native_widget_mac_ns_window_host.mm
@@ -1430,14 +1430,12 @@ // NativeWidgetMacNSWindowHost, internal::InputMethodDelegate: ui::EventDispatchDetails NativeWidgetMacNSWindowHost::DispatchKeyEventPostIME( - ui::KeyEvent* key, - DispatchKeyEventPostIMECallback callback) { + ui::KeyEvent* key) { DCHECK(focus_manager_); if (!focus_manager_->OnKeyEvent(*key)) key->StopPropagation(); else native_widget_mac_->GetWidget()->OnKeyEvent(key); - RunDispatchKeyEventPostIMECallback(key, std::move(callback)); return ui::EventDispatchDetails(); }
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index dd9f68c..d422612 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -11,7 +11,6 @@ #include <string> #include <vector> -#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/format_macros.h" #include "base/i18n/rtl.h" @@ -150,7 +149,7 @@ // which trigger the appropriate NSResponder action messages for composition. #if defined(OS_MACOSX) if (key->is_char()) - return DispatchKeyEventPostIME(key, base::NullCallback()); + return DispatchKeyEventPostIME(key); #endif // Checks whether the key event is from EventGenerator on Windows which will @@ -170,9 +169,9 @@ ui::KeyEvent mock_key(ui::ET_KEY_PRESSED, ui::VKEY_PROCESSKEY, key->flags()); - dispatch_details = DispatchKeyEventPostIME(&mock_key, base::NullCallback()); + dispatch_details = DispatchKeyEventPostIME(&mock_key); } else { - dispatch_details = DispatchKeyEventPostIME(key, base::NullCallback()); + dispatch_details = DispatchKeyEventPostIME(key); } if (key->handled() || dispatch_details.dispatcher_destroyed)
diff --git a/ui/webui/resources/js/cr.js b/ui/webui/resources/js/cr.js index 3f6be5a..3f71e73 100644 --- a/ui/webui/resources/js/cr.js +++ b/ui/webui/resources/js/cr.js
@@ -200,6 +200,10 @@ * @param {PropertyKind=} opt_kind What kind of underlying storage to use. * @param {function(*, *):void=} opt_setHook A function to run after the * property is set, but before the propertyChange event is fired. + * + * TODO(crbug.com/425829): This function makes use of deprecated getter or + * setter functions. + * @suppress {deprecated} */ function defineProperty(obj, name, opt_kind, opt_setHook) { if (typeof obj == 'function') { @@ -208,6 +212,9 @@ const kind = /** @type {PropertyKind} */ (opt_kind || PropertyKind.JS); + // TODO(crbug.com/425829): Remove above suppression once we no longer use + // deprecated functions lookupGetter, defineGetter, lookupSetter, and + // defineSetter. if (!obj.__lookupGetter__(name)) { obj.__defineGetter__(name, getGetter(name, kind)); }
diff --git a/ui/webui/resources/js/cr/ui/overlay.js b/ui/webui/resources/js/cr/ui/overlay.js index 8a7e7db9..9388ae6 100644 --- a/ui/webui/resources/js/cr/ui/overlay.js +++ b/ui/webui/resources/js/cr/ui/overlay.js
@@ -98,6 +98,10 @@ /** * Adds behavioral hooks for the given overlay. * @param {HTMLElement} overlay The .overlay. + * + * TODO(crbug.com/425829): This function makes use of deprecated getter or + * setter functions. + * @suppress {deprecated} */ function setupOverlay(overlay) { // Close the overlay on clicking any of the pages' close buttons. @@ -111,6 +115,8 @@ }); } + // TODO(crbug.com/425829): Remove above suppression once we no longer use + // deprecated functions defineSetter, and defineGetter. // Remove the 'pulse' animation any time the overlay is hidden or shown. overlay.__defineSetter__('hidden', function(value) { this.classList.remove('pulse');