diff --git a/DEPS b/DEPS index 4d9fa75..23495a612 100644 --- a/DEPS +++ b/DEPS
@@ -167,11 +167,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': '7aeabcfa6a7370d5482d77e138ba2475ae5ac958', + 'skia_revision': '0846d68474fbc92ea33ca648b5c340e75fc578d4', # 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': '656e25f970901daff67319c68a19b109bee5ad1a', + 'v8_revision': '1370481f4b1fba0c2a764320b3e7c75785628e52', # 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. @@ -179,7 +179,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': '71c1138d6739b58cb8cc849ea1a2fd8c9f2776c3', + 'angle_revision': 'ceac3320975b432fdde2ade2afc2a24af927aee0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -286,11 +286,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '10951a7c9a13ec663bc1dfdaec268840be865e9a', + 'spv_tools_revision': '85c67b5e08eea1818767f174515612464740a53c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_headers_revision': '601d738723ac381741311c6c98c36d6170be14a2', + 'spv_headers_revision': '842ec90674627ed2ffef609e3cd79d1562eded01', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -302,7 +302,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. - 'dawn_revision': '52bd6b7da6a758888e99436656e836f178b762af', + 'dawn_revision': '55a00c7a1f9a188c5a512af510f8184bbdbad580', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -887,7 +887,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '0081c0ff173c3af29933cbc6965d4a2d83b09576', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'f656f57a367a1dfadb6b82285a14adc1567bd1d6', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -1269,7 +1269,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '6a28e95a8e403120ced88f347d0c7ffe24b7b8f7', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '1fab224fb263308aeb6e5af05d9c4f77fb31c6e9', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1459,7 +1459,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '7c4e67ff117d6c640e6dd17989afe2fb7da7eecb', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '0e3517d55865290b695b59a4cb8ed08e429bbe69', + Var('webrtc_git') + '/src.git' + '@' + '45b176fc22892db55c0f5bd5dc876386ee5512d0', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1521,7 +1521,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@5efc9bd8e0097b2083e37979114bb92523dbe396', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@01cd0891cf7a9b2bdc805f690dcd43fe79adef8d', 'condition': 'checkout_src_internal', },
diff --git a/WATCHLISTS b/WATCHLISTS index c55f9e3..2c0aeb72 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -776,6 +776,10 @@ 'chrome/browser/resources/chromeos/login/|'\ 'ui/login/', }, + 'chromeos_media_app': { + 'filepath': 'chromeos/components/media_app_ui/|'\ + 'chromeos/resources/media_app_resources.grdp', + }, 'chromeos_net': { 'filepath': 'ash/system/network/|'\ 'chromeos/network/|'\ @@ -2235,6 +2239,7 @@ 'alemate+watch@chromium.org', 'rsorokin+watch@chromium.org', 'tbarzic+watch@chromium.org'], + 'chromeos_media_app': ['cros-essential-apps-dev+watch@chromium.org'], 'chromeos_net': ['azeemarshad+watch-network@chromium.org', 'benchan+watch-network@chromium.org', 'ejcaruso+watch-network@chromium.org',
diff --git a/android_webview/common/crash_reporter/aw_crash_reporter_client.cc b/android_webview/common/crash_reporter/aw_crash_reporter_client.cc index dc40d4cc..c369ac3 100644 --- a/android_webview/common/crash_reporter/aw_crash_reporter_client.cc +++ b/android_webview/common/crash_reporter/aw_crash_reporter_client.cc
@@ -105,7 +105,7 @@ } bool JavaExceptionFilter( - const base::android::ScopedJavaLocalRef<jthrowable>& java_exception) { + const base::android::JavaRef<jthrowable>& java_exception) { return Java_AwCrashReporterClient_stackTraceContainsWebViewCode( AttachCurrentThread(), java_exception); } @@ -194,6 +194,13 @@ AwCrashReporterClient* client = g_crash_reporter_client.Pointer(); crash_reporter::SetCrashReporterClient(client); crash_reporter::InitializeCrashpad(process_type.empty(), process_type); + if (process_type.empty()) { + base::android::InitJavaExceptionReporter(); + } else { + base::android::InitJavaExceptionReporterForChildProcess(); + } + base::android::SetJavaExceptionFilter(base::BindRepeating( + &AwCrashReporterClient::JavaExceptionFilter, base::Unretained(client))); g_enabled = true; }
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java index 17db873..d20d20d8 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java
@@ -46,7 +46,6 @@ import org.chromium.base.TraceEvent; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.CachedMetrics; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.ScopedSysTraceEvent; @@ -152,8 +151,6 @@ try (ScopedSysTraceEvent e = ScopedSysTraceEvent.scoped("WebViewChromiumAwInit.LibraryLoader")) { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_WEBVIEW); - } catch (ProcessInitException e) { - throw new RuntimeException("Error initializing WebView library", e); } PathService.override(PathService.DIR_MODULE, "/system/lib/");
diff --git a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java index 443f0cd..0e9288d 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java +++ b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
@@ -28,7 +28,6 @@ import org.chromium.base.annotations.JNINamespace; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskRunner; @@ -89,8 +88,6 @@ // It's okay for the WebView to do this before initialization because we have // setup the JNI bindings by this point. LibraryLoader.getInstance().switchCommandLineForWebView(); - } catch (ProcessInitException e) { - throw new RuntimeException("Cannot load WebView", e); } finally { StrictMode.setThreadPolicy(oldPolicy); } @@ -143,8 +140,6 @@ "AwBrowserProcess.startBrowserProcessesSync")) { BrowserStartupController.get(LibraryProcessType.PROCESS_WEBVIEW) .startBrowserProcessesSync(!multiProcess); - } catch (ProcessInitException e) { - throw new RuntimeException("Cannot initialize WebView", e); } }); }
diff --git a/android_webview/java/src/org/chromium/android_webview/AwCookieManager.java b/android_webview/java/src/org/chromium/android_webview/AwCookieManager.java index 82f2493..eba0701c 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwCookieManager.java +++ b/android_webview/java/src/org/chromium/android_webview/AwCookieManager.java
@@ -14,7 +14,6 @@ import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; /** * AwCookieManager manages cookies according to RFC2109 spec. @@ -30,11 +29,7 @@ } public AwCookieManager(long nativeCookieManager) { - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_WEBVIEW); - } catch (ProcessInitException e) { - throw new RuntimeException("Error initializing WebView library", e); - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_WEBVIEW); mNativeCookieManager = nativeCookieManager; } @@ -106,8 +101,8 @@ * @return The cookies in the format of NAME=VALUE [; NAME=VALUE] */ public String getCookie(final String url) { - String cookie = AwCookieManagerJni.get().getCookie( - mNativeCookieManager, AwCookieManager.this, url.toString()); + String cookie = + AwCookieManagerJni.get().getCookie(mNativeCookieManager, AwCookieManager.this, url); // Return null if the string is empty to match legacy behavior return cookie == null || cookie.trim().isEmpty() ? null : cookie; }
diff --git a/android_webview/tools/cts_config/expected_failure_on_bot.json b/android_webview/tools/cts_config/expected_failure_on_bot.json index 346cf9d..2c63c08 100644 --- a/android_webview/tools/cts_config/expected_failure_on_bot.json +++ b/android_webview/tools/cts_config/expected_failure_on_bot.json
@@ -1,8 +1,2 @@ { - "android.webkit.cts.ServiceWorkerClientTest": [ - { - "name": "testServiceWorkerClientInterceptCallback", - "_bug_id": "crbug.com/675809" - } - ] }
diff --git a/android_webview/tools/cts_config/webview_cts_gcs_path.json b/android_webview/tools/cts_config/webview_cts_gcs_path.json index 8740ddc..4a8a816 100644 --- a/android_webview/tools/cts_config/webview_cts_gcs_path.json +++ b/android_webview/tools/cts_config/webview_cts_gcs_path.json
@@ -184,7 +184,13 @@ }, "test_runs": [ { - "apk": "android-cts/testcases/CtsWebkitTestCases.apk" + "apk": "android-cts/testcases/CtsWebkitTestCases.apk", + "excludes": [ + { + "match": "android.webkit.cts.ServiceWorkerClientTest.testServiceWorkerClientInterceptCallback", + "_bug_id": "crbug.com/675809" + } + ] }, { "apk": "android-cts/testcases/CtsWidgetTestCases.apk", @@ -211,7 +217,13 @@ }, "test_runs": [ { - "apk": "android-cts/testcases/CtsWebkitTestCases.apk" + "apk": "android-cts/testcases/CtsWebkitTestCases.apk", + "excludes": [ + { + "match": "android.webkit.cts.ServiceWorkerClientTest.testServiceWorkerClientInterceptCallback", + "_bug_id": "crbug.com/675809" + } + ] }, { "apk": "android-cts/testcases/CtsWebViewStartupApp.apk"
diff --git a/android_webview/tools/run_cts.py b/android_webview/tools/run_cts.py index 4148b867..09cf661 100755 --- a/android_webview/tools/run_cts.py +++ b/android_webview/tools/run_cts.py
@@ -34,6 +34,8 @@ os.path.dirname(__file__), os.pardir, os.pardir, 'build', 'android', 'test_runner.py') +# TODO(crbug.com/928093): remove this file as it is covered by +# webview_cts_gcs_path.json. _EXPECTED_FAILURES_FILE = os.path.join( os.path.dirname(__file__), 'cts_config', 'expected_failure_on_bot.json')
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index c1df05f..4946e24 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -168,7 +168,7 @@ * * @param processType the process the shared library is loaded in. */ - public void ensureInitialized(@LibraryProcessType int processType) throws ProcessInitException { + public void ensureInitialized(@LibraryProcessType int processType) { synchronized (mLock) { if (mInitialized) return; @@ -222,10 +222,8 @@ * May be called on any thread, but should only be called once. Note the thread * this is called on will be the thread that runs the native code's static initializers. * See the comment in doInBackground() for more considerations on this. - * - * @throws ProcessInitException if the native library failed to load. */ - public void loadNow() throws ProcessInitException { + public void loadNow() { loadNowOverrideApplicationContext(ContextUtils.getApplicationContext()); } @@ -235,9 +233,8 @@ * context. * * @param appContext The overriding app context to be used to load libraries. - * @throws ProcessInitException if the native library failed to load with this context. */ - public void loadNowOverrideApplicationContext(Context appContext) throws ProcessInitException { + public void loadNowOverrideApplicationContext(Context appContext) { synchronized (mLock) { if (mLoaded && appContext != ContextUtils.getApplicationContext()) { throw new IllegalStateException("Attempt to load again from alternate context."); @@ -246,7 +243,7 @@ } } - public void loadNowInZygote(ApplicationInfo appInfo) throws ProcessInitException { + public void loadNowInZygote(ApplicationInfo appInfo) { synchronized (mLock) { assert !mLoaded; loadAlreadyLocked(appInfo, true /* inZygote */); @@ -261,7 +258,7 @@ * * @param processType the process the shared library is loaded in. */ - public void initialize(@LibraryProcessType int processType) throws ProcessInitException { + public void initialize(@LibraryProcessType int processType) { synchronized (mLock) { initializeAlreadyLocked(processType); } @@ -383,8 +380,7 @@ // Invoke either Linker.loadLibrary(...), System.loadLibrary(...) or System.load(...), // triggering JNI_OnLoad in native code. @GuardedBy("mLock") - private void loadAlreadyLocked(ApplicationInfo appInfo, boolean inZygote) - throws ProcessInitException { + private void loadAlreadyLocked(ApplicationInfo appInfo, boolean inZygote) { try (TraceEvent te = TraceEvent.scoped("LibraryLoader.loadAlreadyLocked")) { if (mLoaded) return; assert !mInitialized; @@ -478,8 +474,7 @@ // Invoke base::android::LibraryLoaded in library_loader_hooks.cc @GuardedBy("mLock") - private void initializeAlreadyLocked(@LibraryProcessType int processType) - throws ProcessInitException { + private void initializeAlreadyLocked(@LibraryProcessType int processType) { if (mInitialized) { if (mLibraryProcessType != processType) { throw new ProcessInitException(
diff --git a/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java b/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java index 1066675..e766b50 100644 --- a/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java +++ b/base/android/java/src/org/chromium/base/library_loader/ProcessInitException.java
@@ -5,9 +5,9 @@ package org.chromium.base.library_loader; /** - * The exception that is thrown when the intialization of a process was failed. + * The exception that is thrown when the initialization of a process has failed. */ -public class ProcessInitException extends Exception { +public class ProcessInitException extends RuntimeException { private int mErrorCode = LoaderErrors.LOADER_ERROR_NORMAL_COMPLETION; /**
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java index 2ba02f7..b38e8e0 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
@@ -221,15 +221,7 @@ android.os.Debug.waitForDebugger(); } - boolean nativeLibraryLoaded = false; - try { - nativeLibraryLoaded = mDelegate.loadNativeLibrary(getApplicationContext()); - } catch (Exception e) { - Log.e(TAG, "Failed to load native library.", e); - } - if (!nativeLibraryLoaded) { - System.exit(-1); - } + mDelegate.loadNativeLibrary(getApplicationContext()); synchronized (mLibraryInitializedLock) { mLibraryInitialized = true;
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java index d865823..f642365 100644 --- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java +++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessServiceDelegate.java
@@ -35,10 +35,8 @@ /** * Called when the delegate should load the native library. * @param hostContext The host context the library should be loaded with (i.e. Chrome). - * @return true if the library was loaded successfully, false otherwise in which case the - * service stops. */ - boolean loadNativeLibrary(Context hostContext); + void loadNativeLibrary(Context hostContext); /** * Called when the delegate should preload the native library.
diff --git a/base/android/java_exception_reporter.h b/base/android/java_exception_reporter.h index 7306ab44..0c4d8b6 100644 --- a/base/android/java_exception_reporter.h +++ b/base/android/java_exception_reporter.h
@@ -31,7 +31,7 @@ // Sets a filter that determines whether a java exception should cause a crash // report. |java_exception_filter| should return true if a crash report should // be generated. -void SetJavaExceptionFilter( +BASE_EXPORT void SetJavaExceptionFilter( base::RepeatingCallback<bool(const JavaRef<jthrowable>&)> java_exception_filter);
diff --git a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java index 654863d..75c142c6 100644 --- a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java +++ b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientServiceDelegate.java
@@ -11,7 +11,6 @@ import android.util.SparseArray; import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.process_launcher.ChildProcessServiceDelegate; import org.chromium.native_test.MainRunner; @@ -55,14 +54,8 @@ } @Override - public boolean loadNativeLibrary(Context hostContext) { - try { - LibraryLoader.getInstance().loadNow(); - return true; - } catch (ProcessInitException pie) { - Log.e(TAG, "Unable to load native libraries.", pie); - return false; - } + public void loadNativeLibrary(Context hostContext) { + LibraryLoader.getInstance().loadNow(); } @Override
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index d0f6174..ef3c1a2 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8900990138279554656 \ No newline at end of file +8900963580510499440 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index a1fa977..2997a23 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8900988970603371744 \ No newline at end of file +8900963579521722560 \ No newline at end of file
diff --git a/cc/tiles/tile_manager.cc b/cc/tiles/tile_manager.cc index e6d77b6..3245505e 100644 --- a/cc/tiles/tile_manager.cc +++ b/cc/tiles/tile_manager.cc
@@ -17,7 +17,6 @@ #include "base/metrics/histogram.h" #include "base/numerics/safe_conversions.h" #include "base/optional.h" -#include "base/system/sys_info.h" #include "base/threading/thread_checker.h" #include "base/trace_event/traced_value.h" #include "cc/base/devtools_instrumentation.h" @@ -848,13 +847,10 @@ } } - // The hard_limit for low-end devices is 8MB, so we set the max_value for the - // histogram to be 8200KB. - if (had_enough_memory_to_schedule_tiles_needed_now && - base::SysInfo::AmountOfPhysicalMemoryMB() <= 512) { + if (had_enough_memory_to_schedule_tiles_needed_now) { int64_t tiles_gpu_memory_kb = memory_usage.memory_bytes() / 1024; - UMA_HISTOGRAM_CUSTOM_COUNTS("TileManager.TilesGPUMemoryUsage", - tiles_gpu_memory_kb, 1, 8200, 100); + UMA_HISTOGRAM_MEMORY_KB("TileManager.TilesGPUMemoryUsage2", + tiles_gpu_memory_kb); } UMA_HISTOGRAM_BOOLEAN("TileManager.ExceededMemoryBudget",
diff --git a/chrome/VERSION b/chrome/VERSION index 843ad14..e8431bae 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=79 MINOR=0 -BUILD=3928 +BUILD=3929 PATCH=0
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java index 09a247f..aeeee891 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java
@@ -416,8 +416,9 @@ @Override public int getHeight() { if (mViewportMode == AssistantViewportMode.RESIZE_LAYOUT_VIEWPORT - && mBottomSheetController.getBottomSheet().getCurrentSheetContent() == mContent) + && mBottomSheetController.getBottomSheet().getCurrentSheetContent() == mContent) { return mPeekHeightCoordinator.getPeekHeight(); + } return 0; }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java index 86dabe9e3..d561ddfc 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetails.java
@@ -4,33 +4,23 @@ package org.chromium.chrome.browser.autofill_assistant.details; -import androidx.annotation.Nullable; - import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - /** * Java side equivalent of autofill_assistant::DetailsProto. */ @JNINamespace("autofill_assistant") public class AssistantDetails { - private static final String RFC_3339_FORMAT_WITHOUT_TIMEZONE = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; - private final String mTitle; + private final int mTitleMaxLines; private final String mImageUrl; private final ImageClickthroughData mImageClickthroughData; private final boolean mShowImagePlaceholder; - @Nullable - private final Date mDate; private final String mDescriptionLine1; private final String mDescriptionLine2; private final String mDescriptionLine3; + private final String mPriceAttribution; /** Whether user approval is required (i.e., due to changes). */ private boolean mUserApprovalRequired; /** Whether the title should be highlighted. */ @@ -51,22 +41,23 @@ /** An optional price label, such as 'Estimated Total incl. VAT'. */ private final String mTotalPriceLabel; - public AssistantDetails(String title, String imageUrl, + public AssistantDetails(String title, int titleMaxLines, String imageUrl, ImageClickthroughData imageClickthroughData, boolean showImagePlaceholder, - String totalPriceLabel, String totalPrice, @Nullable Date date, String descriptionLine1, - String descriptionLine2, String descriptionLine3, boolean userApprovalRequired, - boolean highlightTitle, boolean highlightLine1, boolean highlightLine2, - boolean highlightLine3, boolean animatePlaceholders) { + String totalPriceLabel, String totalPrice, String descriptionLine1, + String descriptionLine2, String descriptionLine3, String priceAttribution, + boolean userApprovalRequired, boolean highlightTitle, boolean highlightLine1, + boolean highlightLine2, boolean highlightLine3, boolean animatePlaceholders) { this.mTotalPriceLabel = totalPriceLabel; this.mTitle = title; + this.mTitleMaxLines = titleMaxLines; this.mImageUrl = imageUrl; this.mImageClickthroughData = imageClickthroughData; this.mShowImagePlaceholder = showImagePlaceholder; this.mTotalPrice = totalPrice; - this.mDate = date; this.mDescriptionLine1 = descriptionLine1; this.mDescriptionLine2 = descriptionLine2; this.mDescriptionLine3 = descriptionLine3; + this.mPriceAttribution = priceAttribution; this.mUserApprovalRequired = userApprovalRequired; this.mHighlightTitle = highlightTitle; @@ -80,6 +71,10 @@ return mTitle; } + int getTitleMaxLines() { + return mTitleMaxLines; + } + String getImageUrl() { return mImageUrl; } @@ -96,11 +91,6 @@ return mShowImagePlaceholder; } - @Nullable - Date getDate() { - return mDate; - } - String getDescriptionLine1() { return mDescriptionLine1; } @@ -113,7 +103,11 @@ return mDescriptionLine3; } - public String getTotalPrice() { + String getPriceAttribution() { + return mPriceAttribution; + } + + String getTotalPrice() { return mTotalPrice; } @@ -141,7 +135,7 @@ return mHighlightLine3; } - public boolean getAnimatePlaceholders() { + boolean getAnimatePlaceholders() { return mAnimatePlaceholders; } @@ -149,38 +143,21 @@ * Create details with the given values. */ @CalledByNative - private static AssistantDetails create(String title, String imageUrl, + private static AssistantDetails create(String title, int titleMaxLines, String imageUrl, boolean allowImageClickthrough, String imageClickthroughDesc, String imageClickthroughPostiveText, String imageClickthroughNegativeText, String imageClickthroughUrl, boolean showImagePlaceholder, String totalPriceLabel, - String totalPrice, String datetime, long year, int month, int day, int hour, int minute, - int second, String descriptionLine1, String descriptionLine2, String descriptionLine3, - boolean userApprovalRequired, boolean highlightTitle, boolean highlightLine1, - boolean highlightLine2, boolean highlightLine3, boolean animatePlaceholders) { - Date date = null; - if (year > 0 && month > 0 && day > 0 && hour >= 0 && minute >= 0 && second >= 0) { - Calendar calendar = Calendar.getInstance(); - calendar.clear(); - // Month in Java Date is 0-based, but the one we receive from the server is 1-based. - calendar.set((int) year, month - 1, day, hour, minute, second); - date = calendar.getTime(); - } else if (!datetime.isEmpty()) { - try { - // The parameter contains the timezone shift from the current location, that we - // don't care about. - date = new SimpleDateFormat(RFC_3339_FORMAT_WITHOUT_TIMEZONE, Locale.ROOT) - .parse(datetime); - } catch (ParseException e) { - // Ignore. - } - } - - return new AssistantDetails(title, imageUrl, + String totalPrice, String descriptionLine1, String descriptionLine2, + String descriptionLine3, String priceAttribution, boolean userApprovalRequired, + boolean highlightTitle, boolean highlightLine1, boolean highlightLine2, + boolean highlightLine3, boolean animatePlaceholders) { + return new AssistantDetails(title, titleMaxLines, imageUrl, new ImageClickthroughData(allowImageClickthrough, imageClickthroughDesc, imageClickthroughPostiveText, imageClickthroughNegativeText, imageClickthroughUrl), - showImagePlaceholder, totalPriceLabel, totalPrice, date, descriptionLine1, - descriptionLine2, descriptionLine3, userApprovalRequired, highlightTitle, - highlightLine1, highlightLine2, highlightLine3, animatePlaceholders); + showImagePlaceholder, totalPriceLabel, totalPrice, descriptionLine1, + descriptionLine2, descriptionLine3, priceAttribution, userApprovalRequired, + highlightTitle, highlightLine1, highlightLine2, highlightLine3, + animatePlaceholders); } } \ No newline at end of file
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsCoordinator.java index c6d6d3f..bdc7f47 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsCoordinator.java
@@ -5,7 +5,6 @@ package org.chromium.chrome.browser.autofill_assistant.details; import android.content.Context; -import android.os.Build; import android.view.LayoutInflater; import android.view.View; @@ -17,8 +16,6 @@ import org.chromium.chrome.browser.image_fetcher.ImageFetcherFactory; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; -import java.util.Locale; - /** * Coordinator responsible for showing details. */ @@ -27,22 +24,19 @@ private final AssistantDetailsModel mModel; public AssistantDetailsCoordinator(Context context, AssistantDetailsModel model) { - this(context, - Build.VERSION.SDK_INT >= Build.VERSION_CODES.N - ? context.getResources().getConfiguration().getLocales().get(0) - : context.getResources().getConfiguration().locale, - model, ImageFetcherFactory.createImageFetcher(ImageFetcherConfig.DISK_CACHE_ONLY)); + this(context, model, + ImageFetcherFactory.createImageFetcher(ImageFetcherConfig.DISK_CACHE_ONLY)); } @VisibleForTesting - public AssistantDetailsCoordinator(Context context, Locale locale, AssistantDetailsModel model, - ImageFetcher imageFetcher) { + public AssistantDetailsCoordinator( + Context context, AssistantDetailsModel model, ImageFetcher imageFetcher) { mView = LayoutInflater.from(context).inflate( R.layout.autofill_assistant_details, /* root= */ null); mModel = model; ViewHolder viewHolder = new ViewHolder(context, mView); AssistantDetailsViewBinder viewBinder = - new AssistantDetailsViewBinder(context, locale, imageFetcher); + new AssistantDetailsViewBinder(context, imageFetcher); PropertyModelChangeProcessor.create(model, viewHolder, viewBinder); // Details view is initially hidden.
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java index 706fa26..34fe83a 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/details/AssistantDetailsViewBinder.java
@@ -40,13 +40,6 @@ import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; - /** * This class is responsible for pushing updates to the Autofill Assistant details view. These * updates are pulled from the {@link AssistantDetailsModel} when a notification of an update is @@ -57,8 +50,6 @@ AssistantDetailsViewBinder.ViewHolder, PropertyKey> { private static final int IMAGE_BORDER_RADIUS = 8; private static final int PULSING_DURATION_MS = 1_000; - private static final String DETAILS_TIME_FORMAT = "H:mma"; - private static final String DETAILS_DATE_FORMAT = "EEE, MMM d"; /** * A wrapper class that holds the different views of the header. @@ -91,7 +82,6 @@ } private final Context mContext; - private final Locale mLocale; private final int mImageWidth; private final int mImageHeight; @@ -101,9 +91,8 @@ private ValueAnimator mPulseAnimation; private ImageFetcher mImageFetcher; - AssistantDetailsViewBinder(Context context, Locale locale, ImageFetcher imageFetcher) { + AssistantDetailsViewBinder(Context context, ImageFetcher imageFetcher) { mContext = context; - mLocale = locale; mImageWidth = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_details_image_size); mImageHeight = context.getResources().getDimensionPixelSize( @@ -138,32 +127,21 @@ private void setDetails(AssistantDetails details, ViewHolder viewHolder) { viewHolder.mTitleView.setText(details.getTitle()); - viewHolder.mDescriptionLine1View.setText(makeDescriptionLine1Text(details)); + viewHolder.mDescriptionLine1View.setText(details.getDescriptionLine1()); viewHolder.mDescriptionLine2View.setText(details.getDescriptionLine2()); + viewHolder.mDescriptionLine3View.setText(details.getDescriptionLine3()); viewHolder.mTotalPriceLabelView.setText(details.getTotalPriceLabel()); viewHolder.mTotalPriceView.setText(details.getTotalPrice()); + viewHolder.mPriceAttributionView.setText(details.getPriceAttribution()); - // If there is a price, we show descriptionLine3 on its left. Otherwise, we show it below - // descriptionLine2. - if (details.getTotalPrice().isEmpty()) { - viewHolder.mDescriptionLine3View.setText(details.getDescriptionLine3()); - viewHolder.mPriceAttributionView.setText(""); - } else { - viewHolder.mDescriptionLine3View.setText(""); - viewHolder.mPriceAttributionView.setText(details.getDescriptionLine3()); - } - - // Allow title line wrapping if no or only one description set. - boolean isDescriptionLine1Empty = viewHolder.mDescriptionLine1View.length() == 0; - boolean isDescriptionLine2Empty = viewHolder.mDescriptionLine2View.length() == 0; - if (isDescriptionLine1Empty || isDescriptionLine2Empty) { - int maxLines = isDescriptionLine1Empty && isDescriptionLine2Empty ? 3 : 2; - viewHolder.mTitleView.setSingleLine(false); - viewHolder.mTitleView.setMaxLines(maxLines); - viewHolder.mTitleView.setEllipsize(TextUtils.TruncateAt.END); - } else { + // Allow title line wrapping according to number of maximum allowed lines. + if (details.getTitleMaxLines() == 1) { viewHolder.mTitleView.setSingleLine(true); viewHolder.mTitleView.setEllipsize(null); + } else { + viewHolder.mTitleView.setSingleLine(false); + viewHolder.mTitleView.setMaxLines(details.getTitleMaxLines()); + viewHolder.mTitleView.setEllipsize(TextUtils.TruncateAt.END); } hideIfEmpty(viewHolder.mDescriptionLine1View); @@ -204,38 +182,6 @@ setTextStyles(details, viewHolder); } - private String makeDescriptionLine1Text(AssistantDetails details) { - if (!details.getDescriptionLine1().isEmpty()) { - return details.getDescriptionLine1(); - } else { - return makeDatetimeText(details); - } - } - - private String makeDatetimeText(AssistantDetails details) { - List<String> parts = new ArrayList<>(); - Date date = details.getDate(); - if (date != null) { - parts.add(formatDetailsTime(date)); - parts.add(formatDetailsDate(date)); - } - - // TODO(crbug.com/806868): Use a view instead of this dot text. - return TextUtils.join(" • ", parts); - } - - private String formatDetailsTime(Date date) { - DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, mLocale); - String timeFormatPattern = (df instanceof SimpleDateFormat) - ? ((SimpleDateFormat) df).toPattern() - : DETAILS_TIME_FORMAT; - return new SimpleDateFormat(timeFormatPattern, mLocale).format(date); - } - - private String formatDetailsDate(Date date) { - return new SimpleDateFormat(DETAILS_DATE_FORMAT, mLocale).format(date); - } - private void hideIfEmpty(TextView view) { view.setVisibility(view.length() == 0 ? View.GONE : View.VISIBLE); } @@ -248,7 +194,7 @@ setTextStyle(viewHolder.mDescriptionLine2View, details.getUserApprovalRequired(), details.getHighlightLine2(), R.style.TextAppearance_BlackBody); setTextStyle(viewHolder.mDescriptionLine3View, details.getUserApprovalRequired(), - details.getHighlightLine2(), R.style.TextAppearance_AssistantDetailsAttribution); + details.getHighlightLine3(), R.style.TextAppearance_AssistantDetailsAttribution); setTextStyle(viewHolder.mPriceAttributionView, details.getUserApprovalRequired(), details.getHighlightLine3(), R.style.TextAppearance_AssistantDetailsAttribution); setTextStyle(viewHolder.mTotalPriceLabelView, details.getUserApprovalRequired(),
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDetailsUiTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDetailsUiTest.java index ce5d0c9..135ecaf7 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDetailsUiTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantDetailsUiTest.java
@@ -11,16 +11,17 @@ import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; +import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.hasTypefaceStyle; import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.isTextMaxLines; import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking; import android.graphics.Bitmap; import android.graphics.BitmapFactory; +import android.graphics.Typeface; import android.support.test.InstrumentationRegistry; import android.support.test.filters.MediumTest; import android.view.View; @@ -32,7 +33,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.LocaleUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.ChromeSwitches; @@ -42,9 +42,6 @@ import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import java.util.Calendar; -import java.util.Locale; - /** Tests for the Autofill Assistant details. */ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @RunWith(ChromeJUnit4ClassRunner.class) @@ -76,21 +73,15 @@ } } + /** Creates a coordinator for use in UI tests, and adds it to the global view hierarchy. */ private AssistantDetailsCoordinator createCoordinator(AssistantDetailsModel model) throws Exception { - return createCoordinator(model, Locale.getDefault()); - } - - /** Creates a coordinator for use in UI tests, and adds it to the global view hierarchy. */ - private AssistantDetailsCoordinator createCoordinator( - AssistantDetailsModel model, Locale locale) throws Exception { AssistantDetailsCoordinator coordinator = runOnUiThreadBlocking(() -> { Bitmap testImage = BitmapFactory.decodeResource( mTestRule.getActivity().getResources(), R.drawable.btn_close); return new AssistantDetailsCoordinator(InstrumentationRegistry.getTargetContext(), - locale, model, - new AutofillAssistantUiTestUtil.MockImageFetcher(testImage, null)); + model, new AutofillAssistantUiTestUtil.MockImageFetcher(testImage, null)); }); runOnUiThreadBlocking(() @@ -125,21 +116,19 @@ runOnUiThreadBlocking(() -> { model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", "line 2", - "line 3", false, false, false, false, false, false)); + new AssistantDetails("title", 1, "image", null, false, "Total", "$12", "line 1", + "line 2", "", "line 3", false, false, false, false, false, false)); }); onView(is(viewHolder.mImageView)).check(matches(isDisplayed())); onView(is(viewHolder.mTitleView)).check(matches(isDisplayed())); onView(is(viewHolder.mDescriptionLine1View)).check(matches(isDisplayed())); onView(is(viewHolder.mDescriptionLine2View)).check(matches(isDisplayed())); + onView(is(viewHolder.mDescriptionLine3View)).check(matches(not(isDisplayed()))); onView(is(viewHolder.mPriceView)).check(matches(isDisplayed())); onView(is(viewHolder.mTotalPriceLabelView)).check(matches(isDisplayed())); onView(is(viewHolder.mTotalPriceView)).check(matches(isDisplayed())); - // When total price is set, descriptionLine3 is shown in mPriceAttributionView instead. onView(is(viewHolder.mPriceAttributionView)).check(matches(isDisplayed())); - onView(is(viewHolder.mDescriptionLine3View)).check(matches(not(isDisplayed()))); } @Test @@ -153,121 +142,60 @@ runOnUiThreadBlocking( () -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - null, "line 1", "line 2", "line 3", false, false, false, - false, false, false))); + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "line 1", "line 2", "", "line 3", false, false, + false, false, false, false))); onView(is(viewHolder.mTitleView)).check(matches(isTextMaxLines(1))); + onView(is(viewHolder.mTitleView)).check(matches(allOf(withText("title"), isDisplayed()))); - /* Description line 2 not set, title may wrap once. */ + /* titleMaxLines is set to 2, check that it is properly applied. */ runOnUiThreadBlocking(() -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, - "Total", "$12", null, "line 1", "", "line 3", + new AssistantDetails("title", 2, "image", null, false, + "Total", "$12", "line 1", "", "", "line 3", false, false, false, false, false, false))); onView(is(viewHolder.mTitleView)).check(matches(isTextMaxLines(2))); - - /* Description line 1 not set, title may wrap once.*/ - runOnUiThreadBlocking(() - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, - "Total", "$12", null, "", "line 2", "line 3", - false, false, false, false, false, false))); - onView(is(viewHolder.mTitleView)).check(matches(isTextMaxLines(2))); - - /* Description lines 1 and 2 not set, title may wrap twice.*/ - runOnUiThreadBlocking(() - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, - "Total", "$12", null, "", "", "line 3", false, - false, false, false, false, false))); - onView(is(viewHolder.mTitleView)).check(matches(isTextMaxLines(3))); - - /* Check title text and visibility. */ onView(is(viewHolder.mTitleView)).check(matches(allOf(withText("title"), isDisplayed()))); } @Test @MediumTest public void testDescriptionLine1() throws Exception { - Locale locale = LocaleUtils.forLanguageTag("en-US"); AssistantDetailsModel model = new AssistantDetailsModel(); - AssistantDetailsCoordinator coordinator = createCoordinator(model, locale); + AssistantDetailsCoordinator coordinator = createCoordinator(model); ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); - /* Both line 1 and date are set: description line 1 should show line 1. */ - runOnUiThreadBlocking( - () - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", - "line 2", "line 3", false, false, false, false, false, - false))); + /* Description line 1 is set and should be visible. */ + runOnUiThreadBlocking(() + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, + "", "", "line 1", "", "", "", false, false, + false, false, false, false))); onView(is(viewHolder.mDescriptionLine1View)) .check(matches(allOf(withText("line 1"), isDisplayed()))); - /* - * Line 1 is empty, but date is set: description line 1 should show the date & time. - * Note: locale was set to en-US, so we know the output format for date and time. - */ - Calendar calendar = java.util.Calendar.getInstance(locale); - calendar.set(2050, 6, 25, 10, 05, 00); + /* Description line 1 is not set and should be invisible. */ runOnUiThreadBlocking( () -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - calendar.getTime(), "", "line 2", "line 3", false, false, - false, false, false, false))); - onView(is(viewHolder.mDescriptionLine1View)) - .check(matches(withText(containsString("Mon, Jul 25")))); - onView(is(viewHolder.mDescriptionLine1View)) - .check(matches(withText(containsString("10:05 AM")))); - - /* Line 1 is empty, date is not set: description line 1 should be invisible. */ - runOnUiThreadBlocking(() - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, - "Total", "$12", null, "", "line 2", "line 3", - false, false, false, false, false, false))); + new AssistantDetails("title", 1, "image", null, false, "", "", "", + "", "", "", false, false, false, false, false, false))); onView(is(viewHolder.mDescriptionLine1View)).check(matches(not(isDisplayed()))); } @Test @MediumTest - public void testDescriptionLine1NonUSLocale() throws Exception { - Locale locale = LocaleUtils.forLanguageTag("de-DE"); - AssistantDetailsModel model = new AssistantDetailsModel(); - AssistantDetailsCoordinator coordinator = createCoordinator(model, locale); - ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); - - Calendar calendar = java.util.Calendar.getInstance(locale); - calendar.set(2050, 6, 25, 10, 05, 00); - runOnUiThreadBlocking( - () - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - calendar.getTime(), "", "line 2", "line 3", false, false, - false, false, false, false))); - onView(is(viewHolder.mDescriptionLine1View)) - .check(matches(withText(containsString("Mo., Juli 25")))); - onView(is(viewHolder.mDescriptionLine1View)) - .check(matches(withText(containsString("10:05")))); - } - - @Test - @MediumTest public void testDescriptionLine2() throws Exception { AssistantDetailsModel model = new AssistantDetailsModel(); AssistantDetailsCoordinator coordinator = createCoordinator(model); ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); /* Description line 2 is set and should be visible. */ - runOnUiThreadBlocking( - () - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", - "line 2", "line 3", false, false, false, false, false, - false))); + runOnUiThreadBlocking(() + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, + "", "", "", "line 2", "", "", false, false, + false, false, false, false))); onView(is(viewHolder.mDescriptionLine2View)) .check(matches(allOf(withText("line 2"), isDisplayed()))); @@ -275,9 +203,8 @@ runOnUiThreadBlocking( () -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", "", - "line 3", false, false, false, false, false, false))); + new AssistantDetails("title", 2, "image", null, false, "", "", "", + "", "", "", false, false, false, false, false, false))); onView(is(viewHolder.mDescriptionLine2View)).check(matches(not(isDisplayed()))); } @@ -288,37 +215,126 @@ AssistantDetailsCoordinator coordinator = createCoordinator(model); ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); - /* No total price set, line 3 should be displayed in the normal spot. */ - runOnUiThreadBlocking( - () - -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "", "", - java.util.Calendar.getInstance().getTime(), "line 1", - "line 2", "line 3", false, false, false, false, false, - false))); + /* Description line 3 is set and should be visible. */ + runOnUiThreadBlocking(() + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, + "", "", "", "", "line 3", "", false, false, + false, false, false, false))); onView(is(viewHolder.mDescriptionLine3View)) .check(matches(allOf(withText("line 3"), isDisplayed()))); - onView(is(viewHolder.mPriceAttributionView)).check(matches(not(isDisplayed()))); - /* Total price and line 3 set, line 3 should be displayed in a different view. */ + /* Description line 3 is not set and should be invisible. */ + runOnUiThreadBlocking(() + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, + "", "", "", "", "", "line 3", false, false, + false, false, false, false))); + onView(is(viewHolder.mDescriptionLine3View)).check(matches(not(isDisplayed()))); + } + + @Test + @MediumTest + public void testPriceAttribution() throws Exception { + AssistantDetailsModel model = new AssistantDetailsModel(); + AssistantDetailsCoordinator coordinator = createCoordinator(model); + ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); + + /* Price attribution is set and should be visible. */ runOnUiThreadBlocking( () -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", "", - "line 3", false, false, false, false, false, false))); + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "", "", "", "price attribution", false, false, false, + false, false, false))); onView(is(viewHolder.mPriceAttributionView)) - .check(matches(allOf(withText("line 3"), isDisplayed()))); - onView(is(viewHolder.mDescriptionLine3View)).check(matches(not(isDisplayed()))); + .check(matches(allOf(withText("price attribution"), isDisplayed()))); - /* Line 3 not set, both views should be invisible. */ + /* Price attribution is not set and should be invisible. */ runOnUiThreadBlocking( () -> model.set(AssistantDetailsModel.DETAILS, - new AssistantDetails("title", "image", null, false, "Total", "$12", - java.util.Calendar.getInstance().getTime(), "line 1", "", - "", false, false, false, false, false, false))); - onView(is(viewHolder.mDescriptionLine3View)).check(matches(not(isDisplayed()))); + new AssistantDetails("title", 2, "image", null, false, "", "", "", + "", "", "", false, false, false, false, false, false))); onView(is(viewHolder.mPriceAttributionView)).check(matches(not(isDisplayed()))); } + + @Test + @MediumTest + public void testHighlighting() throws Exception { + AssistantDetailsModel model = new AssistantDetailsModel(); + AssistantDetailsCoordinator coordinator = createCoordinator(model); + ViewHolder viewHolder = runOnUiThreadBlocking(() -> new ViewHolder(coordinator.getView())); + + /* Check that title is highlighted. */ + runOnUiThreadBlocking( + () + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "line 1", "line 2", "line 3", "Est. total", true, + true, false, false, false, false))); + onView(is(viewHolder.mTitleView)).check(matches(hasTypefaceStyle(Typeface.BOLD_ITALIC))); + onView(is(viewHolder.mDescriptionLine1View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine2View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine3View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mPriceAttributionView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + + /* Check that description 1 is highlighted. */ + runOnUiThreadBlocking( + () + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "line 1", "line 2", "line 3", "Est. total", true, + false, true, false, false, false))); + onView(is(viewHolder.mTitleView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine1View)) + .check(matches(hasTypefaceStyle(Typeface.BOLD_ITALIC))); + onView(is(viewHolder.mDescriptionLine2View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine3View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mPriceAttributionView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + + /* Check that description 2 is highlighted. */ + runOnUiThreadBlocking( + () + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "line 1", "line 2", "line 3", "Est. total", true, + false, false, true, false, false))); + onView(is(viewHolder.mTitleView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine1View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine2View)) + .check(matches(hasTypefaceStyle(Typeface.BOLD_ITALIC))); + onView(is(viewHolder.mDescriptionLine3View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mPriceAttributionView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + + /* Check that description 3 and price attribution are highlighted. */ + runOnUiThreadBlocking( + () + -> model.set(AssistantDetailsModel.DETAILS, + new AssistantDetails("title", 1, "image", null, false, "Total", + "$12", "line 1", "line 2", "line 3", "Est. total", true, + false, false, false, true, false))); + onView(is(viewHolder.mTitleView)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine1View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine2View)) + .check(matches(not(hasTypefaceStyle(Typeface.BOLD_ITALIC)))); + onView(is(viewHolder.mDescriptionLine3View)) + .check(matches(hasTypefaceStyle(Typeface.BOLD_ITALIC))); + onView(is(viewHolder.mPriceAttributionView)) + .check(matches(hasTypefaceStyle(Typeface.BOLD_ITALIC))); + } }
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java index fd52f00..d8f8816 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTest.java
@@ -57,7 +57,6 @@ import org.chromium.net.test.EmbeddedTestServer; import java.util.Arrays; -import java.util.Calendar; import java.util.List; /** @@ -170,12 +169,14 @@ () -> assistantCoordinator.getModel().getDetailsModel().set( AssistantDetailsModel.DETAILS, - new AssistantDetails(movieTitle, /* imageUrl = */ "", + new AssistantDetails(movieTitle, /* titleMaxLines = */ 1, + /* imageUrl = */ "", /* imageClickthroughData = */ null, /* showImage = */ false, /* totalPriceLabel = */ "", - /* totalPrice = */ "", Calendar.getInstance().getTime(), - descriptionLine1, descriptionLine2, descriptionLine3, + /* totalPrice = */ "", descriptionLine1, descriptionLine2, + descriptionLine3, + /* priceAttribution = */ "", /* userApprovalRequired= */ false, /* highlightTitle= */ false, /* highlightLine1= */ false, /* highlightLine2 = */ false,
diff --git a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java index 3badbb0f1..4e96e07 100644 --- a/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java +++ b/chrome/android/features/autofill_assistant/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiTestUtil.java
@@ -8,6 +8,7 @@ import static android.support.test.espresso.assertion.ViewAssertions.matches; import android.graphics.Bitmap; +import android.graphics.Typeface; import android.support.design.widget.CoordinatorLayout; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.NoMatchingViewException; @@ -85,6 +86,9 @@ return new TypeSafeMatcher<View>() { @Override protected boolean matchesSafely(View item) { + if (!(item instanceof TextView)) { + return false; + } return ((TextView) item).getMaxLines() == maxLines; } @@ -95,6 +99,28 @@ }; } + /** Checks that a text view has a specific typeface style. */ + public static TypeSafeMatcher<View> hasTypefaceStyle(/*@Typeface.Style*/ int style) { + return new TypeSafeMatcher<View>() { + @Override + protected boolean matchesSafely(View item) { + if (!(item instanceof TextView)) { + return false; + } + Typeface typeface = ((TextView) item).getTypeface(); + if (typeface == null) { + return false; + } + return (typeface.getStyle() & style) == style; + } + + @Override + public void describeTo(Description description) { + description.appendText("hasTypefaceStyle"); + } + }; + } + /** Returns all views with a matching tag. */ public static List<View> findViewsWithTag(View view, Object tag) { List<View> viewsWithTag = new ArrayList<>();
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java index 80c7345f3..852412a7 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java
@@ -6,6 +6,7 @@ import org.chromium.base.metrics.CachedMetrics.EnumeratedHistogramSample; import org.chromium.chrome.browser.autofill_assistant.metrics.DropOutReason; +import org.chromium.chrome.browser.autofill_assistant.metrics.FeatureModuleInstallation; import org.chromium.chrome.browser.autofill_assistant.metrics.OnBoarding; /** @@ -27,6 +28,10 @@ new EnumeratedHistogramSample( "Android.AutofillAssistant.OnBoarding", OnBoarding.MAX_VALUE + 1); + private static final EnumeratedHistogramSample ENUMERATED_FEATURE_MODULE_INSTALLATION = + new EnumeratedHistogramSample("Android.AutofillAssistant.FeatureModuleInstallation", + FeatureModuleInstallation.MAX_VALUE + 1); + /** * Records the reason for a drop out. */ @@ -40,4 +45,12 @@ /* package */ static void recordOnBoarding(@OnBoarding int metric) { ENUMERATED_ON_BOARDING.record(metric); } + + /** + * Records the feature module installation action. + */ + /* package */ static void recordFeatureModuleInstallation( + @FeatureModuleInstallation int metric) { + ENUMERATED_FEATURE_MODULE_INSTALLATION.record(metric); + } }
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java index 50d6b50..ef0dc28 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantModuleEntryProvider.java
@@ -11,6 +11,7 @@ import org.chromium.base.Log; import org.chromium.base.SysUtils; import org.chromium.chrome.R; +import org.chromium.chrome.browser.autofill_assistant.metrics.FeatureModuleInstallation; import org.chromium.chrome.browser.modules.ModuleInstallUi; import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.module_installer.ModuleInstaller; @@ -45,6 +46,8 @@ void getModuleEntry(Tab tab, Callback<AutofillAssistantModuleEntry> callback) { AutofillAssistantModuleEntry entry = getModuleEntryIfInstalled(); if (entry != null) { + AutofillAssistantMetrics.recordFeatureModuleInstallation( + FeatureModuleInstallation.DFM_ALREADY_INSTALLED); callback.onResult(entry); return; } @@ -79,6 +82,8 @@ return; } Log.v(TAG, "Deferred install triggered."); + AutofillAssistantMetrics.recordFeatureModuleInstallation( + FeatureModuleInstallation.DFM_BACKGROUND_INSTALLATION_REQUESTED); AutofillAssistantModule.installDeferred(); } @@ -91,6 +96,8 @@ if (retry) { loadDynamicModuleWithUi(tab, callback); } else { + AutofillAssistantMetrics.recordFeatureModuleInstallation( + FeatureModuleInstallation.DFM_FOREGROUND_INSTALLATION_FAILED); callback.onResult(null); } } @@ -100,6 +107,8 @@ ModuleInstaller.getInstance().install("autofill_assistant", (success) -> { if (success) { // Don't show success UI from DFM, transition to autobot UI directly. + AutofillAssistantMetrics.recordFeatureModuleInstallation( + FeatureModuleInstallation.DFM_FOREGROUND_INSTALLATION_SUCCEEDED); callback.onResult(AutofillAssistantModule.getImpl()); return; }
diff --git a/chrome/android/java/res/drawable-hdpi/navigation_bubble_shadow.9.png b/chrome/android/java/res/drawable-hdpi-v21/navigation_bubble_shadow.9.png similarity index 100% rename from chrome/android/java/res/drawable-hdpi/navigation_bubble_shadow.9.png rename to chrome/android/java/res/drawable-hdpi-v21/navigation_bubble_shadow.9.png Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/navigation_bubble_shadow.9.png b/chrome/android/java/res/drawable-mdpi-v21/navigation_bubble_shadow.9.png similarity index 100% rename from chrome/android/java/res/drawable-mdpi/navigation_bubble_shadow.9.png rename to chrome/android/java/res/drawable-mdpi-v21/navigation_bubble_shadow.9.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xhdpi/navigation_bubble_shadow.9.png b/chrome/android/java/res/drawable-xhdpi-v21/navigation_bubble_shadow.9.png similarity index 100% rename from chrome/android/java/res/drawable-xhdpi/navigation_bubble_shadow.9.png rename to chrome/android/java/res/drawable-xhdpi-v21/navigation_bubble_shadow.9.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/navigation_bubble_shadow.9.png b/chrome/android/java/res/drawable-xxhdpi-v21/navigation_bubble_shadow.9.png similarity index 100% rename from chrome/android/java/res/drawable-xxhdpi/navigation_bubble_shadow.9.png rename to chrome/android/java/res/drawable-xxhdpi-v21/navigation_bubble_shadow.9.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxxhdpi/navigation_bubble_shadow.9.png b/chrome/android/java/res/drawable-xxxhdpi-v21/navigation_bubble_shadow.9.png similarity index 100% rename from chrome/android/java/res/drawable-xxxhdpi/navigation_bubble_shadow.9.png rename to chrome/android/java/res/drawable-xxxhdpi-v21/navigation_bubble_shadow.9.png Binary files differ
diff --git a/chrome/android/java/res/drawable/navigation_bubble_shadow.xml b/chrome/android/java/res/drawable/navigation_bubble_shadow.xml new file mode 100644 index 0000000..3bc26b92 --- /dev/null +++ b/chrome/android/java/res/drawable/navigation_bubble_shadow.xml
@@ -0,0 +1,82 @@ +<?xml version="1.0" encoding="utf-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. --> + +<!-- TODO(crbug.com/1009058): Remove this with KitKiat deprecation. --> + +<layer-list + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/navigation_bubble_shadow"> + + <!-- Drop Shadow --> + <item> + <shape android:shape="rectangle"> + <padding + android:bottom="@dimen/navigation_bubble_shadow_padding" + android:left="@dimen/navigation_bubble_shadow_padding" + android:right="@dimen/navigation_bubble_shadow_padding" + android:top="@dimen/navigation_bubble_shadow_padding" /> + + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="#00CCCCCC" /> + + </shape> + </item> + <item> + <shape android:shape="rectangle"> + <padding + android:bottom="@dimen/navigation_bubble_shadow_padding" + android:left="@dimen/navigation_bubble_shadow_padding" + android:right="@dimen/navigation_bubble_shadow_padding" + android:top="@dimen/navigation_bubble_shadow_padding" /> + + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="#10CCCCCC" /> + </shape> + </item> + <item> + <shape android:shape="rectangle"> + <padding + android:bottom="@dimen/navigation_bubble_shadow_padding" + android:left="@dimen/navigation_bubble_shadow_padding" + android:right="@dimen/navigation_bubble_shadow_padding" + android:top="@dimen/navigation_bubble_shadow_padding" /> + + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="#20CCCCCC" /> + </shape> + </item> + <item> + <shape android:shape="rectangle"> + <padding + android:bottom="@dimen/navigation_bubble_shadow_padding" + android:left="@dimen/navigation_bubble_shadow_padding" + android:right="@dimen/navigation_bubble_shadow_padding" + android:top="@dimen/navigation_bubble_shadow_padding" /> + + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="#30CCCCCC" /> + </shape> + </item> + <item> + <shape android:shape="rectangle"> + <padding + android:bottom="@dimen/navigation_bubble_shadow_padding" + android:left="@dimen/navigation_bubble_shadow_padding" + android:right="@dimen/navigation_bubble_shadow_padding" + android:top="@dimen/navigation_bubble_shadow_padding" /> + + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="#50CCCCCC" /> + </shape> + </item> + + <!-- Background Color (white) --> + <item> + <shape android:shape="rectangle"> + <corners android:radius="@dimen/navigation_bubble_radius" /> + <solid android:color="@color/navigation_bubble_background_color" /> + </shape> + </item> +</layer-list>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 6fc0fb24..5674cac 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -685,6 +685,8 @@ <!-- History Navigation UI Item --> <dimen name="navigation_bubble_size">44dp</dimen> + <dimen name="navigation_bubble_radius">22dp</dimen> + <dimen name="navigation_bubble_shadow_padding">1dp</dimen> <dimen name="navigation_bubble_arrow_size">32dp</dimen> <dimen name="navigation_bubble_start_padding">2dp</dimen> <dimen name="navigation_bubble_top_padding">4dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java index 4d1eb71..a9e3c20 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackgroundService.java
@@ -12,7 +12,6 @@ import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.background_sync.BackgroundSyncBackgroundTaskScheduler; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; @@ -92,14 +91,7 @@ @VisibleForTesting protected void launchBrowser(Context context, String tag) { Log.i(TAG, "Launching browser"); - try { - ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "ProcessInitException while starting the browser process"); - // Since the library failed to initialize nothing in the application - // can work, so kill the whole application not just the activity. - System.exit(-1); - } + ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); } @VisibleForTesting
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackupAgent.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackupAgent.java index fc380e2..b066c1c4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackupAgent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeBackupAgent.java
@@ -19,7 +19,6 @@ import org.chromium.base.Log; import org.chromium.base.PathUtils; import org.chromium.base.VisibleForTesting; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.firstrun.FirstRunSignInProcessor; @@ -160,12 +159,7 @@ Log.e(TAG, "Backup agent started from child process"); return false; } - try { - ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.w(TAG, "Browser launch failed on backup or restore: " + e); - return false; - } + ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/SynchronousInitializationActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/SynchronousInitializationActivity.java index d047490..168053cf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/SynchronousInitializationActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/SynchronousInitializationActivity.java
@@ -8,8 +8,6 @@ import androidx.annotation.CallSuper; -import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.browser.bookmarks.BookmarkActivity; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; @@ -27,12 +25,6 @@ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - // Ensure that native library is loaded. - try { - ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTask.java b/chrome/android/java/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTask.java index 390212d..61612ce 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTask.java
@@ -173,9 +173,8 @@ ChromeBrowserInitializer.getInstance(context).handlePostNativeStartup( true /* isAsync */, parts); } catch (ProcessInitException e) { - Log.e(TAG, "ProcessInitException while starting the browser process."); + Log.e(TAG, "Background Launch Error", e); rescheduleRunnable.run(); - return; } } });
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java index 1e32afc7..4bb3b0f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarkswidget/BookmarkWidgetService.java
@@ -25,7 +25,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.task.PostTask; import org.chromium.chrome.R; @@ -307,14 +306,7 @@ public void onCreate() { // Required to be applied here redundantly to prevent crashes in the cases where the // package data is deleted or the Chrome application forced to stop. - try { - ChromeBrowserInitializer.getInstance(mContext).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - // Since the library failed to initialize nothing in the application - // can work, so kill the whole application not just the activity - System.exit(-1); - } + ChromeBrowserInitializer.getInstance(mContext).handleSynchronousStartup(); if (isWidgetNewlyCreated()) { RecordUserAction.record("BookmarkNavigatorWidgetAdded"); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java index 0ab364d..268c815 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/OriginVerifier.java
@@ -33,6 +33,7 @@ import org.chromium.chrome.browser.util.UrlConstants; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.UiThreadTaskTraits; +import org.chromium.content_public.browser.WebContents; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -76,6 +77,8 @@ @Nullable private OriginVerificationListener mListener; private Origin mOrigin; private long mVerificationStartTime; + @Nullable + private WebContents mWebContents; /** * A collection of Relationships (stored as Strings, with the signature set to an empty String) @@ -89,8 +92,9 @@ @Inject public Factory() {} - public OriginVerifier create(String packageName, @Relation int relation) { - return new OriginVerifier(packageName, relation); + public OriginVerifier create( + String packageName, @Relation int relation, @Nullable WebContents webContents) { + return new OriginVerifier(packageName, relation, webContents); } } @@ -205,11 +209,15 @@ * Use {@link OriginVerifier#start} * @param packageName The package for the Android application for verification. * @param relation Digital Asset Links {@link Relation} to use during verification. + * @param webContents The web contents of the tab used for reporting errors to DevTools. Can be + * null if unavailable. */ - public OriginVerifier(String packageName, @Relation int relation) { + public OriginVerifier( + String packageName, @Relation int relation, @Nullable WebContents webContents) { mPackageName = packageName; mSignatureFingerprint = getCertificateSHA256FingerprintForPackage(mPackageName); mRelation = relation; + mWebContents = webContents; } /** @@ -257,8 +265,9 @@ // Early return for testing without native. return; } - mNativeOriginVerifier = OriginVerifierJni.get().init( - OriginVerifier.this, Profile.getLastUsedProfile().getOriginalProfile()); + if (mWebContents != null && mWebContents.isDestroyed()) mWebContents = null; + mNativeOriginVerifier = OriginVerifierJni.get().init(OriginVerifier.this, mWebContents, + Profile.getLastUsedProfile().getOriginalProfile()); assert mNativeOriginVerifier != 0; String relationship = null; switch (mRelation) { @@ -451,7 +460,7 @@ @NativeMethods interface Natives { - long init(OriginVerifier caller, Profile profile); + long init(OriginVerifier caller, @Nullable WebContents webContents, Profile profile); boolean verifyOrigin(long nativeOriginVerifier, OriginVerifier caller, String packageName, String signatureFingerprint, String origin, String relationship); void destroy(long nativeOriginVerifier, OriginVerifier caller);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifier.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifier.java index 6b44c96c..e2dcce10 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifier.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifier.java
@@ -34,6 +34,7 @@ import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.tab.TabObserverRegistrar; import org.chromium.content_public.browser.NavigationHandle; +import org.chromium.content_public.browser.WebContents; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -53,7 +54,7 @@ public class TrustedWebActivityVerifier implements NativeInitObserver, Destroyable, SaveInstanceStateObserver { /** The Digital Asset Link relationship used for Trusted Web Activities. */ - private final static int RELATIONSHIP = CustomTabsService.RELATION_HANDLE_ALL_URLS; + private static final int RELATIONSHIP = CustomTabsService.RELATION_HANDLE_ALL_URLS; /** Used in activity instance state */ private static final String KEY_CLIENT_PACKAGE = "twaClientPackageName"; @@ -145,7 +146,10 @@ } assert mClientPackageName != null; - mOriginVerifier = originVerifierFactory.create(mClientPackageName, RELATIONSHIP); + WebContents webContents = + tabProvider.getTab() != null ? tabProvider.getTab().getWebContents() : null; + mOriginVerifier = + originVerifierFactory.create(mClientPackageName, RELATIONSHIP, webContents); tabObserverRegistrar.registerTabObserver(mVerifyOnPageLoadObserver); tabProvider.addObserver(mVerifyOnTabSwitchObserver);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java index 2b5361b..46643a0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java
@@ -477,7 +477,8 @@ } }; - params.originVerifier = new OriginVerifier(params.getPackageName(), relation); + params.originVerifier = + new OriginVerifier(params.getPackageName(), relation, /* webContents= */ null); PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, () -> { params.originVerifier.start(listener, origin); }); if (relation == CustomTabsService.RELATION_HANDLE_ALL_URLS
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java index 513e940..e2b1dbb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabsConnection.java
@@ -45,7 +45,6 @@ import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.CachedMetrics.EnumeratedHistogramSample; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; @@ -373,14 +372,7 @@ /** Warmup activities that should only happen once. */ private static void initializeBrowser(final Context context) { ThreadUtils.assertOnUiThread(); - try { - ChromeBrowserInitializer.getInstance(context).handleSynchronousStartupWithGpuWarmUp(); - } catch (ProcessInitException e) { - Log.e(TAG, "ProcessInitException while starting the browser process."); - // Cannot do anything without the native library, and cannot show a - // dialog to the user. - System.exit(-1); - } + ChromeBrowserInitializer.getInstance(context).handleSynchronousStartupWithGpuWarmUp(); ChildProcessLauncherHelper.warmUp(context, true); } @@ -490,8 +482,7 @@ String scheme = uri.normalizeScheme().getScheme(); boolean allowedScheme = scheme == null || scheme.equals(UrlConstants.HTTP_SCHEME) || scheme.equals(UrlConstants.HTTPS_SCHEME); - if (!allowedScheme) return false; - return true; + return allowedScheme; } /** @@ -1308,7 +1299,7 @@ String line = null; while ((line = reader.readLine()) != null) { // line format: 2:cpu:/bg_non_interactive - String fields[] = line.trim().split(":"); + String[] fields = line.trim().split(":"); if (fields.length == 3 && fields[1].equals(controllerName)) return fields[2]; } } catch (IOException e) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadBroadcastManager.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadBroadcastManager.java index dee0866..419eb616 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadBroadcastManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadBroadcastManager.java
@@ -31,11 +31,8 @@ import org.chromium.base.ContentUriUtils; import org.chromium.base.ContextUtils; -import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.download.DownloadNotificationUmaHelper.UmaDownloadResumption; import org.chromium.chrome.browser.download.items.OfflineContentAggregatorNotificationBridgeUiFactory; @@ -211,13 +208,8 @@ } }; - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); } @VisibleForTesting @@ -345,7 +337,7 @@ // On Q+, content URI is being used and there is no download ID. openDownloadWithId(context, intent, DownloadItem.INVALID_DOWNLOAD_ID, contentId); } else { - long ids[] = + long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS); if (ids == null || ids.length == 0) { DownloadManagerService.openDownloadsPage(context, DownloadOpenSource.NOTIFICATION);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitializationActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitializationActivity.java index 04f3ac62..d95507c7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitializationActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitializationActivity.java
@@ -499,11 +499,7 @@ @Override public final void onCreateWithNative() { mLifecycleDispatcher.onCreateWithNative(); - try { - ChromeBrowserInitializer.getInstance(this).handlePostNativeStartup(true, this); - } catch (ProcessInitException e) { - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance(this).handlePostNativeStartup(true, this); } @CallSuper
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java index 24a2371..aeae778 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java
@@ -24,7 +24,6 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryPrefetcher; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.memory.MemoryPressureUma; import org.chromium.base.task.AsyncTask; import org.chromium.base.task.PostTask; @@ -135,22 +134,19 @@ /** * Initializes the Chrome browser process synchronously. - * - * @throws ProcessInitException if there is a problem with the native library. */ - public void handleSynchronousStartup() throws ProcessInitException { + public void handleSynchronousStartup() { handleSynchronousStartupInternal(false); } /** * Initializes the Chrome browser process synchronously with GPU process warmup. */ - public void handleSynchronousStartupWithGpuWarmUp() throws ProcessInitException { + public void handleSynchronousStartupWithGpuWarmUp() { handleSynchronousStartupInternal(true); } - private void handleSynchronousStartupInternal(final boolean startGpuProcess) - throws ProcessInitException { + private void handleSynchronousStartupInternal(final boolean startGpuProcess) { ThreadUtils.checkUiThread(); BrowserParts parts = new EmptyBrowserParts() { @@ -268,8 +264,7 @@ * @param delegate The delegate for the {@link ChromeBrowserInitializer} to communicate * initialization tasks. */ - public void handlePostNativeStartup(final boolean isAsync, final BrowserParts delegate) - throws ProcessInitException { + public void handlePostNativeStartup(final boolean isAsync, final BrowserParts delegate) { assert ThreadUtils.runningOnUiThread() : "Tried to start the browser on the wrong thread"; if (!mPostInflationStartupComplete) { throw new IllegalStateException( @@ -351,8 +346,7 @@ } private void startChromeBrowserProcessesAsync(boolean startGpuProcess, - boolean startServiceManagerOnly, BrowserStartupController.StartupCallback callback) - throws ProcessInitException { + boolean startServiceManagerOnly, BrowserStartupController.StartupCallback callback) { try { TraceEvent.begin("ChromeBrowserInitializer.startChromeBrowserProcessesAsync"); getBrowserStartupController().startBrowserProcessesAsync( @@ -362,7 +356,7 @@ } } - private void startChromeBrowserProcessesSync() throws ProcessInitException { + private void startChromeBrowserProcessesSync() { try { TraceEvent.begin("ChromeBrowserInitializer.startChromeBrowserProcessesSync"); ThreadUtils.assertOnUiThread();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/NativeStartupBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/init/NativeStartupBridge.java index f4f17a2..98983dd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/NativeStartupBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/NativeStartupBridge.java
@@ -4,10 +4,8 @@ package org.chromium.chrome.browser.init; -import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.UiThreadTaskTraits; @@ -29,13 +27,9 @@ PostTask.postTask(UiThreadTaskTraits.DEFAULT, new Runnable() { @Override public void run() { - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup( - true /* isAsync */, parts); - } catch (ProcessInitException e) { - Log.e(TAG, "ProcessInitException while starting the browser process."); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup( + true /* isAsync */, parts); } }); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridge.java index 680e96d..c33c3fe1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridge.java
@@ -29,7 +29,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; @@ -250,15 +249,7 @@ // activity, and it loads the library, but there are some native calls even before that // activity is started: from RecordUserAction.record and (indirectly) from // UrlFormatter.formatUrlForSecurityDisplay. - try { - ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - // The library failed to initialize and nothing in the application can work, so kill - // the whole application. - System.exit(-1); - return; - } + ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); // Use the application context because it lives longer. When using the given context, it // may be stopped before the preferences intent is handled.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationService.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationService.java index b6bf2ee..07cf085 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationService.java
@@ -18,7 +18,6 @@ import android.os.SystemClock; import android.util.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.webapps.WebappRegistry; @@ -102,33 +101,27 @@ * @param intent The intent containing the notification's information. */ static void dispatchIntentOnUIThread(Context context, Intent intent) { + ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); + + // Warm up the WebappRegistry, as we need to check if this notification should launch a + // standalone web app. This no-ops if the registry is already initialized and warmed, + // but triggers a strict mode violation otherwise (i.e. the browser isn't running). + // Temporarily disable strict mode to work around the violation. + StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { - ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); - - // Warm up the WebappRegistry, as we need to check if this notification should launch a - // standalone web app. This no-ops if the registry is already initialized and warmed, - // but triggers a strict mode violation otherwise (i.e. the browser isn't running). - // Temporarily disable strict mode to work around the violation. - StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); - try { - WebappRegistry.getInstance(); - WebappRegistry.warmUpSharedPrefs(); - } finally { - StrictMode.setThreadPolicy(oldPolicy); - } - - // Now that the browser process is initialized, we pass forward the call to the - // NotificationPlatformBridge which will take care of delivering the appropriate events. - if (!NotificationPlatformBridge.dispatchNotificationEvent(intent)) { - Log.w(TAG, "Unable to dispatch the notification event to Chrome."); - } - - // TODO(peter): Verify that the lifetime of the NotificationService is sufficient - // when a notification event could be dispatched successfully. - - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to start the browser process.", e); - System.exit(-1); + WebappRegistry.getInstance(); + WebappRegistry.warmUpSharedPrefs(); + } finally { + StrictMode.setThreadPolicy(oldPolicy); } + + // Now that the browser process is initialized, we pass forward the call to the + // NotificationPlatformBridge which will take care of delivering the appropriate events. + if (!NotificationPlatformBridge.dispatchNotificationEvent(intent)) { + Log.w(TAG, "Unable to dispatch the notification event to Chrome."); + } + + // TODO(peter): Verify that the lifetime of the NotificationService is sufficient + // when a notification event could be dispatched successfully. } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/scheduler/DisplayAgent.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/scheduler/DisplayAgent.java index 95303f92..9a00e4d8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/scheduler/DisplayAgent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/scheduler/DisplayAgent.java
@@ -13,12 +13,9 @@ import android.os.Build; import org.chromium.base.ContextUtils; -import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.init.EmptyBrowserParts; @@ -165,13 +162,8 @@ }; // Try to load native. - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateNotificationController.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateNotificationController.java index e356a5a..871afd2c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateNotificationController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateNotificationController.java
@@ -22,11 +22,9 @@ import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.document.ChromeLauncherActivity; import org.chromium.chrome.browser.init.BrowserParts; @@ -212,13 +210,8 @@ }; // Try to load native. - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library after clicking update notification.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); } private void handleUpdateIntent(Context context, Intent intent) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/CredentialLeakDialogBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/CredentialLeakDialogBridge.java index 6b43f25..0e254907 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/CredentialLeakDialogBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/CredentialLeakDialogBridge.java
@@ -9,6 +9,7 @@ import org.chromium.chrome.browser.ChromeActivity; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modaldialog.DialogDismissalCause; +import org.chromium.ui.modaldialog.ModalDialogManager; /** JNI call glue between the native password manager CredentialLeak class and Java objects. */ public class CredentialLeakDialogBridge { @@ -37,7 +38,7 @@ boolean primaryButtonFilled = negativeButton != null; mCredentialLeakDialog.showDialog(credentialLeakTitle, credentialLeakDetails, boldRangeStart, boldRangeEnd, R.drawable.password_check_warning, positiveButton, negativeButton, - this::onClick, primaryButtonFilled); + this::onClick, primaryButtonFilled, ModalDialogManager.ModalDialogType.APP); } @CalledByNative
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/OnboardingDialogBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/OnboardingDialogBridge.java index 998435e..8fee33a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/OnboardingDialogBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/OnboardingDialogBridge.java
@@ -15,6 +15,7 @@ import org.chromium.chrome.browser.ChromeActivity; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modaldialog.DialogDismissalCause; +import org.chromium.ui.modaldialog.ModalDialogManager; /** JNI call glue between the native password manager onboarding class and Java objects. */ public class OnboardingDialogBridge { @@ -64,7 +65,8 @@ public void showDialog(String onboardingTitle, String onboardingDetails) { mOnboardingDialog.showDialog(onboardingTitle, onboardingDetails, getDrawableResourceFromFeature(), mResources.getString(R.string.continue_button), - mResources.getString(R.string.not_now), this::onClick, true); + mResources.getString(R.string.not_now), this::onClick, true, + ModalDialogManager.ModalDialogType.TAB); } @CalledByNative
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogCoordinator.java index 05321eb..2f4972d9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogCoordinator.java
@@ -42,18 +42,18 @@ public void showDialog(String title, String details, int boldRangeStart, int boldRangeEnd, @DrawableRes int drawableId, String positiveButtonText, String negativeButtonText, - Callback<Integer> onClick, boolean primaryButtonFilled) { + Callback<Integer> onClick, boolean primaryButtonFilled, + @ModalDialogManager.ModalDialogType int type) { mMediator.setContents(title, details, boldRangeStart, boldRangeEnd, drawableId); mMediator.setButtons(positiveButtonText, negativeButtonText, onClick, primaryButtonFilled); - mMediator.showDialog(); + mMediator.showDialog(type); } public void showDialog(String title, String details, @DrawableRes int drawableId, String positiveButtonText, String negativeButtonText, Callback<Integer> onClick, - boolean primaryButtonFilled) { - mMediator.setContents(title, details, 0, 0, drawableId); - mMediator.setButtons(positiveButtonText, negativeButtonText, onClick, primaryButtonFilled); - mMediator.showDialog(); + boolean primaryButtonFilled, @ModalDialogManager.ModalDialogType int type) { + showDialog(title, details, 0, 0, drawableId, positiveButtonText, negativeButtonText, + onClick, primaryButtonFilled, type); } public void dismissDialog(@DialogDismissalCause int dismissalCause) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogMediator.java index 5073607..81c7b7d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogMediator.java
@@ -123,11 +123,11 @@ mModel.set(ILLUSTRATION_VISIBLE, hasSufficientSpaceForIllustration(newHeight)); } - void showDialog() { + void showDialog(@ModalDialogManager.ModalDialogType int type) { mModel.set(ILLUSTRATION_VISIBLE, hasSufficientSpaceForIllustration(mAndroidContentView.getHeight())); mDialogModel = mModalDialogBuilder.build(); - mDialogManager.showDialog(mDialogModel, ModalDialogManager.ModalDialogType.TAB); + mDialogManager.showDialog(mDialogModel, type); } void dismissDialog(int dismissalClause) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java index 887145be..2d0073e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java
@@ -20,7 +20,6 @@ import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.content_public.browser.UiThreadTaskTraits; @@ -55,20 +54,17 @@ if (!CommandLine.isInitialized()) { CommandLine.init(null); } - try { - // The decoder service relies on PathUtils. - PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> { - PathUtils.setPrivateDataDirectorySuffix( - ChromeApplication.PRIVATE_DATA_DIRECTORY_SUFFIX); - }); - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); - DecoderServiceJni.get().initializePhotoPickerSandbox(); + // The decoder service relies on PathUtils. + PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> { + PathUtils.setPrivateDataDirectorySuffix( + ChromeApplication.PRIVATE_DATA_DIRECTORY_SUFFIX); + }); - mNativeLibraryAndSandboxInitialized = true; - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to initialize the native library and sandbox", e); - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); + DecoderServiceJni.get().initializePhotoPickerSandbox(); + + mNativeLibraryAndSandboxInitialized = true; super.onCreate(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java index adb757e..f05a178 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java
@@ -21,14 +21,12 @@ import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.widget.RecyclerView; -import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.VisibleForTesting; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeBaseAppCompatActivity; import org.chromium.chrome.browser.ChromeFeatureList; @@ -90,17 +88,7 @@ // from Android notifications, when Android is restoring Preferences after Chrome was // killed, or for tests. This should happen before super.onCreate() because it might // recreate a fragment, and a fragment might depend on the native library. - try { - ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - // This can only ever happen, if at all, when the activity is started from an Android - // notification (or in tests). As such we don't want to show an error messsage to the - // user. The application is completely broken at this point, so close it down - // completely (not just the activity). - System.exit(-1); - return; - } + ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); super.onCreate(savedInstanceState);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/provider/ChromeBrowserProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/provider/ChromeBrowserProvider.java index 46db06c..a5f6470 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/provider/ChromeBrowserProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/provider/ChromeBrowserProvider.java
@@ -34,7 +34,6 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.IntentHandler; @@ -639,13 +638,7 @@ synchronized (mLoadNativeLock) { PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> { if (mNativeChromeBrowserProvider != 0) return; - try { - ChromeBrowserInitializer.getInstance(getContext()).handleSynchronousStartup(); - } catch (ProcessInitException e) { - // Chrome browser runs in the background, so exit silently; but do exit, - // since otherwise the next attempt to use Chrome will find a broken JNI. - System.exit(-1); - } + ChromeBrowserInitializer.getInstance(getContext()).handleSynchronousStartup(); ensureNativeSideInitialized(); }); } @@ -786,16 +779,13 @@ */ @VisibleForTesting public boolean equalContents(BookmarkNode node) { - return node != null - && mId == node.mId - && !(mName == null ^ node.mName == null) + return node != null && mId == node.mId && (mName == null) == (node.mName == null) && (mName == null || mName.equals(node.mName)) - && !(mUrl == null ^ node.mUrl == null) - && (mUrl == null || mUrl.equals(node.mUrl)) - && mType == node.mType + && (mUrl == null) == (node.mUrl == null) + && (mUrl == null || mUrl.equals(node.mUrl)) && mType == node.mType && byteArrayEqual(mFavicon, node.mFavicon) && byteArrayEqual(mThumbnail, node.mThumbnail) - && !(mParent == null ^ node.mParent == null) + && (mParent == null) == (node.mParent == null) && children().size() == node.children().size(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java index 52b98de..1a97fb2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java
@@ -10,11 +10,8 @@ import android.content.Intent; import org.chromium.base.ApplicationStatus; -import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.AsyncTask; import org.chromium.base.task.PostTask; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.init.EmptyBrowserParts; @@ -79,12 +76,7 @@ SigninHelper.markAccountsChangedPref(); } }; - try { - ChromeBrowserInitializer.getInstance(context).handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance(context).handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance(context).handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance(context).handlePostNativeStartup(true, parts); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/ChromeGcmListenerService.java b/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/ChromeGcmListenerService.java index bf356dd..67a8abf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/ChromeGcmListenerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/ChromeGcmListenerService.java
@@ -17,7 +17,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.chrome.browser.DeviceConditions; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; @@ -222,18 +221,8 @@ */ static void dispatchMessageToDriver(Context applicationContext, GCMMessage message) { ThreadUtils.assertOnUiThread(); - - try { - ChromeBrowserInitializer.getInstance(applicationContext).handleSynchronousStartup(); - GCMDriver.dispatchMessage(message); - - } catch (ProcessInitException e) { - Log.e(TAG, "ProcessInitException while starting the browser process"); - - // Since the library failed to initialize nothing in the application can work, so kill - // the whole application as opposed to just this service. - System.exit(-1); - } + ChromeBrowserInitializer.getInstance(applicationContext).handleSynchronousStartup(); + GCMDriver.dispatchMessage(message); } private static boolean isNativeLoaded() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java index 989f998b..b816693 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninActivity.java
@@ -12,10 +12,7 @@ import androidx.annotation.IntDef; -import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeBaseAppCompatActivity; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.preferences.ManagedPreferencesUtils; @@ -109,12 +106,7 @@ protected void onCreate(Bundle savedInstanceState) { // Make sure the native is initialized before calling super.onCreate(), as it might recreate // SigninFragment that currently depends on native. See https://crbug.com/983730. - try { - ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); super.onCreate(savedInstanceState); setContentView(R.layout.signin_activity);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/PassphraseActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/PassphraseActivity.java index f41d773..03b3b38 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/PassphraseActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/PassphraseActivity.java
@@ -12,11 +12,8 @@ import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; -import android.util.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.chrome.browser.sync.SyncController; @@ -41,13 +38,7 @@ // may be started explicitly from Android notifications. // During a normal user flow the ChromeTabbedActivity would start the Chrome browser // process and this wouldn't be necessary. - try { - ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to start browser process.", e); - ChromeApplication.reportStartupErrorAndExit(e); - return; - } + ChromeBrowserInitializer.getInstance(this).handleSynchronousStartup(); assert ProfileSyncService.get() != null; getSupportFragmentManager().addOnBackStackChangedListener(this); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java index 95ca1de..36c3a48 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/Tab.java
@@ -123,9 +123,6 @@ /** Gives {@link Tab} a way to interact with the Android window. */ private WindowAndroid mWindowAndroid; - /** Whether or not this {@link Tab} is initialized and should be interacted with. */ - private boolean mIsInitialized; - /** The current native page (e.g. chrome-native://newtab), or {@code null} if there is none. */ private NativePage mNativePage; @@ -1015,6 +1012,7 @@ // activity. maybeShowNativePage(getUrl(), true); + assert mNativeTabAndroid != 0; TabJni.get().attachDetachedTab(mNativeTabAndroid, Tab.this); if (getWebContents() != null) { @@ -1126,16 +1124,11 @@ } /** - * Builds the native counterpart to this class. Meant to be overridden by subclasses to build - * subclass native counterparts instead. Subclasses should not call this via super and instead - * rely on the native class to create the JNI association. - * - * TODO(dfalcantara): Make this function harder to access. + * Builds the native counterpart to this class. */ - public void initializeNative() { + private void initializeNative() { if (mNativeTabAndroid == 0) TabJni.get().init(Tab.this); assert mNativeTabAndroid != 0; - mIsInitialized = true; } /** @@ -1250,7 +1243,6 @@ * this method is called. Once this call is made this {@link Tab} should no longer be used. */ public void destroy() { - mIsInitialized = false; // Update the title before destroying the tab. http://b/5783092 updateTitle(); @@ -1270,9 +1262,10 @@ // InfoBarContainer. The native tab should be destroyed before the infobar container as // destroying the native tab cleanups up any remaining infobars. The infobar container // expects all infobars to be cleaned up before its own destruction. - assert mNativeTabAndroid != 0; - TabJni.get().destroy(mNativeTabAndroid, Tab.this); - assert mNativeTabAndroid == 0; + if (mNativeTabAndroid != 0) { + TabJni.get().destroy(mNativeTabAndroid, Tab.this); + assert mNativeTabAndroid == 0; + } } /** @@ -1280,7 +1273,7 @@ * {@link #initializeNative()} being called or after {@link #destroy()}. */ public boolean isInitialized() { - return mIsInitialized; + return mNativeTabAndroid != 0; } /** @@ -1659,6 +1652,7 @@ webContents.setSize(originalWidth, originalHeight); if (!bounds.isEmpty()) { + assert mNativeTabAndroid != 0; TabJni.get().onPhysicalBackingSizeChanged( mNativeTabAndroid, Tab.this, webContents, bounds.right, bounds.bottom); } @@ -1690,6 +1684,7 @@ @CalledByNative private void setNativePtr(long nativePtr) { + assert nativePtr != 0; assert mNativeTabAndroid == 0; mNativeTabAndroid = nativePtr; } @@ -1738,6 +1733,7 @@ */ public void createHistoricalTab() { if (!isFrozen()) { + assert mNativeTabAndroid != 0; TabJni.get().createHistoricalTab(mNativeTabAndroid, Tab.this); } else if (mFrozenContentsState != null) { mFrozenContentsState.createHistoricalTab(); @@ -1885,6 +1881,7 @@ * @return Whether input events from the renderer are ignored on the browser side. */ public boolean areRendererInputEventsIgnored() { + assert mNativeTabAndroid != 0; return TabJni.get().areRendererInputEventsIgnored(mNativeTabAndroid, Tab.this); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/RestoreHistogramTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/RestoreHistogramTest.java index 3a0bd05..ccdcb82 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/RestoreHistogramTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/RestoreHistogramTest.java
@@ -13,7 +13,6 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.MetricsUtils; @@ -33,7 +32,6 @@ * Test that the fundamental method for writing the histogram * {@link ChromeBackupAgent#recordRestoreHistogram()} works correctly * - * @throws ProcessInitException * @Note This can't be tested in the ChromeBackupAgent Junit test, since the histograms are * written in the C++ code, and because all the functions are static there is no easy way * of mocking them in Mockito (one can disable them, but that would spoil the point of the @@ -41,7 +39,7 @@ */ @Test @SmallTest - public void testHistogramWriter() throws ProcessInitException { + public void testHistogramWriter() { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); MetricsUtils.HistogramDelta noRestoreDelta = new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT, @@ -78,12 +76,11 @@ * Test that the histogram is written during Chrome first run. * * @throws InterruptedException - * @throws ProcessInitException */ @Test @DisabledTest(message = "Test is flaky. crbug.com/875372") @SmallTest - public void testWritingHistogramAtStartup() throws InterruptedException, ProcessInitException { + public void testWritingHistogramAtStartup() throws InterruptedException { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); MetricsUtils.HistogramDelta noRestoreDelta = new MetricsUtils.HistogramDelta(ChromeBackupAgent.HISTOGRAM_ANDROID_RESTORE_RESULT,
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundService.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundService.java index 0b540d9..b4f8ef3b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundService.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ServicificationBackgroundService.java
@@ -11,7 +11,6 @@ import org.junit.Assert; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.init.EmptyBrowserParts; @@ -55,12 +54,8 @@ } }; - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); } // Posts an assertion task to the UI thread. Since this is only called after the call
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/OriginVerifierTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/OriginVerifierTest.java index 02e5753e..01eb2c8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/OriginVerifierTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/OriginVerifierTest.java
@@ -7,6 +7,8 @@ import android.net.Uri; import android.support.test.filters.SmallTest; +import androidx.browser.customtabs.CustomTabsService; + import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -28,6 +30,7 @@ import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.UiThreadTaskTraits; +import org.chromium.content_public.browser.test.mock.MockWebContents; import org.chromium.content_public.browser.test.util.TestThreadUtils; import java.util.HashSet; @@ -36,8 +39,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import androidx.browser.customtabs.CustomTabsService; - /** Tests for OriginVerifier. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @@ -91,10 +92,10 @@ mHttpsOrigin = new Origin("https://www.example.com"); mHttpOrigin = new Origin("http://www.android.com"); - mHandleAllUrlsVerifier = - new OriginVerifier(PACKAGE_NAME, CustomTabsService.RELATION_HANDLE_ALL_URLS); - mUseAsOriginVerifier = - new OriginVerifier(PACKAGE_NAME, CustomTabsService.RELATION_USE_AS_ORIGIN); + mHandleAllUrlsVerifier = new OriginVerifier( + PACKAGE_NAME, CustomTabsService.RELATION_HANDLE_ALL_URLS, new MockWebContents()); + mUseAsOriginVerifier = new OriginVerifier( + PACKAGE_NAME, CustomTabsService.RELATION_USE_AS_ORIGIN, /* webContents= */ null); mVerificationResultSemaphore = new Semaphore(0); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityTest.java index 56b597dc..829e5e7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/TrustedWebActivityTest.java
@@ -29,7 +29,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.Restriction; @@ -66,7 +65,7 @@ private String mTestPage; @Before - public void setUp() throws InterruptedException, ProcessInitException { + public void setUp() throws InterruptedException { // Native needs to be initialized to start the test server. LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityPermissionsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityPermissionsTest.java index a4e691f..c76fb75 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityPermissionsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityPermissionsTest.java
@@ -20,7 +20,6 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeSwitches; @@ -53,7 +52,7 @@ private TrustedWebActivityPermissionManager mPermissionManager; @Before - public void setUp() throws InterruptedException, ProcessInitException, TimeoutException { + public void setUp() throws InterruptedException, TimeoutException { // Native needs to be initialized to start the test server. LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java index d132989..0a9ef748 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerTest.java
@@ -24,7 +24,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Restriction; @@ -507,12 +506,8 @@ public void setUp() throws Exception { // Load the browser process. TestThreadUtils.runOnUiThreadBlocking(() -> { - try { - ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) - .handleSynchronousStartup(); - } catch (ProcessInitException e) { - Assert.fail("Failed to load browser"); - } + ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) + .handleSynchronousStartup(); }); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/feed/FeedAppLifecycleTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/feed/FeedAppLifecycleTest.java index d04b275..138a71e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/feed/FeedAppLifecycleTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/feed/FeedAppLifecycleTest.java
@@ -19,7 +19,6 @@ import com.google.android.libraries.feed.hostimpl.storage.testing.InMemoryJournalStorage; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -29,7 +28,6 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.base.test.util.CallbackHelper; @@ -107,11 +105,7 @@ DeferredStartupHandler.setInstanceForTests(mTestDeferredStartupHandler); TestThreadUtils.runOnUiThreadBlocking(() -> { - try { - ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); - } catch (ProcessInitException e) { - Assert.fail("Native initialization failed"); - } + ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); Profile profile = Profile.getLastUsedProfile().getOriginalProfile(); mLifecycleBridge = new FeedLifecycleBridge(profile); mAppLifecycle =
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/DefaultSearchEnginePromoDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/DefaultSearchEnginePromoDialogTest.java index c7c0122b..e8911dd6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/DefaultSearchEnginePromoDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/DefaultSearchEnginePromoDialogTest.java
@@ -13,7 +13,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.ChromeSwitches; @@ -40,10 +39,10 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class DefaultSearchEnginePromoDialogTest { @Before - public void setUp() throws ExecutionException, ProcessInitException { + public void setUp() throws ExecutionException { TestThreadUtils.runOnUiThreadBlocking(new Callable<Void>() { @Override - public Void call() throws ProcessInitException { + public Void call() { ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) .handleSynchronousStartup();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerReferralTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerReferralTest.java index c8aaa3fd..d11a50d5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerReferralTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerReferralTest.java
@@ -16,7 +16,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.CallbackHelper; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; @@ -38,7 +37,7 @@ private String mYandexReferralId = ""; @Before - public void setUp() throws ExecutionException, ProcessInitException { + public void setUp() throws ExecutionException { mDefaultLocale = Locale.getDefault(); Locale.setDefault(new Locale("ru", "RU")); @@ -51,7 +50,7 @@ TestThreadUtils.runOnUiThreadBlocking(new Callable<Void>() { @Override - public Void call() throws ProcessInitException { + public Void call() { ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) .handleSynchronousStartup(); return null;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerTest.java index 09b949d..333b20d9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/locale/LocaleManagerTest.java
@@ -13,7 +13,6 @@ import org.junit.runner.RunWith; import org.chromium.base.Callback; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.ChromeSwitches; @@ -35,10 +34,10 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class LocaleManagerTest { @Before - public void setUp() throws ExecutionException, ProcessInitException { + public void setUp() throws ExecutionException { TestThreadUtils.runOnUiThreadBlocking(new Callable<Void>() { @Override - public Void call() throws ProcessInitException { + public Void call() { ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) .handleSynchronousStartup(); return null;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/BackgroundMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/BackgroundMetricsTest.java index 4b66eff7..1ee3e6a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/BackgroundMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/metrics/BackgroundMetricsTest.java
@@ -14,11 +14,9 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; @@ -64,12 +62,8 @@ } }; PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); }); CriteriaHelper.pollUiThread( () -> mNativeLoaded.get(), "Failed while waiting for starting native.");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/prefetch/TestOfflinePageService.java b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/prefetch/TestOfflinePageService.java index 186c826..655d3b6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/prefetch/TestOfflinePageService.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/prefetch/TestOfflinePageService.java
@@ -13,7 +13,6 @@ import org.junit.Assert; import org.chromium.base.Log; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CallbackHelper; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.components.gcm_driver.GCMDriver; @@ -286,12 +285,8 @@ extras.putString("subtype", prefetchSubtype); // is this necessary? GCMMessage message = new GCMMessage(senderId, extras); - try { - ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); - GCMDriver.dispatchMessage(message); - } catch (ProcessInitException e) { - Assert.fail(e.getMessage()); - } + ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); + GCMDriver.dispatchMessage(message); }); return operationName; }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogTest.java index 037bc96..b2cf64c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogTest.java
@@ -39,6 +39,7 @@ import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.modaldialog.DialogDismissalCause; +import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modelutil.PropertyModel; /** Test for the password manager illustration modal dialog. */ @@ -75,7 +76,8 @@ mModel = mMediator.getModelForTesting(); TestThreadUtils.runOnUiThreadBlocking(() -> { mCoordinator.showDialog(TITLE, DETAILS, R.drawable.data_reduction_illustration, - OK_BUTTON, CANCEL_BUTTON, mOnClick, false); + OK_BUTTON, CANCEL_BUTTON, mOnClick, false, + ModalDialogManager.ModalDialogType.TAB); }); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/PreferencesTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/PreferencesTest.java index dcffbd52..89a1bd20 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/PreferencesTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/preferences/PreferencesTest.java
@@ -25,7 +25,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.DisableIf; @@ -161,12 +160,8 @@ @Policies.Add({ @Policies.Item(key = "DefaultSearchProviderEnabled", string = "false") }) public void testSearchEnginePreference_DisabledIfNoDefaultSearchEngine() throws Exception { TestThreadUtils.runOnUiThreadBlocking(() -> { - try { - ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) - .handleSynchronousStartup(); - } catch (ProcessInitException e) { - Assert.fail("Unable to initialize process: " + e); - } + ChromeBrowserInitializer.getInstance(InstrumentationRegistry.getTargetContext()) + .handleSynchronousStartup(); }); ensureTemplateUrlServiceLoaded(); @@ -366,13 +361,8 @@ @SmallTest @Policies.Add({ @Policies.Item(key = "PasswordManagerEnabled", string = "false") }) public void testSavePasswordsPreferences_ManagedAndDisabled() throws ExecutionException { - TestThreadUtils.runOnUiThreadBlocking(() -> { - try { - ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); - } catch (ProcessInitException e) { - Assert.fail("Unable to initialize process: " + e); - } - }); + TestThreadUtils.runOnUiThreadBlocking( + () -> { ChromeBrowserInitializer.getInstance().handleSynchronousStartup(); }); CriteriaHelper.pollUiThread(new Criteria() { @Override
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/push_messaging/PushMessagingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/push_messaging/PushMessagingTest.java index 22fc131..4597d77b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/push_messaging/PushMessagingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/push_messaging/PushMessagingTest.java
@@ -20,7 +20,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisabledTest; @@ -321,12 +320,8 @@ extras.putString("subtype", appId); GCMMessage message = new GCMMessage(senderId, extras); - try { - ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); - GCMDriver.dispatchMessage(message); - } catch (ProcessInitException e) { - Assert.fail("Chrome browser failed to initialize."); - } + ChromeBrowserInitializer.getInstance(context).handleSynchronousStartup(); + GCMDriver.dispatchMessage(message); }); mMessageHandledHelper.waitForCallback(mMessageHandledHelper.getCallCount()); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabObserverTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabObserverTest.java index dcfdee6..68e633c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabObserverTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabModelSelectorTabObserverTest.java
@@ -135,14 +135,9 @@ } private Tab createTestTab(boolean incognito) { - return ThreadUtils.runOnUiThreadBlockingNoException(() -> { - Tab testTab = new TabBuilder() - .setIncognito(incognito) - .setWindow(mTestRule.getWindowAndroid()) - .build(); - testTab.initializeNative(); - return testTab; - }); + return ThreadUtils.runOnUiThreadBlockingNoException( + new TabBuilder().setIncognito(incognito).setWindow( + mTestRule.getWindowAndroid())::build); } private static void addTab(TabModel tabModel, Tab tab) {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java index 43b2658..b92668f 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java
@@ -40,7 +40,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ContextUtils; import org.chromium.base.PathUtils; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.firstrun.FirstRunSignInProcessor; import org.chromium.chrome.browser.firstrun.FirstRunStatus; @@ -133,12 +132,10 @@ /** * Test method for {@link ChromeBackupAgent#onBackup} testing first backup * - * @throws ProcessInitException */ @Test @SuppressWarnings("unchecked") - public void testOnBackup_firstBackup() throws FileNotFoundException, IOException, - ClassNotFoundException, ProcessInitException { + public void testOnBackup_firstBackup() throws IOException, ClassNotFoundException { // Mock the backup data. BackupDataOutput backupData = mock(BackupDataOutput.class); @@ -414,13 +411,9 @@ * Test method for {@link ChromeBackupAgent#onRestore}. * * @throws IOException - * @throws ClassNotFoundException - * @throws ProcessInitException - * @throws InterruptedException */ @Test - public void testOnRestore_normal() - throws IOException, ClassNotFoundException, ProcessInitException, InterruptedException { + public void testOnRestore_normal() throws IOException { // Create a state file. File stateFile = File.createTempFile("Test", ""); ParcelFileDescriptor newState = @@ -455,12 +448,9 @@ * device * * @throws IOException - * @throws ClassNotFoundException - * @throws ProcessInitException */ @Test - public void testOnRestore_badUser() - throws IOException, ClassNotFoundException, ProcessInitException { + public void testOnRestore_badUser() throws IOException { // Create a state file. File stateFile = File.createTempFile("Test", ""); ParcelFileDescriptor newState = @@ -492,12 +482,9 @@ * Test method for {@link ChromeBackupAgent#onRestore} for browser startup failure * * @throws IOException - * @throws ClassNotFoundException - * @throws ProcessInitException */ @Test - public void testOnRestore_browserStartupFails() - throws IOException, ClassNotFoundException, ProcessInitException { + public void testOnRestore_browserStartupFails() throws IOException { // Create a state file. File stateFile = File.createTempFile("Test", ""); ParcelFileDescriptor newState = @@ -525,12 +512,9 @@ * Test method for {@link ChromeBackupAgent#onRestore} for browser startup failure * * @throws IOException - * @throws ClassNotFoundException - * @throws ProcessInitException */ @Test - public void testOnRestore_afterFirstRun() - throws IOException, ClassNotFoundException, ProcessInitException { + public void testOnRestore_afterFirstRun() throws IOException { // Create a state file. File stateFile = File.createTempFile("Test", ""); ParcelFileDescriptor newState =
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTaskTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTaskTest.java index a34c7dcc..8bd91bc 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTaskTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/background_task_scheduler/NativeBackgroundTaskTest.java
@@ -67,11 +67,10 @@ @Override public void startBrowserProcessesAsync(boolean startGpuProcess, - boolean startServiceManagerOnly, final StartupCallback callback) - throws ProcessInitException {} + boolean startServiceManagerOnly, final StartupCallback callback) {} @Override - public void startBrowserProcessesSync(boolean singleProcess) throws ProcessInitException {} + public void startBrowserProcessesSync(boolean singleProcess) {} @Override public boolean isFullBrowserStarted() { @@ -238,53 +237,45 @@ private void setUpChromeBrowserInitializer(InitializerSetup setup) { doNothing().when(mChromeBrowserInitializer).handlePreNativeStartup(any(BrowserParts.class)); - try { - switch (setup) { - case SUCCESS: - doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) { - mBrowserParts.getValue().finishNativeInitialization(); - return null; - } - }) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), mBrowserParts.capture()); - break; - case FAILURE: - doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) { - mBrowserParts.getValue().onStartupFailure(); - return null; - } - }) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), mBrowserParts.capture()); - break; - case EXCEPTION: - doThrow(new ProcessInitException( - LoaderErrors.LOADER_ERROR_NATIVE_LIBRARY_LOAD_FAILED)) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), any(BrowserParts.class)); - break; - default: - assert false; - } - } catch (ProcessInitException e) { - // Exception ignored, as try-catch is required by language. + switch (setup) { + case SUCCESS: + doAnswer(new Answer<Void>() { + @Override + public Void answer(InvocationOnMock invocation) { + mBrowserParts.getValue().finishNativeInitialization(); + return null; + } + }) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), mBrowserParts.capture()); + break; + case FAILURE: + doAnswer(new Answer<Void>() { + @Override + public Void answer(InvocationOnMock invocation) { + mBrowserParts.getValue().onStartupFailure(); + return null; + } + }) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), mBrowserParts.capture()); + break; + case EXCEPTION: + doThrow(new ProcessInitException( + LoaderErrors.LOADER_ERROR_NATIVE_LIBRARY_LOAD_FAILED)) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), any(BrowserParts.class)); + break; + default: + assert false; } } private void verifyStartupCalls(int expectedPreNativeCalls, int expectedPostNativeCalls) { - try { - verify(mChromeBrowserInitializer, times(expectedPreNativeCalls)) - .handlePreNativeStartup(any(BrowserParts.class)); - verify(mChromeBrowserInitializer, times(expectedPostNativeCalls)) - .handlePostNativeStartup(eq(true), any(BrowserParts.class)); - } catch (ProcessInitException e) { - // Exception ignored, as try-catch is required by language. - } + verify(mChromeBrowserInitializer, times(expectedPreNativeCalls)) + .handlePreNativeStartup(any(BrowserParts.class)); + verify(mChromeBrowserInitializer, times(expectedPostNativeCalls)) + .handlePostNativeStartup(eq(true), any(BrowserParts.class)); } private static boolean waitOnLatch(CountDownLatch latch) {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifierTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifierTest.java index f4f486ca..af6e6476 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifierTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifierTest.java
@@ -93,7 +93,8 @@ public void setUp() { MockitoAnnotations.initMocks(this); when(mCustomTabsConnection.getClientPackageNameForSession(any())).thenReturn(PACKAGE_NAME); - when(mOriginVerifierFactory.create(any(), anyInt())).thenReturn(mOriginVerifier.mock); + when(mOriginVerifierFactory.create(any(), anyInt(), any())) + .thenReturn(mOriginVerifier.mock); when(mTabProvider.getTab()).thenReturn(mTab); when(mIntentDataProvider.getTrustedWebActivityAdditionalOrigins()).thenReturn( Arrays.asList("https://www.origin2.com/"));
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java index 038e68fe..8ea08f0 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java
@@ -32,7 +32,6 @@ import org.robolectric.shadows.multidex.ShadowMultiDex; import org.chromium.base.Callback; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.DeviceConditions; @@ -139,16 +138,12 @@ ShadowRecordHistogram.reset(); MockitoAnnotations.initMocks(this); doNothing().when(mChromeBrowserInitializer).handlePreNativeStartup(any(BrowserParts.class)); - try { - doAnswer((InvocationOnMock invocation) -> { - mBrowserParts.getValue().finishNativeInitialization(); - return null; - }) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), mBrowserParts.capture()); - } catch (ProcessInitException ex) { - fail("Unexpected exception while initializing mock of ChromeBrowserInitializer."); - } + doAnswer((InvocationOnMock invocation) -> { + mBrowserParts.getValue().finishNativeInitialization(); + return null; + }) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), mBrowserParts.capture()); ChromeBrowserInitializer.setForTesting(mChromeBrowserInitializer);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java index 3a49d04b..0b211f8 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java
@@ -32,7 +32,6 @@ import org.chromium.components.variations.firstrun.VariationsSeedFetcher; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; @@ -50,7 +49,7 @@ private VariationsSeedFetcher mVariationsSeedFetcher; - public AsyncInitTaskRunnerTest() throws ProcessInitException { + public AsyncInitTaskRunnerTest() { mLoader = spy(LibraryLoader.getInstance()); doNothing().when(mLoader).ensureInitialized(anyInt()); LibraryLoader.setLibraryLoaderForTesting(mLoader); @@ -84,8 +83,7 @@ } @Test - public void libraryLoaderOnlyTest() - throws InterruptedException, ProcessInitException, ExecutionException { + public void libraryLoaderOnlyTest() throws InterruptedException { mRunner.startBackgroundTasks(false, false); Robolectric.flushBackgroundThreadScheduler(); @@ -97,7 +95,7 @@ } @Test - public void libraryLoaderFailTest() throws InterruptedException, ProcessInitException { + public void libraryLoaderFailTest() throws InterruptedException { doThrow(new ProcessInitException(LoaderErrors.LOADER_ERROR_NATIVE_LIBRARY_LOAD_FAILED)) .when(mLoader) .ensureInitialized(LibraryProcessType.PROCESS_BROWSER); @@ -111,7 +109,7 @@ } @Test - public void fetchVariationsTest() throws InterruptedException, ProcessInitException { + public void fetchVariationsTest() throws InterruptedException { mRunner.startBackgroundTasks(false, true); Robolectric.flushBackgroundThreadScheduler();
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/OfflineNotificationBackgroundTaskUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/OfflineNotificationBackgroundTaskUnitTest.java index 1200d27e..947724b3 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/OfflineNotificationBackgroundTaskUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/OfflineNotificationBackgroundTaskUnitTest.java
@@ -9,7 +9,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; @@ -42,7 +41,6 @@ import org.robolectric.shadows.multidex.ShadowMultiDex; import org.chromium.base.Callback; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.DeviceConditions; import org.chromium.chrome.browser.ShadowDeviceConditions; @@ -120,19 +118,15 @@ MockitoAnnotations.initMocks(this); // Set up the context. doNothing().when(mChromeBrowserInitializer).handlePreNativeStartup(any(BrowserParts.class)); - try { - doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) { - mBrowserParts.getValue().finishNativeInitialization(); - return null; - } - }) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), mBrowserParts.capture()); - } catch (ProcessInitException ex) { - fail("Unexpected exception while initializing mock of ChromeBrowserInitializer."); - } + doAnswer(new Answer<Void>() { + @Override + public Void answer(InvocationOnMock invocation) { + mBrowserParts.getValue().finishNativeInitialization(); + return null; + } + }) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), mBrowserParts.capture()); doAnswer((invocation) -> { Object callback = invocation.getArguments()[1];
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchBackgroundTaskUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchBackgroundTaskUnitTest.java index 55b46d6..da702486 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchBackgroundTaskUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchBackgroundTaskUnitTest.java
@@ -32,7 +32,6 @@ import org.robolectric.annotation.Config; import org.robolectric.shadows.multidex.ShadowMultiDex; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.DeviceConditions; @@ -111,19 +110,15 @@ MockitoAnnotations.initMocks(this); mocker.mock(PrefetchBackgroundTaskJni.TEST_HOOKS, mPrefetchBackgroundTaskJniMock); doNothing().when(mChromeBrowserInitializer).handlePreNativeStartup(any(BrowserParts.class)); - try { - doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) { - mBrowserParts.getValue().finishNativeInitialization(); - return null; - } - }) - .when(mChromeBrowserInitializer) - .handlePostNativeStartup(eq(true), mBrowserParts.capture()); - } catch (ProcessInitException ex) { - fail("Unexpected exception while initializing mock of ChromeBrowserInitializer."); - } + doAnswer(new Answer<Void>() { + @Override + public Void answer(InvocationOnMock invocation) { + mBrowserParts.getValue().finishNativeInitialization(); + return null; + } + }) + .when(mChromeBrowserInitializer) + .handlePostNativeStartup(eq(true), mBrowserParts.capture()); ChromeBrowserInitializer.setForTesting(mChromeBrowserInitializer);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/GeolocationHeaderUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/GeolocationHeaderUnitTest.java index cc66192..2c3e17c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/GeolocationHeaderUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/GeolocationHeaderUnitTest.java
@@ -27,7 +27,6 @@ import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordHistogramJni; import org.chromium.base.test.BaseRobolectricTestRunner; @@ -222,7 +221,7 @@ } @Test - public void testGetGeoHeaderOldLocationHighAccuracy() throws ProcessInitException { + public void testGetGeoHeaderOldLocationHighAccuracy() { GeolocationHeader.setLocationSourceForTesting( GeolocationHeader.LocationSource.HIGH_ACCURACY); // Visible networks should be included @@ -231,7 +230,7 @@ } @Test - public void testGetGeoHeaderOldLocationBatterySaving() throws ProcessInitException { + public void testGetGeoHeaderOldLocationBatterySaving() { GeolocationHeader.setLocationSourceForTesting( GeolocationHeader.LocationSource.BATTERY_SAVING); checkOldLocation( @@ -239,21 +238,21 @@ } @Test - public void testGetGeoHeaderOldLocationGpsOnly() throws ProcessInitException { + public void testGetGeoHeaderOldLocationGpsOnly() { GeolocationHeader.setLocationSourceForTesting(GeolocationHeader.LocationSource.GPS_ONLY); // In GPS only mode, networks should never be included. checkOldLocation("X-Geo: w " + ENCODED_PROTO_LOCATION); } @Test - public void testGetGeoHeaderOldLocationLocationOff() throws ProcessInitException { + public void testGetGeoHeaderOldLocationLocationOff() { GeolocationHeader.setLocationSourceForTesting(GeolocationHeader.LocationSource.MASTER_OFF); // If the master switch is off, networks should never be included (old location might). checkOldLocation("X-Geo: w " + ENCODED_PROTO_LOCATION); } @Test - public void testGetGeoHeaderOldLocationAppPermissionDenied() throws ProcessInitException { + public void testGetGeoHeaderOldLocationAppPermissionDenied() { GeolocationHeader.setLocationSourceForTesting( GeolocationHeader.LocationSource.HIGH_ACCURACY); GeolocationHeader.setAppPermissionGrantedForTesting(false);
diff --git a/chrome/android/monochrome/java/src/com/android/webview/chromium/LicenseContentProvider.java b/chrome/android/monochrome/java/src/com/android/webview/chromium/LicenseContentProvider.java index bb90d43..20b0ae2 100644 --- a/chrome/android/monochrome/java/src/com/android/webview/chromium/LicenseContentProvider.java +++ b/chrome/android/monochrome/java/src/com/android/webview/chromium/LicenseContentProvider.java
@@ -14,7 +14,6 @@ import android.os.ParcelFileDescriptor; import org.chromium.base.ThreadUtils; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.components.aboutui.CreditUtilsJni; @@ -48,11 +47,7 @@ ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { - try { - ChromeBrowserInitializer.getInstance(getContext()).handleSynchronousStartup(); - } catch (ProcessInitException e) { - throw new RuntimeException(e); - } + ChromeBrowserInitializer.getInstance(getContext()).handleSynchronousStartup(); } }); CreditUtilsJni.get().writeCreditsHtml(output.detachFd());
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index e3620a1..7630cbc2 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -953,34 +953,26 @@ return; } - const DetailsProto& proto = details->details_proto(); - const DetailsChangesProto& changes = details->changes(); - auto jdetails = Java_AssistantDetails_create( - env, base::android::ConvertUTF8ToJavaString(env, proto.title()), - base::android::ConvertUTF8ToJavaString(env, proto.image_url()), - proto.image_clickthrough_data().allow_clickthrough(), - base::android::ConvertUTF8ToJavaString( - env, proto.image_clickthrough_data().description()), - base::android::ConvertUTF8ToJavaString( - env, proto.image_clickthrough_data().positive_text()), - base::android::ConvertUTF8ToJavaString( - env, proto.image_clickthrough_data().negative_text()), - base::android::ConvertUTF8ToJavaString( - env, proto.image_clickthrough_data().clickthrough_url()), - proto.show_image_placeholder(), - base::android::ConvertUTF8ToJavaString(env, proto.total_price_label()), - base::android::ConvertUTF8ToJavaString(env, proto.total_price()), - base::android::ConvertUTF8ToJavaString(env, details->datetime()), - proto.datetime().date().year(), proto.datetime().date().month(), - proto.datetime().date().day(), proto.datetime().time().hour(), - proto.datetime().time().minute(), proto.datetime().time().second(), - base::android::ConvertUTF8ToJavaString(env, proto.description_line_1()), - base::android::ConvertUTF8ToJavaString(env, proto.description_line_2()), - base::android::ConvertUTF8ToJavaString(env, proto.description_line_3()), - changes.user_approval_required(), changes.highlight_title(), - changes.highlight_line1(), changes.highlight_line2(), - changes.highlight_line3(), proto.animate_placeholders()); + env, base::android::ConvertUTF8ToJavaString(env, details->title()), + details->titleMaxLines(), + base::android::ConvertUTF8ToJavaString(env, details->imageUrl()), + details->imageAllowClickthrough(), + base::android::ConvertUTF8ToJavaString(env, details->imageDescription()), + base::android::ConvertUTF8ToJavaString(env, details->imagePositiveText()), + base::android::ConvertUTF8ToJavaString(env, details->imageNegativeText()), + base::android::ConvertUTF8ToJavaString(env, + details->imageClickthroughUrl()), + details->showImagePlaceholder(), + base::android::ConvertUTF8ToJavaString(env, details->totalPriceLabel()), + base::android::ConvertUTF8ToJavaString(env, details->totalPrice()), + base::android::ConvertUTF8ToJavaString(env, details->descriptionLine1()), + base::android::ConvertUTF8ToJavaString(env, details->descriptionLine2()), + base::android::ConvertUTF8ToJavaString(env, details->descriptionLine3()), + base::android::ConvertUTF8ToJavaString(env, details->priceAttribution()), + details->userApprovalRequired(), details->highlightTitle(), + details->highlightLine1(), details->highlightLine2(), + details->highlightLine3(), details->animatePlaceholders()); Java_AssistantDetailsModel_setDetails(env, jmodel, jdetails); }
diff --git a/chrome/browser/android/customtabs/OWNERS b/chrome/browser/android/customtabs/OWNERS index ea261d0d..a7280b9 100644 --- a/chrome/browser/android/customtabs/OWNERS +++ b/chrome/browser/android/customtabs/OWNERS
@@ -1,2 +1,3 @@ -yusufo@chromium.org lizeb@chromium.org +peconn@chromium.org +yusufo@chromium.org
diff --git a/chrome/browser/android/customtabs/origin_verifier.cc b/chrome/browser/android/customtabs/origin_verifier.cc index 73c8082..687c1e20 100644 --- a/chrome/browser/android/customtabs/origin_verifier.cc +++ b/chrome/browser/android/customtabs/origin_verifier.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" #include "services/network/public/cpp/simple_url_loader.h" using base::android::ConvertJavaStringToUTF16; @@ -30,12 +31,14 @@ OriginVerifier::OriginVerifier(JNIEnv* env, const JavaRef<jobject>& obj, + const JavaRef<jobject>& jweb_contents, const JavaRef<jobject>& jprofile) { jobject_.Reset(obj); Profile* profile = ProfileAndroid::FromProfileAndroid(jprofile); DCHECK(profile); asset_link_handler_ = std::make_unique<digital_asset_links::DigitalAssetLinksHandler>( + content::WebContents::FromJavaWebContents(jweb_contents), content::BrowserContext::GetDefaultStoragePartition(profile) ->GetURLLoaderFactoryForBrowserProcess()); } @@ -98,11 +101,13 @@ static jlong JNI_OriginVerifier_Init( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& jweb_contents, const base::android::JavaParamRef<jobject>& jprofile) { if (!g_browser_process) return 0; - OriginVerifier* native_verifier = new OriginVerifier(env, obj, jprofile); + OriginVerifier* native_verifier = + new OriginVerifier(env, obj, jweb_contents, jprofile); return reinterpret_cast<intptr_t>(native_verifier); }
diff --git a/chrome/browser/android/customtabs/origin_verifier.h b/chrome/browser/android/customtabs/origin_verifier.h index d3fe2509..4b83ed5 100644 --- a/chrome/browser/android/customtabs/origin_verifier.h +++ b/chrome/browser/android/customtabs/origin_verifier.h
@@ -13,7 +13,7 @@ namespace digital_asset_links { enum class RelationshipCheckResult; class DigitalAssetLinksHandler; -} +} // namespace digital_asset_links namespace customtabs { @@ -22,6 +22,7 @@ public: OriginVerifier(JNIEnv* env, const base::android::JavaRef<jobject>& obj, + const base::android::JavaRef<jobject>& jweb_contents, const base::android::JavaRef<jobject>& jprofile); ~OriginVerifier();
diff --git a/chrome/browser/android/digital_asset_links/DEPS b/chrome/browser/android/digital_asset_links/DEPS index 9eb012c..2cd319b 100644 --- a/chrome/browser/android/digital_asset_links/DEPS +++ b/chrome/browser/android/digital_asset_links/DEPS
@@ -3,7 +3,7 @@ include_rules = [ "-chrome", "-content", - "+content/public/test", + "+content/public", "+chrome/browser/android/digital_asset_links", "+net", ]
diff --git a/chrome/browser/android/digital_asset_links/digital_asset_links_handler.cc b/chrome/browser/android/digital_asset_links/digital_asset_links_handler.cc index cac07e53..63c12ff 100644 --- a/chrome/browser/android/digital_asset_links/digital_asset_links_handler.cc +++ b/chrome/browser/android/digital_asset_links/digital_asset_links_handler.cc
@@ -12,6 +12,7 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/values.h" +#include "content/public/browser/web_contents.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_response_headers.h" @@ -102,6 +103,19 @@ return false; } +// Shows a warning message in the DevTools console. +void AddMessageToConsole(content::WebContents* web_contents, + const std::string& message) { + if (web_contents) { + web_contents->GetMainFrame()->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, message); + return; + } + + // Fallback to LOG. + LOG(WARNING) << message; +} + } // namespace namespace digital_asset_links { @@ -109,8 +123,10 @@ const char kDigitalAssetLinksCheckResponseKeyLinked[] = "linked"; DigitalAssetLinksHandler::DigitalAssetLinksHandler( + content::WebContents* web_contents, scoped_refptr<network::SharedURLLoaderFactory> factory) - : shared_url_loader_factory_(std::move(factory)) {} + : content::WebContentsObserver(web_contents), + shared_url_loader_factory_(std::move(factory)) {} DigitalAssetLinksHandler::~DigitalAssetLinksHandler() = default; @@ -127,13 +143,17 @@ int net_error = url_loader_->NetError(); if (net_error == net::ERR_INTERNET_DISCONNECTED || net_error == net::ERR_NAME_NOT_RESOLVED) { - LOG(WARNING) << "Digital Asset Links connection failed."; + AddMessageToConsole(web_contents(), + "Digital Asset Links connection failed."); std::move(callback_).Run(RelationshipCheckResult::NO_CONNECTION); return; } - LOG(WARNING) << base::StringPrintf( - "Digital Asset Links endpoint responded with code %d.", response_code); + AddMessageToConsole( + web_contents(), + base::StringPrintf( + "Digital Asset Links endpoint responded with code %d.", + response_code)); std::move(callback_).Run(RelationshipCheckResult::FAILURE); return; } @@ -157,7 +177,7 @@ base::Value statement_list) { if (!statement_list.is_list()) { std::move(callback_).Run(RelationshipCheckResult::FAILURE); - LOG(WARNING) << "Statement List is not a list."; + AddMessageToConsole(web_contents(), "Statement List is not a list."); return; } @@ -190,17 +210,17 @@ } for (const auto& failure_reason : failures) - LOG(WARNING) << failure_reason; + AddMessageToConsole(web_contents(), failure_reason); std::move(callback_).Run(RelationshipCheckResult::FAILURE); } void DigitalAssetLinksHandler::OnJSONParseFailed( const std::string& error_message) { - LOG(WARNING) - << base::StringPrintf( - "Digital Asset Links response parsing failed with message:") - << error_message; + AddMessageToConsole( + web_contents(), + "Digital Asset Links response parsing failed with message: " + + error_message); std::move(callback_).Run(RelationshipCheckResult::FAILURE); }
diff --git a/chrome/browser/android/digital_asset_links/digital_asset_links_handler.h b/chrome/browser/android/digital_asset_links/digital_asset_links_handler.h index 66533fd..e8d2df8 100644 --- a/chrome/browser/android/digital_asset_links/digital_asset_links_handler.h +++ b/chrome/browser/android/digital_asset_links/digital_asset_links_handler.h
@@ -8,6 +8,7 @@ #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "base/values.h" +#include "content/public/browser/web_contents_observer.h" namespace network { class SharedURLLoaderFactory; @@ -34,11 +35,13 @@ // for details of usage and APIs. These APIs are used to verify declared // relationships between different asset types like web domains or Android apps. // The lifecycle of this handler will be governed by the owner. -class DigitalAssetLinksHandler { +// The WebContents are used for logging console messages. +class DigitalAssetLinksHandler : public content::WebContentsObserver { public: - explicit DigitalAssetLinksHandler( + DigitalAssetLinksHandler( + content::WebContents* web_contents, scoped_refptr<network::SharedURLLoaderFactory> factory); - ~DigitalAssetLinksHandler(); + ~DigitalAssetLinksHandler() override; // Checks whether the given "relationship" has been declared by the target // |web_domain| for the source Android app which is uniquely defined by the
diff --git a/chrome/browser/android/digital_asset_links/digital_asset_links_handler_unittest.cc b/chrome/browser/android/digital_asset_links/digital_asset_links_handler_unittest.cc index 050cf1a..0b527fb 100644 --- a/chrome/browser/android/digital_asset_links/digital_asset_links_handler_unittest.cc +++ b/chrome/browser/android/digital_asset_links/digital_asset_links_handler_unittest.cc
@@ -121,7 +121,8 @@ } // namespace TEST_F(DigitalAssetLinksHandlerTest, CorrectAssetLinksUrl) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -133,7 +134,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, PositiveResponse) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -145,7 +147,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, PackageMismatch) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -157,7 +160,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, SignatureMismatch) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -169,7 +173,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, RelationshipMismatch) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -182,7 +187,8 @@ TEST_F(DigitalAssetLinksHandlerTest, StatementIsolation) { // Ensure we don't merge separate statements together. - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -194,7 +200,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, BadAssetLinks_Empty) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -206,7 +213,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, BadAssetLinks_NotList) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -218,7 +226,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, BadAssetLinks_StatementNotDict) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -230,7 +239,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, BadAssetLinks_MissingFields) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -242,7 +252,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, BadRequest) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -254,7 +265,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, NetworkError) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)), @@ -266,7 +278,8 @@ } TEST_F(DigitalAssetLinksHandlerTest, NetworkDisconnected) { - DigitalAssetLinksHandler handler(GetSharedURLLoaderFactory()); + DigitalAssetLinksHandler handler(/* web_contents= */ nullptr, + GetSharedURLLoaderFactory()); handler.CheckDigitalAssetLinkRelationship( base::BindOnce(&DigitalAssetLinksHandlerTest::OnRelationshipCheckComplete, base::Unretained(this)),
diff --git a/chrome/browser/badging/badge_manager.cc b/chrome/browser/badging/badge_manager.cc index be2da584..682cccc8 100644 --- a/chrome/browser/badging/badge_manager.cc +++ b/chrome/browser/badging/badge_manager.cc
@@ -99,8 +99,7 @@ delegate_->OnBadgeUpdated(scope); } -void BadgeManager::SetBadge(const GURL& /*scope*/, - blink::mojom::BadgeValuePtr mojo_value) { +void BadgeManager::SetBadge(blink::mojom::BadgeValuePtr mojo_value) { if (mojo_value->is_number() && mojo_value->get_number() == 0) { mojo::ReportBadMessage( "|value| should not be zero when it is |number| (ClearBadge should be " @@ -120,7 +119,7 @@ UpdateBadge(app_scope.value(), base::make_optional(value)); } -void BadgeManager::ClearBadge(const GURL& /*scope*/) { +void BadgeManager::ClearBadge() { const base::Optional<GURL> app_scope = GetAppScopeForContext(receivers_.current_context()); if (!app_scope)
diff --git a/chrome/browser/badging/badge_manager.h b/chrome/browser/badging/badge_manager.h index cd04096..5f5833f3 100644 --- a/chrome/browser/badging/badge_manager.h +++ b/chrome/browser/badging/badge_manager.h
@@ -75,11 +75,8 @@ // blink::mojom::BadgeService: // Note: These are private to stop them being called outside of mojo as they // require a mojo binding context. - // TODO(crbug.com/1006665): Remove scope from the mojo interface in SetBadge - // and ClearBadge. - void SetBadge(const GURL& /*scope*/, - blink::mojom::BadgeValuePtr value) override; - void ClearBadge(const GURL& /*scope*/) override; + void SetBadge(blink::mojom::BadgeValuePtr value) override; + void ClearBadge() override; // Finds the scope URL of the most specific badge for |scope|. Returns // GURL::EmptyGURL() if no match is found.
diff --git a/chrome/browser/chrome_browser_interface_binders.cc b/chrome/browser/chrome_browser_interface_binders.cc index 07757ee..7c59f51 100644 --- a/chrome/browser/chrome_browser_interface_binders.cc +++ b/chrome/browser/chrome_browser_interface_binders.cc
@@ -4,16 +4,19 @@ #include "chrome/browser/chrome_browser_interface_binders.h" +#include "base/feature_list.h" #include "build/build_config.h" #include "chrome/browser/navigation_predictor/navigation_predictor.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" +#include "content/public/common/content_features.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/image_annotation/public/mojom/constants.mojom-forward.h" #include "services/image_annotation/public/mojom/image_annotation.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "third_party/blink/public/mojom/loader/navigation_predictor.mojom.h" +#include "third_party/blink/public/mojom/payments/payment_request.mojom.h" #if defined(OS_ANDROID) #include "content/public/browser/web_contents.h" @@ -28,6 +31,7 @@ #endif #else #include "chrome/browser/badging/badge_manager.h" +#include "chrome/browser/payments/payment_request_factory.h" #endif namespace chrome { @@ -75,6 +79,10 @@ map->Add<blink::mojom::MediaControlsMenuHost>(base::BindRepeating( &ForwardToJavaFrameRegistry<blink::mojom::MediaControlsMenuHost>)); #endif + if (base::FeatureList::IsEnabled(features::kWebPayments)) { + map->Add<payments::mojom::PaymentRequest>(base::BindRepeating( + &ForwardToJavaFrameRegistry<payments::mojom::PaymentRequest>)); + } map->Add<blink::mojom::ShareService>(base::BindRepeating( &ForwardToJavaWebContents<blink::mojom::ShareService>)); #if defined(ENABLE_SPATIAL_NAVIGATION_HOST) @@ -84,6 +92,10 @@ #else map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindReceiver)); + if (base::FeatureList::IsEnabled(features::kWebPayments)) { + map->Add<payments::mojom::PaymentRequest>( + base::BindRepeating(&payments::CreatePaymentRequest)); + } #endif }
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 49443d7..9e64786 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -422,7 +422,6 @@ #include "components/navigation_interception/intercept_navigation_delegate.h" #include "content/public/browser/android/java_interfaces.h" #include "services/service_manager/public/cpp/interface_provider.h" -#include "third_party/blink/public/mojom/payments/payment_request.mojom.h" #include "third_party/blink/public/mojom/webauthn/authenticator.mojom.h" #include "ui/base/resource/resource_bundle_android.h" #include "ui/base/ui_base_paths.h" @@ -438,7 +437,6 @@ #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/media/unified_autoplay_config.h" -#include "chrome/browser/payments/payment_request_factory.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/browser/serial/chrome_serial_delegate.h" @@ -4399,14 +4397,7 @@ #if defined(OS_ANDROID) frame_interfaces_parameterized_->AddInterface( - base::Bind(&ForwardToJavaFrameRegistry<payments::mojom::PaymentRequest>)); - frame_interfaces_parameterized_->AddInterface( base::Bind(&ForwardToJavaFrameRegistry<blink::mojom::Authenticator>)); -#else - if (base::FeatureList::IsEnabled(features::kWebPayments)) { - frame_interfaces_parameterized_->AddInterface( - base::Bind(&payments::CreatePaymentRequest)); - } #endif #if defined(OS_ANDROID)
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index 1cd98d5..45a4d4e 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -1658,13 +1658,15 @@ DVLOG(1) << "AutotestPrivateBootstrapMachineLearningServiceFunction"; // Load a model. This will first bootstrap the Mojo connection to ML Service. - chromeos::machine_learning::ServiceConnection::GetInstance()->LoadModel( - chromeos::machine_learning::mojom::ModelSpec::New( - chromeos::machine_learning::mojom::ModelId::TEST_MODEL), - mojo::MakeRequest(&model_), - base::BindOnce( - &AutotestPrivateBootstrapMachineLearningServiceFunction::ModelLoaded, - this)); + chromeos::machine_learning::ServiceConnection::GetInstance() + ->LoadBuiltinModel( + chromeos::machine_learning::mojom::BuiltinModelSpec::New( + chromeos::machine_learning::mojom::BuiltinModelId::TEST_MODEL), + mojo::MakeRequest(&model_), + base::BindOnce( + &AutotestPrivateBootstrapMachineLearningServiceFunction:: + ModelLoaded, + this)); model_.set_connection_error_handler(base::BindOnce( &AutotestPrivateBootstrapMachineLearningServiceFunction::ConnectionError, this));
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/login_api.h b/chrome/browser/chromeos/extensions/login_screen/login/login_api.h index f33a4563..522ab97 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login/login_api.h +++ b/chrome/browser/chromeos/extensions/login_screen/login/login_api.h
@@ -15,7 +15,7 @@ void RegisterLocalStatePrefs(PrefRegistrySimple* registry); -} +} // namespace login_api class LoginLaunchManagedGuestSessionFunction : public ExtensionFunction { public:
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc b/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc new file mode 100644 index 0000000..814a1695 --- /dev/null +++ b/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc
@@ -0,0 +1,115 @@ +// 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/extensions/login_screen/login/login_api.h" + +#include <memory> +#include <string> + +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.h" +#include "chrome/browser/chromeos/login/test/local_policy_test_server_mixin.h" +#include "chrome/common/pref_names.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/proto/chrome_device_policy.pb.h" +#include "components/prefs/pref_service.h" +#include "components/session_manager/core/session_manager.h" +#include "components/user_manager/user_type.h" +#include "components/version_info/version_info.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_service.h" +#include "content/public/test/test_utils.h" +#include "extensions/browser/api/test/test_api.h" +#include "extensions/test/extension_test_message_listener.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +constexpr char kAccountId[] = "public-session@test"; +constexpr char kData[] = "some data"; +constexpr char kLaunchManagedGuestSession[] = "LoginLaunchManagedGuestSession"; +constexpr char kLaunchManagedGuestSessionNoAccounts[] = + "LoginLaunchManagedGuestSessionNoAccounts"; +constexpr char kExitCurrentSession[] = "LoginExitCurrentSession"; +constexpr char kFetchDataForNextLoginAttempt[] = + "LoginFetchDataForNextLoginAttempt"; + +} // namespace + +namespace chromeos { + +class LoginApitest : public LoginScreenApitestBase { + public: + LoginApitest() : LoginScreenApitestBase(version_info::Channel::STABLE) {} + ~LoginApitest() override = default; + + void SetUpDeviceLocalAccountPolicy() { + enterprise_management::DeviceLocalAccountsProto* const + device_local_accounts = + device_policy()->payload().mutable_device_local_accounts(); + enterprise_management::DeviceLocalAccountInfoProto* const account = + device_local_accounts->add_account(); + account->set_account_id(kAccountId); + account->set_type(enterprise_management::DeviceLocalAccountInfoProto:: + ACCOUNT_TYPE_PUBLIC_SESSION); + RefreshDevicePolicy(); + } + + void SetTestCustomArg(const std::string custom_arg) { + config_.SetKey("customArg", base::Value(custom_arg)); + extensions::TestGetConfigFunction::set_test_config_state(&config_); + } + + private: + chromeos::LocalPolicyTestServerMixin local_policy_mixin_{&mixin_host_}; + base::DictionaryValue config_; + + DISALLOW_COPY_AND_ASSIGN(LoginApitest); +}; + +IN_PROC_BROWSER_TEST_F(LoginApitest, LaunchManagedGuestSession) { + SetUpDeviceLocalAccountPolicy(); + SetUpExtensionAndRunTest(kLaunchManagedGuestSession); + EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); + + // Check that the active user is of type |USER_TYPE_PUBLIC_ACCOUNT|. + // We cannot use the email as an identifier as a different email is generated + // for managed guest sessions. + user_manager::UserManager* user_manager = user_manager::UserManager::Get(); + EXPECT_TRUE(user_manager->GetActiveUser()->GetType() == + user_manager::USER_TYPE_PUBLIC_ACCOUNT); +} + +IN_PROC_BROWSER_TEST_F(LoginApitest, LaunchManagedGuestSessionNoAccounts) { + SetUpExtensionAndRunTest(kLaunchManagedGuestSessionNoAccounts); +} + +IN_PROC_BROWSER_TEST_F(LoginApitest, ExitCurrentSession) { + SetUpDeviceLocalAccountPolicy(); + SetTestCustomArg(kData); + content::WindowedNotificationObserver termination_waiter( + chrome::NOTIFICATION_APP_TERMINATING, + content::NotificationService::AllSources()); + + SetUpExtensionAndRunTest(kExitCurrentSession, /*assert_test_succeed=*/false); + termination_waiter.Wait(); + + PrefService* local_state = g_browser_process->local_state(); + EXPECT_EQ(kData, local_state->GetString( + prefs::kLoginExtensionApiDataForNextLoginAttempt)); +} + +IN_PROC_BROWSER_TEST_F(LoginApitest, FetchDataForNextLoginAttempt) { + SetTestCustomArg(kData); + PrefService* local_state = g_browser_process->local_state(); + local_state->SetString(prefs::kLoginExtensionApiDataForNextLoginAttempt, + kData); + SetUpExtensionAndRunTest(kFetchDataForNextLoginAttempt); + + EXPECT_EQ("", local_state->GetString( + prefs::kLoginExtensionApiDataForNextLoginAttempt)); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.cc b/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.cc index afedcf8..0830e2a 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.cc +++ b/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.cc
@@ -6,6 +6,7 @@ #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" +#include "testing/gtest/include/gtest/gtest.h" namespace { @@ -31,6 +32,11 @@ void LoginScreenApitestBase::SetUpExtensionAndRunTest( const std::string& testName) { + SetUpExtensionAndRunTest(testName, /*assert_test_succeed=*/true); +} +void LoginScreenApitestBase::SetUpExtensionAndRunTest( + const std::string& testName, + bool assert_test_succeed) { extensions::ResultCatcher catcher; ExtensionTestMessageListener listener(kWaitingForTestName, @@ -42,7 +48,8 @@ ASSERT_TRUE(listener.WaitUntilSatisfied()); listener.Reply(testName); - ASSERT_TRUE(catcher.GetNextResult()); + if (assert_test_succeed) + ASSERT_TRUE(catcher.GetNextResult()); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.h b/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.h index 985794c..01d7c4c 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.h +++ b/chrome/browser/chromeos/extensions/login_screen/login_screen_apitest_base.h
@@ -17,6 +17,7 @@ // screen extension" and is also whitelisted for the following APIs: // * loginScreenUi // * storage +// * login // The extension's code can be found in // chrome/test/data/extensions/api_test/login_screen_apis/ class LoginScreenApitestBase @@ -27,6 +28,9 @@ void SetUpExtensionAndRunTest(const std::string& testName); + void SetUpExtensionAndRunTest(const std::string& testName, + bool assert_test_succeed); + protected: const std::string extension_id_; const std::string extension_update_manifest_path_;
diff --git a/chrome/browser/chromeos/extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc b/chrome/browser/chromeos/extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc index 2ee98c5d..50c90623 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc +++ b/chrome/browser/chromeos/extensions/login_screen/login_screen_ui/login_screen_extension_ui_handler_unittest.cc
@@ -37,7 +37,7 @@ const char kUrl[] = "test.html"; const char kWhitelistedExtensionID1[] = - "oclffehlkdgibkainkilopaalpdobkan"; // chrome.loginScreenUi test extension + "oclffehlkdgibkainkilopaalpdobkan"; // Login screen APIs test extension const char kWhitelistedExtensionID2[] = "lpimkpkllnkdlcigdbgmabfplniahkgm"; // Imprivata (login screen) const char kPermissionName[] = "loginScreenUi";
diff --git a/chrome/browser/chromeos/input_method/input_method_engine_browsertests.cc b/chrome/browser/chromeos/input_method/input_method_engine_browsertests.cc index f651cc38..65d3afca 100644 --- a/chrome/browser/chromeos/input_method/input_method_engine_browsertests.cc +++ b/chrome/browser/chromeos/input_method/input_method_engine_browsertests.cc
@@ -300,10 +300,10 @@ engine_handler->FocusIn(context); { - SCOPED_TRACE("KeyDown, Ctrl:No, alt:No, Shift:No, Caps:No"); + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:No, AltGr:No, Shift:No, Caps:No"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:a:KeyA:false:false:false:false"; + "onKeyEvent::true:keydown:a:KeyA:false:false:false:false:false"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event( @@ -316,10 +316,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:Yes, alt:No, Shift:No, Caps:No"); + SCOPED_TRACE("KeyDown, Ctrl:Yes, Alt:No, AltGr:No, Shift:No, Caps:No"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:a:KeyA:true:false:false:false"; + "onKeyEvent::true:keydown:a:KeyA:true:false:false:false:false"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, @@ -334,10 +334,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:No, alt:Yes, Shift:No, Caps:No"); + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:Yes, AltGr:No, Shift:No, Caps:No"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:a:KeyA:false:true:false:false"; + "onKeyEvent::true:keydown:a:KeyA:false:true:false:false:false"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, @@ -352,10 +352,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:No, alt:No, Shift:Yes, Caps:No"); + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:No, AltGr:No, Shift:Yes, Caps:No"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:A:KeyA:false:false:true:false"; + "onKeyEvent::true:keydown:A:KeyA:false:false:false:true:false"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, @@ -370,10 +370,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:No, alt:No, Shift:No, Caps:Yes"); + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:No, AltGr:No, Shift:No, Caps:Yes"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:A:KeyA:false:false:false:true"; + "onKeyEvent::true:keydown:A:KeyA:false:false:false:false:true"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::DomCode::US_A, @@ -386,10 +386,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:Yes, alt:Yes, Shift:No, Caps:No"); + SCOPED_TRACE("KeyDown, Ctrl:Yes, Alt:Yes, AltGr:No, Shift:No, Caps:No"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:a:KeyA:true:true:false:false"; + "onKeyEvent::true:keydown:a:KeyA:true:true:false:false:false"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, @@ -404,10 +404,10 @@ callback.WaitUntilCalled(); } { - SCOPED_TRACE("KeyDown, Ctrl:No, alt:No, Shift:Yes, Caps:Yes"); + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:No, AltGr:No, Shift:Yes, Caps:Yes"); KeyEventDoneCallback callback(false); const std::string expected_value = - "onKeyEvent::true:keydown:a:KeyA:false:false:true:true"; + "onKeyEvent::true:keydown:a:KeyA:false:false:false:true:true"; ExtensionTestMessageListener keyevent_listener(expected_value, false); ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::DomCode::US_A, @@ -419,6 +419,22 @@ EXPECT_TRUE(keyevent_listener.was_satisfied()); callback.WaitUntilCalled(); } + { + SCOPED_TRACE("KeyDown, Ctrl:No, Alt:No, AltGr:Yes, Shift:No, Caps:No"); + KeyEventDoneCallback callback(false); + const std::string expected_value = + "onKeyEvent::true:keydown:a:KeyA:false:false:true:false:false"; + ExtensionTestMessageListener keyevent_listener(expected_value, false); + + ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::DomCode::US_A, + ui::EF_ALTGR_DOWN); + ui::IMEEngineHandlerInterface::KeyEventDoneCallback keyevent_callback = + base::BindOnce(&KeyEventDoneCallback::Run, base::Unretained(&callback)); + engine_handler->ProcessKeyEvent(key_event, std::move(keyevent_callback)); + ASSERT_TRUE(keyevent_listener.WaitUntilSatisfied()); + EXPECT_TRUE(keyevent_listener.was_satisfied()); + callback.WaitUntilCalled(); + } // Media keys cases. const struct { ui::KeyboardCode keycode; @@ -452,7 +468,7 @@ SCOPED_TRACE(std::string("KeyDown, ") + kMediaKeyCases[i].code); KeyEventDoneCallback callback(false); const std::string expected_value = base::StringPrintf( - "onKeyEvent::true:keydown:%s:%s:false:false:false:false", + "onKeyEvent::true:keydown:%s:%s:false:false:false:false:false", kMediaKeyCases[i].key, kMediaKeyCases[i].code); ExtensionTestMessageListener keyevent_listener(expected_value, false); @@ -1255,7 +1271,7 @@ { SCOPED_TRACE("Verifies onKeyEvent event."); ExtensionTestMessageListener keydown_listener( - "onKeyEvent::true:keydown:a:KeyA:false:false:false:false", false); + "onKeyEvent::true:keydown:a:KeyA:false:false:false:false:false", false); EXPECT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_A, false, false, false, false));
diff --git a/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc index 1d49104..664545c7 100644 --- a/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc +++ b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc
@@ -152,7 +152,10 @@ WizardController::default_controller()->AdvanceToScreen( WelcomeView::kScreenId); - OobeScreenWaiter(NetworkScreenView::kScreenId).Wait(); + OobeScreenWaiter screen_waiter(NetworkScreenView::kScreenId); + // WebUI window is not visible until the screen animation finishes. + screen_waiter.set_no_check_native_window_visible(); + screen_waiter.Wait(); OobeScreenWaiter(EnrollmentScreenView::kScreenId).Wait();
diff --git a/chrome/browser/chromeos/login/oobe_interactive_ui_test.cc b/chrome/browser/chromeos/login/oobe_interactive_ui_test.cc index 27d045c..81c5b5b4 100644 --- a/chrome/browser/chromeos/login/oobe_interactive_ui_test.cc +++ b/chrome/browser/chromeos/login/oobe_interactive_ui_test.cc
@@ -3,6 +3,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/test/shell_test_api.h" #include "base/bind.h" @@ -13,6 +15,8 @@ #include "base/values.h" #include "build/branding_buildflags.h" #include "build/buildflag.h" +#include "chrome/browser/chrome_browser_main.h" +#include "chrome/browser/chrome_browser_main_extra_parts.h" #include "chrome/browser/chromeos/arc/arc_service_launcher.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.h" @@ -55,6 +59,8 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "ui/aura/window.h" +#include "ui/aura/window_observer.h" #include "ui/display/display_switches.h" using net::test_server::BasicHttpResponse; @@ -354,6 +360,58 @@ ScopedQuickUnlockPrivateGetAuthTokenFunctionObserver); }; +// Observes an |aura::Window| to see if the window was visible at some point in +// time. +class NativeWindowVisibilityObserver : public aura::WindowObserver { + public: + NativeWindowVisibilityObserver() = default; + // aura::Window will remove observers on destruction. + ~NativeWindowVisibilityObserver() override = default; + + void Observe(aura::Window* window) { + window_ = window; + window_->AddObserver(this); + } + + void OnWindowVisibilityChanged(aura::Window* window, bool visible) override { + if (visible) + was_visible_ = visible; + } + + bool was_visible() { return was_visible_; } + + private: + // The window was visible at some point in time. + bool was_visible_ = false; + + aura::Window* window_; + + DISALLOW_COPY_AND_ASSIGN(NativeWindowVisibilityObserver); +}; + +// Sets the |NativeWindowVisibilityObserver| to observe the +// |LoginDisplayHost|'s |NativeWindow|. This needs to be done in +// |PostProfileInit()| as the |default_host| will not be initialized before +// this. +class NativeWindowVisibilityBrowserMainExtraParts + : public ChromeBrowserMainExtraParts { + public: + NativeWindowVisibilityBrowserMainExtraParts( + NativeWindowVisibilityObserver* observer) + : observer_(observer) {} + ~NativeWindowVisibilityBrowserMainExtraParts() override = default; + + // ChromeBrowserMainExtraParts: + void PostProfileInit() override { + observer_->Observe(LoginDisplayHost::default_host()->GetNativeWindow()); + } + + private: + NativeWindowVisibilityObserver* observer_; + + DISALLOW_COPY_AND_ASSIGN(NativeWindowVisibilityBrowserMainExtraParts); +}; + class OobeEndToEndTestSetupMixin : public InProcessBrowserTestMixin { public: struct Parameters { @@ -684,7 +742,8 @@ : PublicSessionOobeTest(false /*requires_terms_of_service*/) {} explicit PublicSessionOobeTest(bool requires_terms_of_service) - : requires_terms_of_service_(requires_terms_of_service) { + : requires_terms_of_service_(requires_terms_of_service), + observer_(std::make_unique<NativeWindowVisibilityObserver>()) { // Prevents Chrome from starting to quit right after login display is // finalized. login_manager_.set_should_launch_browser(true); @@ -728,11 +787,26 @@ MixinBasedInProcessBrowserTest::SetUpInProcessBrowserTestFixture(); } + void CreatedBrowserMainParts(content::BrowserMainParts* parts) override { + MixinBasedInProcessBrowserTest::CreatedBrowserMainParts(parts); + static_cast<ChromeBrowserMainParts*>(parts)->AddParts( + new NativeWindowVisibilityBrowserMainExtraParts(observer_.get())); + } + + void TearDownOnMainThread() override { + observer_.reset(); + MixinBasedInProcessBrowserTest::TearDownOnMainThread(); + } + + bool DialogWasVisible() { return observer_->was_visible(); } + LoginManagerMixin login_manager_{&mixin_host_, {}}; private: const bool requires_terms_of_service_; + std::unique_ptr<NativeWindowVisibilityObserver> observer_; + OobeEndToEndTestSetupMixin setup_{&mixin_host_, nullptr, GetParam()}; DeviceStateMixin device_state_{ &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; @@ -740,6 +814,8 @@ IN_PROC_BROWSER_TEST_P(PublicSessionOobeTest, NoTermsOfService) { login_manager_.WaitForActiveSession(); + // Check that the dialog was never shown. + EXPECT_FALSE(DialogWasVisible()); } INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index 936945a..8fd2323 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -1482,6 +1482,9 @@ // Verifies that password attributes are extracted and stored during a // successful log in - but only if the appropriate policy is enabled. IN_PROC_BROWSER_TEST_P(SAMLPasswordAttributesTest, LoginSucceeded) { + // LoginDisplayHostMojo does not show Oobe dialog by default. + LoginDisplayHost::default_host()->ShowGaiaDialog(true, EmptyAccountId()); + fake_saml_idp()->SetLoginHTMLTemplate("saml_login.html"); fake_saml_idp()->SetSamlResponseFile("saml_with_password_attributes.xml"); StartSamlAndWaitForIdpPageLoad(kFirstSAMLUserEmail); @@ -1513,6 +1516,9 @@ // Verify that no password attributes are stored when login fails. IN_PROC_BROWSER_TEST_P(SAMLPasswordAttributesTest, LoginFailed) { + // LoginDisplayHostMojo does not show Oobe dialog by default. + LoginDisplayHost::default_host()->ShowGaiaDialog(true, EmptyAccountId()); + fake_saml_idp()->SetLoginHTMLTemplate("saml_login.html"); fake_saml_idp()->SetSamlResponseFile("saml_with_password_attributes.xml"); StartSamlAndWaitForIdpPageLoad(kFirstSAMLUserEmail);
diff --git a/chrome/browser/chromeos/login/test/oobe_screen_waiter.cc b/chrome/browser/chromeos/login/test/oobe_screen_waiter.cc index 6f7c21a..c45c4a3 100644 --- a/chrome/browser/chromeos/login/test/oobe_screen_waiter.cc +++ b/chrome/browser/chromeos/login/test/oobe_screen_waiter.cc
@@ -6,7 +6,11 @@ #include "base/run_loop.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" +#include "chrome/browser/chromeos/login/ui/webui_login_view.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/window.h" +#include "ui/views/controls/webview/webview.h" +#include "ui/views/view.h" namespace chromeos { @@ -18,13 +22,20 @@ void OobeScreenWaiter::Wait() { DCHECK_EQ(State::IDLE, state_); - if (GetOobeUI()->current_screen() == target_screen_) { + if ((!check_native_window_visible_ || IsNativeWindowVisible()) && + IsTargetScreenReached()) { state_ = State::DONE; return; } DCHECK(!run_loop_); oobe_ui_observer_.Add(GetOobeUI()); + if (check_native_window_visible_) { + aura::Window* native_window = + LoginDisplayHost::default_host()->GetNativeWindow(); + DCHECK(native_window); + native_window_observer_.Add(native_window); + } state_ = State::WAITING_FOR_SCREEN; @@ -35,6 +46,8 @@ DCHECK_EQ(State::DONE, state_); oobe_ui_observer_.RemoveAll(); + if (check_native_window_visible_) + native_window_observer_.RemoveAll(); if (assert_last_screen_) EXPECT_EQ(target_screen_, GetOobeUI()->current_screen()); @@ -60,10 +73,33 @@ return; } - if (new_screen == target_screen_) + if (check_native_window_visible_ && !IsNativeWindowVisible()) { + return; + } + + if (IsTargetScreenReached()) EndWait(); } +void OobeScreenWaiter::OnWindowVisibilityChanged(aura::Window* window, + bool visible) { + DCHECK_NE(state_, State::IDLE); + DCHECK(check_native_window_visible_); + + if (IsNativeWindowVisible() && IsTargetScreenReached()) + EndWait(); +} + +bool OobeScreenWaiter::IsTargetScreenReached() { + return GetOobeUI()->current_screen() == target_screen_; +} + +bool OobeScreenWaiter::IsNativeWindowVisible() { + aura::Window* native_window = + LoginDisplayHost::default_host()->GetNativeWindow(); + return native_window && native_window->IsVisible(); +} + void OobeScreenWaiter::OnDestroyingOobeUI() { oobe_ui_observer_.RemoveAll();
diff --git a/chrome/browser/chromeos/login/test/oobe_screen_waiter.h b/chrome/browser/chromeos/login/test/oobe_screen_waiter.h index 3dedcd2..c737b1e 100644 --- a/chrome/browser/chromeos/login/test/oobe_screen_waiter.h +++ b/chrome/browser/chromeos/login/test/oobe_screen_waiter.h
@@ -10,6 +10,7 @@ #include "chrome/browser/chromeos/login/oobe_screen.h" #include "chrome/browser/chromeos/login/test/test_condition_waiter.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" +#include "ui/aura/window_observer.h" namespace base { class RunLoop; @@ -21,13 +22,17 @@ // A waiter that blocks until the target oobe screen is reached. class OobeScreenWaiter : public OobeUI::Observer, - public test::TestConditionWaiter { + public test::TestConditionWaiter, + public aura::WindowObserver { public: explicit OobeScreenWaiter(OobeScreenId target_screen); ~OobeScreenWaiter() override; void set_no_assert_last_screen() { assert_last_screen_ = false; } void set_assert_next_screen() { assert_next_screen_ = true; } + void set_no_check_native_window_visible() { + check_native_window_visible_ = false; + } // OobeUI::Observer implementation: void OnCurrentScreenChanged(OobeScreenId current_screen, @@ -37,12 +42,21 @@ // TestConditionWaiter; void Wait() override; + // aura::WindowObserver: + void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; + private: enum class State { IDLE, WAITING_FOR_SCREEN, DONE }; OobeUI* GetOobeUI(); void EndWait(); + // Returns true if the target screen is reached. + bool IsTargetScreenReached(); + + // Returns true if the native window is visible. + bool IsNativeWindowVisible(); + const OobeScreenId target_screen_; State state_ = State::IDLE; @@ -52,12 +66,20 @@ // This applies to the time period Wait() is running only. bool assert_last_screen_ = true; - // If set, the watier will assert OOBE UI does not transition to any other - // screen before transisioning to the target screen. + // If set, the waiter will assert OOBE UI does not transition to any other + // screen before transitioning to the target screen. bool assert_next_screen_ = false; + // If set, the waiter will only finish waiting if the target screen has been + // reached and the native window is visible. The assert_last_screen and + // assert_next_screen checks will only be done if the native window is + // visible. True by default. + bool check_native_window_visible_ = true; + ScopedObserver<OobeUI, OobeScreenWaiter> oobe_ui_observer_{this}; + ScopedObserver<aura::Window, OobeScreenWaiter> native_window_observer_{this}; + std::unique_ptr<base::RunLoop> run_loop_; DISALLOW_COPY_AND_ASSIGN(OobeScreenWaiter);
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc b/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc index b38f22a..e75c71a 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_mojo.cc
@@ -78,6 +78,7 @@ LoginScreenClient::Get()->SetDelegate(nullptr); if (dialog_) { dialog_->GetOobeUI()->signin_screen_handler()->SetDelegate(nullptr); + StopObservingOobeUI(); dialog_->Close(); } } @@ -85,6 +86,7 @@ void LoginDisplayHostMojo::OnDialogDestroyed( const OobeUIDialogDelegate* dialog) { if (dialog == dialog_) { + StopObservingOobeUI(); dialog_ = nullptr; wizard_controller_.reset(); } @@ -101,25 +103,25 @@ DCHECK(GetOobeUI()); GetOobeUI()->signin_screen_handler()->ShowPasswordChangedDialog( show_password_error, email); - dialog_->Show(); + ShowDialog(); } void LoginDisplayHostMojo::ShowWhitelistCheckFailedError() { DCHECK(GetOobeUI()); GetOobeUI()->signin_screen_handler()->ShowWhitelistCheckFailedError(); - dialog_->Show(); + ShowDialog(); } void LoginDisplayHostMojo::ShowErrorScreen(LoginDisplay::SigninError error_id) { DCHECK(GetOobeUI()); GetOobeUI()->signin_screen_handler()->ShowErrorScreen(error_id); - dialog_->Show(); + ShowDialog(); } void LoginDisplayHostMojo::ShowSigninUI(const std::string& email) { DCHECK(GetOobeUI()); GetOobeUI()->signin_screen_handler()->ShowSigninUI(email); - dialog_->Show(); + ShowDialog(); } void LoginDisplayHostMojo::HandleDisplayCaptivePortal() { @@ -174,12 +176,15 @@ } void LoginDisplayHostMojo::StartWizard(OobeScreenId first_screen) { - DCHECK(GetOobeUI()); + OobeUI* oobe_ui = GetOobeUI(); + DCHECK(oobe_ui); + // Dialog is not shown immediately, and will be shown only when a screen + // change occurs. This prevents the dialog from showing when there are no + // screens to show. + ObserveOobeUI(); wizard_controller_ = std::make_unique<WizardController>(); wizard_controller_->Init(first_screen); - - dialog_->Show(); } WizardController* LoginDisplayHostMojo::GetWizardController() { @@ -241,11 +246,11 @@ } void LoginDisplayHostMojo::OnStartAppLaunch() { - dialog_->ShowFullScreen(); + ShowFullScreen(); } void LoginDisplayHostMojo::OnStartArcKiosk() { - dialog_->ShowFullScreen(); + ShowFullScreen(); } void LoginDisplayHostMojo::OnBrowserCreated() { @@ -264,7 +269,7 @@ ShowGaiaDialogCommon(prefilled_account); - dialog_->Show(); + ShowDialog(); } void LoginDisplayHostMojo::HideOobeDialog() { @@ -280,7 +285,7 @@ } LoadWallpaper(focused_pod_account_id_); - dialog_->Hide(); + HideDialog(); } void LoginDisplayHostMojo::UpdateOobeDialogSize(int width, int height) { @@ -451,6 +456,17 @@ const UserContext& user_context, bool has_incomplete_migration) {} +void LoginDisplayHostMojo::OnCurrentScreenChanged(OobeScreenId current_screen, + OobeScreenId new_screen) { + DCHECK(dialog_); + if (!dialog_->IsVisible()) + ShowDialog(); +} + +void LoginDisplayHostMojo::OnDestroyingOobeUI() { + StopObservingOobeUI(); +} + void LoginDisplayHostMojo::LoadOobeDialog() { if (dialog_) return; @@ -484,4 +500,45 @@ existing_user_controller_->Login(user_context, chromeos::SigninSpecifics()); } +void LoginDisplayHostMojo::ShowDialog() { + ObserveOobeUI(); + dialog_->Show(); +} + +void LoginDisplayHostMojo::ShowFullScreen() { + ObserveOobeUI(); + dialog_->ShowFullScreen(); +} + +void LoginDisplayHostMojo::HideDialog() { + // Stop observing so that dialog will not be shown when a screen change + // occurs. Screen changes can occur even when the dialog is not shown (e.g. + // with hidden error screens). + StopObservingOobeUI(); + dialog_->Hide(); +} + +void LoginDisplayHostMojo::ObserveOobeUI() { + if (added_as_oobe_observer_) + return; + + OobeUI* oobe_ui = GetOobeUI(); + if (!oobe_ui) + return; + + oobe_ui->AddObserver(this); + added_as_oobe_observer_ = true; +} + +void LoginDisplayHostMojo::StopObservingOobeUI() { + if (!added_as_oobe_observer_) + return; + + added_as_oobe_observer_ = false; + + OobeUI* oobe_ui = GetOobeUI(); + if (oobe_ui) + oobe_ui->RemoveObserver(this); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_mojo.h b/chrome/browser/chromeos/login/ui/login_display_host_mojo.h index ba9f5127..7cc02dc 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_mojo.h +++ b/chrome/browser/chromeos/login/ui/login_display_host_mojo.h
@@ -18,6 +18,7 @@ #include "chrome/browser/chromeos/login/ui/login_display_host_common.h" #include "chrome/browser/chromeos/login/ui/oobe_ui_dialog_delegate.h" #include "chrome/browser/ui/ash/login_screen_client.h" +#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chromeos/login/auth/auth_status_consumer.h" #include "chromeos/login/auth/challenge_response_key.h" @@ -34,7 +35,8 @@ // screen. class LoginDisplayHostMojo : public LoginDisplayHostCommon, public LoginScreenClient::Delegate, - public AuthStatusConsumer { + public AuthStatusConsumer, + public OobeUI::Observer { public: LoginDisplayHostMojo(); ~LoginDisplayHostMojo() override; @@ -126,6 +128,11 @@ void OnOldEncryptionDetected(const UserContext& user_context, bool has_incomplete_migration) override; + // OobeUI::Observer: + void OnCurrentScreenChanged(OobeScreenId current_screen, + OobeScreenId new_screen) override; + void OnDestroyingOobeUI() override; + private: void LoadOobeDialog(); @@ -137,6 +144,17 @@ base::OnceCallback<void(bool)> on_auth_complete_callback, std::vector<ChallengeResponseKey> challenge_response_keys); + // Helper methods to show and hide the dialog. + void ShowDialog(); + void ShowFullScreen(); + void HideDialog(); + + // Adds this as a |OobeUI::Observer| if it has not already been added as one. + void ObserveOobeUI(); + + // Removes this as a |OobeUI::Observer| if it has been added as an observer. + void StopObservingOobeUI(); + // State associated with a pending authentication attempt. struct AuthState { AuthState(AccountId account_id, base::OnceCallback<void(bool)> callback); @@ -181,6 +199,9 @@ SecurityTokenPinDialogHostAshImpl security_token_pin_dialog_host_ash_impl_; + // Set if this has been added as a |OobeUI::Observer|. + bool added_as_oobe_observer_ = false; + base::WeakPtrFactory<LoginDisplayHostMojo> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LoginDisplayHostMojo);
diff --git a/chrome/browser/chromeos/policy/device_local_account.cc b/chrome/browser/chromeos/policy/device_local_account.cc index 6226639..4069a228 100644 --- a/chrome/browser/chromeos/policy/device_local_account.cc +++ b/chrome/browser/chromeos/policy/device_local_account.cc
@@ -30,6 +30,8 @@ const char kKioskAppAccountDomainPrefix[] = "kiosk-apps"; const char kArcKioskAppAccountDomainPrefix[] = "arc-kiosk-apps"; const char kSAMLPublicAccountDomainPrefix[] = "saml-public-accounts"; +const char kWebKioskAppAccountDomainPrefix[] = "web-kiosk-apps"; + const char kDeviceLocalAccountDomainSuffix[] = ".device-local.localhost"; } // namespace @@ -57,6 +59,13 @@ this->display_name_ == other.display_name_; } +WebKioskAppBasicInfo::WebKioskAppBasicInfo(const std::string& url) + : url_(url) {} + +WebKioskAppBasicInfo::WebKioskAppBasicInfo() {} + +WebKioskAppBasicInfo::~WebKioskAppBasicInfo() {} + DeviceLocalAccount::DeviceLocalAccount(Type type, const std::string& account_id, const std::string& kiosk_app_id, @@ -76,6 +85,14 @@ user_id(GenerateDeviceLocalAccountUserId(account_id, type)), arc_kiosk_app_info(arc_kiosk_app_info) {} +DeviceLocalAccount::DeviceLocalAccount( + const WebKioskAppBasicInfo& web_kiosk_app_info, + const std::string& account_id) + : type(DeviceLocalAccount::TYPE_WEB_KIOSK_APP), + account_id(account_id), + user_id(GenerateDeviceLocalAccountUserId(account_id, type)), + web_kiosk_app_info(web_kiosk_app_info) {} + DeviceLocalAccount::DeviceLocalAccount(const DeviceLocalAccount& other) = default; @@ -98,6 +115,9 @@ case DeviceLocalAccount::TYPE_SAML_PUBLIC_SESSION: domain_prefix = kSAMLPublicAccountDomainPrefix; break; + case DeviceLocalAccount::TYPE_WEB_KIOSK_APP: + domain_prefix = kWebKioskAppAccountDomainPrefix; + break; case DeviceLocalAccount::TYPE_COUNT: NOTREACHED(); break; @@ -141,6 +161,11 @@ *type = DeviceLocalAccount::TYPE_SAML_PUBLIC_SESSION; return true; } + if (domain_prefix == kWebKioskAppAccountDomainPrefix) { + if (type) + *type = DeviceLocalAccount::TYPE_WEB_KIOSK_APP; + return true; + } // |user_id| is a device-local account but its type is not recognized. NOTREACHED(); @@ -187,6 +212,9 @@ chromeos::kAccountsPrefDeviceLocalAccountsKeyArcKioskDisplayName, base::Value(it->arc_kiosk_app_info.display_name())); } + } else if (it->type == DeviceLocalAccount::TYPE_WEB_KIOSK_APP) { + entry->SetKey(chromeos::kAccountsPrefDeviceLocalAccountsKeyWebKioskUrl, + base::Value(it->web_kiosk_app_info.url())); } list.Append(std::move(entry)); } @@ -249,19 +277,16 @@ case DeviceLocalAccount::TYPE_KIOSK_APP: { std::string kiosk_app_id; std::string kiosk_app_update_url; - if (type == DeviceLocalAccount::TYPE_KIOSK_APP) { - if (!entry->GetStringWithoutPathExpansion( - chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppId, - &kiosk_app_id)) { - LOG(ERROR) - << "Missing app ID in device-local account entry at index " << i - << "."; - continue; - } - entry->GetStringWithoutPathExpansion( - chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppUpdateURL, - &kiosk_app_update_url); + if (!entry->GetStringWithoutPathExpansion( + chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppId, + &kiosk_app_id)) { + LOG(ERROR) << "Missing app ID in device-local account entry at index " + << i << "."; + continue; } + entry->GetStringWithoutPathExpansion( + chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppUpdateURL, + &kiosk_app_update_url); accounts.push_back( DeviceLocalAccount(DeviceLocalAccount::TYPE_KIOSK_APP, account_id, @@ -296,6 +321,22 @@ accounts.push_back(DeviceLocalAccount(arc_kiosk_app, account_id)); break; } + case DeviceLocalAccount::TYPE_WEB_KIOSK_APP: { + std::string url; + if (!entry->GetStringWithoutPathExpansion( + chromeos::kAccountsPrefDeviceLocalAccountsKeyWebKioskUrl, + &url)) { + LOG(ERROR) << "Missing install url in Web kiosk type device-local " + "account at index " + << i << "."; + continue; + } + + accounts.push_back(DeviceLocalAccount( + WebKioskAppBasicInfo(url), account_id)); + + break; + } default: NOTREACHED(); }
diff --git a/chrome/browser/chromeos/policy/device_local_account.h b/chrome/browser/chromeos/policy/device_local_account.h index 9f9ca48..85cd4fd 100644 --- a/chrome/browser/chromeos/policy/device_local_account.h +++ b/chrome/browser/chromeos/policy/device_local_account.h
@@ -38,6 +38,18 @@ std::string display_name_; }; +// TODO(apotapchuk): Might be expanded to include title and icon_url. +struct WebKioskAppBasicInfo { + WebKioskAppBasicInfo(const std::string& url); + WebKioskAppBasicInfo(); + ~WebKioskAppBasicInfo(); + + const std::string& url() const { return url_; } + + private: + std::string url_; +}; + // This must match DeviceLocalAccountInfoProto.AccountType in // chrome_device_policy.proto. struct DeviceLocalAccount { @@ -51,6 +63,8 @@ TYPE_ARC_KIOSK_APP, // SAML public session account TYPE_SAML_PUBLIC_SESSION, + // An account that serves as a container for a single full-screen web app. + TYPE_WEB_KIOSK_APP, // Sentinel, must be last. TYPE_COUNT }; @@ -61,6 +75,8 @@ const std::string& kiosk_app_update_url); DeviceLocalAccount(const ArcKioskAppBasicInfo& arc_kiosk_app_info, const std::string& account_id); + DeviceLocalAccount(const WebKioskAppBasicInfo& app_info, + const std::string& account_id); DeviceLocalAccount(const DeviceLocalAccount& other); ~DeviceLocalAccount(); @@ -88,6 +104,7 @@ std::string kiosk_app_update_url; ArcKioskAppBasicInfo arc_kiosk_app_info; + WebKioskAppBasicInfo web_kiosk_app_info; }; std::string GenerateDeviceLocalAccountUserId(const std::string& account_id,
diff --git a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc index 433d4333..b59f26f 100644 --- a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
@@ -264,6 +264,12 @@ chromeos::kAccountsPrefDeviceLocalAccountsKeyArcKioskDisplayName, base::Value(entry.android_kiosk_app().display_name())); } + if (entry.web_kiosk_app().has_url()) { + entry_dict->SetKey( + chromeos::kAccountsPrefDeviceLocalAccountsKeyWebKioskUrl, + base::Value(entry.web_kiosk_app().url())); + } + } else if (entry.has_deprecated_public_session_id()) { // Deprecated public session specification. entry_dict->SetKey(chromeos::kAccountsPrefDeviceLocalAccountsKeyId, @@ -986,6 +992,18 @@ nullptr); } } + if (container.has_login_screen_autoclick_enabled()) { + PolicyLevel level; + if (GetPolicyLevel(container.has_login_screen_autoclick_enabled_options(), + container.login_screen_autoclick_enabled_options(), + &level)) { + policies->Set(key::kDeviceLoginScreenAutoclickEnabled, level, + POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, + std::make_unique<base::Value>( + container.login_screen_autoclick_enabled()), + nullptr); + } + } } }
diff --git a/chrome/browser/chromeos/policy/login_profile_policy_provider.cc b/chrome/browser/chromeos/policy/login_profile_policy_provider.cc index 1928551..362525c3 100644 --- a/chrome/browser/chromeos/policy/login_profile_policy_provider.cc +++ b/chrome/browser/chromeos/policy/login_profile_policy_provider.cc
@@ -50,6 +50,7 @@ key::kCursorHighlightEnabled}, {key::kDeviceLoginScreenCaretHighlightEnabled, key::kCaretHighlightEnabled}, {key::kDeviceLoginScreenMonoAudioEnabled, key::kMonoAudioEnabled}, + {key::kDeviceLoginScreenAutoclickEnabled, key::kAutoclickEnabled}, }; const DevicePolicyToUserPolicyMapEntry kRecommendedDevicePoliciesMap[] = {
diff --git a/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc b/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc index 0d3e9c9..baf9360 100644 --- a/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc
@@ -751,4 +751,56 @@ accessibility_manager->EnableMonoAudio(false); EXPECT_FALSE(accessibility_manager->IsMonoAudioEnabled()); } + +IN_PROC_BROWSER_TEST_F(LoginScreenAccessibilityPolicyBrowsertest, + DeviceLoginScreenAutoclickEnabled) { + // Verifies that the state of the autoclick accessibility feature on + // the login screen can be controlled through device policy. + chromeos::AccessibilityManager* accessibility_manager = + chromeos::AccessibilityManager::Get(); + ASSERT_TRUE(accessibility_manager); + EXPECT_FALSE(accessibility_manager->IsAutoclickEnabled()); + + // Manually enable the autoclick. + accessibility_manager->EnableAutoclick(true); + EXPECT_TRUE(accessibility_manager->IsAutoclickEnabled()); + + // Disable the autoclick through device policy and wait for the change + // to take effect. + em::ChromeDeviceSettingsProto& proto(device_policy()->payload()); + proto.mutable_accessibility_settings()->set_login_screen_autoclick_enabled( + false); + RefreshDevicePolicyAndWaitForPrefChange( + ash::prefs::kAccessibilityAutoclickEnabled); + + // Verify that the pref which controls the autoclick in the login + // profile is managed by the policy. + EXPECT_TRUE(IsPrefManaged(ash::prefs::kAccessibilityAutoclickEnabled)); + EXPECT_EQ(base::Value(false), + GetPrefValue(ash::prefs::kAccessibilityAutoclickEnabled)); + + // Verify that the autoclick cannot be enabled manually anymore. + accessibility_manager->EnableAutoclick(true); + EXPECT_FALSE(accessibility_manager->IsAutoclickEnabled()); + + // Enable the autoclick through device policy as a recommended value and wait + // for the change to take effect. + proto.mutable_accessibility_settings()->set_login_screen_autoclick_enabled( + true); + proto.mutable_accessibility_settings() + ->mutable_login_screen_autoclick_enabled_options() + ->set_mode(em::PolicyOptions::RECOMMENDED); + RefreshDevicePolicyAndWaitForPrefChange( + ash::prefs::kAccessibilityAutoclickEnabled); + + // Verify that the pref which controls the autoclick in the login + // profile is being applied as recommended by the policy. + EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilityAutoclickEnabled)); + EXPECT_EQ(base::Value(true), + GetPrefValue(ash::prefs::kAccessibilityAutoclickEnabled)); + + // Verify that the autoclick can be enabled manually again. + accessibility_manager->EnableAutoclick(false); + EXPECT_FALSE(accessibility_manager->IsAutoclickEnabled()); +} } // namespace policy
diff --git a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.cc b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.cc index 7f5f51d..d4fc3c4 100644 --- a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.cc +++ b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.cc
@@ -52,11 +52,12 @@ // A helper function which invokes |store_screenshot_callback| on |task_runner|. void RunStoreScreenshotOnTaskRunner( - const ui::GrabWindowSnapshotAsyncPNGCallback& store_screenshot_callback, + ui::GrabWindowSnapshotAsyncPNGCallback store_screenshot_callback, scoped_refptr<base::TaskRunner> task_runner, scoped_refptr<base::RefCountedMemory> png_data) { - task_runner->PostTask(FROM_HERE, - base::BindOnce(store_screenshot_callback, png_data)); + task_runner->PostTask( + FROM_HERE, + base::BindOnce(std::move(store_screenshot_callback), png_data)); } } // namespace @@ -222,10 +223,11 @@ gfx::Rect rect = root_window->bounds(); screenshot_delegate_->TakeSnapshot( root_window, rect, - base::Bind(&RunStoreScreenshotOnTaskRunner, - base::Bind(&DeviceCommandScreenshotJob::StoreScreenshot, - weak_ptr_factory_.GetWeakPtr(), screen), - base::ThreadTaskRunnerHandle::Get())); + base::BindOnce( + &RunStoreScreenshotOnTaskRunner, + base::BindOnce(&DeviceCommandScreenshotJob::StoreScreenshot, + weak_ptr_factory_.GetWeakPtr(), screen), + base::ThreadTaskRunnerHandle::Get())); } }
diff --git a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.h b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.h index 5211e35..98b9553 100644 --- a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.h +++ b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job.h
@@ -78,7 +78,7 @@ virtual void TakeSnapshot( gfx::NativeWindow window, const gfx::Rect& source_rect, - const ui::GrabWindowSnapshotAsyncPNGCallback& callback) = 0; + ui::GrabWindowSnapshotAsyncPNGCallback callback) = 0; // Creates a new fully configured instance of an UploadJob. This method // may be called any number of times.
diff --git a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job_unittest.cc b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job_unittest.cc index 0489a5b..8635376 100644 --- a/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job_unittest.cc +++ b/chrome/browser/chromeos/policy/remote_commands/device_command_screenshot_job_unittest.cc
@@ -143,10 +143,9 @@ ~MockScreenshotDelegate() override; bool IsScreenshotAllowed() override; - void TakeSnapshot( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const ui::GrabWindowSnapshotAsyncPNGCallback& callback) override; + void TakeSnapshot(gfx::NativeWindow window, + const gfx::Rect& source_rect, + ui::GrabWindowSnapshotAsyncPNGCallback callback) override; std::unique_ptr<UploadJob> CreateUploadJob(const GURL&, UploadJob::Delegate*) override; @@ -171,13 +170,13 @@ void MockScreenshotDelegate::TakeSnapshot( gfx::NativeWindow window, const gfx::Rect& source_rect, - const ui::GrabWindowSnapshotAsyncPNGCallback& callback) { + ui::GrabWindowSnapshotAsyncPNGCallback callback) { const int width = source_rect.width(); const int height = source_rect.height(); scoped_refptr<base::RefCountedBytes> test_png = GenerateTestPNG(width, height); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(callback, test_png)); + FROM_HERE, base::BindOnce(std::move(callback), test_png)); } std::unique_ptr<UploadJob> MockScreenshotDelegate::CreateUploadJob(
diff --git a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc index 33d1fe4a..e8f408c 100644 --- a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc +++ b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.cc
@@ -41,11 +41,11 @@ void ScreenshotDelegate::TakeSnapshot( gfx::NativeWindow window, const gfx::Rect& source_rect, - const ui::GrabWindowSnapshotAsyncPNGCallback& callback) { + ui::GrabWindowSnapshotAsyncPNGCallback callback) { ui::GrabWindowSnapshotAsyncPNG( window, source_rect, - base::Bind(&ScreenshotDelegate::StoreScreenshot, - weak_ptr_factory_.GetWeakPtr(), callback)); + base::BindOnce(&ScreenshotDelegate::StoreScreenshot, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } std::unique_ptr<UploadJob> ScreenshotDelegate::CreateUploadJob( @@ -86,9 +86,9 @@ } void ScreenshotDelegate::StoreScreenshot( - const ui::GrabWindowSnapshotAsyncPNGCallback& callback, + ui::GrabWindowSnapshotAsyncPNGCallback callback, scoped_refptr<base::RefCountedMemory> png_data) { - callback.Run(png_data); + std::move(callback).Run(png_data); } } // namespace policy
diff --git a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.h b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.h index e06c4b2..73c59acb 100644 --- a/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.h +++ b/chrome/browser/chromeos/policy/remote_commands/screenshot_delegate.h
@@ -28,16 +28,15 @@ // DeviceCommandScreenshotJob::Delegate: bool IsScreenshotAllowed() override; - void TakeSnapshot( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const ui::GrabWindowSnapshotAsyncPNGCallback& callback) override; + void TakeSnapshot(gfx::NativeWindow window, + const gfx::Rect& source_rect, + ui::GrabWindowSnapshotAsyncPNGCallback callback) override; std::unique_ptr<UploadJob> CreateUploadJob( const GURL& upload_url, UploadJob::Delegate* delegate) override; private: - void StoreScreenshot(const ui::GrabWindowSnapshotAsyncPNGCallback& callback, + void StoreScreenshot(ui::GrabWindowSnapshotAsyncPNGCallback callback, scoped_refptr<base::RefCountedMemory> png_data); base::WeakPtrFactory<ScreenshotDelegate> weak_ptr_factory_{this};
diff --git a/chrome/browser/chromeos/power/ml/smart_dim/ml_service_client.cc b/chrome/browser/chromeos/power/ml/smart_dim/ml_service_client.cc index f1400e4..4ca9bf1 100644 --- a/chrome/browser/chromeos/power/ml/smart_dim/ml_service_client.cc +++ b/chrome/browser/chromeos/power/ml/smart_dim/ml_service_client.cc
@@ -18,14 +18,14 @@ #include "chromeos/services/machine_learning/public/mojom/tensor.mojom.h" #include "mojo/public/cpp/bindings/map.h" +using ::chromeos::machine_learning::mojom::BuiltinModelId; +using ::chromeos::machine_learning::mojom::BuiltinModelSpec; +using ::chromeos::machine_learning::mojom::BuiltinModelSpecPtr; using ::chromeos::machine_learning::mojom::CreateGraphExecutorResult; using ::chromeos::machine_learning::mojom::ExecuteResult; using ::chromeos::machine_learning::mojom::FloatList; using ::chromeos::machine_learning::mojom::Int64List; using ::chromeos::machine_learning::mojom::LoadModelResult; -using ::chromeos::machine_learning::mojom::ModelId; -using ::chromeos::machine_learning::mojom::ModelSpec; -using ::chromeos::machine_learning::mojom::ModelSpecPtr; using ::chromeos::machine_learning::mojom::Tensor; using ::chromeos::machine_learning::mojom::TensorPtr; using ::chromeos::machine_learning::mojom::ValueList; @@ -131,14 +131,15 @@ void MlServiceClientImpl::InitMlServiceHandlesIfNeeded() { if (!model_) { // Load the model. - ModelSpecPtr spec = - ModelSpec::New(base::FeatureList::IsEnabled(features::kSmartDimModelV3) - ? ModelId::SMART_DIM_20190521 - : ModelId::SMART_DIM_20181115); - chromeos::machine_learning::ServiceConnection::GetInstance()->LoadModel( - std::move(spec), mojo::MakeRequest(&model_), - base::BindOnce(&MlServiceClientImpl::LoadModelCallback, - weak_factory_.GetWeakPtr())); + BuiltinModelSpecPtr spec = BuiltinModelSpec::New( + base::FeatureList::IsEnabled(features::kSmartDimModelV3) + ? BuiltinModelId::SMART_DIM_20190521 + : BuiltinModelId::SMART_DIM_20181115); + chromeos::machine_learning::ServiceConnection::GetInstance() + ->LoadBuiltinModel( + std::move(spec), mojo::MakeRequest(&model_), + base::BindOnce(&MlServiceClientImpl::LoadModelCallback, + weak_factory_.GetWeakPtr())); } if (!executor_) {
diff --git a/chrome/browser/content_settings/tab_specific_content_settings.cc b/chrome/browser/content_settings/tab_specific_content_settings.cc index 1071597..4a2a019 100644 --- a/chrome/browser/content_settings/tab_specific_content_settings.cc +++ b/chrome/browser/content_settings/tab_specific_content_settings.cc
@@ -725,7 +725,7 @@ RendererContentSettingRules rules; GetRendererContentSettingRules(map_, &rules); - chrome::mojom::RendererConfigurationAssociatedPtr rc_interface; + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration> rc_interface; channel->GetRemoteAssociatedInterface(&rc_interface); rc_interface->SetContentSettingRules(rules); }
diff --git a/chrome/browser/extensions/api/input_ime/input_ime_api.cc b/chrome/browser/extensions/api/input_ime/input_ime_api.cc index 315df77c..006075d 100644 --- a/chrome/browser/extensions/api/input_ime/input_ime_api.cc +++ b/chrome/browser/extensions/api/input_ime/input_ime_api.cc
@@ -112,10 +112,11 @@ } key_data_value.key = event.key; key_data_value.code = event.code; - key_data_value.alt_key.reset(new bool(event.alt_key)); - key_data_value.ctrl_key.reset(new bool(event.ctrl_key)); - key_data_value.shift_key.reset(new bool(event.shift_key)); - key_data_value.caps_lock.reset(new bool(event.caps_lock)); + key_data_value.alt_key = std::make_unique<bool>(event.alt_key); + key_data_value.altgr_key = std::make_unique<bool>(event.altgr_key); + key_data_value.ctrl_key = std::make_unique<bool>(event.ctrl_key); + key_data_value.shift_key = std::make_unique<bool>(event.shift_key); + key_data_value.caps_lock = std::make_unique<bool>(event.caps_lock); std::unique_ptr<base::ListValue> args( input_ime::OnKeyEvent::Create(component_id, key_data_value, request_id)); @@ -402,8 +403,9 @@ SendKeyEvents::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(parent_params); const SendKeyEvents::Params::Parameters& params = parent_params->parameters; - std::vector<InputMethodEngineBase::KeyboardEvent> key_data_out; + std::vector<InputMethodEngineBase::KeyboardEvent> key_data_out; + key_data_out.reserve(params.key_data.size()); for (const auto& key_event : params.key_data) { key_data_out.emplace_back(); InputMethodEngineBase::KeyboardEvent& event = key_data_out.back(); @@ -412,6 +414,7 @@ event.code = key_event.code; event.key_code = key_event.key_code.get() ? *(key_event.key_code) : 0; event.alt_key = key_event.alt_key ? *(key_event.alt_key) : false; + event.altgr_key = key_event.altgr_key ? *(key_event.altgr_key) : false; event.ctrl_key = key_event.ctrl_key ? *(key_event.ctrl_key) : false; event.shift_key = key_event.shift_key ? *(key_event.shift_key) : false; event.caps_lock = key_event.caps_lock ? *(key_event.caps_lock) : false;
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/OWNERS b/chrome/browser/extensions/api/webrtc_logging_private/OWNERS index 67620a2..c954e42 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/OWNERS +++ b/chrome/browser/extensions/api/webrtc_logging_private/OWNERS
@@ -1 +1,3 @@ +eladalon@chromium.org grunell@chromium.org +guidou@chromium.org
diff --git a/chrome/browser/metrics/field_trial_synchronizer.cc b/chrome/browser/metrics/field_trial_synchronizer.cc index eca86f0..a4cf830 100644 --- a/chrome/browser/metrics/field_trial_synchronizer.cc +++ b/chrome/browser/metrics/field_trial_synchronizer.cc
@@ -13,6 +13,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" +#include "mojo/public/cpp/bindings/associated_remote.h" using content::BrowserThread; @@ -50,7 +51,8 @@ IPC::ChannelProxy* channel = host->GetChannel(); // channel might be null in tests. if (host->IsInitializedAndNotDead() && channel) { - chrome::mojom::RendererConfigurationAssociatedPtr renderer_configuration; + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration> + renderer_configuration; channel->GetRemoteAssociatedInterface(&renderer_configuration); renderer_configuration->SetFieldTrialGroup(field_trial_name, group_name); }
diff --git a/chrome/browser/net/network_context_configuration_browsertest.cc b/chrome/browser/net/network_context_configuration_browsertest.cc index 2c6a8c5..8819c86 100644 --- a/chrome/browser/net/network_context_configuration_browsertest.cc +++ b/chrome/browser/net/network_context_configuration_browsertest.cc
@@ -64,6 +64,7 @@ #include "net/base/net_errors.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h" +#include "net/cookies/cookie_util.h" #include "net/dns/mock_host_resolver.h" #include "net/http/http_response_headers.h" #include "net/reporting/reporting_policy.h" @@ -201,11 +202,13 @@ kPersistent, }; - NetworkContextConfigurationBrowserTest() { + NetworkContextConfigurationBrowserTest() + : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) { // Have to get a port before setting up the command line, but can only set // up the connection listener after there's a main thread, so can't start // the test server here. EXPECT_TRUE(embedded_test_server()->InitializeAndListen()); + EXPECT_TRUE(https_server()->InitializeAndListen()); } // Returns a cacheable response (10 hours) that is some random text. @@ -240,6 +243,8 @@ embedded_test_server()->RegisterRequestHandler(base::BindRepeating( &NetworkContextConfigurationBrowserTest::HandleCacheRandom)); embedded_test_server()->StartAcceptingConnections(); + net::test_server::RegisterDefaultHandlers(https_server()); + https_server()->StartAcceptingConnections(); if (is_incognito()) incognito_ = CreateIncognitoBrowser(); @@ -282,6 +287,8 @@ .c_str()); } + net::EmbeddedTestServer* https_server() { return &https_server_; } + content::StoragePartition* GetStoragePartition() { return GetStoragePartitionForContextType(GetParam().network_context_type); } @@ -528,18 +535,24 @@ return false; } + // |server| should be |TYPE_HTTPS| if the cookie is third-party, because + // SameSite=None cookies must be Secure. void SetCookie(CookieType cookie_type, - CookiePersistenceType cookie_expiration_type) { + CookiePersistenceType cookie_expiration_type, + net::EmbeddedTestServer* server) { std::unique_ptr<network::ResourceRequest> request = std::make_unique<network::ResourceRequest>(); std::string cookie_line = "cookie"; if (cookie_expiration_type == CookiePersistenceType::kPersistent) cookie_line += ";max-age=3600"; - request->url = embedded_test_server()->GetURL("/set-cookie?" + cookie_line); + // Third party (i.e. SameSite=None) cookies must be secure. + if (cookie_type == CookieType::kThirdParty) + cookie_line += ";SameSite=None;Secure"; + request->url = server->GetURL("/set-cookie?" + cookie_line); if (cookie_type == CookieType::kThirdParty) request->site_for_cookies = GURL("http://example.com"); else - request->site_for_cookies = embedded_test_server()->base_url(); + request->site_for_cookies = server->base_url(); content::SimpleURLLoaderTestHelper simple_loader_helper; std::unique_ptr<network::SimpleURLLoader> simple_loader = network::SimpleURLLoader::Create(std::move(request), @@ -599,7 +612,7 @@ GetNetworkContextForContextType(network_context_type) ->GetCookieManager(cookie_manager.BindNewPipeAndPassReceiver()); cookie_manager->GetCookieList( - url, net::CookieOptions(), + url, net::CookieOptions::MakeAllInclusive(), base::BindOnce( [](std::string* cookies_out, base::RunLoop* run_loop, const net::CookieStatusList& cookies, @@ -734,6 +747,7 @@ Browser* incognito_ = nullptr; base::test::ScopedFeatureList feature_list_; + net::EmbeddedTestServer https_server_; std::unique_ptr<net::test_server::ControllableHttpResponse> controllable_http_response_; @@ -750,6 +764,11 @@ SecureCookiesAllowedForChromeScheme) { if (IsRestartStateWithInProcessNetworkService()) return; + // TODO(crbug.com/1007320): This does not work under SameSiteByDefaultCookies, + // (and also does not work for SameSite cookies, in general). This is not + // easily fixable, so disable the test for now. + if (net::cookie_util::IsSameSiteByDefaultCookiesEnabled()) + return; // Cookies are only allowed for chrome:// schemes requesting a secure origin, // so create an HTTPS server. net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); @@ -757,7 +776,8 @@ ASSERT_TRUE(https_server.Start()); if (GetPrefService()->FindPreference(prefs::kBlockThirdPartyCookies)) GetPrefService()->SetBoolean(prefs::kBlockThirdPartyCookies, true); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent, + embedded_test_server()); std::unique_ptr<network::ResourceRequest> request = std::make_unique<network::ResourceRequest>(); @@ -805,7 +825,8 @@ ASSERT_TRUE(test_server.Start()); GetPrefService()->SetBoolean(prefs::kBlockThirdPartyCookies, true); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent, + embedded_test_server()); extensions::TestExtensionDir extension_dir; extension_dir.WriteManifest(R"({ @@ -825,6 +846,10 @@ loader.LoadExtension(extension_dir.UnpackedPath()); ASSERT_TRUE(extension); + // This request will show up as cross-site because the chrome-extension URL + // won't match the test_server domain (127.0.0.1), but because we set + // |attach_same_site_cookies| to true for extension-initiated requests, this + // will actually be able to get the cookie. GURL url = test_server.GetURL("/echocookieheader"); std::string script = R"((url => { var xhr = new XMLHttpRequest(); @@ -1401,7 +1426,8 @@ return; EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty()); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent, + embedded_test_server()); EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty()); } @@ -1423,7 +1449,8 @@ CookieIsolation) { if (IsRestartStateWithInProcessNetworkService()) return; - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kPersistent, + embedded_test_server()); EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty()); ForEachOtherContext( @@ -1447,9 +1474,10 @@ return; GetPrefService()->SetBoolean(prefs::kBlockThirdPartyCookies, true); - SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession); + SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession, + https_server()); - EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty()); + EXPECT_TRUE(GetCookies(https_server()->base_url()).empty()); } IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, @@ -1472,15 +1500,18 @@ // The kBlockThirdPartyCookies pref should carry over to the next session. EXPECT_TRUE(GetPrefService()->GetBoolean(prefs::kBlockThirdPartyCookies)); - SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession); + SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession, + https_server()); - EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty()); + EXPECT_TRUE(GetCookies(https_server()->base_url()).empty()); // Set pref to false, third party cookies should be allowed now. GetPrefService()->SetBoolean(prefs::kBlockThirdPartyCookies, false); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession); + // Set a third-party cookie. It should actually get set this time. + SetCookie(CookieType::kThirdParty, CookiePersistenceType::kSession, + https_server()); - EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty()); + EXPECT_FALSE(GetCookies(https_server()->base_url()).empty()); } IN_PROC_BROWSER_TEST_P(NetworkContextConfigurationBrowserTest, @@ -1498,7 +1529,8 @@ CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK); FlushNetworkInterface(); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession, + embedded_test_server()); EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty()); } @@ -1515,7 +1547,8 @@ return; // The content settings should carry over to the next session. - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession, + embedded_test_server()); EXPECT_TRUE(GetCookies(embedded_test_server()->base_url()).empty()); @@ -1523,7 +1556,8 @@ CookieSettingsFactory::GetForProfile(browser()->profile()) ->SetDefaultCookieSetting(CONTENT_SETTING_ALLOW); FlushNetworkInterface(); - SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession); + SetCookie(CookieType::kFirstParty, CookiePersistenceType::kSession, + embedded_test_server()); EXPECT_FALSE(GetCookies(embedded_test_server()->base_url()).empty()); }
diff --git a/chrome/browser/payments/payment_request_factory.cc b/chrome/browser/payments/payment_request_factory.cc index 22d1d01e..bdebbf0 100644 --- a/chrome/browser/payments/payment_request_factory.cc +++ b/chrome/browser/payments/payment_request_factory.cc
@@ -16,9 +16,9 @@ namespace { -using PaymentRequestFactoryCallback = - base::RepeatingCallback<void(mojom::PaymentRequestRequest request, - content::RenderFrameHost* render_frame_host)>; +using PaymentRequestFactoryCallback = base::RepeatingCallback<void( + mojo::PendingReceiver<mojom::PaymentRequest> receiver, + content::RenderFrameHost* render_frame_host)>; PaymentRequestFactoryCallback& GetTestingFactoryCallback() { static base::NoDestructor<PaymentRequestFactoryCallback> callback; @@ -27,10 +27,11 @@ } // namespace -void CreatePaymentRequest(mojom::PaymentRequestRequest request, - content::RenderFrameHost* render_frame_host) { +void CreatePaymentRequest( + content::RenderFrameHost* render_frame_host, + mojo::PendingReceiver<mojom::PaymentRequest> receiver) { if (GetTestingFactoryCallback()) { - return GetTestingFactoryCallback().Run(std::move(request), + return GetTestingFactoryCallback().Run(std::move(receiver), render_frame_host); } @@ -42,7 +43,7 @@ ->CreatePaymentRequest( render_frame_host, web_contents, std::make_unique<ChromePaymentRequestDelegate>(web_contents), - std::move(request), + std::move(receiver), /*observer_for_testing=*/nullptr); }
diff --git a/chrome/browser/payments/payment_request_factory.h b/chrome/browser/payments/payment_request_factory.h index 44046b4..162b7adf 100644 --- a/chrome/browser/payments/payment_request_factory.h +++ b/chrome/browser/payments/payment_request_factory.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_FACTORY_H_ #define CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_FACTORY_H_ +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom.h" namespace content { @@ -13,19 +14,20 @@ namespace payments { -// Will create a PaymentRequest based on the contents of |request|. The -// |request| was initiated by the frame hosted by |render_frame_host|, which is +// Will create a PaymentRequest based on the contents of |receiver|. The +// |receiver| was initiated by the frame hosted by |render_frame_host|, which is // inside of |web_contents|. This function is called every time a new instance // of PaymentRequest is created in the renderer. -void CreatePaymentRequest(mojom::PaymentRequestRequest request, - content::RenderFrameHost* render_frame_host); +void CreatePaymentRequest( + content::RenderFrameHost* render_frame_host, + mojo::PendingReceiver<mojom::PaymentRequest> receiver); // Unit tests should clean up this factory override by giving a null callback so // as to not interfere with other tests. void SetPaymentRequestFactoryForTesting( - base::RepeatingCallback<void(mojom::PaymentRequestRequest request, - content::RenderFrameHost* render_frame_host)> - factory_callback); + base::RepeatingCallback< + void(mojo::PendingReceiver<mojom::PaymentRequest> receiver, + content::RenderFrameHost* render_frame_host)> factory_callback); } // namespace payments
diff --git a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc index f2095ab0..b43a568 100644 --- a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc +++ b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc
@@ -17,7 +17,8 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/render_process_host.h" #include "extensions/buildflags/buildflags.h" -#include "mojo/public/cpp/bindings/strong_associated_binding.h" +#include "mojo/public/cpp/bindings/pending_associated_receiver.h" +#include "mojo/public/cpp/bindings/self_owned_associated_receiver.h" #include "ppapi/host/ppapi_host.h" #include "ppapi/shared_impl/ppapi_switches.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -35,7 +36,7 @@ namespace { void BindPluginInfoHost( int render_process_id, - chrome::mojom::PluginInfoHostAssociatedRequest request) { + mojo::PendingAssociatedReceiver<chrome::mojom::PluginInfoHost> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* host = content::RenderProcessHost::FromID(render_process_id); @@ -43,9 +44,9 @@ return; Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext()); - mojo::MakeStrongAssociatedBinding( + mojo::MakeSelfOwnedAssociatedReceiver( std::make_unique<PluginInfoHostImpl>(render_process_id, profile), - std::move(request)); + std::move(receiver)); } } // namespace
diff --git a/chrome/browser/plugins/plugin_observer.cc b/chrome/browser/plugins/plugin_observer.cc index ec8d219..894d29f1 100644 --- a/chrome/browser/plugins/plugin_observer.cc +++ b/chrome/browser/plugins/plugin_observer.cc
@@ -38,6 +38,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/common/webplugininfo.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "ui/base/l10n/l10n_util.h" @@ -51,36 +52,37 @@ PluginObserver* observer, base::string16 plugin_name, PluginInstaller* installer, - chrome::mojom::PluginRendererPtr plugin_renderer_interface) + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer_remote) : PluginInstallerObserver(installer), observer_(observer), - plugin_renderer_interface_(std::move(plugin_renderer_interface)) { - plugin_renderer_interface_.set_connection_error_handler( + plugin_renderer_remote_(std::move(plugin_renderer_remote)) { + plugin_renderer_remote_.set_disconnect_handler( base::Bind(&PluginObserver::RemovePluginPlaceholderHost, base::Unretained(observer_), this)); DCHECK(installer); } void DownloadFinished() override { - plugin_renderer_interface_->FinishedDownloading(); + plugin_renderer_remote_->FinishedDownloading(); } private: PluginObserver* observer_; - chrome::mojom::PluginRendererPtr plugin_renderer_interface_; + mojo::Remote<chrome::mojom::PluginRenderer> plugin_renderer_remote_; }; class PluginObserver::ComponentObserver : public update_client::UpdateClient::Observer { public: using Events = update_client::UpdateClient::Observer::Events; - ComponentObserver(PluginObserver* observer, - const std::string& component_id, - chrome::mojom::PluginRendererPtr plugin_renderer_interface) + ComponentObserver( + PluginObserver* observer, + const std::string& component_id, + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer_remote) : observer_(observer), component_id_(component_id), - plugin_renderer_interface_(std::move(plugin_renderer_interface)) { - plugin_renderer_interface_.set_connection_error_handler( + plugin_renderer_remote_(std::move(plugin_renderer_remote)) { + plugin_renderer_remote_.set_disconnect_handler( base::Bind(&PluginObserver::RemoveComponentObserver, base::Unretained(observer_), this)); g_browser_process->component_updater()->AddObserver(this); @@ -99,15 +101,15 @@ return; switch (event) { case Events::COMPONENT_UPDATED: - plugin_renderer_interface_->UpdateSuccess(); + plugin_renderer_remote_->UpdateSuccess(); observer_->RemoveComponentObserver(this); break; case Events::COMPONENT_UPDATE_FOUND: - plugin_renderer_interface_->UpdateDownloading(); + plugin_renderer_remote_->UpdateDownloading(); break; case Events::COMPONENT_NOT_UPDATED: case Events::COMPONENT_UPDATE_ERROR: - plugin_renderer_interface_->UpdateFailure(); + plugin_renderer_remote_->UpdateFailure(); observer_->RemoveComponentObserver(this); break; default: @@ -119,7 +121,7 @@ private: PluginObserver* observer_; std::string component_id_; - chrome::mojom::PluginRendererPtr plugin_renderer_interface_; + mojo::Remote<chrome::mojom::PluginRenderer> plugin_renderer_remote_; DISALLOW_COPY_AND_ASSIGN(ComponentObserver); }; @@ -193,7 +195,7 @@ } void PluginObserver::BlockedOutdatedPlugin( - chrome::mojom::PluginRendererPtr plugin_renderer, + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer, const std::string& identifier) { PluginFinder* finder = PluginFinder::GetInstance(); // Find plugin to update. @@ -214,7 +216,7 @@ } void PluginObserver::BlockedComponentUpdatedPlugin( - chrome::mojom::PluginRendererPtr plugin_renderer, + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer, const std::string& identifier) { auto component_observer = std::make_unique<ComponentObserver>( this, identifier, std::move(plugin_renderer));
diff --git a/chrome/browser/plugins/plugin_observer.h b/chrome/browser/plugins/plugin_observer.h index cfadf1f..88b6fb9 100644 --- a/chrome/browser/plugins/plugin_observer.h +++ b/chrome/browser/plugins/plugin_observer.h
@@ -18,6 +18,7 @@ #include "content/public/browser/web_contents_binding_set.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" +#include "mojo/public/cpp/bindings/pending_remote.h" class InfoBarService; @@ -47,10 +48,11 @@ explicit PluginObserver(content::WebContents* web_contents); // chrome::mojom::PluginHost methods. - void BlockedOutdatedPlugin(chrome::mojom::PluginRendererPtr plugin_renderer, - const std::string& identifier) override; + void BlockedOutdatedPlugin( + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer, + const std::string& identifier) override; void BlockedComponentUpdatedPlugin( - chrome::mojom::PluginRendererPtr plugin_renderer, + mojo::PendingRemote<chrome::mojom::PluginRenderer> plugin_renderer, const std::string& identifier) override; void ShowFlashPermissionBubble() override; void CouldNotLoadPlugin(const base::FilePath& plugin_path) override;
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 31848eb6..9c85889 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -677,6 +677,9 @@ { key::kDeviceLoginScreenMonoAudioEnabled, nullptr, base::Value::Type::BOOLEAN }, + { key::kDeviceLoginScreenAutoclickEnabled, + nullptr, + base::Value::Type::BOOLEAN }, { key::kRebootAfterUpdate, prefs::kRebootAfterUpdate, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/profiles/profile_avatar_icon_util.cc b/chrome/browser/profiles/profile_avatar_icon_util.cc index 08dda10ca2..c102c45 100644 --- a/chrome/browser/profiles/profile_avatar_icon_util.cc +++ b/chrome/browser/profiles/profile_avatar_icon_util.cc
@@ -19,6 +19,7 @@ #include "base/values.h" #include "build/build_config.h" #include "cc/paint/paint_flags.h" +#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/grit/generated_resources.h" @@ -30,10 +31,12 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" +#include "ui/gfx/color_palette.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/image/canvas_image_source.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_operations.h" +#include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/skia_util.h" #include "url/url_canon.h" @@ -329,6 +332,11 @@ constexpr size_t kPlaceholderAvatarIndex = 0; #endif +gfx::ImageSkia GetGuestAvatar(int size) { + return gfx::CreateVectorIcon(kUserAccountAvatarIcon, size, + gfx::kGoogleGrey500); +} + gfx::Image GetSizedAvatarIcon(const gfx::Image& image, bool is_rectangle, int width,
diff --git a/chrome/browser/profiles/profile_avatar_icon_util.h b/chrome/browser/profiles/profile_avatar_icon_util.h index 9a1e0d8..f155b135 100644 --- a/chrome/browser/profiles/profile_avatar_icon_util.h +++ b/chrome/browser/profiles/profile_avatar_icon_util.h
@@ -13,6 +13,7 @@ #include "build/build_config.h" #include "third_party/skia/include/core/SkColor.h" +#include "ui/gfx/image/image_skia.h" namespace base { class FilePath; @@ -55,6 +56,9 @@ SHAPE_SQUARE, }; +// Returns the default guest avatar. +gfx::ImageSkia GetGuestAvatar(int size = 256); + // Returns a version of |image| of a specific size. Note that no checks are // done on the width/height so make sure they're reasonable values; in the // range of 16-256 is probably best.
diff --git a/chrome/browser/profiles/renderer_updater.cc b/chrome/browser/profiles/renderer_updater.cc index 9dd4252..e0e76c1a 100644 --- a/chrome/browser/profiles/renderer_updater.cc +++ b/chrome/browser/profiles/renderer_updater.cc
@@ -17,6 +17,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "extensions/buildflags/buildflags.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "services/network/public/cpp/features.h" #if defined(OS_CHROMEOS) @@ -125,16 +126,17 @@ Profile::FromBrowserContext(render_process_host->GetBrowserContext()); bool is_incognito_process = profile->IsOffTheRecord(); - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request; + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver; #if defined(OS_CHROMEOS) if (merge_session_running_) { - chrome::mojom::ChromeOSListenerPtr chromeos_listener; - chromeos_listener_request = MakeRequest(&chromeos_listener); + mojo::Remote<chrome::mojom::ChromeOSListener> chromeos_listener; + chromeos_listener_receiver = chromeos_listener.BindNewPipeAndPassReceiver(); chromeos_listeners_.push_back(std::move(chromeos_listener)); } #endif // defined(OS_CHROMEOS) renderer_configuration->SetInitialConfiguration( - is_incognito_process, std::move(chromeos_listener_request)); + is_incognito_process, std::move(chromeos_listener_receiver)); UpdateRenderer(&renderer_configuration); @@ -152,9 +154,9 @@ renderer_configuration->SetContentSettingRules(rules); } -std::vector<chrome::mojom::RendererConfigurationAssociatedPtr> +std::vector<mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>> RendererUpdater::GetRendererConfigurations() { - std::vector<chrome::mojom::RendererConfigurationAssociatedPtr> rv; + std::vector<mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>> rv; for (content::RenderProcessHost::iterator it( content::RenderProcessHost::AllHostsIterator()); !it.IsAtEnd(); it.Advance()) { @@ -171,14 +173,15 @@ return rv; } -chrome::mojom::RendererConfigurationAssociatedPtr +mojo::AssociatedRemote<chrome::mojom::RendererConfiguration> RendererUpdater::GetRendererConfiguration( content::RenderProcessHost* render_process_host) { IPC::ChannelProxy* channel = render_process_host->GetChannel(); if (!channel) - return nullptr; + return mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>(); - chrome::mojom::RendererConfigurationAssociatedPtr renderer_configuration; + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration> + renderer_configuration; channel->GetRemoteAssociatedInterface(&renderer_configuration); return renderer_configuration; } @@ -222,7 +225,8 @@ } void RendererUpdater::UpdateRenderer( - chrome::mojom::RendererConfigurationAssociatedPtr* renderer_configuration) { + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>* + renderer_configuration) { (*renderer_configuration) ->SetConfiguration(chrome::mojom::DynamicParams::New( force_google_safesearch_.GetValue(),
diff --git a/chrome/browser/profiles/renderer_updater.h b/chrome/browser/profiles/renderer_updater.h index 9c92a09..a043acf 100644 --- a/chrome/browser/profiles/renderer_updater.h +++ b/chrome/browser/profiles/renderer_updater.h
@@ -16,6 +16,8 @@ #include "components/prefs/pref_member.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/variations/variations_http_header_provider.h" +#include "mojo/public/cpp/bindings/associated_remote.h" +#include "mojo/public/cpp/bindings/remote.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/signin/oauth2_login_manager.h" @@ -46,11 +48,11 @@ void InitializeRenderer(content::RenderProcessHost* render_process_host); private: - std::vector<chrome::mojom::RendererConfigurationAssociatedPtr> + std::vector<mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>> GetRendererConfigurations(); - chrome::mojom::RendererConfigurationAssociatedPtr GetRendererConfiguration( - content::RenderProcessHost* render_process_host); + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration> + GetRendererConfiguration(content::RenderProcessHost* render_process_host); #if defined(OS_CHROMEOS) // chromeos::OAuth2LoginManager::Observer: @@ -72,15 +74,17 @@ void UpdateAllRenderers(); // Update the given renderer due to a configuration change. - void UpdateRenderer(chrome::mojom::RendererConfigurationAssociatedPtr* - renderer_configuration); + void UpdateRenderer( + mojo::AssociatedRemote<chrome::mojom::RendererConfiguration>* + renderer_configuration); Profile* profile_; PrefChangeRegistrar pref_change_registrar_; #if defined(OS_CHROMEOS) chromeos::OAuth2LoginManager* oauth2_login_manager_; bool merge_session_running_; - std::vector<chrome::mojom::ChromeOSListenerPtr> chromeos_listeners_; + std::vector<mojo::Remote<chrome::mojom::ChromeOSListener>> + chromeos_listeners_; #endif variations::VariationsHttpHeaderProvider* variations_http_header_provider_;
diff --git a/chrome/browser/referrer_policy_browsertest.cc b/chrome/browser/referrer_policy_browsertest.cc index 5c830b03..154ac07 100644 --- a/chrome/browser/referrer_policy_browsertest.cc +++ b/chrome/browser/referrer_policy_browsertest.cc
@@ -7,7 +7,9 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h" #include "chrome/browser/ui/browser.h" @@ -23,9 +25,11 @@ #include "content/public/browser/notification_service.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" +#include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_test_utils.h" +#include "services/network/public/cpp/features.h" #include "third_party/blink/public/platform/web_input_event.h" class ReferrerPolicyTest : public InProcessBrowserTest { @@ -210,6 +214,18 @@ net::EmbeddedTestServer https_server_; }; +class ReferrerPolicyCapReferrerToOriginOnCrossOriginTest + : public ReferrerPolicyTest { + public: + ReferrerPolicyCapReferrerToOriginOnCrossOriginTest() { + scoped_feature_list_.InitAndEnableFeature( + network::features::kCapReferrerToOriginOnCrossOrigin); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + class ReferrerPolicyWithReduceReferrerGranularityFlagTest : public ReferrerPolicyTest { public: @@ -668,3 +684,99 @@ blink::WebMouseEvent::Button::kLeft, EXPECT_ORIGIN_AS_REFERRER, expected_referrer_policy); } + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly defers to a more restrictive referrer policy on a +// cross-origin navigation. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + HonorsMoreRestrictivePolicyOnNavigation) { + RunReferrerTest(network::mojom::ReferrerPolicy::kSameOrigin, START_ON_HTTPS, + REGULAR_LINK, NO_REDIRECT /*direct navigation x-origin*/, + WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_EMPTY_REFERRER); +} + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly overrides a less restrictive referrer policy on a +// cross-origin navigation. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + CorrectlyOverridesOnNavigation) { + RunReferrerTest(network::mojom::ReferrerPolicy::kAlways, START_ON_HTTPS, + REGULAR_LINK, NO_REDIRECT /*direct navigation x-origin*/, + WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, + EXPECT_ORIGIN_AS_REFERRER); +} + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly defers to a more restrictive referrer policy on a +// cross-origin redirect. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + HonorsMoreRestrictivePolicyOnRedirect) { + RunReferrerTest(network::mojom::ReferrerPolicy::kStrictOrigin, START_ON_HTTPS, + REGULAR_LINK, SERVER_REDIRECT_FROM_HTTPS_TO_HTTP, + WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_EMPTY_REFERRER); +} + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly overrides a less restrictive referrer policy on a +// cross-origin redirect. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + CorrectlyOverridesOnRedirect) { + RunReferrerTest( + network::mojom::ReferrerPolicy::kAlways, START_ON_HTTP, REGULAR_LINK, + SERVER_REDIRECT_FROM_HTTP_TO_HTTPS, WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_ORIGIN_AS_REFERRER); +} + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly respects a less restrictive referrer policy on a +// same-origin navigation. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + DeclinesToOverrideOnSameOriginNavigation) { + RunReferrerTest(network::mojom::ReferrerPolicy::kAlways, START_ON_HTTP, + REGULAR_LINK, NO_REDIRECT /*direct navigation same-origin*/, + WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_FULL_REFERRER); +} + +// Test that capping referrer granularity at origin on cross-origin requests +// correctly respects a less restrictive referrer policy on a +// same-origin redirect. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + DeclinesToOverrideOnSameOriginRedirect) { + RunReferrerTest(network::mojom::ReferrerPolicy::kAlways, START_ON_HTTP, + REGULAR_LINK, SERVER_REDIRECT_FROM_HTTP_TO_HTTP, + WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_FULL_REFERRER); +} + +// Test that, when capping referrer granularity at origin on cross-origin +// requests, the referrer remains truncated if we're redirected back +// to the initiating origin. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + OverrideMaintainedOnRedirectBackToOriginalOrigin) { + RunReferrerTest( + network::mojom::ReferrerPolicy::kAlways, START_ON_HTTPS, REGULAR_LINK, + SERVER_REDIRECT_FROM_HTTP_TO_HTTPS, WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_ORIGIN_AS_REFERRER); +} + +// Test that, when the cross-origin referrer cap is on but we also have the +// "no referrers at all" pref set, we send no referrer at all on cross-origin +// requests. +IN_PROC_BROWSER_TEST_F(ReferrerPolicyCapReferrerToOriginOnCrossOriginTest, + RespectsNoReferrerPref) { + browser()->profile()->GetPrefs()->SetBoolean(prefs::kEnableReferrers, false); + content::BrowserContext::GetDefaultStoragePartition(browser()->profile()) + ->FlushNetworkInterfaceForTesting(); + RunReferrerTest(network::mojom::ReferrerPolicy::kAlways, START_ON_HTTPS, + REGULAR_LINK, NO_REDIRECT, WindowOpenDisposition::CURRENT_TAB, + blink::WebMouseEvent::Button::kLeft, EXPECT_EMPTY_REFERRER, + // when the pref is set, the renderer sets the referrer policy + // to the default on outgoing requests at the same time + // it removes referrers + content::Referrer::NetReferrerPolicyToBlinkReferrerPolicy( + content::Referrer::GetDefaultReferrerPolicy())); +}
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc index fe0c19c..df2fa35 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.cc
@@ -59,7 +59,7 @@ private: static void DispatchNonPersistentNotificationCreated( WebContentsProxy contents_proxy, - int64_t navigation_id); + const url::Origin& origin); // Binds to the task runner where the object is constructed. scoped_refptr<base::SequencedTaskRunner> destination_task_runner_; @@ -314,9 +314,10 @@ const performance_manager::PageNode* page_node = frame_node->GetPageNode(); destination_task_runner_->PostTask( FROM_HERE, - base::BindOnce(&GraphObserver::DispatchNonPersistentNotificationCreated, - page_node->GetContentsProxy(), - page_node->GetNavigationID())); + base::BindOnce( + &GraphObserver::DispatchNonPersistentNotificationCreated, + page_node->GetContentsProxy(), + url::Origin::Create(page_node->GetMainFrameUrl().GetOrigin()))); } namespace { @@ -324,15 +325,12 @@ // Return the WCO if notification is not late, and it's available. LocalSiteCharacteristicsWebContentsObserver* MaybeGetWCO( performance_manager::WebContentsProxy contents_proxy, - int64_t navigation_id) { - // Bail if this is a late notification. - if (contents_proxy.LastNavigationId() != navigation_id) - return nullptr; - - // The proxy is guaranteed to dereference if the navigation ID above was - // valid. + const url::Origin& origin) { content::WebContents* web_contents = contents_proxy.Get(); - DCHECK(web_contents); + // The WC may be dead by the time the task posted from the PM sequence arrives + // on the UI thread. + if (!web_contents) + return nullptr; // The L41r is not itself WebContentsUserData, but rather stored on // the RC TabHelper, so retrieve that first - if available. @@ -341,7 +339,11 @@ if (!rc_th) return nullptr; - return rc_th->local_site_characteristics_wc_observer(); + auto* wco = rc_th->local_site_characteristics_wc_observer(); + if (wco->writer_origin() != origin) + return nullptr; + + return wco; } } // namespace @@ -349,8 +351,8 @@ // static void LocalSiteCharacteristicsWebContentsObserver::GraphObserver:: DispatchNonPersistentNotificationCreated(WebContentsProxy contents_proxy, - int64_t navigation_id) { - if (auto* wco = MaybeGetWCO(contents_proxy, navigation_id)) + const url::Origin& origin) { + if (auto* wco = MaybeGetWCO(contents_proxy, origin)) wco->OnNonPersistentNotificationCreated(); }
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h index c9094ba..52da89c7 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer.h
@@ -51,11 +51,11 @@ LoadingState old_loading_state, LoadingState new_loading_state) override; + const url::Origin& writer_origin() const { return writer_origin_; } SiteCharacteristicsDataWriter* GetWriterForTesting() const { return writer_.get(); } - url::Origin GetWriterOriginForTesting() const { return writer_origin_; } void ResetWriterForTesting() { writer_.reset(); } private:
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc index 864c05c1..399339e 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_webcontents_observer_unittest.cc
@@ -140,7 +140,7 @@ MockDataWriter* mock_writer = NavigateAndReturnMockWriter(kTestUrl1); EXPECT_TRUE(mock_writer); - auto writer_origin = observer()->GetWriterOriginForTesting(); + auto writer_origin = observer()->writer_origin(); EXPECT_EQ(url::Origin::Create(kTestUrl1), writer_origin); @@ -162,8 +162,8 @@ mock_writer = NavigateAndReturnMockWriter(kTestUrl2); ::testing::Mock::VerifyAndClear(mock_writer); - EXPECT_FALSE(writer_origin == observer()->GetWriterOriginForTesting()); - writer_origin = observer()->GetWriterOriginForTesting(); + EXPECT_FALSE(writer_origin == observer()->writer_origin()); + writer_origin = observer()->writer_origin(); EXPECT_EQ(url::Origin::Create(kTestUrl2), mock_writer->Origin());
diff --git a/chrome/browser/resources/chromeos/machine_learning/machine_learning_internals.js b/chrome/browser/resources/chromeos/machine_learning/machine_learning_internals.js index 04ce3e0..8e36bac 100644 --- a/chrome/browser/resources/chromeos/machine_learning/machine_learning_internals.js +++ b/chrome/browser/resources/chromeos/machine_learning/machine_learning_internals.js
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -const ModelId = chromeos.machineLearning.mojom.ModelId; +const BuiltinModelId = chromeos.machineLearning.mojom.BuiltinModelId; const LoadModelResult = chromeos.machineLearning.mojom.LoadModelResult; const CreateGraphExecutorResult = chromeos.machineLearning.mojom.CreateGraphExecutorResult; @@ -18,18 +18,18 @@ */ this.pageHandler = chromeos.machineLearning.mojom.PageHandler.getRemote(); /** - * @private {!Map<ModelId, + * @private {!Map<BuiltinModelId, * !chromeos.machineLearning.mojom.GraphExecutorRemote>} */ this.modelMap_ = new Map(); } /** - * @param {!ModelId} modelId Model to load. + * @param {!BuiltinModelId} modelId Model to load. * @return * {!Promise<!chromeos.machineLearning.mojom.GraphExecutorRemote>} A - * promise that resolves when loadModel and createGraphExecutor both - * succeed. + * promise that resolves when loadBuiltinModel and createGraphExecutor + * both succeed. */ async prepareModel(modelId) { if (this.modelMap_.has(modelId)) { @@ -38,12 +38,12 @@ const modelSpec = {id: modelId}; /** @type {chromeos.machineLearning.mojom.ModelRemote} */ const model = new chromeos.machineLearning.mojom.ModelRemote(); - const {result: loadModelResult} = await this.pageHandler.loadModel( + const {result: loadModelResult} = await this.pageHandler.loadBuiltinModel( modelSpec, model.$.bindNewPipeAndPassReceiver()); if (loadModelResult != LoadModelResult.OK) { const error = machine_learning_internals.utils.enumToString( loadModelResult, LoadModelResult); - throw new Error(`LoadModel failed! Error: ${error}.`); + throw new Error(`LoadBuiltinModel failed! Error: ${error}.`); } /** @type {chromeos.machineLearning.mojom.GraphExecutorRemote} */ const graphExecutor =
diff --git a/chrome/browser/resources/chromeos/machine_learning/test_model_tab.js b/chrome/browser/resources/chromeos/machine_learning/test_model_tab.js index 05fc706..5365e0e 100644 --- a/chrome/browser/resources/chromeos/machine_learning/test_model_tab.js +++ b/chrome/browser/resources/chromeos/machine_learning/test_model_tab.js
@@ -23,7 +23,7 @@ */ const testModelGraphExecutor = await machine_learning_internals.BrowserProxy.getInstance() - .prepareModel(ModelId.TEST_MODEL); + .prepareModel(BuiltinModelId.TEST_MODEL); $('test-model-status').textContent = 'Model loaded successfully!'; $('test-status').textContent = '';
diff --git a/chrome/browser/resources/print_preview/data/destination.js b/chrome/browser/resources/print_preview/data/destination.js index 403becb..bfd894d 100644 --- a/chrome/browser/resources/print_preview/data/destination.js +++ b/chrome/browser/resources/print_preview/data/destination.js
@@ -95,6 +95,17 @@ let VendorCapabilitySelectOption; /** + * Same as cloud_devices::printer::TypedValueVendorCapability::ValueType. + * @enum {string} + */ + const VendorCapabilityValueType = { + BOOLEAN: 'BOOLEAN', + FLOAT: 'FLOAT', + INTEGER: 'INTEGER', + STRING: 'STRING', + }; + + /** * Specifies a custom vendor capability. * @typedef {{ * id: (string), @@ -106,6 +117,7 @@ * }|undefined), * typed_value_cap: ({ * default: (number | string | boolean | undefined), + * value_type: (print_preview.VendorCapabilityValueType | undefined), * }|undefined), * range_cap: ({ * default: (number), @@ -966,6 +978,7 @@ makeRecentDestination: makeRecentDestination, RecentDestination: RecentDestination, VendorCapabilitySelectOption: VendorCapabilitySelectOption, + VendorCapabilityValueType: VendorCapabilityValueType, VendorCapability: VendorCapability, // <if expr="chromeos">
diff --git a/chrome/browser/resources/print_preview/ui/advanced_settings_item.html b/chrome/browser/resources/print_preview/ui/advanced_settings_item.html index 2dd7432..396e852 100644 --- a/chrome/browser/resources/print_preview/ui/advanced_settings_item.html +++ b/chrome/browser/resources/print_preview/ui/advanced_settings_item.html
@@ -1,6 +1,7 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_checkbox/cr_checkbox.html"> <link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html"> <link rel="import" href="chrome://resources/cr_elements/search_highlight_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> @@ -76,11 +77,16 @@ </select> </div> </template> - <span hidden$="[[isCapabilityTypeSelect_(capability)]]"> + <span hidden$="[[!isCapabilityTypeInput_(capability)]]"> <cr-input type="text" on-input="onUserInput_" spellcheck="false" placeholder="[[getCapabilityPlaceholder_(capability)]]"> </cr-input> </span> + <span hidden$="[[!isCapabilityTypeCheckbox_(capability)]]"> + <cr-checkbox on-change="onCheckboxInput_" + checked="[[isChecked_(currentValue_)]]"> + </cr-checkbox> + </span> </div> </template> <script src="advanced_settings_item.js"></script>
diff --git a/chrome/browser/resources/print_preview/ui/advanced_settings_item.js b/chrome/browser/resources/print_preview/ui/advanced_settings_item.js index 4b01e0e..56450e9 100644 --- a/chrome/browser/resources/print_preview/ui/advanced_settings_item.js +++ b/chrome/browser/resources/print_preview/ui/advanced_settings_item.js
@@ -67,6 +67,33 @@ }, /** + * @return {boolean} Whether the capability represented by this item is + * of type checkbox. + * @private + */ + isCapabilityTypeCheckbox_: function() { + return this.capability.type == 'TYPED_VALUE' && + this.capability.typed_value_cap.value_type == 'BOOLEAN'; + }, + + /** + * @return {boolean} Whether the capability represented by this item is + * of type input. + * @private + */ + isCapabilityTypeInput_: function() { + return !this.isCapabilityTypeSelect_() && !this.isCapabilityTypeCheckbox_(); + }, + + /** + * @return {boolean} Whether the checkbox setting is checked. + * @private + */ + isChecked_: function() { + return this.currentValue_ == 'true'; + }, + + /** * @param {!print_preview.VendorCapabilitySelectOption} option The option * for a select capability. * @return {boolean} Whether the option is selected. @@ -137,6 +164,14 @@ }, /** + * @param {!Event} e Event containing the new value. + * @private + */ + onCheckboxInput_: function(e) { + this.currentValue_ = e.target.checked ? 'true' : 'false'; + }, + + /** * @return {string} The current value of the setting, or the empty string if * it is not set. */
diff --git a/chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer_unittest.cc b/chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer_unittest.cc index ce7e8a4..3a1d715 100644 --- a/chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer_unittest.cc +++ b/chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer_unittest.cc
@@ -50,7 +50,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/click_to_call/click_to_call_ui_controller_unittest.cc b/chrome/browser/sharing/click_to_call/click_to_call_ui_controller_unittest.cc index 3ea339f..e65fd3b 100644 --- a/chrome/browser/sharing/click_to_call/click_to_call_ui_controller_unittest.cc +++ b/chrome/browser/sharing/click_to_call/click_to_call_ui_controller_unittest.cc
@@ -43,7 +43,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc b/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc index c643179c..2d53bb1 100644 --- a/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc +++ b/chrome/browser/sharing/click_to_call/click_to_call_utils_unittest.cc
@@ -41,7 +41,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/shared_clipboard/shared_clipboard_context_menu_observer_unittest.cc b/chrome/browser/sharing/shared_clipboard/shared_clipboard_context_menu_observer_unittest.cc index 4efff24..3cc8a81 100644 --- a/chrome/browser/sharing/shared_clipboard/shared_clipboard_context_menu_observer_unittest.cc +++ b/chrome/browser/sharing/shared_clipboard/shared_clipboard_context_menu_observer_unittest.cc
@@ -46,7 +46,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_desktop_unittest.cc b/chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_desktop_unittest.cc index 7850885..1a9641a 100644 --- a/chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_desktop_unittest.cc +++ b/chrome/browser/sharing/shared_clipboard/shared_clipboard_message_handler_desktop_unittest.cc
@@ -31,6 +31,7 @@ explicit MockSharingService( NotificationDisplayService* notification_display_service) : SharingService( + /* pref_service= */ nullptr, /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr,
diff --git a/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc b/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc index 87c2015..b515573 100644 --- a/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc +++ b/chrome/browser/sharing/shared_clipboard/shared_clipboard_ui_controller_unittest.cc
@@ -43,7 +43,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/shared_clipboard/shared_clipboard_utils_unittest.cc b/chrome/browser/sharing/shared_clipboard/shared_clipboard_utils_unittest.cc index 312c313..b749697 100644 --- a/chrome/browser/sharing/shared_clipboard/shared_clipboard_utils_unittest.cc +++ b/chrome/browser/sharing/shared_clipboard/shared_clipboard_utils_unittest.cc
@@ -37,7 +37,8 @@ class MockSharingService : public SharingService { public: explicit MockSharingService(std::unique_ptr<SharingFCMHandler> fcm_handler) - : SharingService(/* sync_prefs= */ nullptr, + : SharingService(/* pref_service= */ nullptr, + /* sync_prefs= */ nullptr, /* vapid_key_manager= */ nullptr, /* sharing_device_registration= */ nullptr, /* fcm_sender= */ nullptr,
diff --git a/chrome/browser/sharing/sharing_device_registration.cc b/chrome/browser/sharing/sharing_device_registration.cc index 1c58c20..8a00e676 100644 --- a/chrome/browser/sharing/sharing_device_registration.cc +++ b/chrome/browser/sharing/sharing_device_registration.cc
@@ -17,8 +17,10 @@ #include "chrome/browser/sharing/sharing_device_registration_result.h" #include "chrome/browser/sharing/sharing_sync_preference.h" #include "chrome/browser/sharing/vapid_key_manager.h" +#include "chrome/common/pref_names.h" #include "components/gcm_driver/crypto/p256_key_util.h" #include "components/gcm_driver/instance_id/instance_id_driver.h" +#include "components/prefs/pref_service.h" #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/local_device_info_provider.h" #include "crypto/ec_private_key.h" @@ -31,11 +33,13 @@ using sync_pb::SharingSpecificFields; SharingDeviceRegistration::SharingDeviceRegistration( + PrefService* pref_service, SharingSyncPreference* sharing_sync_preference, instance_id::InstanceIDDriver* instance_id_driver, VapidKeyManager* vapid_key_manager, syncer::LocalDeviceInfoProvider* local_device_info_provider) - : sharing_sync_preference_(sharing_sync_preference), + : pref_service_(pref_service), + sharing_sync_preference_(sharing_sync_preference), instance_id_driver_(instance_id_driver), vapid_key_manager_(vapid_key_manager), local_device_info_provider_(local_device_info_provider) {} @@ -221,6 +225,11 @@ } bool SharingDeviceRegistration::IsSharedClipboardSupported() const { + // Check the enterprise policy for Shared Clipboard. + if (pref_service_ && + !pref_service_->GetBoolean(prefs::kSharedClipboardEnabled)) { + return false; + } return base::FeatureList::IsEnabled(kSharedClipboardReceiver); }
diff --git a/chrome/browser/sharing/sharing_device_registration.h b/chrome/browser/sharing/sharing_device_registration.h index af3caff..0e849b2 100644 --- a/chrome/browser/sharing/sharing_device_registration.h +++ b/chrome/browser/sharing/sharing_device_registration.h
@@ -15,6 +15,8 @@ #include "components/gcm_driver/instance_id/instance_id.h" #include "components/sync/protocol/device_info_specifics.pb.h" +class PrefService; + namespace instance_id { class InstanceIDDriver; } @@ -35,6 +37,7 @@ base::OnceCallback<void(SharingDeviceRegistrationResult)>; SharingDeviceRegistration( + PrefService* pref_service, SharingSyncPreference* prefs, instance_id::InstanceIDDriver* instance_id_driver, VapidKeyManager* vapid_key_manager, @@ -53,6 +56,9 @@ std::set<sync_pb::SharingSpecificFields_EnabledFeatures> enabled_feautres); + // Returns if device can handle receiving of shared clipboard contents. + bool IsSharedClipboardSupported() const; + private: FRIEND_TEST_ALL_PREFIXES(SharingDeviceRegistrationTest, RegisterDeviceTest_Success); @@ -95,9 +101,7 @@ // Returns if device can handle receiving phone numbers for calling. bool IsClickToCallSupported() const; - // Returns if device can handle receiving of shared clipboard contents. - bool IsSharedClipboardSupported() const; - + PrefService* pref_service_; SharingSyncPreference* sharing_sync_preference_; instance_id::InstanceIDDriver* instance_id_driver_; VapidKeyManager* vapid_key_manager_;
diff --git a/chrome/browser/sharing/sharing_device_registration_unittest.cc b/chrome/browser/sharing/sharing_device_registration_unittest.cc index 9ce36d5..db0cb9fe 100644 --- a/chrome/browser/sharing/sharing_device_registration_unittest.cc +++ b/chrome/browser/sharing/sharing_device_registration_unittest.cc
@@ -10,14 +10,20 @@ #include "base/run_loop.h" #include "base/test/bind_test_util.h" +#include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "chrome/browser/sharing/fake_local_device_info_provider.h" +#include "chrome/browser/sharing/shared_clipboard/feature_flags.h" #include "chrome/browser/sharing/sharing_constants.h" #include "chrome/browser/sharing/sharing_device_registration_result.h" #include "chrome/browser/sharing/sharing_sync_preference.h" #include "chrome/browser/sharing/vapid_key_manager.h" +#include "chrome/common/pref_names.h" #include "components/gcm_driver/instance_id/instance_id_driver.h" +#include "components/prefs/pref_registry.h" +#include "components/prefs/pref_service_factory.h" #include "components/sync_device_info/device_info.h" +#include "components/sync_preferences/pref_service_mock_factory.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/browser_task_environment.h" #include "google_apis/gcm/engine/account_mapping.h" @@ -115,18 +121,36 @@ SharingDeviceRegistrationTest() : sync_prefs_(&prefs_), vapid_key_manager_(&sync_prefs_), - sharing_device_registration_(&sync_prefs_, + sharing_device_registration_(pref_service_.get(), + &sync_prefs_, &mock_instance_id_driver_, &vapid_key_manager_, &fake_local_device_info_provider_) { SharingSyncPreference::RegisterProfilePrefs(prefs_.registry()); } + static std::unique_ptr<PrefService> CreatePrefServiceAndRegisterPrefs() { + scoped_refptr<user_prefs::PrefRegistrySyncable> registry( + new user_prefs::PrefRegistrySyncable()); + registry->RegisterBooleanPref(prefs::kSharedClipboardEnabled, true); + PrefServiceFactory factory; + factory.set_user_prefs(base::MakeRefCounted<TestingPrefStore>()); + return factory.Create(registry); + } + void SetUp() { ON_CALL(mock_instance_id_driver_, GetInstanceID(_)) .WillByDefault(testing::Return(&fake_instance_id_)); } + void SetSharedClipboardPolicy(bool val) { + pref_service_->SetBoolean(prefs::kSharedClipboardEnabled, val); + } + + void EnableSharedClipboardReceiverFlag() { + scoped_feature_list_.InitAndEnableFeature(kSharedClipboardReceiver); + } + void RegisterDeviceSync() { base::RunLoop run_loop; sharing_device_registration_.RegisterDevice( @@ -168,6 +192,9 @@ FakeLocalDeviceInfoProvider fake_local_device_info_provider_; FakeInstanceID fake_instance_id_; + base::test::ScopedFeatureList scoped_feature_list_; + std::unique_ptr<PrefService> pref_service_ = + CreatePrefServiceAndRegisterPrefs(); SharingSyncPreference sync_prefs_; VapidKeyManager vapid_key_manager_; SharingDeviceRegistration sharing_device_registration_; @@ -180,6 +207,20 @@ } // namespace +TEST_F(SharingDeviceRegistrationTest, IsSharedClipboardSupported_True) { + SetSharedClipboardPolicy(true); + EnableSharedClipboardReceiverFlag(); + + EXPECT_TRUE(sharing_device_registration_.IsSharedClipboardSupported()); +} + +TEST_F(SharingDeviceRegistrationTest, IsSharedClipboardSupported_False) { + SetSharedClipboardPolicy(false); + EnableSharedClipboardReceiverFlag(); + + EXPECT_FALSE(sharing_device_registration_.IsSharedClipboardSupported()); +} + TEST_F(SharingDeviceRegistrationTest, RegisterDeviceTest_Success) { SetInstanceIDFCMResult(InstanceID::Result::SUCCESS); SetInstanceIDFCMToken(kFCMToken);
diff --git a/chrome/browser/sharing/sharing_service.cc b/chrome/browser/sharing/sharing_service.cc index 7107b3d..3369b90f 100644 --- a/chrome/browser/sharing/sharing_service.cc +++ b/chrome/browser/sharing/sharing_service.cc
@@ -27,14 +27,17 @@ #include "chrome/browser/sharing/sharing_metrics.h" #include "chrome/browser/sharing/sharing_sync_preference.h" #include "chrome/browser/sharing/vapid_key_manager.h" +#include "chrome/common/pref_names.h" #include "components/gcm_driver/crypto/gcm_encryption_provider.h" #include "components/gcm_driver/gcm_driver.h" +#include "components/prefs/pref_service.h" #include "components/sync/driver/sync_service.h" #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/local_device_info_provider.h" #include "content/public/browser/browser_task_traits.h" SharingService::SharingService( + PrefService* pref_service, std::unique_ptr<SharingSyncPreference> sync_prefs, std::unique_ptr<VapidKeyManager> vapid_key_manager, std::unique_ptr<SharingDeviceRegistration> sharing_device_registration, @@ -45,7 +48,8 @@ syncer::LocalDeviceInfoProvider* local_device_info_provider, syncer::SyncService* sync_service, NotificationDisplayService* notification_display_service) - : sync_prefs_(std::move(sync_prefs)), + : pref_service_(pref_service), + sync_prefs_(std::move(sync_prefs)), vapid_key_manager_(std::move(vapid_key_manager)), sharing_device_registration_(std::move(sharing_device_registration)), fcm_sender_(std::move(fcm_sender)), @@ -91,7 +95,9 @@ this, notification_display_service); #endif // defined(OS_ANDROID) - if (base::FeatureList::IsEnabled(kSharedClipboardReceiver)) { + if (pref_service_ && + !pref_service_->GetBoolean(prefs::kSharedClipboardEnabled) && + base::FeatureList::IsEnabled(kSharedClipboardReceiver)) { fcm_handler_->AddSharingHandler( chrome_browser_sharing::SharingMessage::kSharedClipboardMessage, shared_clipboard_message_handler_.get());
diff --git a/chrome/browser/sharing/sharing_service.h b/chrome/browser/sharing/sharing_service.h index 124160c..c9796fd 100644 --- a/chrome/browser/sharing/sharing_service.h +++ b/chrome/browser/sharing/sharing_service.h
@@ -44,6 +44,7 @@ } // namespace syncer class NotificationDisplayService; +class PrefService; class SharingFCMHandler; class SharingMessageHandler; class SharingSyncPreference; @@ -72,6 +73,7 @@ }; SharingService( + PrefService* pref_service, std::unique_ptr<SharingSyncPreference> sync_prefs, std::unique_ptr<VapidKeyManager> vapid_key_manager, std::unique_ptr<SharingDeviceRegistration> sharing_device_registration, @@ -154,6 +156,7 @@ // in transitioning state. bool IsSyncDisabled() const; + PrefService* pref_service_; std::unique_ptr<SharingSyncPreference> sync_prefs_; std::unique_ptr<VapidKeyManager> vapid_key_manager_; std::unique_ptr<SharingDeviceRegistration> sharing_device_registration_;
diff --git a/chrome/browser/sharing/sharing_service_factory.cc b/chrome/browser/sharing/sharing_service_factory.cc index 1d1457b..a05744b3 100644 --- a/chrome/browser/sharing/sharing_service_factory.cc +++ b/chrome/browser/sharing/sharing_service_factory.cc
@@ -86,7 +86,7 @@ std::make_unique<VapidKeyManager>(sync_prefs.get()); std::unique_ptr<SharingDeviceRegistration> sharing_device_registration = std::make_unique<SharingDeviceRegistration>( - sync_prefs.get(), instance_id_service->driver(), + profile->GetPrefs(), sync_prefs.get(), instance_id_service->driver(), vapid_key_manager.get(), local_device_info_provider); std::unique_ptr<SharingFCMSender> fcm_sender = std::make_unique<SharingFCMSender>(gcm_driver, local_device_info_provider, @@ -97,7 +97,7 @@ sync_prefs.get()); return new SharingService( - std::move(sync_prefs), std::move(vapid_key_manager), + profile->GetPrefs(), std::move(sync_prefs), std::move(vapid_key_manager), std::move(sharing_device_registration), std::move(fcm_sender), std::move(fcm_handler), gcm_driver, device_info_tracker, local_device_info_provider, sync_service, notification_display_service);
diff --git a/chrome/browser/sharing/sharing_service_unittest.cc b/chrome/browser/sharing/sharing_service_unittest.cc index 143996f..ceb23b7a 100644 --- a/chrome/browser/sharing/sharing_service_unittest.cc +++ b/chrome/browser/sharing/sharing_service_unittest.cc
@@ -132,11 +132,13 @@ class FakeSharingDeviceRegistration : public SharingDeviceRegistration { public: FakeSharingDeviceRegistration( + PrefService* pref_service, SharingSyncPreference* prefs, instance_id::InstanceIDDriver* instance_id_driver, VapidKeyManager* vapid_key_manager, syncer::LocalDeviceInfoProvider* device_info_tracker) - : SharingDeviceRegistration(prefs, + : SharingDeviceRegistration(pref_service, + prefs, instance_id_driver, vapid_key_manager, device_info_tracker) {} @@ -211,8 +213,8 @@ SharingServiceTest() { sync_prefs_ = new SharingSyncPreference(&prefs_); sharing_device_registration_ = new FakeSharingDeviceRegistration( - sync_prefs_, &mock_instance_id_driver_, vapid_key_manager_, - &fake_local_device_info_provider_); + /* pref_service= */ nullptr, sync_prefs_, &mock_instance_id_driver_, + vapid_key_manager_, &fake_local_device_info_provider_); vapid_key_manager_ = new VapidKeyManager(sync_prefs_); fcm_sender_ = new SharingFCMSender(&fake_gcm_driver_, &fake_local_device_info_provider_, @@ -253,7 +255,8 @@ SharingService* GetSharingService() { if (!sharing_service_) { sharing_service_ = std::make_unique<SharingService>( - base::WrapUnique(sync_prefs_), base::WrapUnique(vapid_key_manager_), + /* pref_service= */ nullptr, base::WrapUnique(sync_prefs_), + base::WrapUnique(vapid_key_manager_), base::WrapUnique(sharing_device_registration_), base::WrapUnique(fcm_sender_), base::WrapUnique(fcm_handler_), &fake_gcm_driver_, &device_info_tracker_,
diff --git a/chrome/browser/ui/app_list/search/search_result_ranker/ml_app_rank_provider.cc b/chrome/browser/ui/app_list/search/search_result_ranker/ml_app_rank_provider.cc index b0b1632..f1a6907 100644 --- a/chrome/browser/ui/app_list/search/search_result_ranker/ml_app_rank_provider.cc +++ b/chrome/browser/ui/app_list/search/search_result_ranker/ml_app_rank_provider.cc
@@ -24,14 +24,14 @@ #include "mojo/public/cpp/bindings/map.h" #include "ui/base/resource/resource_bundle.h" +using ::chromeos::machine_learning::mojom::BuiltinModelId; +using ::chromeos::machine_learning::mojom::BuiltinModelSpec; +using ::chromeos::machine_learning::mojom::BuiltinModelSpecPtr; using ::chromeos::machine_learning::mojom::CreateGraphExecutorResult; using ::chromeos::machine_learning::mojom::ExecuteResult; using ::chromeos::machine_learning::mojom::FloatList; using ::chromeos::machine_learning::mojom::Int64List; using ::chromeos::machine_learning::mojom::LoadModelResult; -using ::chromeos::machine_learning::mojom::ModelId; -using ::chromeos::machine_learning::mojom::ModelSpec; -using ::chromeos::machine_learning::mojom::ModelSpecPtr; using ::chromeos::machine_learning::mojom::Tensor; using ::chromeos::machine_learning::mojom::TensorPtr; using ::chromeos::machine_learning::mojom::ValueList; @@ -309,10 +309,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(creation_sequence_checker_); if (!model_) { // Load the model. - ModelSpecPtr spec = ModelSpec::New(ModelId::TOP_CAT_20190722); - chromeos::machine_learning::ServiceConnection::GetInstance()->LoadModel( - std::move(spec), model_.BindNewPipeAndPassReceiver(), - base::BindOnce(&LoadModelCallback)); + BuiltinModelSpecPtr spec = + BuiltinModelSpec::New(BuiltinModelId::TOP_CAT_20190722); + chromeos::machine_learning::ServiceConnection::GetInstance() + ->LoadBuiltinModel(std::move(spec), model_.BindNewPipeAndPassReceiver(), + base::BindOnce(&LoadModelCallback)); } if (!executor_) {
diff --git a/chrome/browser/ui/ash/launcher_animations_interactive_uitest.cc b/chrome/browser/ui/ash/launcher_animations_interactive_uitest.cc index 743137a..63d0a5a9b 100644 --- a/chrome/browser/ui/ash/launcher_animations_interactive_uitest.cc +++ b/chrome/browser/ui/ash/launcher_animations_interactive_uitest.cc
@@ -111,6 +111,13 @@ DISALLOW_COPY_AND_ASSIGN(LauncherAnimationsTestBase); }; +// TODO(crbug.com/1009459): many of these tests are failing on MSan builds. +#if defined(MEMORY_SANITIZER) +#define MAYBE_Run DISABLED_Run +#else +#define MAYBE_Run Run +#endif + class LauncherAnimationsFullscreenTest : public LauncherAnimationsTestBase { public: LauncherAnimationsFullscreenTest() = default; @@ -126,7 +133,7 @@ DISALLOW_COPY_AND_ASSIGN(LauncherAnimationsFullscreenTest); }; -IN_PROC_BROWSER_TEST_P(LauncherAnimationsFullscreenTest, Run) { +IN_PROC_BROWSER_TEST_P(LauncherAnimationsFullscreenTest, MAYBE_Run) { SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, true, ash::AppListViewState::kFullscreenAllApps); SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, true, @@ -152,7 +159,7 @@ DISALLOW_COPY_AND_ASSIGN(LauncherAnimationsExpandToFullscreenTest); }; -IN_PROC_BROWSER_TEST_P(LauncherAnimationsExpandToFullscreenTest, Run) { +IN_PROC_BROWSER_TEST_P(LauncherAnimationsExpandToFullscreenTest, MAYBE_Run) { SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, false, ash::AppListViewState::kPeeking); SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, true, @@ -180,7 +187,7 @@ DISALLOW_COPY_AND_ASSIGN(LauncherAnimationsPeekingTest); }; -IN_PROC_BROWSER_TEST_P(LauncherAnimationsPeekingTest, Run) { +IN_PROC_BROWSER_TEST_P(LauncherAnimationsPeekingTest, MAYBE_Run) { SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, false, ash::AppListViewState::kPeeking); SendKeyAndWaitForState(ui::VKEY_BROWSER_SEARCH, false,
diff --git a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc index 5f2fd248..46b69f7 100644 --- a/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc +++ b/chrome/browser/ui/ash/launcher_drag_interactive_uitest.cc
@@ -86,7 +86,13 @@ } // Drag to close the launcher. -IN_PROC_BROWSER_TEST_P(LauncherDragTest, Close) { +// TODO(crbug.com/1009459): many of these tests are failing on MSan builds. +#if defined(MEMORY_SANITIZER) +#define MAYBE_Close DISABLED_Close +#else +#define MAYBE_Close Close +#endif +IN_PROC_BROWSER_TEST_P(LauncherDragTest, MAYBE_Close) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); aura::Window* browser_window = browser_view->GetWidget()->GetNativeWindow(); ash::ShellTestApi shell_test_api;
diff --git a/chrome/browser/ui/bookmarks/bookmark_drag_drop.cc b/chrome/browser/ui/bookmarks/bookmark_drag_drop.cc index 5b3983e29..dc10b50 100644 --- a/chrome/browser/ui/bookmarks/bookmark_drag_drop.cc +++ b/chrome/browser/ui/bookmarks/bookmark_drag_drop.cc
@@ -9,6 +9,7 @@ #include "build/build_config.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/bookmarks/bookmark_stats.h" #include "chrome/browser/undo/bookmark_undo_service_factory.h" #include "components/bookmarks/browser/bookmark_client.h" #include "components/bookmarks/browser/bookmark_model.h" @@ -42,6 +43,7 @@ const BookmarkNode* parent_node, size_t index, bool copy) { + DCHECK(profile); BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(profile); #if !defined(OS_ANDROID) bookmarks::ScopedGroupBookmarkActions group_drops(model); @@ -66,6 +68,7 @@ } return ui::DragDropTypes::DRAG_NONE; } + RecordBookmarksAdded(profile); // Dropping a folder from different profile. Always accept. bookmarks::CloneBookmarkNode(model, data.elements, parent_node, index, true); return ui::DragDropTypes::DRAG_COPY;
diff --git a/chrome/browser/ui/bookmarks/bookmark_stats.cc b/chrome/browser/ui/bookmarks/bookmark_stats.cc index ffa936f4..e38db05 100644 --- a/chrome/browser/ui/bookmarks/bookmark_stats.cc +++ b/chrome/browser/ui/bookmarks/bookmark_stats.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/browser/ui/bookmarks/bookmark_stats.h" +#include "chrome/browser/profiles/profile.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" @@ -18,6 +19,14 @@ location == BOOKMARK_LAUNCH_LOCATION_BAR_SUBFOLDER; } +auto GetMetricProfile(const Profile* profile) { + DCHECK(profile); + DCHECK(profile->IsRegularProfile() || profile->IsIncognitoProfile()); + return profile->IsRegularProfile() + ? profile_metrics::BrowserProfileType::kRegular + : profile_metrics::BrowserProfileType::kIncognito; +} + } // namespace void RecordBookmarkLaunch(BookmarkLaunchLocation location, @@ -55,3 +64,19 @@ base::UserMetricsAction("ClickedBookmarkBarAppsShortcutButton")); } } + +void RecordBookmarksAdded(const Profile* profile) { + profile_metrics::BrowserProfileType profile_type = GetMetricProfile(profile); + UMA_HISTOGRAM_ENUMERATION("Bookmarks.AddedPerProfileType", profile_type); +} + +void RecordBookmarkAllTabsWithTabsCount(const Profile* profile, int count) { + profile_metrics::BrowserProfileType profile_type = GetMetricProfile(profile); + if (profile_type == profile_metrics::BrowserProfileType::kRegular) { + UMA_HISTOGRAM_COUNTS_100("Bookmarks.BookmarkAllTabsWithTabsCount.Regular", + count); + } else { + UMA_HISTOGRAM_COUNTS_100("Bookmarks.BookmarkAllTabsWithTabsCount.Incognito", + count); + } +}
diff --git a/chrome/browser/ui/bookmarks/bookmark_stats.h b/chrome/browser/ui/bookmarks/bookmark_stats.h index e5c495b2..4f41619 100644 --- a/chrome/browser/ui/bookmarks/bookmark_stats.h +++ b/chrome/browser/ui/bookmarks/bookmark_stats.h
@@ -7,7 +7,11 @@ #include "components/profile_metrics/browser_profile_type.h" +class Profile; + // This enum is used for the Bookmarks.EntryPoint histogram. +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. enum BookmarkEntryPoint { BOOKMARK_ENTRY_POINT_ACCELERATOR, BOOKMARK_ENTRY_POINT_STAR_GESTURE, @@ -18,6 +22,8 @@ }; // This enum is used for the Bookmarks.LaunchLocation histogram. +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. enum BookmarkLaunchLocation { BOOKMARK_LAUNCH_LOCATION_NONE, BOOKMARK_LAUNCH_LOCATION_ATTACHED_BAR = 0, @@ -55,4 +61,13 @@ // Records the user opening the apps page for UMA purposes. void RecordBookmarkAppsPageOpen(BookmarkLaunchLocation location); +// Records the user adding a bookmark via star action, drag and drop, via +// Bookmark this tab... and Bookmark all tabs... buttons. For the Bookmark +// open tabs... the action is recorded only once and not as many times as +// count of tabs that were bookmarked. +void RecordBookmarksAdded(const Profile* profile); + +// Records the user bookmarking all tabs, along with the open tabs count. +void RecordBookmarkAllTabsWithTabsCount(const Profile* profile, int count); + #endif // CHROME_BROWSER_UI_BOOKMARKS_BOOKMARK_STATS_H_
diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index 1c4beb41..9548de2 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc
@@ -33,6 +33,7 @@ #include "chrome/browser/ui/accelerator_utils.h" #include "chrome/browser/ui/autofill/payments/manage_migration_ui_controller.h" #include "chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h" +#include "chrome/browser/ui/bookmarks/bookmark_stats.h" #include "chrome/browser/ui/bookmarks/bookmark_utils.h" #include "chrome/browser/ui/bookmarks/bookmark_utils_desktop.h" #include "chrome/browser/ui/browser.h" @@ -840,6 +841,9 @@ // weird situations where the bubble is deleted as soon as it is shown. browser->window()->ShowBookmarkBubble(url, was_bookmarked_by_user); } + + if (!was_bookmarked_by_user && is_bookmarked_by_user) + RecordBookmarksAdded(browser->profile()); } void BookmarkCurrentTabAllowingExtensionOverrides(Browser* browser) { @@ -873,6 +877,10 @@ void BookmarkAllTabs(Browser* browser) { base::RecordAction(UserMetricsAction("BookmarkAllTabs")); + RecordBookmarkAllTabsWithTabsCount(browser->profile(), + browser->tab_strip_model()->count()); + // We record the profile that invoked this option. + RecordBookmarksAdded(browser->profile()); chrome::ShowBookmarkAllTabsDialog(browser); }
diff --git a/chrome/browser/ui/input_method/input_method_engine_base.cc b/chrome/browser/ui/input_method/input_method_engine_base.cc index 0c19b51..0736114 100644 --- a/chrome/browser/ui/input_method/input_method_engine_base.cc +++ b/chrome/browser/ui/input_method/input_method_engine_base.cc
@@ -126,6 +126,7 @@ } ext_event->key_code = static_cast<int>(event.key_code()); ext_event->alt_key = event.IsAltDown(); + ext_event->altgr_key = event.IsAltGrDown(); ext_event->ctrl_key = event.IsControlDown(); ext_event->shift_key = event.IsShiftDown(); ext_event->caps_lock = event.IsCapsLockOn(); @@ -138,8 +139,7 @@ } // namespace -InputMethodEngineBase::KeyboardEvent::KeyboardEvent() - : alt_key(false), ctrl_key(false), shift_key(false), caps_lock(false) {} +InputMethodEngineBase::KeyboardEvent::KeyboardEvent() = default; InputMethodEngineBase::KeyboardEvent::KeyboardEvent( const KeyboardEvent& other) = default; @@ -330,6 +330,7 @@ int flags = ui::EF_NONE; flags |= event.alt_key ? ui::EF_ALT_DOWN : ui::EF_NONE; + flags |= event.altgr_key ? ui::EF_ALTGR_DOWN : ui::EF_NONE; flags |= event.ctrl_key ? ui::EF_CONTROL_DOWN : ui::EF_NONE; flags |= event.shift_key ? ui::EF_SHIFT_DOWN : ui::EF_NONE; flags |= event.caps_lock ? ui::EF_CAPS_LOCK_ON : ui::EF_NONE;
diff --git a/chrome/browser/ui/input_method/input_method_engine_base.h b/chrome/browser/ui/input_method/input_method_engine_base.h index 7ed1807..ac7b934 100644 --- a/chrome/browser/ui/input_method/input_method_engine_base.h +++ b/chrome/browser/ui/input_method/input_method_engine_base.h
@@ -41,10 +41,11 @@ std::string code; int key_code; // only used by on-screen keyboards. std::string extension_id; - bool alt_key; - bool ctrl_key; - bool shift_key; - bool caps_lock; + bool alt_key = false; + bool altgr_key = false; + bool ctrl_key = false; + bool shift_key = false; + bool caps_lock = false; }; enum SegmentStyle {
diff --git a/chrome/browser/ui/views/payments/payment_request_browsertest_base.cc b/chrome/browser/ui/views/payments/payment_request_browsertest_base.cc index 638d4a9..55721cf 100644 --- a/chrome/browser/ui/views/payments/payment_request_browsertest_base.cc +++ b/chrome/browser/ui/views/payments/payment_request_browsertest_base.cc
@@ -497,7 +497,7 @@ } void PaymentRequestBrowserTestBase::CreatePaymentRequestForTest( - payments::mojom::PaymentRequestRequest request, + mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, content::RenderFrameHost* render_frame_host) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); @@ -509,7 +509,7 @@ delegate_ = delegate.get(); PaymentRequestWebContentsManager::GetOrCreateForWebContents(web_contents) ->CreatePaymentRequest(web_contents->GetMainFrame(), web_contents, - std::move(delegate), std::move(request), this); + std::move(delegate), std::move(receiver), this); } void PaymentRequestBrowserTestBase::ClickOnDialogViewAndWait(
diff --git a/chrome/browser/ui/views/payments/payment_request_browsertest_base.h b/chrome/browser/ui/views/payments/payment_request_browsertest_base.h index a8eae5618..d4c6976 100644 --- a/chrome/browser/ui/views/payments/payment_request_browsertest_base.h +++ b/chrome/browser/ui/views/payments/payment_request_browsertest_base.h
@@ -25,6 +25,7 @@ #include "components/sync/driver/test_sync_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/browser/web_contents_observer.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "testing/gmock/include/gmock/gmock.h" @@ -182,7 +183,7 @@ void WaitForOnPersonalDataChanged(); void CreatePaymentRequestForTest( - payments::mojom::PaymentRequestRequest request, + mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, content::RenderFrameHost* render_frame_host); // Click on a view from within the dialog and waits for an observed event
diff --git a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc index 8f07faac..9ae9842 100644 --- a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc +++ b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc
@@ -435,8 +435,7 @@ return gfx::CreateVectorIcon(kIncognitoIcon, icon_size, icon_color); case State::kGuestSession: if (base::FeatureList::IsEnabled(features::kAnimatedAvatarButton)) { - return gfx::CreateVectorIcon(kUserAccountAvatarIcon, icon_size, - icon_color); + return profiles::GetGuestAvatar(icon_size); } return gfx::CreateVectorIcon(kUserMenuGuestIcon, icon_size, icon_color); case State::kGenericProfile:
diff --git a/chrome/browser/ui/views/profiles/profile_menu_view.cc b/chrome/browser/ui/views/profiles/profile_menu_view.cc index ec038cc..1a4d79d 100644 --- a/chrome/browser/ui/views/profiles/profile_menu_view.cc +++ b/chrome/browser/ui/views/profiles/profile_menu_view.cc
@@ -433,7 +433,7 @@ } void ProfileMenuView::BuildGuestIdentity() { - SetIdentityInfo(ImageForMenu(kUserAccountAvatarIcon), GetIdentityBadge(), + SetIdentityInfo(profiles::GetGuestAvatar(), GetIdentityBadge(), l10n_util::GetStringUTF16(IDS_GUEST_PROFILE_NAME)); } @@ -618,7 +618,7 @@ base::Unretained(this))); AddProfileFeatureButton( - ColoredImageForMenu(kUserAccountAvatarIcon, gfx::kGoogleGrey500), + profiles::GetGuestAvatar(), l10n_util::GetStringUTF16(IDS_GUEST_PROFILE_NAME), base::BindRepeating(&ProfileMenuView::OnGuestProfileButtonClicked, base::Unretained(this)));
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc index be46394..38e1186 100644 --- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc +++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc
@@ -20,11 +20,11 @@ MachineLearningInternalsPageHandler::~MachineLearningInternalsPageHandler() = default; -void MachineLearningInternalsPageHandler::LoadModel( - mojom::ModelSpecPtr spec, +void MachineLearningInternalsPageHandler::LoadBuiltinModel( + mojom::BuiltinModelSpecPtr spec, mojom::ModelRequest request, - LoadModelCallback callback) { - ServiceConnection::GetInstance()->LoadModel( + LoadBuiltinModelCallback callback) { + ServiceConnection::GetInstance()->LoadBuiltinModel( std::move(spec), std::move(request), std::move(callback)); }
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h index f0059447..d95f6b4 100644 --- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h +++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h
@@ -25,9 +25,9 @@ private: // mojom::PageHandler: - void LoadModel(mojom::ModelSpecPtr spec, - mojom::ModelRequest request, - LoadModelCallback callback) override; + void LoadBuiltinModel(mojom::BuiltinModelSpecPtr spec, + mojom::ModelRequest request, + LoadBuiltinModelCallback callback) override; mojo::Receiver<mojom::PageHandler> receiver_;
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom index 3e56bc1..19d1e7f 100644 --- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom +++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom
@@ -9,7 +9,8 @@ import "chromeos/services/machine_learning/public/mojom/graph_executor.mojom"; interface PageHandler { - // Loads the specified model by forwarding it to Chrome OS ML Service. - LoadModel(ModelSpec spec, Model& request) => (LoadModelResult result); -}; - + // Loads the specified builtin model by forwarding it to Chrome OS ML + // Service. + LoadBuiltinModel(BuiltinModelSpec spec, Model& request) + => (LoadModelResult result); +}; \ No newline at end of file
diff --git a/chrome/browser/web_applications/components/manifest_update_manager_browsertest.cc b/chrome/browser/web_applications/components/manifest_update_manager_browsertest.cc index 9088cf1..25d7dfd 100644 --- a/chrome/browser/web_applications/components/manifest_update_manager_browsertest.cc +++ b/chrome/browser/web_applications/components/manifest_update_manager_browsertest.cc
@@ -351,6 +351,26 @@ } IN_PROC_BROWSER_TEST_F(ManifestUpdateManagerBrowserTest, + CheckIgnoresInvalidManifest) { + const char* manifest_template = R"( + { + "name": "Test app name", + "start_url": ".", + "scope": "/", + "display": "standalone", + "icons": $1, + $2 + } + )"; + OverrideManifest(manifest_template, {kInstallableIconList, ""}); + AppId app_id = InstallWebApp(); + OverrideManifest(manifest_template, {kInstallableIconList, + "invalid manifest syntax !@#$%^*&()"}); + EXPECT_EQ(GetResultAfterPageLoad(GetAppURL(), &app_id), + ManifestUpdateResult::kAppDataInvalid); +} + +IN_PROC_BROWSER_TEST_F(ManifestUpdateManagerBrowserTest, CheckFindsThemeColorChange) { const char* manifest_template = R"( {
diff --git a/chrome/browser/web_applications/components/manifest_update_task.cc b/chrome/browser/web_applications/components/manifest_update_task.cc index ab6056b6..44668e8d 100644 --- a/chrome/browser/web_applications/components/manifest_update_task.cc +++ b/chrome/browser/web_applications/components/manifest_update_task.cc
@@ -78,7 +78,13 @@ void ManifestUpdateTask::OnDidGetInstallableData(const InstallableData& data) { DCHECK_EQ(stage_, Stage::kPendingInstallableData); - if (!IsUpdateNeededForInstallableData(data)) { + if (!data.errors.empty()) { + DestroySelf(ManifestUpdateResult::kAppDataInvalid); + return; + } + + DCHECK(data.manifest); + if (!IsUpdateNeededForManifest(*data.manifest)) { DestroySelf(ManifestUpdateResult::kAppUpToDate); return; } @@ -90,17 +96,12 @@ AsWeakPtr(), *data.manifest)); } -bool ManifestUpdateTask::IsUpdateNeededForInstallableData( - const InstallableData& data) { - if (!data.errors.empty()) +bool ManifestUpdateTask::IsUpdateNeededForManifest( + const blink::Manifest& manifest) const { + if (app_id_ != GenerateAppIdFromURL(manifest.start_url)) return false; - DCHECK(data.manifest); - - if (app_id_ != GenerateAppIdFromURL(data.manifest->start_url)) - return false; - - if (data.manifest->theme_color != registrar_.GetAppThemeColor(app_id_)) + if (manifest.theme_color != registrar_.GetAppThemeColor(app_id_)) return true; // TODO(crbug.com/926083): Check more manifest fields.
diff --git a/chrome/browser/web_applications/components/manifest_update_task.h b/chrome/browser/web_applications/components/manifest_update_task.h index f7b619d0..aa9f53a 100644 --- a/chrome/browser/web_applications/components/manifest_update_task.h +++ b/chrome/browser/web_applications/components/manifest_update_task.h
@@ -26,6 +26,7 @@ kWebContentsDestroyed, kAppUninstalled, kAppUpToDate, + kAppDataInvalid, kAppUpdateFailed, kAppUpdated, }; @@ -67,7 +68,7 @@ }; void OnDidGetInstallableData(const InstallableData& data); - bool IsUpdateNeededForInstallableData(const InstallableData& data); + bool IsUpdateNeededForManifest(const blink::Manifest& manifest) const; void OnAllAppWindowsClosed(blink::Manifest manifest); void OnInstallationComplete(const AppId& app_id, InstallResultCode code); void DestroySelf(ManifestUpdateResult result);
diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index def914b..2b7d157 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json
@@ -450,6 +450,7 @@ "location": "policy", "platforms": ["chromeos"], "whitelist": [ + "7FE4A999359A456C4B0FB7B7AD85CEA29CA50519", // Login screen APIs test extension "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) "4DBFC1C52D6660DD90791976DF7FEF7B3D360509", // Imprivata (login screen) DEV "A24DE1B21A67E25FB62AC8491642038FE25DA75B", // Imprivata (in session) @@ -474,7 +475,7 @@ "location": "policy", "platforms": ["chromeos"], "whitelist": [ - "7FE4A999359A456C4B0FB7B7AD85CEA29CA50519", // chrome.loginScreenUi test extension + "7FE4A999359A456C4B0FB7B7AD85CEA29CA50519", // Login screen APIs test extension "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) "4DBFC1C52D6660DD90791976DF7FEF7B3D360509" // Imprivata (login screen) DEV ]
diff --git a/chrome/common/extensions/api/input_ime.json b/chrome/common/extensions/api/input_ime.json index b4fce4a5..ee09502 100644 --- a/chrome/common/extensions/api/input_ime.json +++ b/chrome/common/extensions/api/input_ime.json
@@ -24,6 +24,7 @@ "code": {"type": "string", "description": "Value of the physical key being pressed. The value is not affected by current keyboard layout or modifier state."}, "keyCode": {"type": "integer", "optional": true, "description": "The deprecated HTML keyCode, which is system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed."}, "altKey": {"type": "boolean", "optional": true, "description": "Whether or not the ALT key is pressed."}, + "altgrKey": {"type": "boolean", "optional": true, "description": "Whether or not the ALTGR key is pressed."}, "ctrlKey": {"type": "boolean", "optional": true, "description": "Whether or not the CTRL key is pressed."}, "shiftKey": {"type": "boolean", "optional": true, "description": "Whether or not the SHIFT key is pressed."}, "capsLock": {"type": "boolean", "optional": true, "description": "Whether or not the CAPS_LOCK is enabled."}
diff --git a/chrome/common/plugin.mojom b/chrome/common/plugin.mojom index 252b9b7..04f9470 100644 --- a/chrome/common/plugin.mojom +++ b/chrome/common/plugin.mojom
@@ -20,12 +20,12 @@ CouldNotLoadPlugin(mojo_base.mojom.FilePath file_path); // Notifies when a plugin couldn't be loaded because it's outdated. - BlockedOutdatedPlugin(PluginRenderer plugin_renderer, + BlockedOutdatedPlugin(pending_remote<PluginRenderer> plugin_renderer, string group_id); // Notifies when a plugin couldn't be loaded because it requires a // component update. - BlockedComponentUpdatedPlugin(PluginRenderer plugin_renderer, + BlockedComponentUpdatedPlugin(pending_remote<PluginRenderer> plugin_renderer, string group_id); };
diff --git a/chrome/common/renderer_configuration.mojom b/chrome/common/renderer_configuration.mojom index 0ade9fa..4d01879f0 100644 --- a/chrome/common/renderer_configuration.mojom +++ b/chrome/common/renderer_configuration.mojom
@@ -27,8 +27,9 @@ // Configures the renderer with settings that won't change. // The |chromeos_listener| is only passed on Chrome OS when // the merge session is still running - otherwise not set. - SetInitialConfiguration(bool is_incognito_process, - ChromeOSListener&? chromeos_listener); + SetInitialConfiguration( + bool is_incognito_process, + pending_receiver<ChromeOSListener>? chromeos_listener); // Update renderer configuration with settings that can change. SetConfiguration(DynamicParams params);
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 82ca528e..f986c18c 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -747,7 +747,7 @@ #if BUILDFLAG(ENABLE_PLUGINS) -chrome::mojom::PluginInfoHostAssociatedPtr& +mojo::AssociatedRemote<chrome::mojom::PluginInfoHost>& ChromeContentRendererClient::GetPluginInfoHost() { struct PluginInfoHostHolder { PluginInfoHostHolder() { @@ -755,7 +755,7 @@ &plugin_info_host); } ~PluginInfoHostHolder() {} - chrome::mojom::PluginInfoHostAssociatedPtr plugin_info_host; + mojo::AssociatedRemote<chrome::mojom::PluginInfoHost> plugin_info_host; }; static base::NoDestructor<PluginInfoHostHolder> holder; return holder->plugin_info_host; @@ -989,9 +989,9 @@ IDR_BLOCKED_PLUGIN_HTML, l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name)); placeholder->AllowLoading(); - chrome::mojom::PluginHostAssociatedPtr plugin_host; + mojo::AssociatedRemote<chrome::mojom::PluginHost> plugin_host; render_frame->GetRemoteAssociatedInterfaces()->GetInterface( - &plugin_host); + plugin_host.BindNewEndpointAndPassReceiver()); plugin_host->BlockedOutdatedPlugin(placeholder->BindPluginRenderer(), identifier); break; @@ -1007,9 +1007,9 @@ IDR_BLOCKED_PLUGIN_HTML, l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name)); placeholder->AllowLoading(); - chrome::mojom::PluginAuthHostAssociatedPtr plugin_auth_host; + mojo::AssociatedRemote<chrome::mojom::PluginAuthHost> plugin_auth_host; render_frame->GetRemoteAssociatedInterfaces()->GetInterface( - &plugin_auth_host); + plugin_auth_host.BindNewEndpointAndPassReceiver()); plugin_auth_host->BlockedUnauthorizedPlugin(group_name, identifier); observer->DidBlockContentType(content_type, group_name); break; @@ -1046,9 +1046,9 @@ IDR_BLOCKED_PLUGIN_HTML, l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name)); placeholder->AllowLoading(); - chrome::mojom::PluginHostAssociatedPtr plugin_host; + mojo::AssociatedRemote<chrome::mojom::PluginHost> plugin_host; render_frame->GetRemoteAssociatedInterfaces()->GetInterface( - &plugin_host); + plugin_host.BindNewEndpointAndPassReceiver()); plugin_host->BlockedComponentUpdatedPlugin( placeholder->BindPluginRenderer(), identifier); break;
diff --git a/chrome/renderer/chrome_content_renderer_client.h b/chrome/renderer/chrome_content_renderer_client.h index 3cb3dde..d306846 100644 --- a/chrome/renderer/chrome_content_renderer_client.h +++ b/chrome/renderer/chrome_content_renderer_client.h
@@ -28,6 +28,7 @@ #include "extensions/buildflags/buildflags.h" #include "ipc/ipc_channel_proxy.h" #include "media/media_buildflags.h" +#include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/generic_pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "ppapi/buildflags/buildflags.h" @@ -214,7 +215,8 @@ void BindReceiverOnMainThread(mojo::GenericPendingReceiver receiver) override; #if BUILDFLAG(ENABLE_PLUGINS) - static chrome::mojom::PluginInfoHostAssociatedPtr& GetPluginInfoHost(); + static mojo::AssociatedRemote<chrome::mojom::PluginInfoHost>& + GetPluginInfoHost(); static blink::WebPlugin* CreatePlugin( content::RenderFrame* render_frame,
diff --git a/chrome/renderer/chrome_render_thread_observer.cc b/chrome/renderer/chrome_render_thread_observer.cc index 47189d7..3cc9905 100644 --- a/chrome/renderer/chrome_render_thread_observer.cc +++ b/chrome/renderer/chrome_render_thread_observer.cc
@@ -50,7 +50,6 @@ #include "extensions/buildflags/buildflags.h" #include "ipc/ipc_sync_channel.h" #include "media/base/localized_strings.h" -#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/base/net_errors.h" #include "net/base/net_module.h" #include "services/service_manager/public/cpp/binder_registry.h" @@ -142,11 +141,12 @@ // static scoped_refptr<ChromeRenderThreadObserver::ChromeOSListener> ChromeRenderThreadObserver::ChromeOSListener::Create( - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request) { + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver) { scoped_refptr<ChromeOSListener> helper = new ChromeOSListener(); content::ChildThread::Get()->GetIOTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&ChromeOSListener::BindOnIOThread, helper, - std::move(chromeos_listener_request))); + std::move(chromeos_listener_receiver))); return helper; } @@ -175,14 +175,14 @@ : session_merged_callbacks_(base::MakeRefCounted<DelayedCallbackGroup>( MergeSessionLoaderThrottle::GetMergeSessionTimeout(), GetCallbackGroupTaskRunner())), - merge_session_running_(true), - binding_(this) {} + merge_session_running_(true) {} ChromeRenderThreadObserver::ChromeOSListener::~ChromeOSListener() {} void ChromeRenderThreadObserver::ChromeOSListener::BindOnIOThread( - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request) { - binding_.Bind(std::move(chromeos_listener_request)); + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver) { + receiver_.Bind(std::move(chromeos_listener_receiver)); } #endif // defined(OS_CHROMEOS) @@ -247,12 +247,13 @@ void ChromeRenderThreadObserver::SetInitialConfiguration( bool is_incognito_process, - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request) { + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver) { is_incognito_process_ = is_incognito_process; #if defined(OS_CHROMEOS) - if (chromeos_listener_request) { + if (chromeos_listener_receiver) { chromeos_listener_ = - ChromeOSListener::Create(std::move(chromeos_listener_request)); + ChromeOSListener::Create(std::move(chromeos_listener_receiver)); } #endif // defined(OS_CHROMEOS) }
diff --git a/chrome/renderer/chrome_render_thread_observer.h b/chrome/renderer/chrome_render_thread_observer.h index b49fc17..1714c08 100644 --- a/chrome/renderer/chrome_render_thread_observer.h +++ b/chrome/renderer/chrome_render_thread_observer.h
@@ -15,6 +15,8 @@ #include "content/public/renderer/render_thread_observer.h" #include "mojo/public/cpp/bindings/associated_receiver_set.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" #if defined(OS_CHROMEOS) #include "chrome/renderer/chromeos_delayed_callback_group.h" @@ -44,7 +46,8 @@ public base::RefCountedThreadSafe<ChromeOSListener> { public: static scoped_refptr<ChromeOSListener> Create( - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request); + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver); // Is the merge session still running? bool IsMergeSessionRunning() const; @@ -63,13 +66,13 @@ ChromeOSListener(); ~ChromeOSListener() override; - void BindOnIOThread( - chrome::mojom::ChromeOSListenerRequest chromeos_listener_request); + void BindOnIOThread(mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver); scoped_refptr<DelayedCallbackGroup> session_merged_callbacks_; bool merge_session_running_ GUARDED_BY(lock_); mutable base::Lock lock_; - mojo::Binding<chrome::mojom::ChromeOSListener> binding_; + mojo::Receiver<chrome::mojom::ChromeOSListener> receiver_{this}; DISALLOW_COPY_AND_ASSIGN(ChromeOSListener); }; @@ -106,9 +109,10 @@ blink::AssociatedInterfaceRegistry* associated_interfaces) override; // chrome::mojom::RendererConfiguration: - void SetInitialConfiguration(bool is_incognito_process, - chrome::mojom::ChromeOSListenerRequest - chromeos_listener_request) override; + void SetInitialConfiguration( + bool is_incognito_process, + mojo::PendingReceiver<chrome::mojom::ChromeOSListener> + chromeos_listener_receiver) override; void SetConfiguration(chrome::mojom::DynamicParamsPtr params) override; void SetContentSettingRules( const RendererContentSettingRules& rules) override;
diff --git a/chrome/renderer/plugins/chrome_plugin_placeholder.cc b/chrome/renderer/plugins/chrome_plugin_placeholder.cc index 9b3541d..205c7398f 100644 --- a/chrome/renderer/plugins/chrome_plugin_placeholder.cc +++ b/chrome/renderer/plugins/chrome_plugin_placeholder.cc
@@ -31,6 +31,7 @@ #include "content/public/renderer/render_thread.h" #include "gin/object_template_builder.h" #include "ipc/ipc_sync_channel.h" +#include "mojo/public/cpp/bindings/associated_remote.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #include "third_party/blink/public/common/page/page_zoom.h" @@ -68,8 +69,7 @@ : plugins::LoadablePluginPlaceholder(render_frame, params, html_data), status_(chrome::mojom::PluginStatus::kAllowed), title_(title), - context_menu_request_id_(0), - plugin_renderer_binding_(this) { + context_menu_request_id_(0) { RenderThread::Get()->AddObserver(this); } @@ -79,10 +79,9 @@ render_frame()->CancelContextMenu(context_menu_request_id_); } -chrome::mojom::PluginRendererPtr ChromePluginPlaceholder::BindPluginRenderer() { - chrome::mojom::PluginRendererPtr plugin_renderer; - plugin_renderer_binding_.Bind(mojo::MakeRequest(&plugin_renderer)); - return plugin_renderer; +mojo::PendingRemote<chrome::mojom::PluginRenderer> +ChromePluginPlaceholder::BindPluginRenderer() { + return plugin_renderer_receiver_.BindNewPipeAndPassRemote(); } // TODO(bauerb): Move this method to NonLoadablePluginPlaceholder? @@ -188,8 +187,9 @@ } void ChromePluginPlaceholder::ShowPermissionBubbleCallback() { - chrome::mojom::PluginHostAssociatedPtr plugin_host; - render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(&plugin_host); + mojo::AssociatedRemote<chrome::mojom::PluginHost> plugin_host; + render_frame()->GetRemoteAssociatedInterfaces()->GetInterface( + plugin_host.BindNewEndpointAndPassReceiver()); plugin_host->ShowFlashPermissionBubble(); }
diff --git a/chrome/renderer/plugins/chrome_plugin_placeholder.h b/chrome/renderer/plugins/chrome_plugin_placeholder.h index a3b1e36..738a37a 100644 --- a/chrome/renderer/plugins/chrome_plugin_placeholder.h +++ b/chrome/renderer/plugins/chrome_plugin_placeholder.h
@@ -16,7 +16,8 @@ #include "components/plugins/renderer/loadable_plugin_placeholder.h" #include "content/public/renderer/context_menu_client.h" #include "content/public/renderer/render_thread_observer.h" -#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" class ChromePluginPlaceholder final : public plugins::LoadablePluginPlaceholder, @@ -44,7 +45,7 @@ void SetStatus(chrome::mojom::PluginStatus status); - chrome::mojom::PluginRendererPtr BindPluginRenderer(); + mojo::PendingRemote<chrome::mojom::PluginRenderer> BindPluginRenderer(); private: ChromePluginPlaceholder(content::RenderFrame* render_frame, @@ -96,7 +97,7 @@ int context_menu_request_id_; // Nonzero when request pending. base::string16 plugin_name_; - mojo::Binding<chrome::mojom::PluginRenderer> plugin_renderer_binding_; + mojo::Receiver<chrome::mojom::PluginRenderer> plugin_renderer_receiver_{this}; DISALLOW_COPY_AND_ASSIGN(ChromePluginPlaceholder); };
diff --git a/chrome/services/media_gallery_util/public/cpp/media_parser_provider.h b/chrome/services/media_gallery_util/public/cpp/media_parser_provider.h index f76f455b..fe5642f 100644 --- a/chrome/services/media_gallery_util/public/cpp/media_parser_provider.h +++ b/chrome/services/media_gallery_util/public/cpp/media_parser_provider.h
@@ -11,7 +11,7 @@ #include "mojo/public/cpp/bindings/remote.h" // Base class used by SafeMediaMetadataParser and SafeAudioVideoChecker to -// retrieve a MediaParserPtr. +// retrieve a mojo::Remote<MediaParser>. class MediaParserProvider { public: MediaParserProvider();
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index d7e3b0d..b039966 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2040,6 +2040,7 @@ "../browser/chromeos/extensions/incoming_native_messaging_apitest.cc", "../browser/chromeos/extensions/info_private_apitest.cc", "../browser/chromeos/extensions/input_method_apitest_chromeos.cc", + "../browser/chromeos/extensions/login_screen/login/login_apitest.cc", "../browser/chromeos/extensions/login_screen/login_screen_apitest_base.cc", "../browser/chromeos/extensions/login_screen/login_screen_apitest_base.h", "../browser/chromeos/extensions/login_screen/login_screen_ui/login_screen_ui_apitest.cc",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ReducedModeNativeTestRule.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ReducedModeNativeTestRule.java index 2a34225..e8654301 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ReducedModeNativeTestRule.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/ReducedModeNativeTestRule.java
@@ -10,9 +10,7 @@ import org.junit.runners.model.Statement; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.task.PostTask; -import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.init.EmptyBrowserParts; @@ -66,12 +64,8 @@ } }; PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { - try { - ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); - ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); - } catch (ProcessInitException e) { - ChromeApplication.reportStartupErrorAndExit(e); - } + ChromeBrowserInitializer.getInstance().handlePreNativeStartup(parts); + ChromeBrowserInitializer.getInstance().handlePostNativeStartup(true, parts); }); waitForNativeLoaded(); }
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/README b/chrome/test/data/extensions/api_test/login_screen_apis/README index 7d271c6..71f8a09 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/README +++ b/chrome/test/data/extensions/api_test/login_screen_apis/README
@@ -4,6 +4,8 @@ This extension is used in the API tests for the following APIs: -chrome.loginScreenUi +-chrome.storage +-chrome.login The code for the tests can be found under the chrome/browser/chromeos/extensions/login_screen_apis/ directory.
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/extension.crx b/chrome/test/data/extensions/api_test/login_screen_apis/extension.crx index 0742a2eb..04dde109 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/extension.crx +++ b/chrome/test/data/extensions/api_test/login_screen_apis/extension.crx Binary files differ
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/extension/background.js b/chrome/test/data/extensions/api_test/login_screen_apis/extension/background.js index 4d3d48fe..011529e4 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/extension/background.js +++ b/chrome/test/data/extensions/api_test/login_screen_apis/extension/background.js
@@ -9,6 +9,8 @@ '"local" is not available for login screen extensions'; const cannotAccessSyncStorageErrorMessage = '"sync" is not available for login screen extensions'; +const noManagedGuestSessionAccountsErrorMessage = + 'No managed guest session accounts'; const tests = { /* LoginScreenUi ************************************************************/ @@ -82,6 +84,35 @@ chrome.test.succeed(); }); }, + + /* Login ********************************************************************/ + 'LoginLaunchManagedGuestSession': () => { + chrome.login.launchManagedGuestSession(() => { + chrome.test.assertNoLastError(); + chrome.test.succeed(); + }); + }, + 'LoginLaunchManagedGuestSessionNoAccounts': () => { + chrome.login.launchManagedGuestSession(() => { + chrome.test.assertLastError(noManagedGuestSessionAccountsErrorMessage); + chrome.test.succeed(); + }); + }, + 'LoginExitCurrentSession': () => { + chrome.test.getConfig(config => { + chrome.login.exitCurrentSession(config.customArg); + // No check for success as browser process exists. + }); + }, + 'LoginFetchDataForNextLoginAttempt': () => { + chrome.test.getConfig(config => { + chrome.login.fetchDataForNextLoginAttempt(data => { + chrome.test.assertNoLastError(); + chrome.test.assertEq(config.customArg, data); + chrome.test.succeed(); + }); + }); + }, }; // |waitForTestName()| waits for the browser test to reply with a test name and
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/extension/manifest.json b/chrome/test/data/extensions/api_test/login_screen_apis/extension/manifest.json index 8d0dd00..e34313b0b 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/extension/manifest.json +++ b/chrome/test/data/extensions/api_test/login_screen_apis/extension/manifest.json
@@ -1,6 +1,6 @@ { "name": "Login screen APIs test extension", - "version": "1.19", + "version": "1.20", "manifest_version": 2, "description": "Login screen APIs test extension", "background": { @@ -9,6 +9,7 @@ }, "permissions": [ "loginScreenUi", - "storage" + "storage", + "login" ] }
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/extension/window.html b/chrome/test/data/extensions/api_test/login_screen_apis/extension/window.html index 4687da5..85308728 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/extension/window.html +++ b/chrome/test/data/extensions/api_test/login_screen_apis/extension/window.html
@@ -4,6 +4,6 @@ * LICENSE file. --> <html> -<head><title>loginScreenUi component API interface test</title></head> -<body><h2>chrome.loginScreenUi.* tests</h2></body> +<head><title>Login screen APIs test extension</title></head> +<body><h2>Login screen APIS tests</h2></body> </html>
diff --git a/chrome/test/data/extensions/api_test/login_screen_apis/update_manifest.xml b/chrome/test/data/extensions/api_test/login_screen_apis/update_manifest.xml index ce618c6..64abc8a8 100644 --- a/chrome/test/data/extensions/api_test/login_screen_apis/update_manifest.xml +++ b/chrome/test/data/extensions/api_test/login_screen_apis/update_manifest.xml
@@ -7,6 +7,6 @@ <app appid='oclffehlkdgibkainkilopaalpdobkan'> <updatecheck codebase='http://mock.http/extensions/api_test/login_screen_apis/extension.crx' - version='1.19' /> + version='1.20' /> </app> </gupdate>
diff --git a/chrome/test/data/extensions/input_ime/main.js b/chrome/test/data/extensions/input_ime/main.js index 066a093..798bf4bb 100644 --- a/chrome/test/data/extensions/input_ime/main.js +++ b/chrome/test/data/extensions/input_ime/main.js
@@ -80,6 +80,7 @@ keyData.code + ':' + keyData.ctrlKey + ':' + keyData.altKey + ':' + + keyData.altgrKey + ':' + keyData.shiftKey + ':' + keyData.capsLock); this.nextRequestID_++;
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 71319b5..2679964 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4066,6 +4066,9 @@ "DeviceLoginScreenMonoAudioEnabled" : { }, + "DeviceLoginScreenAutoclickEnabled" : { + }, + "DeviceLoginScreenLocales" : { },
diff --git a/chrome/test/data/webui/print_preview/advanced_item_test.js b/chrome/test/data/webui/print_preview/advanced_item_test.js index 37a1ab7b..fabf5e28 100644 --- a/chrome/test/data/webui/print_preview/advanced_item_test.js +++ b/chrome/test/data/webui/print_preview/advanced_item_test.js
@@ -7,8 +7,10 @@ const TestNames = { DisplaySelect: 'display select', DisplayInput: 'display input', + DisplayCheckbox: 'display checkbox', UpdateSelect: 'update select', UpdateInput: 'update input', + UpdateCheckbox: 'update checkbox', QueryName: 'query name', QueryOption: 'query option', }; @@ -50,9 +52,9 @@ assertEquals('Recycled', select.options[1].textContent.trim()); assertEquals('Special', select.options[2].textContent.trim()); - // The input should not be shown for a select capability. - const input = item.$$('cr-input'); - assertTrue(input.parentElement.hidden); + // Don't show input or checkbox. + assertTrue(item.$$('cr-input').parentElement.hidden); + assertTrue(item.$$('cr-checkbox').parentElement.hidden); }); test(assert(TestNames.DisplayInput), function() { @@ -70,8 +72,29 @@ assertFalse(input.parentElement.hidden); assertEquals('', input.inputElement.value); - // No select. + // Don't show select or checkbox. assertEquals(null, item.$$('select')); + assertTrue(item.$$('cr-checkbox').parentElement.hidden); + }); + + test(assert(TestNames.DisplayCheckbox), function() { + // Create capability + item.capability = print_preview_test_utils + .getCddTemplateWithAdvancedSettings(4, 'FooDevice') + .capabilities.printer.vendor_capability[3]; + Polymer.dom.flush(); + + const label = item.$$('.label'); + assertEquals('Staple', label.textContent); + + // The checkbox should be shown. + const checkbox = item.$$('cr-checkbox'); + assertFalse(checkbox.parentElement.hidden); + assertFalse(checkbox.checked); + + // Don't show select or input. + assertEquals(null, item.$$('select')); + assertTrue(item.$$('cr-input').parentElement.hidden); }); // Test that a select capability updates correctly when the setting is @@ -104,6 +127,24 @@ assertEquals('ABCD', input.inputElement.value); }); + // Test that an checkbox capability updates correctly when the setting is + // updated (e.g. when sticky settings are set). + test(assert(TestNames.UpdateCheckbox), function() { + // Create capability + item.capability = print_preview_test_utils + .getCddTemplateWithAdvancedSettings(4, 'FooDevice') + .capabilities.printer.vendor_capability[3]; + Polymer.dom.flush(); + + // Check that checkbox is unset. + const checkbox = item.$$('cr-checkbox'); + assertFalse(checkbox.checked); + + // Update the setting. + item.set('settings.vendorItems.value', {'finishings/4': 'true'}); + assertTrue(checkbox.checked); + }); + // Test that the setting is displayed correctly when the search query // matches its display name. test(assert(TestNames.QueryName), function() {
diff --git a/chrome/test/data/webui/print_preview/print_preview_test_utils.js b/chrome/test/data/webui/print_preview/print_preview_test_utils.js index 86e949a..b46056e8 100644 --- a/chrome/test/data/webui/print_preview/print_preview_test_utils.js +++ b/chrome/test/data/webui/print_preview/print_preview_test_utils.js
@@ -151,6 +151,20 @@ } }); + if (numSettings < 4) { + return template; + } + + template.capabilities.printer.vendor_capability.push({ + display_name: 'Staple', + id: 'finishings/4', + type: 'TYPED_VALUE', + typed_value_cap: { + default: '', + value_type: 'BOOLEAN', + } + }); + return template; }
diff --git a/chrome/test/payments/payment_request_test_controller_desktop.cc b/chrome/test/payments/payment_request_test_controller_desktop.cc index 860fe59..a91e98a 100644 --- a/chrome/test/payments/payment_request_test_controller_desktop.cc +++ b/chrome/test/payments/payment_request_test_controller_desktop.cc
@@ -10,6 +10,7 @@ #include "components/payments/content/payment_request_web_contents_manager.h" #include "components/payments/core/payment_prefs.h" #include "components/sync_preferences/testing_pref_service_syncable.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" namespace payments { @@ -107,7 +108,7 @@ SetPaymentRequestFactoryForTesting(base::BindRepeating( [](PaymentRequest::ObserverForTest* observer_for_test, bool is_incognito, bool valid_ssl, PrefService* prefs, - payments::mojom::PaymentRequestRequest request, + mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, content::RenderFrameHost* render_frame_host) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); @@ -120,7 +121,7 @@ web_contents); manager->CreatePaymentRequest(web_contents->GetMainFrame(), web_contents, std::move(delegate), - std::move(request), observer_for_test); + std::move(receiver), observer_for_test); }, observer_converter_.get(), is_incognito_, valid_ssl_, prefs_.get())); }
diff --git a/chromecast/browser/webview/proto/webview.proto b/chromecast/browser/webview/proto/webview.proto index c6311258..2ee355e 100644 --- a/chromecast/browser/webview/proto/webview.proto +++ b/chromecast/browser/webview/proto/webview.proto
@@ -22,8 +22,6 @@ // This identifies the surface that this webview will display into. // It should be unique and the same as whatever was set into // |aura_surface_set_client_surface_id| on the wayland surface. - // It is an error to attempt to create a webview if the surface - // does not yet exist. int32 webview_id = 1; // This is the cast window ID that will be assigned to the web contents // window. @@ -101,6 +99,75 @@ int32 error_code = 1; } +message EvaluateJavascriptRequest { + string javascript_blob = 1; +} + +message EvaluateJavascriptResponse { + string json = 1; +} + +message AddJavascriptChannelsRequest { + repeated string channels = 1; +} + +message RemoveJavascriptChannelsRequest { + repeated string channels = 1; +} + +message GetCurrentUrlRequest {} + +message GetCurrentUrlResponse { + string url = 1; +} + +message CanGoBackRequest {} + +message CanGoBackResponse { + bool can_go_back = 1; +} + +message CanGoForwardRequest {} + +message CanGoForwardResponse { + bool can_go_forward = 1; +} + +message GoBackRequest {} + +message GoForwardRequest {} + +message ReloadRequest {} + +message ClearCacheRequest {} + +message UserAgent { + oneof type { + bool is_null = 1; + string value = 2; + } +} + +message UpdateSettingsRequest { + bool javascript_enabled = 1; + bool has_navigation_delegate = 2; + bool debugging_enabled = 3; + // A null value means the default user agent should be used. + // An absent value represents no change to this setting from the last time it + // was set. + UserAgent user_agent = 4; +} + +message GetTitleRequest {} + +message GetTitleResponse { + string title = 1; +} + +message SetAutoMediaPlaybackPolicyRequest { + bool require_user_gesture = 1; +} + message WebviewRequest { oneof type { // This must be the first message. @@ -111,6 +178,32 @@ NavigateRequest navigate = 3; // Expect page events to follow. StopPageRequest stop_page = 4; + // Expect async response. + EvaluateJavascriptRequest evaluate_javascript = 5; + // No response. + AddJavascriptChannelsRequest add_javascript_channels = 6; + // No response. + RemoveJavascriptChannelsRequest remove_javascript_channels = 7; + // Expect async response. + GetCurrentUrlRequest get_current_url = 8; + // Expect async response. + CanGoBackRequest can_go_back = 9; + // Expect async response. + CanGoForwardRequest can_go_forward = 10; + // No response. + GoBackRequest go_back = 11; + // No response. + GoForwardRequest go_forward = 12; + // No response. + ReloadRequest reload = 13; + // No response. + ClearCacheRequest clear_cache = 14; + // No response. + UpdateSettingsRequest update_settings = 15; + // Expect async response. + GetTitleRequest get_title = 16; + // No response. + SetAutoMediaPlaybackPolicyRequest set_auto_media_playback_policy = 17; } } @@ -118,9 +211,15 @@ oneof type { WebviewCreateResponse create_response = 1; AsyncPageEvent page_event = 2; + EvaluateJavascriptResponse evaluate_javascript = 3; + GetCurrentUrlResponse get_current_url = 4; + CanGoBackResponse can_go_back = 5; + CanGoForwardResponse can_go_forward = 6; + GetTitleResponse get_title = 7; } } service WebviewService { + // Creates a webview. See the comment at the top of the file. rpc CreateWebview(stream WebviewRequest) returns (stream WebviewResponse); }
diff --git a/chromecast/browser/webview/webview_controller.cc b/chromecast/browser/webview/webview_controller.cc index 887fe25..e982dee 100644 --- a/chromecast/browser/webview/webview_controller.cc +++ b/chromecast/browser/webview/webview_controller.cc
@@ -4,11 +4,17 @@ #include "chromecast/browser/webview/webview_controller.h" +#include "base/json/json_writer.h" +#include "base/strings/utf_string_conversions.h" #include "chromecast/base/version.h" #include "chromecast/browser/cast_web_contents_impl.h" #include "chromecast/browser/webview/proto/webview.pb.h" #include "chromecast/browser/webview/webview_layout_manager.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/browsing_data_remover.h" +#include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/web_preferences.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/events/event.h" @@ -62,6 +68,81 @@ } break; + case webview::WebviewRequest::kEvaluateJavascript: + if (request.has_evaluate_javascript()) { + HandleEvaluateJavascript(request.evaluate_javascript()); + } else { + client_->OnError("evaluate_javascript() not supplied"); + } + break; + + case webview::WebviewRequest::kAddJavascriptChannels: + if (request.has_add_javascript_channels()) { + HandleAddJavascriptChannels(request.add_javascript_channels()); + } else { + client_->OnError("add_javascript_channels() not supplied"); + } + break; + + case webview::WebviewRequest::kRemoveJavascriptChannels: + if (request.has_remove_javascript_channels()) { + HandleRemoveJavascriptChannels(request.remove_javascript_channels()); + } else { + client_->OnError("remove_javascript_channels() not supplied"); + } + break; + + case webview::WebviewRequest::kGetCurrentUrl: + HandleGetCurrentUrl(); + break; + + case webview::WebviewRequest::kCanGoBack: + HandleCanGoBack(); + break; + + case webview::WebviewRequest::kCanGoForward: + HandleCanGoForward(); + break; + + case webview::WebviewRequest::kGoBack: + contents_->GetController().GoBack(); + break; + + case webview::WebviewRequest::kGoForward: + contents_->GetController().GoForward(); + break; + + case webview::WebviewRequest::kReload: + // TODO(dnicoara): Are the default parameters correct? + contents_->GetController().Reload(content::ReloadType::NORMAL, + /*check_for_repost=*/true); + break; + + case webview::WebviewRequest::kClearCache: + HandleClearCache(); + break; + + case webview::WebviewRequest::kUpdateSettings: + if (request.has_update_settings()) { + HandleUpdateSettings(request.update_settings()); + } else { + client_->OnError("update_settings() not supplied"); + } + break; + + case webview::WebviewRequest::kGetTitle: + HandleGetTitle(); + break; + + case webview::WebviewRequest::kSetAutoMediaPlaybackPolicy: + if (request.has_set_auto_media_playback_policy()) { + HandleSetAutoMediaPlaybackPolicy( + request.set_auto_media_playback_policy()); + } else { + client_->OnError("set_auto_media_playback_policy() not supplied"); + } + break; + default: client_->OnError("Unknown request code"); break; @@ -134,6 +215,115 @@ } } +void WebviewController::JavascriptCallback(base::Value result) { + std::string json; + base::JSONWriter::Write(result, &json); + std::unique_ptr<webview::WebviewResponse> response = + std::make_unique<webview::WebviewResponse>(); + response->mutable_evaluate_javascript()->set_json(json); + client_->EnqueueSend(std::move(response)); +} + +void WebviewController::HandleEvaluateJavascript( + const webview::EvaluateJavascriptRequest& request) { + contents_->GetMainFrame()->ExecuteJavaScript( + base::UTF8ToUTF16(request.javascript_blob()), + base::BindOnce(&WebviewController::JavascriptCallback, + weak_ptr_factory_.GetWeakPtr())); +} + +void WebviewController::HandleAddJavascriptChannels( + const webview::AddJavascriptChannelsRequest& request) { + // TODO(dnicoara): Handle this. + client_->OnError("Unimplemented add_javascript_channels()"); +} + +void WebviewController::HandleRemoveJavascriptChannels( + const webview::RemoveJavascriptChannelsRequest& request) { + // TODO(dnicoara): Handle this. + client_->OnError("Unimplemented remove_javascript_channels()"); +} + +void WebviewController::HandleGetCurrentUrl() { + std::unique_ptr<webview::WebviewResponse> response = + std::make_unique<webview::WebviewResponse>(); + + response->mutable_get_current_url()->set_url(contents_->GetURL().spec()); + client_->EnqueueSend(std::move(response)); +} + +void WebviewController::HandleCanGoBack() { + std::unique_ptr<webview::WebviewResponse> response = + std::make_unique<webview::WebviewResponse>(); + + response->mutable_can_go_back()->set_can_go_back( + contents_->GetController().CanGoBack()); + client_->EnqueueSend(std::move(response)); +} + +void WebviewController::HandleCanGoForward() { + std::unique_ptr<webview::WebviewResponse> response = + std::make_unique<webview::WebviewResponse>(); + + response->mutable_can_go_forward()->set_can_go_forward( + contents_->GetController().CanGoForward()); + client_->EnqueueSend(std::move(response)); +} + +void WebviewController::HandleClearCache() { + // TODO(dnicoara): See if there is a generic way to inform the renderer to + // clear cache. + // Android has a specific renderer message for this: + // https://cs.chromium.org/chromium/src/android_webview/common/render_view_messages.h?rcl=65107121555167a3db39de5633c3297f7e861315&l=44 + + // Remove disk cache. + content::BrowsingDataRemover* remover = + content::BrowserContext::GetBrowsingDataRemover( + contents_->GetBrowserContext()); + remover->Remove(base::Time(), base::Time::Max(), + content::BrowsingDataRemover::DATA_TYPE_CACHE, + content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB | + content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB); +} + +void WebviewController::HandleGetTitle() { + std::unique_ptr<webview::WebviewResponse> response = + std::make_unique<webview::WebviewResponse>(); + + response->mutable_get_title()->set_title( + base::UTF16ToUTF8(contents_->GetTitle())); + client_->EnqueueSend(std::move(response)); +} + +void WebviewController::HandleUpdateSettings( + const webview::UpdateSettingsRequest& request) { + content::WebPreferences prefs = + contents_->GetRenderViewHost()->GetWebkitPreferences(); + prefs.javascript_enabled = request.javascript_enabled(); + contents_->GetRenderViewHost()->UpdateWebkitPreferences(prefs); + + // TODO(dnicoara): Add support for |has_navigation_delegate|. + + // Given that cast_shell enables devtools unconditionally there isn't + // anything that needs to be done for |request.debugging_enabled()|. Though, + // as a note, remote debugging is always on. + + if (request.has_user_agent() && + request.user_agent().type_case() == webview::UserAgent::kValue) { + contents_->SetUserAgentOverride(request.user_agent().value(), true); + } +} + +void WebviewController::HandleSetAutoMediaPlaybackPolicy( + const webview::SetAutoMediaPlaybackPolicyRequest& request) { + content::WebPreferences prefs = + contents_->GetRenderViewHost()->GetWebkitPreferences(); + prefs.autoplay_policy = request.require_user_gesture() + ? content::AutoplayPolicy::kUserGestureRequired + : content::AutoplayPolicy::kNoUserGestureRequired; + contents_->GetRenderViewHost()->UpdateWebkitPreferences(prefs); +} + webview::AsyncPageEvent_State WebviewController::current_state() { // The PB enum is defined identically. return static_cast<webview::AsyncPageEvent_State>(
diff --git a/chromecast/browser/webview/webview_controller.h b/chromecast/browser/webview/webview_controller.h index 627b03e..9a7160b 100644 --- a/chromecast/browser/webview/webview_controller.h +++ b/chromecast/browser/webview/webview_controller.h
@@ -58,6 +58,21 @@ webview::AsyncPageEvent_State current_state(); void ProcessInputEvent(const webview::InputEvent& ev); + void JavascriptCallback(base::Value result); + void HandleEvaluateJavascript( + const webview::EvaluateJavascriptRequest& request); + void HandleAddJavascriptChannels( + const webview::AddJavascriptChannelsRequest& request); + void HandleRemoveJavascriptChannels( + const webview::RemoveJavascriptChannelsRequest& request); + void HandleGetCurrentUrl(); + void HandleCanGoBack(); + void HandleCanGoForward(); + void HandleClearCache(); + void HandleGetTitle(); + void HandleUpdateSettings(const webview::UpdateSettingsRequest& request); + void HandleSetAutoMediaPlaybackPolicy( + const webview::SetAutoMediaPlaybackPolicyRequest& request); bool Check(bool condition, const char* error); @@ -74,6 +89,8 @@ std::unique_ptr<CastWebContents> cast_web_contents_; bool stopped_ = false; + base::WeakPtrFactory<WebviewController> weak_ptr_factory_{this}; + DISALLOW_COPY_AND_ASSIGN(WebviewController); };
diff --git a/chromeos/components/media_app_ui/OWNERS b/chromeos/components/media_app_ui/OWNERS index 13c6f49f..c0abe0f6 100644 --- a/chromeos/components/media_app_ui/OWNERS +++ b/chromeos/components/media_app_ui/OWNERS
@@ -1 +1,7 @@ tapted@chromium.org +dstockwell@chromium.org +bugsnash@chromium.org + +# TEAM: cros-essential-apps-dev@chromium.org +# COMPONENT: Platform>Apps>PhotoEditor +# Internal Component: b/components/562866
diff --git a/chromeos/profiles/orderfile.newest.txt b/chromeos/profiles/orderfile.newest.txt index e7667a6e..d5f2205 100644 --- a/chromeos/profiles/orderfile.newest.txt +++ b/chromeos/profiles/orderfile.newest.txt
@@ -1 +1 @@ -chromeos-chrome-orderfile-field-79-3904.12-1569231291-benchmark-78.0.3902.0-r1.orderfile.xz \ No newline at end of file +chromeos-chrome-orderfile-field-79-3904.12-1569231291-benchmark-79.0.3923.0-r1.orderfile.xz \ No newline at end of file
diff --git a/chromeos/services/machine_learning/public/cpp/fake_service_connection.cc b/chromeos/services/machine_learning/public/cpp/fake_service_connection.cc index 3d9ce55..860107a 100644 --- a/chromeos/services/machine_learning/public/cpp/fake_service_connection.cc +++ b/chromeos/services/machine_learning/public/cpp/fake_service_connection.cc
@@ -14,10 +14,18 @@ FakeServiceConnectionImpl::~FakeServiceConnectionImpl() {} -void FakeServiceConnectionImpl::LoadModel( - mojom::ModelSpecPtr spec, +void FakeServiceConnectionImpl::LoadBuiltinModel( + mojom::BuiltinModelSpecPtr spec, mojom::ModelRequest request, - mojom::MachineLearningService::LoadModelCallback callback) { + mojom::MachineLearningService::LoadBuiltinModelCallback callback) { + model_bindings_.AddBinding(this, std::move(request)); + std::move(callback).Run(mojom::LoadModelResult::OK); +} + +void FakeServiceConnectionImpl::LoadFlatBufferModel( + mojom::FlatBufferModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadFlatBufferModelCallback callback) { model_bindings_.AddBinding(this, std::move(request)); std::move(callback).Run(mojom::LoadModelResult::OK); }
diff --git a/chromeos/services/machine_learning/public/cpp/fake_service_connection.h b/chromeos/services/machine_learning/public/cpp/fake_service_connection.h index df5b778..34ae28b 100644 --- a/chromeos/services/machine_learning/public/cpp/fake_service_connection.h +++ b/chromeos/services/machine_learning/public/cpp/fake_service_connection.h
@@ -30,12 +30,17 @@ FakeServiceConnectionImpl(); ~FakeServiceConnectionImpl() override; - // It's safe to execute LoadModel for multi times, but all the requests will - // be bound to the same instance. - void LoadModel( - mojom::ModelSpecPtr spec, + // It's safe to execute LoadBuiltinModel and LoadFlatBufferModel for multi + // times, but all the requests will be bound to the same instance. + void LoadBuiltinModel(mojom::BuiltinModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadBuiltinModelCallback + callback) override; + void LoadFlatBufferModel( + mojom::FlatBufferModelSpecPtr spec, mojom::ModelRequest request, - mojom::MachineLearningService::LoadModelCallback callback) override; + mojom::MachineLearningService::LoadFlatBufferModelCallback callback) + override; // mojom::Model: void CreateGraphExecutor(
diff --git a/chromeos/services/machine_learning/public/cpp/service_connection.cc b/chromeos/services/machine_learning/public/cpp/service_connection.cc index 39b1b8d..e74c54a1 100644 --- a/chromeos/services/machine_learning/public/cpp/service_connection.cc +++ b/chromeos/services/machine_learning/public/cpp/service_connection.cc
@@ -26,10 +26,16 @@ ServiceConnectionImpl(); ~ServiceConnectionImpl() override = default; - void LoadModel(mojom::ModelSpecPtr spec, - mojom::ModelRequest request, - mojom::MachineLearningService::LoadModelCallback - result_callback) override; + void LoadBuiltinModel(mojom::BuiltinModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadBuiltinModelCallback + result_callback) override; + + void LoadFlatBufferModel( + mojom::FlatBufferModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadFlatBufferModelCallback + result_callback) override; private: // Binds the top level interface |machine_learning_service_| to an @@ -51,14 +57,25 @@ DISALLOW_COPY_AND_ASSIGN(ServiceConnectionImpl); }; -void ServiceConnectionImpl::LoadModel( - mojom::ModelSpecPtr spec, +void ServiceConnectionImpl::LoadBuiltinModel( + mojom::BuiltinModelSpecPtr spec, mojom::ModelRequest request, - mojom::MachineLearningService::LoadModelCallback result_callback) { + mojom::MachineLearningService::LoadBuiltinModelCallback result_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); BindMachineLearningServiceIfNeeded(); - machine_learning_service_->LoadModel(std::move(spec), std::move(request), - std::move(result_callback)); + machine_learning_service_->LoadBuiltinModel( + std::move(spec), std::move(request), std::move(result_callback)); +} + +void ServiceConnectionImpl::LoadFlatBufferModel( + mojom::FlatBufferModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadFlatBufferModelCallback + result_callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + BindMachineLearningServiceIfNeeded(); + machine_learning_service_->LoadFlatBufferModel( + std::move(spec), std::move(request), std::move(result_callback)); } void ServiceConnectionImpl::BindMachineLearningServiceIfNeeded() {
diff --git a/chromeos/services/machine_learning/public/cpp/service_connection.h b/chromeos/services/machine_learning/public/cpp/service_connection.h index 5b456bdf..d7837fd 100644 --- a/chromeos/services/machine_learning/public/cpp/service_connection.h +++ b/chromeos/services/machine_learning/public/cpp/service_connection.h
@@ -12,13 +12,27 @@ // Encapsulates a connection to the Chrome OS ML Service daemon via its Mojo // interface. -// Usage: +// Usage for Built-in models: // chromeos::machine_learning::mojom::ModelPtr model; -// chromeos::machine_learning::mojom::ModelSpec spec = ...; +// chromeos::machine_learning::mojom::BuiltinModelSpecPtr spec = +// chromeos::machine_learning::mojom::BuiltinModelSpec::New(); +// spec->id = ...; // chromeos::machine_learning::ServiceConnection::GetInstance() -// ->LoadModel(spec, mojom::MakeRequest(&model), -// base::BindOnce(&MyCallBack)); +// ->LoadBuiltinModel(std::move(spec), mojom::MakeRequest(&model), +// base::BindOnce(&MyCallBack)); // // Use |model| or wait for |MyCallBack|. +// Usage for Flatbuffer models: +// chromeos::machine_learning::mojom::ModelPtr model; +// chromeos::machine_learning::mojom::FlatBufferModelSpecPtr spec = +// chromeos::machine_learning::mojom::FlatBufferModelSpec::New(); +// spec->model_string = ...; +// spec->inputs = ...; +// spec->outputs = ...; +// spec->metrics_model_name = ...; +// chromeos::machine_learning::ServiceConnection::GetInstance() +// ->LoadFlatBufferModel(std::move(spec), mojom::MakeRequest(&model), +// base::BindOnce(&MyCallBack)); +// // Sequencing: Must be used on a single sequence (may be created on another). class ServiceConnection { public: @@ -28,13 +42,23 @@ static void UseFakeServiceConnectionForTesting( ServiceConnection* fake_service_connection); - // Instruct ML daemon to load the model specified in |spec|, binding a Model - // implementation to |request|. - // Bootstraps the initial Mojo connection to the daemon if necessary. - virtual void LoadModel( - mojom::ModelSpecPtr spec, + // Instruct ML daemon to load the builtin model specified in |spec|, binding a + // Model implementation to |request|. Bootstraps the initial Mojo connection + // to the daemon if necessary. + virtual void LoadBuiltinModel( + mojom::BuiltinModelSpecPtr spec, mojom::ModelRequest request, - mojom::MachineLearningService::LoadModelCallback result_callback) = 0; + mojom::MachineLearningService::LoadBuiltinModelCallback + result_callback) = 0; + + // Instruct ML daemon to load the flatbuffer model specified in |spec|, + // binding a Model implementation to |request|. Bootstraps the initial Mojo + // connection to the daemon if necessary. + virtual void LoadFlatBufferModel( + mojom::FlatBufferModelSpecPtr spec, + mojom::ModelRequest request, + mojom::MachineLearningService::LoadFlatBufferModelCallback + result_callback) = 0; protected: ServiceConnection() = default;
diff --git a/chromeos/services/machine_learning/public/cpp/service_connection_unittest.cc b/chromeos/services/machine_learning/public/cpp/service_connection_unittest.cc index 1895d51..fd685dc 100644 --- a/chromeos/services/machine_learning/public/cpp/service_connection_unittest.cc +++ b/chromeos/services/machine_learning/public/cpp/service_connection_unittest.cc
@@ -52,17 +52,90 @@ DISALLOW_COPY_AND_ASSIGN(ServiceConnectionTest); }; -// Tests that BindModelProvider runs OK (no crash) in a basic Mojo environment. -TEST_F(ServiceConnectionTest, BindModelProvider) { +// Tests that LoadBuiltinModel runs OK (no crash) in a basic Mojo +// environment. +TEST_F(ServiceConnectionTest, LoadBuiltinModel) { mojom::ModelPtr model; - mojom::ModelSpecPtr spec = mojom::ModelSpec::New(mojom::ModelId::TEST_MODEL); - ServiceConnection::GetInstance()->LoadModel( + mojom::BuiltinModelSpecPtr spec = + mojom::BuiltinModelSpec::New(mojom::BuiltinModelId::TEST_MODEL); + ServiceConnection::GetInstance()->LoadBuiltinModel( std::move(spec), mojo::MakeRequest(&model), base::BindOnce([](mojom::LoadModelResult result) {})); } -// Tests the fake ML service. -TEST_F(ServiceConnectionTest, FakeServiceConnection) { +// Tests that LoadFlatBufferModel runs OK (no crash) in a basic Mojo +// environment. +TEST_F(ServiceConnectionTest, LoadFlatBufferModel) { + mojom::ModelPtr model; + mojom::FlatBufferModelSpecPtr spec = mojom::FlatBufferModelSpec::New(); + ServiceConnection::GetInstance()->LoadFlatBufferModel( + std::move(spec), mojo::MakeRequest(&model), + base::BindOnce([](mojom::LoadModelResult result) {})); +} + +// Tests the fake ML service for builtin model. +TEST_F(ServiceConnectionTest, FakeServiceConnectionForBuiltinModel) { + mojom::ModelPtr model; + bool callback_done = false; + FakeServiceConnectionImpl fake_service_connection; + ServiceConnection::UseFakeServiceConnectionForTesting( + &fake_service_connection); + + const double expected_value = 200.002; + fake_service_connection.SetOutputValue(std::vector<int64_t>{1L}, + std::vector<double>{expected_value}); + ServiceConnection::GetInstance()->LoadBuiltinModel( + mojom::BuiltinModelSpec::New(mojom::BuiltinModelId::TEST_MODEL), + mojo::MakeRequest(&model), + base::BindOnce( + [](bool* callback_done, mojom::LoadModelResult result) { + EXPECT_EQ(result, mojom::LoadModelResult::OK); + *callback_done = true; + }, + &callback_done)); + base::RunLoop().RunUntilIdle(); + ASSERT_TRUE(callback_done); + ASSERT_TRUE(model.is_bound()); + + callback_done = false; + mojom::GraphExecutorPtr graph; + model->CreateGraphExecutor( + mojo::MakeRequest(&graph), + base::BindOnce( + [](bool* callback_done, mojom::CreateGraphExecutorResult result) { + EXPECT_EQ(result, mojom::CreateGraphExecutorResult::OK); + *callback_done = true; + }, + &callback_done)); + base::RunLoop().RunUntilIdle(); + ASSERT_TRUE(callback_done); + ASSERT_TRUE(graph.is_bound()); + + callback_done = false; + base::flat_map<std::string, mojom::TensorPtr> inputs; + std::vector<std::string> outputs; + graph->Execute(std::move(inputs), std::move(outputs), + base::BindOnce( + [](bool* callback_done, double expected_value, + const mojom::ExecuteResult result, + base::Optional<std::vector<mojom::TensorPtr>> outputs) { + EXPECT_EQ(result, mojom::ExecuteResult::OK); + ASSERT_TRUE(outputs.has_value()); + ASSERT_EQ(outputs->size(), 1LU); + mojom::TensorPtr& tensor = (*outputs)[0]; + EXPECT_EQ(tensor->data->get_float_list()->value[0], + expected_value); + + *callback_done = true; + }, + &callback_done, expected_value)); + + base::RunLoop().RunUntilIdle(); + ASSERT_TRUE(callback_done); +} + +// Tests the fake ML service for flatbuffer model. +TEST_F(ServiceConnectionTest, FakeServiceConnectionForFlatBufferModel) { mojom::ModelPtr model; bool callback_done = false; FakeServiceConnectionImpl fake_service_connection; @@ -73,9 +146,8 @@ fake_service_connection.SetOutputValue(std::vector<int64_t>{1L}, std::vector<double>{expected_value}); - ServiceConnection::GetInstance()->LoadModel( - mojom::ModelSpec::New(mojom::ModelId::TEST_MODEL), - mojo::MakeRequest(&model), + ServiceConnection::GetInstance()->LoadFlatBufferModel( + mojom::FlatBufferModelSpec::New(), mojo::MakeRequest(&model), base::BindOnce( [](bool* callback_done, mojom::LoadModelResult result) { EXPECT_EQ(result, mojom::LoadModelResult::OK);
diff --git a/chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom b/chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom index 68f9e00..745ad0f4 100644 --- a/chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom +++ b/chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom
@@ -29,6 +29,12 @@ // Top-level interface between Chromium and the ML Service daemon. interface MachineLearningService { - // The ModelId inside ModelSpec is used to specify the model to be loaded. - LoadModel(ModelSpec spec, Model& request) => (LoadModelResult result); + // The BuiltinModelId inside BuiltinModelSpec is used to specify the model to + // be loaded. + LoadBuiltinModel(BuiltinModelSpec spec, Model& request) + => (LoadModelResult result); + // The FlatbufferModelSpec contains both of the flatbuffer content and the + // metadata. + LoadFlatBufferModel(FlatBufferModelSpec spec, Model& request) + => (LoadModelResult result); };
diff --git a/chromeos/services/machine_learning/public/mojom/model.mojom b/chromeos/services/machine_learning/public/mojom/model.mojom index 50df002..8ea2ed45 100644 --- a/chromeos/services/machine_learning/public/mojom/model.mojom +++ b/chromeos/services/machine_learning/public/mojom/model.mojom
@@ -21,7 +21,7 @@ // numeric values should never be reused. // ModelIds prefixed with UNSUPPORTED_ are no longer supported. Attempts to load // them will produce an error. -enum ModelId { +enum BuiltinModelId { // Unknown ML model. It is marked as unsupported. UNSUPPORTED_UNKNOWN = 0, // Test ML model. @@ -46,8 +46,30 @@ kMax = MEMORY_ALLOCATION_ERROR, }; -struct ModelSpec { - ModelId id; +// Model specification for builtin models. +// Because ml-service can retrieve a builtin model's content and metadata, only +// an |id| is needed to specify it. +struct BuiltinModelSpec { + BuiltinModelId id; +}; + +// Model specification for downloaded models. +// For a downloaded model, both of the model content and metadata must be +// specified. +struct FlatBufferModelSpec { + // The content of the model's tflite model file. + string model_string; + // A map from input nodes' names to their indices. + map<string, int32> inputs; + // A map from output nodes' names to their indices. + map<string, int32> outputs; + // Used in naming the UMA metric histograms of the model. An example of the + // names of the histograms is: + // + // MachineLearningService.|metrics_model_name|.ExecuteResult.CpuTimeMicrosec + // + // This variable must NOT be empty. + string metrics_model_name; }; // The lifetime of the cached model is tied to the lifetime of the Model
diff --git a/chromeos/services/multidevice_setup/fake_feature_state_observer.cc b/chromeos/services/multidevice_setup/fake_feature_state_observer.cc index 3b2503d..35a7df02 100644 --- a/chromeos/services/multidevice_setup/fake_feature_state_observer.cc +++ b/chromeos/services/multidevice_setup/fake_feature_state_observer.cc
@@ -12,11 +12,11 @@ FakeFeatureStateObserver::~FakeFeatureStateObserver() = default; -mojom::FeatureStateObserverPtr -FakeFeatureStateObserver::GenerateInterfacePtr() { - mojom::FeatureStateObserverPtr interface_ptr; - bindings_.AddBinding(this, mojo::MakeRequest(&interface_ptr)); - return interface_ptr; +mojo::PendingRemote<mojom::FeatureStateObserver> +FakeFeatureStateObserver::GenerateRemote() { + mojo::PendingRemote<mojom::FeatureStateObserver> remote; + receivers_.Add(this, remote.InitWithNewPipeAndPassReceiver()); + return remote; } void FakeFeatureStateObserver::OnFeatureStatesChanged(
diff --git a/chromeos/services/multidevice_setup/fake_feature_state_observer.h b/chromeos/services/multidevice_setup/fake_feature_state_observer.h index 2764644c..cd0a10c 100644 --- a/chromeos/services/multidevice_setup/fake_feature_state_observer.h +++ b/chromeos/services/multidevice_setup/fake_feature_state_observer.h
@@ -9,7 +9,8 @@ #include "base/macros.h" #include "base/optional.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" -#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver_set.h" namespace chromeos { @@ -21,7 +22,7 @@ FakeFeatureStateObserver(); ~FakeFeatureStateObserver() override; - mojom::FeatureStateObserverPtr GenerateInterfacePtr(); + mojo::PendingRemote<mojom::FeatureStateObserver> GenerateRemote(); const std::vector<base::flat_map<mojom::Feature, mojom::FeatureState>>& feature_state_updates() { @@ -37,7 +38,7 @@ std::vector<base::flat_map<mojom::Feature, mojom::FeatureState>> feature_state_updates_; - mojo::BindingSet<mojom::FeatureStateObserver> bindings_; + mojo::ReceiverSet<mojom::FeatureStateObserver> receivers_; DISALLOW_COPY_AND_ASSIGN(FakeFeatureStateObserver); };
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_impl.cc b/chromeos/services/multidevice_setup/multidevice_setup_impl.cc index b7c3902..a4c3708 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_impl.cc +++ b/chromeos/services/multidevice_setup/multidevice_setup_impl.cc
@@ -167,8 +167,8 @@ } void MultiDeviceSetupImpl::AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) { - feature_state_observers_.AddPtr(std::move(observer)); + mojo::PendingRemote<mojom::FeatureStateObserver> observer) { + feature_state_observers_.Add(std::move(observer)); } void MultiDeviceSetupImpl::GetEligibleHostDevices( @@ -331,10 +331,8 @@ void MultiDeviceSetupImpl::OnFeatureStatesChange( const FeatureStateManager::FeatureStatesMap& feature_states_map) { - feature_state_observers_.ForAllPtrs( - [&feature_states_map](mojom::FeatureStateObserver* observer) { - observer->OnFeatureStatesChanged(feature_states_map); - }); + for (auto& observer : feature_state_observers_) + observer->OnFeatureStatesChanged(feature_states_map); } bool MultiDeviceSetupImpl::AttemptSetHost(const std::string& host_device_id) {
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_impl.h b/chromeos/services/multidevice_setup/multidevice_setup_impl.h index 949cd1e0..0f01a47 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_impl.h +++ b/chromeos/services/multidevice_setup/multidevice_setup_impl.h
@@ -12,8 +12,6 @@ #include "chromeos/services/multidevice_setup/host_status_provider.h" #include "chromeos/services/multidevice_setup/multidevice_setup_base.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" -#include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/bindings/interface_ptr_set.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "url/gurl.h" @@ -87,7 +85,7 @@ void AddHostStatusObserver( mojo::PendingRemote<mojom::HostStatusObserver> observer) override; void AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) override; + mojo::PendingRemote<mojom::FeatureStateObserver> observer) override; void GetEligibleHostDevices(GetEligibleHostDevicesCallback callback) override; void SetHostDevice(const std::string& host_device_id, const std::string& auth_token, @@ -141,7 +139,7 @@ AuthTokenValidator* auth_token_validator_; mojo::RemoteSet<mojom::HostStatusObserver> host_status_observers_; - mojo::InterfacePtrSet<mojom::FeatureStateObserver> feature_state_observers_; + mojo::RemoteSet<mojom::FeatureStateObserver> feature_state_observers_; DISALLOW_COPY_AND_ASSIGN(MultiDeviceSetupImpl); };
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_impl_unittest.cc b/chromeos/services/multidevice_setup/multidevice_setup_impl_unittest.cc index 91a13c3..280e2618 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_impl_unittest.cc +++ b/chromeos/services/multidevice_setup/multidevice_setup_impl_unittest.cc
@@ -947,8 +947,7 @@ // because it never requires authentication for either enabling or disabling. TEST_F(MultiDeviceSetupImplTest, FeatureStateChanges_NoAuthTokenRequired) { auto observer = std::make_unique<FakeFeatureStateObserver>(); - multidevice_setup()->AddFeatureStateObserver( - observer->GenerateInterfacePtr()); + multidevice_setup()->AddFeatureStateObserver(observer->GenerateRemote()); EXPECT_EQ(mojom::FeatureState::kUnavailableNoVerifiedHost, CallGetFeatureStates()[mojom::Feature::kInstantTethering]); @@ -981,8 +980,7 @@ TEST_F(MultiDeviceSetupImplTest, FeatureStateChanges_AuthTokenRequired_SmartLock) { auto observer = std::make_unique<FakeFeatureStateObserver>(); - multidevice_setup()->AddFeatureStateObserver( - observer->GenerateInterfacePtr()); + multidevice_setup()->AddFeatureStateObserver(observer->GenerateRemote()); EXPECT_EQ(mojom::FeatureState::kUnavailableNoVerifiedHost, CallGetFeatureStates()[mojom::Feature::kSmartLock]); @@ -1025,8 +1023,7 @@ TEST_F(MultiDeviceSetupImplTest, FeatureStateChanges_AuthTokenRequired_BetterTogetherSuite) { auto observer = std::make_unique<FakeFeatureStateObserver>(); - multidevice_setup()->AddFeatureStateObserver( - observer->GenerateInterfacePtr()); + multidevice_setup()->AddFeatureStateObserver(observer->GenerateRemote()); EXPECT_EQ(mojom::FeatureState::kUnavailableNoVerifiedHost, CallGetFeatureStates()[mojom::Feature::kBetterTogetherSuite]);
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_initializer.cc b/chromeos/services/multidevice_setup/multidevice_setup_initializer.cc index f54219a0..d7f2506 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_initializer.cc +++ b/chromeos/services/multidevice_setup/multidevice_setup_initializer.cc
@@ -119,7 +119,7 @@ } void MultiDeviceSetupInitializer::AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) { + mojo::PendingRemote<mojom::FeatureStateObserver> observer) { if (multidevice_setup_impl_) { multidevice_setup_impl_->AddFeatureStateObserver(std::move(observer)); return;
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_initializer.h b/chromeos/services/multidevice_setup/multidevice_setup_initializer.h index 47e84b0..642bf8b 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_initializer.h +++ b/chromeos/services/multidevice_setup/multidevice_setup_initializer.h
@@ -93,7 +93,7 @@ void AddHostStatusObserver( mojo::PendingRemote<mojom::HostStatusObserver> observer) override; void AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) override; + mojo::PendingRemote<mojom::FeatureStateObserver> observer) override; void GetEligibleHostDevices(GetEligibleHostDevicesCallback callback) override; void SetHostDevice(const std::string& host_device_id, const std::string& auth_token, @@ -137,7 +137,8 @@ mojo::PendingRemote<mojom::AccountStatusChangeDelegate> pending_delegate_; std::vector<mojo::PendingRemote<mojom::HostStatusObserver>> pending_host_status_observers_; - std::vector<mojom::FeatureStateObserverPtr> pending_feature_state_observers_; + std::vector<mojo::PendingRemote<mojom::FeatureStateObserver>> + pending_feature_state_observers_; std::vector<GetEligibleHostDevicesCallback> pending_get_eligible_hosts_args_; std::vector<GetHostStatusCallback> pending_get_host_args_; std::vector<std::tuple<mojom::Feature,
diff --git a/chromeos/services/multidevice_setup/multidevice_setup_service_unittest.cc b/chromeos/services/multidevice_setup/multidevice_setup_service_unittest.cc index a573363..2829f6e2 100644 --- a/chromeos/services/multidevice_setup/multidevice_setup_service_unittest.cc +++ b/chromeos/services/multidevice_setup/multidevice_setup_service_unittest.cc
@@ -256,7 +256,7 @@ auto fake_feature_state_observer = std::make_unique<FakeFeatureStateObserver>(); multidevice_setup_ptr()->AddFeatureStateObserver( - fake_feature_state_observer->GenerateInterfacePtr()); + fake_feature_state_observer->GenerateRemote()); multidevice_setup_ptr().FlushForTesting(); // GetEligibleHostDevices(). @@ -403,7 +403,7 @@ auto fake_feature_state_observer = std::make_unique<FakeFeatureStateObserver>(); multidevice_setup_ptr()->AddFeatureStateObserver( - fake_feature_state_observer->GenerateInterfacePtr()); + fake_feature_state_observer->GenerateRemote()); multidevice_setup_ptr().FlushForTesting(); EXPECT_TRUE(fake_multidevice_setup()->HasAtLeastOneFeatureStateObserver());
diff --git a/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.cc b/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.cc index 098c271..22cb252 100644 --- a/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.cc +++ b/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.cc
@@ -89,10 +89,8 @@ void FakeMultiDeviceSetup::NotifyFeatureStateChanged( const base::flat_map<mojom::Feature, mojom::FeatureState>& feature_states_map) { - feature_state_observers_.ForAllPtrs( - [&feature_states_map](mojom::FeatureStateObserver* observer) { - observer->OnFeatureStatesChanged(feature_states_map); - }); + for (auto& observer : feature_state_observers_) + observer->OnFeatureStatesChanged(feature_states_map); } void FakeMultiDeviceSetup::SetAccountStatusChangeDelegate( @@ -106,8 +104,8 @@ } void FakeMultiDeviceSetup::AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) { - feature_state_observers_.AddPtr(std::move(observer)); + mojo::PendingRemote<mojom::FeatureStateObserver> observer) { + feature_state_observers_.Add(std::move(observer)); } void FakeMultiDeviceSetup::GetEligibleHostDevices(
diff --git a/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.h b/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.h index 0a1e9b25..7702688e 100644 --- a/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.h +++ b/chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.h
@@ -12,7 +12,6 @@ #include "chromeos/services/multidevice_setup/multidevice_setup_base.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/bindings/interface_ptr_set.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/remote_set.h" @@ -94,7 +93,7 @@ void AddHostStatusObserver( mojo::PendingRemote<mojom::HostStatusObserver> observer) override; void AddFeatureStateObserver( - mojom::FeatureStateObserverPtr observer) override; + mojo::PendingRemote<mojom::FeatureStateObserver> observer) override; void GetEligibleHostDevices(GetEligibleHostDevicesCallback callback) override; void SetHostDevice(const std::string& host_device_id, const std::string& auth_token, @@ -119,7 +118,7 @@ mojo::Remote<mojom::AccountStatusChangeDelegate> delegate_; mojo::RemoteSet<mojom::HostStatusObserver> host_status_observers_; - mojo::InterfacePtrSet<mojom::FeatureStateObserver> feature_state_observers_; + mojo::RemoteSet<mojom::FeatureStateObserver> feature_state_observers_; std::vector<GetEligibleHostDevicesCallback> get_eligible_hosts_args_; std::vector<std::tuple<std::string, std::string, SetHostDeviceCallback>>
diff --git a/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.cc b/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.cc index b4a7fe6..7785312 100644 --- a/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.cc +++ b/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.cc
@@ -48,8 +48,7 @@ MultiDeviceSetupClientImpl::MultiDeviceSetupClientImpl( service_manager::Connector* connector) - : feature_state_observer_binding_(this), - remote_device_cache_( + : remote_device_cache_( multidevice::RemoteDeviceCache::Factory::Get()->BuildInstance()), host_status_with_device_(GenerateDefaultHostStatusWithDevice()), feature_states_map_(GenerateDefaultFeatureStatesMap()) { @@ -57,7 +56,7 @@ multidevice_setup_ptr_->AddHostStatusObserver( GenerateHostStatusObserverRemote()); multidevice_setup_ptr_->AddFeatureStateObserver( - GenerateFeatureStatesObserverInterfacePtr()); + GenerateFeatureStatesObserverRemote()); multidevice_setup_ptr_->GetHostStatus( base::BindOnce(&MultiDeviceSetupClientImpl::OnHostStatusChanged, base::Unretained(this))); @@ -160,11 +159,9 @@ return host_status_observer_receiver_.BindNewPipeAndPassRemote(); } -mojom::FeatureStateObserverPtr -MultiDeviceSetupClientImpl::GenerateFeatureStatesObserverInterfacePtr() { - mojom::FeatureStateObserverPtr interface_ptr; - feature_state_observer_binding_.Bind(mojo::MakeRequest(&interface_ptr)); - return interface_ptr; +mojo::PendingRemote<mojom::FeatureStateObserver> +MultiDeviceSetupClientImpl::GenerateFeatureStatesObserverRemote() { + return feature_state_observer_receiver_.BindNewPipeAndPassRemote(); } void MultiDeviceSetupClientImpl::FlushForTesting() {
diff --git a/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.h b/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.h index d42e058..bbb39b2 100644 --- a/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.h +++ b/chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client_impl.h
@@ -16,7 +16,6 @@ #include "chromeos/components/multidevice/remote_device_ref.h" #include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" -#include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -89,14 +88,16 @@ mojo::PendingRemote<mojom::HostStatusObserver> GenerateHostStatusObserverRemote(); - mojom::FeatureStateObserverPtr GenerateFeatureStatesObserverInterfacePtr(); + mojo::PendingRemote<mojom::FeatureStateObserver> + GenerateFeatureStatesObserverRemote(); void FlushForTesting(); mojom::MultiDeviceSetupPtr multidevice_setup_ptr_; mojo::Receiver<mojom::HostStatusObserver> host_status_observer_receiver_{ this}; - mojo::Binding<mojom::FeatureStateObserver> feature_state_observer_binding_; + mojo::Receiver<mojom::FeatureStateObserver> feature_state_observer_receiver_{ + this}; std::unique_ptr<multidevice::RemoteDeviceCache> remote_device_cache_; HostStatusWithDevice host_status_with_device_;
diff --git a/chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom b/chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom index c74e6ec..2421ba5 100644 --- a/chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom +++ b/chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom
@@ -146,8 +146,8 @@ AddHostStatusObserver(pending_remote<HostStatusObserver> observer); // Adds an observer of feature state changes. To stop observing, disconnect - // the FeatureStateObserverPtr passed here. - AddFeatureStateObserver(FeatureStateObserver observer); + // the pending_remote<FeatureStateObserver> passed here. + AddFeatureStateObserver(pending_remote<FeatureStateObserver> observer); // Provides a list of all eligible host devices (i.e., those which can be // passed to SetHostDevice()).
diff --git a/chromeos/settings/cros_settings_names.cc b/chromeos/settings/cros_settings_names.cc index 9f72e6c1..0b430905a 100644 --- a/chromeos/settings/cros_settings_names.cc +++ b/chromeos/settings/cros_settings_names.cc
@@ -31,6 +31,7 @@ "arc_kiosk_action"; const char kAccountsPrefDeviceLocalAccountsKeyArcKioskDisplayName[] = "arc_kiosk_display_name"; +const char kAccountsPrefDeviceLocalAccountsKeyWebKioskUrl[] = "web_kiosk_url"; const char kAccountsPrefDeviceLocalAccountAutoLoginId[] = "cros.accounts.deviceLocalAccountAutoLoginId"; const char kAccountsPrefDeviceLocalAccountAutoLoginDelay[] =
diff --git a/chromeos/settings/cros_settings_names.h b/chromeos/settings/cros_settings_names.h index 90665ae..4ae7792 100644 --- a/chromeos/settings/cros_settings_names.h +++ b/chromeos/settings/cros_settings_names.h
@@ -38,6 +38,8 @@ COMPONENT_EXPORT(CHROMEOS_SETTINGS) extern const char kAccountsPrefDeviceLocalAccountsKeyArcKioskDisplayName[]; COMPONENT_EXPORT(CHROMEOS_SETTINGS) +extern const char kAccountsPrefDeviceLocalAccountsKeyWebKioskUrl[]; +COMPONENT_EXPORT(CHROMEOS_SETTINGS) extern const char kAccountsPrefDeviceLocalAccountAutoLoginId[]; COMPONENT_EXPORT(CHROMEOS_SETTINGS) extern const char kAccountsPrefDeviceLocalAccountAutoLoginDelay[];
diff --git a/chromeos/test/data/oobe_configuration/TestLeaveWelcomeScreen.json b/chromeos/test/data/oobe_configuration/TestLeaveWelcomeScreen.json index babeb398..9a17f15 100644 --- a/chromeos/test/data/oobe_configuration/TestLeaveWelcomeScreen.json +++ b/chromeos/test/data/oobe_configuration/TestLeaveWelcomeScreen.json
@@ -1,3 +1,3 @@ { - "welcomeNext": true, -} \ No newline at end of file + "welcomeNext": true +}
diff --git a/components/arc/ime/OWNERS b/components/arc/ime/OWNERS index 9d5fb32..537633a 100644 --- a/components/arc/ime/OWNERS +++ b/components/arc/ime/OWNERS
@@ -1,4 +1,5 @@ kinaba@chromium.org +tetsui@chromium.org yhanada@chromium.org # COMPONENT: UI>Input>Text>IME
diff --git a/components/arc/video_accelerator/arc_video_accelerator_util.cc b/components/arc/video_accelerator/arc_video_accelerator_util.cc index c0869683..3e463f3d 100644 --- a/components/arc/video_accelerator/arc_video_accelerator_util.cc +++ b/components/arc/video_accelerator/arc_video_accelerator_util.cc
@@ -36,23 +36,14 @@ return false; } - // Offsets monotonically increase and strides monotonically decrease. - // Note: this offset assumption might not be correct if planes are stored in - // multiple buffers. - // TODO(b/127230761): Remove this offset check once one fd is given per one - // plane. + // Strides monotonically decrease. for (size_t i = 1; i < num_planes; i++) { - if (gmb_handle.native_pixmap_handle.planes[i].offset < - gmb_handle.native_pixmap_handle.planes[i - 1].offset) { - return false; - } if (gmb_handle.native_pixmap_handle.planes[i - 1].stride < gmb_handle.native_pixmap_handle.planes[i].stride) { return false; } } - size_t prev_buffer_end = 0; for (size_t i = 0; i < num_planes; i++) { const auto& plane = gmb_handle.native_pixmap_handle.planes[i]; DVLOGF(4) << "Plane " << i << ", offset: " << plane.offset @@ -82,15 +73,6 @@ VLOGF(1) << "Invalid strides/offsets"; return false; } - - // The end of the previous plane must not be bigger than the offset of the - // current plane. - // TODO(b/127230761): Remove this check once one fd is given per one plane. - if (prev_buffer_end > base::checked_cast<size_t>(plane.offset)) { - VLOGF(1) << "Invalid offset"; - return false; - } - prev_buffer_end = min_buffer_size.ValueOrDie(); } return true; @@ -140,27 +122,66 @@ return true; } +std::vector<base::ScopedFD> DuplicateFD(base::ScopedFD fd, size_t num_fds) { + if (!fd.is_valid()) { + VLOGF(1) << "Input fd is not valid"; + return {}; + } + + std::vector<base::ScopedFD> fds(num_fds); + fds[0] = std::move(fd); + for (size_t i = 1; i < num_fds; ++i) { + base::ScopedFD dup_fd(HANDLE_EINTR(dup(fds[0].get()))); + if (!dup_fd.is_valid()) { + VLOGF(1) << "Failed to duplicate fd"; + return {}; + } + fds[i] = std::move(dup_fd); + } + + return fds; +} + base::Optional<gfx::GpuMemoryBufferHandle> CreateGpuMemoryBufferHandle( media::VideoPixelFormat pixel_format, const gfx::Size& coded_size, - base::ScopedFD fd, + std::vector<base::ScopedFD> scoped_fds, const std::vector<VideoFramePlane>& planes) { + std::vector<media::ColorPlaneLayout> color_planes; + for (size_t i = 0; i < planes.size(); ++i) { + int32_t stride = base::checked_cast<int32_t>(planes[i].stride); + size_t offset = base::checked_cast<size_t>(planes[i].offset); + size_t plane_height = + media::VideoFrame::Rows(i, pixel_format, coded_size.height()); + base::CheckedNumeric<size_t> current_size = + base::CheckMul(stride, plane_height); + if (!current_size.IsValid()) { + VLOGF(1) << "Invalid stride/height"; + return base::nullopt; + } + + color_planes.emplace_back(stride, offset, current_size.ValueOrDie()); + } + + return CreateGpuMemoryBufferHandle(pixel_format, coded_size, + std::move(scoped_fds), color_planes); +} + +base::Optional<gfx::GpuMemoryBufferHandle> CreateGpuMemoryBufferHandle( + media::VideoPixelFormat pixel_format, + const gfx::Size& coded_size, + std::vector<base::ScopedFD> scoped_fds, + const std::vector<media::ColorPlaneLayout>& planes) { const size_t num_planes = media::VideoFrame::NumPlanes(pixel_format); if (planes.size() != num_planes || planes.size() == 0) { VLOGF(1) << "Invalid number of dmabuf planes passed: " << planes.size() << ", expected: " << num_planes; return base::nullopt; } - - std::array<base::ScopedFD, media::VideoFrame::kMaxPlanes> scoped_fds; - DCHECK_LE(num_planes, media::VideoFrame::kMaxPlanes); - scoped_fds[0] = std::move(fd); - for (size_t i = 1; i < num_planes; ++i) { - scoped_fds[i].reset(HANDLE_EINTR(dup(scoped_fds[0].get()))); - if (!scoped_fds[i].is_valid()) { - VLOGF(1) << "Failed to duplicate fd"; - return base::nullopt; - } + if (scoped_fds.size() != num_planes) { + VLOGF(1) << "Invalid number of fds passed: " << scoped_fds.size() + << ", expected: " << num_planes; + return base::nullopt; } gfx::GpuMemoryBufferHandle gmb_handle; @@ -178,17 +199,9 @@ } uint32_t stride = base::checked_cast<uint32_t>(planes[i].stride); uint64_t offset = base::checked_cast<uint64_t>(planes[i].offset); - - size_t plane_height = - media::VideoFrame::Rows(i, pixel_format, coded_size.height()); - base::CheckedNumeric<uint64_t> current_size = - base::CheckMul(stride, plane_height); - if (!current_size.IsValid()) { - VLOGF(1) << "Invalid stride/height"; - return base::nullopt; - } + uint64_t size = base::checked_cast<uint64_t>(planes[i].size); gmb_handle.native_pixmap_handle.planes.emplace_back( - stride, offset, current_size.ValueOrDie(), std::move(scoped_fds[i])); + stride, offset, size, std::move(scoped_fds[i])); } if (!VerifyGpuMemoryBufferHandle(pixel_format, coded_size, gmb_handle))
diff --git a/components/arc/video_accelerator/arc_video_accelerator_util.h b/components/arc/video_accelerator/arc_video_accelerator_util.h index 8eada637..d832c08 100644 --- a/components/arc/video_accelerator/arc_video_accelerator_util.h +++ b/components/arc/video_accelerator/arc_video_accelerator_util.h
@@ -11,6 +11,7 @@ #include "base/files/scoped_file.h" #include "base/optional.h" #include "components/arc/video_accelerator/video_frame_plane.h" +#include "media/base/color_plane_layout.h" #include "media/base/video_types.h" #include "mojo/public/cpp/system/handle.h" #include "ui/gfx/geometry/size.h" @@ -25,14 +26,23 @@ // Return the file size of |fd| in bytes. bool GetFileSize(const int fd, size_t* size); +// Return a list of duplicated |fd|. The size of list is |num_fds|. Return an +// empty list if duplicatation fails. +std::vector<base::ScopedFD> DuplicateFD(base::ScopedFD fd, size_t num_fds); + // Return GpuMemoryBufferHandle iff |planes| are valid for a video frame located -// on |fd| and of |pixel_format| and |coded_size|. Otherwise returns -// base::nullopt. +// on |scoped_fds| and of |pixel_format| and |coded_size|. Otherwise +// returns base::nullopt. base::Optional<gfx::GpuMemoryBufferHandle> CreateGpuMemoryBufferHandle( media::VideoPixelFormat pixel_format, const gfx::Size& coded_size, - base::ScopedFD fd, + std::vector<base::ScopedFD> scoped_fds, const std::vector<VideoFramePlane>& planes); +base::Optional<gfx::GpuMemoryBufferHandle> CreateGpuMemoryBufferHandle( + media::VideoPixelFormat pixel_format, + const gfx::Size& coded_size, + std::vector<base::ScopedFD> scoped_fds, + const std::vector<media::ColorPlaneLayout>& planes); // Create a temp file and write |data| into the file. base::ScopedFD CreateTempFileForTesting(const std::string& data);
diff --git a/components/arc/video_accelerator/gpu_arc_video_decode_accelerator.cc b/components/arc/video_accelerator/gpu_arc_video_decode_accelerator.cc index 0e035f6..ba07a3d 100644 --- a/components/arc/video_accelerator/gpu_arc_video_decode_accelerator.cc +++ b/components/arc/video_accelerator/gpu_arc_video_decode_accelerator.cc
@@ -486,8 +486,17 @@ } gmb_handle.native_pixmap_handle = std::move(protected_native_pixmap); } else { + std::vector<base::ScopedFD> handle_fds = + DuplicateFD(std::move(handle_fd), planes.size()); + if (handle_fds.empty()) { + VLOGF(1) << "Failed to duplicate fd"; + client_->NotifyError( + mojom::VideoDecodeAccelerator::Result::INVALID_ARGUMENT); + return; + } + auto handle = CreateGpuMemoryBufferHandle(pixel_format, coded_size_, - std::move(handle_fd), planes); + std::move(handle_fds), planes); if (!handle) { VLOGF(1) << "Failed to create GpuMemoryBufferHandle"; client_->NotifyError(
diff --git a/components/arc/video_accelerator/gpu_arc_video_encode_accelerator.cc b/components/arc/video_accelerator/gpu_arc_video_encode_accelerator.cc index 4e3f09f..1e51c700 100644 --- a/components/arc/video_accelerator/gpu_arc_video_encode_accelerator.cc +++ b/components/arc/video_accelerator/gpu_arc_video_encode_accelerator.cc
@@ -182,8 +182,14 @@ return; } + std::vector<base::ScopedFD> fds = DuplicateFD(std::move(fd), planes.size()); + if (fds.empty()) { + DLOG(ERROR) << "Failed to duplicate fd"; + client_->NotifyError(Error::kInvalidArgumentError); + return; + } auto gmb_handle = - CreateGpuMemoryBufferHandle(format, coded_size_, std::move(fd), planes); + CreateGpuMemoryBufferHandle(format, coded_size_, std::move(fds), planes); if (!gmb_handle) { DLOG(ERROR) << "Failed to create GpuMemoryBufferHandle"; client_->NotifyError(Error::kInvalidArgumentError); @@ -232,8 +238,17 @@ return; } - auto gmb_handle = CreateGpuMemoryBufferHandle( - format, coded_size_, base::ScopedFD(HANDLE_EINTR(dup(fd.get()))), planes); + base::ScopedFD dup_fd(HANDLE_EINTR(dup(fd.get()))); + std::vector<base::ScopedFD> fds = + DuplicateFD(std::move(dup_fd), planes.size()); + if (fds.empty()) { + DLOG(ERROR) << "Failed to duplicate fd"; + client_->NotifyError(Error::kInvalidArgumentError); + return; + } + + auto gmb_handle = + CreateGpuMemoryBufferHandle(format, coded_size_, std::move(fds), planes); if (!gmb_handle) { DLOG(ERROR) << "Failed to create GpuMemoryBufferHandle"; client_->NotifyError(Error::kInvalidArgumentError);
diff --git a/components/autofill/core/browser/autofill_metrics_unittest.cc b/components/autofill/core/browser/autofill_metrics_unittest.cc index e72ad9ed..5f57321 100644 --- a/components/autofill/core/browser/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/autofill_metrics_unittest.cc
@@ -7463,7 +7463,8 @@ } // Verify that we correctly log metrics tracking the duration of form fill. -TEST_F(AutofillMetricsTest, FormFillDuration) { +// TODO(crbug.com/1009364) Test is flake on many builders. +TEST_F(AutofillMetricsTest, DISABLED_FormFillDuration) { // Load a fillable form. FormData form; form.name = ASCIIToUTF16("TestForm");
diff --git a/components/autofill_assistant/browser/details.cc b/components/autofill_assistant/browser/details.cc index 294d566..0b5b66d 100644 --- a/components/autofill_assistant/browser/details.cc +++ b/components/autofill_assistant/browser/details.cc
@@ -7,18 +7,80 @@ #include <unordered_set> #include <base/strings/stringprintf.h> +#include "base/i18n/time_formatting.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/time/time.h" #include "components/autofill/core/browser/geo/country_names.h" #include "components/autofill_assistant/browser/trigger_context.h" #include "components/strings/grit/components_strings.h" +#include "third_party/re2/src/re2/re2.h" #include "ui/base/l10n/l10n_util.h" namespace autofill_assistant { +namespace { +// TODO(b/141850276): Remove hardcoded formatting strings. +constexpr char kDateFormat[] = "EEE, MMM d"; +constexpr char kTimeFormat[] = "h:mm a"; +constexpr char kDateTimeSeparator[] = " \xE2\x80\xA2 "; constexpr char kSpaceBetweenCardNumAndDate[] = " "; +// Parse RFC 3339 date-time. Store the value in the datetime proto field. +bool ParseDateTimeStringToProto(const std::string& datetime, + DateTimeProto* result) { + // RFC 3339 format without timezone: yyyy'-'MM'-'dd'T'HH':'mm':'ss + std::string pattern = + R"rgx((\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}))rgx"; + + int year, month, day, hour, minute, second; + if (re2::RE2::FullMatch(datetime, pattern, &year, &month, &day, &hour, + &minute, &second)) { + auto* date = result->mutable_date(); + date->set_year(year); + date->set_month(month); + date->set_day(day); + auto* time = result->mutable_time(); + time->set_hour(hour); + time->set_minute(minute); + time->set_second(second); + return true; + } else { + return false; + } +} + +// Format a datetime proto with current locale. +std::string FormatDateTimeProto(const DateTimeProto& date_time) { + if (!date_time.has_date() || !date_time.has_time()) { + return std::string(); + } + auto date_proto = date_time.date(); + auto time_proto = date_time.time(); + + base::Time::Exploded exploded_time = { + date_proto.year(), date_proto.month(), + /* day_of_week = */ -1, date_proto.day(), time_proto.hour(), + time_proto.minute(), time_proto.second(), 0}; + base::Time time; + + if (base::Time::FromLocalExploded(exploded_time, &time)) { + auto date_string = base::TimeFormatWithPattern(time, kDateFormat); + auto time_string = base::TimeFormatWithPattern(time, kTimeFormat); + + return base::StrCat({base::UTF16ToUTF8(time_string), kDateTimeSeparator, + base::UTF16ToUTF8(date_string)}); + } + + return std::string(); +} + +} // namespace + +Details::Details() = default; +Details::~Details() = default; + // static bool Details::UpdateFromProto(const ShowDetailsProto& proto, Details* details) { if (!proto.has_details()) { @@ -125,52 +187,45 @@ base::Value Details::GetDebugContext() const { base::Value dict(base::Value::Type::DICTIONARY); - if (!details_proto().title().empty()) - dict.SetKey("title", base::Value(details_proto().title())); + if (!proto_.title().empty()) + dict.SetKey("title", base::Value(proto_.title())); - if (!details_proto().image_url().empty()) - dict.SetKey("image_url", base::Value(details_proto().image_url())); + if (!proto_.image_url().empty()) + dict.SetKey("image_url", base::Value(proto_.image_url())); - if (!details_proto().total_price().empty()) - dict.SetKey("total_price", base::Value(details_proto().total_price())); + if (!proto_.total_price().empty()) + dict.SetKey("total_price", base::Value(proto_.total_price())); - if (!details_proto().total_price_label().empty()) - dict.SetKey("total_price_label", - base::Value(details_proto().total_price_label())); + if (!proto_.total_price_label().empty()) + dict.SetKey("total_price_label", base::Value(proto_.total_price_label())); - if (!details_proto().description_line_1().empty()) - dict.SetKey("description_line_1", - base::Value(details_proto().description_line_1())); + if (!proto_.description_line_1().empty()) + dict.SetKey("description_line_1", base::Value(proto_.description_line_1())); - if (!details_proto().description_line_2().empty()) - dict.SetKey("description_line_2", - base::Value(details_proto().description_line_2())); + if (!proto_.description_line_2().empty()) + dict.SetKey("description_line_2", base::Value(proto_.description_line_2())); - if (!details_proto().description_line_3().empty()) - dict.SetKey("description_line_3", - base::Value(details_proto().description_line_3())); + if (!proto_.description_line_3().empty()) + dict.SetKey("description_line_3", base::Value(proto_.description_line_3())); - if (details_proto().has_datetime()) { - dict.SetKey("datetime", - base::Value(base::StringPrintf( - "%d-%02d-%02dT%02d:%02d:%02d", - static_cast<int>(details_proto().datetime().date().year()), - details_proto().datetime().date().month(), - details_proto().datetime().date().day(), - details_proto().datetime().time().hour(), - details_proto().datetime().time().minute(), - details_proto().datetime().time().second()))); + if (proto_.has_datetime()) { + dict.SetKey( + "datetime", + base::Value(base::StringPrintf( + "%d-%02d-%02dT%02d:%02d:%02d", + static_cast<int>(proto_.datetime().date().year()), + proto_.datetime().date().month(), proto_.datetime().date().day(), + proto_.datetime().time().hour(), proto_.datetime().time().minute(), + proto_.datetime().time().second()))); } - if (!datetime_.empty()) - dict.SetKey("datetime_str", base::Value(datetime_)); dict.SetKey("user_approval_required", - base::Value(changes().user_approval_required())); - dict.SetKey("highlight_title", base::Value(changes().highlight_title())); - dict.SetKey("highlight_line1", base::Value(changes().highlight_line1())); - dict.SetKey("highlight_line2", base::Value(changes().highlight_line2())); - dict.SetKey("highlight_line3", base::Value(changes().highlight_line3())); - dict.SetKey("highlight_line3", base::Value(changes().highlight_line3())); + base::Value(change_flags_.user_approval_required())); + dict.SetKey("highlight_title", base::Value(change_flags_.highlight_title())); + dict.SetKey("highlight_line1", base::Value(change_flags_.highlight_line1())); + dict.SetKey("highlight_line2", base::Value(change_flags_.highlight_line2())); + dict.SetKey("highlight_line3", base::Value(change_flags_.highlight_line3())); + dict.SetKey("highlight_line3", base::Value(change_flags_.highlight_line3())); return dict; } @@ -186,6 +241,7 @@ proto_.set_animate_placeholders(true); proto_.set_show_image_placeholder(true); if (MaybeUpdateFromDetailsParameters(context)) { + Update(); return true; } @@ -208,10 +264,13 @@ base::Optional<std::string> screening_datetime = context.GetParameter("MOVIES_SCREENING_DATETIME"); - if (screening_datetime) { - datetime_ = screening_datetime.value(); + if (screening_datetime && + ParseDateTimeStringToProto(screening_datetime.value(), + proto_.mutable_datetime())) { is_updated = true; } + + Update(); return is_updated; } @@ -278,8 +337,121 @@ return details_updated; } +void Details::SetDetailsProto(const DetailsProto& proto) { + proto_ = proto; + Update(); +} + +const std::string Details::title() const { + return proto_.title(); +} + +int Details::titleMaxLines() const { + return title_max_lines_; +} + +const std::string Details::imageUrl() const { + return proto_.image_url(); +} + +bool Details::imageAllowClickthrough() const { + return proto_.image_clickthrough_data().allow_clickthrough(); +} + +const std::string Details::imageDescription() const { + return proto_.image_clickthrough_data().description(); +} + +const std::string Details::imagePositiveText() const { + return proto_.image_clickthrough_data().positive_text(); +} + +const std::string Details::imageNegativeText() const { + return proto_.image_clickthrough_data().negative_text(); +} + +const std::string Details::imageClickthroughUrl() const { + return proto_.image_clickthrough_data().clickthrough_url(); +} + +bool Details::showImagePlaceholder() const { + return proto_.show_image_placeholder(); +} + +const std::string Details::totalPriceLabel() const { + return proto_.total_price_label(); +} + +const std::string Details::totalPrice() const { + return proto_.total_price(); +} + +const std::string Details::descriptionLine1() const { + return description_line_1_content_; +} + +const std::string Details::descriptionLine2() const { + return proto_.description_line_2(); +} + +const std::string Details::descriptionLine3() const { + return description_line_3_content_; +} + +const std::string Details::priceAttribution() const { + return price_attribution_content_; +} + +bool Details::userApprovalRequired() const { + return change_flags_.user_approval_required(); +} + +bool Details::highlightTitle() const { + return change_flags_.highlight_title(); +} + +bool Details::highlightLine1() const { + return change_flags_.highlight_line1(); +} + +bool Details::highlightLine2() const { + return change_flags_.highlight_line2(); +} + +bool Details::highlightLine3() const { + return change_flags_.highlight_line3(); +} + +bool Details::animatePlaceholders() const { + return proto_.animate_placeholders(); +} + void Details::ClearChanges() { change_flags_.Clear(); } +void Details::Update() { + auto formatted_datetime = FormatDateTimeProto(proto_.datetime()); + description_line_1_content_.assign(proto_.description_line_1().empty() + ? formatted_datetime + : proto_.description_line_1()); + + description_line_3_content_.assign(proto_.total_price().empty() + ? proto_.description_line_3() + : std::string()); + price_attribution_content_.assign(proto_.total_price().empty() + ? std::string() + : proto_.description_line_3()); + + bool isDescriptionLine1Empty = descriptionLine1().empty(); + bool isDescriptionLine2Empty = descriptionLine2().empty(); + if (isDescriptionLine1Empty && isDescriptionLine2Empty) { + title_max_lines_ = 3; + } else if (isDescriptionLine1Empty || isDescriptionLine2Empty) { + title_max_lines_ = 2; + } else { + title_max_lines_ = 1; + } +} + } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/details.h b/components/autofill_assistant/browser/details.h index ccbdf748..fe1e4c6 100644 --- a/components/autofill_assistant/browser/details.h +++ b/components/autofill_assistant/browser/details.h
@@ -17,9 +17,8 @@ class Details { public: - const DetailsProto& details_proto() const { return proto_; } - const DetailsChangesProto& changes() const { return change_flags_; } - const std::string datetime() const { return datetime_; } + Details(); + ~Details(); // Returns a dictionary describing the current execution context, which // is intended to be serialized as JSON string. The execution context is @@ -54,27 +53,58 @@ ClientMemory* client_memory, Details* details); - void SetDetailsProto(const DetailsProto& proto) { proto_ = proto; } - void SetDetailsChangesProto(const DetailsChangesProto& change_flags) { - change_flags_ = change_flags; - } + const std::string title() const; + int titleMaxLines() const; + const std::string imageUrl() const; + bool imageAllowClickthrough() const; + const std::string imageDescription() const; + const std::string imagePositiveText() const; + const std::string imageNegativeText() const; + const std::string imageClickthroughUrl() const; + bool showImagePlaceholder() const; + const std::string totalPriceLabel() const; + const std::string totalPrice() const; + const std::string descriptionLine1() const; + const std::string descriptionLine2() const; + const std::string descriptionLine3() const; + const std::string priceAttribution() const; + bool userApprovalRequired() const; + bool highlightTitle() const; + bool highlightLine1() const; + bool highlightLine2() const; + bool highlightLine3() const; + bool animatePlaceholders() const; + // Clears all change flags. void ClearChanges(); private: + void SetDetailsProto(const DetailsProto& proto); + void SetDetailsChangesProto(const DetailsChangesProto& change_flags) { + change_flags_ = change_flags; + } + // Tries updating the details using generic detail parameters. Returns true // if at least one generic detail parameter was found and used. bool MaybeUpdateFromDetailsParameters(const TriggerContext& context); + // Updates fields by taking the current |proto_| values into account. + void Update(); + DetailsProto proto_; DetailsChangesProto change_flags_; - // RFC 3339 date-time. Ignore if proto.description_line_1 is set. - // - // TODO(crbug.com/806868): parse RFC 3339 date-time on the C++ side and fill - // proto.description_line_1 with the result instead of carrying a string - // representation of the datetime. - std::string datetime_; + // Maximum of lines for the title. + int title_max_lines_ = 1; + + // Content to be shown in description line 1 in the UI. + std::string description_line_1_content_; + + // Content to be shown in description line 3 in the UI. + std::string description_line_3_content_; + + // Content to be shown in the price attribution view in the UI. + std::string price_attribution_content_; }; } // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/details_unittest.cc b/components/autofill_assistant/browser/details_unittest.cc index 8abf364c..b23cabe 100644 --- a/components/autofill_assistant/browser/details_unittest.cc +++ b/components/autofill_assistant/browser/details_unittest.cc
@@ -4,6 +4,7 @@ #include "components/autofill_assistant/browser/details.h" +#include "base/test/icu_test_util.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/geo/country_names.h" @@ -19,11 +20,21 @@ using ::testing::Eq; -MATCHER_P(EqualsProto, message, "") { - std::string expected_serialized, actual_serialized; - message.SerializeToString(&expected_serialized); - arg.SerializeToString(&actual_serialized); - return expected_serialized == actual_serialized; +void SetDateTimeProto(DateTimeProto* proto, + int year, + int month, + int day, + int hour, + int minute, + int second) { + auto* date = proto->mutable_date(); + date->set_year(year); + date->set_month(month); + date->set_day(day); + auto* time = proto->mutable_time(); + time->set_hour(hour); + time->set_minute(minute); + time->set_second(second); } class DetailsTest : public testing::Test { @@ -50,27 +61,6 @@ ClientMemory client_memory_; }; -TEST_F(DetailsTest, DetailsProtoStoredInMemberVariable) { - Details details; - DetailsProto proto; - proto.set_title("title"); - - details.SetDetailsProto(proto); - EXPECT_THAT(proto, EqualsProto(details.details_proto())); -} - -TEST_F(DetailsTest, DetailsChangesProto) { - Details details; - DetailsChangesProto proto; - proto.set_user_approval_required(true); - - details.SetDetailsChangesProto(proto); - EXPECT_THAT(proto, EqualsProto(details.changes())); - - details.ClearChanges(); - EXPECT_THAT(DetailsChangesProto(), EqualsProto(details.changes())); -} - TEST_F(DetailsTest, UpdateFromParametersEmpty) { Details details; // Nothing has to be updated. @@ -87,13 +77,26 @@ EXPECT_FALSE(details.UpdateFromParameters(*context)); } +TEST_F(DetailsTest, UpdateFromParametersSetsPlaceholderFlags) { + std::map<std::string, std::string> parameters; + parameters["DETAILS_SHOW_INITIAL"] = "true"; + + auto context = TriggerContext::Create(parameters, "exps"); + + Details details; + details.UpdateFromParameters(*context); + + EXPECT_TRUE(details.animatePlaceholders()); + EXPECT_TRUE(details.showImagePlaceholder()); +} + TEST_F(DetailsTest, UpdateFromParametersUpdateFromDetails) { std::map<std::string, std::string> parameters; parameters["DETAILS_SHOW_INITIAL"] = "true"; parameters["DETAILS_TITLE"] = "title"; parameters["DETAILS_DESCRIPTION_LINE_1"] = "line1"; parameters["DETAILS_DESCRIPTION_LINE_2"] = "line2"; - parameters["DETAILS_DESCRIPTION_LINE_3"] = "line3"; + parameters["DETAILS_DESCRIPTION_LINE_3"] = "Est. total"; parameters["DETAILS_IMAGE_URL"] = "image"; parameters["DETAILS_IMAGE_CLICKTHROUGH_URL"] = "clickthrough"; parameters["DETAILS_TOTAL_PRICE_LABEL"] = "total"; @@ -104,47 +107,39 @@ Details details; EXPECT_TRUE(details.UpdateFromParameters(*context)); - DetailsProto expected; - expected.set_animate_placeholders(true); - expected.set_show_image_placeholder(true); - - expected.set_title("title"); - expected.set_description_line_1("line1"); - expected.set_description_line_2("line2"); - expected.set_description_line_3("line3"); - expected.set_image_url("image"); - auto* data = expected.mutable_image_clickthrough_data(); - data->set_allow_clickthrough(true); - data->set_clickthrough_url("clickthrough"); - expected.set_total_price_label("total"); - expected.set_total_price("12"); - - EXPECT_THAT(details.details_proto(), EqualsProto(expected)); + EXPECT_TRUE(details.animatePlaceholders()); + EXPECT_THAT(details.title(), Eq("title")); + EXPECT_THAT(details.descriptionLine1(), Eq("line1")); + EXPECT_THAT(details.descriptionLine2(), Eq("line2")); + EXPECT_THAT(details.priceAttribution(), Eq("Est. total")); + EXPECT_THAT(details.imageUrl(), + Eq("image")); // Overwrites show_image_placeholder + EXPECT_TRUE(details.imageAllowClickthrough()); + EXPECT_THAT(details.imageClickthroughUrl(), Eq("clickthrough")); + EXPECT_THAT(details.totalPriceLabel(), Eq("total")); + EXPECT_THAT(details.totalPrice(), Eq("12")); } TEST_F(DetailsTest, UpdateFromParametersBackwardsCompatibility) { + base::test::ScopedRestoreICUDefaultLocale restore_locale; + base::i18n::SetICUDefaultLocale("en_US"); + std::map<std::string, std::string> parameters; parameters["MOVIES_MOVIE_NAME"] = "movie_name"; parameters["MOVIES_THEATER_NAME"] = "movie_theater"; - parameters["MOVIES_SCREENING_DATETIME"] = "datetime"; + parameters["MOVIES_SCREENING_DATETIME"] = "2019-09-26T16:40:02"; auto context = TriggerContext::Create(parameters, "exps"); Details details; EXPECT_TRUE(details.UpdateFromParameters(*context)); - DetailsProto expected; - expected.set_animate_placeholders(true); - expected.set_show_image_placeholder(true); - - expected.set_title("movie_name"); - expected.set_description_line_2("movie_theater"); - - EXPECT_THAT(details.datetime(), "datetime"); - EXPECT_THAT(details.details_proto().title(), "movie_name"); - EXPECT_THAT(details.details_proto().description_line_2(), "movie_theater"); - - EXPECT_THAT(details.details_proto(), EqualsProto(expected)); + EXPECT_TRUE(details.animatePlaceholders()); + EXPECT_TRUE(details.showImagePlaceholder()); + EXPECT_THAT(details.title(), Eq("movie_name")); + EXPECT_THAT(details.descriptionLine2(), Eq("movie_theater")); + EXPECT_THAT(details.descriptionLine1(), + Eq("4:40 PM \xE2\x80\xA2 Thu, Sep 26")); } TEST_F(DetailsTest, UpdateFromProtoNoDetails) { @@ -152,16 +147,16 @@ EXPECT_FALSE(Details::UpdateFromProto(ShowDetailsProto(), &details)); } -TEST_F(DetailsTest, UpdateFromProto) { +TEST_F(DetailsTest, UpdateFromProtoBackwardsCompatibility) { ShowDetailsProto proto; proto.mutable_details()->set_title("title"); - proto.mutable_change_flags()->set_user_approval_required(true); + proto.mutable_details()->set_description("description"); Details details; EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); - EXPECT_EQ(details.details_proto().title(), "title"); - EXPECT_TRUE(details.changes().user_approval_required()); + EXPECT_THAT(details.title(), Eq("title")); + EXPECT_THAT(details.descriptionLine2(), Eq("description")); } TEST_F(DetailsTest, UpdateFromContactDetailsNoAddressInMemory) { @@ -178,11 +173,10 @@ EXPECT_TRUE( Details::UpdateFromContactDetails(proto, &client_memory_, &details)); - const auto& result = details.details_proto(); - EXPECT_THAT(result.title(), + EXPECT_THAT(details.title(), Eq(l10n_util::GetStringUTF8(IDS_PAYMENTS_CONTACT_DETAILS_LABEL))); - EXPECT_THAT(result.description_line_1(), Eq("Charles Hardin Holley")); - EXPECT_THAT(result.description_line_2(), Eq("\xE2\x98\xBA@gmail.com")); + EXPECT_THAT(details.descriptionLine1(), Eq("Charles Hardin Holley")); + EXPECT_THAT(details.descriptionLine2(), Eq("\xE2\x98\xBA@gmail.com")); } TEST_F(DetailsTest, UpdateFromShippingAddressNoAddressInMemory) { @@ -199,12 +193,11 @@ EXPECT_TRUE( Details::UpdateFromShippingAddress(proto, &client_memory_, &details)); - const auto& result = details.details_proto(); EXPECT_THAT( - result.title(), + details.title(), Eq(l10n_util::GetStringUTF8(IDS_PAYMENTS_SHIPPING_ADDRESS_LABEL))); - EXPECT_THAT(result.description_line_1(), Eq("Charles Hardin Holley")); - EXPECT_THAT(result.description_line_2(), + EXPECT_THAT(details.descriptionLine1(), Eq("Charles Hardin Holley")); + EXPECT_THAT(details.descriptionLine2(), Eq("123 Apple St.\nunit 6 79401 Lubbock US")); } @@ -232,13 +225,197 @@ EXPECT_TRUE( Details::UpdateFromSelectedCreditCard(proto, &client_memory_, &details)); - const auto& result = details.details_proto(); EXPECT_THAT( - result.title(), + details.title(), Eq(l10n_util::GetStringUTF8(IDS_PAYMENTS_METHOD_OF_PAYMENT_LABEL))); // The credit card string contains 4 non-ascii dots, we just check that it // does contain something. - EXPECT_FALSE(result.description_line_1().empty()); + EXPECT_FALSE(details.descriptionLine1().empty()); +} + +TEST_F(DetailsTest, GetTitleMaxLines) { + Details details; + + ShowDetailsProto proto_no_description; + proto_no_description.mutable_details()->set_title("title"); + EXPECT_TRUE(Details::UpdateFromProto(proto_no_description, &details)); + EXPECT_THAT(details.titleMaxLines(), Eq(3)); + + ShowDetailsProto proto_description1; + proto_description1.mutable_details()->set_title("title"); + proto_description1.mutable_details()->set_description_line_1("line 1"); + EXPECT_TRUE(Details::UpdateFromProto(proto_description1, &details)); + EXPECT_THAT(details.titleMaxLines(), Eq(2)); + + ShowDetailsProto proto_description2; + proto_description2.mutable_details()->set_title("title"); + proto_description2.mutable_details()->set_description_line_2("line 2"); + EXPECT_TRUE(Details::UpdateFromProto(proto_description2, &details)); + EXPECT_THAT(details.titleMaxLines(), Eq(2)); + + ShowDetailsProto proto_description1_date; + proto_description1_date.mutable_details()->set_title("title"); + SetDateTimeProto( + proto_description1_date.mutable_details()->mutable_datetime(), 2019, 9, + 26, 16, 40, 2); + EXPECT_TRUE(Details::UpdateFromProto(proto_description1_date, &details)); + EXPECT_THAT(details.titleMaxLines(), Eq(2)); + + ShowDetailsProto proto_both_descriptions; + proto_both_descriptions.mutable_details()->set_title("title"); + proto_both_descriptions.mutable_details()->set_description_line_1("line 1"); + proto_both_descriptions.mutable_details()->set_description_line_2("line 2"); + EXPECT_TRUE(Details::UpdateFromProto(proto_both_descriptions, &details)); + EXPECT_THAT(details.titleMaxLines(), Eq(1)); +} + +TEST_F(DetailsTest, GetDescriptionLine1) { + base::test::ScopedRestoreICUDefaultLocale restore_locale; + + Details details; + + ShowDetailsProto proto_description; + proto_description.mutable_details()->set_description_line_1("line 1"); + EXPECT_TRUE(Details::UpdateFromProto(proto_description, &details)); + EXPECT_THAT(details.descriptionLine1(), Eq("line 1")); + + base::i18n::SetICUDefaultLocale("en_US"); + ShowDetailsProto proto_date; + SetDateTimeProto(proto_date.mutable_details()->mutable_datetime(), 2019, 9, + 25, 15, 16, 0); + EXPECT_TRUE(Details::UpdateFromProto(proto_date, &details)); + EXPECT_THAT(details.descriptionLine1(), + Eq("3:16 PM \xE2\x80\xA2 Wed, Sep 25")); + + base::i18n::SetICUDefaultLocale("de_DE"); + ShowDetailsProto proto_date_de; + SetDateTimeProto(proto_date.mutable_details()->mutable_datetime(), 2019, 9, + 25, 15, 16, 0); + EXPECT_TRUE(Details::UpdateFromProto(proto_date, &details)); + EXPECT_THAT(details.descriptionLine1(), + Eq("3:16 PM \xE2\x80\xA2 Mi., 25. Sept.")); + + ShowDetailsProto proto_empty; + proto_empty.mutable_details()->set_title("title"); + EXPECT_TRUE(Details::UpdateFromProto(proto_empty, &details)); + EXPECT_THAT(details.descriptionLine1(), Eq("")); +} + +TEST_F(DetailsTest, GetDescriptionLine2) { + Details details; + + ShowDetailsProto proto_description; + proto_description.mutable_details()->set_title("title"); + proto_description.mutable_details()->set_description_line_2("line 2"); + EXPECT_TRUE(Details::UpdateFromProto(proto_description, &details)); + EXPECT_THAT(details.descriptionLine2(), Eq("line 2")); +} + +TEST_F(DetailsTest, GetDescriptionLine3) { + Details details; + + ShowDetailsProto proto_no_price; + proto_no_price.mutable_details()->set_title("title"); + proto_no_price.mutable_details()->set_description_line_3("line 3"); + EXPECT_TRUE(Details::UpdateFromProto(proto_no_price, &details)); + EXPECT_THAT(details.descriptionLine3(), Eq("line 3")); + + ShowDetailsProto proto_with_price; + proto_with_price.mutable_details()->set_title("title"); + proto_with_price.mutable_details()->set_description_line_3("Est. total"); + proto_with_price.mutable_details()->set_total_price("$2.50"); + EXPECT_TRUE(Details::UpdateFromProto(proto_with_price, &details)); + EXPECT_THAT(details.descriptionLine3(), Eq("")); +} + +TEST_F(DetailsTest, GetPriceAttribution) { + Details details; + + ShowDetailsProto proto_no_price; + proto_no_price.mutable_details()->set_title("title"); + proto_no_price.mutable_details()->set_description_line_3("line 3"); + EXPECT_TRUE(Details::UpdateFromProto(proto_no_price, &details)); + EXPECT_THAT(details.priceAttribution(), Eq("")); + + ShowDetailsProto proto_with_price; + proto_with_price.mutable_details()->set_title("title"); + proto_with_price.mutable_details()->set_description_line_3("Est. total"); + proto_with_price.mutable_details()->set_total_price("$2.50"); + EXPECT_TRUE(Details::UpdateFromProto(proto_with_price, &details)); + EXPECT_THAT(details.priceAttribution(), Eq("Est. total")); +} + +TEST_F(DetailsTest, GetTitle) { + Details details; + ShowDetailsProto proto; + proto.mutable_details()->set_title("title"); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_THAT(details.title(), Eq("title")); +} + +TEST_F(DetailsTest, GetImageUrl) { + Details details; + ShowDetailsProto proto; + proto.mutable_details()->set_image_url("url"); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_THAT(details.imageUrl(), Eq("url")); +} + +TEST_F(DetailsTest, GetClickthroughData) { + Details details; + ShowDetailsProto proto; + auto* clitkthrough_data = + proto.mutable_details()->mutable_image_clickthrough_data(); + clitkthrough_data->set_allow_clickthrough(true); + clitkthrough_data->set_description("description"); + clitkthrough_data->set_positive_text("positive"); + clitkthrough_data->set_negative_text("negative"); + proto.mutable_details() + ->mutable_image_clickthrough_data() + ->set_clickthrough_url("url"); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_TRUE(details.imageAllowClickthrough()); + EXPECT_THAT(details.imageDescription(), Eq("description")); + EXPECT_THAT(details.imagePositiveText(), Eq("positive")); + EXPECT_THAT(details.imageNegativeText(), Eq("negative")); + EXPECT_THAT(details.imageClickthroughUrl(), Eq("url")); +} + +TEST_F(DetailsTest, GetPlaceholderFlags) { + Details details; + ShowDetailsProto proto; + proto.mutable_details()->set_show_image_placeholder(true); + proto.mutable_details()->set_animate_placeholders(true); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_TRUE(details.showImagePlaceholder()); + EXPECT_TRUE(details.animatePlaceholders()); +} + +TEST_F(DetailsTest, GetTotalPrice) { + Details details; + ShowDetailsProto proto; + proto.mutable_details()->set_total_price_label("Total"); + proto.mutable_details()->set_total_price("$2.50"); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_THAT(details.totalPriceLabel(), Eq("Total")); + EXPECT_THAT(details.totalPrice(), Eq("$2.50")); +} + +TEST_F(DetailsTest, GetHighlightFlags) { + Details details; + ShowDetailsProto proto; + proto.mutable_details()->set_title("title"); + proto.mutable_change_flags()->set_user_approval_required(true); + proto.mutable_change_flags()->set_highlight_title(true); + proto.mutable_change_flags()->set_highlight_line1(true); + proto.mutable_change_flags()->set_highlight_line2(true); + proto.mutable_change_flags()->set_highlight_line3(true); + EXPECT_TRUE(Details::UpdateFromProto(proto, &details)); + EXPECT_TRUE(details.userApprovalRequired()); + EXPECT_TRUE(details.highlightTitle()); + EXPECT_TRUE(details.highlightLine1()); + EXPECT_TRUE(details.highlightLine2()); + EXPECT_TRUE(details.highlightLine3()); } } // namespace
diff --git a/components/autofill_assistant/browser/metrics.h b/components/autofill_assistant/browser/metrics.h index 9a387c9..05b9ada 100644 --- a/components/autofill_assistant/browser/metrics.h +++ b/components/autofill_assistant/browser/metrics.h
@@ -117,6 +117,25 @@ kMaxValue = NOT_REQUIRED }; + // The different ways in which DFM can be installed. + // + // GENERATED_JAVA_ENUM_PACKAGE: ( + // org.chromium.chrome.browser.autofill_assistant.metrics) + // GENERATED_JAVA_CLASS_NAME_OVERRIDE: FeatureModuleInstallation + // + // This enum is used in histograms, do not remove/renumber entries. Only add + // at the end and update kMaxValue. Also remember to update the + // AutofillAssistantFeatureModuleInstallation enum listing in + // tools/metrics/histograms/enums.xml. + enum class FeatureModuleInstallation { + DFM_BACKGROUND_INSTALLATION_REQUESTED = 0, + DFM_FOREGROUND_INSTALLATION_SUCCEEDED = 1, + DFM_FOREGROUND_INSTALLATION_FAILED = 2, + DFM_ALREADY_INSTALLED = 3, + + kMaxValue = DFM_ALREADY_INSTALLED + }; + static void RecordDropOut(DropOutReason reason); static void RecordPaymentRequestPrefilledSuccess(bool initially_complete, bool success);
diff --git a/components/constrained_window/constrained_window_views_unittest.cc b/components/constrained_window/constrained_window_views_unittest.cc index 21ea2eb..ef6d1c20 100644 --- a/components/constrained_window/constrained_window_views_unittest.cc +++ b/components/constrained_window/constrained_window_views_unittest.cc
@@ -211,6 +211,12 @@ } // Ensure CreateBrowserModalDialogViews() works correctly with a null parent. +// Flaky on Win10. https://crbug.com/1009182 +#if defined(OS_WIN) +#define MAYBE_NullModalParent DISABLED_NullModalParent +#else +#define MAYBE_NullModalParent NullModalParent +#endif TEST_F(ConstrainedWindowViewsTest, NullModalParent) { // Use desktop widgets (except on ChromeOS) for extra coverage. test_views_delegate()->set_use_desktop_native_widgets(true);
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index e10c21c..bb207bb 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -239,6 +239,7 @@ "surface_unittest.cc", "text_input_unittest.cc", "touch_unittest.cc", + "xdg_shell_surface_unittest.cc", ] deps += [
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index 19ac3bc..fe311892 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -21,6 +21,7 @@ #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" +#include "ui/base/ui_base_types.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" #include "ui/wm/core/transient_window_manager.h" @@ -265,6 +266,11 @@ AttemptToStartDrag(component); } +bool ShellSurface::ShouldAutoMaximize() { + // Unless a child class overrides the behaviour, we will never auto-maximize. + return false; +} + //////////////////////////////////////////////////////////////////////////////// // SurfaceDelegate overrides: @@ -503,6 +509,10 @@ return false; } + // Allow the window to maximize itself on launch. + if (ShouldAutoMaximize()) + initial_show_state_ = ui::SHOW_STATE_MAXIMIZED; + CreateShellSurfaceWidget(initial_show_state_); }
diff --git a/components/exo/shell_surface.h b/components/exo/shell_surface.h index ec05998d..81d9cf3 100644 --- a/components/exo/shell_surface.h +++ b/components/exo/shell_surface.h
@@ -10,6 +10,7 @@ #include "base/containers/circular_deque.h" #include "base/macros.h" #include "components/exo/shell_surface_base.h" +#include "ui/base/ui_base_types.h" namespace ui { class CompositorLock; @@ -81,6 +82,14 @@ // Start an interactive move of surface. void StartMove(); + // Before widget initialization, this method will be called. Depending on the + // implementation, it may return true to force the surface to launch in a + // maximized state. + virtual bool ShouldAutoMaximize(); + + // Return the initial show state for this surface. + ui::WindowShowState initial_show_state() { return initial_show_state_; } + // Overridden from SurfaceDelegate: void OnSetParent(Surface* parent, const gfx::Point& position) override; @@ -163,7 +172,7 @@ gfx::Vector2d pending_origin_offset_accumulator_; int resize_component_ = HTCAPTION; // HT constant (see ui/base/hit_test.h) int pending_resize_component_ = HTCAPTION; - ui::WindowShowState initial_show_state_ = ui::SHOW_STATE_NORMAL; + ui::WindowShowState initial_show_state_ = ui::SHOW_STATE_DEFAULT; bool ignore_window_bounds_changes_ = false; DISALLOW_COPY_AND_ASSIGN(ShellSurface);
diff --git a/components/exo/xdg_shell_surface.cc b/components/exo/xdg_shell_surface.cc index c0e48e7..9bff0a4 100644 --- a/components/exo/xdg_shell_surface.cc +++ b/components/exo/xdg_shell_surface.cc
@@ -4,6 +4,13 @@ #include "components/exo/xdg_shell_surface.h" +#include "ash/frame/non_client_frame_view_ash.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" +#include "ui/views/window/caption_button_layout_constants.h" + namespace exo { //////////////////////////////////////////////////////////////////////////////// @@ -14,12 +21,33 @@ bool activatable, bool can_minimize, int container) - : ShellSurface(surface, - origin, - activatable, - can_minimize, - container) {} + : ShellSurface(surface, origin, activatable, can_minimize, container) {} XdgShellSurface::~XdgShellSurface() {} +bool XdgShellSurface::ShouldAutoMaximize() { + if (initial_show_state() != ui::SHOW_STATE_DEFAULT || is_popup_ || + !CanMaximize()) + return false; + + DCHECK(!widget_); + gfx::Size work_area_size = display::Screen::GetScreen() + ->GetDisplayNearestWindow(host_window()) + .work_area_size(); + DCHECK(!work_area_size.IsEmpty()); + + gfx::Rect window_bounds = GetVisibleBounds(); + // This way to predict the size of the widget if it were maximized is brittle. + // We rely on unit tests to guard against changes in the size of the window + // decorations. + if (frame_enabled()) { + window_bounds.Inset(0, 0, 0, + -views::GetCaptionButtonLayoutSize( + views::CaptionButtonLayoutSize::kNonBrowserCaption) + .height()); + } + return window_bounds.width() >= work_area_size.width() && + window_bounds.height() >= work_area_size.height(); +} + } // namespace exo
diff --git a/components/exo/xdg_shell_surface.h b/components/exo/xdg_shell_surface.h index f8f4c8eb..6ac38df 100644 --- a/components/exo/xdg_shell_surface.h +++ b/components/exo/xdg_shell_surface.h
@@ -50,6 +50,11 @@ int container); ~XdgShellSurface() override; + // Xdg surfaces have the behaviour that they should maximize themselves if + // their bounds are larger or equal to the display area. This behaviour is + // implemented in linux display managers (e.g. Muffin/Cinnamon). + bool ShouldAutoMaximize() override; + bool x_flipped() const { return x_flipped_; } void set_x_flipped(bool flipped) { x_flipped_ = flipped; }
diff --git a/components/exo/xdg_shell_surface_unittest.cc b/components/exo/xdg_shell_surface_unittest.cc new file mode 100644 index 0000000..a1ff680c --- /dev/null +++ b/components/exo/xdg_shell_surface_unittest.cc
@@ -0,0 +1,122 @@ +// 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 "components/exo/xdg_shell_surface.h" + +#include "components/exo/buffer.h" +#include "components/exo/display.h" +#include "components/exo/shell_surface.h" +#include "components/exo/surface.h" +#include "components/exo/test/exo_test_base.h" +#include "components/exo/test/exo_test_helper.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace exo { +namespace { + +struct SurfaceTriplet { + std::unique_ptr<Surface> surface; + std::unique_ptr<ShellSurface> shell_surface; + std::unique_ptr<Buffer> buffer; +}; + +class XdgShellSurfaceTest : public test::ExoTestBase { + protected: + SurfaceTriplet BuildSurface(int w, int h) { + auto surface = std::make_unique<Surface>(); + auto shell_surface = std::make_unique<XdgShellSurface>( + surface.get(), gfx::Point{0, 0}, + /*activatable=*/true, + /*can_minimize=*/true, ash::desks_util::GetActiveDeskContainerId()); + auto buffer = std::make_unique<Buffer>( + exo_test_helper()->CreateGpuMemoryBuffer({w, h})); + surface->Attach(buffer.get()); + return {std::move(surface), std::move(shell_surface), std::move(buffer)}; + } + + // Returns the size of the surface associated with a maximized widget. If the + // widget is |decorated| the size will be smaller due to the widget's + // decorations. + gfx::Size GetMaximizedSurfaceSize(bool decorated) { + SurfaceTriplet temp = BuildSurface(1, 1); + temp.surface->SetFrame(decorated ? SurfaceFrameType::NORMAL + : SurfaceFrameType::NONE); + temp.shell_surface->Maximize(); + temp.surface->Commit(); + + EXPECT_TRUE(temp.shell_surface->GetWidget()->IsMaximized()); + return temp.shell_surface->GetWidget()->client_view()->size(); + } +}; + +// We don't actually care about the size of decorations. The purpose of this +// test is to ensure that enabling decorations in the way that we do actually +// causes the widget to be drawn with a (nonzero-sized) frame. +TEST_F(XdgShellSurfaceTest, DecoratedSurfaceSmallerThanUndecorated) { + gfx::Size undecorated_size = GetMaximizedSurfaceSize(false); + gfx::Size decorated_size = GetMaximizedSurfaceSize(true); + + // The best expectation we can have is that the window decoration must be + // nonzero in one direction. + int decoration_width = undecorated_size.width() - decorated_size.width(); + int decoration_height = undecorated_size.height() - decorated_size.height(); + EXPECT_GE(decoration_width, 0); + EXPECT_GE(decoration_height, 0); + EXPECT_GT(decoration_width + decoration_height, 0); +} + +TEST_F(XdgShellSurfaceTest, UndecoratedSurfaceAutoMaximizes) { + gfx::Size maximized_size = GetMaximizedSurfaceSize(/*decorated=*/false); + + SurfaceTriplet max_surface = + BuildSurface(maximized_size.width(), maximized_size.height()); + max_surface.surface->Commit(); + EXPECT_TRUE(max_surface.shell_surface->GetWidget()->IsMaximized()); + + SurfaceTriplet narrow_surface = + BuildSurface(maximized_size.width() - 1, maximized_size.height()); + narrow_surface.surface->Commit(); + EXPECT_FALSE(narrow_surface.shell_surface->GetWidget()->IsMaximized()); + + SurfaceTriplet short_surface = + BuildSurface(maximized_size.width(), maximized_size.height() - 1); + short_surface.surface->Commit(); + EXPECT_FALSE(short_surface.shell_surface->GetWidget()->IsMaximized()); +} + +TEST_F(XdgShellSurfaceTest, DecoratedSurfaceAutoMaximizes) { + gfx::Size maximized_size = GetMaximizedSurfaceSize(/*decorated=*/true); + + SurfaceTriplet max_surface = + BuildSurface(maximized_size.width(), maximized_size.height()); + max_surface.surface->SetFrame(SurfaceFrameType::NORMAL); + max_surface.surface->Commit(); + EXPECT_TRUE(max_surface.shell_surface->GetWidget()->IsMaximized()); + + SurfaceTriplet narrow_surface = + BuildSurface(maximized_size.width() - 1, maximized_size.height()); + narrow_surface.surface->SetFrame(SurfaceFrameType::NORMAL); + narrow_surface.surface->Commit(); + EXPECT_FALSE(narrow_surface.shell_surface->GetWidget()->IsMaximized()); + + SurfaceTriplet short_surface = + BuildSurface(maximized_size.width(), maximized_size.height() - 1); + short_surface.surface->SetFrame(SurfaceFrameType::NORMAL); + short_surface.surface->Commit(); + EXPECT_FALSE(short_surface.shell_surface->GetWidget()->IsMaximized()); +} + +TEST_F(XdgShellSurfaceTest, DontMaximizeIfStateWasModified) { + gfx::Size maximized_size = GetMaximizedSurfaceSize(/*decorated=*/true); + + SurfaceTriplet test_surface = + BuildSurface(maximized_size.width() + 1, maximized_size.height() + 1); + // Explicitly restoring the window should prevent auto maximize. + test_surface.shell_surface->Restore(); + test_surface.surface->Commit(); + EXPECT_FALSE(test_surface.shell_surface->GetWidget()->IsMaximized()); +} + +} // namespace +} // namespace exo
diff --git a/components/gcm_driver/gcm_driver_desktop_unittest.cc b/components/gcm_driver/gcm_driver_desktop_unittest.cc index 6cfe0f1..271d2a7 100644 --- a/components/gcm_driver/gcm_driver_desktop_unittest.cc +++ b/components/gcm_driver/gcm_driver_desktop_unittest.cc
@@ -688,7 +688,12 @@ EXPECT_EQ(GCMClient::SUCCESS, unregistration_result()); } +// TODO(crbug.com/1009185): Test is failing on ASan build. +#if defined(ADDRESS_SANITIZER) +TEST_F(GCMDriverFunctionalTest, DISABLED_UnregisterRemovesEncryptionInfo) { +#else TEST_F(GCMDriverFunctionalTest, UnregisterRemovesEncryptionInfo) { +#endif std::vector<std::string> sender_ids; sender_ids.push_back("sender1"); Register(kTestAppID1, sender_ids, GCMDriverTest::WAIT);
diff --git a/components/gcm_driver/gcm_driver_unittest.cc b/components/gcm_driver/gcm_driver_unittest.cc index 39a43ba..561b6670 100644 --- a/components/gcm_driver/gcm_driver_unittest.cc +++ b/components/gcm_driver/gcm_driver_unittest.cc
@@ -277,7 +277,12 @@ async_operation_completed_callback_.Run(); } +// TODO(crbug.com/1009185): Test is failing on ASan build. +#if defined(ADDRESS_SANITIZER) +TEST_F(GCMDriverBaseTest, DISABLED_SendWebPushMessage) { +#else TEST_F(GCMDriverBaseTest, SendWebPushMessage) { +#endif GetEncryptionInfo(kTestAppID1, GCMDriverBaseTest::WAIT); WebPushMessage message; @@ -316,7 +321,12 @@ EXPECT_FALSE(send_web_push_message_id()); } +// TODO(crbug.com/1009185): Test is failing on ASan build. +#if defined(ADDRESS_SANITIZER) +TEST_F(GCMDriverBaseTest, DISABLED_SendWebPushMessageServerError) { +#else TEST_F(GCMDriverBaseTest, SendWebPushMessageServerError) { +#endif GetEncryptionInfo(kTestAppID1, GCMDriverBaseTest::WAIT); WebPushMessage message;
diff --git a/components/media_message_center/media_controls_progress_view_unittest.cc b/components/media_message_center/media_controls_progress_view_unittest.cc index 846925a2..9f791ca 100644 --- a/components/media_message_center/media_controls_progress_view_unittest.cc +++ b/components/media_message_center/media_controls_progress_view_unittest.cc
@@ -54,7 +54,17 @@ DISALLOW_COPY_AND_ASSIGN(MediaControlsProgressViewTest); }; -TEST_F(MediaControlsProgressViewTest, InitProgress) { +// TODO(crbug.com/1009356): many of these tests are failing on TSan builds. +#if defined(THREAD_SANITIZER) +#define MAYBE_MediaControlsProgressViewTest \ + DISABLED_MediaControlsProgressViewTest +class DISABLED_MediaControlsProgressViewTest + : public MediaControlsProgressViewTest {}; +#else +#define MAYBE_MediaControlsProgressViewTest MediaControlsProgressViewTest +#endif + +TEST_F(MAYBE_MediaControlsProgressViewTest, InitProgress) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -68,7 +78,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .5); } -TEST_F(MediaControlsProgressViewTest, InitProgressOverHour) { +TEST_F(MAYBE_MediaControlsProgressViewTest, InitProgressOverHour) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromHours(2) /* duration */, base::TimeDelta::FromMinutes(30) /* position */); @@ -82,7 +92,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .25); } -TEST_F(MediaControlsProgressViewTest, InitProgressOverDay) { +TEST_F(MAYBE_MediaControlsProgressViewTest, InitProgressOverDay) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromHours(25) /* duration */, base::TimeDelta::FromHours(5) /* position */); @@ -97,7 +107,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .2); } -TEST_F(MediaControlsProgressViewTest, UpdateProgress) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgress) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -120,7 +130,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .55); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressFastPlayback) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressFastPlayback) { media_session::MediaPosition media_position( 2 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -143,7 +153,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .55); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressSlowPlayback) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressSlowPlayback) { media_session::MediaPosition media_position( .5 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -166,7 +176,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .55); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressNegativePlayback) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressNegativePlayback) { media_session::MediaPosition media_position( -1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -189,7 +199,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .45); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressPastDuration) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressPastDuration) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -214,7 +224,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), 1); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressBeforeStart) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressBeforeStart) { media_session::MediaPosition media_position( -1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -239,7 +249,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), 0); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressPaused) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressPaused) { media_session::MediaPosition media_position( 0 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */); @@ -263,7 +273,7 @@ EXPECT_EQ(progress_view_->progress_bar_for_testing()->GetValue(), .5); } -TEST_F(MediaControlsProgressViewTest, UpdateProgressTwice) { +TEST_F(MAYBE_MediaControlsProgressViewTest, UpdateProgressTwice) { media_session::MediaPosition media_position( 1 /* playback_rate */, base::TimeDelta::FromSeconds(600) /* duration */, base::TimeDelta::FromSeconds(300) /* position */);
diff --git a/components/media_message_center/media_notification_view_unittest.cc b/components/media_message_center/media_notification_view_unittest.cc index 8031323f..beba759 100644 --- a/components/media_message_center/media_notification_view_unittest.cc +++ b/components/media_message_center/media_notification_view_unittest.cc
@@ -327,7 +327,15 @@ DISALLOW_COPY_AND_ASSIGN(MediaNotificationViewTest); }; -TEST_F(MediaNotificationViewTest, ButtonsSanityCheck) { +// TODO(crbug.com/1009287): many of these tests are failing on TSan builds. +#if defined(THREAD_SANITIZER) +#define MAYBE_MediaNotificationViewTest DISABLED_MediaNotificationViewTest +class DISABLED_MediaNotificationViewTest : public MediaNotificationViewTest {}; +#else +#define MAYBE_MediaNotificationViewTest MediaNotificationViewTest +#endif + +TEST_F(MAYBE_MediaNotificationViewTest, ButtonsSanityCheck) { view()->SetExpanded(true); EnableAllActions(); @@ -357,7 +365,7 @@ EXPECT_FALSE(GetButtonForAction(MediaSessionAction::kPause)); } -TEST_F(MediaNotificationViewTest, ButtonsFocusCheck) { +TEST_F(MAYBE_MediaNotificationViewTest, ButtonsFocusCheck) { // Expand and enable all actions to show all buttons. view()->SetExpanded(true); EnableAllActions(); @@ -388,7 +396,7 @@ focus_manager->GetFocusedView()); } -TEST_F(MediaNotificationViewTest, PlayPauseButtonTooltipCheck) { +TEST_F(MAYBE_MediaNotificationViewTest, PlayPauseButtonTooltipCheck) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -410,7 +418,7 @@ EXPECT_NE(tooltip, new_tooltip); } -TEST_F(MediaNotificationViewTest, NextTrackButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, NextTrackButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kNextTrack); @@ -423,7 +431,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kNextTrack); } -TEST_F(MediaNotificationViewTest, PlayButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, PlayButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kPlay); @@ -436,7 +444,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kPlay); } -TEST_F(MediaNotificationViewTest, PauseButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, PauseButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kPause); EXPECT_CALL(container(), OnMediaSessionInfoChanged(_)); @@ -457,7 +465,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kPause); } -TEST_F(MediaNotificationViewTest, PreviousTrackButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, PreviousTrackButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kPreviousTrack); @@ -470,7 +478,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kPreviousTrack); } -TEST_F(MediaNotificationViewTest, SeekBackwardButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, SeekBackwardButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kSeekBackward); @@ -483,7 +491,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kSeekBackward); } -TEST_F(MediaNotificationViewTest, SeekForwardButtonClick) { +TEST_F(MAYBE_MediaNotificationViewTest, SeekForwardButtonClick) { EXPECT_CALL(controller(), LogMediaSessionActionButtonPressed(_)); EnableAction(MediaSessionAction::kSeekForward); @@ -496,7 +504,7 @@ ExpectHistogramActionRecorded(MediaSessionAction::kSeekForward); } -TEST_F(MediaNotificationViewTest, PlayToggle_FromObserver_Empty) { +TEST_F(MAYBE_MediaNotificationViewTest, PlayToggle_FromObserver_Empty) { EnableAction(MediaSessionAction::kPlay); { @@ -517,7 +525,7 @@ } } -TEST_F(MediaNotificationViewTest, PlayToggle_FromObserver_PlaybackState) { +TEST_F(MAYBE_MediaNotificationViewTest, PlayToggle_FromObserver_PlaybackState) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -554,7 +562,7 @@ } } -TEST_F(MediaNotificationViewTest, MetadataIsDisplayed) { +TEST_F(MAYBE_MediaNotificationViewTest, MetadataIsDisplayed) { view()->SetExpanded(true); EnableAllActions(); @@ -569,7 +577,7 @@ EXPECT_EQ(kMediaTitleArtistRowExpectedHeight, title_artist_row()->height()); } -TEST_F(MediaNotificationViewTest, UpdateMetadata_FromObserver) { +TEST_F(MAYBE_MediaNotificationViewTest, UpdateMetadata_FromObserver) { EnableAllActions(); ExpectHistogramMetadataRecorded(MediaNotificationView::Metadata::kTitle, 1); @@ -607,7 +615,7 @@ ExpectHistogramMetadataRecorded(MediaNotificationView::Metadata::kCount, 2); } -TEST_F(MediaNotificationViewTest, UpdateMetadata_AppName) { +TEST_F(MAYBE_MediaNotificationViewTest, UpdateMetadata_AppName) { EXPECT_EQ(base::ASCIIToUTF16(kTestDefaultAppName), header_row()->app_name_for_testing()); @@ -633,7 +641,7 @@ header_row()->app_name_for_testing()); } -TEST_F(MediaNotificationViewTest, Buttons_WhenCollapsed) { +TEST_F(MAYBE_MediaNotificationViewTest, Buttons_WhenCollapsed) { EXPECT_CALL(container(), OnVisibleActionsChanged(std::set<MediaSessionAction>( {MediaSessionAction::kPlay, MediaSessionAction::kPreviousTrack, @@ -683,7 +691,7 @@ EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kSeekForward)); } -TEST_F(MediaNotificationViewTest, Buttons_WhenExpanded) { +TEST_F(MAYBE_MediaNotificationViewTest, Buttons_WhenExpanded) { EXPECT_CALL(container(), OnVisibleActionsChanged(std::set<MediaSessionAction>( {MediaSessionAction::kPlay, MediaSessionAction::kPreviousTrack, @@ -709,7 +717,7 @@ EXPECT_TRUE(IsActionButtonVisible(MediaSessionAction::kSeekForward)); } -TEST_F(MediaNotificationViewTest, ClickHeader_ToggleExpand) { +TEST_F(MAYBE_MediaNotificationViewTest, ClickHeader_ToggleExpand) { view()->SetExpanded(true); EnableAllActions(); @@ -724,7 +732,7 @@ EXPECT_TRUE(IsActuallyExpanded()); } -TEST_F(MediaNotificationViewTest, ActionButtonsHiddenByDefault) { +TEST_F(MAYBE_MediaNotificationViewTest, ActionButtonsHiddenByDefault) { EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kPlay)); EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kNextTrack)); EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kPreviousTrack)); @@ -732,7 +740,7 @@ EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kSeekBackward)); } -TEST_F(MediaNotificationViewTest, ActionButtonsToggleVisibility) { +TEST_F(MAYBE_MediaNotificationViewTest, ActionButtonsToggleVisibility) { EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kNextTrack)); EnableAction(MediaSessionAction::kNextTrack); @@ -744,7 +752,7 @@ EXPECT_FALSE(IsActionButtonVisible(MediaSessionAction::kNextTrack)); } -TEST_F(MediaNotificationViewTest, UpdateArtworkFromItem) { +TEST_F(MAYBE_MediaNotificationViewTest, UpdateArtworkFromItem) { int title_artist_width = title_artist_row()->width(); const SkColor accent = header_row()->accent_color_for_testing(); gfx::Size size = view()->size(); @@ -789,12 +797,12 @@ EXPECT_EQ(accent, header_row()->accent_color_for_testing()); } -TEST_F(MediaNotificationViewTest, ExpandableDefaultState) { +TEST_F(MAYBE_MediaNotificationViewTest, ExpandableDefaultState) { EXPECT_FALSE(IsActuallyExpanded()); EXPECT_FALSE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, ExpandablePlayPauseActionCountsOnce) { +TEST_F(MAYBE_MediaNotificationViewTest, ExpandablePlayPauseActionCountsOnce) { view()->SetExpanded(true); EXPECT_FALSE(IsActuallyExpanded()); @@ -823,7 +831,7 @@ EXPECT_TRUE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, BecomeExpandableAndWasNotExpandable) { +TEST_F(MAYBE_MediaNotificationViewTest, BecomeExpandableAndWasNotExpandable) { view()->SetExpanded(true); EXPECT_FALSE(IsActuallyExpanded()); @@ -835,7 +843,8 @@ EXPECT_TRUE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, BecomeExpandableButWasAlreadyExpandable) { +TEST_F(MAYBE_MediaNotificationViewTest, + BecomeExpandableButWasAlreadyExpandable) { view()->SetExpanded(true); EXPECT_FALSE(IsActuallyExpanded()); @@ -852,7 +861,7 @@ EXPECT_TRUE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, BecomeNotExpandableAndWasExpandable) { +TEST_F(MAYBE_MediaNotificationViewTest, BecomeNotExpandableAndWasExpandable) { view()->SetExpanded(true); EXPECT_FALSE(IsActuallyExpanded()); @@ -872,7 +881,7 @@ EXPECT_FALSE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, +TEST_F(MAYBE_MediaNotificationViewTest, BecomeNotExpandableButWasAlreadyNotExpandable) { view()->SetExpanded(true); @@ -885,7 +894,7 @@ EXPECT_FALSE(expand_button_enabled()); } -TEST_F(MediaNotificationViewTest, ActionButtonRowSizeAndAlignment) { +TEST_F(MAYBE_MediaNotificationViewTest, ActionButtonRowSizeAndAlignment) { EnableAction(MediaSessionAction::kPlay); views::Button* button = GetButtonForAction(MediaSessionAction::kPlay); @@ -905,7 +914,7 @@ EXPECT_GT(button_x, button->GetBoundsInScreen().x()); } -TEST_F(MediaNotificationViewTest, NotifysContainerOfExpandedState) { +TEST_F(MAYBE_MediaNotificationViewTest, NotifysContainerOfExpandedState) { // Track the expanded state given to |container_|. bool expanded = false; EXPECT_CALL(container(), OnExpanded(_)) @@ -932,7 +941,7 @@ EXPECT_FALSE(expanded); } -TEST_F(MediaNotificationViewTest, AccessibleNodeData) { +TEST_F(MAYBE_MediaNotificationViewTest, AccessibleNodeData) { ui::AXNodeData data; view()->GetAccessibleNodeData(&data); @@ -941,7 +950,7 @@ EXPECT_EQ(base::ASCIIToUTF16("title - artist"), accessible_name()); } -TEST_F(MediaNotificationViewTest, Freezing_DoNotUpdateMetadata) { +TEST_F(MAYBE_MediaNotificationViewTest, Freezing_DoNotUpdateMetadata) { media_session::MediaMetadata metadata; metadata.title = base::ASCIIToUTF16("title2"); metadata.artist = base::ASCIIToUTF16("artist2"); @@ -954,7 +963,7 @@ EXPECT_EQ(base::ASCIIToUTF16("artist"), artist_label()->GetText()); } -TEST_F(MediaNotificationViewTest, Freezing_DoNotUpdateImage) { +TEST_F(MAYBE_MediaNotificationViewTest, Freezing_DoNotUpdateImage) { SkBitmap image; image.allocN32Pixels(10, 10); image.eraseColor(SK_ColorMAGENTA); @@ -968,7 +977,7 @@ EXPECT_TRUE(GetArtworkImage().isNull()); } -TEST_F(MediaNotificationViewTest, Freezing_DoNotUpdatePlaybackState) { +TEST_F(MAYBE_MediaNotificationViewTest, Freezing_DoNotUpdatePlaybackState) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -989,7 +998,7 @@ EXPECT_FALSE(GetButtonForAction(MediaSessionAction::kPause)); } -TEST_F(MediaNotificationViewTest, Freezing_DoNotUpdateActions) { +TEST_F(MAYBE_MediaNotificationViewTest, Freezing_DoNotUpdateActions) { EXPECT_FALSE( GetButtonForAction(MediaSessionAction::kSeekForward)->GetVisible()); @@ -1000,7 +1009,7 @@ GetButtonForAction(MediaSessionAction::kSeekForward)->GetVisible()); } -TEST_F(MediaNotificationViewTest, Freezing_DisableInteraction) { +TEST_F(MAYBE_MediaNotificationViewTest, Freezing_DisableInteraction) { EnableAllActions(); EXPECT_EQ(0, media_controller()->next_track_count()); @@ -1013,7 +1022,7 @@ EXPECT_EQ(0, media_controller()->next_track_count()); } -TEST_F(MediaNotificationViewTest, UnfreezingDoesntMissUpdates) { +TEST_F(MAYBE_MediaNotificationViewTest, UnfreezingDoesntMissUpdates) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -1063,7 +1072,7 @@ EXPECT_EQ(base::ASCIIToUTF16("artist2"), artist_label()->GetText()); } -TEST_F(MediaNotificationViewTest, UnfreezingWaitsForArtwork_Timeout) { +TEST_F(MAYBE_MediaNotificationViewTest, UnfreezingWaitsForArtwork_Timeout) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -1137,7 +1146,8 @@ EXPECT_TRUE(GetArtworkImage().isNull()); } -TEST_F(MediaNotificationViewTest, UnfreezingWaitsForArtwork_ReceiveArtwork) { +TEST_F(MAYBE_MediaNotificationViewTest, + UnfreezingWaitsForArtwork_ReceiveArtwork) { EnableAction(MediaSessionAction::kPlay); EnableAction(MediaSessionAction::kPause); @@ -1214,7 +1224,7 @@ EXPECT_FALSE(GetArtworkImage().isNull()); } -TEST_F(MediaNotificationViewTest, ForcedExpandedState) { +TEST_F(MAYBE_MediaNotificationViewTest, ForcedExpandedState) { // Make the view expandable. EnableAllActions();
diff --git a/components/metrics/single_sample_metrics_factory_impl_unittest.cc b/components/metrics/single_sample_metrics_factory_impl_unittest.cc index ff6ba71..31a1c9c 100644 --- a/components/metrics/single_sample_metrics_factory_impl_unittest.cc +++ b/components/metrics/single_sample_metrics_factory_impl_unittest.cc
@@ -140,7 +140,8 @@ base::HistogramBase::kUmaTargetedHistogramFlag)); } -TEST_F(SingleSampleMetricsFactoryImplTest, MultithreadedMetrics) { +// TODO(crbug.com/1009360). Flaky timeouts. +TEST_F(SingleSampleMetricsFactoryImplTest, DISABLED_MultithreadedMetrics) { base::HistogramTester tester; std::unique_ptr<base::SingleSampleMetric> metric = factory_->CreateCustomCountsMetric(kMetricName, kMin, kMax, kBucketCount);
diff --git a/components/password_manager/core/browser/leaked_credentials_table.cc b/components/password_manager/core/browser/leaked_credentials_table.cc index e63c012..f16a94e 100644 --- a/components/password_manager/core/browser/leaked_credentials_table.cc +++ b/components/password_manager/core/browser/leaked_credentials_table.cc
@@ -13,7 +13,8 @@ constexpr char kLeakedCredentialsTableName[] = "leaked_credentials"; -// Represents all the columns of the leaked credentials table. +// Represents columns of the leaked credentials table. Used with SQL +// queries that use all the columns. enum class LeakedCredentialsTableColumn { kUrl, kUsername, @@ -99,9 +100,8 @@ sql::Statement s(db_->GetCachedStatement( SQL_FROM_HERE, "DELETE FROM leaked_credentials WHERE url = ? AND username = ? ")); - s.BindString(GetColumnNumber(LeakedCredentialsTableColumn::kUrl), url.spec()); - s.BindString16(GetColumnNumber(LeakedCredentialsTableColumn::kUsername), - username); + s.BindString(0, url.spec()); + s.BindString16(1, username); return s.Run(); }
diff --git a/components/payments/content/payment_request_web_contents_manager.cc b/components/payments/content/payment_request_web_contents_manager.cc index 980b79c..5326902 100644 --- a/components/payments/content/payment_request_web_contents_manager.cc +++ b/components/payments/content/payment_request_web_contents_manager.cc
@@ -30,11 +30,11 @@ content::RenderFrameHost* render_frame_host, content::WebContents* web_contents, std::unique_ptr<ContentPaymentRequestDelegate> delegate, - mojo::InterfaceRequest<payments::mojom::PaymentRequest> request, + mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, PaymentRequest::ObserverForTest* observer_for_testing) { auto new_request = std::make_unique<PaymentRequest>( render_frame_host, web_contents, std::move(delegate), this, - delegate->GetDisplayManager(), std::move(request), observer_for_testing); + delegate->GetDisplayManager(), std::move(receiver), observer_for_testing); PaymentRequest* request_ptr = new_request.get(); payment_requests_.insert(std::make_pair(request_ptr, std::move(new_request))); }
diff --git a/components/payments/content/payment_request_web_contents_manager.h b/components/payments/content/payment_request_web_contents_manager.h index 05ca76d..3f9e72b 100644 --- a/components/payments/content/payment_request_web_contents_manager.h +++ b/components/payments/content/payment_request_web_contents_manager.h
@@ -12,7 +12,7 @@ #include "components/payments/content/payment_request.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom.h" namespace content { @@ -50,7 +50,7 @@ content::RenderFrameHost* render_frame_host, content::WebContents* web_contents, std::unique_ptr<ContentPaymentRequestDelegate> delegate, - mojo::InterfaceRequest<payments::mojom::PaymentRequest> request, + mojo::PendingReceiver<payments::mojom::PaymentRequest> receiver, PaymentRequest::ObserverForTest* observer_for_testing); // Destroys the given |request|.
diff --git a/components/policy/proto/chrome_device_policy.proto b/components/policy/proto/chrome_device_policy.proto index e96148c8..310241b 100644 --- a/components/policy/proto/chrome_device_policy.proto +++ b/components/policy/proto/chrome_device_policy.proto
@@ -380,6 +380,14 @@ optional string display_name = 4; } +// Parameters for Web App-based device local accounts. +message WebKioskAppInfoProto { + // Install url (must be present). + // In case it is the only field provided, title and icon will be deduced + // during first app launch. + optional string url = 1; +} + // Describes a single device-local account. message DeviceLocalAccountInfoProto { // Deprecated: Account identifier for a public session device-local account. @@ -407,6 +415,8 @@ ACCOUNT_TYPE_KIOSK_ANDROID_APP = 2; // SAML public session account ACCOUNT_TYPE_SAML_PUBLIC_SESSION = 3; + // Web App. + ACCOUNT_TYPE_WEB_KIOSK_APP = 4; } // The account type. @@ -417,6 +427,9 @@ // Kiosk App parameters, relevant if |type| is ACCOUNT_TYPE_KIOSK_ANDROID_APP optional AndroidKioskAppInfoProto android_kiosk_app = 5; + + // Web Kiosk App parameters, relevant if |type| is ACCOUNT_TYPE_WEB_KIOSK_APP + optional WebKioskAppInfoProto web_kiosk_app = 6; } message DeviceLocalAccountsProto { @@ -724,6 +737,22 @@ // between users. optional bool login_screen_mono_audio_enabled = 22; optional PolicyOptions login_screen_mono_audio_enabled_options = 23; + + // Sets the state of the autoclick accessibility feature on the login + // screen. If this policy is set to true, the autoclick will be enabled + // when the login screen is shown. If this policy is set to false, the + // autoclick will be disabled when the autoclick is shown. If the + // PolicyOptions mode was being mandatory then the user won't be able to + // change these settings. Only if PolicyOptions was being set as recommended + // users can temporarily override this setting by enabling or disabling the + // autoclick. However, the user's choice is not persistent and the + // default is restored whenever the login screen is shown anew or the user + // remains idle on the login screen for a minute. If this policy is left + // unset, the autoclick is disabled when the login screen is first + // shown. Users can enable or disable the autoclick anytime and its + // status on the login screen is persisted between users. + optional bool login_screen_autoclick_enabled = 24; + optional PolicyOptions login_screen_autoclick_enabled_options = 25; } message SupervisedUsersSettingsProto {
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 08b7f94..074b716 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -650,6 +650,7 @@ 'DeviceLoginScreenCursorHighlightEnabled', 'DeviceLoginScreenCaretHighlightEnabled', 'DeviceLoginScreenMonoAudioEnabled', + 'DeviceLoginScreenAutoclickEnabled', ], }, { @@ -10508,6 +10509,33 @@ If this policy is left unset, the mono audio is disabled on the login screen initially but can be enabled by the user anytime.''', }, { + 'name': 'DeviceLoginScreenAutoclickEnabled', + 'owners': ['amraboelkher@chromium.org', 'emaxx@chromium.org'], + 'type': 'main', + 'schema': { 'type': 'boolean' }, + 'supported_on': ['chrome_os:79-'], + 'device_only': True, + 'features': { + 'can_be_recommended': True, + 'dynamic_refresh': True, + }, + 'example_value': True, + 'id': 617, + 'caption': '''Enable the autoclick on the login screen''', + 'tags': [], + 'desc': '''Enable the autoclick accessibility feature on the login screen. + + This feature allows to automatically click when the mouse cursor stops, without requiring the user to physically press the mouse or touchpad buttons. + + If this policy is set to true, the autoclick will always be enabled on the login screen. + + If this policy is set to false, the autoclick will always be disabled on the login screen. + + If you set this policy, users cannot change or override it. + + If this policy is left unset, the autoclick is disabled on the login screen initially but can be enabled by the user anytime.''', + }, + { 'name': 'HideWebStoreIcon', 'owners': ['file://components/policy/resources/OWNERS'], 'type': 'main', @@ -18327,6 +18355,7 @@ 'DeviceLoginScreenCursorHighlightEnabled': 'accessibility_settings.login_screen_cursor_highlight_enabled', 'DeviceLoginScreenCaretHighlightEnabled': 'accessibility_settings.login_screen_caret_highlight_enabled', 'DeviceLoginScreenMonoAudioEnabled': 'accessibility_settings.login_screen_mono_audio_enabled', + 'DeviceLoginScreenAutoclickEnabled': 'accessibility_settings.login_screen_autoclick_enabled', 'AttestationEnabledForDevice': 'attestation_settings.attestation_enabled', 'AttestationForContentProtectionEnabled': 'attestation_settings.content_protection_enabled', 'SystemTimezone': 'system_timezone.timezone', @@ -18827,6 +18856,6 @@ ], 'placeholders': [], 'deleted_policy_ids': [412, 546, 562, 569], - 'highest_id_currently_used': 616, + 'highest_id_currently_used': 617, 'highest_atomic_group_id_currently_used': 37 }
diff --git a/components/printing/common/cloud_print_cdd_conversion.cc b/components/printing/common/cloud_print_cdd_conversion.cc index 75474d08..e1718eb3 100644 --- a/components/printing/common/cloud_print_cdd_conversion.cc +++ b/components/printing/common/cloud_print_cdd_conversion.cc
@@ -179,15 +179,15 @@ select_capability.AddDefaultOption( printer::SelectVendorCapabilityOption(value.name, localized_value), - value.is_default); + value.name == capability.default_value); } vendor_capabilities.AddOption(printer::VendorCapability( capability.name, capability_name, std::move(select_capability))); } else { - vendor_capabilities.AddOption(printer::VendorCapability( - capability.name, capability_name, - printer::TypedValueVendorCapability( - ToCloudValueType(base::Value::Type::STRING)))); + vendor_capabilities.AddOption( + printer::VendorCapability(capability.name, capability_name, + printer::TypedValueVendorCapability( + ToCloudValueType(capability.type)))); } } vendor_capabilities.SaveTo(&description);
diff --git a/components/search_engines/prepopulated_engines.json b/components/search_engines/prepopulated_engines.json index b134602..af61d0c5 100644 --- a/components/search_engines/prepopulated_engines.json +++ b/components/search_engines/prepopulated_engines.json
@@ -635,6 +635,7 @@ "alternate_urls": [ "http://hladaj.atlas.sk/fulltext/?phrase={searchTerms}" ], + "type": "SEARCH_ENGINE_ATLAS", "id": 27 }, @@ -1009,5 +1010,9 @@ "type": "SEARCH_ENGINE_ZOZNAM", "id": 85 } + }, + + "generate_array": { + "array_name": "kAllEngines" } }
diff --git a/components/search_engines/prepopulated_engines_schema.json b/components/search_engines/prepopulated_engines_schema.json index c46435e..bffe770e2 100644 --- a/components/search_engines/prepopulated_engines_schema.json +++ b/components/search_engines/prepopulated_engines_schema.json
@@ -9,6 +9,7 @@ { "type_name": "PrepopulatedEngine", "headers": [ + "base/stl_util.h", "components/search_engines/search_engine_type.h" ], "schema": [
diff --git a/components/search_engines/template_url_prepopulate_data.cc b/components/search_engines/template_url_prepopulate_data.cc index 5fd11a9..52dd123a 100644 --- a/components/search_engines/template_url_prepopulate_data.cc +++ b/components/search_engines/template_url_prepopulate_data.cc
@@ -889,96 +889,6 @@ }; // ---------------------------------------------------------------------------- -// A list of all the engines that we know about. -const PrepopulatedEngine* const kAllEngines[] = { - // Prepopulated engines: - &ask, - &baidu, - &bing, - &coccoc, - &daum, - &duckduckgo, - &google, - &mail_ru, - &naver, - &qwant, - &seznam, - &sogou, - &yahoo, - &yahoo_ar, - &yahoo_at, - &yahoo_au, - &yahoo_br, - &yahoo_ca, - &yahoo_ch, - &yahoo_cl, - &yahoo_co, - &yahoo_de, - &yahoo_dk, - &yahoo_es, - &yahoo_fi, - &yahoo_fr, - &yahoo_hk, - &yahoo_id, - &yahoo_in, - &yahoo_jp, - &yahoo_mx, - &yahoo_my, - &yahoo_nl, - &yahoo_nz, - &yahoo_pe, - &yahoo_ph, - &yahoo_qc, - &yahoo_se, - &yahoo_sg, - &yahoo_th, - &yahoo_tr, - &yahoo_tw, - &yahoo_uk, - &yahoo_ve, - &yahoo_vn, - &yandex_by, - &yandex_com, - &yandex_kz, - &yandex_ru, - &yandex_tr, - &yandex_ua, - - // UMA-only engines: - &atlas_cz, - &atlas_sk, - &avg, - &babylon, - &conduit, - &delfi_lt, - &delfi_lv, - &delta, - &funmoods, - &goo, - &imesh, - &iminent, - &in, - &incredibar, - &libero, - &neti, - &nigma, - &ok, - &rambler, - &sapo, - &search_results, - &searchnu, - &snapdo, - &softonic, - &sweetim, - &sweetpacks, - &terra_ar, - &terra_es, - &tut, - &walla, - &wp, - &zoznam, -}; - std::vector<std::unique_ptr<TemplateURLData>> GetPrepopulationSetFromCountryID( int country_id) { const PrepopulatedEngine* const* engines; @@ -1404,8 +1314,8 @@ #endif std::vector<const PrepopulatedEngine*> GetAllPrepopulatedEngines() { - return std::vector<const PrepopulatedEngine*>(std::begin(kAllEngines), - std::end(kAllEngines)); + return std::vector<const PrepopulatedEngine*>( + &kAllEngines[0], &kAllEngines[0] + kAllEnginesLength); } void ClearPrepopulatedEnginesInPrefs(PrefService* prefs) { @@ -1442,7 +1352,7 @@ return google.type; // Now check the rest of the prepopulate data. - for (size_t i = 0; i < base::size(kAllEngines); ++i) { + for (size_t i = 0; i < kAllEnginesLength; ++i) { // First check the main search URL. if (SameDomain(url, GURL(kAllEngines[i]->search_url))) return kAllEngines[i]->type;
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.cc b/components/send_tab_to_self/send_tab_to_self_bridge.cc index 4fd9f58..d13eff1e 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge.cc
@@ -712,6 +712,12 @@ } void SendTabToSelfBridge::SetTargetDeviceInfoList() { + // Verify that the current TrackedCacheGuid() is the local GUID without + // enforcing that tracked cache GUID is set. + DCHECK(device_info_tracker_->IsRecentLocalCacheGuid( + change_processor()->TrackedCacheGuid()) || + change_processor()->TrackedCacheGuid().empty()); + std::vector<std::unique_ptr<syncer::DeviceInfo>> all_devices = device_info_tracker_->GetAllDeviceInfo(); number_of_devices_ = all_devices.size(); @@ -734,10 +740,17 @@ break; } - // TODO(crbug.com/966413): Implement a better way to dedupe local devices in - // case the user has other devices with the same name. + // Don't include this device if it is the local device. + if (device_info_tracker_->IsRecentLocalCacheGuid(device->guid())) { + continue; + } + // Don't include this device. Also compare the name as the device can have // different cache guids (e.g. after stopping and re-starting sync). + // TODO(crbug.com/991943): This shouldn't be required now that + // IsRecentLocalCacheGuid() is used above. However, issues have been + // observed on Android, as if IsRecentLocalCacheGuid() didn't get populated + // reliably. if (device->guid() == change_processor()->TrackedCacheGuid() || device->client_name() == local_device_name_) { continue;
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc index 5176d5d0..d626cf7a 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc
@@ -99,7 +99,7 @@ sync_pb::SyncEnums_DeviceType_TYPE_LINUX, "scoped_is", clock()->Now() - base::TimeDelta::FromDays(1), /*send_tab_to_self_receiving_enabled=*/true); - AddTestDevice(local_device_.get()); + AddTestDevice(local_device_.get(), /*local=*/true); } // Initialized the bridge based on the current local device and store. Can @@ -179,8 +179,11 @@ .WillByDefault(Return(cache_guid)); } - void AddTestDevice(const syncer::DeviceInfo* device) { + void AddTestDevice(const syncer::DeviceInfo* device, bool local = false) { device_info_tracker_.Add(device); + if (local) { + device_info_tracker_.SetLocalCacheGuid(device->guid()); + } } syncer::MockModelTypeChangeProcessor* processor() { return &mock_processor_; }
diff --git a/components/signin/core/browser/android/java/src/org/chromium/components/signin/OAuth2TokenService.java b/components/signin/core/browser/android/java/src/org/chromium/components/signin/OAuth2TokenService.java index a13a14f..8d1e47b 100644 --- a/components/signin/core/browser/android/java/src/org/chromium/components/signin/OAuth2TokenService.java +++ b/components/signin/core/browser/android/java/src/org/chromium/components/signin/OAuth2TokenService.java
@@ -135,21 +135,21 @@ String username, String scope, final long nativeCallback) { Account account = getAccountOrNullFromUsername(username); if (account == null) { - ThreadUtils.postOnUiThread(() - -> OAuth2TokenServiceJni.get().oAuth2TokenFetched( - null, false, nativeCallback)); + ThreadUtils.postOnUiThread(() -> { + OAuth2TokenServiceJni.get().onOAuth2TokenFetched(null, false, nativeCallback); + }); return; } String oauth2Scope = OAUTH2_SCOPE_PREFIX + scope; getAccessToken(account, oauth2Scope, new GetAccessTokenCallback() { @Override public void onGetTokenSuccess(String token) { - OAuth2TokenServiceJni.get().oAuth2TokenFetched(token, false, nativeCallback); + OAuth2TokenServiceJni.get().onOAuth2TokenFetched(token, false, nativeCallback); } @Override public void onGetTokenFailure(boolean isTransientError) { - OAuth2TokenServiceJni.get().oAuth2TokenFetched( + OAuth2TokenServiceJni.get().onOAuth2TokenFetched( null, isTransientError, nativeCallback); } }); @@ -398,7 +398,8 @@ @NativeMethods interface Natives { - void oAuth2TokenFetched(String authToken, boolean isTransientError, long nativeCallback); + void onOAuth2TokenFetched( + String authToken, boolean isTransientError, long nativeCallback); void updateAccountList(long nativeOAuth2TokenServiceDelegateAndroid, OAuth2TokenService caller, String currentlySignedInAccount); }
diff --git a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc index ba2a161..84bfe8fb 100644 --- a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc +++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc
@@ -488,7 +488,7 @@ // Called from Java when fetching of an OAuth2 token is finished. The // |authToken| param is only valid when |result| is true. -void JNI_OAuth2TokenService_OAuth2TokenFetched( +void JNI_OAuth2TokenService_OnOAuth2TokenFetched( JNIEnv* env, const JavaParamRef<jstring>& authToken, jboolean isTransientError,
diff --git a/components/sync/driver/glue/sync_engine_backend.cc b/components/sync/driver/glue/sync_engine_backend.cc index 4953d03..99269df2 100644 --- a/components/sync/driver/glue/sync_engine_backend.cc +++ b/components/sync/driver/glue/sync_engine_backend.cc
@@ -18,6 +18,7 @@ #include "components/sync/base/invalidation_adapter.h" #include "components/sync/base/sync_base_switches.h" #include "components/sync/driver/configure_context.h" +#include "components/sync/driver/directory_data_type_controller.h" #include "components/sync/driver/model_type_controller.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/engine/cycle/commit_counters.h" @@ -681,6 +682,20 @@ sync_manager_->UpdateInvalidationClientId(client_id); } +void SyncEngineBackend::GetNigoriNodeForDebugging(AllNodesCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (nigori_controller_) { + // USS implementation of Nigori. + nigori_controller_->GetAllNodes(std::move(callback)); + } else { + // Directory implementation of Nigori. + DCHECK(user_share_.directory); + std::move(callback).Run( + NIGORI, DirectoryDataTypeController::GetAllNodesForTypeFromDirectory( + NIGORI, user_share_.directory.get())); + } +} + bool SyncEngineBackend::HasUnsyncedItemsForTest() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(sync_manager_);
diff --git a/components/sync/driver/glue/sync_engine_backend.h b/components/sync/driver/glue/sync_engine_backend.h index 1624e52..ade6f25 100644 --- a/components/sync/driver/glue/sync_engine_backend.h +++ b/components/sync/driver/glue/sync_engine_backend.h
@@ -46,6 +46,10 @@ public SyncManager::Observer, public TypeDebugInfoObserver { public: + using AllNodesCallback = + base::OnceCallback<void(const ModelType, + std::unique_ptr<base::ListValue>)>; + SyncEngineBackend(const std::string& name, const base::FilePath& sync_data_folder, const base::WeakPtr<SyncEngineImpl>& host); @@ -174,6 +178,9 @@ // Notify about change in client id. void DoOnInvalidatorClientIdChange(const std::string& client_id); + // Returns a ListValue representing Nigori node. + void GetNigoriNodeForDebugging(AllNodesCallback callback); + bool HasUnsyncedItemsForTest() const; private:
diff --git a/components/sync/driver/glue/sync_engine_impl.cc b/components/sync/driver/glue/sync_engine_impl.cc index 8113c24..fd54656 100644 --- a/components/sync/driver/glue/sync_engine_impl.cc +++ b/components/sync/driver/glue/sync_engine_impl.cc
@@ -16,6 +16,7 @@ #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/public/invalidation_service.h" #include "components/invalidation/public/object_id_invalidation_map.h" +#include "components/sync/base/bind_to_task_runner.h" #include "components/sync/base/invalidation_helper.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/driver/glue/sync_engine_backend.h" @@ -445,6 +446,14 @@ DCHECK(success); } +void SyncEngineImpl::GetNigoriNodeForDebugging(AllNodesCallback callback) { + DCHECK(backend_); + sync_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&SyncEngineBackend::GetNigoriNodeForDebugging, backend_, + BindToCurrentSequence(std::move(callback)))); +} + void SyncEngineImpl::OnInvalidatorClientIdChange(const std::string& client_id) { sync_task_runner_->PostTask( FROM_HERE,
diff --git a/components/sync/driver/glue/sync_engine_impl.h b/components/sync/driver/glue/sync_engine_impl.h index 4c3874db..e7a9c1f 100644 --- a/components/sync/driver/glue/sync_engine_impl.h +++ b/components/sync/driver/glue/sync_engine_impl.h
@@ -92,6 +92,7 @@ bool empty_jar, const base::Closure& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; + void GetNigoriNodeForDebugging(AllNodesCallback callback) override; // InvalidationHandler implementation. void OnInvalidatorStateChange(InvalidatorState state) override;
diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc index 31c290a..42e3b29 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc
@@ -1652,10 +1652,10 @@ &GetAllNodesRequestHelper::OnReceivedNodesForType, helper)); } } else { - // Control Types. - helper->OnReceivedNodesForType( - type, DirectoryDataTypeController::GetAllNodesForTypeFromDirectory( - type, GetUserShare()->directory.get())); + // We should have no data type controller only for Nigori. + DCHECK_EQ(type, NIGORI); + engine_->GetNigoriNodeForDebugging(base::BindOnce( + &GetAllNodesRequestHelper::OnReceivedNodesForType, helper)); } } }
diff --git a/components/sync/engine/fake_sync_engine.cc b/components/sync/engine/fake_sync_engine.cc index c7220657..9fee2c2 100644 --- a/components/sync/engine/fake_sync_engine.cc +++ b/components/sync/engine/fake_sync_engine.cc
@@ -108,4 +108,6 @@ void FakeSyncEngine::SetInvalidationsForSessionsEnabled(bool enabled) {} +void FakeSyncEngine::GetNigoriNodeForDebugging(AllNodesCallback callback) {} + } // namespace syncer
diff --git a/components/sync/engine/fake_sync_engine.h b/components/sync/engine/fake_sync_engine.h index 99703dc..6f858a8 100644 --- a/components/sync/engine/fake_sync_engine.h +++ b/components/sync/engine/fake_sync_engine.h
@@ -88,7 +88,7 @@ bool empty_jar, const base::Closure& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; - + void GetNigoriNodeForDebugging(AllNodesCallback callback) override; void set_fail_initial_download(bool should_fail); private:
diff --git a/components/sync/engine/mock_sync_engine.h b/components/sync/engine/mock_sync_engine.h index 73586d7..57705236 100644 --- a/components/sync/engine/mock_sync_engine.h +++ b/components/sync/engine/mock_sync_engine.h
@@ -60,6 +60,7 @@ MOCK_METHOD1(ClearServerData, void(const base::Closure&)); MOCK_METHOD3(OnCookieJarChanged, void(bool, bool, const base::Closure&)); MOCK_METHOD1(SetInvalidationsForSessionsEnabled, void(bool)); + MOCK_METHOD1(GetNigoriNodeForDebugging, void(AllNodesCallback)); }; } // namespace syncer
diff --git a/components/sync/engine/sync_engine.h b/components/sync/engine/sync_engine.h index 69f286d..0cd3776 100644 --- a/components/sync/engine/sync_engine.h +++ b/components/sync/engine/sync_engine.h
@@ -43,6 +43,8 @@ // interface will handle crossing threads if necessary. class SyncEngine : public ModelTypeConfigurer { public: + using AllNodesCallback = + base::OnceCallback<void(ModelType, std::unique_ptr<base::ListValue>)>; using HttpPostProviderFactoryGetter = base::OnceCallback<std::unique_ptr<HttpPostProviderFactory>( CancelationSignal*)>; @@ -190,6 +192,9 @@ // Enables/Disables invalidations for session sync related datatypes. virtual void SetInvalidationsForSessionsEnabled(bool enabled) = 0; + // Returns a ListValue representing Nigori node. + virtual void GetNigoriNodeForDebugging(AllNodesCallback callback) = 0; + private: DISALLOW_COPY_AND_ASSIGN(SyncEngine); };
diff --git a/components/sync/nigori/nigori_model_type_processor.cc b/components/sync/nigori/nigori_model_type_processor.cc index d817d119..f9b67c7 100644 --- a/components/sync/nigori/nigori_model_type_processor.cc +++ b/components/sync/nigori/nigori_model_type_processor.cc
@@ -229,35 +229,34 @@ AllNodesCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::unique_ptr<base::DictionaryValue> root_node; std::unique_ptr<EntityData> entity_data = bridge_->GetData(); - if (entity_data) { - if (entity_) { - const sync_pb::EntityMetadata& metadata = entity_->metadata(); - // Set id value as directory, "s" means server. - entity_data->id = "s" + metadata.server_id(); - entity_data->creation_time = ProtoTimeToTime(metadata.creation_time()); - entity_data->modification_time = - ProtoTimeToTime(metadata.modification_time()); - } - root_node = entity_data->ToDictionaryValue(); - if (entity_) { - root_node->Set("metadata", EntityMetadataToValue(entity_->metadata())); - } - } else { - root_node = std::make_unique<base::DictionaryValue>(); + if (!entity_data) { + std::move(callback).Run(syncer::NIGORI, + std::make_unique<base::ListValue>()); + return; + } + + if (entity_) { + const sync_pb::EntityMetadata& metadata = entity_->metadata(); + // Set id value as directory, "s" means server. + entity_data->id = "s" + metadata.server_id(); + entity_data->creation_time = ProtoTimeToTime(metadata.creation_time()); + entity_data->modification_time = + ProtoTimeToTime(metadata.modification_time()); + } + std::unique_ptr<base::DictionaryValue> root_node; + root_node = entity_data->ToDictionaryValue(); + if (entity_) { + root_node->Set("metadata", EntityMetadataToValue(entity_->metadata())); } // Function isTypeRootNode in sync_node_browser.js use PARENT_ID and // UNIQUE_SERVER_TAG to check if the node is root node. isChildOf in // sync_node_browser.js uses modelType to check if root node is parent of real - // data node. NON_UNIQUE_NAME will be the name of node to display. - root_node->SetString("ID", "NIGORI_ROOT"); + // data node. root_node->SetString("PARENT_ID", "r"); root_node->SetString("UNIQUE_SERVER_TAG", "Nigori"); - root_node->SetBoolean("IS_DIR", false); - root_node->SetString("modelType", "Nigori"); - root_node->SetString("NON_UNIQUE_NAME", "Nigori"); + root_node->SetString("modelType", ModelTypeToString(NIGORI)); auto all_nodes = std::make_unique<base::ListValue>(); all_nodes->Append(std::move(root_node));
diff --git a/components/sync/nigori/nigori_sync_bridge_impl.cc b/components/sync/nigori/nigori_sync_bridge_impl.cc index 9e11940..2c3abac 100644 --- a/components/sync/nigori/nigori_sync_bridge_impl.cc +++ b/components/sync/nigori/nigori_sync_bridge_impl.cc
@@ -1051,11 +1051,25 @@ std::unique_ptr<EntityData> NigoriSyncBridgeImpl::GetData() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(cryptographer_->CanEncrypt()); - DCHECK_NE(passphrase_type_, NigoriSpecifics::UNKNOWN); + if (passphrase_type_ == NigoriSpecifics::UNKNOWN) { + // Bridge never received NigoriSpecifics from the server. This line should + // be reachable only from processor's GetAllNodesForDebugging(). + DCHECK(!cryptographer_->CanEncrypt()); + DCHECK(!pending_keys_.has_value()); + return nullptr; + } NigoriSpecifics specifics; - EncryptKeyBag(*cryptographer_, specifics.mutable_encryption_keybag()); + if (cryptographer_->CanEncrypt()) { + EncryptKeyBag(*cryptographer_, specifics.mutable_encryption_keybag()); + } else { + DCHECK(pending_keys_.has_value()); + // This case is reachable only from processor's GetAllNodesForDebugging(), + // since currently commit is never issued while bridge has |pending_keys_|. + // Note: with complete support of TRUSTED_VAULT mode, commit might be + // issued in this case as well. + *specifics.mutable_encryption_keybag() = *pending_keys_; + } specifics.set_keybag_is_frozen(true); specifics.set_encrypt_everything(encrypt_everything_); if (encrypt_everything_) { @@ -1081,6 +1095,8 @@ } // TODO(crbug.com/922900): add other fields support. NOTIMPLEMENTED(); + DCHECK(IsValidNigoriSpecifics(specifics)); + auto entity_data = std::make_unique<EntityData>(); *entity_data->specifics.mutable_nigori() = std::move(specifics); entity_data->name = kNigoriNonUniqueName;
diff --git a/components/sync_device_info/fake_device_info_tracker.cc b/components/sync_device_info/fake_device_info_tracker.cc index 12fb0d8..51b8032d 100644 --- a/components/sync_device_info/fake_device_info_tracker.cc +++ b/components/sync_device_info/fake_device_info_tracker.cc
@@ -34,7 +34,11 @@ std::unique_ptr<DeviceInfo> FakeDeviceInfoTracker::GetDeviceInfo( const std::string& client_id) const { - NOTREACHED(); + for (const DeviceInfo* device : devices_) { + if (device->guid() == client_id) { + return CloneDeviceInfo(*device); + } + } return nullptr; } @@ -66,12 +70,7 @@ bool FakeDeviceInfoTracker::IsRecentLocalCacheGuid( const std::string& cache_guid) const { - for (const DeviceInfo* device : devices_) { - if (device->guid() == cache_guid) { - return true; - } - } - return false; + return local_device_cache_guid_ == cache_guid; } void FakeDeviceInfoTracker::Add(const DeviceInfo* device) { @@ -86,4 +85,10 @@ observer.OnDeviceInfoChange(); } +void FakeDeviceInfoTracker::SetLocalCacheGuid(const std::string& cache_guid) { + // ensure that this cache guid is present in the tracker. + DCHECK(GetDeviceInfo(cache_guid)); + local_device_cache_guid_ = cache_guid; +} + } // namespace syncer
diff --git a/components/sync_device_info/fake_device_info_tracker.h b/components/sync_device_info/fake_device_info_tracker.h index ecc390f..15a87896 100644 --- a/components/sync_device_info/fake_device_info_tracker.h +++ b/components/sync_device_info/fake_device_info_tracker.h
@@ -42,9 +42,13 @@ // actual number of devices in |devices_|. void OverrideActiveDeviceCount(int count); + // Marks an existing DeviceInfo entry as being on the local device. + void SetLocalCacheGuid(const std::string& cache_guid); + private: // DeviceInfo stored here are not owned. std::vector<const DeviceInfo*> devices_; + std::string local_device_cache_guid_; base::Optional<int> active_device_count_; // Registered observers, not owned. base::ObserverList<Observer, true>::Unchecked observers_;
diff --git a/components/viz/service/display/renderer_pixeltest.cc b/components/viz/service/display/renderer_pixeltest.cc index 62b3574..8889bdd 100644 --- a/components/viz/service/display/renderer_pixeltest.cc +++ b/components/viz/service/display/renderer_pixeltest.cc
@@ -1693,9 +1693,7 @@ std::unique_ptr<media::VideoResourceUpdater> video_resource_updater_; }; -// TODO(samans): Make these tests pass with Vulkan. https://crbug.com/960795 -using NonVulkanGPURendererTypes = ::testing::Types<GLRenderer, SkiaRenderer>; -TYPED_TEST_SUITE(VideoRendererPixelTest, NonVulkanGPURendererTypes); +TYPED_TEST_SUITE(VideoRendererPixelTest, GPURendererTypes); template <typename RendererType> class VideoRendererPixelHiLoTest : public VideoRendererPixelTest<RendererType>,
diff --git a/content/browser/accessibility/accessibility_auralinux_browsertest.cc b/content/browser/accessibility/accessibility_auralinux_browsertest.cc index 98ff8df..91b3500 100644 --- a/content/browser/accessibility/accessibility_auralinux_browsertest.cc +++ b/content/browser/accessibility/accessibility_auralinux_browsertest.cc
@@ -824,6 +824,90 @@ g_object_unref(div); } +IN_PROC_BROWSER_TEST_F(AccessibilityAuraLinuxBrowserTest, + TestTextSelectionAcrossElements) { + LoadInitialAccessibilityTreeFromHtml(std::string( + R"HTML(<!DOCTYPE html> + <html> + <body> + <div id="parent" contenteditable="true"> + <div id="child1">Child 1</div> + <div id="child2">Child 2</div> + </div> + </body> + </html>)HTML")); + + AtkObject* document = GetRendererAccessible(); + EXPECT_EQ(1, atk_object_get_n_accessible_children(document)); + + AtkText* parent = ATK_TEXT(atk_object_ref_accessible_child(document, 0)); + EXPECT_EQ(2, atk_object_get_n_accessible_children(ATK_OBJECT(parent))); + AtkText* child1 = + ATK_TEXT(atk_object_ref_accessible_child(ATK_OBJECT(parent), 0)); + AtkText* child2 = + ATK_TEXT(atk_object_ref_accessible_child(ATK_OBJECT(parent), 1)); + EXPECT_NE(nullptr, child1); + EXPECT_NE(nullptr, child2); + + auto callback = G_CALLBACK(+[](AtkText*, bool* flag) { *flag = true; }); + bool saw_selection_change_in_parent = false; + g_signal_connect(parent, "text-selection-changed", callback, + &saw_selection_change_in_parent); + bool saw_selection_change_in_child1 = false; + g_signal_connect(child1, "text-selection-changed", callback, + &saw_selection_change_in_child1); + bool saw_selection_change_in_child2 = false; + g_signal_connect(child2, "text-selection-changed", callback, + &saw_selection_change_in_child2); + + AccessibilityNotificationWaiter selection_waiter( + shell()->web_contents(), ui::kAXModeComplete, + ax::mojom::Event::kTextSelectionChanged); + ExecuteScript( + base::UTF8ToUTF16("let parent = document.getElementById('parent');" + "let child1 = document.getElementById('child1');" + "let child2 = document.getElementById('child2');" + "let range = document.createRange();" + "range.setStart(child1.firstChild, 3);" + "range.setEnd(child1.firstChild, 5);" + "parent.focus();" + "document.getSelection().removeAllRanges();" + "document.getSelection().addRange(range);")); + selection_waiter.WaitForNotification(); + + EXPECT_FALSE(saw_selection_change_in_parent); + EXPECT_TRUE(saw_selection_change_in_child1); + EXPECT_FALSE(saw_selection_change_in_child2); + + saw_selection_change_in_parent = false; + saw_selection_change_in_child1 = false; + saw_selection_change_in_child2 = false; + + EXPECT_TRUE(atk_text_remove_selection(parent, 0)); + selection_waiter.WaitForNotification(); + + EXPECT_FALSE(saw_selection_change_in_parent); + EXPECT_TRUE(saw_selection_change_in_child1); + EXPECT_FALSE(saw_selection_change_in_child2); + + saw_selection_change_in_parent = false; + saw_selection_change_in_child1 = false; + saw_selection_change_in_child2 = false; + + ExecuteScript( + base::UTF8ToUTF16("let range2 = document.createRange();" + "range2.setStart(child1.firstChild, 0);" + "range2.setEnd(child2.firstChild, 3);" + "parent.focus();" + "document.getSelection().removeAllRanges();" + "document.getSelection().addRange(range2);")); + selection_waiter.WaitForNotification(); + + EXPECT_TRUE(saw_selection_change_in_parent); + EXPECT_FALSE(saw_selection_change_in_child1); + EXPECT_FALSE(saw_selection_change_in_child2); +} + // TODO(crbug.com/981913): This flakes on linux. IN_PROC_BROWSER_TEST_F( AccessibilityAuraLinuxBrowserTest, @@ -982,6 +1066,8 @@ saw_caret_move_in_div = false; atk_text_set_caret_offset(anonymous_block, 3); + selection_waiter.WaitForNotification(); + EXPECT_FALSE(saw_caret_move_in_div); EXPECT_FALSE(saw_caret_move_in_text); EXPECT_FALSE(saw_caret_move_in_anonymous_block);
diff --git a/content/browser/accessibility/browser_accessibility_cocoa.mm b/content/browser/accessibility/browser_accessibility_cocoa.mm index fd183bb..5bdcea9 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa.mm +++ b/content/browser/accessibility/browser_accessibility_cocoa.mm
@@ -23,6 +23,7 @@ #include "base/strings/string_util.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" +#include "base/trace_event/trace_event.h" #include "content/browser/accessibility/browser_accessibility_mac.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_manager_mac.h" @@ -31,6 +32,7 @@ #include "content/public/common/content_client.h" #include "third_party/blink/public/strings/grit/blink_strings.h" #include "third_party/skia/include/core/SkColor.h" +#include "ui/accessibility/ax_enum_util.h" #include "ui/accessibility/ax_range.h" #include "ui/accessibility/ax_role_properties.h" #include "ui/accessibility/platform/ax_platform_node.h" @@ -1680,7 +1682,9 @@ // Returns an enum indicating the role from owner_. // internal - (ax::mojom::Role)internalRole { - return static_cast<ax::mojom::Role>(owner_->GetRole()); + if ([self instanceActive]) + return static_cast<ax::mojom::Role>(owner_->GetRole()); + return ax::mojom::Role::kNone; } - (BOOL)shouldExposeNameInDescription { @@ -1814,31 +1818,32 @@ // Returns a string indicating the NSAccessibility role of this object. - (NSString*)role { - if (![self instanceActive]) + if (![self instanceActive]) { + TRACE_EVENT0("accessibility", "BrowserAccessibilityCocoa::role nil"); return nil; + } + NSString* cocoa_role = nil; ax::mojom::Role role = [self internalRole]; if (role == ax::mojom::Role::kCanvas && owner_->GetBoolAttribute(ax::mojom::BoolAttribute::kCanvasHasFallback)) { - return NSAccessibilityGroupRole; + cocoa_role = NSAccessibilityGroupRole; + } else if ((owner_->IsPlainTextField() && + owner_->HasState(ax::mojom::State::kMultiline)) || + owner_->IsRichTextField()) { + cocoa_role = NSAccessibilityTextAreaRole; + } else if (role == ax::mojom::Role::kImage && + owner_->HasExplicitlyEmptyName()) { + cocoa_role = NSAccessibilityUnknownRole; + } else if (owner_->IsWebAreaForPresentationalIframe()) { + cocoa_role = NSAccessibilityGroupRole; + } else { + cocoa_role = [AXPlatformNodeCocoa nativeRoleFromAXRole:role]; } - if ((owner_->IsPlainTextField() && - owner_->HasState(ax::mojom::State::kMultiline)) || - owner_->IsRichTextField()) { - return NSAccessibilityTextAreaRole; - } - - if (role == ax::mojom::Role::kImage && owner_->HasExplicitlyEmptyName()) - return NSAccessibilityUnknownRole; - - // If this is a web area for a presentational iframe, give it a role of - // something other than WebArea so that the fact that it's a separate doc - // is not exposed to AT. - if (owner_->IsWebAreaForPresentationalIframe()) - return NSAccessibilityGroupRole; - - return [AXPlatformNodeCocoa nativeRoleFromAXRole:role]; + TRACE_EVENT1("accessibility", "BrowserAccessibilityCocoa::role", + "role=", base::SysNSStringToUTF8(cocoa_role)); + return cocoa_role; } // Returns a string indicating the role description of this object. @@ -1861,7 +1866,6 @@ } NSString* role = [self role]; - ContentClient* content_client = content::GetContentClient(); // The following descriptions are specific to webkit. @@ -2517,6 +2521,10 @@ // Returns the accessibility value for the given attribute. If the value isn't // supported this will return nil. - (id)accessibilityAttributeValue:(NSString*)attribute { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilityAttributeValue", + "role=", ui::ToString([self internalRole]), + "attribute=", base::SysNSStringToUTF8(attribute)); if (![self instanceActive]) return nil; @@ -2531,6 +2539,21 @@ // value isn't supported this will return nil. - (id)accessibilityAttributeValue:(NSString*)attribute forParameter:(id)parameter { + if (parameter && [parameter isKindOfClass:[NSNumber self]]) { + TRACE_EVENT2( + "accessibility", + "BrowserAccessibilityCocoa::accessibilityAttributeValue:forParameter", + "role=", ui::ToString([self internalRole]), "attribute=", + base::SysNSStringToUTF8(attribute) + + " parameter=" + base::SysNSStringToUTF8([parameter stringValue])); + } else { + TRACE_EVENT2( + "accessibility", + "BrowserAccessibilityCocoa::accessibilityAttributeValue:forParameter", + "role=", ui::ToString([self internalRole]), + "attribute=", base::SysNSStringToUTF8(attribute)); + } + if (![self instanceActive]) return nil; @@ -3026,6 +3049,10 @@ // Returns an array of parameterized attributes names that this object will // respond to. - (NSArray*)accessibilityParameterizedAttributeNames { + TRACE_EVENT1( + "accessibility", + "BrowserAccessibilityCocoa::accessibilityParameterizedAttributeNames", + "role=", ui::ToString([self internalRole])); if (![self instanceActive]) return nil; @@ -3111,6 +3138,9 @@ // Returns an array of action names that this object will respond to. - (NSArray*)accessibilityActionNames { + TRACE_EVENT1("accessibility", + "BrowserAccessibilityCocoa::accessibilityActionNames", + "role=", ui::ToString([self internalRole])); if (![self instanceActive]) return nil; @@ -3137,6 +3167,9 @@ // Returns the list of accessibility attributes that this object supports. - (NSArray*)accessibilityAttributeNames { + TRACE_EVENT1("accessibility", + "BrowserAccessibilityCocoa::accessibilityAttributeNames", + "role=", ui::ToString([self internalRole])); if (![self instanceActive]) return nil; @@ -3386,6 +3419,9 @@ // Returns the index of the child in this objects array of children. - (NSUInteger)accessibilityGetIndexOf:(id)child { + TRACE_EVENT1("accessibility", + "BrowserAccessibilityCocoa::accessibilityGetIndexOf", + "role=", ui::ToString([self internalRole])); if (![self instanceActive]) return 0; @@ -3401,6 +3437,10 @@ // Returns whether or not the specified attribute can be set by the // accessibility API via |accessibilitySetValue:forAttribute:|. - (BOOL)accessibilityIsAttributeSettable:(NSString*)attribute { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilityIsAttributeSettable", + "role=", ui::ToString([self internalRole]), + "attribute=", base::SysNSStringToUTF8(attribute)); if (![self instanceActive]) return NO; @@ -3425,6 +3465,9 @@ // Returns whether or not this object should be ignored in the accessibility // tree. - (BOOL)accessibilityIsIgnored { + TRACE_EVENT1("accessibility", + "BrowserAccessibilityCocoa::accessibilityIsIgnored", + "role=", ui::ToString([self internalRole])); if (![self instanceActive]) return YES; @@ -3434,6 +3477,10 @@ // Performs the given accessibility action on the webkit accessibility object // that backs this object. - (void)accessibilityPerformAction:(NSString*)action { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilityPerformAction", + "role=", ui::ToString([self internalRole]), + "action=", base::SysNSStringToUTF8(action)); if (![self instanceActive]) return; @@ -3477,6 +3524,10 @@ // Returns the description of the given action. - (NSString*)accessibilityActionDescription:(NSString*)action { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilityActionDescription", + "role=", ui::ToString([self internalRole]), + "action=", base::SysNSStringToUTF8(action)); if (![self instanceActive]) return nil; @@ -3487,6 +3538,11 @@ // This class does not support this. - (BOOL)accessibilitySetOverrideValue:(id)value forAttribute:(NSString*)attribute { + TRACE_EVENT2( + "accessibility", + "BrowserAccessibilityCocoa::accessibilitySetOverrideValue:forAttribute", + "role=", ui::ToString([self internalRole]), + "attribute=", base::SysNSStringToUTF8(attribute)); if (![self instanceActive]) return NO; return NO; @@ -3494,6 +3550,10 @@ // Sets the value for an accessibility attribute via the accessibility API. - (void)accessibilitySetValue:(id)value forAttribute:(NSString*)attribute { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilitySetValue:forAttribute", + "role=", ui::ToString([self internalRole]), + "attribute=", base::SysNSStringToUTF8(attribute)); if (![self instanceActive]) return; @@ -3518,6 +3578,10 @@ // or one of its children, so this will never return nil unless this // object is invalid. - (id)accessibilityHitTest:(NSPoint)point { + TRACE_EVENT2("accessibility", + "BrowserAccessibilityCocoa::accessibilityHitTest", + "role=", ui::ToString([self internalRole]), + "point=", base::SysNSStringToUTF8(NSStringFromPoint(point))); if (![self instanceActive]) return nil; @@ -3546,6 +3610,9 @@ } - (BOOL)accessibilityNotifiesWhenDestroyed { + TRACE_EVENT1("accessibility", + "BrowserAccessibilityCocoa::accessibilityNotifiesWhenDestroyed", + "role=", ui::ToString([self internalRole])); // Indicate that BrowserAccessibilityCocoa will post a notification when it's // destroyed (see -detach). This allows VoiceOver to do some internal things // more efficiently.
diff --git a/content/browser/accessibility/browser_accessibility_manager_auralinux.h b/content/browser/accessibility/browser_accessibility_manager_auralinux.h index d6b0547..7ee8c62 100644 --- a/content/browser/accessibility/browser_accessibility_manager_auralinux.h +++ b/content/browser/accessibility/browser_accessibility_manager_auralinux.h
@@ -25,6 +25,9 @@ ~BrowserAccessibilityManagerAuraLinux() override; static ui::AXTreeUpdate GetEmptyDocument(); + static BrowserAccessibility* FindCommonAncestor( + BrowserAccessibility* object1, + BrowserAccessibility* object2); // Implementation of BrowserAccessibilityManager methods. void FireFocusEvent(BrowserAccessibility* node) override;
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 7e08168d..2dc6906 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -236,6 +236,10 @@ RunCSSTest(FILE_PATH_LITERAL("font-family.html")); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, AccessibilityCSSFontSize) { + RunCSSTest(FILE_PATH_LITERAL("font-size.html")); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, AccessibilityCSSDisplayToNone) { RunCSSTest(FILE_PATH_LITERAL("display-to-none.html"));
diff --git a/content/browser/browser_interface_binders.cc b/content/browser/browser_interface_binders.cc index f90239e..9042c86 100644 --- a/content/browser/browser_interface_binders.cc +++ b/content/browser/browser_interface_binders.cc
@@ -26,6 +26,8 @@ #include "device/gamepad/gamepad_monitor.h" #include "device/gamepad/public/mojom/gamepad.mojom.h" #include "media/capture/mojom/image_capture.mojom.h" +#include "media/mojo/mojom/video_decode_perf_history.mojom.h" +#include "media/mojo/services/video_decode_perf_history.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/sensor_provider.mojom.h" #include "services/device/public/mojom/vibration_manager.mojom.h" @@ -145,9 +147,6 @@ &ForwardServiceReceiver<device::mojom::VibrationManager>, device::mojom::kServiceName, base::Unretained(host))); - map->Add<media::mojom::ImageCapture>( - base::BindRepeating(&ImageCaptureImpl::Create)); - map->Add<payments::mojom::PaymentManager>( base::BindRepeating(&RenderProcessHost::CreatePaymentManager, base::Unretained(host->GetProcess()))); @@ -167,6 +166,13 @@ map->Add<blink::test::mojom::VirtualAuthenticatorManager>( base::BindRepeating(&RenderFrameHostImpl::GetVirtualAuthenticatorManager, base::Unretained(host))); + + map->Add<media::mojom::ImageCapture>( + base::BindRepeating(&ImageCaptureImpl::Create)); + + map->Add<media::mojom::VideoDecodePerfHistory>( + base::BindRepeating(&RenderProcessHost::BindVideoDecodePerfHistory, + base::Unretained(host->GetProcess()))); } void PopulateBinderMapWithContext( @@ -215,6 +221,9 @@ map->Add<blink::mojom::SmsReceiver>(base::BindRepeating( &DedicatedWorkerHost::BindSmsReceiverReceiver, base::Unretained(host))); } + map->Add<media::mojom::VideoDecodePerfHistory>( + base::BindRepeating(&DedicatedWorkerHost::BindVideoDecodePerfHistory, + base::Unretained(host))); map->Add<payments::mojom::PaymentManager>(base::BindRepeating( &DedicatedWorkerHost::CreatePaymentManager, base::Unretained(host))); } @@ -248,6 +257,8 @@ &SharedWorkerHost::CreateAppCacheBackend, base::Unretained(host))); map->Add<blink::mojom::ScreenEnumeration>( base::BindRepeating(&ScreenEnumerationImpl::Create)); + map->Add<media::mojom::VideoDecodePerfHistory>(base::BindRepeating( + &SharedWorkerHost::BindVideoDecodePerfHistory, base::Unretained(host))); map->Add<payments::mojom::PaymentManager>(base::BindRepeating( &SharedWorkerHost::CreatePaymentManager, base::Unretained(host))); } @@ -291,6 +302,11 @@ map->Add<blink::mojom::PermissionService>( base::BindRepeating(&ServiceWorkerProviderHost::CreatePermissionService, base::Unretained(host))); + + map->Add<media::mojom::VideoDecodePerfHistory>(base::BindRepeating( + &ServiceWorkerProviderHost::BindVideoDecodePerfHistory, + base::Unretained(host))); + map->Add<payments::mojom::PaymentManager>( base::BindRepeating(&ServiceWorkerProviderHost::CreatePaymentManager, base::Unretained(host)));
diff --git a/content/browser/cache_storage/cache_storage_dispatcher_host.cc b/content/browser/cache_storage/cache_storage_dispatcher_host.cc index 26822e0..0eb5de1 100644 --- a/content/browser/cache_storage/cache_storage_dispatcher_host.cc +++ b/content/browser/cache_storage/cache_storage_dispatcher_host.cc
@@ -330,30 +330,6 @@ mojo::GetBadMessageCallback())); } - void SetSideData(const GURL& url, - base::Time response_time, - base::span<const uint8_t> side_data, - int64_t trace_id, - SetSideDataCallback callback) override { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_WITH_FLOW1("CacheStorage", - "CacheStorageDispatcherHost::CacheImpl::SetSideData", - TRACE_ID_GLOBAL(trace_id), - TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, - "url", url.spec()); - content::CacheStorageCache* cache = cache_handle_.value(); - if (!cache) { - std::move(callback).Run(blink::mojom::CacheStorageError::kErrorNotFound); - return; - } - scoped_refptr<net::IOBuffer> buffer = - base::MakeRefCounted<net::IOBuffer>(side_data.size()); - if (!side_data.empty()) - memcpy(buffer->data(), &side_data.front(), side_data.size()); - cache->WriteSideData(std::move(callback), url, response_time, trace_id, - std::move(buffer), side_data.size()); - } - CacheStorageCacheHandle cache_handle_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(CacheImpl);
diff --git a/content/browser/child_process_security_policy_impl.cc b/content/browser/child_process_security_policy_impl.cc index 2144315..8e177771 100644 --- a/content/browser/child_process_security_policy_impl.cc +++ b/content/browser/child_process_security_policy_impl.cc
@@ -1198,14 +1198,6 @@ DELETE_FILE_GRANT); } -bool ChildProcessSecurityPolicyImpl::CanAccessDataForWebSocket( - int child_id, - const GURL& url) { - DCHECK(url.SchemeIsWSOrWSS()); - GURL url_to_check = net::ChangeWebSocketSchemeToHttpScheme(url); - return CanAccessDataForOrigin(child_id, url_to_check); -} - bool ChildProcessSecurityPolicyImpl::HasWebUIBindings(int child_id) { base::AutoLock lock(lock_);
diff --git a/content/browser/child_process_security_policy_impl.h b/content/browser/child_process_security_policy_impl.h index 8976f94c..08c9707d 100644 --- a/content/browser/child_process_security_policy_impl.h +++ b/content/browser/child_process_security_policy_impl.h
@@ -234,10 +234,6 @@ bool CanDeleteFileSystemFile(int child_id, const storage::FileSystemURL& filesystem_url); - // True if cookie headers may be exposed to renderer |child_id| for |url| for - // display in DevTools. |url| should be a WebSocket URL. - bool CanAccessDataForWebSocket(int child_id, const GURL& url); - // Returns true if the specified child_id has been granted ReadRawCookies. bool CanReadRawCookies(int child_id);
diff --git a/content/browser/frame_host/keep_alive_handle_factory.cc b/content/browser/frame_host/keep_alive_handle_factory.cc index 70b5ad3..9d702d0 100644 --- a/content/browser/frame_host/keep_alive_handle_factory.cc +++ b/content/browser/frame_host/keep_alive_handle_factory.cc
@@ -4,16 +4,20 @@ #include "content/browser/frame_host/keep_alive_handle_factory.h" +#include <memory> +#include <utility> + #include "base/bind.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/task/post_task.h" +#include "content/common/frame.mojom.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_features.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "mojo/public/cpp/bindings/strong_binding_set.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/unique_receiver_set.h" namespace content { @@ -44,9 +48,9 @@ timeout); } - void AddBinding(std::unique_ptr<mojom::KeepAliveHandle> impl, - mojom::KeepAliveHandleRequest request) { - binding_set_.AddBinding(std::move(impl), std::move(request)); + void AddReceiver(std::unique_ptr<mojom::KeepAliveHandle> impl, + mojo::PendingReceiver<mojom::KeepAliveHandle> receiver) { + receiver_set_.Add(std::move(impl), std::move(receiver)); } base::WeakPtr<Context> AsWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } @@ -55,7 +59,7 @@ friend class base::RefCounted<Context>; ~Context() { Detach(); } - mojo::StrongBindingSet<mojom::KeepAliveHandle> binding_set_; + mojo::UniqueReceiverSet<mojom::KeepAliveHandle> receiver_set_; const int process_id_; bool detached_ = false; @@ -85,7 +89,8 @@ context_->DetachLater(timeout_); } -void KeepAliveHandleFactory::Create(mojom::KeepAliveHandleRequest request) { +void KeepAliveHandleFactory::Create( + mojo::PendingReceiver<mojom::KeepAliveHandle> receiver) { scoped_refptr<Context> context; if (context_) { context = context_.get(); @@ -94,8 +99,8 @@ context_ = context->AsWeakPtr(); } - context->AddBinding(std::make_unique<KeepAliveHandleImpl>(context), - std::move(request)); + context->AddReceiver(std::make_unique<KeepAliveHandleImpl>(context), + std::move(receiver)); } void KeepAliveHandleFactory::SetTimeout(base::TimeDelta timeout) {
diff --git a/content/browser/frame_host/keep_alive_handle_factory.h b/content/browser/frame_host/keep_alive_handle_factory.h index d5eb453..746ae50 100644 --- a/content/browser/frame_host/keep_alive_handle_factory.h +++ b/content/browser/frame_host/keep_alive_handle_factory.h
@@ -9,6 +9,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "content/common/frame.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" namespace content { @@ -25,7 +26,7 @@ explicit KeepAliveHandleFactory(RenderProcessHost* process_host); ~KeepAliveHandleFactory(); - void Create(mojom::KeepAliveHandleRequest request); + void Create(mojo::PendingReceiver<mojom::KeepAliveHandle> receiver); // Sets the timeout after which all created handles will be invalidated. void SetTimeout(base::TimeDelta timeout);
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 25d718a..9267e74 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -1424,6 +1424,12 @@ common_params_->referrer = Referrer::SanitizeForRequest( common_params_->url, *common_params_->referrer); + // On redirects, the initial referrer is no longer correct, so it must + // be updated. (A parallel process updates the outgoing referrer in the + // network stack.) + commit_params_->redirect_infos.back().new_referrer = + common_params_->referrer->url.spec(); + // Check Content Security Policy before the NavigationThrottles run. This // gives CSP a chance to modify requests that NavigationThrottles would // otherwise block. @@ -3124,6 +3130,8 @@ Referrer::SanitizeForRequest(common_params_->url, *sanitized_referrer_); } + common_params_->referrer = sanitized_referrer_.Clone(); + was_redirected_ = true; redirect_chain_.push_back(common_params_->url);
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 86c5db3..5d7c757 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -117,6 +117,7 @@ #include "content/common/accessibility_messages.h" #include "content/common/associated_interfaces.mojom.h" #include "content/common/content_security_policy/content_security_policy.h" +#include "content/common/frame.mojom.h" #include "content/common/frame_messages.h" #include "content/common/frame_owner_properties.h" #include "content/common/input/input_handler.mojom.h" @@ -146,6 +147,7 @@ #include "content/public/browser/site_isolation_policy.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/webvr_service_provider.h" +#include "content/public/common/bind_interface_helpers.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_features.h" @@ -170,6 +172,8 @@ #include "media/mojo/services/media_interface_provider.h" #include "media/mojo/services/media_metrics_provider.h" #include "media/mojo/services/video_decode_perf_history.h" +#include "mojo/public/cpp/bindings/associated_receiver.h" +#include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/message.h" #include "mojo/public/cpp/bindings/pending_associated_remote.h" @@ -848,7 +852,6 @@ has_selection_(false), is_audible_(false), last_navigation_previews_state_(PREVIEWS_UNSPECIFIED), - frame_host_associated_binding_(this), waiting_for_init_(renderer_initiated_creation), has_focused_editable_element_(false), push_messaging_manager_( @@ -4195,7 +4198,7 @@ } void RenderFrameHostImpl::IssueKeepAliveHandle( - mojom::KeepAliveHandleRequest request) { + mojo::PendingReceiver<mojom::KeepAliveHandle> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (GetProcess()->IsKeepAliveRefCountDisabled()) return; @@ -4209,7 +4212,7 @@ std::make_unique<KeepAliveHandleFactory>(GetProcess()); keep_alive_handle_factory_->SetTimeout(keep_alive_timeout_); } - keep_alive_handle_factory_->Create(std::move(request)); + keep_alive_handle_factory_->Create(std::move(receiver)); } // TODO(ahemery): Move checks to mojo bad message reporting. @@ -5497,12 +5500,13 @@ associated_registry_ = std::make_unique<blink::AssociatedInterfaceRegistry>(); registry_ = std::make_unique<service_manager::BinderRegistry>(); - auto make_binding = [](RenderFrameHostImpl* impl, - mojom::FrameHostAssociatedRequest request) { - impl->frame_host_associated_binding_.Bind(std::move(request)); - }; + auto bind_frame_host_receiver = + [](RenderFrameHostImpl* impl, + mojo::PendingAssociatedReceiver<mojom::FrameHost> receiver) { + impl->frame_host_associated_receiver_.Bind(std::move(receiver)); + }; associated_registry_->AddInterface( - base::BindRepeating(make_binding, base::Unretained(this))); + base::BindRepeating(bind_frame_host_receiver, base::Unretained(this))); associated_registry_->AddInterface(base::BindRepeating( [](RenderFrameHostImpl* self, @@ -5512,9 +5516,10 @@ base::Unretained(this))); RegisterMojoInterfaces(); - mojom::FrameFactoryPtr frame_factory; + mojo::PendingRemote<mojom::FrameFactory> frame_factory; BindInterface(GetProcess(), &frame_factory); - frame_factory->CreateFrame(routing_id_, MakeRequest(&frame_)); + mojo::Remote<mojom::FrameFactory>(std::move(frame_factory)) + ->CreateFrame(routing_id_, frame_.BindNewPipeAndPassReceiver()); service_manager::mojom::InterfaceProviderPtr remote_interfaces; frame_->GetInterfaceProvider(mojo::MakeRequest(&remote_interfaces)); @@ -5530,7 +5535,7 @@ frame_.reset(); frame_bindings_control_.reset(); - frame_host_associated_binding_.Close(); + frame_host_associated_receiver_.reset(); navigation_control_.reset(); frame_input_handler_.reset();
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 2ed48ec..b69cb64 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -57,6 +57,7 @@ #include "content/public/common/previews_state.h" #include "content/public/common/transferrable_url_loader.mojom.h" #include "media/mojo/mojom/interface_factory.mojom.h" +#include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -885,8 +886,9 @@ mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker>); // Exposed so that tests can swap out the implementation and intercept calls. - mojo::AssociatedBinding<mojom::FrameHost>& frame_host_binding_for_testing() { - return frame_host_associated_binding_; + mojo::AssociatedReceiver<mojom::FrameHost>& + frame_host_receiver_for_testing() { + return frame_host_associated_receiver_; } mojo::Binding<service_manager::mojom::InterfaceProvider>& @@ -1407,7 +1409,8 @@ CreatePortalCallback callback) override; void AdoptPortal(const base::UnguessableToken& portal_token, AdoptPortalCallback callback) override; - void IssueKeepAliveHandle(mojom::KeepAliveHandleRequest request) override; + void IssueKeepAliveHandle( + mojo::PendingReceiver<mojom::KeepAliveHandle> receiver) override; void DidCommitProvisionalLoad( std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> validated_params, @@ -2166,9 +2169,10 @@ bool has_committed_any_navigation_ = false; bool render_process_has_died_ = false; - mojo::AssociatedBinding<mojom::FrameHost> frame_host_associated_binding_; - mojom::FramePtr frame_; - mojom::FrameBindingsControlAssociatedPtr frame_bindings_control_; + mojo::AssociatedReceiver<mojom::FrameHost> frame_host_associated_receiver_{ + this}; + mojo::Remote<mojom::Frame> frame_; + mojo::AssociatedRemote<mojom::FrameBindingsControl> frame_bindings_control_; mojo::AssociatedRemote<mojom::FrameNavigationControl> navigation_control_; // If this is true then this object was created in response to a renderer
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index f981978..2142ad5 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -1600,10 +1600,10 @@ service_manager::mojom::InterfaceProviderRequest interface_provider_request_with_pending_request = mojo::MakeRequest(&interface_provider_with_pending_request); - mojom::FrameHostTestInterfacePtr test_interface; + mojo::Remote<mojom::FrameHostTestInterface> test_interface; interface_provider_with_pending_request->GetInterface( mojom::FrameHostTestInterface::Name_, - mojo::MakeRequest(&test_interface).PassMessagePipe()); + test_interface.BindNewPipeAndPassReceiver().PassPipe()); // Replace the |interface_provider_request| argument in the next // DidCommitProvisionalLoad message coming from the renderer with the @@ -1677,12 +1677,12 @@ ASSERT_TRUE(injector.original_request_of_last_commit().is_pending()); } - // Prepare an interface request for FrameHostTestInterface. - mojom::FrameHostTestInterfacePtr test_interface; - auto test_interface_request = mojo::MakeRequest(&test_interface); + // Prepare an interface receiver for FrameHostTestInterface. + mojo::Remote<mojom::FrameHostTestInterface> test_interface; + auto test_interface_receiver = test_interface.BindNewPipeAndPassReceiver(); // Set up |dispatched_interface_request_callback| that would be invoked if the - // interface request for FrameHostTestInterface was ever dispatched to the + // interface receiver for FrameHostTestInterface was ever dispatched to the // RenderFrameHostImpl. base::MockCallback<base::RepeatingClosure> dispatched_interface_request_callback; @@ -1702,9 +1702,8 @@ base::MockCallback<base::RepeatingClosure> navigation_finished_callback; DidFinishNavigationObserver navigation_finish_observer( main_rfh, base::BindLambdaForTesting([&]() { - interface_provider->GetInterface( - mojom::FrameHostTestInterface::Name_, - test_interface_request.PassMessagePipe()); + interface_provider->GetInterface(mojom::FrameHostTestInterface::Name_, + test_interface_receiver.PassPipe()); std::move(navigation_finished_callback).Run(); })); @@ -1712,10 +1711,13 @@ // document, but whose client end is actually controlled by this test, should // still be alive and well. ASSERT_TRUE(test_interface.is_bound()); - ASSERT_FALSE(test_interface.encountered_error()); + ASSERT_TRUE(test_interface.is_connected()); + + base::RunLoop run_loop; + test_interface.set_disconnect_handler(run_loop.QuitWhenIdleClosure()); // Expect that the GetInterface message will never be dispatched, but the - // DidFinishNavigation callback wll be invoked. + // DidFinishNavigation callback will be invoked. EXPECT_CALL(dispatched_interface_request_callback, Run()).Times(0); EXPECT_CALL(navigation_finished_callback, Run()); @@ -1725,11 +1727,9 @@ // Wait for a connection error on the |test_interface| as a signal, after // which it can be safely assumed that no GetInterface message will ever be // dispatched from that old InterfaceConnection. - base::RunLoop run_loop; - test_interface.set_connection_error_handler(run_loop.QuitWhenIdleClosure()); run_loop.Run(); - EXPECT_TRUE(test_interface.encountered_error()); + EXPECT_FALSE(test_interface.is_connected()); } // Test the edge case where the `window` global object asssociated with the
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index 025b88712..43c21e3f 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -858,11 +858,11 @@ if (IsPerNavigationMojoInterfaceEnabled()) { auto navigation_client_receiver = navigation_client.InitWithNewEndpointAndPassReceiver(); - rfh->frame_host_binding_for_testing().impl()->BeginNavigation( + rfh->frame_host_receiver_for_testing().impl()->BeginNavigation( std::move(common_params), std::move(begin_params), mojo::NullRemote(), std::move(navigation_client), mojo::NullRemote()); } else { - rfh->frame_host_binding_for_testing().impl()->BeginNavigation( + rfh->frame_host_receiver_for_testing().impl()->BeginNavigation( std::move(common_params), std::move(begin_params), mojo::NullRemote(), mojo::NullAssociatedRemote(), mojo::NullRemote()); }
diff --git a/content/browser/portal/portal_browsertest.cc b/content/browser/portal/portal_browsertest.cc index 5faf3de..93c420d 100644 --- a/content/browser/portal/portal_browsertest.cc +++ b/content/browser/portal/portal_browsertest.cc
@@ -166,12 +166,12 @@ public: explicit PortalCreatedObserver(RenderFrameHostImpl* render_frame_host_impl) : render_frame_host_impl_(render_frame_host_impl) { - old_impl_ = render_frame_host_impl_->frame_host_binding_for_testing() + old_impl_ = render_frame_host_impl_->frame_host_receiver_for_testing() .SwapImplForTesting(this); } ~PortalCreatedObserver() override { - render_frame_host_impl_->frame_host_binding_for_testing() + render_frame_host_impl_->frame_host_receiver_for_testing() .SwapImplForTesting(old_impl_); }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 23ebf96..e4a2ac7 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -191,6 +191,7 @@ #include "media/audio/audio_manager.h" #include "media/base/media_switches.h" #include "media/media_buildflags.h" +#include "media/mojo/services/video_decode_perf_history.h" #include "media/webrtc/webrtc_switches.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" @@ -1940,6 +1941,13 @@ std::move(receiver))); } +void RenderProcessHostImpl::BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + GetBrowserContext()->GetVideoDecodePerfHistory()->BindReceiver( + std::move(receiver)); +} + void RenderProcessHostImpl::CreateLockManager( int render_frame_id, const url::Origin& origin,
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index a826a1e..e58f6a8 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -51,6 +51,7 @@ #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_platform_file.h" #include "media/media_buildflags.h" +#include "media/mojo/mojom/video_decode_perf_history.mojom.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_receiver_set.h" #include "mojo/public/cpp/bindings/associated_remote.h" @@ -505,6 +506,12 @@ return file_system_manager_impl_.get(); } + // Binds |receiver| to the VideoDecodePerfHistory instance owned by the render + // process host, and is used by workers via BrowserInterfaceBroker. + void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) + override; + // Binds |receiver| to the LockManager owned by |storage_partition_impl_|. // |receiver| belongs to a frame or worker at |origin| hosted by this process. // If it belongs to a frame, |render_frame_id| identifies it, otherwise it is
diff --git a/content/browser/renderer_interface_binders.cc b/content/browser/renderer_interface_binders.cc index 7e58737..a399ac0 100644 --- a/content/browser/renderer_interface_binders.cc +++ b/content/browser/renderer_interface_binders.cc
@@ -29,8 +29,6 @@ #include "content/public/browser/render_process_host.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" -#include "media/mojo/mojom/video_decode_perf_history.mojom.h" -#include "media/mojo/services/video_decode_perf_history.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" @@ -208,12 +206,6 @@ ->GetCookieStoreContext() ->CreateService(std::move(request), origin); })); - parameterized_binder_registry_.AddInterface(base::BindRepeating( - [](media::mojom::VideoDecodePerfHistoryRequest request, - RenderProcessHost* host, const url::Origin& origin) { - host->GetBrowserContext()->GetVideoDecodePerfHistory()->BindRequest( - std::move(request)); - })); } RendererInterfaceBinders& GetRendererInterfaceBinders() {
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index 40a44c2..61679b2 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -91,7 +91,6 @@ #include "storage/browser/blob/blob_handle.h" #include "storage/browser/blob/blob_reader.h" #include "storage/browser/blob/blob_storage_context.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/service_worker/service_worker_status_code.h" #include "third_party/blink/public/common/service_worker/service_worker_type_converters.h" @@ -3506,180 +3505,6 @@ WaitUntilSideDataSizeIs(0); } -class ServiceWorkerCodeCacheStrategyTestBase : public ServiceWorkerBrowserTest { - public: - ServiceWorkerCodeCacheStrategyTestBase() = default; - ~ServiceWorkerCodeCacheStrategyTestBase() override = default; - - protected: - static const char kWorkerUrl[]; - static const char kPageUrl[]; - static const char kCachedInInstallEventUrl[]; - static const char kCachedInInstallEventWithMimeTypeParamUrl[]; - static const char kCachedInFetchEventUrl[]; - static const char kCachedInMessageEventUrl[]; - - void RegisterAndActivateServiceWorker() { - auto observer = base::MakeRefCounted<WorkerActivatedObserver>(wrapper()); - observer->Init(); - blink::mojom::ServiceWorkerRegistrationOptions options( - embedded_test_server()->GetURL(kPageUrl), - blink::mojom::ScriptType::kClassic, - blink::mojom::ServiceWorkerUpdateViaCache::kImports); - public_context()->RegisterServiceWorker( - embedded_test_server()->GetURL(kWorkerUrl), options, - base::BindOnce(&ExpectResultAndRun, true, base::DoNothing())); - observer->Wait(); - } - - void NavigateToTestPage() { - StartServerAndNavigateToSetup(); - RegisterAndActivateServiceWorker(); - EXPECT_TRUE( - NavigateToURL(shell(), embedded_test_server()->GetURL(kPageUrl))); - } - - void InitiateEventsToCacheScript() { - // Fetch a test script in the page. The service worker will put the - // response into CacheStorage in the fetch event handler. - EXPECT_EQ("DONE", EvalJs(shell(), - "fetch_script('code_cache_strategy_test_script.js?" - "cached_in_fetch_event');")); - // Post a message to the service worker to put the response of the test - // script into CacheStorage in the message event handler. - EXPECT_EQ("DONE", EvalJs(shell(), - "post_message('cache_script_in_message_event');")); - } - - CacheStorageContextImpl* GetCacheStorageContextImpl() { - StoragePartition* partition = BrowserContext::GetDefaultStoragePartition( - shell()->web_contents()->GetBrowserContext()); - return static_cast<CacheStorageContextImpl*>( - partition->GetCacheStorageContext()); - } - - bool HasSideData(const std::string& path) { - int size = CacheStorageSideDataSizeChecker::GetSize( - GetCacheStorageContextImpl(), embedded_test_server()->base_url(), - std::string("cache_name"), embedded_test_server()->GetURL(path)); - return size > 0; - } - - void WaitForSideData(const std::string& path) { - while (true) { - if (HasSideData(path)) - return; - } - } - - base::test::ScopedFeatureList feature_list_; - - DISALLOW_COPY_AND_ASSIGN(ServiceWorkerCodeCacheStrategyTestBase); -}; - -const char ServiceWorkerCodeCacheStrategyTestBase::kPageUrl[] = - "/service_worker/code_cache_strategy.html"; -const char ServiceWorkerCodeCacheStrategyTestBase::kWorkerUrl[] = - "/service_worker/code_cache_strategy_worker.js"; -const char ServiceWorkerCodeCacheStrategyTestBase::kCachedInInstallEventUrl[] = - "/service_worker/" - "code_cache_strategy_test_script.js?cached_in_install_event"; -const char ServiceWorkerCodeCacheStrategyTestBase:: - kCachedInInstallEventWithMimeTypeParamUrl[] = - "/service_worker/" - "code_cache_strategy_test_script.js?cached_in_install_event_with_mime_" - "type_param"; -const char ServiceWorkerCodeCacheStrategyTestBase::kCachedInFetchEventUrl[] = - "/service_worker/code_cache_strategy_test_script.js?cached_in_fetch_event"; -const char ServiceWorkerCodeCacheStrategyTestBase::kCachedInMessageEventUrl[] = - "/service_worker/" - "code_cache_strategy_test_script.js?cached_in_message_event"; - -class ServiceWorkerCodeCacheStrategyDontGenerateTest - : public ServiceWorkerCodeCacheStrategyTestBase { - public: - void SetUp() override { - feature_list_.InitAndEnableFeatureWithParameters( - blink::features::kServiceWorkerAggressiveCodeCache, - {{blink::kServiceWorkerEagerCodeCacheStrategy, "dontgenerate"}}); - ServiceWorkerCodeCacheStrategyTestBase::SetUp(); - } -}; - -IN_PROC_BROWSER_TEST_F(ServiceWorkerCodeCacheStrategyDontGenerateTest, - DontGenerate) { - NavigateToTestPage(); - InitiateEventsToCacheScript(); - EXPECT_FALSE(HasSideData(kCachedInInstallEventUrl)); - EXPECT_FALSE(HasSideData(kCachedInInstallEventWithMimeTypeParamUrl)); - EXPECT_FALSE(HasSideData(kCachedInFetchEventUrl)); - EXPECT_FALSE(HasSideData(kCachedInMessageEventUrl)); -} - -class ServiceWorkerCodeCacheStrategyInstallEventTest - : public ServiceWorkerCodeCacheStrategyTestBase { - public: - void SetUp() override { - feature_list_.InitAndEnableFeatureWithParameters( - blink::features::kServiceWorkerAggressiveCodeCache, - {{blink::kServiceWorkerEagerCodeCacheStrategy, "installevent"}}); - ServiceWorkerCodeCacheStrategyTestBase::SetUp(); - } -}; - -IN_PROC_BROWSER_TEST_F(ServiceWorkerCodeCacheStrategyInstallEventTest, - GenerateInInstallEvent) { - NavigateToTestPage(); - InitiateEventsToCacheScript(); - EXPECT_TRUE(HasSideData(kCachedInInstallEventUrl)); - EXPECT_TRUE(HasSideData(kCachedInInstallEventWithMimeTypeParamUrl)); - EXPECT_FALSE(HasSideData(kCachedInFetchEventUrl)); - EXPECT_FALSE(HasSideData(kCachedInMessageEventUrl)); -} - -class ServiceWorkerCodeCacheStrategyIdleTaskTest - : public ServiceWorkerCodeCacheStrategyTestBase { - public: - void SetUp() override { - feature_list_.InitAndEnableFeatureWithParameters( - blink::features::kServiceWorkerAggressiveCodeCache, - {{blink::kServiceWorkerEagerCodeCacheStrategy, "idletask"}}); - ServiceWorkerCodeCacheStrategyTestBase::SetUp(); - } -}; - -IN_PROC_BROWSER_TEST_F(ServiceWorkerCodeCacheStrategyIdleTaskTest, - GenerateInIdleTask) { - NavigateToTestPage(); - InitiateEventsToCacheScript(); - EXPECT_TRUE(HasSideData(kCachedInInstallEventUrl)); - EXPECT_TRUE(HasSideData(kCachedInInstallEventWithMimeTypeParamUrl)); - // These should not time out. - WaitForSideData(kCachedInFetchEventUrl); - WaitForSideData(kCachedInMessageEventUrl); -} - -// Test that generating and storing code cache in idle tasks doesn't corrupt -// cache entry when Cache#put() is called twice asynchronously. -IN_PROC_BROWSER_TEST_F(ServiceWorkerCodeCacheStrategyIdleTaskTest, - CacheScriptTwice) { - const char kCachedTwiceUrl[] = - "/service_worker/code_cache_strategy_test_script.js?cached_twice"; - - NavigateToTestPage(); - - // Ask the service worker to call Cache#put() twice asynchronously. - // The first response is a dummy script that contains no function. - // The second response is an actual script that contains |test_function()|. - EXPECT_EQ("DONE", EvalJs(shell(), "post_message('cache_script_twice');")); - - WaitForSideData(kCachedTwiceUrl); - - // Ask the page to load the test script and execute |test_function()|, which - // will return "SUCCESS". - EXPECT_EQ("SUCCESS", EvalJs(shell(), "execute_cached_twice_script();")); -} - // ServiceWorkerDisableWebSecurityTests check the behavior when the web security // is disabled. If '--disable-web-security' flag is set, we don't check the // origin equality in Blink. So the Service Worker related APIs should succeed
diff --git a/content/browser/service_worker/service_worker_provider_host.cc b/content/browser/service_worker/service_worker_provider_host.cc index 36ec9013..c0fc866 100644 --- a/content/browser/service_worker/service_worker_provider_host.cc +++ b/content/browser/service_worker/service_worker_provider_host.cc
@@ -31,6 +31,7 @@ #include "content/browser/web_contents/frame_tree_node_id_registry.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/service_worker/service_worker_utils.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" @@ -41,6 +42,7 @@ #include "content/public/common/child_process_host.h" #include "content/public/common/content_client.h" #include "content/public/common/origin_util.h" +#include "media/mojo/services/video_decode_perf_history.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/message.h" #include "net/base/url_util.h" @@ -87,6 +89,18 @@ origin); } +void BindVideoDecodePerfHistoryImpl( + int process_id, + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + auto* process = RenderProcessHost::FromID(process_id); + if (!process) + return; + + process->GetBrowserContext()->GetVideoDecodePerfHistory()->BindReceiver( + std::move(receiver)); +} + void CreateLockManagerImpl( const url::Origin& origin, int process_id, @@ -1424,6 +1438,16 @@ render_process_id_, std::move(receiver))); } +void ServiceWorkerProviderHost::BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) { + DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId()); + DCHECK(IsProviderForServiceWorker()); + RunOrPostTaskOnThread( + FROM_HERE, BrowserThread::UI, + base::BindOnce(&BindVideoDecodePerfHistoryImpl, render_process_id_, + std::move(receiver))); +} + void ServiceWorkerProviderHost::CreatePermissionService( mojo::PendingReceiver<blink::mojom::PermissionService> receiver) { DCHECK_CURRENTLY_ON(ServiceWorkerContext::GetCoreThreadId());
diff --git a/content/browser/service_worker/service_worker_provider_host.h b/content/browser/service_worker/service_worker_provider_host.h index f896495..eb7545ec 100644 --- a/content/browser/service_worker/service_worker_provider_host.h +++ b/content/browser/service_worker/service_worker_provider_host.h
@@ -25,6 +25,7 @@ #include "content/browser/service_worker/service_worker_registration.h" #include "content/common/content_export.h" #include "content/public/common/resource_type.h" +#include "media/mojo/mojom/video_decode_perf_history.mojom.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/binding.h" @@ -424,6 +425,11 @@ // For service worker execution contexts. Forwards |receiver| to the process // host on the UI thread. + void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver); + + // For service worker execution contexts. Forwards |receiver| to the process + // host on the UI thread. void CreateLockManager( mojo::PendingReceiver<blink::mojom::LockManager> receiver);
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 904729470..90e38c4 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -46,11 +46,6 @@ #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" #include "third_party/blink/public/common/service_worker/service_worker_type_converters.h" #include "third_party/blink/public/common/service_worker/service_worker_utils.h" -#include "third_party/blink/public/mojom/service_worker/embedded_worker.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h" -#include "third_party/blink/public/web/web_console_message.h" namespace content { namespace {
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index a6fda4b..b2633f3 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -7979,7 +7979,7 @@ test_callback) : render_frame_host_(render_frame_host), test_callback_(std::move(test_callback)) { - render_frame_host_->frame_host_binding_for_testing().SwapImplForTesting( + render_frame_host_->frame_host_receiver_for_testing().SwapImplForTesting( this); }
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index f135066..af4ce961 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -5682,6 +5682,8 @@ scoped_refptr<ShowWidgetMessageFilter> filter = new ShowWidgetMessageFilter(); c_node->current_frame_host()->GetProcess()->AddFilter(filter.get()); + WaitForHitTestData(c_node->current_frame_host()); + // Target left-click event to child frame. blink::WebMouseEvent click_event( blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers,
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index ba76526..a3fac4b 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -1411,8 +1411,14 @@ GenURL("c.com", "/title1.html"))); } +// TODO(http://crbug.com/997808): Flaky on Linux ASAN. +#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER) +#define MAYBE_SplitCacheDedicatedWorkers DISABLED_SplitCacheDedicatedWorkers +#else +#define MAYBE_SplitCacheDedicatedWorkers SplitCacheDedicatedWorkers +#endif IN_PROC_BROWSER_TEST_F(WebContentsSplitCacheWithFrameOriginBrowserTest, - SplitCacheDedicatedWorkers) { + MAYBE_SplitCacheDedicatedWorkers) { // Load 3p.com/script from a.com's worker. The first time it's loaded from the // network and the second it's cached. EXPECT_FALSE(TestResourceLoadFromDedicatedWorker( @@ -1510,12 +1516,6 @@ GenURL("d.com", "/title1.html"), true); } -// TODO(http://crbug.com/997808): Flaky on Linux ASAN. -#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER) -#define MAYBE_SplitCacheDedicatedWorkers DISABLED_SplitCacheDedicatedWorkers -#else -#define MAYBE_SplitCacheDedicatedWorkers SplitCacheDedicatedWorkers -#endif IN_PROC_BROWSER_TEST_P(WebContentsSplitCacheBrowserTestEnabled, MAYBE_SplitCacheDedicatedWorkers) { // Load 3p.com/script from a.com's worker. The first time it's loaded from the
diff --git a/content/browser/worker_host/dedicated_worker_host.cc b/content/browser/worker_host/dedicated_worker_host.cc index 232de7e..b41d9e6b 100644 --- a/content/browser/worker_host/dedicated_worker_host.cc +++ b/content/browser/worker_host/dedicated_worker_host.cc
@@ -405,6 +405,15 @@ worker_process_host->BindFileSystemManager(GetOrigin(), std::move(receiver)); } +void DedicatedWorkerHost::BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + RenderProcessHost* worker_process_host = GetProcessHost(); + if (!worker_process_host) + return; + worker_process_host->BindVideoDecodePerfHistory(std::move(receiver)); +} + void DedicatedWorkerHost::CreateIdleManager( mojo::PendingReceiver<blink::mojom::IdleManager> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI);
diff --git a/content/browser/worker_host/dedicated_worker_host.h b/content/browser/worker_host/dedicated_worker_host.h index 58c1d326..a1daa5b 100644 --- a/content/browser/worker_host/dedicated_worker_host.h +++ b/content/browser/worker_host/dedicated_worker_host.h
@@ -7,6 +7,7 @@ #include "content/browser/browser_interface_broker_impl.h" #include "content/public/browser/render_process_host.h" +#include "media/mojo/mojom/video_decode_perf_history.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" @@ -68,6 +69,8 @@ void BindFileSystemManager( mojo::PendingReceiver<blink::mojom::FileSystemManager> receiver); + void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver); void CreateIdleManager( mojo::PendingReceiver<blink::mojom::IdleManager> receiver); void CreatePaymentManager(
diff --git a/content/browser/worker_host/shared_worker_host.cc b/content/browser/worker_host/shared_worker_host.cc index 7c6e733..e9622b45 100644 --- a/content/browser/worker_host/shared_worker_host.cc +++ b/content/browser/worker_host/shared_worker_host.cc
@@ -333,6 +333,15 @@ GetRenderFrameIDsForWorker())); } +void SharedWorkerHost::BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + RenderProcessHost* worker_process_host = GetProcessHost(); + if (!worker_process_host) + return; + worker_process_host->BindVideoDecodePerfHistory(std::move(receiver)); +} + void SharedWorkerHost::CreateAppCacheBackend( mojo::PendingReceiver<blink::mojom::AppCacheBackend> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI);
diff --git a/content/browser/worker_host/shared_worker_host.h b/content/browser/worker_host/shared_worker_host.h index 6ea3666..62a3907 100644 --- a/content/browser/worker_host/shared_worker_host.h +++ b/content/browser/worker_host/shared_worker_host.h
@@ -20,6 +20,7 @@ #include "content/public/browser/global_routing_id.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_worker_instance.h" +#include "media/mojo/mojom/video_decode_perf_history.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" @@ -108,6 +109,8 @@ void AllowCacheStorage(const GURL& url, base::OnceCallback<void(bool)> callback); + void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver); void CreateAppCacheBackend( mojo::PendingReceiver<blink::mojom::AppCacheBackend> receiver); void CreatePaymentManager(
diff --git a/content/common/frame.mojom b/content/common/frame.mojom index 9ab40d6..f0d9cafc 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom
@@ -271,7 +271,7 @@ // Implemented by a service that provides implementations of the Frame // interface. (e.g. renderer processes). interface FrameFactory { - CreateFrame(int32 frame_routing_id, Frame& frame); + CreateFrame(int32 frame_routing_id, pending_receiver<Frame> frame); }; struct CreateNewWindowParams { @@ -385,7 +385,7 @@ mojo_base.mojom.UnguessableToken devtools_frame_token); // Creates and returns a KeepAliveHandle. - IssueKeepAliveHandle(KeepAliveHandle& keep_alive_handle); + IssueKeepAliveHandle(pending_receiver<KeepAliveHandle> keep_alive_handle); // Sent by the renderer when a navigation commits in the frame.
diff --git a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java index 0b82a217..c353bfb 100644 --- a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java +++ b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessServiceDelegate.java
@@ -99,9 +99,10 @@ } @Override - public boolean loadNativeLibrary(Context hostContext) { + public void loadNativeLibrary(Context hostContext) { if (LibraryLoader.getInstance().isLoadedByZygote()) { - return initializeLibrary(); + initializeLibrary(); + return; } JNIUtils.enableSelectiveJniRegistration(); @@ -118,51 +119,31 @@ linker.disableSharedRelros(); } } - boolean isLoaded = false; try { LibraryLoader.getInstance().loadNowOverrideApplicationContext(hostContext); - isLoaded = true; } catch (ProcessInitException e) { if (requestedSharedRelro) { Log.w(TAG, "Failed to load native library with shared RELRO, " + "retrying without"); - } else { - Log.e(TAG, "Failed to load native library", e); - } - } - if (!isLoaded && requestedSharedRelro) { - linker.disableSharedRelros(); - try { + linker.disableSharedRelros(); LibraryLoader.getInstance().loadNowOverrideApplicationContext(hostContext); - isLoaded = true; - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to load native library on retry", e); + } else { + throw e; } } - if (!isLoaded) { - return false; - } LibraryLoader.getInstance().registerRendererProcessHistogram(); - - return initializeLibrary(); + initializeLibrary(); } - private boolean initializeLibrary() { - try { - LibraryLoader.getInstance().initialize(mLibraryProcessType); - } catch (ProcessInitException e) { - Log.w(TAG, "startup failed: %s", e); - return false; - } + private void initializeLibrary() { + LibraryLoader.getInstance().initialize(mLibraryProcessType); // Now that the library is loaded, get the FD map, // TODO(jcivelli): can this be done in onBeforeMain? We would have to mode onBeforeMain // so it's called before FDs are registered. ContentChildProcessServiceDelegateJni.get().retrieveFileDescriptorsIdsToKeys( ContentChildProcessServiceDelegate.this); - - return true; } @Override
diff --git a/content/public/android/java/src/org/chromium/content/browser/BrowserStartupControllerImpl.java b/content/public/android/java/src/org/chromium/content/browser/BrowserStartupControllerImpl.java index a3c4030a..66f9ae4 100644 --- a/content/public/android/java/src/org/chromium/content/browser/BrowserStartupControllerImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/BrowserStartupControllerImpl.java
@@ -190,7 +190,7 @@ @Override public void startBrowserProcessesAsync(boolean startGpuProcess, boolean startServiceManagerOnly, - final StartupCallback callback) throws ProcessInitException { + final StartupCallback callback) { assert ThreadUtils.runningOnUiThread() : "Tried to start the browser on the wrong thread."; ServicificationStartupUma.getInstance().record(ServicificationStartupUma.getStartupMode( mFullBrowserStartupDone, mServiceManagerStarted, startServiceManagerOnly)); @@ -243,7 +243,7 @@ } @Override - public void startBrowserProcessesSync(boolean singleProcess) throws ProcessInitException { + public void startBrowserProcessesSync(boolean singleProcess) { ServicificationStartupUma.getInstance().record( ServicificationStartupUma.getStartupMode(mFullBrowserStartupDone, mServiceManagerStarted, false /* startServiceManagerOnly */)); @@ -428,8 +428,8 @@ } @VisibleForTesting - void prepareToStartBrowserProcess(final boolean singleProcess, - final Runnable completionCallback) throws ProcessInitException { + void prepareToStartBrowserProcess( + final boolean singleProcess, final Runnable completionCallback) { Log.i(TAG, "Initializing chromium process, singleProcess=%b", singleProcess); // This strictmode exception is to cover the case where the browser process is being started
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/BrowserStartupController.java b/content/public/android/java/src/org/chromium/content_public/browser/BrowserStartupController.java index ec2f4d4..7f5b61e6 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/BrowserStartupController.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/BrowserStartupController.java
@@ -4,7 +4,6 @@ package org.chromium.content_public.browser; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content.browser.BrowserStartupControllerImpl; /** @@ -22,7 +21,7 @@ /** * This provides the interface to the callbacks for successful or failed startup */ - public interface StartupCallback { + interface StartupCallback { void onSuccess(); void onFailure(); } @@ -35,7 +34,7 @@ * LibraryProcessType.PROCESS_WEBVIEW. * @return BrowserStartupController instance. */ - public static BrowserStartupController get(int libraryProcessType) { + static BrowserStartupController get(int libraryProcessType) { return BrowserStartupControllerImpl.get(libraryProcessType); } @@ -51,7 +50,7 @@ * @param callback the callback to be called when browser startup is complete. */ void startBrowserProcessesAsync(boolean startGpuProcess, boolean startServiceManagerOnly, - final StartupCallback callback) throws ProcessInitException; + final StartupCallback callback); /** * Start the browser process synchronously. If the browser is already being started @@ -62,9 +61,8 @@ * * @param singleProcess true iff the browser should run single-process, ie. keep renderers in * the browser process - * @throws ProcessInitException */ - void startBrowserProcessesSync(boolean singleProcess) throws ProcessInitException; + void startBrowserProcessesSync(boolean singleProcess); /** * @return Whether the browser process has been started in "Full Browser" mode successfully. See
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/BrowserStartupControllerTest.java b/content/public/android/javatests/src/org/chromium/content/browser/BrowserStartupControllerTest.java index 076f2ef..143f54c 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/BrowserStartupControllerTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/BrowserStartupControllerTest.java
@@ -38,8 +38,7 @@ private boolean mServiceManagerStarted; @Override - void prepareToStartBrowserProcess(boolean singleProcess, Runnable completionCallback) - throws ProcessInitException { + void prepareToStartBrowserProcess(boolean singleProcess, Runnable completionCallback) { if (!mLibraryLoadSucceeds) { throw new ProcessInitException( LoaderErrors.LOADER_ERROR_NATIVE_LIBRARY_LOAD_FAILED);
diff --git a/content/public/app/content_browser_manifest.cc b/content/public/app/content_browser_manifest.cc index ad3fca6..a5e263d 100644 --- a/content/public/app/content_browser_manifest.cc +++ b/content/public/app/content_browser_manifest.cc
@@ -171,7 +171,6 @@ "blink.mojom.NotificationService", "blink.mojom.QuotaDispatcherHost", "blink.mojom.WebSocketConnector", - "media.mojom.VideoDecodePerfHistory", "shape_detection.mojom.BarcodeDetectionProvider", "shape_detection.mojom.FaceDetectionProvider", "shape_detection.mojom.TextDetection"}) @@ -187,7 +186,6 @@ "blink.mojom.SerialService", "blink.mojom.WebUsbService", "blink.mojom.WebSocketConnector", - "media.mojom.VideoDecodePerfHistory", "shape_detection.mojom.BarcodeDetectionProvider", "shape_detection.mojom.FaceDetectionProvider", "shape_detection.mojom.TextDetection"}) @@ -199,7 +197,6 @@ "blink.mojom.NativeFileSystemManager", "blink.mojom.NotificationService", "blink.mojom.QuotaDispatcherHost", - "media.mojom.VideoDecodePerfHistory", "network.mojom.RestrictedCookieManager", "blink.mojom.WebSocketConnector", "shape_detection.mojom.BarcodeDetectionProvider", @@ -243,11 +240,9 @@ "media.mojom.MediaMetricsProvider", "media.mojom.RemoterFactory", "media.mojom.Renderer", - "media.mojom.VideoDecodePerfHistory", "mojom.ProcessInternalsHandler", "network.mojom.RestrictedCookieManager", "blink.mojom.WebSocketConnector", - "payments.mojom.PaymentRequest", "resource_coordinator.mojom.DocumentCoordinationUnit", "shape_detection.mojom.BarcodeDetectionProvider", "shape_detection.mojom.FaceDetectionProvider",
diff --git a/content/public/browser/render_process_host.h b/content/public/browser/render_process_host.h index ae365a1e..f69fa8c 100644 --- a/content/public/browser/render_process_host.h +++ b/content/public/browser/render_process_host.h
@@ -24,6 +24,7 @@ #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_sender.h" #include "media/media_buildflags.h" +#include "media/mojo/mojom/video_decode_perf_history.mojom-forward.h" #include "mojo/public/cpp/bindings/generic_pending_receiver.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" @@ -499,6 +500,12 @@ mojo::PendingReceiver<blink::mojom::IDBFactory> receiver, const url::Origin& origin) = 0; + // Binds |receiver| to the VideoDecodePerfHistory instance. This is for + // internal use only, and is only exposed here to support + // MockRenderProcessHost usage in tests. + virtual void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) = 0; + // Binds |receiver| to an instance of LockManager. This is for internal use // only, and is only exposed here to support MockRenderProcessHost usage in // tests.
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 238fa57..1efa61ee1 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -23,6 +23,11 @@ "AllowContentInitiatedDataUrlNavigations", base::FEATURE_DISABLED_BY_DEFAULT}; +// Allows popups during page unloading. +// TODO(https://crbug.com/937569): Remove this in Chrome 82. +const base::Feature kAllowPopupsDuringPageUnload{ + "AllowPopupsDuringPageUnload", base::FEATURE_DISABLED_BY_DEFAULT}; + // Accepts Origin-Signed HTTP Exchanges to be signed with certificates // that do not have CanSignHttpExchangesDraft extension. // TODO(https://crbug.com/862003): Remove when certificates with
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index b8aaa14..5e321d5 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -19,6 +19,7 @@ CONTENT_EXPORT extern const base::Feature kAllowActivationDelegationAttr; CONTENT_EXPORT extern const base::Feature kAllowContentInitiatedDataUrlNavigations; +CONTENT_EXPORT extern const base::Feature kAllowPopupsDuringPageUnload; CONTENT_EXPORT extern const base::Feature kAllowSignedHTTPExchangeCertsWithoutExtension; CONTENT_EXPORT extern const base::Feature kAudioServiceAudioStreams;
diff --git a/content/public/common/referrer.cc b/content/public/common/referrer.cc index d8ed5796..40f8cfa 100644 --- a/content/public/common/referrer.cc +++ b/content/public/common/referrer.cc
@@ -10,6 +10,7 @@ #include "content/public/common/content_features.h" #include "net/base/features.h" #include "services/network/loader_util.h" +#include "services/network/public/cpp/features.h" #include "third_party/blink/public/mojom/referrer.mojom.h" namespace content { @@ -97,9 +98,13 @@ break; } - if (base::FeatureList::IsEnabled(net::features::kCapRefererHeaderLength) && - base::saturated_cast<int>(sanitized_referrer->url.spec().length()) > - net::features::kMaxRefererHeaderLength.Get()) { + if ((base::FeatureList::IsEnabled(net::features::kCapRefererHeaderLength) && + base::saturated_cast<int>(sanitized_referrer->url.spec().length()) > + net::features::kMaxRefererHeaderLength.Get()) || + (base::FeatureList::IsEnabled( + network::features::kCapReferrerToOriginOnCrossOrigin) && + !url::Origin::Create(sanitized_referrer->url) + .IsSameOriginWith(url::Origin::Create(request)))) { sanitized_referrer->url = sanitized_referrer->url.GetOrigin(); }
diff --git a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/NativeLibraryTestRule.java b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/NativeLibraryTestRule.java index 2fd94e7..b6ad13e 100644 --- a/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/NativeLibraryTestRule.java +++ b/content/public/test/android/javatests/src/org/chromium/content_public/browser/test/NativeLibraryTestRule.java
@@ -12,7 +12,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.ui.resources.ResourceExtractor; @@ -49,24 +48,16 @@ private void nativeInitialization(boolean initBrowserProcess) { if (initBrowserProcess) { - try { - // Extract compressed resource paks. - ResourceExtractor resourceExtractor = ResourceExtractor.get(); - resourceExtractor.setResultTraits(UiThreadTaskTraits.BOOTSTRAP); - resourceExtractor.startExtractingResources("en"); - resourceExtractor.waitForCompletion(); + // Extract compressed resource paks. + ResourceExtractor resourceExtractor = ResourceExtractor.get(); + resourceExtractor.setResultTraits(UiThreadTaskTraits.BOOTSTRAP); + resourceExtractor.startExtractingResources("en"); + resourceExtractor.waitForCompletion(); - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .startBrowserProcessesSync(false); - } catch (ProcessInitException e) { - throw new Error(e); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .startBrowserProcessesSync(false); } else { - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - } catch (ProcessInitException e) { - throw new Error(e); - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); } }
diff --git a/content/public/test/mock_render_process_host.h b/content/public/test/mock_render_process_host.h index 1fc01f7..93e9986 100644 --- a/content/public/test/mock_render_process_host.h +++ b/content/public/test/mock_render_process_host.h
@@ -178,6 +178,9 @@ override {} void BindIndexedDB(mojo::PendingReceiver<blink::mojom::IDBFactory> receiver, const url::Origin& origin) override; + void BindVideoDecodePerfHistory( + mojo::PendingReceiver<media::mojom::VideoDecodePerfHistory> receiver) + override {} void CreateLockManager( int render_frame_id, const url::Origin& origin,
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index 651c7c3e..2c6cf18 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -29,6 +29,7 @@ #include "base/time/time.h" #include "build/build_config.h" #include "content/child/child_thread_impl.h" +#include "content/common/frame.mojom.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_features.h" #include "content/public/common/navigation_policy.h" @@ -40,6 +41,7 @@ #include "content/renderer/loader/resource_dispatcher.h" #include "content/renderer/loader/sync_load_response.h" #include "content/renderer/loader/web_url_request_util.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/data_url.h" #include "net/base/filename_util.h" #include "net/base/host_port_pair.h" @@ -373,7 +375,7 @@ ResourceDispatcher* resource_dispatcher, std::unique_ptr<WebResourceLoadingTaskRunnerHandle> task_runner_handle, scoped_refptr<network::SharedURLLoaderFactory> factory, - mojom::KeepAliveHandlePtr keep_alive_handle); + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle); ResourceDispatcher* resource_dispatcher() { return resource_dispatcher_; } int request_id() const { return request_id_; } @@ -438,7 +440,7 @@ ResourceDispatcher* resource_dispatcher_; std::unique_ptr<WebResourceLoadingTaskRunnerHandle> task_runner_handle_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - mojom::KeepAliveHandlePtr keep_alive_handle_; + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle_; enum DeferState { NOT_DEFERRING, SHOULD_DEFER }; DeferState defers_loading_; int request_id_; @@ -557,14 +559,14 @@ ResourceDispatcher* resource_dispatcher, std::unique_ptr<WebResourceLoadingTaskRunnerHandle> task_runner_handle, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - mojom::KeepAliveHandlePtr keep_alive_handle_ptr) + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle) : loader_(loader), report_raw_headers_(false), client_(nullptr), resource_dispatcher_(resource_dispatcher), task_runner_handle_(std::move(task_runner_handle)), task_runner_(task_runner_handle_->GetTaskRunner()), - keep_alive_handle_(std::move(keep_alive_handle_ptr)), + keep_alive_handle_(std::move(keep_alive_handle)), defers_loading_(NOT_DEFERRING), request_id_(-1), url_loader_factory_(std::move(url_loader_factory)) { @@ -1012,13 +1014,13 @@ : WebURLLoaderImpl(resource_dispatcher, std::move(task_runner_handle), std::move(url_loader_factory), - nullptr) {} + mojo::NullRemote()) {} WebURLLoaderImpl::WebURLLoaderImpl( ResourceDispatcher* resource_dispatcher, std::unique_ptr<WebResourceLoadingTaskRunnerHandle> task_runner_handle, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - mojom::KeepAliveHandlePtr keep_alive_handle) + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle) : context_(new Context(this, resource_dispatcher, std::move(task_runner_handle),
diff --git a/content/renderer/loader/web_url_loader_impl.h b/content/renderer/loader/web_url_loader_impl.h index c5b9715..6c28739 100644 --- a/content/renderer/loader/web_url_loader_impl.h +++ b/content/renderer/loader/web_url_loader_impl.h
@@ -11,6 +11,7 @@ #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "content/common/frame.mojom.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/system/data_pipe.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" @@ -60,7 +61,7 @@ std::unique_ptr<blink::scheduler::WebResourceLoadingTaskRunnerHandle> task_runner_handle, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - mojom::KeepAliveHandlePtr keep_alive_handle); + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle); ~WebURLLoaderImpl() override; static void PopulateURLResponse(const blink::WebURL& url,
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index a81eb70..2a675b5 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -53,6 +53,7 @@ #include "content/common/content_security_policy/content_security_policy.h" #include "content/common/content_security_policy_header.h" #include "content/common/edit_command.h" +#include "content/common/frame.mojom.h" #include "content/common/frame_messages.h" #include "content/common/frame_owner_properties.h" #include "content/common/frame_replication_state.h" @@ -146,7 +147,11 @@ #include "content/renderer/web_ui_extension_data.h" #include "content/renderer/worker/dedicated_worker_host_factory_client.h" #include "crypto/sha2.h" +#include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "mojo/public/cpp/bindings/pending_associated_remote.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/base/data_url.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" @@ -1146,10 +1151,10 @@ // This should not be called if the frame is detached. DCHECK(frame_); - mojom::KeepAliveHandlePtr keep_alive_handle; + mojo::PendingRemote<mojom::KeepAliveHandle> keep_alive_handle; if (request.GetKeepalive()) { frame_->GetFrameHost()->IssueKeepAliveHandle( - mojo::MakeRequest(&keep_alive_handle)); + keep_alive_handle.InitWithNewPipeAndPassReceiver()); } return std::make_unique<WebURLLoaderImpl>( RenderThreadImpl::current()->resource_dispatcher(), @@ -1869,8 +1874,6 @@ pepper_last_mouse_event_target_(nullptr), #endif autoplay_configuration_binding_(this), - frame_binding_(this), - frame_bindings_control_binding_(this), frame_navigation_control_receiver_(this), fullscreen_binding_(this), mhtml_file_writer_binding_(this), @@ -2354,16 +2357,16 @@ void RenderFrameImpl::BindFrame( const service_manager::BindSourceInfo& browser_info, - mojom::FrameRequest request) { + mojo::PendingReceiver<mojom::Frame> receiver) { browser_info_ = browser_info; - frame_binding_.Bind(std::move(request), - GetTaskRunner(blink::TaskType::kInternalIPC)); + frame_receiver_.Bind(std::move(receiver), + GetTaskRunner(blink::TaskType::kInternalIPC)); } void RenderFrameImpl::BindFrameBindingsControl( - mojom::FrameBindingsControlAssociatedRequest request) { - frame_bindings_control_binding_.Bind( - std::move(request), GetTaskRunner(blink::TaskType::kInternalIPC)); + mojo::PendingAssociatedReceiver<mojom::FrameBindingsControl> receiver) { + frame_bindings_control_receiver_.Bind( + std::move(receiver), GetTaskRunner(blink::TaskType::kInternalIPC)); } void RenderFrameImpl::BindFrameNavigationControl(
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 1708222..5deef72 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -67,6 +67,7 @@ #include "mojo/public/cpp/bindings/pending_associated_receiver.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/remote.h" #include "mojo/public/cpp/system/data_pipe.h" #include "ppapi/buildflags/buildflags.h" @@ -889,13 +890,13 @@ // Binds to the FrameHost in the browser. void BindFrame(const service_manager::BindSourceInfo& browser_info, - mojom::FrameRequest request); + mojo::PendingReceiver<mojom::Frame> receiver); // Virtual so that a TestRenderFrame can mock out the interface. virtual mojom::FrameHost* GetFrameHost(); void BindFrameBindingsControl( - mojom::FrameBindingsControlAssociatedRequest request); + mojo::PendingAssociatedReceiver<mojom::FrameBindingsControl> receiver); void BindFrameNavigationControl( mojo::PendingAssociatedReceiver<mojom::FrameNavigationControl> receiver); // Only used when PerNavigationMojoInterface is enabled. @@ -1665,9 +1666,9 @@ mojo::AssociatedBinding<blink::mojom::AutoplayConfigurationClient> autoplay_configuration_binding_; - mojo::Binding<mojom::Frame> frame_binding_; - mojo::AssociatedBinding<mojom::FrameBindingsControl> - frame_bindings_control_binding_; + mojo::Receiver<mojom::Frame> frame_receiver_{this}; + mojo::AssociatedReceiver<mojom::FrameBindingsControl> + frame_bindings_control_receiver_{this}; mojo::AssociatedReceiver<mojom::FrameNavigationControl> frame_navigation_control_receiver_; mojo::AssociatedBinding<mojom::FullscreenVideoElementHandler>
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index ac9ff1dc..5c652ff 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -63,6 +63,7 @@ #include "content/child/thread_safe_sender.h" #include "content/common/buildflags.h" #include "content/common/content_constants_internal.h" +#include "content/common/frame.mojom.h" #include "content/common/frame_messages.h" #include "content/common/frame_owner_properties.h" #include "content/common/view_messages.h" @@ -122,8 +123,9 @@ #include "media/media_buildflags.h" #include "media/video/gpu_video_accelerator_factories.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/self_owned_receiver.h" -#include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/public/cpp/system/message_pipe.h" #include "net/base/net_errors.h" #include "net/base/port_util.h" @@ -312,8 +314,9 @@ private: // mojom::FrameFactory: - void CreateFrame(int32_t frame_routing_id, - mojom::FrameRequest frame_request) override { + void CreateFrame( + int32_t frame_routing_id, + mojo::PendingReceiver<mojom::Frame> frame_receiver) override { // TODO(morrita): This is for investigating http://crbug.com/415059 and // should be removed once it is fixed. CHECK_LT(routing_id_highmark_, frame_routing_id); @@ -326,11 +329,11 @@ // we want. if (!frame) { RenderThreadImpl::current()->RegisterPendingFrameCreate( - source_info_, frame_routing_id, std::move(frame_request)); + source_info_, frame_routing_id, std::move(frame_receiver)); return; } - frame->BindFrame(source_info_, std::move(frame_request)); + frame->BindFrame(source_info_, std::move(frame_receiver)); } private: @@ -338,10 +341,10 @@ int32_t routing_id_highmark_; }; -void CreateFrameFactory(mojom::FrameFactoryRequest request, +void CreateFrameFactory(mojo::PendingReceiver<mojom::FrameFactory> receiver, const service_manager::BindSourceInfo& source_info) { - mojo::MakeStrongBinding(std::make_unique<FrameFactoryImpl>(source_info), - std::move(request)); + mojo::MakeSelfOwnedReceiver(std::make_unique<FrameFactoryImpl>(source_info), + std::move(receiver)); } scoped_refptr<viz::ContextProviderCommandBuffer> CreateOffscreenContext( @@ -1076,7 +1079,7 @@ frame->GetTaskRunner(blink::TaskType::kInternalNavigationAssociated)); scoped_refptr<PendingFrameCreate> create(it->second); - frame->BindFrame(it->second->browser_info(), it->second->TakeFrameRequest()); + frame->BindFrame(it->second->browser_info(), it->second->TakeFrameReceiver()); pending_frame_creates_.erase(it); } @@ -1088,11 +1091,12 @@ void RenderThreadImpl::RegisterPendingFrameCreate( const service_manager::BindSourceInfo& browser_info, int routing_id, - mojom::FrameRequest frame_request) { + mojo::PendingReceiver<mojom::Frame> frame_receiver) { std::pair<PendingFrameCreateMap::iterator, bool> result = pending_frame_creates_.insert(std::make_pair( - routing_id, base::MakeRefCounted<PendingFrameCreate>( - browser_info, routing_id, std::move(frame_request)))); + routing_id, + base::MakeRefCounted<PendingFrameCreate>(browser_info, routing_id, + std::move(frame_receiver)))); CHECK(result.second) << "Inserting a duplicate item."; } @@ -2367,10 +2371,10 @@ RenderThreadImpl::PendingFrameCreate::PendingFrameCreate( const service_manager::BindSourceInfo& browser_info, int routing_id, - mojom::FrameRequest frame_request) + mojo::PendingReceiver<mojom::Frame> frame_receiver) : browser_info_(browser_info), routing_id_(routing_id), - frame_request_(std::move(frame_request)) {} + frame_receiver_(std::move(frame_receiver)) {} RenderThreadImpl::PendingFrameCreate::~PendingFrameCreate() { }
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 7cd7d03..5ed2fca 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -425,7 +425,7 @@ void RegisterPendingFrameCreate( const service_manager::BindSourceInfo& source_info, int routing_id, - mojom::FrameRequest frame); + mojo::PendingReceiver<mojom::Frame> frame); mojom::RendererHost* GetRendererHost(); @@ -657,12 +657,14 @@ public: PendingFrameCreate(const service_manager::BindSourceInfo& source_info, int routing_id, - mojom::FrameRequest frame_request); + mojo::PendingReceiver<mojom::Frame> frame_receiver); const service_manager::BindSourceInfo& browser_info() const { return browser_info_; } - mojom::FrameRequest TakeFrameRequest() { return std::move(frame_request_); } + mojo::PendingReceiver<mojom::Frame> TakeFrameReceiver() { + return std::move(frame_receiver_); + } private: friend class base::RefCounted<PendingFrameCreate>; @@ -674,7 +676,7 @@ service_manager::BindSourceInfo browser_info_; int routing_id_; - mojom::FrameRequest frame_request_; + mojo::PendingReceiver<mojom::Frame> frame_receiver_; }; using PendingFrameCreateMap =
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index f3fbb63..6052ce9 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -1784,7 +1784,8 @@ bool RenderViewImpl::AllowPopupsDuringPageUnload() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); - return command_line.HasSwitch(switches::kAllowPopupsDuringPageUnload); + return command_line.HasSwitch(switches::kAllowPopupsDuringPageUnload) || + base::FeatureList::IsEnabled(features::kAllowPopupsDuringPageUnload); } bool RenderViewImpl::CanUpdateLayout() {
diff --git a/content/shell/android/browsertests/src/org/chromium/content_shell/browsertests/ContentShellBrowserTestActivity.java b/content/shell/android/browsertests/src/org/chromium/content_shell/browsertests/ContentShellBrowserTestActivity.java index 4641d47..5f881f9 100644 --- a/content/shell/android/browsertests/src/org/chromium/content_shell/browsertests/ContentShellBrowserTestActivity.java +++ b/content/shell/android/browsertests/src/org/chromium/content_shell/browsertests/ContentShellBrowserTestActivity.java
@@ -12,11 +12,9 @@ import org.chromium.base.ContentUriUtils; import org.chromium.base.ContextUtils; -import org.chromium.base.Log; import org.chromium.base.StrictModeContext; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.BrowserStartupController.StartupCallback; import org.chromium.content_shell.ShellManager; @@ -56,9 +54,6 @@ protected void initializeBrowserProcess() { try (StrictModeContext ignored = StrictModeContext.allowDiskReads()) { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - } catch (ProcessInitException e) { - Log.e(TAG, "Cannot load content_browsertests.", e); - System.exit(-1); } ContentUriUtils.setFileProviderUtil(new FileProviderHelper()); @@ -79,25 +74,20 @@ // to be called. runTests(); }); - try { - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .startBrowserProcessesAsync(false, false, new StartupCallback() { - @Override - public void onSuccess() { - // The C++ test harness is running thanks to runTests() above, but it - // waits for Java initialization to complete. This tells C++ that it may - // continue now to finish running the tests. - NativeBrowserTest.javaStartupTasksComplete(); - } - @Override - public void onFailure() { - throw new RuntimeException("Failed to startBrowserProcessesAsync()"); - } - }); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - System.exit(-1); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .startBrowserProcessesAsync(false, false, new StartupCallback() { + @Override + public void onSuccess() { + // The C++ test harness is running thanks to runTests() above, but it + // waits for Java initialization to complete. This tells C++ that it may + // continue now to finish running the tests. + NativeBrowserTest.javaStartupTasksComplete(); + } + @Override + public void onFailure() { + throw new RuntimeException("Failed to startBrowserProcessesAsync()"); + } + }); } protected abstract int getTestActivityViewId();
diff --git a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java index 046228a..826e7c5 100644 --- a/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java +++ b/content/shell/android/linker_test_apk/src/org/chromium/chromium_linker_test_apk/ChromiumLinkerTestActivity.java
@@ -15,7 +15,6 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.Linker; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.WebContents; import org.chromium.content_shell.Shell; @@ -41,11 +40,7 @@ // Load the library in the browser process, this will also run the test // runner in this process. - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - } catch (ProcessInitException e) { - Log.i(TAG, "Cannot load chromium_linker_test:" + e); - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); // Now, start a new renderer process by creating a new view. // This will run the test runner in the renderer process. @@ -53,30 +48,25 @@ LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.test_activity, null); - mShellManager = (ShellManager) view.findViewById(R.id.shell_container); + mShellManager = view.findViewById(R.id.shell_container); mWindowAndroid = new ActivityWindowAndroid(this, false); mShellManager.setWindow(mWindowAndroid); mShellManager.setStartupUrl("about:blank"); - try { - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .startBrowserProcessesAsync( - true, false, new BrowserStartupController.StartupCallback() { - @Override - public void onSuccess() { - finishInitialization(savedInstanceState); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .startBrowserProcessesAsync( + true, false, new BrowserStartupController.StartupCallback() { + @Override + public void onSuccess() { + finishInitialization(savedInstanceState); + } - @Override - public void onFailure() { - initializationFailed(); - } - }); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - finish(); - } + @Override + public void onFailure() { + initializationFailed(); + } + }); // TODO(digit): Ensure that after the content view is initialized, // the program finishes().
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java index 20da39a2..31127d1 100644 --- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java +++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java
@@ -17,7 +17,6 @@ import org.chromium.base.CommandLine; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.process_launcher.ChildProcessConnection; import org.chromium.base.process_launcher.FileDescriptorInfo; import org.chromium.content.browser.ChildProcessLauncherHelperImpl; @@ -58,12 +57,7 @@ @Override public void onCreate() { CommandLine.init(null); - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); - } catch (ProcessInitException ex) { - throw new RuntimeException(ex); - } - + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); mHandlerThread.start(); }
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ContentShellActivity.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ContentShellActivity.java index d3323f8..398285d 100644 --- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ContentShellActivity.java +++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ContentShellActivity.java
@@ -16,7 +16,6 @@ import org.chromium.base.MemoryPressureListener; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.DeviceUtils; import org.chromium.content_public.browser.WebContents; @@ -57,18 +56,10 @@ DeviceUtils.addDeviceSpecificUserAgentSwitch(); - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - } catch (ProcessInitException e) { - Log.e(TAG, "ContentView initialization failed.", e); - // Since the library failed to initialize nothing in the application - // can work, so kill the whole application not just the activity - System.exit(-1); - return; - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); setContentView(R.layout.content_shell_activity); - mShellManager = (ShellManager) findViewById(R.id.shell_container); + mShellManager = findViewById(R.id.shell_container); final boolean listenToActivityState = true; mWindowAndroid = new ActivityWindowAndroid(this, listenToActivityState); mWindowAndroid.restoreInstanceState(savedInstanceState); @@ -84,32 +75,22 @@ } if (CommandLine.getInstance().hasSwitch(RUN_WEB_TESTS_SWITCH)) { - try { - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .startBrowserProcessesSync(false); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to load native library.", e); - System.exit(-1); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .startBrowserProcessesSync(false); } else { - try { - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .startBrowserProcessesAsync( - true, false, new BrowserStartupController.StartupCallback() { - @Override - public void onSuccess() { - finishInitialization(savedInstanceState); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .startBrowserProcessesAsync( + true, false, new BrowserStartupController.StartupCallback() { + @Override + public void onSuccess() { + finishInitialization(savedInstanceState); + } - @Override - public void onFailure() { - initializationFailed(); - } - }); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - System.exit(-1); - } + @Override + public void onFailure() { + initializationFailed(); + } + }); } }
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java index 885d3b31..bcecabc 100644 --- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java +++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java
@@ -18,7 +18,6 @@ import org.chromium.base.Log; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.process_launcher.ChildProcessService; import org.chromium.base.process_launcher.ChildProcessServiceDelegate; @@ -79,21 +78,15 @@ } @Override - public boolean loadNativeLibrary(Context hostContext) { + public void loadNativeLibrary(Context hostContext) { // Store the command line before loading the library to avoid an assert in CommandLine. mCommandLine = CommandLine.getJavaSwitchesOrNull(); // Non-main processes are launched for testing. Mark them as such so that the JNI // in the seconary dex won't be registered. See https://crbug.com/810720. JNIUtils.enableSelectiveJniRegistration(); - boolean isLoaded = false; - try { - LibraryLoader.getInstance().loadNow(); - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); - isLoaded = true; - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to load native library.", e); - } + LibraryLoader.getInstance().loadNow(); + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_CHILD); // Loading the library happen on the main thread and onConnectionSetup is called from // the client. Wait for onConnectionSetup so mIChildProcessTest is set. @@ -109,12 +102,11 @@ if (mIChildProcessTest != null) { try { - mIChildProcessTest.onLoadNativeLibrary(isLoaded); + mIChildProcessTest.onLoadNativeLibrary(true); } catch (RemoteException re) { Log.e(TAG, "Failed to call IChildProcessTest.onLoadNativeLibrary.", re); } } - return true; } @Override @@ -145,7 +137,7 @@ Looper.prepare(); Looper.loop(); } - }; + } private ChildProcessService mService;
diff --git a/content/test/data/accessibility/css/font-size-expected-auralinux.txt b/content/test/data/accessibility/css/font-size-expected-auralinux.txt new file mode 100644 index 0000000..0b56463 --- /dev/null +++ b/content/test/data/accessibility/css/font-size-expected-auralinux.txt
@@ -0,0 +1,45 @@ +[document web] size=7.5pt size=8.5pt size=9pt size=10pt size=10.5pt size=11.5pt size=15pt size=30pt size=37.5pt size=75pt size=10pt size=11pt size=12pt size=13pt size=14pt size=15pt size=20pt size=40pt size=50pt size=100pt +++[paragraph] size=7.5pt +++++[text] name='10.2340920823px' size=7.5pt +++[paragraph] size=7.5pt +++++[text] name='10px' size=7.5pt +++[paragraph] size=8.5pt +++++[text] name='11px' size=8.5pt +++[paragraph] size=9pt +++++[text] name='12px' size=9pt +++[paragraph] size=10pt +++++[text] name='13px' size=10pt +++[paragraph] size=10.5pt +++++[text] name='14px' size=10.5pt +++[paragraph] size=11.5pt +++++[text] name='15px' size=11.5pt +++[paragraph] size=15pt +++++[text] name='20px' size=15pt +++[paragraph] size=30pt +++++[text] name='40px' size=30pt +++[paragraph] size=37.5pt +++++[text] name='50px' size=37.5pt +++[paragraph] size=75pt +++++[text] name='100px' size=75pt +++[paragraph] size=10pt +++++[text] name='10.2340920823pt' size=10pt +++[paragraph] size=10pt +++++[text] name='10pt' size=10pt +++[paragraph] size=11pt +++++[text] name='11pt' size=11pt +++[paragraph] size=12pt +++++[text] name='12pt' size=12pt +++[paragraph] size=13pt +++++[text] name='13pt' size=13pt +++[paragraph] size=14pt +++++[text] name='14pt' size=14pt +++[paragraph] size=15pt +++++[text] name='15pt' size=15pt +++[paragraph] size=20pt +++++[text] name='20pt' size=20pt +++[paragraph] size=40pt +++++[text] name='40pt' size=40pt +++[paragraph] size=50pt +++++[text] name='50pt' size=50pt +++[paragraph] size=100pt +++++[text] name='100pt' size=100pt
diff --git a/content/test/data/accessibility/css/font-size-expected-blink.txt b/content/test/data/accessibility/css/font-size-expected-blink.txt new file mode 100644 index 0000000..dff887a7 --- /dev/null +++ b/content/test/data/accessibility/css/font-size-expected-blink.txt
@@ -0,0 +1,68 @@ +rootWebArea fontSize=16.00 +++genericContainer ignored fontSize=16.00 +++++paragraph fontSize=10.23 +++++++staticText name='10.2340920823px' fontSize=10.23 +++++++++inlineTextBox name='10.2340920823px' +++++paragraph fontSize=10.00 +++++++staticText name='10px' fontSize=10.00 +++++++++inlineTextBox name='10px' +++++paragraph fontSize=11.00 +++++++staticText name='11px' fontSize=11.00 +++++++++inlineTextBox name='11px' +++++paragraph fontSize=12.00 +++++++staticText name='12px' fontSize=12.00 +++++++++inlineTextBox name='12px' +++++paragraph fontSize=13.00 +++++++staticText name='13px' fontSize=13.00 +++++++++inlineTextBox name='13px' +++++paragraph fontSize=14.00 +++++++staticText name='14px' fontSize=14.00 +++++++++inlineTextBox name='14px' +++++paragraph fontSize=15.00 +++++++staticText name='15px' fontSize=15.00 +++++++++inlineTextBox name='15px' +++++paragraph fontSize=20.00 +++++++staticText name='20px' fontSize=20.00 +++++++++inlineTextBox name='20px' +++++paragraph fontSize=40.00 +++++++staticText name='40px' fontSize=40.00 +++++++++inlineTextBox name='40px' +++++paragraph fontSize=50.00 +++++++staticText name='50px' fontSize=50.00 +++++++++inlineTextBox name='50px' +++++paragraph fontSize=100.00 +++++++staticText name='100px' fontSize=100.00 +++++++++inlineTextBox name='100px' +++++paragraph fontSize=13.65 +++++++staticText name='10.2340920823pt' fontSize=13.65 +++++++++inlineTextBox name='10.2340920823pt' +++++paragraph fontSize=13.33 +++++++staticText name='10pt' fontSize=13.33 +++++++++inlineTextBox name='10pt' +++++paragraph fontSize=14.67 +++++++staticText name='11pt' fontSize=14.67 +++++++++inlineTextBox name='11pt' +++++paragraph fontSize=16.00 +++++++staticText name='12pt' fontSize=16.00 +++++++++inlineTextBox name='12pt' +++++paragraph fontSize=17.33 +++++++staticText name='13pt' fontSize=17.33 +++++++++inlineTextBox name='13pt' +++++paragraph fontSize=18.67 +++++++staticText name='14pt' fontSize=18.67 +++++++++inlineTextBox name='14pt' +++++paragraph fontSize=20.00 +++++++staticText name='15pt' fontSize=20.00 +++++++++inlineTextBox name='15pt' +++++paragraph fontSize=26.67 +++++++staticText name='20pt' fontSize=26.67 +++++++++inlineTextBox name='20pt' +++++paragraph fontSize=53.33 +++++++staticText name='40pt' fontSize=53.33 +++++++++inlineTextBox name='40pt' +++++paragraph fontSize=66.67 +++++++staticText name='50pt' fontSize=66.67 +++++++++inlineTextBox name='50pt' +++++paragraph fontSize=133.33 +++++++staticText name='100pt' fontSize=133.33 +++++++++inlineTextBox name='100pt'
diff --git a/content/test/data/accessibility/css/font-size-expected-win.txt b/content/test/data/accessibility/css/font-size-expected-win.txt new file mode 100644 index 0000000..95b6966a --- /dev/null +++ b/content/test/data/accessibility/css/font-size-expected-win.txt
@@ -0,0 +1,45 @@ +ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE font-size:7.5pt font-size:8.5pt font-size:9pt font-size:10pt font-size:10.5pt font-size:11.5pt font-size:15pt font-size:30pt font-size:37.5pt font-size:75pt font-size:10pt font-size:11pt font-size:12pt font-size:13pt font-size:14pt font-size:15pt font-size:20pt font-size:40pt font-size:50pt font-size:100pt +++IA2_ROLE_PARAGRAPH font-size:7.5pt +++++ROLE_SYSTEM_STATICTEXT name='10.2340920823px' font-size:7.5pt +++IA2_ROLE_PARAGRAPH font-size:7.5pt +++++ROLE_SYSTEM_STATICTEXT name='10px' font-size:7.5pt +++IA2_ROLE_PARAGRAPH font-size:8.5pt +++++ROLE_SYSTEM_STATICTEXT name='11px' font-size:8.5pt +++IA2_ROLE_PARAGRAPH font-size:9pt +++++ROLE_SYSTEM_STATICTEXT name='12px' font-size:9pt +++IA2_ROLE_PARAGRAPH font-size:10pt +++++ROLE_SYSTEM_STATICTEXT name='13px' font-size:10pt +++IA2_ROLE_PARAGRAPH font-size:10.5pt +++++ROLE_SYSTEM_STATICTEXT name='14px' font-size:10.5pt +++IA2_ROLE_PARAGRAPH font-size:11.5pt +++++ROLE_SYSTEM_STATICTEXT name='15px' font-size:11.5pt +++IA2_ROLE_PARAGRAPH font-size:15pt +++++ROLE_SYSTEM_STATICTEXT name='20px' font-size:15pt +++IA2_ROLE_PARAGRAPH font-size:30pt +++++ROLE_SYSTEM_STATICTEXT name='40px' font-size:30pt +++IA2_ROLE_PARAGRAPH font-size:37.5pt +++++ROLE_SYSTEM_STATICTEXT name='50px' font-size:37.5pt +++IA2_ROLE_PARAGRAPH font-size:75pt +++++ROLE_SYSTEM_STATICTEXT name='100px' font-size:75pt +++IA2_ROLE_PARAGRAPH font-size:10pt +++++ROLE_SYSTEM_STATICTEXT name='10.2340920823pt' font-size:10pt +++IA2_ROLE_PARAGRAPH font-size:10pt +++++ROLE_SYSTEM_STATICTEXT name='10pt' font-size:10pt +++IA2_ROLE_PARAGRAPH font-size:11pt +++++ROLE_SYSTEM_STATICTEXT name='11pt' font-size:11pt +++IA2_ROLE_PARAGRAPH font-size:12pt +++++ROLE_SYSTEM_STATICTEXT name='12pt' font-size:12pt +++IA2_ROLE_PARAGRAPH font-size:13pt +++++ROLE_SYSTEM_STATICTEXT name='13pt' font-size:13pt +++IA2_ROLE_PARAGRAPH font-size:14pt +++++ROLE_SYSTEM_STATICTEXT name='14pt' font-size:14pt +++IA2_ROLE_PARAGRAPH font-size:15pt +++++ROLE_SYSTEM_STATICTEXT name='15pt' font-size:15pt +++IA2_ROLE_PARAGRAPH font-size:20pt +++++ROLE_SYSTEM_STATICTEXT name='20pt' font-size:20pt +++IA2_ROLE_PARAGRAPH font-size:40pt +++++ROLE_SYSTEM_STATICTEXT name='40pt' font-size:40pt +++IA2_ROLE_PARAGRAPH font-size:50pt +++++ROLE_SYSTEM_STATICTEXT name='50pt' font-size:50pt +++IA2_ROLE_PARAGRAPH font-size:100pt +++++ROLE_SYSTEM_STATICTEXT name='100pt' font-size:100pt
diff --git a/content/test/data/accessibility/css/font-size.html b/content/test/data/accessibility/css/font-size.html new file mode 100644 index 0000000..a71d9f6e --- /dev/null +++ b/content/test/data/accessibility/css/font-size.html
@@ -0,0 +1,32 @@ +<!-- +@BLINK-ALLOW:fontSize=* +@WIN-ALLOW:font-size:* +@AURALINUX-ALLOW:size=* +--> +<!DOCTYPE html> +<html> + <body> + <p style="font-size: 10.2340920823px">10.2340920823px</p> + <p style="font-size: 10px">10px</p> + <p style="font-size: 11px">11px</p> + <p style="font-size: 12px">12px</p> + <p style="font-size: 13px">13px</p> + <p style="font-size: 14px">14px</p> + <p style="font-size: 15px">15px</p> + <p style="font-size: 20px">20px</p> + <p style="font-size: 40px">40px</p> + <p style="font-size: 50px">50px</p> + <p style="font-size: 100px">100px</p> + <p style="font-size: 10.2340920823pt">10.2340920823pt</p> + <p style="font-size: 10pt">10pt</p> + <p style="font-size: 11pt">11pt</p> + <p style="font-size: 12pt">12pt</p> + <p style="font-size: 13pt">13pt</p> + <p style="font-size: 14pt">14pt</p> + <p style="font-size: 15pt">15pt</p> + <p style="font-size: 20pt">20pt</p> + <p style="font-size: 40pt">40pt</p> + <p style="font-size: 50pt">50pt</p> + <p style="font-size: 100pt">100pt</p> + </body> +</html>
diff --git a/content/test/data/service_worker/code_cache_strategy.html b/content/test/data/service_worker/code_cache_strategy.html deleted file mode 100644 index b109843..0000000 --- a/content/test/data/service_worker/code_cache_strategy.html +++ /dev/null
@@ -1,36 +0,0 @@ -<html> -<title>Code cache strategy test</title> -<script> -async function fetch_script(url) { - try { - await fetch(url).then(res => res.text()); - return 'DONE'; - } catch (error) { - return `${error}`; - } -} - -async function post_message(command) { - return new Promise(resolve => { - let listener = (e) => { - navigator.serviceWorker.removeEventListener('message', listener); - resolve(e.data); - }; - navigator.serviceWorker.addEventListener('message', listener); - navigator.serviceWorker.controller.postMessage({ command: command }); - }); -} - -async function execute_cached_twice_script() { - return new Promise(resolve => { - const tag = document.createElement('script'); - tag.src = 'code_cache_strategy_test_script.js?cached_twice'; - tag.onload = () => { - const result = test_function(); - resolve(result); - }; - document.body.appendChild(tag); - }); -} -</script> -</html>
diff --git a/content/test/data/service_worker/code_cache_strategy_test_script.js b/content/test/data/service_worker/code_cache_strategy_test_script.js deleted file mode 100644 index ebb7d7e..0000000 --- a/content/test/data/service_worker/code_cache_strategy_test_script.js +++ /dev/null
@@ -1,7 +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. - -function test_function() { - return 'SUCCESS'; -}
diff --git a/content/test/data/service_worker/code_cache_strategy_worker.js b/content/test/data/service_worker/code_cache_strategy_worker.js deleted file mode 100644 index ff94ce8e..0000000 --- a/content/test/data/service_worker/code_cache_strategy_worker.js +++ /dev/null
@@ -1,74 +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. - -const CACHE_NAME = 'cache_name'; -const SCRIPT_PATH = 'code_cache_strategy_test_script.js'; - -async function get_from_cache_or_fetch(request) { - const cache = await caches.open(CACHE_NAME); - const cached = await cache.match(request); - if (cached) { - return cached; - } - const response = await fetch(request); - await cache.put(request, response.clone()); - return response; -} - -async function cache_script_in_message_event(source) { - const cache = await caches.open(CACHE_NAME); - await cache.add(`${SCRIPT_PATH}?cached_in_message_event`); - source.postMessage('DONE'); -} - -async function cache_script_twice(source) { - const cache = await caches.open(CACHE_NAME); - const url = `${SCRIPT_PATH}?cached_twice`; - const response = await fetch(url); - const dummy_response = new Response('/* dummy script */', { - headers: { - 'Content-Type': 'application/javascript' - } - }); - - // 1st step: put synthesized response without await. - cache.put(url, dummy_response); - // 2nd step: put the actual response. - await cache.put(url, response); - source.postMessage('DONE'); -} - -self.addEventListener('install', e => { - e.waitUntil(async function() { - const cache = await caches.open(CACHE_NAME); - await cache.addAll([ - `${SCRIPT_PATH}?cached_in_install_event`, - ]); - - // Create a synthetic response with a mime-type that has a charset - const script_body = "function test_function() { return 'SUCCESS'; }"; - const response = new Response(script_body, { - headers: { 'content-type': 'application/javascript; charset=utf-8' } - }); - await cache.put( - `${SCRIPT_PATH}?cached_in_install_event_with_mime_type_param`, - response); - }()); -}); - -self.addEventListener('fetch', e => { - const url = e.request.url; - if (url.indexOf('cached_in_fetch_event') >= 0) { - e.respondWith(get_from_cache_or_fetch(e.request)); - } -}); - -self.addEventListener('message', e => { - const command = e.data.command; - if (command === 'cache_script_in_message_event') { - cache_script_in_message_event(e.source); - } else if (command === 'cache_script_twice') { - cache_script_twice(e.source); - } -});
diff --git a/content/test/frame_host_interceptor.cc b/content/test/frame_host_interceptor.cc index 155890a..21b7a7ae 100644 --- a/content/test/frame_host_interceptor.cc +++ b/content/test/frame_host_interceptor.cc
@@ -8,9 +8,11 @@ #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/common/frame.mojom-test-utils.h" +#include "content/common/frame.mojom.h" #include "content/common/frame_messages.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "mojo/public/cpp/bindings/associated_receiver.h" namespace content { @@ -22,18 +24,18 @@ FrameAgent(FrameHostInterceptor* interceptor, RenderFrameHost* rfh) : interceptor_(interceptor), rfhi_(static_cast<RenderFrameHostImpl*>(rfh)), - impl_(binding().SwapImplForTesting(this)) {} + impl_(receiver().SwapImplForTesting(this)) {} ~FrameAgent() override { - auto* old_impl = binding().SwapImplForTesting(impl_); + auto* old_impl = receiver().SwapImplForTesting(impl_); // TODO(https://crbug.com/729021): Investigate the scenario where // |old_impl| can be nullptr if the renderer process is killed. DCHECK_EQ(this, old_impl); } protected: - mojo::AssociatedBinding<mojom::FrameHost>& binding() { - return rfhi_->frame_host_binding_for_testing(); + mojo::AssociatedReceiver<mojom::FrameHost>& receiver() { + return rfhi_->frame_host_receiver_for_testing(); } // mojom::FrameHostInterceptorForTesting:
diff --git a/content/test/navigation_simulator_impl.cc b/content/test/navigation_simulator_impl.cc index 8d40b98..e5606bd 100644 --- a/content/test/navigation_simulator_impl.cc +++ b/content/test/navigation_simulator_impl.cc
@@ -1128,14 +1128,14 @@ navigation_client_remote; navigation_client_receiver_ = navigation_client_remote.InitWithNewEndpointAndPassReceiver(); - render_frame_host_->frame_host_binding_for_testing() + render_frame_host_->frame_host_receiver_for_testing() .impl() ->BeginNavigation(std::move(common_params), std::move(begin_params), mojo::NullRemote(), std::move(navigation_client_remote), mojo::NullRemote()); } else { - render_frame_host_->frame_host_binding_for_testing() + render_frame_host_->frame_host_receiver_for_testing() .impl() ->BeginNavigation(std::move(common_params), std::move(begin_params), mojo::NullRemote(), mojo::NullAssociatedRemote(),
diff --git a/content/test/test_render_frame.cc b/content/test/test_render_frame.cc index e7fbc41e..b433a9d0 100644 --- a/content/test/test_render_frame.cc +++ b/content/test/test_render_frame.cc
@@ -11,6 +11,7 @@ #include "base/bind_helpers.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" +#include "content/common/frame.mojom.h" #include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/navigation_params.mojom.h" @@ -150,7 +151,8 @@ base::UnguessableToken()); } - void IssueKeepAliveHandle(mojom::KeepAliveHandleRequest request) override {} + void IssueKeepAliveHandle( + mojo::PendingReceiver<mojom::KeepAliveHandle> receiver) override {} void DidCommitSameDocumentNavigation( std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params)
diff --git a/extensions/common/api/_behavior_features.json b/extensions/common/api/_behavior_features.json index dc502354..5daa412 100644 --- a/extensions/common/api/_behavior_features.json +++ b/extensions/common/api/_behavior_features.json
@@ -88,7 +88,7 @@ "platforms": ["chromeos"], "whitelist": [ "FA84F98B32AFC3013F5711F8711F8F38DB210AB7", // Sign-in Screen Test Extension - "7FE4A999359A456C4B0FB7B7AD85CEA29CA50519", // chrome.loginScreenUi Test Extension + "7FE4A999359A456C4B0FB7B7AD85CEA29CA50519", // Login screen APIs test extension "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) "4DBFC1C52D6660DD90791976DF7FEF7B3D360509" // Imprivata (login screen) DEV ]
diff --git a/ios/chrome/app/strings/ios_chromium_strings.grd b/ios/chrome/app/strings/ios_chromium_strings.grd index d7595b2..20a10cc 100644 --- a/ios/chrome/app/strings/ios_chromium_strings.grd +++ b/ios/chrome/app/strings/ios_chromium_strings.grd
@@ -222,9 +222,6 @@ <message name="IDS_IOS_OPTIONS_IMPORT_DATA_TITLE_SIGNIN" desc="The title of the Import Data settings screen when signing in. [30em]"> Sign in to Chromium </message> - <message name="IDS_IOS_OPTIONS_PRIVACY_FOOTER" desc="Footer for the clear browsing data dialog [Length: 300em] [iOS only]"> - Chromium may use web services to improve your browsing experience. You may optionally disable these services. <ph name="BEGIN_LINK">BEGIN_LINK</ph>Learn more<ph name="END_LINK">END_LINK</ph> - </message> <message name="IDS_IOS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY" desc="The text of the identity section for iOS."> Chromium verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. </message> @@ -282,9 +279,6 @@ <message name="IDS_IOS_UPGRADE_AVAILABLE" desc="Text to inform the user of the presence of a new version of the application"> Chromium just got better! A new version is available. </message> - <message name="IDS_IOS_SIGNIN_PROMO_SETTINGS" desc="Text to inform the user that they can sign in to get personal settings"> - Sign in to Chromium to get your bookmarks, passwords, and more on all your devices. - </message> </messages> </release> </grit>
diff --git a/ios/chrome/app/strings/ios_google_chrome_strings.grd b/ios/chrome/app/strings/ios_google_chrome_strings.grd index a22ee18b..b09bc7d 100644 --- a/ios/chrome/app/strings/ios_google_chrome_strings.grd +++ b/ios/chrome/app/strings/ios_google_chrome_strings.grd
@@ -222,9 +222,6 @@ <message name="IDS_IOS_OPTIONS_IMPORT_DATA_TITLE_SIGNIN" desc="The title of the Import Data settings screen when signing in. [30em]"> Sign in to Chrome </message> - <message name="IDS_IOS_OPTIONS_PRIVACY_FOOTER" desc="Footer for the clear browsing data dialog [Length: 300em] [iOS only]"> - Google Chrome may use web services to improve your browsing experience. You may optionally disable these services. <ph name="BEGIN_LINK">BEGIN_LINK</ph>Learn more<ph name="END_LINK">END_LINK</ph> - </message> <message name="IDS_IOS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY" desc="The text of the identity section for iOS."> Chrome verified that <ph name="ISSUER">$1<ex>VeriSign</ex></ph> issued this website's certificate. </message> @@ -282,9 +279,6 @@ <message name="IDS_IOS_UPGRADE_AVAILABLE" desc="Text to inform the user of the presence of a new version of the application"> Chrome just got better! A new version is available. </message> - <message name="IDS_IOS_SIGNIN_PROMO_SETTINGS" desc="Text to inform the user that they can sign in to get personal settings"> - Sign in to Chrome to get your bookmarks, passwords, and more on all your devices. - </message> </messages> </release> </grit>
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 8f58991..7b83839 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -1081,12 +1081,6 @@ <message name="IDS_IOS_OPTIONS_REPORT_AN_ISSUE" desc="Title for the option on Settings page to report an issue. [Length: 20em] [iOS only]"> Report an Issue </message> - <message name="IDS_IOS_OPTIONS_SEARCH_URL_SUGGESTIONS" desc="Title for the option to turn on/off search and URL suggestions. [Length: 18em] [iOS only]"> - Search and Site Suggestions - </message> - <message name="IDS_IOS_OPTIONS_SEND_USAGE_DATA" desc="Title for opening the setting for if/when to send usage data and crash reports. [Length: 20em] [iOS only]"> - Send Usage Data - </message> <message name="IDS_IOS_OPTIONS_WEB_SERVICES_LABEL" desc="Title for group of web services items in Privacy settings table, including Show Suggestions, Preload Webpages, and Send Usage Data. [Length: 10em] [iOS only]"> Web Services </message> @@ -1600,9 +1594,6 @@ <message name="IDS_IOS_SIGN_IN_TO_CHROME_SETTING_SUBTITLE" desc="The subtitle for the setting item to Sign in to Chrome [iOS only]"> Get your bookmarks, history, passwords, and other settings on all your devices </message> - <message name="IDS_IOS_SIGN_IN_TO_CHROME_SETTING_SYNCING" desc="The subtitle for the setting item of the signed in user [iOS only]"> - Syncing to <ph name="EMAIL">$1<ex>john.doe@gmail.com</ex></ph> - </message> <message name="IDS_IOS_SIGN_IN_TO_CHROME_SETTING_SYNC_OFF" desc="The subtitle for the setting item of the signed in user when sync is off [iOS only]"> Sync is off </message>
diff --git a/ios/chrome/browser/tabs/tab_model.h b/ios/chrome/browser/tabs/tab_model.h index 9e0cdfa0..13e8158 100644 --- a/ios/chrome/browser/tabs/tab_model.h +++ b/ios/chrome/browser/tabs/tab_model.h
@@ -82,10 +82,6 @@ webStateList:(WebStateList*)webStateList NS_DESIGNATED_INITIALIZER; -// Temporary backwards compatibility init which creates a webStateList. -- (instancetype)initWithSessionService:(SessionServiceIOS*)service - browserState:(ios::ChromeBrowserState*)browserState; - - (instancetype)init NS_UNAVAILABLE; // Add/modify tabs. @@ -141,9 +137,6 @@ // the tab model after this is called is unsafe. - (void)disconnect; -// Legacy method name for -disconnect, will be deleted very soon. -- (void)browserStateDestroyed; - @end #endif // IOS_CHROME_BROWSER_TABS_TAB_MODEL_H_
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index 430bcbeb..b92b6bf 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -243,10 +243,6 @@ // Used to observe owned Tabs' WebStates. std::unique_ptr<web::WebStateObserver> _webStateObserver; - - // Legacy ivars for backwards compatibility with some tests - std::unique_ptr<WebStateListDelegate> _legacyWebStateListDelegate; - std::unique_ptr<WebStateList> _legacyOwnedWebStateList; } // Session window for the contents of the tab model. @@ -376,17 +372,6 @@ return self; } -- (instancetype)initWithSessionService:(SessionServiceIOS*)service - browserState:(ios::ChromeBrowserState*)browserState { - _legacyWebStateListDelegate = std::make_unique<BrowserWebStateListDelegate>(); - _legacyOwnedWebStateList = - std::make_unique<WebStateList>(_legacyWebStateListDelegate.get()); - - return [self initWithSessionService:service - browserState:browserState - webStateList:_legacyOwnedWebStateList.get()]; -} - - (web::WebState*)insertWebStateWithURL:(const GURL&)URL referrer:(const web::Referrer&)referrer transition:(ui::PageTransition)transition @@ -520,10 +505,6 @@ _webStateObserver.reset(); } -- (void)browserStateDestroyed { - [self disconnect]; -} - #pragma mark - SessionWindowRestoring(public) - (void)saveSessionImmediately:(BOOL)immediately {
diff --git a/ios/chrome/browser/ui/settings/BUILD.gn b/ios/chrome/browser/ui/settings/BUILD.gn index 17ce1e34..4d118cb 100644 --- a/ios/chrome/browser/ui/settings/BUILD.gn +++ b/ios/chrome/browser/ui/settings/BUILD.gn
@@ -28,7 +28,6 @@ "//ios/chrome/browser/ui/table_view", "//ios/chrome/browser/ui/table_view:styler", "//ios/chrome/browser/ui/table_view/cells", - "//ios/chrome/browser/ui/util", "//ios/chrome/common/colors", "//ios/chrome/common/ui_util", "//ios/public/provider/chrome/browser", @@ -103,12 +102,10 @@ "//components/content_settings/core/browser", "//components/content_settings/core/common", "//components/feature_engagement", - "//components/google/core/common", "//components/handoff", "//components/history/core/browser", "//components/image_fetcher/ios", "//components/keyed_service/core", - "//components/metrics", "//components/password_manager/core/browser", "//components/password_manager/core/common", "//components/payments/core", @@ -120,8 +117,6 @@ "//components/strings", "//components/translate/core/browser", "//components/translate/core/common", - "//components/ukm/ios:features", - "//components/unified_consent", "//components/url_formatter", "//components/version_info", "//ios/chrome/app/strings", @@ -265,7 +260,6 @@ "//base/test:test_support", "//components/autofill/core/common", "//components/content_settings/core/browser", - "//components/google/core/common", "//components/handoff", "//components/language/core/browser", "//components/password_manager/core/browser:test_support", @@ -279,8 +273,6 @@ "//components/sync_preferences:test_support", "//components/translate/core/browser", "//components/translate/core/common", - "//components/ukm/ios:features", - "//components/unified_consent", "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", @@ -304,7 +296,6 @@ "//ios/chrome/browser/ui/settings/cells", "//ios/chrome/browser/ui/table_view", "//ios/chrome/browser/ui/table_view:test_support", - "//ios/chrome/browser/ui/util", "//ios/chrome/browser/voice", "//ios/chrome/browser/web", "//ios/chrome/browser/web:test_support", @@ -351,8 +342,6 @@ "//components/prefs", "//components/search_engines", "//components/strings", - "//components/ukm/ios:features", - "//components/unified_consent", "//ios/chrome/app:app_internal", "//ios/chrome/app/strings", "//ios/chrome/app/theme", @@ -370,8 +359,6 @@ "//ios/chrome/browser/ui/authentication/cells", "//ios/chrome/browser/ui/settings:test_support", "//ios/chrome/browser/ui/table_view/cells", - "//ios/chrome/browser/ui/util", - "//ios/chrome/browser/ui/util:util", "//ios/chrome/test:eg_test_support", "//ios/chrome/test:test_support", "//ios/chrome/test/app:test_support",
diff --git a/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm b/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm index fe2c0c1..97161ac 100644 --- a/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/privacy_table_view_controller.mm
@@ -6,41 +6,26 @@ #include "base/logging.h" #import "base/mac/foundation_util.h" -#include "components/google/core/common/google_util.h" #include "components/handoff/pref_names_ios.h" -#include "components/metrics/metrics_pref_names.h" #include "components/payments/core/payment_prefs.h" #import "components/prefs/ios/pref_observer_bridge.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" -#include "components/ukm/ios/features.h" -#include "components/unified_consent/feature.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/browsing_data/browsing_data_features.h" -#include "ios/chrome/browser/chrome_url_constants.h" -#include "ios/chrome/browser/pref_names.h" -#include "ios/chrome/browser/system_flags.h" #import "ios/chrome/browser/ui/commands/open_new_tab_command.h" -#import "ios/chrome/browser/ui/settings/cells/settings_cells_constants.h" #import "ios/chrome/browser/ui/settings/cells/settings_switch_cell.h" #import "ios/chrome/browser/ui/settings/cells/settings_switch_item.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_collection_view_controller.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_local_commands.h" #import "ios/chrome/browser/ui/settings/clear_browsing_data/clear_browsing_data_table_view_controller.h" -#import "ios/chrome/browser/ui/settings/dataplan_usage_table_view_controller.h" -#import "ios/chrome/browser/ui/settings/google_services/accounts_table_view_controller.h" #import "ios/chrome/browser/ui/settings/handoff_table_view_controller.h" #import "ios/chrome/browser/ui/settings/settings_navigation_controller.h" -#import "ios/chrome/browser/ui/settings/utils/pref_backed_boolean.h" -#import "ios/chrome/browser/ui/settings/utils/settings_utils.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_detail_icon_item.h" -#import "ios/chrome/browser/ui/table_view/cells/table_view_detail_text_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_link_header_footer_item.h" -#import "ios/chrome/browser/ui/table_view/cells/table_view_text_header_footer_item.h" #include "ios/chrome/browser/ui/ui_feature_flags.h" -#include "ios/chrome/browser/ui/util/ui_util.h" #include "ios/chrome/grit/ios_chromium_strings.h" #include "ios/chrome/grit/ios_strings.h" #include "ui/base/l10n/l10n_util.h" @@ -63,9 +48,6 @@ typedef NS_ENUM(NSInteger, ItemType) { ItemTypeOtherDevicesHandoff = kItemTypeEnumZero, ItemTypeWebServicesPaymentSwitch, - ItemTypeWebServicesSendUsageData, - ItemTypeWebServicesShowSuggestions, - ItemTypeWebServicesFooter, ItemTypeClearBrowsingDataClear, // Footer to suggest the user to open Sync and Google services settings. ItemTypeClearBrowsingDataFooter, @@ -77,13 +59,9 @@ } // namespace -@interface PrivacyTableViewController () <BooleanObserver, - ClearBrowsingDataLocalCommands, +@interface PrivacyTableViewController () <ClearBrowsingDataLocalCommands, PrefObserverDelegate> { ios::ChromeBrowserState* _browserState; // weak - PrefBackedBoolean* _suggestionsEnabled; - // The item related to the switch for the show suggestions setting. - SettingsSwitchItem* _showSuggestionsItem; // Pref observer to track changes to prefs. std::unique_ptr<PrefObserverBridge> _prefObserverBridge; @@ -93,8 +71,6 @@ // Updatable Items TableViewDetailIconItem* _handoffDetailItem; - TableViewDetailIconItem* _sendUsageDetailItem; - SettingsSwitchItem* _sendUsageToggleSwitchItem; } @end @@ -114,14 +90,6 @@ _browserState = browserState; self.title = l10n_util::GetNSString(IDS_OPTIONS_ADVANCED_SECTION_TITLE_PRIVACY); - if (!unified_consent::IsUnifiedConsentFeatureEnabled()) { - // When unified consent flag is enabled, the suggestion setting is - // available in the "Google Services and sync" settings. - _suggestionsEnabled = [[PrefBackedBoolean alloc] - initWithPrefService:_browserState->GetPrefs() - prefName:prefs::kSearchSuggestEnabled]; - [_suggestionsEnabled setObserver:self]; - } PrefService* prefService = _browserState->GetPrefs(); @@ -133,14 +101,6 @@ // screen. _prefObserverBridge->ObserveChangesForPreference( prefs::kIosHandoffToOtherDevices, &_prefChangeRegistrar); - if (!unified_consent::IsUnifiedConsentFeatureEnabled()) { - _prefObserverBridge->ObserveChangesForPreference( - metrics::prefs::kMetricsReportingEnabled, - &_prefChangeRegistrarApplicationContext); - _prefObserverBridge->ObserveChangesForPreference( - prefs::kMetricsReportingWifiOnly, - &_prefChangeRegistrarApplicationContext); - } } return self; } @@ -167,34 +127,13 @@ toSectionWithIdentifier:SectionIdentifierWebServices]; [model addItem:[self canMakePaymentItem] toSectionWithIdentifier:SectionIdentifierWebServices]; - if (!unified_consent::IsUnifiedConsentFeatureEnabled()) { - // When unified consent flag is enabled, the show suggestions feature and - // metrics reporting feature are available in the "Google Services and sync" - // settings. - if (base::FeatureList::IsEnabled(kUmaCellular)) { - [model addItem:[self sendUsageToggleSwitchItem] - toSectionWithIdentifier:SectionIdentifierWebServices]; - } else { - [model addItem:[self sendUsageDetailItem] - toSectionWithIdentifier:SectionIdentifierWebServices]; - } - _showSuggestionsItem = [self showSuggestionsSwitchItem]; - [model addItem:_showSuggestionsItem - toSectionWithIdentifier:SectionIdentifierWebServices]; - - [model setFooter:[self showSuggestionsFooterItem] - forSectionWithIdentifier:SectionIdentifierWebServices]; - } - // Clear Browsing Section [model addSectionWithIdentifier:SectionIdentifierClearBrowsingData]; [model addItem:[self clearBrowsingDetailItem] toSectionWithIdentifier:SectionIdentifierClearBrowsingData]; - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - [model setFooter:[self showClearBrowsingDataFooterItem] - forSectionWithIdentifier:SectionIdentifierClearBrowsingData]; - } + [model setFooter:[self showClearBrowsingDataFooterItem] + forSectionWithIdentifier:SectionIdentifierClearBrowsingData]; } #pragma mark - Model Objects @@ -212,29 +151,6 @@ return _handoffDetailItem; } -- (SettingsSwitchItem*)showSuggestionsSwitchItem { - SettingsSwitchItem* showSuggestionsSwitchItem = [[SettingsSwitchItem alloc] - initWithType:ItemTypeWebServicesShowSuggestions]; - showSuggestionsSwitchItem.text = - l10n_util::GetNSString(IDS_IOS_OPTIONS_SEARCH_URL_SUGGESTIONS); - showSuggestionsSwitchItem.on = [_suggestionsEnabled value]; - - return showSuggestionsSwitchItem; -} - -- (TableViewHeaderFooterItem*)showSuggestionsFooterItem { - TableViewLinkHeaderFooterItem* showSuggestionsFooterItem = - [[TableViewLinkHeaderFooterItem alloc] - initWithType:ItemTypeWebServicesFooter]; - showSuggestionsFooterItem.text = - l10n_util::GetNSString(IDS_IOS_OPTIONS_PRIVACY_FOOTER); - showSuggestionsFooterItem.linkURL = google_util::AppendGoogleLocaleParam( - GURL(kPrivacyLearnMoreURL), - GetApplicationContext()->GetApplicationLocale()); - - return showSuggestionsFooterItem; -} - // Creates TableViewHeaderFooterItem instance to show a link to open the Sync // and Google services settings. - (TableViewHeaderFooterItem*)showClearBrowsingDataFooterItem { @@ -273,31 +189,6 @@ isEnabled); } -- (TableViewItem*)sendUsageDetailItem { - NSString* detailText = [DataplanUsageTableViewController - currentLabelForPreference:GetApplicationContext()->GetLocalState() - basePref:metrics::prefs::kMetricsReportingEnabled - wifiPref:prefs::kMetricsReportingWifiOnly]; - _sendUsageDetailItem = - [self detailItemWithType:ItemTypeWebServicesSendUsageData - titleId:IDS_IOS_OPTIONS_SEND_USAGE_DATA - detailText:detailText]; - - return _sendUsageDetailItem; -} - -- (SettingsSwitchItem*)sendUsageToggleSwitchItem { - _sendUsageToggleSwitchItem = [[SettingsSwitchItem alloc] - initWithType:ItemTypeWebServicesSendUsageData]; - _sendUsageToggleSwitchItem.text = - l10n_util::GetNSString(IDS_IOS_OPTIONS_SEND_USAGE_DATA); - _sendUsageToggleSwitchItem.on = - GetApplicationContext()->GetLocalState()->GetBoolean( - metrics::prefs::kMetricsReportingEnabled); - - return _sendUsageToggleSwitchItem; -} - - (TableViewDetailIconItem*)detailItemWithType:(NSInteger)type titleId:(NSInteger)titleId detailText:(NSString*)detailText { @@ -320,25 +211,12 @@ NSInteger itemType = [self.tableViewModel itemTypeForIndexPath:indexPath]; - if (itemType == ItemTypeWebServicesShowSuggestions) { - SettingsSwitchCell* switchCell = - base::mac::ObjCCastStrict<SettingsSwitchCell>(cell); - [switchCell.switchView addTarget:self - action:@selector(showSuggestionsToggled:) - forControlEvents:UIControlEventValueChanged]; - } else if (itemType == ItemTypeWebServicesPaymentSwitch) { + if (itemType == ItemTypeWebServicesPaymentSwitch) { SettingsSwitchCell* switchCell = base::mac::ObjCCastStrict<SettingsSwitchCell>(cell); [switchCell.switchView addTarget:self action:@selector(canMakePaymentSwitchChanged:) forControlEvents:UIControlEventValueChanged]; - } else if (itemType == ItemTypeWebServicesSendUsageData && - base::FeatureList::IsEnabled(kUmaCellular)) { - SettingsSwitchCell* switchCell = - base::mac::ObjCCastStrict<SettingsSwitchCell>(cell); - [switchCell.switchView addTarget:self - action:@selector(sendUsageDataToggled:) - forControlEvents:UIControlEventValueChanged]; } return cell; } @@ -370,16 +248,6 @@ controller = [[HandoffTableViewController alloc] initWithBrowserState:_browserState]; break; - case ItemTypeWebServicesSendUsageData: - if (!base::FeatureList::IsEnabled(kUmaCellular)) { - controller = [[DataplanUsageTableViewController alloc] - initWithPrefs:GetApplicationContext()->GetLocalState() - basePref:metrics::prefs::kMetricsReportingEnabled - wifiPref:prefs::kMetricsReportingWifiOnly - title:l10n_util::GetNSString( - IDS_IOS_OPTIONS_SEND_USAGE_DATA)]; - } - break; case ItemTypeClearBrowsingDataClear: if (IsNewClearBrowsingDataUIEnabled()) { ClearBrowsingDataTableViewController* clearBrowsingDataViewController = @@ -393,7 +261,6 @@ } break; case ItemTypeWebServicesPaymentSwitch: - case ItemTypeWebServicesShowSuggestions: default: break; } @@ -406,18 +273,6 @@ [tableView deselectRowAtIndexPath:indexPath animated:YES]; } -#pragma mark - BooleanObserver - -- (void)booleanDidChange:(id<ObservableBoolean>)observableBoolean { - DCHECK_EQ(observableBoolean, _suggestionsEnabled); - - // Update the item. - _showSuggestionsItem.on = [_suggestionsEnabled value]; - - // Update the cell. - [self reconfigureCellsForItems:@[ _showSuggestionsItem ]]; -} - #pragma mark - ClearBrowsingDataLocalCommands - (void)openURL:(const GURL&)URL { @@ -435,24 +290,6 @@ #pragma mark - Actions -- (void)showSuggestionsToggled:(UISwitch*)sender { - NSIndexPath* switchPath = [self.tableViewModel - indexPathForItemType:ItemTypeWebServicesShowSuggestions - sectionIdentifier:SectionIdentifierWebServices]; - - SettingsSwitchItem* switchItem = - base::mac::ObjCCastStrict<SettingsSwitchItem>( - [self.tableViewModel itemAtIndexPath:switchPath]); - SettingsSwitchCell* switchCell = - base::mac::ObjCCastStrict<SettingsSwitchCell>( - [self.tableView cellForRowAtIndexPath:switchPath]); - - DCHECK_EQ(switchCell.switchView, sender); - BOOL isOn = switchCell.switchView.isOn; - switchItem.on = isOn; - [_suggestionsEnabled setValue:isOn]; -} - - (void)canMakePaymentSwitchChanged:(UISwitch*)sender { NSIndexPath* switchPath = [self.tableViewModel indexPathForItemType:ItemTypeWebServicesPaymentSwitch @@ -470,20 +307,6 @@ [self setCanMakePaymentEnabled:sender.isOn]; } -- (void)sendUsageDataToggled:(UISwitch*)sender { - NSIndexPath* switchPath = - [self.tableViewModel indexPathForItem:_sendUsageToggleSwitchItem]; - SettingsSwitchCell* switchCell = - base::mac::ObjCCastStrict<SettingsSwitchCell>( - [self.tableView cellForRowAtIndexPath:switchPath]); - - DCHECK_EQ(switchCell.switchView, sender); - _sendUsageToggleSwitchItem.on = sender.isOn; - - GetApplicationContext()->GetLocalState()->SetBoolean( - metrics::prefs::kMetricsReportingEnabled, sender.isOn); -} - #pragma mark - PrefObserverDelegate - (void)onPreferenceChanged:(const std::string&)preferenceName { @@ -496,28 +319,6 @@ [self reconfigureCellsForItems:@[ _handoffDetailItem ]]; return; } - - if (preferenceName == metrics::prefs::kMetricsReportingEnabled || - preferenceName == prefs::kMetricsReportingWifiOnly) { - DCHECK(!unified_consent::IsUnifiedConsentFeatureEnabled()); - if (base::FeatureList::IsEnabled(kUmaCellular)) { - bool isOn = GetApplicationContext()->GetLocalState()->GetBoolean( - metrics::prefs::kMetricsReportingEnabled); - _sendUsageToggleSwitchItem.on = isOn; - [self reconfigureCellsForItems:@[ _sendUsageToggleSwitchItem ]]; - return; - } else { - NSString* detailText = [DataplanUsageTableViewController - currentLabelForPreference:GetApplicationContext()->GetLocalState() - basePref:metrics::prefs::kMetricsReportingEnabled - wifiPref:prefs::kMetricsReportingWifiOnly]; - - _sendUsageDetailItem.detailText = detailText; - - [self reconfigureCellsForItems:@[ _sendUsageDetailItem ]]; - return; - } - } } #pragma mark - TableViewLinkHeaderFooterItemDelegate
diff --git a/ios/chrome/browser/ui/settings/privacy_table_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/privacy_table_view_controller_unittest.mm index 13ea9fd..95dcd1b 100644 --- a/ios/chrome/browser/ui/settings/privacy_table_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/privacy_table_view_controller_unittest.mm
@@ -14,8 +14,6 @@ #include "components/strings/grit/components_strings.h" #include "components/sync_preferences/pref_service_mock_factory.h" #include "components/sync_preferences/pref_service_syncable.h" -#include "components/ukm/ios/features.h" -#include "components/unified_consent/feature.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #include "ios/chrome/browser/pref_names.h" @@ -95,9 +93,7 @@ EXPECT_EQ(2, NumberOfSections()); // Sections[0]. - const int kExpectedNumberOfItermsInSection0 = - unified_consent::IsUnifiedConsentFeatureEnabled() ? 2 : 4; - EXPECT_EQ(kExpectedNumberOfItermsInSection0, NumberOfItemsInSection(0)); + EXPECT_EQ(2, NumberOfItemsInSection(0)); NSString* handoffSubtitle = chrome_browser_state_->GetPrefs()->GetBoolean( prefs::kIosHandoffToOtherDevices) ? l10n_util::GetNSString(IDS_IOS_SETTING_ON) @@ -109,19 +105,6 @@ NO, l10n_util::GetNSString(IDS_SETTINGS_CAN_MAKE_PAYMENT_TOGGLE_LABEL), 0, 1); - if (!unified_consent::IsUnifiedConsentFeatureEnabled()) { - if (base::FeatureList::IsEnabled(kUmaCellular)) { - CheckSwitchCellStateAndTextWithId(NO, IDS_IOS_OPTIONS_SEND_USAGE_DATA, 0, - 2); - } else { - CheckDetailItemTextWithIds(IDS_IOS_OPTIONS_SEND_USAGE_DATA, - IDS_IOS_OPTIONS_DATA_USAGE_NEVER, 0, 2); - } - CheckSwitchCellStateAndTextWithId( - YES, IDS_IOS_OPTIONS_SEARCH_URL_SUGGESTIONS, 0, 3); - CheckSectionFooterWithId(IDS_IOS_OPTIONS_PRIVACY_FOOTER, 0); - } - // Sections[1]. EXPECT_EQ(1, NumberOfItemsInSection(1)); CheckTextCellText(l10n_util::GetNSString(IDS_IOS_CLEAR_BROWSING_DATA_TITLE),
diff --git a/ios/chrome/browser/ui/settings/settings_egtest.mm b/ios/chrome/browser/ui/settings/settings_egtest.mm index 3f764b3..375acd9 100644 --- a/ios/chrome/browser/ui/settings/settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/settings_egtest.mm
@@ -19,7 +19,6 @@ #include "components/prefs/pref_member.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" -#include "components/unified_consent/feature.h" #import "ios/chrome/app/main_controller.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/content_settings/host_content_settings_map_factory.h" @@ -75,10 +74,6 @@ kBreakpadFirstLaunch, }; -// Matcher for the Send Usage Data cell on the Privacy screen. -id<GREYMatcher> SendUsageDataButton() { - return ButtonWithAccessibilityLabelId(IDS_IOS_OPTIONS_SEND_USAGE_DATA); -} // Matcher for the Clear Browsing Data cell on the Privacy screen. id<GREYMatcher> ClearBrowsingDataCell() { return ButtonWithAccessibilityLabelId(IDS_IOS_CLEAR_BROWSING_DATA_TITLE); @@ -721,20 +716,11 @@ GREYAssertNil(settings.keyCommands, @"Settings should not register key commands when presented."); - // Dismiss the Sign-in UI. - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - // Cancel the sign-in operation. - [[EarlGrey selectElementWithMatcher: - grey_buttonTitle([l10n_util::GetNSString( - IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON) - uppercaseString])] performAction:grey_tap()]; - } else { - // Cancel the add account operation. - [[EarlGrey - selectElementWithMatcher:grey_allOf(grey_buttonTitle(@"Cancel"), - grey_sufficientlyVisible(), nil)] - performAction:grey_tap()]; - } + // Cancel the sign-in operation. + [[EarlGrey selectElementWithMatcher: + grey_buttonTitle([l10n_util::GetNSString( + IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON) + uppercaseString])] performAction:grey_tap()]; // Wait for UI to finish closing the Sign-in screen. [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; @@ -744,20 +730,4 @@ @"Settings should register key commands when presented."); } -// Verifies the UI elements are accessible on the Send Usage Data page. -- (void)testAccessibilityOnSendUsageData { - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - EARL_GREY_TEST_DISABLED( - @"Privacy switch for ContentSuggestion was moved to the Sync and " - "Google services settings screen, so it is no longer present in the " - "privacy section. This test is now covered by " - "-[GoogleServicesSettingsTestCase testOpeningServices]."); - } - [ChromeEarlGreyUI openSettingsMenu]; - [ChromeEarlGreyUI tapSettingsMenuButton:SettingsMenuPrivacyButton()]; - [ChromeEarlGreyUI tapPrivacyMenuButton:SendUsageDataButton()]; - [ChromeEarlGrey verifyAccessibilityForCurrentScreen]; - [self closeSubSettingsMenu]; -} - @end
diff --git a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm index 24fe63a..2c5a9ed 100644 --- a/ios/chrome/browser/ui/settings/settings_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_table_view_controller.mm
@@ -22,7 +22,6 @@ #import "components/signin/public/identity_manager/objc/identity_manager_observer_bridge.h" #include "components/strings/grit/components_strings.h" #include "components/sync/driver/sync_service.h" -#include "components/unified_consent/feature.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h" @@ -383,15 +382,13 @@ [model addItem:[self accountCellItem] toSectionWithIdentifier:SectionIdentifierAccount]; } - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - if (![model hasSectionForSectionIdentifier:SectionIdentifierAccount]) { - // Add the Account section for the Google services cell, if the user is - // signed-out. - [model addSectionWithIdentifier:SectionIdentifierAccount]; - } - [model addItem:[self googleServicesCellItem] - toSectionWithIdentifier:SectionIdentifierAccount]; + if (![model hasSectionForSectionIdentifier:SectionIdentifierAccount]) { + // Add the Account section for the Google services cell, if the user is + // signed-out. + [model addSectionWithIdentifier:SectionIdentifierAccount]; } + [model addItem:[self googleServicesCellItem] + toSectionWithIdentifier:SectionIdentifierAccount]; // Basics section [model addSectionWithIdentifier:SectionIdentifierBasics]; @@ -454,13 +451,8 @@ if (_signinPromoViewMediator) { TableViewSigninPromoItem* signinPromoItem = [[TableViewSigninPromoItem alloc] initWithType:ItemTypeSigninPromo]; - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - signinPromoItem.text = - l10n_util::GetNSString(IDS_IOS_SIGNIN_PROMO_SETTINGS_WITH_UNITY); - } else { - signinPromoItem.text = - l10n_util::GetNSString(IDS_IOS_SIGNIN_PROMO_SETTINGS); - } + signinPromoItem.text = + l10n_util::GetNSString(IDS_IOS_SIGNIN_PROMO_SETTINGS_WITH_UNITY); signinPromoItem.configurator = [_signinPromoViewMediator createConfigurator]; signinPromoItem.delegate = _signinPromoViewMediator; @@ -969,33 +961,7 @@ } identityAccountItem.image = [self userAccountImage]; identityAccountItem.text = [_identity userFullName]; - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - identityAccountItem.detailText = _identity.userEmail; - return; - } - - SyncSetupService* syncSetupService = - SyncSetupServiceFactory::GetForBrowserState(_browserState); - if (!syncSetupService->HasFinishedInitialSetup()) { - identityAccountItem.detailText = - l10n_util::GetNSString(IDS_IOS_SYNC_SETUP_IN_PROGRESS); - identityAccountItem.shouldDisplayError = NO; - return; - } - identityAccountItem.shouldDisplayError = - !IsTransientSyncError(syncSetupService->GetSyncServiceState()); - if (identityAccountItem.shouldDisplayError) { - identityAccountItem.detailText = - GetSyncErrorDescriptionForSyncSetupService(syncSetupService); - } else { - identityAccountItem.detailText = - syncSetupService->IsSyncEnabled() - ? l10n_util::GetNSStringF( - IDS_IOS_SIGN_IN_TO_CHROME_SETTING_SYNCING, - base::SysNSStringToUTF16([_identity userEmail])) - : l10n_util::GetNSString( - IDS_IOS_SIGN_IN_TO_CHROME_SETTING_SYNC_OFF); - } + identityAccountItem.detailText = _identity.userEmail; } - (void)reloadAccountCell { @@ -1138,11 +1104,7 @@ #pragma mark SyncObserverModelBridge - (void)onSyncStateChanged { - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - [self reloadGoogleServicesCell]; - } else { - [self reloadAccountCell]; - } + [self reloadGoogleServicesCell]; } #pragma mark - IdentityRefreshLogic
diff --git a/ios/chrome/browser/ui/settings/signin_settings_egtest.mm b/ios/chrome/browser/ui/settings/signin_settings_egtest.mm index 5fc18a7..ed248fc 100644 --- a/ios/chrome/browser/ui/settings/signin_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/signin_settings_egtest.mm
@@ -6,7 +6,6 @@ #include "base/strings/sys_string_conversions.h" #include "components/prefs/pref_service.h" -#include "components/unified_consent/feature.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/pref_names.h" #import "ios/chrome/browser/ui/authentication/signin_earl_grey_ui.h" @@ -43,19 +42,11 @@ checkSigninPromoVisibleWithMode:SigninPromoViewModeColdState]; [ChromeEarlGreyUI tapSettingsMenuButton:PrimarySignInButton()]; - if (unified_consent::IsUnifiedConsentFeatureEnabled()) { - // Cancel the sign-in operation. - [[EarlGrey selectElementWithMatcher: - grey_buttonTitle([l10n_util::GetNSString( - IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON) - uppercaseString])] performAction:grey_tap()]; - } else { - // Cancel the add account operation. - [[EarlGrey - selectElementWithMatcher:grey_allOf(grey_buttonTitle(@"Cancel"), - grey_sufficientlyVisible(), nil)] - performAction:grey_tap()]; - } + // Cancel the sign-in operation. + [[EarlGrey selectElementWithMatcher: + grey_buttonTitle([l10n_util::GetNSString( + IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SKIP_BUTTON) + uppercaseString])] performAction:grey_tap()]; [SigninEarlGreyUI checkSigninPromoVisibleWithMode:SigninPromoViewModeColdState]; }
diff --git a/ios/web/web_state/ui/crw_web_request_controller.mm b/ios/web/web_state/ui/crw_web_request_controller.mm index 8f79bee..f805fc18 100644 --- a/ios/web/web_state/ui/crw_web_request_controller.mm +++ b/ios/web/web_state/ui/crw_web_request_controller.mm
@@ -144,6 +144,9 @@ [_delegate webRequestControllerStopLoading:self]; web::NavigationItemImpl* item = self.navigationManagerImpl->GetLastCommittedItemImpl(); + if (!item) { + return; + } auto navigationContext = web::NavigationContextImpl::CreateNavigationContext( self.webState, URL, /*has_user_gesture=*/true, item->GetTransitionType(),
diff --git a/ios/web_view/internal/cwv_web_view.mm b/ios/web_view/internal/cwv_web_view.mm index 559e7fb..de2a9d1 100644 --- a/ios/web_view/internal/cwv_web_view.mm +++ b/ios/web_view/internal/cwv_web_view.mm
@@ -592,6 +592,9 @@ #pragma mark - Private methods - (void)updateWebStateVisibility { + if (_webState == nullptr) { + return; + } if (self.superview) { _webState->WasShown(); } else {
diff --git a/media/gpu/linux/mailbox_video_frame_converter.cc b/media/gpu/linux/mailbox_video_frame_converter.cc index 7ccc1c4..f59743d 100644 --- a/media/gpu/linux/mailbox_video_frame_converter.cc +++ b/media/gpu/linux/mailbox_video_frame_converter.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" +#include "base/location.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/task/post_task.h" @@ -16,6 +17,7 @@ #include "gpu/ipc/service/gpu_channel.h" #include "gpu/ipc/service/shared_image_stub.h" #include "media/base/format_utils.h" +#include "media/base/video_frame.h" #include "media/gpu/linux/platform_video_frame_utils.h" #include "media/gpu/macros.h" #include "ui/gfx/gpu_memory_buffer.h" @@ -141,14 +143,14 @@ DVLOGF(4); if (!frame || !frame->HasDmaBufs()) - return OnError("Invalid frame."); + return OnError(FROM_HERE, "Invalid frame."); VideoFrame* origin_frame = unwrap_frame_cb_.Run(*frame); if (!origin_frame) - return OnError("Failed to get origin frame."); + return OnError(FROM_HERE, "Failed to get origin frame."); gpu::Mailbox mailbox; - const int origin_frame_id = origin_frame->unique_id(); + const UniqueID origin_frame_id = origin_frame->unique_id(); if (shared_images_.find(origin_frame_id) != shared_images_.end()) mailbox = shared_images_[origin_frame_id]->mailbox(); @@ -170,7 +172,7 @@ DCHECK(parent_task_runner_->RunsTasksInCurrentSequence()); DCHECK(!mailbox.IsZero()); - const int origin_frame_id = origin_frame->unique_id(); + const UniqueID origin_frame_id = origin_frame->unique_id(); DCHECK(base::Contains(shared_images_, origin_frame_id)); // While we were on |gpu_task_runner_|, AbortPendingFrames() might have been @@ -270,15 +272,15 @@ // TODO(crbug.com/998279): consider eager initialization. if (!InitializeOnGPUThread()) { - OnError("InitializeOnGPUThread failed"); + OnError(FROM_HERE, "InitializeOnGPUThread failed"); return nullptr; } const auto buffer_format = VideoPixelFormatToGfxBufferFormat(video_frame->format()); if (!buffer_format) { - OnError("Unsupported format: " + - VideoPixelFormatToString(video_frame->format())); + OnError(FROM_HERE, "Unsupported format: " + + VideoPixelFormatToString(video_frame->format())); return nullptr; } @@ -289,7 +291,7 @@ gpu::Mailbox mailbox = gpu::Mailbox::GenerateForSharedImage(); if (!gpu_channel_) { - OnError("GpuChannel is gone!"); + OnError(FROM_HERE, "GpuChannel is gone!"); return nullptr; } gpu::SharedImageStub* shared_image_stub = gpu_channel_->shared_image_stub(); @@ -305,7 +307,7 @@ gpu::kNullSurfaceHandle, video_frame->coded_size(), video_frame->ColorSpace(), shared_image_usage); if (!success) { - OnError("Failed to create shared image."); + OnError(FROM_HERE, "Failed to create shared image."); return nullptr; } // There's no need to UpdateSharedImage() after CreateSharedImage(). @@ -328,7 +330,7 @@ origin_frame->AddDestructionObserver(base::BindOnce( [](scoped_refptr<base::SequencedTaskRunner> parent_task_runner, base::WeakPtr<MailboxVideoFrameConverter> parent_weak_ptr, - int origin_frame_id) { + UniqueID origin_frame_id) { if (parent_task_runner->RunsTasksInCurrentSequence()) { if (parent_weak_ptr) parent_weak_ptr->UnregisterSharedImage(origin_frame_id); @@ -346,13 +348,13 @@ const gpu::Mailbox& mailbox) { DCHECK(gpu_task_runner_->BelongsToCurrentThread()); if (!gpu_channel_) { - OnError("GpuChannel is gone!"); + OnError(FROM_HERE, "GpuChannel is gone!"); return false; } gpu::SharedImageStub* shared_image_stub = gpu_channel_->shared_image_stub(); DCHECK(shared_image_stub); if (!shared_image_stub->UpdateSharedImage(mailbox, gfx::GpuFenceHandle())) { - OnError("Could not update shared image"); + OnError(FROM_HERE, "Could not update shared image"); return false; } return true; @@ -364,7 +366,7 @@ DCHECK(gpu_task_runner_->BelongsToCurrentThread()); if (!gpu_channel_) - return OnError("GpuChannel is gone!"); + return OnError(FROM_HERE, "GpuChannel is gone!"); gpu::SharedImageStub* shared_image_stub = gpu_channel_->shared_image_stub(); DCHECK(shared_image_stub); @@ -377,7 +379,8 @@ std::vector<gpu::SyncToken>({sync_token}))); } -void MailboxVideoFrameConverter::UnregisterSharedImage(int origin_frame_id) { +void MailboxVideoFrameConverter::UnregisterSharedImage( + UniqueID origin_frame_id) { DCHECK(parent_task_runner_->RunsTasksInCurrentSequence()); DVLOGF(4); @@ -400,8 +403,9 @@ return !input_frame_queue_.empty(); } -void MailboxVideoFrameConverter::OnError(const std::string& msg) { - VLOGF(1) << msg; +void MailboxVideoFrameConverter::OnError(const base::Location& location, + const std::string& msg) { + VLOGF(1) << "(" << location.ToString() << ") " << msg; parent_task_runner_->PostTask( FROM_HERE, base::BindOnce(&MailboxVideoFrameConverter::AbortPendingFrames,
diff --git a/media/gpu/linux/mailbox_video_frame_converter.h b/media/gpu/linux/mailbox_video_frame_converter.h index 84777927..f4ad2f3 100644 --- a/media/gpu/linux/mailbox_video_frame_converter.h +++ b/media/gpu/linux/mailbox_video_frame_converter.h
@@ -5,20 +5,20 @@ #ifndef MEDIA_GPU_LINUX_MAILBOX_VIDEO_FRAME_CONVERTER_H_ #define MEDIA_GPU_LINUX_MAILBOX_VIDEO_FRAME_CONVERTER_H_ -#include <map> - #include "base/callback_forward.h" #include "base/containers/queue.h" -#include "base/memory/ref_counted.h" +#include "base/containers/small_map.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" -#include "base/single_thread_task_runner.h" #include "gpu/command_buffer/common/mailbox.h" -#include "media/base/video_decoder.h" -#include "media/base/video_frame.h" #include "media/gpu/media_gpu_export.h" #include "media/gpu/video_frame_converter.h" +namespace base { +class Location; +class SingleThreadTaskRunner; +} // namespace base + namespace gpu { class GpuChannel; class CommandBufferStub; @@ -26,6 +26,8 @@ namespace media { +class VideoFrame; + // This class is used for converting DMA-buf backed VideoFrames to mailbox-based // VideoFrames. See ConvertFrame() for more details. // After conversion, the mailbox VideoFrame will retain a reference of the @@ -59,6 +61,9 @@ bool HasPendingFrames() const override; private: + // Use VideoFrame::unique_id() as internal VideoFrame indexing. + using UniqueID = decltype(std::declval<VideoFrame>().unique_id()); + // A self-cleaning SharedImage, with move-only semantics. class ScopedSharedImage; @@ -100,7 +105,7 @@ VideoFrame* origin_frame, std::unique_ptr<ScopedSharedImage> scoped_shared_image); // Unregisters the |origin_frame_id| and associated SharedImage. - void UnregisterSharedImage(int origin_frame_id); + void UnregisterSharedImage(UniqueID origin_frame_id); // Updates the SharedImage associated to |mailbox|. Returns true if the update // could be carried out, false otherwise. @@ -113,7 +118,7 @@ const gpu::SyncToken& sync_token); // Invoked when any error occurs. |msg| is the error message. - void OnError(const std::string& msg); + void OnError(const base::Location& location, const std::string& msg); // In DmabufVideoFramePool, we recycle the unused frames. To do that, each // time a frame is requested from the pool it is wrapped inside another frame. @@ -134,14 +139,14 @@ // Mapping from the unique id of the frame to its corresponding SharedImage. // Accessed only on |parent_task_runner_|. - // TODO(crbug.com/998279): use base::small_map. - // TODO(crbug.com/998279): use VideoFrame::unique_id() return type. - std::map<int, std::unique_ptr<ScopedSharedImage>> shared_images_; + base::small_map<std::map<UniqueID, std::unique_ptr<ScopedSharedImage>>> + shared_images_; // The queue of input frames and the unique_id of their origin frame. // Accessed only on |parent_task_runner_|. // TODO(crbug.com/998279): remove this member entirely. - base::queue<std::pair<scoped_refptr<VideoFrame>, int>> input_frame_queue_; + base::queue<std::pair<scoped_refptr<VideoFrame>, UniqueID>> + input_frame_queue_; // The weak pointer of this, bound to |parent_task_runner_|. // Used at the VideoFrame destruction callback.
diff --git a/media/gpu/vaapi/vaapi_jpeg_encoder.cc b/media/gpu/vaapi/vaapi_jpeg_encoder.cc index 25297a49..854baba 100644 --- a/media/gpu/vaapi/vaapi_jpeg_encoder.cc +++ b/media/gpu/vaapi/vaapi_jpeg_encoder.cc
@@ -376,11 +376,11 @@ return false; } - std::vector<uint8_t> jpeg_header; - size_t jpeg_header_size = exif_buffer_size > 0 - ? kJpegDefaultHeaderSize + exif_buffer_size - : kJpegDefaultHeaderSize + kJFIFApp0Size; - jpeg_header.resize(jpeg_header_size); + size_t jpeg_header_size = + exif_buffer_size > 0 + ? kJpegDefaultHeaderSize + kJFIFApp1HeaderSize + exif_buffer_size + : kJpegDefaultHeaderSize + kJFIFApp0Size; + std::vector<uint8_t> jpeg_header(jpeg_header_size); size_t length_in_bits = FillJpegHeader(input_size, exif_buffer, exif_buffer_size, quality, jpeg_header.data(), exif_offset);
diff --git a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc index b2385ad..f569a8d6 100644 --- a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc
@@ -505,7 +505,7 @@ uint8_t* target_data = static_cast<uint8_t*>(buffer->shm->memory()); size_t data_size = 0; - if (!vaapi_wrapper_->DownloadAndDestroyVABuffer( + if (!vaapi_wrapper_->DownloadFromVABuffer( encode_job->coded_buffer_id(), encode_job->input_surface()->id(), target_data, buffer->shm->size(), &data_size)) { NOTIFY_ERROR(kPlatformFailureError, "Failed downloading coded buffer"); @@ -519,6 +519,8 @@ child_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Client::BitstreamBufferReady, client_, buffer->id, encode_job->Metadata(data_size))); + + vaapi_wrapper_->DestroyVABuffer(encode_job->coded_buffer_id()); } void VaapiVideoEncodeAccelerator::Encode(scoped_refptr<VideoFrame> frame, @@ -617,6 +619,7 @@ // If this is a flush (null) frame, don't create/submit a new encode job for // it, but forward a null job to the submitted_encode_jobs_ queue. scoped_refptr<VaapiEncodeJob> job; + TRACE_EVENT0("media,gpu", "VAVEA::FromCreateEncodeJobToReturn"); if (input_frame) { job = CreateEncodeJob(input_frame->frame, input_frame->force_keyframe); if (!job) @@ -630,8 +633,10 @@ NOTIFY_ERROR(kPlatformFailureError, "Failed preparing an encode job."); return; } - - TRACE_EVENT0("media,gpu", "VAVEA: Execute"); + } + TRACE_EVENT0("media,gpu", "VAVEA::FromExecuteToReturn"); + if (job) { + TRACE_EVENT0("media,gpu", "VAVEA::Execute"); job->Execute(); }
diff --git a/media/gpu/vaapi/vaapi_wrapper.cc b/media/gpu/vaapi/vaapi_wrapper.cc index e99850d..f3ef253 100644 --- a/media/gpu/vaapi/vaapi_wrapper.cc +++ b/media/gpu/vaapi/vaapi_wrapper.cc
@@ -1590,7 +1590,9 @@ const void* buffer) { DCHECK_LT(va_buffer_type, VABufferTypeMax); DCHECK(buffer); + TRACE_EVENT0("media,gpu", "VaapiWrapper::SubmitBuffer"); base::AutoLock auto_lock(*va_lock_); + TRACE_EVENT0("media,gpu", "VaapiWrapper::SubmitBufferLocked"); VABufferID buffer_id; VAStatus va_res = vaCreateBuffer(va_display_, va_context_id_, va_buffer_type, @@ -1649,8 +1651,14 @@ } void VaapiWrapper::DestroyPendingBuffers() { + TRACE_EVENT0("media,gpu", "VaapiWrapper::DestroyPendingBuffers"); base::AutoLock auto_lock(*va_lock_); + DestroyPendingBuffers_Locked(); +} +void VaapiWrapper::DestroyPendingBuffers_Locked() { + TRACE_EVENT0("media,gpu", "VaapiWrapper::DestroyPendingBuffers_Locked"); + va_lock_->AssertAcquired(); for (const auto& pending_va_buf : pending_va_bufs_) { VAStatus va_res = vaDestroyBuffer(va_display_, pending_va_buf); VA_LOG_ON_ERROR(va_res, "vaDestroyBuffer failed"); @@ -1666,8 +1674,9 @@ } bool VaapiWrapper::ExecuteAndDestroyPendingBuffers(VASurfaceID va_surface_id) { - bool result = Execute(va_surface_id); - DestroyPendingBuffers(); + base::AutoLock auto_lock(*va_lock_); + bool result = Execute_Locked(va_surface_id); + DestroyPendingBuffers_Locked(); return result; } @@ -1711,7 +1720,9 @@ bool VaapiWrapper::UploadVideoFrameToSurface(const VideoFrame& frame, VASurfaceID va_surface_id) { + TRACE_EVENT0("media,gpu", "VaapiWrapper::UploadVideoFrameToSurface"); base::AutoLock auto_lock(*va_lock_); + TRACE_EVENT0("media,gpu", "VaapiWrapper::UploadVideoFrameToSurfaceLocked"); const gfx::Size size = frame.coded_size(); bool va_create_put_fallback = false; @@ -1785,7 +1796,9 @@ } bool VaapiWrapper::CreateVABuffer(size_t size, VABufferID* buffer_id) { + TRACE_EVENT0("media,gpu", "VaapiWrapper::CreateVABuffer"); base::AutoLock auto_lock(*va_lock_); + TRACE_EVENT0("media,gpu", "VaapiWrapper::CreateVABufferLocked"); VAStatus va_res = vaCreateBuffer(va_display_, va_context_id_, VAEncCodedBufferType, size, 1, NULL, buffer_id); @@ -1802,7 +1815,9 @@ size_t target_size, size_t* coded_data_size) { DCHECK(target_ptr); + TRACE_EVENT0("media,gpu", "VaapiWrapper::DownloadFromVABuffer"); base::AutoLock auto_lock(*va_lock_); + TRACE_EVENT0("media,gpu", "VaapiWrapper::DownloadFromVABufferLocked"); VAStatus va_res = vaSyncSurface(va_display_, sync_surface_id); VA_SUCCESS_OR_RETURN(va_res, "Failed syncing surface", false); @@ -1813,8 +1828,11 @@ auto* buffer_segment = reinterpret_cast<VACodedBufferSegment*>(mapping.data()); + // memcpy calls should be fast, unlocking and relocking for unmapping might + // cause another thread to acquire the lock and we'd have to wait delaying the + // notification that the encode is done. { - base::AutoUnlock auto_unlock(*va_lock_); + TRACE_EVENT0("media,gpu", "VaapiWrapper::DownloadFromVABufferCopyEncoded"); *coded_data_size = 0; while (buffer_segment) { @@ -1861,21 +1879,12 @@ return true; } -bool VaapiWrapper::DownloadAndDestroyVABuffer(VABufferID buffer_id, - VASurfaceID sync_surface_id, - uint8_t* target_ptr, - size_t target_size, - size_t* coded_data_size) { - bool result = DownloadFromVABuffer(buffer_id, sync_surface_id, target_ptr, - target_size, coded_data_size); - +void VaapiWrapper::DestroyVABuffer(VABufferID buffer_id) { base::AutoLock auto_lock(*va_lock_); VAStatus va_res = vaDestroyBuffer(va_display_, buffer_id); VA_LOG_ON_ERROR(va_res, "vaDestroyBuffer failed"); const auto was_found = va_buffers_.erase(buffer_id); DCHECK(was_found); - - return result; } void VaapiWrapper::DestroyVABuffers() { @@ -2176,6 +2185,12 @@ bool VaapiWrapper::Execute(VASurfaceID va_surface_id) { TRACE_EVENT0("media,gpu", "VaapiWrapper::Execute"); base::AutoLock auto_lock(*va_lock_); + return Execute_Locked(va_surface_id); +} + +bool VaapiWrapper::Execute_Locked(VASurfaceID va_surface_id) { + TRACE_EVENT0("media,gpu", "VaapiWrapper::Execute_Locked"); + va_lock_->AssertAcquired(); DVLOG(4) << "Pending VA bufs to commit: " << pending_va_bufs_.size(); DVLOG(4) << "Pending slice bufs to commit: " << pending_slice_bufs_.size();
diff --git a/media/gpu/vaapi/vaapi_wrapper.h b/media/gpu/vaapi/vaapi_wrapper.h index 27b3fe6..f0cbe42 100644 --- a/media/gpu/vaapi/vaapi_wrapper.h +++ b/media/gpu/vaapi/vaapi_wrapper.h
@@ -351,13 +351,8 @@ size_t target_size, size_t* coded_data_size); - // See DownloadFromVABuffer() for details. After downloading, it deletes - // the VA buffer with |buffer_id|. - bool DownloadAndDestroyVABuffer(VABufferID buffer_id, - VASurfaceID sync_surface_id, - uint8_t* target_ptr, - size_t target_size, - size_t* coded_data_size); + // Deletes the VA buffer identified by |buffer_id|. + void DestroyVABuffer(VABufferID buffer_id); // Destroy all previously-allocated (and not yet destroyed) buffers. void DestroyVABuffers(); @@ -410,6 +405,10 @@ // if vaapi driver refuses to accept parameter or slice buffers submitted // by client, or if execution fails in hardware. bool Execute(VASurfaceID va_surface_id); + bool Execute_Locked(VASurfaceID va_surface_id) + EXCLUSIVE_LOCKS_REQUIRED(va_lock_); + + void DestroyPendingBuffers_Locked() EXCLUSIVE_LOCKS_REQUIRED(va_lock_); // Attempt to set render mode to "render to texture.". Failure is non-fatal. void TryToSetVADisplayAttributeToLocalGPU();
diff --git a/media/mojo/services/video_decode_perf_history.cc b/media/mojo/services/video_decode_perf_history.cc index 744faf1..9a63156f 100644 --- a/media/mojo/services/video_decode_perf_history.cc +++ b/media/mojo/services/video_decode_perf_history.cc
@@ -17,7 +17,6 @@ #include "media/base/video_codecs.h" #include "media/capabilities/learning_helper.h" #include "media/mojo/mojom/media_types.mojom.h" -#include "mojo/public/cpp/bindings/strong_binding.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" @@ -75,11 +74,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } -void VideoDecodePerfHistory::BindRequest( - mojom::VideoDecodePerfHistoryRequest request) { +void VideoDecodePerfHistory::BindReceiver( + mojo::PendingReceiver<mojom::VideoDecodePerfHistory> receiver) { DVLOG(3) << __func__; DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - bindings_.AddBinding(this, std::move(request)); + receivers_.Add(this, std::move(receiver)); } void VideoDecodePerfHistory::InitDatabase() {
diff --git a/media/mojo/services/video_decode_perf_history.h b/media/mojo/services/video_decode_perf_history.h index 7ebf833..9024f4a 100644 --- a/media/mojo/services/video_decode_perf_history.h +++ b/media/mojo/services/video_decode_perf_history.h
@@ -19,7 +19,8 @@ #include "media/learning/impl/feature_provider.h" #include "media/mojo/mojom/video_decode_perf_history.mojom.h" #include "media/mojo/services/media_mojo_export.h" -#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver_set.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "ui/gfx/geometry/size.h" @@ -61,9 +62,10 @@ learning::FeatureProviderFactoryCB()); ~VideoDecodePerfHistory() override; - // Bind the mojo request to this instance. Single instance will be used to - // serve multiple requests. - void BindRequest(mojom::VideoDecodePerfHistoryRequest request); + // Bind the mojo receiver to this instance. Single instance will be used to + // serve multiple receivers. + void BindReceiver( + mojo::PendingReceiver<mojom::VideoDecodePerfHistory> receiver); // mojom::VideoDecodePerfHistory implementation: void GetPerfInfo(mojom::PredictionFeaturesPtr features, @@ -186,9 +188,9 @@ // completes. std::vector<base::OnceClosure> init_deferred_api_calls_; - // Maps bindings from several render-processes to this single browser-process + // Maps receivers from several render-processes to this single browser-process // service. - mojo::BindingSet<mojom::VideoDecodePerfHistory> bindings_; + mojo::ReceiverSet<mojom::VideoDecodePerfHistory> receivers_; // Optional helper for local learning. std::unique_ptr<LearningHelper> learning_helper_;
diff --git a/media/parsers/jpeg_parser.h b/media/parsers/jpeg_parser.h index bd054f5..c7998d1 100644 --- a/media/parsers/jpeg_parser.h +++ b/media/parsers/jpeg_parser.h
@@ -68,6 +68,7 @@ (kNumDcCodeWordsHuffVal * 2) + (kNumAcRunSizeBits * 2) + (kNumAcCodeWordsHuffVal * 2); constexpr size_t kJFIFApp0Size = 16; +constexpr size_t kJFIFApp1HeaderSize = 4; const size_t kJpegMaxHuffmanTableNumBaseline = 2; const size_t kJpegMaxComponents = 4;
diff --git a/mojo/public/cpp/bindings/associated_receiver.h b/mojo/public/cpp/bindings/associated_receiver.h index 170257f..1dfaf256 100644 --- a/mojo/public/cpp/bindings/associated_receiver.h +++ b/mojo/public/cpp/bindings/associated_receiver.h
@@ -200,6 +200,9 @@ // stimulus. void FlushForTesting() { binding_.FlushForTesting(); } + // Returns the interface implementation that was previously specified. + Interface* impl() { return binding_.impl(); } + // Allows test code to swap the interface implementation. ImplPointerType SwapImplForTesting(ImplPointerType new_impl) { return binding_.SwapImplForTesting(new_impl);
diff --git a/net/android/javatests/src/org/chromium/net/HttpUtilTest.java b/net/android/javatests/src/org/chromium/net/HttpUtilTest.java index 4bc208bd..6a08cbe 100644 --- a/net/android/javatests/src/org/chromium/net/HttpUtilTest.java +++ b/net/android/javatests/src/org/chromium/net/HttpUtilTest.java
@@ -13,7 +13,6 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.BaseJUnit4ClassRunner; import java.util.Arrays; @@ -45,7 +44,7 @@ private static final String ALLOWED_HEADER_VALUE = "value"; @Before - public void setUp() throws ProcessInitException { + public void setUp() { LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); }
diff --git a/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java b/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java index 07932f93..6fabece 100644 --- a/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java +++ b/net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerImpl.java
@@ -16,7 +16,6 @@ import org.chromium.base.annotations.JNINamespace; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.test.util.UrlUtils; import java.util.concurrent.Callable; @@ -69,12 +68,7 @@ // This is necessary as EmbeddedTestServerImpl is in a different process than the tests // using it, so it needs to initialize its own application context. ContextUtils.initApplicationContext(mContext.getApplicationContext()); - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); - } catch (ProcessInitException e) { - Log.e(TAG, "Failed to load native libraries.", e); - return false; - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_BROWSER); mHandlerThread = new HandlerThread("EmbeddedTestServer" + sCount.getAndIncrement()); mHandlerThread.start();
diff --git a/net/websockets/websocket_channel.cc b/net/websockets/websocket_channel.cc index 91ec901f..a9be7da5 100644 --- a/net/websockets/websocket_channel.cc +++ b/net/websockets/websocket_channel.cc
@@ -594,7 +594,9 @@ DCHECK(!event_interface_->HasPendingDataFrames()); // We've been waiting for the client to consume the frames before // responding to the closing handshake initiated by the server. - ignore_result(RespondToClosingHandshake()); + if (RespondToClosingHandshake() == CHANNEL_DELETED) { + return CHANNEL_DELETED; + } } // TODO(crbug.com/999235): Remove this CHECK.
diff --git a/printing/backend/cups_ipp_advanced_caps.cc b/printing/backend/cups_ipp_advanced_caps.cc index 44c8700..370d4704 100644 --- a/printing/backend/cups_ipp_advanced_caps.cc +++ b/printing/backend/cups_ipp_advanced_caps.cc
@@ -36,30 +36,19 @@ capabilities->emplace_back(); AdvancedCapability& capability = capabilities->back(); capability.name = attribute_name; -} - -void PopulateBooleanCapability(AdvancedCapability* capability, - bool default_value) { - // TODO(crbug.com/964919) Support checkbox in UI instead of making this - // two-value enum. - capability->values.emplace_back(); - capability->values.back().name = kOptionFalse; - capability->values.back().is_default = !default_value; - capability->values.emplace_back(); - capability->values.back().name = kOptionTrue; - capability->values.back().is_default = default_value; + capability.type = base::Value::Type::STRING; + // TODO(crbug.com/964919) Set defaults. } void BooleanHandler(const CupsOptionProvider& printer, const char* attribute_name, AdvancedCapabilities* capabilities) { - ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); - bool default_value = attr_default && ippGetBoolean(attr_default, 0); - capabilities->emplace_back(); AdvancedCapability& capability = capabilities->back(); capability.name = attribute_name; - PopulateBooleanCapability(&capability, default_value); + capability.type = base::Value::Type::BOOLEAN; + ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); + capability.default_value = attr_default && ippGetBoolean(attr_default, 0); } void KeywordHandler(const CupsOptionProvider& printer, @@ -69,17 +58,15 @@ if (!attr) return; - ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); - std::string default_value; - if (attr_default) { - const char* value = ippGetString(attr_default, 0, nullptr); - if (value) - default_value = value; - } - capabilities->emplace_back(); AdvancedCapability& capability = capabilities->back(); capability.name = attribute_name; + ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); + if (attr_default) { + const char* value = ippGetString(attr_default, 0, nullptr); + if (value) + capability.default_value = value; + } int num_values = ippGetCount(attr); for (int i = 0; i < num_values; i++) { const char* value = ippGetString(attr, i, nullptr); @@ -88,7 +75,6 @@ capability.values.emplace_back(); capability.values.back().name = value; - capability.values.back().is_default = default_value == value; } } @@ -99,18 +85,17 @@ if (!attr) return; - ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); - int default_value = attr_default ? ippGetInteger(attr_default, 0) : 0; - capabilities->emplace_back(); AdvancedCapability& capability = capabilities->back(); capability.name = attribute_name; + ipp_attribute_t* attr_default = printer.GetDefaultOptionValue(attribute_name); + capability.default_value = + base::NumberToString(attr_default ? ippGetInteger(attr_default, 0) : 0); int num_values = ippGetCount(attr); for (int i = 0; i < num_values; i++) { int value = ippGetInteger(attr, i); capability.values.emplace_back(); capability.values.back().name = base::NumberToString(value); - capability.values.back().is_default = default_value == value; } } @@ -133,9 +118,8 @@ AdvancedCapability& capability = capabilities->back(); capability.name = std::string(attribute_name) + "/" + base::NumberToString(value); - - // TODO(crbug.com/964919) Get correct defaults. - PopulateBooleanCapability(&capability, false); + capability.type = base::Value::Type::BOOLEAN; + // TODO(crbug.com/964919) Set defaults. } }
diff --git a/printing/backend/cups_ipp_constants.cc b/printing/backend/cups_ipp_constants.cc index b6b0eb4..b87c25c 100644 --- a/printing/backend/cups_ipp_constants.cc +++ b/printing/backend/cups_ipp_constants.cc
@@ -30,8 +30,8 @@ constexpr char kPinEncryptionNone[] = "none"; -constexpr char kOptionFalse[] = "no"; -constexpr char kOptionTrue[] = "yes"; +constexpr char kOptionFalse[] = "false"; +constexpr char kOptionTrue[] = "true"; #endif // defined(OS_CHROMEOS)
diff --git a/printing/backend/cups_ipp_util_unittest.cc b/printing/backend/cups_ipp_util_unittest.cc index c4a20cd..6c29db8 100644 --- a/printing/backend/cups_ipp_util_unittest.cc +++ b/printing/backend/cups_ipp_util_unittest.cc
@@ -268,9 +268,13 @@ EXPECT_EQ(6u, caps.advanced_capabilities.size()); EXPECT_EQ("ipp-attribute-fidelity", caps.advanced_capabilities[0].name); + EXPECT_EQ(base::Value::Type::BOOLEAN, caps.advanced_capabilities[0].type); EXPECT_EQ("finishings/7", caps.advanced_capabilities[1].name); + EXPECT_EQ(base::Value::Type::BOOLEAN, caps.advanced_capabilities[1].type); EXPECT_EQ("finishings/10", caps.advanced_capabilities[2].name); + EXPECT_EQ(base::Value::Type::BOOLEAN, caps.advanced_capabilities[2].type); EXPECT_EQ("job-name", caps.advanced_capabilities[3].name); + EXPECT_EQ(base::Value::Type::STRING, caps.advanced_capabilities[3].type); EXPECT_EQ("output-bin", caps.advanced_capabilities[4].name); EXPECT_EQ(2u, caps.advanced_capabilities[4].values.size()); EXPECT_EQ("print-quality", caps.advanced_capabilities[5].name);
diff --git a/printing/backend/print_backend.h b/printing/backend/print_backend.h index 12a1c3f..a19fc2c 100644 --- a/printing/backend/print_backend.h +++ b/printing/backend/print_backend.h
@@ -58,9 +58,6 @@ // Localized name for the value. std::string display_name; - - // True iff this is default value. - bool is_default = false; }; struct PRINTING_EXPORT AdvancedCapability { @@ -74,6 +71,12 @@ // Localized name for the attribute. std::string display_name; + // Attribute type. + base::Value::Type type; + + // Default value. + std::string default_value; + // Values for enumerated attributes. std::vector<AdvancedCapabilityValue> values; };
diff --git a/services/network/cors/preflight_controller.cc b/services/network/cors/preflight_controller.cc index c713aa8..cd651a8 100644 --- a/services/network/cors/preflight_controller.cc +++ b/services/network/cors/preflight_controller.cc
@@ -78,8 +78,8 @@ std::unique_ptr<ResourceRequest> preflight_request = std::make_unique<ResourceRequest>(); - // Algorithm step 1 through 4 of the CORS-preflight fetch, - // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0. + // Algorithm step 1 through 5 of the CORS-preflight fetch, + // https://fetch.spec.whatwg.org/#cors-preflight-fetch. preflight_request->url = request.url; preflight_request->method = "OPTIONS"; preflight_request->priority = request.priority; @@ -93,6 +93,9 @@ preflight_request->fetch_window_id = request.fetch_window_id; preflight_request->render_frame_id = request.render_frame_id; + preflight_request->headers.SetHeader(network::kAcceptHeader, + kDefaultAcceptHeader); + preflight_request->headers.SetHeader( header_names::kAccessControlRequestMethod, request.method); @@ -117,9 +120,6 @@ // Additional headers that the algorithm in the spec does not require, but // it's better that CORS preflight requests have them. preflight_request->headers.SetHeader("Sec-Fetch-Mode", "cors"); - // See also https://github.com/whatwg/fetch/issues/922 for kAcceptHeader. - preflight_request->headers.SetHeader(network::kAcceptHeader, - kDefaultAcceptHeader); return preflight_request; }
diff --git a/services/network/network_service_network_delegate.cc b/services/network/network_service_network_delegate.cc index 49407aa..bfa62eea 100644 --- a/services/network/network_service_network_delegate.cc +++ b/services/network/network_service_network_delegate.cc
@@ -50,26 +50,48 @@ NetworkServiceNetworkDelegate::~NetworkServiceNetworkDelegate() = default; +void NetworkServiceNetworkDelegate::MaybeTruncateReferrer( + net::URLRequest* const request, + const GURL& effective_url) { + if (!enable_referrers_) { + request->SetReferrer(std::string()); + return; + } + + if (base::FeatureList::IsEnabled( + features::kCapReferrerToOriginOnCrossOrigin)) { + url::Origin destination_origin = url::Origin::Create(effective_url); + url::Origin source_origin = url::Origin::Create(GURL(request->referrer())); + if (!destination_origin.IsSameOriginWith(source_origin)) + request->SetReferrer(source_origin.GetURL().spec()); + } +} + int NetworkServiceNetworkDelegate::OnBeforeURLRequest( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url) { - if (!enable_referrers_) - request->SetReferrer(std::string()); - NetworkService* network_service = network_context_->network_service(); - if (network_service) - network_service->OnBeforeURLRequest(); + DCHECK(request); - auto* loader = URLLoader::ForRequest(*request); - if (!loader) - return net::OK; + auto* const loader = URLLoader::ForRequest(*request); const GURL* effective_url = nullptr; - if (loader->new_redirect_url()) { + if (loader && loader->new_redirect_url()) { + DCHECK(new_url); *new_url = loader->new_redirect_url().value(); effective_url = new_url; } else { effective_url = &request->url(); } + + MaybeTruncateReferrer(request, *effective_url); + + NetworkService* network_service = network_context_->network_service(); + if (network_service) + network_service->OnBeforeURLRequest(); + + if (!loader) + return net::OK; + if (network_service) { loader->SetAllowReportingRawHeaders(network_service->HasRawHeadersAccess( loader->GetProcessId(), *effective_url));
diff --git a/services/network/network_service_network_delegate.h b/services/network/network_service_network_delegate.h index f2b64266..8e70eb2 100644 --- a/services/network/network_service_network_delegate.h +++ b/services/network/network_service_network_delegate.h
@@ -92,6 +92,12 @@ void ForwardProxyErrors(int net_error); + // Truncates the given request's referrer if required by + // related configuration (for instance, the enable_referrers_ + // attribute or pertinent features/flags) + void MaybeTruncateReferrer(net::URLRequest* request, + const GURL& effective_url); + bool enable_referrers_; bool validate_referrer_policy_on_initial_request_; mojom::ProxyErrorClientPtr proxy_error_client_;
diff --git a/services/network/public/cpp/features.cc b/services/network/public/cpp/features.cc index b2e0fbd..45f2f98 100644 --- a/services/network/public/cpp/features.cc +++ b/services/network/public/cpp/features.cc
@@ -9,6 +9,11 @@ namespace network { namespace features { +// When kCapReferrerToOriginOnCrossOrigin is enabled, HTTP referrers on cross- +// origin requests are restricted to contain at most the source origin. +const base::Feature kCapReferrerToOriginOnCrossOrigin{ + "CapReferrerToOriginOnCrossOrigin", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables Expect CT reporting, which sends reports for opted-in sites // that don't serve sufficient Certificate Transparency information. const base::Feature kExpectCTReporting{"ExpectCTReporting",
diff --git a/services/network/public/cpp/features.h b/services/network/public/cpp/features.h index 5d48305..0aaccb9 100644 --- a/services/network/public/cpp/features.h +++ b/services/network/public/cpp/features.h
@@ -13,6 +13,8 @@ namespace features { COMPONENT_EXPORT(NETWORK_CPP) +extern const base::Feature kCapReferrerToOriginOnCrossOrigin; +COMPONENT_EXPORT(NETWORK_CPP) extern const base::Feature kExpectCTReporting; COMPONENT_EXPORT(NETWORK_CPP) extern const base::Feature kNetworkErrorLogging;
diff --git a/services/network/websocket_throttler.h b/services/network/websocket_throttler.h index 510c057..fa6fbac1 100644 --- a/services/network/websocket_throttler.h +++ b/services/network/websocket_throttler.h
@@ -47,9 +47,7 @@ ~WebSocketPerProcessThrottler(); // Returns if there are too many pending connections. - bool HasTooManyPendingConnections() const { - return num_pending_connections_ >= kMaxPendingWebSocketConnections; - } + bool HasTooManyPendingConnections() const { return false; } // Returns the delay which should be used to throttle opening websocket // connections.
diff --git a/services/network/websocket_throttler_unittest.cc b/services/network/websocket_throttler_unittest.cc index 0d8b332..4194db5 100644 --- a/services/network/websocket_throttler_unittest.cc +++ b/services/network/websocket_throttler_unittest.cc
@@ -107,7 +107,7 @@ EXPECT_EQ(base::TimeDelta(), throttler.CalculateDelay()); } -TEST(WebSocketPerProcessThrottlerTest, TooManyPendingConnections) { +TEST(WebSocketPerProcessThrottlerTest, DISABLED_TooManyPendingConnections) { constexpr int limit = 255; WebSocketPerProcessThrottler throttler; @@ -312,7 +312,7 @@ EXPECT_EQ(0u, throttler.GetSizeForTesting()); } -TEST_F(WebSocketThrottlerTest, TooManyPendingConnections) { +TEST_F(WebSocketThrottlerTest, DISABLED_TooManyPendingConnections) { constexpr int process1 = 1; constexpr int process2 = 2; constexpr int limit = 255;
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 95b561b3..07dc766 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -198,9 +198,6 @@ const base::Feature kServiceWorkerImportedScriptUpdateCheck{ "ServiceWorkerImportedScriptUpdateCheck", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kServiceWorkerAggressiveCodeCache{ - "ServiceWorkerAggressiveCodeCache", base::FEATURE_DISABLED_BY_DEFAULT}; - // Experiment of the delay from navigation to starting an update of a service // worker's script. const base::Feature kServiceWorkerUpdateDelay{
diff --git a/third_party/blink/common/service_worker/service_worker_utils.cc b/third_party/blink/common/service_worker/service_worker_utils.cc index a8c0702e..a8d0803 100644 --- a/third_party/blink/common/service_worker/service_worker_utils.cc +++ b/third_party/blink/common/service_worker/service_worker_utils.cc
@@ -5,37 +5,13 @@ #include "third_party/blink/public/common/service_worker/service_worker_utils.h" #include "base/feature_list.h" -#include "base/metrics/field_trial_params.h" #include "third_party/blink/public/common/features.h" namespace blink { -const char kServiceWorkerEagerCodeCacheStrategy[] = "sw_cache_strategy"; - -namespace { - -constexpr base::FeatureParam<EagerCodeCacheStrategy>::Option - kEagerCodeCacheStrategyOptions[] = { - {EagerCodeCacheStrategy::kDontGenerate, "dontgenerate"}, - {EagerCodeCacheStrategy::kDuringInstallEvent, "installevent"}, - {EagerCodeCacheStrategy::kOnIdleTask, "idletask"}, -}; - -constexpr base::FeatureParam<EagerCodeCacheStrategy> - kEagerCodeCacheStrategyParam{&features::kServiceWorkerAggressiveCodeCache, - "sw_cache_strategy", - EagerCodeCacheStrategy::kDuringInstallEvent, - &kEagerCodeCacheStrategyOptions}; - -} // namespace - bool ServiceWorkerUtils::IsImportedScriptUpdateCheckEnabled() { return base::FeatureList::IsEnabled( blink::features::kServiceWorkerImportedScriptUpdateCheck); } -EagerCodeCacheStrategy ServiceWorkerUtils::GetEagerCodeCacheStrategy() { - return kEagerCodeCacheStrategyParam.Get(); -} - } // namespace blink
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 908f1f4..4e3c03df 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -59,8 +59,6 @@ kServiceWorkerIsolateInForeground; BLINK_COMMON_EXPORT extern const base::Feature kServiceWorkerImportedScriptUpdateCheck; -BLINK_COMMON_EXPORT extern const base::Feature - kServiceWorkerAggressiveCodeCache; BLINK_COMMON_EXPORT extern const base::Feature kServiceWorkerUpdateDelay; BLINK_COMMON_EXPORT extern const base::Feature kStopInBackground; BLINK_COMMON_EXPORT extern const base::Feature
diff --git a/third_party/blink/public/mojom/badging/badging.mojom b/third_party/blink/public/mojom/badging/badging.mojom index 3b7e10ae..4d0296b9 100644 --- a/third_party/blink/public/mojom/badging/badging.mojom +++ b/third_party/blink/public/mojom/badging/badging.mojom
@@ -20,12 +20,8 @@ // Interface for handling badge messages from frames and subframes. interface BadgeService { // Asks the browser process to set a badge. - // |scope| specifies which badges to set. Note: This must be on the same - // origin as the caller. - SetBadge(url.mojom.Url scope, BadgeValue value); + SetBadge(BadgeValue value); // Asks the browser to clear a badge. - // |scope| specifies the badges to clear. Note: This must be on the same - // origin as the caller. - ClearBadge(url.mojom.Url scope); + ClearBadge(); };
diff --git a/third_party/blink/public/mojom/cache_storage/cache_storage.mojom b/third_party/blink/public/mojom/cache_storage/cache_storage.mojom index 48abbf1..ffac72e 100644 --- a/third_party/blink/public/mojom/cache_storage/cache_storage.mojom +++ b/third_party/blink/public/mojom/cache_storage/cache_storage.mojom
@@ -5,11 +5,9 @@ module blink.mojom; import "mojo/public/mojom/base/read_only_buffer.mojom"; -import "mojo/public/mojom/base/time.mojom"; import "third_party/blink/public/mojom/fetch/fetch_api_response.mojom"; import "third_party/blink/public/mojom/fetch/fetch_api_request.mojom"; import "mojo/public/mojom/base/string16.mojom"; -import "url/mojom/url.mojom"; // This enum is used in histograms, so do not change the ordering and always // append new types to the end. @@ -119,11 +117,6 @@ // Perform a batch of operations, used for PUT and DELETE operations. Batch(array<BatchOperation> batch_operations, int64 trace_id) => (CacheStorageVerboseError result); - - // Sets |side_data| if there is an entry of which key is |url| and the entry - // has the same |response_time|. - SetSideData(url.mojom.Url url, mojo_base.mojom.Time response_time, - mojo_base.mojom.ReadOnlyBuffer side_data, int64 trace_id) => (CacheStorageError result); }; // Handles global CacheStorage methods, directly relates to methods available on
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 6352206..e118839 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -2421,6 +2421,11 @@ kXRIsSessionSupported = 3036, kScrollbarUseScrollbarButtonReversedDirection = 3037, kCSSSelectorPseudoScrollbarButtonReversedDirection = 3038, + kFragmentHasTildeAmpersandTilde = 3039, + kFragmentHasColonTildeColon = 3040, + kFragmentHasTildeAtTilde = 3041, + kFragmentHasAmpersandDelimiterQuestion = 3042, + kInvalidFragmentDirective = 3043, // 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/renderer/bindings/core/v8/script_value.cc b/third_party/blink/renderer/bindings/core/v8/script_value.cc index ee44862..ed52b29 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_value.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_value.cc
@@ -41,7 +41,7 @@ return v8::Local<v8::Value>(); DCHECK(GetIsolate()->InContext()); - return value_.Get(ScriptState::From(isolate_->GetCurrentContext())); + return value_->Get(ScriptState::From(isolate_->GetCurrentContext())); } v8::Local<v8::Value> ScriptValue::V8ValueFor( @@ -49,7 +49,7 @@ if (IsEmpty()) return v8::Local<v8::Value>(); - return value_.GetAcrossWorld(target_script_state); + return value_->GetAcrossWorld(target_script_state); } bool ScriptValue::ToString(String& result) const {
diff --git a/third_party/blink/renderer/bindings/core/v8/script_value.h b/third_party/blink/renderer/bindings/core/v8/script_value.h index 32983aa3..0ea8da2 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_value.h +++ b/third_party/blink/renderer/bindings/core/v8/script_value.h
@@ -73,12 +73,12 @@ // TODO(rikaf): Forbid passing empty v8::Local<v8::Value> to ScriptValue's // ctor. - ScriptValue(v8::Isolate* isolate, v8::Local<v8::Value> value) : isolate_(isolate), value_(value.IsEmpty() - ? WorldSafeV8Reference<v8::Value>() - : WorldSafeV8Reference<v8::Value>(isolate, value)) { + ? MakeGarbageCollected<WorldSafeV8ReferenceWrapper>() + : MakeGarbageCollected<WorldSafeV8ReferenceWrapper>(isolate, + value)) { DCHECK(isolate_); } @@ -86,30 +86,17 @@ ScriptValue(v8::Isolate* isolate, v8::MaybeLocal<T> value) : isolate_(isolate), value_(value.IsEmpty() - ? WorldSafeV8Reference<v8::Value>() - : WorldSafeV8Reference<v8::Value>(isolate, - value.ToLocalChecked())) { + ? MakeGarbageCollected<WorldSafeV8ReferenceWrapper>() + : MakeGarbageCollected<WorldSafeV8ReferenceWrapper>( + isolate, + value.ToLocalChecked())) { DCHECK(isolate_); } - ScriptValue(v8::Isolate* isolate, WorldSafeV8Reference<v8::Value> value) - : isolate_(isolate), value_(value) { - DCHECK(isolate_); - } + ScriptValue(const ScriptValue& value) = default; - ScriptValue(const ScriptValue& value) { - // TODO(crbug.com/v8/9773): Deal with null value at the side of v8. - if (value.IsEmpty()) { - isolate_ = nullptr; - value_.Reset(); - } else { - isolate_ = value.isolate_; - value_ = value.value_; - DCHECK(isolate_); - } - } - - // Use this GetIsolate() to do DCHECK inside ScriptValue. + // TODO(riakf): Use this GetIsolate() only when doing DCHECK inside + // ScriptValue. v8::Isolate* GetIsolate() const { DCHECK(isolate_); return isolate_; @@ -118,7 +105,11 @@ ScriptValue& operator=(const ScriptValue& value) = default; bool operator==(const ScriptValue& value) const { - return value_ == value.value_; + if (IsEmpty()) + return value.IsEmpty(); + if (value.IsEmpty()) + return false; + return *value_ == *value.value_; } bool operator!=(const ScriptValue& value) const { return !operator==(value); } @@ -155,11 +146,11 @@ return !value.IsEmpty() && value->IsObject(); } - bool IsEmpty() const { return value_.IsEmpty(); } + bool IsEmpty() const { return !value_ || value_->IsEmpty(); } void Clear() { isolate_ = nullptr; - value_.Reset(); + value_.Clear(); } v8::Local<v8::Value> V8Value() const; @@ -168,10 +159,6 @@ // this "clones" the v8 value and returns it. v8::Local<v8::Value> V8ValueFor(ScriptState*) const; - const WorldSafeV8Reference<v8::Value>& ToWorldSafeV8Reference() const { - return value_; - } - bool ToString(String&) const; static ScriptValue CreateNull(v8::Isolate*); @@ -179,8 +166,41 @@ void Trace(Visitor* visitor) { visitor->Trace(value_); } private: + // WorldSafeV8ReferenceWrapper wraps a WorldSafeV8Reference so that it can be + // used on both the stack and heaps. WorldSafeV8Reference cannot be used on + // the stack because the conservative scanning does not know how to trace + // TraceWrapperV8Reference. + class CORE_EXPORT WorldSafeV8ReferenceWrapper + : public GarbageCollected<WorldSafeV8ReferenceWrapper> { + public: + WorldSafeV8ReferenceWrapper() = default; + WorldSafeV8ReferenceWrapper(v8::Isolate* isolate, + v8::Local<v8::Value> value) + : value_(isolate, value) {} + + virtual ~WorldSafeV8ReferenceWrapper() = default; + void Trace(blink::Visitor* visitor) { visitor->Trace(value_); } + + v8::Local<v8::Value> Get(ScriptState* script_state) const { + return value_.Get(script_state); + } + + v8::Local<v8::Value> GetAcrossWorld(ScriptState* script_state) const { + return value_.GetAcrossWorld(script_state); + } + + bool IsEmpty() const { return value_.IsEmpty(); } + + bool operator==(const WorldSafeV8ReferenceWrapper& other) const { + return value_ == other.value_; + } + + private: + WorldSafeV8Reference<v8::Value> value_; + }; + v8::Isolate* isolate_ = nullptr; - WorldSafeV8Reference<v8::Value> value_; + Member<WorldSafeV8ReferenceWrapper> value_; }; template <>
diff --git a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc index 310104e..ca5eeb3 100644 --- a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.cc
@@ -125,7 +125,10 @@ ToInterpolableList(underlying.interpolable_value.get()); conversion_checkers.push_back( std::make_unique<UnderlyingFilterListChecker>(interpolable_list)); - return InterpolationValue(underlying.interpolable_value->CloneAndZero()); + // The neutral value for composition for a filter list is the empty list, as + // the additive operator is concatenation, so concat(underlying, []) == + // underlying. + return InterpolationValue(std::make_unique<InterpolableList>(0)); } InterpolationValue CSSFilterListInterpolationType::MaybeConvertInitial( @@ -232,45 +235,9 @@ double underlying_fraction, const InterpolationValue& value, double interpolation_fraction) const { - // TODO(crbug.com/1005828): The below behavior is not correct for addition of - // filter values. Additive composition is defined as list concatenation in the - // spec: https://drafts.fxtf.org/filter-effects-1/#addition - InterpolableList& underlying_list = - ToInterpolableList(*underlying_value_owner.Value().interpolable_value); - const InterpolableList& interpolable_list = - ToInterpolableList(*value.interpolable_value); - wtf_size_t underlying_length = underlying_list.length(); - wtf_size_t length = interpolable_list.length(); - - for (wtf_size_t i = 0; i < underlying_length && i < length; i++) { - if (To<InterpolableFilter>(interpolable_list.Get(i))->GetType() != - To<InterpolableFilter>(underlying_list.Get(i))->GetType()) { - underlying_value_owner.Set(*this, value); - return; - } - } - - for (wtf_size_t i = 0; i < length && i < underlying_length; i++) { - underlying_list.GetMutable(i)->ScaleAndAdd(underlying_fraction, - *interpolable_list.Get(i)); - } - - if (length <= underlying_length) - return; - - auto extended_interpolable_list = std::make_unique<InterpolableList>(length); - for (wtf_size_t i = 0; i < length; i++) { - if (i < underlying_length) { - extended_interpolable_list->Set(i, - std::move(underlying_list.GetMutable(i))); - } else { - extended_interpolable_list->Set(i, interpolable_list.Get(i)->Clone()); - } - } - underlying_value_owner.MutableValue().interpolable_value = - std::move(extended_interpolable_list); - underlying_value_owner.MutableValue().non_interpolable_value = - value.non_interpolable_value; + // We do our compositing behavior in |PreInterpolationCompositeIfNeeded|; see + // the documentation on that method. + underlying_value_owner.Set(*this, value); } void CSSFilterListInterpolationType::ApplyStandardPropertyValue( @@ -291,4 +258,90 @@ SetFilterList(CssProperty(), *state.Style(), std::move(filter_operations)); } +InterpolationValue +CSSFilterListInterpolationType::PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation composite) const { + DCHECK(!value.non_interpolable_value); + DCHECK(!underlying.non_interpolable_value); + + // By default, the interpolation stack attempts to optimize composition by + // doing it after interpolation. This does not work in the case of filter + // lists, as they have a composition behavior of concatenation. To work around + // that, we perform our composition in PreInterpolationCompositeIfNeeded + // (which runs before interpolation), and then make Composite a simple + // replacement with the resultant value. + + // The underlying value can be nullptr, most commonly if it contains a url(). + // TODO(crbug.com/1009229): Properly handle url() in filter composite. + if (!underlying.interpolable_value) + return nullptr; + + auto interpolable_list = std::unique_ptr<InterpolableList>( + ToInterpolableList(value.interpolable_value.release())); + const InterpolableList& underlying_list = + ToInterpolableList(*underlying.interpolable_value); + + if (composite == EffectModel::CompositeOperation::kCompositeAdd) { + return PerformAdditiveComposition(std::move(interpolable_list), + underlying_list); + } + DCHECK_EQ(composite, EffectModel::CompositeOperation::kCompositeAccumulate); + return PerformAccumulativeComposition(std::move(interpolable_list), + underlying_list); +} + +InterpolationValue CSSFilterListInterpolationType::PerformAdditiveComposition( + std::unique_ptr<InterpolableList> interpolable_list, + const InterpolableList& underlying_list) const { + // Per the spec, addition of filter lists is defined as concatenation. + // https://drafts.fxtf.org/filter-effects-1/#addition + auto composited_list = std::make_unique<InterpolableList>( + underlying_list.length() + interpolable_list->length()); + for (wtf_size_t i = 0; i < composited_list->length(); i++) { + if (i < underlying_list.length()) { + composited_list->Set(i, underlying_list.Get(i)->Clone()); + } else { + composited_list->Set( + i, interpolable_list->Get(i - underlying_list.length())->Clone()); + } + } + return InterpolationValue(std::move(composited_list)); +} + +InterpolationValue +CSSFilterListInterpolationType::PerformAccumulativeComposition( + std::unique_ptr<InterpolableList> interpolable_list, + const InterpolableList& underlying_list) const { + // Per the spec, accumulation of filter lists operates on pairwise addition of + // the underlying components. + // https://drafts.fxtf.org/filter-effects-1/#accumulation + wtf_size_t length = interpolable_list->length(); + wtf_size_t underlying_length = underlying_list.length(); + + // If any of the types don't match, fallback to replace behavior. + for (wtf_size_t i = 0; i < underlying_length && i < length; i++) { + if (To<InterpolableFilter>(underlying_list.Get(i))->GetType() != + To<InterpolableFilter>(interpolable_list->Get(i))->GetType()) + return InterpolationValue(std::move(interpolable_list)); + } + + // Otherwise, arithmetically combine the matching prefix of the lists then + // concatenate the remainder of the longer one. + wtf_size_t max_length = std::max(length, underlying_length); + auto composited_list = std::make_unique<InterpolableList>(max_length); + for (wtf_size_t i = 0; i < max_length; i++) { + if (i < underlying_length) { + composited_list->Set(i, underlying_list.Get(i)->Clone()); + if (i < length) + composited_list->GetMutable(i)->Add(*interpolable_list->Get(i)); + } else { + composited_list->Set(i, interpolable_list->Get(i)->Clone()); + } + } + + return InterpolationValue(std::move(composited_list)); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.h b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.h index 8fac1a7..1b5175e 100644 --- a/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.h
@@ -26,6 +26,10 @@ void ApplyStandardPropertyValue(const InterpolableValue&, const NonInterpolableValue*, StyleResolverState&) const final; + InterpolationValue PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const final; private: InterpolationValue MaybeConvertNeutral(const InterpolationValue& underlying, @@ -37,6 +41,16 @@ InterpolationValue MaybeConvertValue(const CSSValue&, const StyleResolverState*, ConversionCheckers&) const final; + + // Helper methods to perform either additive or accumulative composition, as + // defined in https://drafts.fxtf.org/filter-effects-1/#addition and + // https://drafts.fxtf.org/filter-effects-1/#accumulation + InterpolationValue PerformAdditiveComposition( + std::unique_ptr<InterpolableList> interpolable_list, + const InterpolableList& underlying_list) const; + InterpolationValue PerformAccumulativeComposition( + std::unique_ptr<InterpolableList> interpolable_list, + const InterpolableList& underlying_list) const; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/css_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_interpolation_type.cc index 3893bf8..cc295d2 100644 --- a/third_party/blink/renderer/core/animation/css_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_interpolation_type.cc
@@ -141,7 +141,8 @@ keyframe, environment, underlying, conversion_checkers); if (result && keyframe.Composite() != EffectModel::CompositeOperation::kCompositeReplace) { - return MakeAdditive(std::move(result)); + return PreInterpolationCompositeIfNeeded(std::move(result), underlying, + keyframe.Composite()); } return result; }
diff --git a/third_party/blink/renderer/core/animation/css_interpolation_type.h b/third_party/blink/renderer/core/animation/css_interpolation_type.h index 0c84cded9..d1a73bb4 100644 --- a/third_party/blink/renderer/core/animation/css_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_interpolation_type.h
@@ -63,7 +63,18 @@ const InterpolationValue& underlying, ConversionCheckers&) const final; - virtual InterpolationValue MakeAdditive(InterpolationValue value) const { + // The interpolation stack has an optimization where we perform compositing + // after interpolation. This is against spec, but it works for simple addition + // cases and halves the amount of computation needed. Some types require + // compositing before interpolation (e.g. if their composition operator is a + // concatenation), however, and for those we define this method that is called + // pre-interpolation. + // TODO(crbug.com/1009230): Revisit the post-interpolation composite + // optimization. + virtual InterpolationValue PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation composite) const { return value; }
diff --git a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc index cd0c029..c386274 100644 --- a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.cc
@@ -212,8 +212,11 @@ OptionalRotation(StyleBuilderConverter::ConvertRotation(value))); } -InterpolationValue CSSRotateInterpolationType::MakeAdditive( - InterpolationValue value) const { +InterpolationValue +CSSRotateInterpolationType::PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const { value.non_interpolable_value = CSSRotateNonInterpolableValue::CreateAdditive( ToCSSRotateNonInterpolableValue(*value.non_interpolable_value)); return value;
diff --git a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.h b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.h index 16096fc..48ff343 100644 --- a/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_rotate_interpolation_type.h
@@ -39,7 +39,10 @@ InterpolationValue MaybeConvertValue(const CSSValue&, const StyleResolverState*, ConversionCheckers&) const final; - InterpolationValue MakeAdditive(InterpolationValue) const final; + InterpolationValue PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const final; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc index 1efebb67..9827d58a 100644 --- a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc
@@ -193,8 +193,10 @@ } } -InterpolationValue CSSScaleInterpolationType::MakeAdditive( - InterpolationValue value) const { +InterpolationValue CSSScaleInterpolationType::PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const { value.non_interpolable_value = CSSScaleNonInterpolableValue::CreateAdditive( ToCSSScaleNonInterpolableValue(*value.non_interpolable_value)); return value;
diff --git a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.h b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.h index c570dd16c..2f05855 100644 --- a/third_party/blink/renderer/core/animation/css_scale_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_scale_interpolation_type.h
@@ -36,7 +36,10 @@ InterpolationValue MaybeConvertValue(const CSSValue&, const StyleResolverState*, ConversionCheckers&) const final; - InterpolationValue MakeAdditive(InterpolationValue) const final; + InterpolationValue PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const final; PairwiseInterpolationValue MaybeMergeSingles( InterpolationValue&&,
diff --git a/third_party/blink/renderer/core/animation/css_transform_interpolation_type.cc b/third_party/blink/renderer/core/animation/css_transform_interpolation_type.cc index a46ed6c..eb2fd9f1 100644 --- a/third_party/blink/renderer/core/animation/css_transform_interpolation_type.cc +++ b/third_party/blink/renderer/core/animation/css_transform_interpolation_type.cc
@@ -250,8 +250,11 @@ return ConvertTransform(std::move(transform)); } -InterpolationValue CSSTransformInterpolationType::MakeAdditive( - InterpolationValue value) const { +InterpolationValue +CSSTransformInterpolationType::PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const { value.non_interpolable_value = CSSTransformNonInterpolableValue::CreateAdditive( ToCSSTransformNonInterpolableValue(*value.non_interpolable_value));
diff --git a/third_party/blink/renderer/core/animation/css_transform_interpolation_type.h b/third_party/blink/renderer/core/animation/css_transform_interpolation_type.h index b2ec86080..d781cad 100644 --- a/third_party/blink/renderer/core/animation/css_transform_interpolation_type.h +++ b/third_party/blink/renderer/core/animation/css_transform_interpolation_type.h
@@ -39,7 +39,10 @@ InterpolationValue MaybeConvertValue(const CSSValue&, const StyleResolverState*, ConversionCheckers&) const final; - InterpolationValue MakeAdditive(InterpolationValue) const final; + InterpolationValue PreInterpolationCompositeIfNeeded( + InterpolationValue value, + const InterpolationValue& underlying, + EffectModel::CompositeOperation) const final; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/animation/interpolable_filter.cc b/third_party/blink/renderer/core/animation/interpolable_filter.cc index 2b23c11..7c3c084 100644 --- a/third_party/blink/renderer/core/animation/interpolable_filter.cc +++ b/third_party/blink/renderer/core/animation/interpolable_filter.cc
@@ -208,10 +208,30 @@ } } +void InterpolableFilter::Add(const InterpolableValue& other) { + value_->Add(*To<InterpolableFilter>(other).value_); + // The following types have an initial value of 1, so addition for them is + // one-based: result = value_ + other.value_ - 1 + switch (type_) { + case FilterOperation::BRIGHTNESS: + case FilterOperation::CONTRAST: + case FilterOperation::GRAYSCALE: + case FilterOperation::INVERT: + case FilterOperation::OPACITY: + case FilterOperation::SATURATE: + case FilterOperation::SEPIA: + value_->Add(*std::make_unique<InterpolableNumber>(-1)); + break; + default: + break; + } +} + void InterpolableFilter::AssertCanInterpolateWith( const InterpolableValue& other) const { - DCHECK(other.IsFilter()); - DCHECK_EQ(type_, To<InterpolableFilter>(other).type_); + const InterpolableFilter& other_filter = To<InterpolableFilter>(other); + value_->AssertCanInterpolateWith(*other_filter.value_); + DCHECK_EQ(type_, other_filter.type_); } void InterpolableFilter::Interpolate(const InterpolableValue& to,
diff --git a/third_party/blink/renderer/core/animation/interpolable_filter.h b/third_party/blink/renderer/core/animation/interpolable_filter.h index a3f268f8..07b20a5 100644 --- a/third_party/blink/renderer/core/animation/interpolable_filter.h +++ b/third_party/blink/renderer/core/animation/interpolable_filter.h
@@ -50,9 +50,7 @@ return false; } void Scale(double scale) final { NOTREACHED(); } - void ScaleAndAdd(double scale, const InterpolableValue& other) final { - value_->ScaleAndAdd(scale, *To<InterpolableFilter>(other).value_); - } + void Add(const InterpolableValue& other) final; void AssertCanInterpolateWith(const InterpolableValue& other) const final; private:
diff --git a/third_party/blink/renderer/core/animation/interpolable_length.cc b/third_party/blink/renderer/core/animation/interpolable_length.cc index 30f9484..08e6cc60 100644 --- a/third_party/blink/renderer/core/animation/interpolable_length.cc +++ b/third_party/blink/renderer/core/animation/interpolable_length.cc
@@ -306,6 +306,23 @@ expression_, NumberNode(scale), CSSMathOperator::kMultiply)); } +void InterpolableLength::Add(const InterpolableValue& other) { + const InterpolableLength& other_length = To<InterpolableLength>(other); + if (IsLengthArray() && other_length.IsLengthArray()) { + for (wtf_size_t i = 0; i < length_array_.values.size(); ++i) { + length_array_.values[i] = + length_array_.values[i] + other_length.length_array_.values[i]; + } + length_array_.type_flags |= other_length.length_array_.type_flags; + return; + } + + CSSMathExpressionNode* result = + CSSMathExpressionBinaryOperation::CreateSimplified( + &AsExpression(), &other_length.AsExpression(), CSSMathOperator::kAdd); + SetExpression(*result); +} + void InterpolableLength::ScaleAndAdd(double scale, const InterpolableValue& other) { const InterpolableLength& other_length = To<InterpolableLength>(other);
diff --git a/third_party/blink/renderer/core/animation/interpolable_length.h b/third_party/blink/renderer/core/animation/interpolable_length.h index 071d604..02ce930 100644 --- a/third_party/blink/renderer/core/animation/interpolable_length.h +++ b/third_party/blink/renderer/core/animation/interpolable_length.h
@@ -66,6 +66,8 @@ return false; } void Scale(double scale) final; + void Add(const InterpolableValue& other) final; + // We override this to avoid two passes in the case of LengthArrays. void ScaleAndAdd(double scale, const InterpolableValue& other) final; void AssertCanInterpolateWith(const InterpolableValue& other) const final;
diff --git a/third_party/blink/renderer/core/animation/interpolable_shadow.cc b/third_party/blink/renderer/core/animation/interpolable_shadow.cc index 9aa7e20..37e48c4 100644 --- a/third_party/blink/renderer/core/animation/interpolable_shadow.cc +++ b/third_party/blink/renderer/core/animation/interpolable_shadow.cc
@@ -166,14 +166,13 @@ color_->Scale(scale); } -void InterpolableShadow::ScaleAndAdd(double scale, - const InterpolableValue& other) { +void InterpolableShadow::Add(const InterpolableValue& other) { const InterpolableShadow& other_shadow = To<InterpolableShadow>(other); - x_->ScaleAndAdd(scale, *other_shadow.x_); - y_->ScaleAndAdd(scale, *other_shadow.y_); - blur_->ScaleAndAdd(scale, *other_shadow.blur_); - spread_->ScaleAndAdd(scale, *other_shadow.spread_); - color_->ScaleAndAdd(scale, *other_shadow.color_); + x_->Add(*other_shadow.x_); + y_->Add(*other_shadow.y_); + blur_->Add(*other_shadow.blur_); + spread_->Add(*other_shadow.spread_); + color_->Add(*other_shadow.color_); } void InterpolableShadow::AssertCanInterpolateWith(
diff --git a/third_party/blink/renderer/core/animation/interpolable_shadow.h b/third_party/blink/renderer/core/animation/interpolable_shadow.h index 6bcc378..bdc200f 100644 --- a/third_party/blink/renderer/core/animation/interpolable_shadow.h +++ b/third_party/blink/renderer/core/animation/interpolable_shadow.h
@@ -65,7 +65,7 @@ return false; } void Scale(double scale) final; - void ScaleAndAdd(double scale, const InterpolableValue& other) final; + void Add(const InterpolableValue& other) final; void AssertCanInterpolateWith(const InterpolableValue& other) const final; private:
diff --git a/third_party/blink/renderer/core/animation/interpolable_value.cc b/third_party/blink/renderer/core/animation/interpolable_value.cc index 504f7aa..272c70d 100644 --- a/third_party/blink/renderer/core/animation/interpolable_value.cc +++ b/third_party/blink/renderer/core/animation/interpolable_value.cc
@@ -79,9 +79,15 @@ values_[i]->Scale(scale); } -void InterpolableNumber::ScaleAndAdd(double scale, - const InterpolableValue& other) { - value_ = value_ * scale + ToInterpolableNumber(other).value_; +void InterpolableNumber::Add(const InterpolableValue& other) { + value_ += ToInterpolableNumber(other).value_; +} + +void InterpolableList::Add(const InterpolableValue& other) { + const InterpolableList& other_list = ToInterpolableList(other); + DCHECK_EQ(other_list.length(), length()); + for (wtf_size_t i = 0; i < length(); i++) + values_[i]->Add(*other_list.values_[i]); } void InterpolableList::ScaleAndAdd(double scale,
diff --git a/third_party/blink/renderer/core/animation/interpolable_value.h b/third_party/blink/renderer/core/animation/interpolable_value.h index 2353b3a..6d0df845 100644 --- a/third_party/blink/renderer/core/animation/interpolable_value.h +++ b/third_party/blink/renderer/core/animation/interpolable_value.h
@@ -44,7 +44,13 @@ // TODO(alancutter): Remove Equals(). virtual bool Equals(const InterpolableValue&) const = 0; virtual void Scale(double scale) = 0; - virtual void ScaleAndAdd(double scale, const InterpolableValue& other) = 0; + virtual void Add(const InterpolableValue& other) = 0; + // The default implementation should be sufficient for most types, but + // subclasses can override this to be more efficient if they chose. + virtual void ScaleAndAdd(double scale, const InterpolableValue& other) { + Scale(scale); + Add(other); + } virtual void AssertCanInterpolateWith( const InterpolableValue& other) const = 0; @@ -81,7 +87,7 @@ bool IsNumber() const final { return true; } bool Equals(const InterpolableValue& other) const final; void Scale(double scale) final; - void ScaleAndAdd(double scale, const InterpolableValue& other) final; + void Add(const InterpolableValue& other) final; void AssertCanInterpolateWith(const InterpolableValue& other) const final; private: @@ -130,6 +136,8 @@ bool IsList() const final { return true; } bool Equals(const InterpolableValue& other) const final; void Scale(double scale) final; + void Add(const InterpolableValue& other) final; + // We override this to avoid two passes on the list from the base version. void ScaleAndAdd(double scale, const InterpolableValue& other) final; void AssertCanInterpolateWith(const InterpolableValue& other) const final;
diff --git a/third_party/blink/renderer/core/animation_frame/worker_animation_frame_provider.cc b/third_party/blink/renderer/core/animation_frame/worker_animation_frame_provider.cc index 6ddf2866..a4917ca 100644 --- a/third_party/blink/renderer/core/animation_frame/worker_animation_frame_provider.cc +++ b/third_party/blink/renderer/core/animation_frame/worker_animation_frame_provider.cc
@@ -41,16 +41,18 @@ TRACE_EVENT0("blink", "WorkerAnimationFrameProvider::BeginFrame"); double time = (frame_time - base::TimeTicks()).InMillisecondsF(); - Microtask::EnqueueMicrotask(WTF::Bind( [](base::WeakPtr<WorkerAnimationFrameProvider> provider, double time) { + if (!provider) + return; TRACE_EVENT0("blink", "WorkerAnimationFrameProvider::RequestAnimationFrame"); - provider->callback_collection_.ExecuteFrameCallbacks(time, time); - + OffscreenCanvas::ScopedInsideWorkerRAF inside_raf_scope; for (auto& offscreen_canvas : provider->offscreen_canvases_) { - offscreen_canvas->PushFrameIfNeeded(); + inside_raf_scope.AddOffscreenCanvas(offscreen_canvas); } + + provider->callback_collection_.ExecuteFrameCallbacks(time, time); }, weak_factory_.GetWeakPtr(), time)); }
diff --git a/third_party/blink/renderer/core/core_idl_files.gni b/third_party/blink/renderer/core/core_idl_files.gni index 8886e3f..3abdd6b6 100644 --- a/third_party/blink/renderer/core/core_idl_files.gni +++ b/third_party/blink/renderer/core/core_idl_files.gni
@@ -51,7 +51,6 @@ "clipboard/data_transfer_item_list.idl", "css/css_condition_rule.idl", "css/css_font_face_rule.idl", - "css/css_font_feature_values_rule.idl", "css/css_grouping_rule.idl", "css/css_import_rule.idl", "css/css_keyframe_rule.idl",
diff --git a/third_party/blink/renderer/core/css/BUILD.gn b/third_party/blink/renderer/core/css/BUILD.gn index afd5ae1..62d2f2d 100644 --- a/third_party/blink/renderer/core/css/BUILD.gn +++ b/third_party/blink/renderer/core/css/BUILD.gn
@@ -58,8 +58,6 @@ "css_font_family_value.h", "css_font_feature_value.cc", "css_font_feature_value.h", - "css_font_feature_values_rule.cc", - "css_font_feature_values_rule.h", "css_font_selector.cc", "css_font_selector.h", "css_font_style_range_value.cc",
diff --git a/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc b/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc deleted file mode 100644 index e4b8ae90..0000000 --- a/third_party/blink/renderer/core/css/css_font_feature_values_rule.cc +++ /dev/null
@@ -1,61 +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 "third_party/blink/renderer/core/css/css_font_feature_values_rule.h" - -#include "third_party/blink/renderer/core/css/css_identifier_value.h" -#include "third_party/blink/renderer/core/css/css_value_list.h" -#include "third_party/blink/renderer/core/css/style_rule.h" -#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" - -namespace blink { - -CSSFontFeatureValuesRule::CSSFontFeatureValuesRule( - StyleRuleFontFeatureValues* font_feature_values_rule, - CSSStyleSheet* parent) - : CSSRule(parent), font_feature_values_rule_(font_feature_values_rule) {} - -CSSFontFeatureValuesRule::~CSSFontFeatureValuesRule() = default; - -void CSSFontFeatureValuesRule::setFontFamily(const String& font_family) {} - -String CSSFontFeatureValuesRule::fontFamily() { - return font_feature_values_rule_->FontFamily().CssText(); -} - -void CSSFontFeatureValuesRule::setFontDisplay(const String& font_display) {} - -String CSSFontFeatureValuesRule::fontDisplay() { - if (font_feature_values_rule_->FontDisplay()) - return font_feature_values_rule_->FontDisplay()->CssText(); - return ""; -} - -String CSSFontFeatureValuesRule::cssText() const { - StringBuilder result; - result.Append("@font-feature-values "); - DCHECK(font_feature_values_rule_); - result.Append(font_feature_values_rule_->FontFamily().CssText()); - result.Append(" { "); - if (const CSSIdentifierValue* display = - font_feature_values_rule_->FontDisplay()) { - result.Append("{ font-display: "); - result.Append(display->CssText()); - result.Append("; } "); - } - result.Append("}"); - return result.ToString(); -} - -void CSSFontFeatureValuesRule::Reattach(StyleRuleBase* rule) { - DCHECK(rule); - font_feature_values_rule_ = To<StyleRuleFontFeatureValues>(rule); -} - -void CSSFontFeatureValuesRule::Trace(blink::Visitor* visitor) { - visitor->Trace(font_feature_values_rule_); - CSSRule::Trace(visitor); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/core/css/css_font_feature_values_rule.h b/third_party/blink/renderer/core/css/css_font_feature_values_rule.h deleted file mode 100644 index 5fac19d..0000000 --- a/third_party/blink/renderer/core/css/css_font_feature_values_rule.h +++ /dev/null
@@ -1,52 +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. - -#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_ -#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_ - -#include "third_party/blink/renderer/core/css/css_rule.h" -#include "third_party/blink/renderer/platform/heap/handle.h" -#include "third_party/blink/renderer/platform/wtf/casting.h" - -namespace blink { - -class StyleRuleFontFeatureValues; - -class CSSFontFeatureValuesRule final : public CSSRule { - DEFINE_WRAPPERTYPEINFO(); - - public: - CSSFontFeatureValuesRule(StyleRuleFontFeatureValues*, CSSStyleSheet* parent); - ~CSSFontFeatureValuesRule() override; - - void setFontFamily(const String& font_family); - String fontFamily(); - void setFontDisplay(const String& font_display); - String fontDisplay(); - - String cssText() const override; - void Reattach(StyleRuleBase*) override; - - StyleRuleFontFeatureValues* StyleRule() const { - return font_feature_values_rule_.Get(); - } - - void Trace(blink::Visitor*) override; - - private: - CSSRule::Type type() const override { return kFontFeatureValuesRule; } - - Member<StyleRuleFontFeatureValues> font_feature_values_rule_; -}; - -template <> -struct DowncastTraits<CSSFontFeatureValuesRule> { - static bool AllowFrom(const CSSRule& rule) { - return rule.type() == CSSRule::kFontFeatureValuesRule; - } -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FEATURE_VALUES_RULE_H_
diff --git a/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl b/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl deleted file mode 100644 index 882239c..0000000 --- a/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl +++ /dev/null
@@ -1,14 +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. - -// https://drafts.csswg.org/css-fonts-4/#om-fontfeaturevalues - -[ - RuntimeEnabled=CSSFontFeatureValues -] interface CSSFontFeatureValuesRule : CSSRule { - attribute CSSOMString fontFamily; - - // fontDisplay is not reflected in CSSOM according to the current draft. - attribute CSSOMString fontDisplay; -};
diff --git a/third_party/blink/renderer/core/css/css_paint_value.cc b/third_party/blink/renderer/core/css/css_paint_value.cc index 9fbd44f..7dc08d42 100644 --- a/third_party/blink/renderer/core/css/css_paint_value.cc +++ b/third_party/blink/renderer/core/css/css_paint_value.cc
@@ -110,7 +110,11 @@ // For Off-Thread PaintWorklet, we just collect the necessary inputs together // and defer the actual JavaScript call until much later (during cc Raster). - if (off_thread_paint_state_ != OffThreadPaintState::kMainThread) { + // + // Generating print-previews happens entirely on the main thread, so we have + // to fall-back to main in that case. + if (off_thread_paint_state_ != OffThreadPaintState::kMainThread && + !document.Printing()) { // It is not necessary for a LayoutObject to always have RareData which // contains the ElementId. If this |layout_object| doesn't have an // ElementId, then create one for it.
diff --git a/third_party/blink/renderer/core/css/css_paint_value_test.cc b/third_party/blink/renderer/core/css/css_paint_value_test.cc index 108255b..58249ba 100644 --- a/third_party/blink/renderer/core/css/css_paint_value_test.cc +++ b/third_party/blink/renderer/core/css/css_paint_value_test.cc
@@ -46,6 +46,9 @@ : ScopedCSSPaintAPIArgumentsForTest(GetParam() & kCSSPaintAPIArguments), ScopedOffMainThreadCSSPaintForTest(GetParam() & kOffMainThreadCSSPaint) {} + + // TODO(xidachen): a mock_generator is used in many tests in this file, put + // that in a Setup method. }; INSTANTIATE_TEST_SUITE_P(, @@ -206,6 +209,52 @@ paint_value->GetImage(*target, GetDocument(), style, target_size)); } +TEST_P(CSSPaintValueTest, PrintingMustFallbackToMainThread) { + if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) + return; + + NiceMock<MockCSSPaintImageGenerator>* mock_generator = + MakeGarbageCollected<NiceMock<MockCSSPaintImageGenerator>>(); + base::AutoReset<MockCSSPaintImageGenerator*> scoped_override_generator( + &g_override_generator, mock_generator); + base::AutoReset<CSSPaintImageGenerator::CSSPaintImageGeneratorCreateFunction> + scoped_create_function( + CSSPaintImageGenerator::GetCreateFunctionForTesting(), + ProvideOverrideGenerator); + + const FloatSize target_size(100, 100); + + SetBodyInnerHTML(R"HTML( + <div id="target"></div> + )HTML"); + LayoutObject* target = GetLayoutObjectByElementId("target"); + const ComputedStyle& style = *target->Style(); + + auto* ident = MakeGarbageCollected<CSSCustomIdentValue>("testpainter"); + CSSPaintValue* paint_value = MakeGarbageCollected<CSSPaintValue>(ident); + + ON_CALL(*mock_generator, IsImageGeneratorReady()).WillByDefault(Return(true)); + // This PW can be composited, so we should only fall back to main once, in + // the case where we are printing. + EXPECT_CALL(*mock_generator, Paint(_, _, _, _)) + .Times(1) + .WillOnce(Return(PaintGeneratedImage::Create(nullptr, target_size))); + + ASSERT_TRUE( + paint_value->GetImage(*target, GetDocument(), style, target_size)); + + // Start printing; our paint should run on the main thread (and thus call + // Paint). + GetDocument().SetPrinting(Document::kPrinting); + ASSERT_TRUE( + paint_value->GetImage(*target, GetDocument(), style, target_size)); + + // Stop printing; we should return to the compositor. + GetDocument().SetPrinting(Document::kNotPrinting); + ASSERT_TRUE( + paint_value->GetImage(*target, GetDocument(), style, target_size)); +} + // Regression test for https://crbug.com/835589. TEST_P(CSSPaintValueTest, DoNotPaintForLink) { SetBodyInnerHTML(R"HTML(
diff --git a/third_party/blink/renderer/core/css/css_rule.h b/third_party/blink/renderer/core/css/css_rule.h index 3036f6e..4dbd80e8 100644 --- a/third_party/blink/renderer/core/css/css_rule.h +++ b/third_party/blink/renderer/core/css/css_rule.h
@@ -55,7 +55,6 @@ kKeyframeRule = 8, kNamespaceRule = 10, kSupportsRule = 12, - kFontFeatureValuesRule = 14, kViewportRule = 15, // Experimental features below. Such features must be greater than 1000: // the 0-1000 range is reserved by the CSS Working Group.
diff --git a/third_party/blink/renderer/core/css/css_rule.idl b/third_party/blink/renderer/core/css/css_rule.idl index d63735b..96679da6 100644 --- a/third_party/blink/renderer/core/css/css_rule.idl +++ b/third_party/blink/renderer/core/css/css_rule.idl
@@ -46,10 +46,6 @@ // https://drafts.csswg.org/css-conditional/#extentions-to-cssrule-interface const unsigned short SUPPORTS_RULE = 12; - // CSS Fonts Level 4 - // https://drafts.csswg.org/css-fonts-4/#font-feature-values - [RuntimeEnabled=CSSFontFeatureValues] const unsigned short FONT_FEATURE_VALUES_RULE = 14; - // CSS Device Adaptation // https://drafts.csswg.org/css-device-adapt/#css-rule-interface [RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
diff --git a/third_party/blink/renderer/core/css/font_face.cc b/third_party/blink/renderer/core/css/font_face.cc index a090bc7..1291405 100644 --- a/third_party/blink/renderer/core/css/font_face.cc +++ b/third_party/blink/renderer/core/css/font_face.cc
@@ -780,13 +780,8 @@ return status_ == kLoading && GetExecutionContext(); } -FontDisplay FontFace::GetFontDisplayWithFallback() const { - if (display_) - return CSSValueToFontDisplay(display_.Get()); - ExecutionContext* context = GetExecutionContext(); - if (!context || !context->IsDocument()) - return kFontDisplayAuto; - return To<Document>(context)->GetStyleEngine().GetDefaultFontDisplay(family_); +FontDisplay FontFace::GetFontDisplay() const { + return CSSValueToFontDisplay(display_.Get()); } } // namespace blink
diff --git a/third_party/blink/renderer/core/css/font_face.h b/third_party/blink/renderer/core/css/font_face.h index 7c8a121..b6ac823 100644 --- a/third_party/blink/renderer/core/css/font_face.h +++ b/third_party/blink/renderer/core/css/font_face.h
@@ -113,9 +113,7 @@ FontSelectionCapabilities GetFontSelectionCapabilities() const; CSSFontFace* CssFontFace() { return css_font_face_.Get(); } size_t ApproximateBlankCharacterCount() const; - // Return FontDisplay using the default from @font-feature-values if not - // specified on this FontFace. - FontDisplay GetFontDisplayWithFallback() const; + FontDisplay GetFontDisplay() const; void Trace(blink::Visitor*) override;
diff --git a/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc b/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc index 9dc8287..e9ed122 100644 --- a/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc +++ b/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc
@@ -15,8 +15,6 @@ return kCSSAtRuleCharset; if (EqualIgnoringASCIICase(name, "font-face")) return kCSSAtRuleFontFace; - if (EqualIgnoringASCIICase(name, "font-feature-values")) - return kCSSAtRuleFontFeatureValues; if (EqualIgnoringASCIICase(name, "import")) return kCSSAtRuleImport; if (EqualIgnoringASCIICase(name, "keyframes")) @@ -48,9 +46,6 @@ case kCSSAtRuleFontFace: feature = WebFeature::kCSSAtRuleFontFace; break; - case kCSSAtRuleFontFeatureValues: - feature = WebFeature::kCSSAtRuleFontFeatureValues; - break; case kCSSAtRuleImport: feature = WebFeature::kCSSAtRuleImport; break;
diff --git a/third_party/blink/renderer/core/css/parser/css_at_rule_id.h b/third_party/blink/renderer/core/css/parser/css_at_rule_id.h index 73fa0fd..f15629e7 100644 --- a/third_party/blink/renderer/core/css/parser/css_at_rule_id.h +++ b/third_party/blink/renderer/core/css/parser/css_at_rule_id.h
@@ -15,7 +15,6 @@ kCSSAtRuleInvalid, kCSSAtRuleCharset, kCSSAtRuleFontFace, - kCSSAtRuleFontFeatureValues, kCSSAtRuleImport, kCSSAtRuleKeyframes, kCSSAtRuleMedia,
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc index dd681c4..08bf277c4 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
@@ -525,8 +525,6 @@ return ConsumeViewportRule(prelude, prelude_offset, stream); case kCSSAtRuleFontFace: return ConsumeFontFaceRule(prelude, prelude_offset, stream); - case kCSSAtRuleFontFeatureValues: - return ConsumeFontFeatureValuesRule(prelude, prelude_offset, stream); case kCSSAtRuleWebkitKeyframes: return ConsumeKeyframesRule(true, prelude, prelude_offset, stream); case kCSSAtRuleKeyframes: @@ -756,44 +754,6 @@ CreateCSSPropertyValueSet(parsed_properties_, kCSSFontFaceRuleMode)); } -StyleRuleFontFeatureValues* CSSParserImpl::ConsumeFontFeatureValuesRule( - CSSParserTokenRange prelude, - const RangeOffset& prelude_offset, - CSSParserTokenStream& block) { - if (!RuntimeEnabledFeatures::CSSFontFeatureValuesEnabled()) - return nullptr; - - const CSSValueList* font_family = - css_parsing_utils::ConsumeFontFamily(prelude); - if (!font_family || !prelude.AtEnd()) - return nullptr; - - if (observer_) { - observer_->StartRuleHeader(StyleRule::kFontFeatureValues, - prelude_offset.start); - observer_->EndRuleHeader(prelude_offset.end); - observer_->StartRuleBody(block.Offset()); - } - - const CSSIdentifierValue* font_display = nullptr; - ConsumeRuleList( - block, kFontFeatureRuleList, [&font_display](StyleRuleBase* rule) { - const CSSValue* value = - To<StyleRuleFontFace>(rule)->Properties().GetPropertyCSSValue( - CSSPropertyID::kFontDisplay); - if (value) - font_display = To<CSSIdentifierValue>(value); - }); - - if (observer_) - observer_->EndRuleBody(block.Offset()); - - if (!block.AtEnd()) - return nullptr; - return MakeGarbageCollected<StyleRuleFontFeatureValues>(font_family, - font_display); -} - StyleRuleKeyframes* CSSParserImpl::ConsumeKeyframesRule( bool webkit_prefixed, CSSParserTokenRange prelude,
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.h b/third_party/blink/renderer/core/css/parser/css_parser_impl.h index 7da6c30..6f1fa33b 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.h +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.h
@@ -26,7 +26,6 @@ class StyleRule; class StyleRuleBase; class StyleRuleCharset; -class StyleRuleFontFeatureValues; class StyleRuleFontFace; class StyleRuleImport; class StyleRuleKeyframe; @@ -163,10 +162,6 @@ StyleRuleFontFace* ConsumeFontFaceRule(CSSParserTokenRange prelude, const RangeOffset& prelude_offset, CSSParserTokenStream& block); - StyleRuleFontFeatureValues* ConsumeFontFeatureValuesRule( - CSSParserTokenRange prelude, - const RangeOffset& prelude_offset, - CSSParserTokenStream& block); StyleRuleKeyframes* ConsumeKeyframesRule(bool webkit_prefixed, CSSParserTokenRange prelude, const RangeOffset& prelude_offset,
diff --git a/third_party/blink/renderer/core/css/remote_font_face_source.cc b/third_party/blink/renderer/core/css/remote_font_face_source.cc index 9655879..475ea4d 100644 --- a/third_party/blink/renderer/core/css/remote_font_face_source.cc +++ b/third_party/blink/renderer/core/css/remote_font_face_source.cc
@@ -280,7 +280,7 @@ return; DCHECK(GetResource()); - SetDisplay(face_->GetFontFace()->GetFontDisplayWithFallback()); + SetDisplay(face_->GetFontFace()->GetFontDisplay()); FontResource* font = ToFontResource(GetResource()); if (font->StillNeedsLoad()) {
diff --git a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc index f953969..f27c217 100644 --- a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
@@ -81,9 +81,6 @@ } if (font_face_rules.size() && document.GetStyleResolver()) document.GetStyleResolver()->InvalidateMatchedPropertiesCache(); - - for (const auto& rule : rule_set.FontFeatureValuesRules()) - document.GetStyleEngine().AddDefaultFontDisplay(rule); } void ScopedStyleResolver::AppendActiveStyleSheets(
diff --git a/third_party/blink/renderer/core/css/rule_set.cc b/third_party/blink/renderer/core/css/rule_set.cc index b619bd7..6224f84 100644 --- a/third_party/blink/renderer/core/css/rule_set.cc +++ b/third_party/blink/renderer/core/css/rule_set.cc
@@ -275,11 +275,6 @@ font_face_rules_.push_back(rule); } -void RuleSet::AddFontFeatureValuesRule(StyleRuleFontFeatureValues* rule) { - EnsurePendingRules(); - font_feature_values_rules_.push_back(rule); -} - void RuleSet::AddKeyframesRule(StyleRuleKeyframes* rule) { EnsurePendingRules(); // So that keyframes_rules_.ShrinkToFit() gets called. keyframes_rules_.push_back(rule); @@ -324,9 +319,6 @@ AddChildRules(media_rule->ChildRules(), medium, add_rule_flags); } else if (auto* font_face_rule = DynamicTo<StyleRuleFontFace>(rule)) { AddFontFaceRule(font_face_rule); - } else if (auto* font_feature_values_rule = - DynamicTo<StyleRuleFontFeatureValues>(rule)) { - AddFontFeatureValuesRule(font_feature_values_rule); } else if (auto* keyframes_rule = DynamicTo<StyleRuleKeyframes>(rule)) { AddKeyframesRule(keyframes_rule); } else if (auto* property_rule = DynamicTo<StyleRuleProperty>(rule)) { @@ -405,7 +397,6 @@ shadow_host_rules_.ShrinkToFit(); page_rules_.ShrinkToFit(); font_face_rules_.ShrinkToFit(); - font_feature_values_rules_.ShrinkToFit(); keyframes_rules_.ShrinkToFit(); property_rules_.ShrinkToFit(); deep_combinator_or_shadow_pseudo_rules_.ShrinkToFit(); @@ -442,7 +433,6 @@ visitor->Trace(shadow_host_rules_); visitor->Trace(page_rules_); visitor->Trace(font_face_rules_); - visitor->Trace(font_feature_values_rules_); visitor->Trace(keyframes_rules_); visitor->Trace(property_rules_); visitor->Trace(deep_combinator_or_shadow_pseudo_rules_);
diff --git a/third_party/blink/renderer/core/css/rule_set.h b/third_party/blink/renderer/core/css/rule_set.h index 946a5f8..ab1531ec 100644 --- a/third_party/blink/renderer/core/css/rule_set.h +++ b/third_party/blink/renderer/core/css/rule_set.h
@@ -243,10 +243,6 @@ const HeapVector<Member<StyleRuleFontFace>>& FontFaceRules() const { return font_face_rules_; } - const HeapVector<Member<StyleRuleFontFeatureValues>>& FontFeatureValuesRules() - const { - return font_feature_values_rules_; - } const HeapVector<Member<StyleRuleKeyframes>>& KeyframesRules() const { return keyframes_rules_; } @@ -302,7 +298,6 @@ void AddPageRule(StyleRulePage*); void AddViewportRule(StyleRuleViewport*); void AddFontFaceRule(StyleRuleFontFace*); - void AddFontFeatureValuesRule(StyleRuleFontFeatureValues*); void AddKeyframesRule(StyleRuleKeyframes*); void AddPropertyRule(StyleRuleProperty*); @@ -346,7 +341,6 @@ RuleFeatureSet features_; HeapVector<Member<StyleRulePage>> page_rules_; HeapVector<Member<StyleRuleFontFace>> font_face_rules_; - HeapVector<Member<StyleRuleFontFeatureValues>> font_feature_values_rules_; HeapVector<Member<StyleRuleKeyframes>> keyframes_rules_; HeapVector<Member<StyleRuleProperty>> property_rules_; HeapVector<MinimalRuleData> deep_combinator_or_shadow_pseudo_rules_;
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index 65a3531..07d7614 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -636,39 +636,13 @@ resolver_->InvalidateMatchedPropertiesCache(); } - default_font_display_map_.clear(); // Rebuild the font cache with @font-face rules from user style sheets. for (unsigned i = 0; i < active_user_style_sheets_.size(); ++i) { DCHECK(active_user_style_sheets_[i].second); AddUserFontFaceRules(*active_user_style_sheets_[i].second); - for (const auto& rule : - active_user_style_sheets_[i].second->FontFeatureValuesRules()) { - AddDefaultFontDisplay(rule); - } } } -void StyleEngine::AddDefaultFontDisplay( - const StyleRuleFontFeatureValues* rule) { - if (!rule->FontDisplay()) - return; - for (const auto& family_value : rule->FontFamily()) { - if (auto* font_family_value = - DynamicTo<CSSFontFamilyValue>(family_value.Get())) { - default_font_display_map_.Set(AtomicString(font_family_value->Value()), - CSSValueToFontDisplay(rule->FontDisplay())); - } - } -} - -FontDisplay StyleEngine::GetDefaultFontDisplay( - const AtomicString& family) const { - auto it = default_font_display_map_.find(family); - if (it == default_font_display_map_.end()) - return kFontDisplayAuto; - return it->value; -} - void StyleEngine::UpdateGenericFontFamilySettings() { // FIXME: we should not update generic font family settings when // document is inactive. @@ -1350,9 +1324,7 @@ kFontFaceRules = 1 << 0, kKeyframesRules = 1 << 1, kFullRecalcRules = 1 << 2, - kFontFeatureValuesRules = 1 << 3, - kFontRules = kFontFaceRules | kFontFeatureValuesRules, - kPropertyRules = 1 << 4 + kPropertyRules = 1 << 3, }; unsigned GetRuleSetFlags(const HeapHashSet<Member<RuleSet>> rule_sets) { @@ -1365,8 +1337,6 @@ flags |= kFontFaceRules; if (rule_set->NeedsFullRecalcForRuleSetInvalidation()) flags |= kFullRecalcRules; - if (!rule_set->FontFeatureValuesRules().IsEmpty()) - flags |= kFontFeatureValuesRules; if (!rule_set->PropertyRules().IsEmpty()) flags |= kPropertyRules; } @@ -1427,7 +1397,7 @@ global_rule_set_->MarkDirty(); unsigned changed_rule_flags = GetRuleSetFlags(changed_rule_sets); - if (changed_rule_flags & kFontRules) { + if (changed_rule_flags & kFontFaceRules) { if (ScopedStyleResolver* scoped_resolver = GetDocument().GetScopedStyleResolver()) { // User style and document scope author style shares the font cache. If @@ -1471,7 +1441,7 @@ unsigned changed_rule_flags = GetRuleSetFlags(changed_rule_sets); bool rebuild_font_cache = change == kActiveSheetsChanged && - (changed_rule_flags & kFontRules) && + (changed_rule_flags & kFontFaceRules) && tree_scope.RootNode().IsDocumentNode(); ScopedStyleResolver* scoped_resolver = tree_scope.GetScopedStyleResolver(); if (scoped_resolver && scoped_resolver->NeedsAppendAllSheets()) { @@ -1858,7 +1828,8 @@ void StyleEngine::UpdateColorScheme() { auto* settings = GetDocument().GetSettings(); - DCHECK(settings); + if (!settings) + return; ForcedColors old_forced_colors = forced_colors_; forced_colors_ = settings->GetForcedColors();
diff --git a/third_party/blink/renderer/core/css/style_engine.h b/third_party/blink/renderer/core/css/style_engine.h index 4847b73..2911f772 100644 --- a/third_party/blink/renderer/core/css/style_engine.h +++ b/third_party/blink/renderer/core/css/style_engine.h
@@ -40,7 +40,6 @@ #include "third_party/blink/renderer/core/css/active_style_sheets.h" #include "third_party/blink/renderer/core/css/css_global_rule_set.h" #include "third_party/blink/renderer/core/css/document_style_sheet_collection.h" -#include "third_party/blink/renderer/core/css/font_display.h" #include "third_party/blink/renderer/core/css/invalidation/pending_invalidations.h" #include "third_party/blink/renderer/core/css/invalidation/style_invalidator.h" #include "third_party/blink/renderer/core/css/layout_tree_rebuild_root.h" @@ -342,8 +341,6 @@ const AtomicString& animation_name); DocumentStyleEnvironmentVariables& EnsureEnvironmentVariables(); - void AddDefaultFontDisplay(const StyleRuleFontFeatureValues*); - FontDisplay GetDefaultFontDisplay(const AtomicString& family) const; scoped_refptr<StyleInitialData> MaybeCreateAndGetInitialData(); @@ -553,10 +550,6 @@ scoped_refptr<StyleInitialData> initial_data_; - // Default font-display collected from @font-feature-values rules. The key is - // font-family. - HashMap<AtomicString, FontDisplay> default_font_display_map_; - // Color schemes explicitly supported by the author through the viewport meta // tag. E.g. <meta name="color-scheme" content="light dark">. A dark color- // scheme is used to opt-out of forced darkening.
diff --git a/third_party/blink/renderer/core/css/style_rule.cc b/third_party/blink/renderer/core/css/style_rule.cc index 5a33d11..4a99e20 100644 --- a/third_party/blink/renderer/core/css/style_rule.cc +++ b/third_party/blink/renderer/core/css/style_rule.cc
@@ -22,7 +22,6 @@ #include "third_party/blink/renderer/core/css/style_rule.h" #include "third_party/blink/renderer/core/css/css_font_face_rule.h" -#include "third_party/blink/renderer/core/css/css_font_feature_values_rule.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_import_rule.h" #include "third_party/blink/renderer/core/css/css_keyframes_rule.h" @@ -94,9 +93,6 @@ case kViewport: To<StyleRuleViewport>(this)->TraceAfterDispatch(visitor); return; - case kFontFeatureValues: - To<StyleRuleFontFeatureValues>(this)->TraceAfterDispatch(visitor); - return; } NOTREACHED(); } @@ -139,9 +135,6 @@ case kViewport: To<StyleRuleViewport>(this)->~StyleRuleViewport(); return; - case kFontFeatureValues: - To<StyleRuleFontFeatureValues>(this)->~StyleRuleFontFeatureValues(); - return; } NOTREACHED(); } @@ -170,8 +163,6 @@ return To<StyleRuleViewport>(this)->Copy(); case kNamespace: return To<StyleRuleNamespace>(this)->Copy(); - case kFontFeatureValues: - return To<StyleRuleFontFeatureValues>(this)->Copy(); case kCharset: case kKeyframe: NOTREACHED(); @@ -226,10 +217,6 @@ rule = MakeGarbageCollected<CSSViewportRule>(To<StyleRuleViewport>(self), parent_sheet); break; - case kFontFeatureValues: - rule = MakeGarbageCollected<CSSFontFeatureValuesRule>( - To<StyleRuleFontFeatureValues>(self), parent_sheet); - break; case kKeyframe: case kCharset: NOTREACHED(); @@ -455,17 +442,4 @@ StyleRuleBase::TraceAfterDispatch(visitor); } -StyleRuleFontFeatureValues::StyleRuleFontFeatureValues( - const CSSValueList* font_family, - const CSSIdentifierValue* font_display) - : StyleRuleBase(kFontFeatureValues), - font_family_(font_family), - font_display_(font_display) {} - -void StyleRuleFontFeatureValues::TraceAfterDispatch(blink::Visitor* visitor) { - visitor->Trace(font_family_); - visitor->Trace(font_display_); - StyleRuleBase::TraceAfterDispatch(visitor); -} - } // namespace blink
diff --git a/third_party/blink/renderer/core/css/style_rule.h b/third_party/blink/renderer/core/css/style_rule.h index 53ef0a15..feaac3a 100644 --- a/third_party/blink/renderer/core/css/style_rule.h +++ b/third_party/blink/renderer/core/css/style_rule.h
@@ -32,10 +32,8 @@ namespace blink { -class CSSIdentifierValue; class CSSRule; class CSSStyleSheet; -class CSSValueList; class CORE_EXPORT StyleRuleBase : public GarbageCollected<StyleRuleBase> { public: @@ -52,7 +50,6 @@ kNamespace, kSupports, kViewport, - kFontFeatureValues, }; RuleType GetType() const { return static_cast<RuleType>(type_); } @@ -69,9 +66,6 @@ bool IsSupportsRule() const { return GetType() == kSupports; } bool IsViewportRule() const { return GetType() == kViewport; } bool IsImportRule() const { return GetType() == kImport; } - bool IsFontFeatureValuesRule() const { - return GetType() == kFontFeatureValues; - } StyleRuleBase* Copy() const; @@ -324,29 +318,6 @@ private: }; -class CORE_EXPORT StyleRuleFontFeatureValues : public StyleRuleBase { - public: - StyleRuleFontFeatureValues(const CSSValueList* font_family, - const CSSIdentifierValue* font_display); - StyleRuleFontFeatureValues(const StyleRuleFontFeatureValues&) = default; - - StyleRuleFontFeatureValues* Copy() const { - return MakeGarbageCollected<StyleRuleFontFeatureValues>(*this); - } - - const CSSValueList& FontFamily() const { - DCHECK(font_family_); - return *font_family_; - } - const CSSIdentifierValue* FontDisplay() const { return font_display_; } - - void TraceAfterDispatch(blink::Visitor*); - - private: - Member<const CSSValueList> font_family_; - Member<const CSSIdentifierValue> font_display_; -}; - template <> struct DowncastTraits<StyleRule> { static bool AllowFrom(const StyleRuleBase& rule) { @@ -401,13 +372,6 @@ } }; -template <> -struct DowncastTraits<StyleRuleFontFeatureValues> { - static bool AllowFrom(const StyleRuleBase& rule) { - return rule.IsFontFeatureValuesRule(); - } -}; - } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_RULE_H_
diff --git a/third_party/blink/renderer/core/css/style_sheet_contents.cc b/third_party/blink/renderer/core/css/style_sheet_contents.cc index 31140d7..000e05e 100644 --- a/third_party/blink/renderer/core/css/style_sheet_contents.cc +++ b/third_party/blink/renderer/core/css/style_sheet_contents.cc
@@ -515,7 +515,6 @@ case StyleRuleBase::kKeyframe: case StyleRuleBase::kSupports: case StyleRuleBase::kViewport: - case StyleRuleBase::kFontFeatureValues: break; } }
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index f34d03c..828909c 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -2266,21 +2266,21 @@ form_controller_ = MakeGarbageCollected<FormController>(*this); HistoryItem* history_item = Loader() ? Loader()->GetHistoryItem() : nullptr; if (history_item) - history_item->SetDocumentState(form_controller_->FormElementsState()); + history_item->SetDocumentState(form_controller_->ControlStates()); } return *form_controller_; } -DocumentState* Document::FormElementsState() const { +DocumentState* Document::GetDocumentState() const { if (!form_controller_) return nullptr; - return form_controller_->FormElementsState(); + return form_controller_->ControlStates(); } -void Document::SetStateForNewFormElements(const Vector<String>& state_vector) { +void Document::SetStateForNewControls(const Vector<String>& state_vector) { if (!state_vector.size() && !form_controller_) return; - GetFormController().SetStateForNewFormElements(state_vector); + GetFormController().SetStateForNewControls(state_vector); } LocalFrameView* Document::View() const { @@ -4352,7 +4352,7 @@ element_data_cache_ = MakeGarbageCollected<ElementDataCache>(); if (previous_state != kFinishedParsing && parsing_state_ == kFinishedParsing) { - if (form_controller_ && form_controller_->HasFormStates()) + if (form_controller_ && form_controller_->HasControlStates()) form_controller_->ScheduleRestore(); } } @@ -4537,6 +4537,21 @@ if (new_url == url_) return; + // Count non-targetText occurrences of :~: in the url fragment to make sure + // the delimiter is web-compatible. This can be removed once the feature + // ships. + wtf_size_t delim_pos = new_url.FragmentIdentifier().Find(":~:"); + if (delim_pos != kNotFound) { + const wtf_size_t one_past_delim = delim_pos + 3; + if (new_url.FragmentIdentifier().Find(kTextFragmentIdentifierPrefix, + one_past_delim) != one_past_delim) { + // We can't use count here because the DocumentLoader hasn't yet been + // created. It'll be use counted with other delimiters in + // FragmentAnchor::TryCreate. + use_count_fragment_directive_ = true; + } + } + // If text fragment identifiers are enabled, we strip the fragment directive // from the URL fragment. // E.g. "#id:~:targetText=a" --> "#id"
diff --git a/third_party/blink/renderer/core/dom/document.h b/third_party/blink/renderer/core/dom/document.h index a8ededf..1682ebcd 100644 --- a/third_party/blink/renderer/core/dom/document.h +++ b/third_party/blink/renderer/core/dom/document.h
@@ -501,8 +501,8 @@ void EvaluateMediaQueryList(); FormController& GetFormController(); - DocumentState* FormElementsState() const; - void SetStateForNewFormElements(const Vector<String>&); + DocumentState* GetDocumentState() const; + void SetStateForNewControls(const Vector<String>&); LocalFrameView* View() const; // can be null LocalFrame* GetFrame() const { return frame_; } // can be null @@ -1619,6 +1619,9 @@ bool NeedsLayoutTreeRebuild() const; String GetFragmentDirective() const { return fragment_directive_; } + bool UseCountFragmentDirective() const { + return use_count_fragment_directive_; + } protected: void ClearXMLVersion() { xml_version_ = String(); } @@ -2130,6 +2133,9 @@ bool toggle_during_parsing_ = false; String fragment_directive_; + + bool use_count_fragment_directive_ = false; + HeapHashMap<WeakMember<Element>, Member<ExplicitlySetAttrElementsMap>> element_explicitly_set_attr_elements_map_; };
diff --git a/third_party/blink/renderer/core/dom/events/native_event_listener.h b/third_party/blink/renderer/core/dom/events/native_event_listener.h index 7e5b674..31ae554 100644 --- a/third_party/blink/renderer/core/dom/events/native_event_listener.h +++ b/third_party/blink/renderer/core/dom/events/native_event_listener.h
@@ -23,7 +23,6 @@ // Helper functions for DowncastTraits. bool IsNativeEventListener() const override { return true; } - virtual bool IsConditionEventListener() const { return false; } virtual bool IsImageEventListener() const { return false; } protected:
diff --git a/third_party/blink/renderer/core/events/error_event.cc b/third_party/blink/renderer/core/events/error_event.cc index d0a80df..a1f1653 100644 --- a/third_party/blink/renderer/core/events/error_event.cc +++ b/third_party/blink/renderer/core/events/error_event.cc
@@ -66,7 +66,7 @@ initializer->hasLineno() ? initializer->lineno() : 0, initializer->hasColno() ? initializer->colno() : 0, nullptr); if (initializer->hasError()) { - error_ = initializer->error().ToWorldSafeV8Reference(); + error_.Set(script_state->GetIsolate(), initializer->error().V8Value()); } } @@ -79,7 +79,7 @@ location_(std::move(location)), world_(world) { if (!error.IsEmpty()) - error_ = error.ToWorldSafeV8Reference(); + error_.Set(error.GetIsolate(), error.V8Value()); } void ErrorEvent::SetUnsanitizedMessage(const String& message) {
diff --git a/third_party/blink/renderer/core/events/message_event.cc b/third_party/blink/renderer/core/events/message_event.cc index 30a2bf6..b008fd9 100644 --- a/third_party/blink/renderer/core/events/message_event.cc +++ b/third_party/blink/renderer/core/events/message_event.cc
@@ -73,7 +73,8 @@ data_type_(kDataTypeScriptValue), source_(nullptr) { if (initializer->hasData()) { - data_as_v8_value_ = initializer->data().ToWorldSafeV8Reference(); + data_as_v8_value_.Set(initializer->data().GetIsolate(), + initializer->data().V8Value()); } if (initializer->hasOrigin()) origin_ = initializer->origin(); @@ -194,7 +195,7 @@ initEvent(type, bubbles, cancelable); data_type_ = kDataTypeScriptValue; - data_as_v8_value_ = data.ToWorldSafeV8Reference(); + data_as_v8_value_.Set(data.GetIsolate(), data.V8Value()); is_data_dirty_ = true; origin_ = origin; last_event_id_ = last_event_id;
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc index 3000be8..da7cd640 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
@@ -947,8 +947,8 @@ StripURLForUseInReport(delegate->GetSecurityOrigin(), blocked_url, redirect_status, effective_type)); break; - case ContentSecurityPolicy::kTrustedTypesViolation: - init->setBlockedURI("trusted-types"); + case ContentSecurityPolicy::kTrustedTypesSinkViolation: + init->setBlockedURI("trusted-types-sink"); break; case ContentSecurityPolicy::kTrustedTypesPolicyViolation: init->setBlockedURI("trusted-types-policy");
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy.h b/third_party/blink/renderer/core/frame/csp/content_security_policy.h index 833641f..600d83f 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy.h +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy.h
@@ -144,7 +144,7 @@ kInlineViolation, kEvalViolation, kURLViolation, - kTrustedTypesViolation, + kTrustedTypesSinkViolation, kTrustedTypesPolicyViolation };
diff --git a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc index 5a15d80..9bb9570 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc
@@ -337,7 +337,7 @@ ContentSecurityPolicy::DirectiveType::kTrustedTypes), ContentSecurityPolicy::DirectiveType::kTrustedTypes, message, KURL(), RedirectStatus::kFollowedRedirect, - ContentSecurityPolicy::kTrustedTypesViolation, sample); + ContentSecurityPolicy::kTrustedTypesSinkViolation, sample); return IsReportOnly(); }
diff --git a/third_party/blink/renderer/core/frame/frame_serializer.cc b/third_party/blink/renderer/core/frame/frame_serializer.cc index ed83655..ae549776 100644 --- a/third_party/blink/renderer/core/frame/frame_serializer.cc +++ b/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -534,7 +534,6 @@ case CSSRule::kKeyframeRule: case CSSRule::kNamespaceRule: case CSSRule::kViewportRule: - case CSSRule::kFontFeatureValuesRule: break; } }
diff --git a/third_party/blink/renderer/core/html/forms/form_controller.cc b/third_party/blink/renderer/core/html/forms/form_controller.cc index 36838e20..f60aa4c 100644 --- a/third_party/blink/renderer/core/html/forms/form_controller.cc +++ b/third_party/blink/renderer/core/html/forms/form_controller.cc
@@ -118,20 +118,19 @@ // ---------------------------------------------------------------------------- -class FormElementKey { +class ControlKey { public: - FormElementKey(StringImpl* = nullptr, StringImpl* = nullptr); - ~FormElementKey(); - FormElementKey(const FormElementKey&); - FormElementKey& operator=(const FormElementKey&); + ControlKey(StringImpl* = nullptr, StringImpl* = nullptr); + ~ControlKey(); + ControlKey(const ControlKey&); + ControlKey& operator=(const ControlKey&); StringImpl* GetName() const { return name_; } StringImpl* GetType() const { return type_; } // Hash table deleted values, which are only constructed and never copied or // destroyed. - FormElementKey(WTF::HashTableDeletedValueType) - : name_(HashTableDeletedValue()) {} + ControlKey(WTF::HashTableDeletedValueType) : name_(HashTableDeletedValue()) {} bool IsHashTableDeletedValue() const { return name_ == HashTableDeletedValue(); } @@ -148,21 +147,21 @@ StringImpl* type_; }; -FormElementKey::FormElementKey(StringImpl* name, StringImpl* type) +ControlKey::ControlKey(StringImpl* name, StringImpl* type) : name_(name), type_(type) { Ref(); } -FormElementKey::~FormElementKey() { +ControlKey::~ControlKey() { Deref(); } -FormElementKey::FormElementKey(const FormElementKey& other) +ControlKey::ControlKey(const ControlKey& other) : name_(other.GetName()), type_(other.GetType()) { Ref(); } -FormElementKey& FormElementKey::operator=(const FormElementKey& other) { +ControlKey& ControlKey::operator=(const ControlKey& other) { other.Ref(); Deref(); name_ = other.GetName(); @@ -170,47 +169,48 @@ return *this; } -void FormElementKey::Ref() const { +void ControlKey::Ref() const { if (GetName()) GetName()->AddRef(); if (GetType()) GetType()->AddRef(); } -void FormElementKey::Deref() const { +void ControlKey::Deref() const { if (GetName()) GetName()->Release(); if (GetType()) GetType()->Release(); } -inline bool operator==(const FormElementKey& a, const FormElementKey& b) { +inline bool operator==(const ControlKey& a, const ControlKey& b) { return a.GetName() == b.GetName() && a.GetType() == b.GetType(); } -struct FormElementKeyHash { - static unsigned GetHash(const FormElementKey&); - static bool Equal(const FormElementKey& a, const FormElementKey& b) { - return a == b; - } +struct ControlKeyHash { + static unsigned GetHash(const ControlKey&); + static bool Equal(const ControlKey& a, const ControlKey& b) { return a == b; } static const bool safe_to_compare_to_empty_or_deleted = true; }; -unsigned FormElementKeyHash::GetHash(const FormElementKey& key) { - return StringHasher::HashMemory<sizeof(FormElementKey)>(&key); +unsigned ControlKeyHash::GetHash(const ControlKey& key) { + return StringHasher::HashMemory<sizeof(ControlKey)>(&key); } -struct FormElementKeyHashTraits : WTF::GenericHashTraits<FormElementKey> { - static void ConstructDeletedValue(FormElementKey& slot, bool) { - new (NotNull, &slot) FormElementKey(WTF::kHashTableDeletedValue); +struct ControlKeyHashTraits : WTF::GenericHashTraits<ControlKey> { + static void ConstructDeletedValue(ControlKey& slot, bool) { + new (NotNull, &slot) ControlKey(WTF::kHashTableDeletedValue); } - static bool IsDeletedValue(const FormElementKey& value) { + static bool IsDeletedValue(const ControlKey& value) { return value.IsHashTableDeletedValue(); } }; // ---------------------------------------------------------------------------- +// SavedFormState represents a set of FormControlState. +// It typically manages controls associated to a single <form>. Controls +// without owner forms are managed by a dedicated SavedFormState. class SavedFormState { USING_FAST_MALLOC(SavedFormState); @@ -220,7 +220,7 @@ static std::unique_ptr<SavedFormState> Deserialize(const Vector<String>&, wtf_size_t& index); void SerializeTo(Vector<String>&) const; - bool IsEmpty() const { return state_for_new_form_elements_.IsEmpty(); } + bool IsEmpty() const { return state_for_new_controls_.IsEmpty(); } void AppendControlState(const AtomicString& name, const AtomicString& type, const FormControlState&); @@ -230,11 +230,11 @@ Vector<String> GetReferencedFilePaths() const; private: - using FormElementStateMap = HashMap<FormElementKey, - Deque<FormControlState>, - FormElementKeyHash, - FormElementKeyHashTraits>; - FormElementStateMap state_for_new_form_elements_; + using ControlStateMap = HashMap<ControlKey, + Deque<FormControlState>, + ControlKeyHash, + ControlKeyHashTraits>; + ControlStateMap state_for_new_controls_; wtf_size_t control_state_count_; DISALLOW_COPY_AND_ASSIGN(SavedFormState); @@ -274,8 +274,8 @@ void SavedFormState::SerializeTo(Vector<String>& state_vector) const { state_vector.push_back(String::Number(control_state_count_)); - for (const auto& form_control : state_for_new_form_elements_) { - const FormElementKey& key = form_control.key; + for (const auto& form_control : state_for_new_controls_) { + const ControlKey& key = form_control.key; const Deque<FormControlState>& queue = form_control.value; for (const FormControlState& form_control_state : queue) { state_vector.push_back(key.GetName()); @@ -288,38 +288,38 @@ void SavedFormState::AppendControlState(const AtomicString& name, const AtomicString& type, const FormControlState& state) { - FormElementKey key(name.Impl(), type.Impl()); - FormElementStateMap::iterator it = state_for_new_form_elements_.find(key); - if (it != state_for_new_form_elements_.end()) { + ControlKey key(name.Impl(), type.Impl()); + ControlStateMap::iterator it = state_for_new_controls_.find(key); + if (it != state_for_new_controls_.end()) { it->value.push_back(state); } else { Deque<FormControlState> state_list; state_list.push_back(state); - state_for_new_form_elements_.Set(key, state_list); + state_for_new_controls_.Set(key, state_list); } control_state_count_++; } FormControlState SavedFormState::TakeControlState(const AtomicString& name, const AtomicString& type) { - if (state_for_new_form_elements_.IsEmpty()) + if (state_for_new_controls_.IsEmpty()) return FormControlState(); - FormElementStateMap::iterator it = state_for_new_form_elements_.find( - FormElementKey(name.Impl(), type.Impl())); - if (it == state_for_new_form_elements_.end()) + ControlStateMap::iterator it = + state_for_new_controls_.find(ControlKey(name.Impl(), type.Impl())); + if (it == state_for_new_controls_.end()) return FormControlState(); DCHECK_GT(it->value.size(), 0u); FormControlState state = it->value.TakeFirst(); control_state_count_--; if (it->value.empty()) - state_for_new_form_elements_.erase(it); + state_for_new_controls_.erase(it); return state; } Vector<String> SavedFormState::GetReferencedFilePaths() const { Vector<String> to_return; - for (const auto& form_control : state_for_new_form_elements_) { - const FormElementKey& key = form_control.key; + for (const auto& form_control : state_for_new_controls_) { + const ControlKey& key = form_control.key; if (!Equal(key.GetType(), "file", 4)) continue; const Deque<FormControlState>& queue = form_control.value; @@ -433,27 +433,27 @@ void DocumentState::Trace(Visitor* visitor) { visitor->Trace(document_); - visitor->Trace(form_controls_); + visitor->Trace(control_list_); } void DocumentState::InvalidateControlList() { - if (form_controls_dirty_) + if (is_control_list_dirty_) return; - form_controls_.resize(0); - form_controls_dirty_ = true; + control_list_.resize(0); + is_control_list_dirty_ = true; } -const DocumentState::FormElementList& DocumentState::ControlList() { - if (form_controls_dirty_) { +const DocumentState::ControlList& DocumentState::GetControlList() { + if (is_control_list_dirty_) { for (auto& element : Traversal<Element>::DescendantsOf(*document_)) { if (auto* control = ListedElement::From(element)) { if (control->ClassSupportsStateRestore()) - form_controls_.push_back(control); + control_list_.push_back(control); } } - form_controls_dirty_ = false; + is_control_list_dirty_ = false; } - return form_controls_; + return control_list_; } static String FormStateSignature() { @@ -469,7 +469,7 @@ auto* key_generator = MakeGarbageCollected<FormKeyGenerator>(); std::unique_ptr<SavedFormStateMap> state_map = base::WrapUnique(new SavedFormStateMap); - for (auto& control : ControlList()) { + for (auto& control : GetControlList()) { DCHECK(control->ToHTMLElement().isConnected()); if (!control->ShouldSaveAndRestoreFormControlState()) continue; @@ -483,7 +483,7 @@ } Vector<String> state_vector; - state_vector.ReserveInitialCapacity(ControlList().size() * 4); + state_vector.ReserveInitialCapacity(GetControlList().size() * 4); state_vector.push_back(FormStateSignature()); for (const auto& saved_form_state : *state_map) { state_vector.push_back(saved_form_state.key); @@ -509,20 +509,20 @@ visitor->Trace(form_key_generator_); } -DocumentState* FormController::FormElementsState() const { +DocumentState* FormController::ControlStates() const { return document_state_.Get(); } -void FormController::SetStateForNewFormElements( +void FormController::SetStateForNewControls( const Vector<String>& state_vector) { - FormStatesFromStateVector(state_vector, saved_form_state_map_); + ControlStatesFromStateVector(state_vector, saved_form_state_map_); } -bool FormController::HasFormStates() const { +bool FormController::HasControlStates() const { return !saved_form_state_map_.IsEmpty(); } -FormControlState FormController::TakeStateForFormElement( +FormControlState FormController::TakeStateForControl( const ListedElement& control) { if (saved_form_state_map_.IsEmpty()) return FormControlState(); @@ -539,7 +539,7 @@ return state; } -void FormController::FormStatesFromStateVector( +void FormController::ControlStatesFromStateVector( const Vector<String>& state_vector, SavedFormStateMap& map) { map.clear(); @@ -570,21 +570,9 @@ void FormController::RestoreControlStateFor(ListedElement& control) { if (kRestoreOnLoad && !document_->HasFinishedParsing()) return; - // We don't save state of a control with - // ShouldSaveAndRestoreFormControlState() == false. But we need to skip - // restoring process too because a control in another form might have the same - // pair of name and type and saved its state. - if (!control.ShouldSaveAndRestoreFormControlState()) - return; if (OwnerFormForState(control)) return; - FormControlState state = TakeStateForFormElement(control); - if (state.ValueSize() <= 0) - return; - // If a user already edited the control, we should not overwrite it. - if (IsDirtyControl(control)) - return; - control.RestoreFormControlState(state); + RestoreControlStateInternal(control); } void FormController::RestoreControlStateIn(HTMLFormElement& form) { @@ -595,26 +583,34 @@ for (const auto& control : elements) { if (!control->ClassSupportsStateRestore()) continue; - if (!control->ShouldSaveAndRestoreFormControlState()) - continue; if (OwnerFormForState(*control) != &form) continue; - FormControlState state = TakeStateForFormElement(*control); - if (state.ValueSize() <= 0) - continue; - // If a user already edited the control, we should not overwrite it. - if (IsDirtyControl(*control)) - continue; - // RestoreFormControlState might dispatch input/change events. - control->RestoreFormControlState(state); + RestoreControlStateInternal(*control); } } +void FormController::RestoreControlStateInternal(ListedElement& control) { + // We don't save state of a control with + // ShouldSaveAndRestoreFormControlState() == false. But we need to skip + // restoring process too because a control in another form might have the same + // pair of name and type and saved its state. + if (!control.ShouldSaveAndRestoreFormControlState()) + return; + FormControlState state = TakeStateForControl(control); + if (state.ValueSize() <= 0) + return; + // If a user already edited the control, we should not overwrite it. + if (IsDirtyControl(control)) + return; + // RestoreFormControlState might dispatch input/change events. + control.RestoreFormControlState(state); +} + void FormController::RestoreControlStateOnUpgrade(ListedElement& control) { DCHECK(control.ClassSupportsStateRestore()); if (!control.ShouldSaveAndRestoreFormControlState()) return; - FormControlState state = TakeStateForFormElement(control); + FormControlState state = TakeStateForControl(control); if (state.ValueSize() > 0) control.RestoreFormControlState(state); } @@ -633,7 +629,7 @@ return; HeapHashSet<Member<HTMLFormElement>> finished_forms; EventQueueScope scope; - for (auto& control : document_state_->ControlList()) { + for (auto& control : document_state_->GetControlList()) { auto* owner = OwnerFormForState(*control); if (!owner) RestoreControlStateFor(*control); @@ -646,7 +642,7 @@ const Vector<String>& state_vector) { Vector<String> to_return; SavedFormStateMap map; - FormStatesFromStateVector(state_vector, map); + ControlStatesFromStateVector(state_vector, map); for (const auto& saved_form_state : map) to_return.AppendVector(saved_form_state.value->GetReferencedFilePaths()); return to_return;
diff --git a/third_party/blink/renderer/core/html/forms/form_controller.h b/third_party/blink/renderer/core/html/forms/form_controller.h index 345d0be4b8..038439d 100644 --- a/third_party/blink/renderer/core/html/forms/form_controller.h +++ b/third_party/blink/renderer/core/html/forms/form_controller.h
@@ -39,6 +39,7 @@ class ListedElement; class SavedFormState; +// FormControlState represents state of a single form control. class FormControlState { DISALLOW_NEW(); @@ -83,17 +84,15 @@ DocumentState(Document& document); void Trace(Visitor*); - // TODO(tkent): Rename this to ControlList or something. The current - // name is confusing because it doesn't contain <form> elements. - using FormElementList = HeapVector<Member<ListedElement>, 64>; + using ControlList = HeapVector<Member<ListedElement>, 64>; void InvalidateControlList(); - const FormElementList& ControlList(); + const ControlList& GetControlList(); Vector<String> ToStateVector(); private: Member<Document> document_; - FormElementList form_controls_; - bool form_controls_dirty_ = true; + ControlList control_list_; + bool is_control_list_dirty_ = true; }; class CORE_EXPORT FormController final @@ -104,13 +103,13 @@ void Trace(Visitor*); void InvalidateStatefulFormControlList(); - // This should be callled only by Document::formElementsState(). - DocumentState* FormElementsState() const; - // This should be callled only by Document::setStateForNewFormElements(). - void SetStateForNewFormElements(const Vector<String>&); + // This should be called only by Document::FormElementsState(). + DocumentState* ControlStates() const; + // This should be called only by Document::SetStateForNewFormElements(). + void SetStateForNewControls(const Vector<String>&); // Returns true if saved state is set to this object and there are entries // which are not consumed yet. - bool HasFormStates() const; + bool HasControlStates() const; void WillDeleteForm(HTMLFormElement*); void RestoreControlStateFor(ListedElement&); void RestoreControlStateIn(HTMLFormElement&); @@ -123,9 +122,11 @@ const Vector<String>& state_vector); private: - FormControlState TakeStateForFormElement(const ListedElement&); - static void FormStatesFromStateVector(const Vector<String>&, - SavedFormStateMap&); + FormControlState TakeStateForControl(const ListedElement&); + static void ControlStatesFromStateVector(const Vector<String>&, + SavedFormStateMap&); + // A helper for RestoreControlStateFor() and RestoreControlStateIn(). + void RestoreControlStateInternal(ListedElement& control); void RestoreAllControlsInDocumentOrder(); Member<Document> document_;
diff --git a/third_party/blink/renderer/core/html/forms/form_controller_test.cc b/third_party/blink/renderer/core/html/forms/form_controller_test.cc index dddbe3c7d..b278e95 100644 --- a/third_party/blink/renderer/core/html/forms/form_controller_test.cc +++ b/third_party/blink/renderer/core/html/forms/form_controller_test.cc
@@ -21,7 +21,7 @@ doc.appendChild(html); Node* body = html->appendChild(doc.CreateRawElement(html_names::kBodyTag)); To<Element>(body)->SetInnerHTMLFromString("<select form='ff'></select>"); - DocumentState* document_state = doc.GetFormController().FormElementsState(); + DocumentState* document_state = doc.GetFormController().ControlStates(); Vector<String> state1 = document_state->ToStateVector(); // <signature>, <control-size>, <form-key>, <name>, <type>, <data-size(0)> EXPECT_EQ(6u, state1.size());
diff --git a/third_party/blink/renderer/core/html/forms/html_input_element.cc b/third_party/blink/renderer/core/html/forms/html_input_element.cc index f187ad8..f32097f7 100644 --- a/third_party/blink/renderer/core/html/forms/html_input_element.cc +++ b/third_party/blink/renderer/core/html/forms/html_input_element.cc
@@ -789,7 +789,7 @@ // attribute. So, delay the setChecked() call until // finishParsingChildren() is called if parsing is in progress. if ((!parsing_in_progress_ || - !GetDocument().GetFormController().HasFormStates()) && + !GetDocument().GetFormController().HasControlStates()) && !dirty_checkedness_) { setChecked(!value.IsNull()); dirty_checkedness_ = false;
diff --git a/third_party/blink/renderer/core/inspector/browser_protocol.pdl b/third_party/blink/renderer/core/inspector/browser_protocol.pdl index 7f49d8d..1c8c7d0c 100644 --- a/third_party/blink/renderer/core/inspector/browser_protocol.pdl +++ b/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -2690,6 +2690,11 @@ # Orientation angle. integer angle + type MediaFeature extends object + properties + string name + string value + # advance: If the scheduler runs out of immediate work, the virtual time base may fast forward to # allow the next delayed task (if any) to run; pause: The virtual time base may not advance; # pauseIfNetworkFetchesPending: The virtual time base may not advance if there are any pending @@ -2786,11 +2791,13 @@ mobile desktop - # Emulates the given media for CSS media queries. + # Emulates the given media type or media feature for CSS media queries. command setEmulatedMedia parameters # Media type to emulate. Empty string disables the override. - string media + optional string media + # Media features to emulate. + optional array of MediaFeature features # Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position # unavailable.
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 e8ac412..ce8b2e3 100644 --- a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
@@ -38,6 +38,7 @@ touch_event_emulation_enabled_(&agent_state_, /*default_value=*/false), max_touch_points_(&agent_state_, /*default_value=*/1), emulated_media_(&agent_state_, /*default_value=*/WTF::String()), + emulated_media_features_(&agent_state_, /*default_value=*/WTF::String()), navigator_platform_override_(&agent_state_, /*default_value=*/WTF::String()), user_agent_override_(&agent_state_, /*default_value=*/WTF::String()), @@ -89,7 +90,16 @@ GetWebViewImpl()->GetDevToolsEmulator()->SetDocumentCookieDisabled(true); setTouchEmulationEnabled(touch_event_emulation_enabled_.Get(), max_touch_points_.Get()); - setEmulatedMedia(emulated_media_.Get()); + auto features = + std::make_unique<protocol::Array<protocol::Emulation::MediaFeature>>(); + for (auto const& name : emulated_media_features_.Keys()) { + auto const& value = emulated_media_features_.Get(name); + features->push_back(std::move(protocol::Emulation::MediaFeature::create() + .setName(name) + .setValue(value) + .build())); + } + setEmulatedMedia(emulated_media_.Get(), std::move(features)); auto rgba = ParseRGBA(default_background_color_override_rgba_.Get()); if (rgba) setDefaultBackgroundColorOverride(std::move(rgba)); @@ -145,7 +155,12 @@ setScrollbarsHidden(false); setDocumentCookieDisabled(false); setTouchEmulationEnabled(false, Maybe<int>()); - setEmulatedMedia(String()); + // Clear emulated media features. Note that the current approach + // doesn't work well in cases where two clients have the same set of + // features overridden to the same value by two different clients + // (e.g. if we allowed two different front-ends with the same + // settings to attach to the same page). TODO: support this use case. + setEmulatedMedia(String(), {}); setCPUThrottlingRate(1); setFocusEmulationEnabled(false); setDefaultBackgroundColorOverride(Maybe<protocol::DOM::RGBA>()); @@ -220,12 +235,35 @@ return response; } -Response InspectorEmulationAgent::setEmulatedMedia(const String& media) { +Response InspectorEmulationAgent::setEmulatedMedia( + Maybe<String> media, + Maybe<protocol::Array<protocol::Emulation::MediaFeature>> features) { Response response = AssertPage(); if (!response.isSuccess()) return response; - emulated_media_.Set(media); - GetWebViewImpl()->GetPage()->GetSettings().SetMediaTypeOverride(media); + if (media.isJust()) { + auto mediaValue = media.takeJust(); + emulated_media_.Set(mediaValue); + GetWebViewImpl()->GetPage()->GetSettings().SetMediaTypeOverride(mediaValue); + } else { + emulated_media_.Set(""); + GetWebViewImpl()->GetPage()->GetSettings().SetMediaTypeOverride(""); + } + for (const WTF::String& feature : emulated_media_features_.Keys()) { + GetWebViewImpl()->GetPage()->SetMediaFeatureOverride(AtomicString(feature), + ""); + } + emulated_media_features_.Clear(); + if (features.isJust()) { + auto featuresValue = features.takeJust(); + for (auto const& mediaFeature : *featuresValue.get()) { + auto const& name = mediaFeature->getName(); + auto const& value = mediaFeature->getValue(); + emulated_media_features_.Set(name, value); + GetWebViewImpl()->GetPage()->SetMediaFeatureOverride(AtomicString(name), + value); + } + } return response; }
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 8704f250..87a2fd3 100644 --- a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
@@ -44,7 +44,10 @@ protocol::Response setTouchEmulationEnabled( bool enabled, protocol::Maybe<int> max_touch_points) override; - protocol::Response setEmulatedMedia(const String&) override; + protocol::Response setEmulatedMedia( + protocol::Maybe<String> media, + protocol::Maybe<protocol::Array<protocol::Emulation::MediaFeature>> + features) override; protocol::Response setCPUThrottlingRate(double) override; protocol::Response setFocusEmulationEnabled(bool) override; protocol::Response setVirtualTimePolicy( @@ -122,6 +125,7 @@ InspectorAgentState::Boolean touch_event_emulation_enabled_; InspectorAgentState::Integer max_touch_points_; InspectorAgentState::String emulated_media_; + InspectorAgentState::StringMap emulated_media_features_; InspectorAgentState::String navigator_platform_override_; InspectorAgentState::String user_agent_override_; InspectorAgentState::String accept_language_override_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc b/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc index 5c8dc0d..bce7ab9 100644 --- a/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc +++ b/third_party/blink/renderer/core/inspector/inspector_style_sheet.cc
@@ -539,7 +539,6 @@ case CSSRule::kFontFaceRule: case CSSRule::kViewportRule: case CSSRule::kKeyframeRule: - case CSSRule::kFontFeatureValuesRule: result->push_back(rule); break; case CSSRule::kMediaRule:
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index b4ca10c..1dc8334 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -468,7 +468,7 @@ same_document_navigation_source == kSameDocumentNavigationHistoryApi ? HistoryNavigationType::kHistoryApi : HistoryNavigationType::kFragment); - history_item_->SetDocumentState(frame_->GetDocument()->FormElementsState()); + history_item_->SetDocumentState(frame_->GetDocument()->GetDocumentState()); if (same_document_navigation_source == kSameDocumentNavigationHistoryApi) { history_item_->SetStateObject(std::move(data)); history_item_->SetScrollRestorationType(scroll_restoration_type); @@ -1338,7 +1338,7 @@ document->BindContentSecurityPolicy(); if (history_item_ && IsBackForwardLoadType(load_type_)) - document->SetStateForNewFormElements(history_item_->GetDocumentState()); + document->SetStateForNewControls(history_item_->GetDocumentState()); DCHECK(document->GetFrame()); // TODO(dgozman): modify frame's client hints directly once we commit
diff --git a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc index 6a3777c0..7f774ab 100644 --- a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc +++ b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
@@ -404,9 +404,8 @@ if (HasPlaceholderCanvas()) { needs_push_frame_ = true; - // TODO(fserb): perhaps we could avoid requesting begin frames here in cases - // where the draw is call from within a worker rAF? - GetOrCreateResourceDispatcher()->SetNeedsBeginFrame(true); + if (!inside_worker_raf_) + GetOrCreateResourceDispatcher()->SetNeedsBeginFrame(true); } } @@ -423,13 +422,6 @@ return false; } -bool OffscreenCanvas::ShouldAccelerate2dContext() const { - base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper = - SharedGpuContext::ContextProviderWrapper(); - return context_provider_wrapper && - context_provider_wrapper->Utils()->Accelerated2DCanvasFeatureEnabled(); -} - bool OffscreenCanvas::PushFrame(scoped_refptr<CanvasResource> canvas_resource, const SkIRect& damage_rect) { TRACE_EVENT0("blink", "OffscreenCanvas::PushFrame"); @@ -447,6 +439,13 @@ return true; } +bool OffscreenCanvas::ShouldAccelerate2dContext() const { + base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper = + SharedGpuContext::ContextProviderWrapper(); + return context_provider_wrapper && + context_provider_wrapper->Utils()->Accelerated2DCanvasFeatureEnabled(); +} + FontSelector* OffscreenCanvas::GetFontSelector() { if (auto* document = DynamicTo<Document>(GetExecutionContext())) { return document->GetStyleEngine().GetFontSelector();
diff --git a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h index fb72bf6..92542d2 100644 --- a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h +++ b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h
@@ -179,6 +179,30 @@ void Trace(blink::Visitor*) override; + class ScopedInsideWorkerRAF { + STACK_ALLOCATED(); + + public: + ScopedInsideWorkerRAF() {} + + void AddOffscreenCanvas(OffscreenCanvas* canvas) { + DCHECK(!canvas->inside_worker_raf_); + canvas->inside_worker_raf_ = true; + canvases_.push_back(canvas); + } + + ~ScopedInsideWorkerRAF() { + for (auto canvas : canvases_) { + DCHECK(canvas->inside_worker_raf_); + canvas->inside_worker_raf_ = false; + canvas->PushFrameIfNeeded(); + } + } + + private: + HeapVector<Member<OffscreenCanvas>> canvases_; + }; + private: int32_t memory_usage_ = 0; @@ -195,7 +219,6 @@ IntSize size_; bool is_neutered_ = false; - bool origin_clean_ = true; bool disable_reading_from_canvas_ = false; @@ -205,6 +228,7 @@ bool needs_matrix_clip_restore_ = false; bool needs_push_frame_ = false; + bool inside_worker_raf_ = false; SkFilterQuality filter_quality_ = kLow_SkFilterQuality;
diff --git a/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc b/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc index a41b97c..5b3d161 100644 --- a/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc +++ b/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
@@ -42,6 +42,29 @@ if (url.FragmentIdentifier().Find("#targetText=") == kNotFound) UseCounter::Count(frame.GetDocument(), WebFeature::kFragmentDoubleHash); } + + // Count cases of other delimiter candidates. We don't care about whether + // they're followed by targetText since they've never been used with it. + if (url.FragmentIdentifier().Find("~&~") != kNotFound) { + UseCounter::Count(frame.GetDocument(), + WebFeature::kFragmentHasTildeAmpersandTilde); + } + if (url.FragmentIdentifier().Find("~@~") != kNotFound) { + UseCounter::Count(frame.GetDocument(), + WebFeature::kFragmentHasTildeAtTilde); + } + if (url.FragmentIdentifier().Find("&delimiter?") != kNotFound) { + UseCounter::Count(frame.GetDocument(), + WebFeature::kFragmentHasAmpersandDelimiterQuestion); + } + } + + // For the actual delimiter, we must determine whether to use count it at + // the point where we strip the directive. We can't use count it at that + // point because the DocumentLoader hasn't yet been created. + if (frame.GetDocument()->UseCountFragmentDirective()) { + UseCounter::Count(frame.GetDocument(), + WebFeature::kFragmentHasColonTildeColon); } bool element_id_anchor_found = false;
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc index cd4d725..ddf99f2 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc
@@ -25,11 +25,6 @@ namespace { -constexpr char kTextFragmentIdentifierPrefix[] = "targetText="; -// Subtract 1 because base::size includes the \0 string terminator. -constexpr size_t kTextFragmentIdentifierPrefixStringLength = - base::size(kTextFragmentIdentifierPrefix) - 1; - bool ParseTargetTextIdentifier(const String& fragment, Vector<TextFragmentSelector>* out_selectors) { DCHECK(out_selectors); @@ -37,8 +32,9 @@ size_t start_pos = 0; size_t end_pos = 0; while (end_pos != kNotFound) { - if (fragment.Find(kTextFragmentIdentifierPrefix, start_pos) != start_pos) + if (fragment.Find(kTextFragmentIdentifierPrefix, start_pos) != start_pos) { return false; + } start_pos += kTextFragmentIdentifierPrefixStringLength; end_pos = fragment.find('&', start_pos); @@ -110,8 +106,11 @@ Vector<TextFragmentSelector> selectors; if (!ParseTargetTextIdentifier(frame.GetDocument()->GetFragmentDirective(), - &selectors)) + &selectors)) { + UseCounter::Count(frame.GetDocument(), + WebFeature::kInvalidFragmentDirective); return nullptr; + } return MakeGarbageCollected<TextFragmentAnchor>( selectors, frame, TextFragmentFormat::FragmentDirective);
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h index 7a6453b9..b591a31 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h
@@ -31,6 +31,11 @@ constexpr size_t kFragmentDirectiveNewPrefixStringLength = base::size(kFragmentDirectiveNewPrefix) - 1; +constexpr char kTextFragmentIdentifierPrefix[] = "targetText="; +// Subtract 1 because base::size includes the \0 string terminator. +constexpr size_t kTextFragmentIdentifierPrefixStringLength = + base::size(kTextFragmentIdentifierPrefix) - 1; + enum class TextFragmentFormat { PlainFragment, FragmentDirective }; class CORE_EXPORT TextFragmentAnchor final : public FragmentAnchor,
diff --git a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc index f4c3c9a..ea873ec 100644 --- a/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc +++ b/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc
@@ -288,6 +288,47 @@ GetDocument().IsUseCounted(WebFeature::kTextFragmentAnchorTapToDismiss)); } +// Test counting cases where the fragment directive fails to parse. +TEST_F(TextFragmentAnchorMetricsTest, InvalidFragmentDirective) { + const int kUncounted = 0; + const int kCounted = 1; + + Vector<std::pair<String, int>> test_cases = { + {"", kUncounted}, + {"#element", kUncounted}, + {"#doesntExist", kUncounted}, + {"#:~:element", kCounted}, + {"#element:~:", kCounted}, + {"#foo:~:bar", kCounted}, + {"#:~:utargetText=foo", kCounted}, + {"#:~:targetText=foo", kUncounted}, + {"#:~:targetText=foo&invalid", kCounted}, + {"#foo:~:targetText=foo", kUncounted}}; + + for (auto test_case : test_cases) { + String url = "https://example.com/test.html" + test_case.first; + SimRequest request(url, "text/html"); + LoadURL(url); + request.Complete(R"HTML( + <!DOCTYPE html> + <p id="element">This is a test page</p> + )HTML"); + Compositor().BeginFrame(); + + RunAsyncMatchingTasks(); + + bool is_use_counted = + GetDocument().IsUseCounted(WebFeature::kInvalidFragmentDirective); + if (test_case.second == kCounted) { + EXPECT_TRUE(is_use_counted) + << "Expected invalid directive in case: " << test_case.first; + } else { + EXPECT_FALSE(is_use_counted) + << "Expected valid directive in case: " << test_case.first; + } + } +} + class TextFragmentRelatedMetricTest : public TextFragmentAnchorMetricsTest, public testing::WithParamInterface<bool> { public: @@ -457,6 +498,167 @@ } } +// Test counting occurrences of ~&~ in the URL fragment. Used for potentially +// using ~&~ as a delimiter. Can be removed once the feature ships. +TEST_P(TextFragmentRelatedMetricTest, TildeAmpersandTildeUseCounter) { + const int kUncounted = 0; + const int kCounted = 1; + + Vector<std::pair<String, int>> test_cases = { + {"", kUncounted}, + {"#element", kUncounted}, + {"#doesntExist", kUncounted}, + {"#~&~element", kCounted}, + {"#element~&~", kCounted}, + {"#foo~&~bar", kCounted}, + {"#foo~&~targetText=foo", kCounted}}; + + for (auto test_case : test_cases) { + String url = "https://example.com/test.html" + test_case.first; + SimRequest request(url, "text/html"); + LoadURL(url); + request.Complete(R"HTML( + <!DOCTYPE html> + <p id="element">This is a test page</p> + )HTML"); + Compositor().BeginFrame(); + + RunAsyncMatchingTasks(); + + bool is_use_counted = + GetDocument().IsUseCounted(WebFeature::kFragmentHasTildeAmpersandTilde); + if (test_case.second == kCounted) { + EXPECT_TRUE(is_use_counted) + << "Expected to count ~&~ but didn't in case: " << test_case.first; + } else { + EXPECT_FALSE(is_use_counted) + << "Expected not to count ~&~ but did in case: " << test_case.first; + } + } +} + +// Test counting occurrences of ~@~ in the URL fragment. Used for potentially +// using ~@~ as a delimiter. Can be removed once the feature ships. +TEST_P(TextFragmentRelatedMetricTest, TildeAtTildeUseCounter) { + const int kUncounted = 0; + const int kCounted = 1; + + Vector<std::pair<String, int>> test_cases = { + {"", kUncounted}, + {"#element", kUncounted}, + {"#doesntExist", kUncounted}, + {"#~@~element", kCounted}, + {"#element~@~", kCounted}, + {"#foo~@~bar", kCounted}, + {"#foo~@~targetText=foo", kCounted}}; + + for (auto test_case : test_cases) { + String url = "https://example.com/test.html" + test_case.first; + SimRequest request(url, "text/html"); + LoadURL(url); + request.Complete(R"HTML( + <!DOCTYPE html> + <p id="element">This is a test page</p> + )HTML"); + Compositor().BeginFrame(); + + RunAsyncMatchingTasks(); + + bool is_use_counted = + GetDocument().IsUseCounted(WebFeature::kFragmentHasTildeAtTilde); + if (test_case.second == kCounted) { + EXPECT_TRUE(is_use_counted) + << "Expected to count ~@~ but didn't in case: " << test_case.first; + } else { + EXPECT_FALSE(is_use_counted) + << "Expected not to count ~@~ but did in case: " << test_case.first; + } + } +} + +// Test counting occurrences of &delimiter? in the URL fragment. Used for +// potentially using &delimiter? as a delimiter. Can be removed once the +// feature ships. +TEST_P(TextFragmentRelatedMetricTest, AmpersandDelimiterQuestionUseCounter) { + const int kUncounted = 0; + const int kCounted = 1; + + Vector<std::pair<String, int>> test_cases = { + {"", kUncounted}, + {"#element", kUncounted}, + {"#doesntExist", kUncounted}, + {"#&delimiter?element", kCounted}, + {"#element&delimiter?", kCounted}, + {"#foo&delimiter?bar", kCounted}, + {"#foo&delimiter?targetText=foo", kCounted}}; + + for (auto test_case : test_cases) { + String url = "https://example.com/test.html" + test_case.first; + SimRequest request(url, "text/html"); + LoadURL(url); + request.Complete(R"HTML( + <!DOCTYPE html> + <p id="element">This is a test page</p> + )HTML"); + Compositor().BeginFrame(); + + RunAsyncMatchingTasks(); + + bool is_use_counted = GetDocument().IsUseCounted( + WebFeature::kFragmentHasAmpersandDelimiterQuestion); + if (test_case.second == kCounted) { + EXPECT_TRUE(is_use_counted) + << "Expected to count &delimiter? but didn't in case: " + << test_case.first; + } else { + EXPECT_FALSE(is_use_counted) + << "Expected not to count &delimiter? but did in case: " + << test_case.first; + } + } +} + +// Test counting occurrences of non-targetText :~: in the URL fragment. Used to +// ensure :~: is web-compatible; can be removed once the feature ships. +TEST_P(TextFragmentRelatedMetricTest, NewDelimiterUseCounter) { + const int kUncounted = 0; + const int kCounted = 1; + + Vector<std::pair<String, int>> test_cases = { + {"", kUncounted}, + {"#element", kUncounted}, + {"#doesntExist", kUncounted}, + {"#:~:element", kCounted}, + {"#element:~:", kCounted}, + {"#foo:~:bar", kCounted}, + {"#:~:utargetText=foo", kCounted}, + {"#:~:targetText=foo", kUncounted}, + {"#foo:~:targetText=foo", kUncounted}}; + + for (auto test_case : test_cases) { + String url = "https://example.com/test.html" + test_case.first; + SimRequest request(url, "text/html"); + LoadURL(url); + request.Complete(R"HTML( + <!DOCTYPE html> + <p id="element">This is a test page</p> + )HTML"); + Compositor().BeginFrame(); + + RunAsyncMatchingTasks(); + + bool is_use_counted = + GetDocument().IsUseCounted(WebFeature::kFragmentHasColonTildeColon); + if (test_case.second == kCounted) { + EXPECT_TRUE(is_use_counted) + << "Expected to count :~: but didn't in case: " << test_case.first; + } else { + EXPECT_FALSE(is_use_counted) + << "Expected not to count :~: but did in case: " << test_case.first; + } + } +} + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/core/script/module_script.cc b/third_party/blink/renderer/core/script/module_script.cc index 3c4b687..2da6b2d 100644 --- a/third_party/blink/renderer/core/script/module_script.cc +++ b/third_party/blink/renderer/core/script/module_script.cc
@@ -50,23 +50,29 @@ DCHECK(!error.IsEmpty()); record_.Clear(); - parse_error_ = error.ToWorldSafeV8Reference(); + parse_error_.Set(settings_object_->GetScriptState()->GetIsolate(), + error.V8Value()); } ScriptValue ModuleScript::CreateParseError() const { - v8::Isolate* isolate = settings_object_->GetScriptState()->GetIsolate(); - ScriptValue error(isolate, parse_error_); + ScriptState* script_state = settings_object_->GetScriptState(); + ScriptState::Scope scope(script_state); + ScriptValue error(script_state->GetIsolate(), parse_error_.Get(script_state)); DCHECK(!error.IsEmpty()); return error; } void ModuleScript::SetErrorToRethrow(ScriptValue error) { - error_to_rethrow_ = error.ToWorldSafeV8Reference(); + ScriptState* script_state = settings_object_->GetScriptState(); + ScriptState::Scope scope(script_state); + error_to_rethrow_.Set(script_state->GetIsolate(), error.V8Value()); } ScriptValue ModuleScript::CreateErrorToRethrow() const { - v8::Isolate* isolate = settings_object_->GetScriptState()->GetIsolate(); - ScriptValue error(isolate, error_to_rethrow_); + ScriptState* script_state = settings_object_->GetScriptState(); + ScriptState::Scope scope(script_state); + ScriptValue error(script_state->GetIsolate(), + error_to_rethrow_.Get(script_state)); DCHECK(!error.IsEmpty()); return error; }
diff --git a/third_party/blink/renderer/core/script/pending_import_map.cc b/third_party/blink/renderer/core/script/pending_import_map.cc index d5fd6dc..b2f0642 100644 --- a/third_party/blink/renderer/core/script/pending_import_map.cc +++ b/third_party/blink/renderer/core/script/pending_import_map.cc
@@ -18,18 +18,20 @@ const KURL& base_url) { Document& element_document = element.GetDocument(); Document* context_document = element_document.ContextDocument(); - Modulator* modulator = - Modulator::From(ToScriptStateForMainWorld(context_document->GetFrame())); + ScriptState* script_state = + ToScriptStateForMainWorld(context_document->GetFrame()); + Modulator* modulator = Modulator::From(script_state); ScriptValue error_to_rethrow; ImportMap* import_map = ImportMap::Parse(*modulator, import_map_text, base_url, *context_document, &error_to_rethrow); return MakeGarbageCollected<PendingImportMap>( - element, import_map, error_to_rethrow, *context_document); + script_state, element, import_map, error_to_rethrow, *context_document); } -PendingImportMap::PendingImportMap(ScriptElementBase& element, +PendingImportMap::PendingImportMap(ScriptState* script_state, + ScriptElementBase& element, ImportMap* import_map, ScriptValue error_to_rethrow, const Document& original_context_document) @@ -37,7 +39,9 @@ import_map_(import_map), original_context_document_(&original_context_document) { if (!error_to_rethrow.IsEmpty()) { - error_to_rethrow_ = error_to_rethrow.ToWorldSafeV8Reference(); + ScriptState::Scope scope(script_state); + error_to_rethrow_.Set(script_state->GetIsolate(), + error_to_rethrow.V8Value()); } } @@ -81,8 +85,13 @@ Modulator* modulator = Modulator::From(ToScriptStateForMainWorld(frame)); - v8::Isolate* isolate = modulator->GetScriptState()->GetIsolate(); - ScriptValue error(isolate, error_to_rethrow_); + ScriptState* script_state = modulator->GetScriptState(); + ScriptState::Scope scope(script_state); + ScriptValue error; + if (!error_to_rethrow_.IsEmpty()) { + error = ScriptValue(script_state->GetIsolate(), + error_to_rethrow_.Get(script_state)); + } modulator->RegisterImportMap(import_map_, error); // <spec step="9">If element is from an external file, then fire an event
diff --git a/third_party/blink/renderer/core/script/pending_import_map.h b/third_party/blink/renderer/core/script/pending_import_map.h index 5fb56f7..f4005ba 100644 --- a/third_party/blink/renderer/core/script/pending_import_map.h +++ b/third_party/blink/renderer/core/script/pending_import_map.h
@@ -40,7 +40,8 @@ const String& import_map_text, const KURL& base_url); - PendingImportMap(ScriptElementBase&, + PendingImportMap(ScriptState* script_state, + ScriptElementBase&, ImportMap*, ScriptValue error_to_rethrow, const Document& original_context_document);
diff --git a/third_party/blink/renderer/core/streams/transform_stream_transformer.h b/third_party/blink/renderer/core/streams/transform_stream_transformer.h index 9a1b9a3..cbbb5b3 100644 --- a/third_party/blink/renderer/core/streams/transform_stream_transformer.h +++ b/third_party/blink/renderer/core/streams/transform_stream_transformer.h
@@ -14,6 +14,7 @@ namespace blink { class ExceptionState; +class ScriptState; class TransformStreamDefaultControllerInterface; class Visitor;
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 6a9790d8..3b3d0d62 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
@@ -74,11 +74,15 @@ SVGSMILElement::Condition* condition) : animation_(animation), condition_(condition) {} - bool Matches(const EventListener& other) const override; - void DisconnectAnimation() { animation_ = nullptr; } - void Invoke(ExecutionContext*, Event*) override; + void Invoke(ExecutionContext*, Event*) override { + if (!animation_) + return; + animation_->AddInstanceTime(condition_->GetBeginOrEnd(), + animation_->Elapsed() + condition_->Offset(), + SMILTimeOrigin::kEvent); + } void Trace(blink::Visitor* visitor) override { visitor->Trace(animation_); @@ -86,40 +90,11 @@ NativeEventListener::Trace(visitor); } - bool IsConditionEventListener() const override { return true; } - private: Member<SVGSMILElement> animation_; Member<SVGSMILElement::Condition> condition_; }; -template <> -struct DowncastTraits<ConditionEventListener> { - static bool AllowFrom(const EventListener& event_listener) { - const NativeEventListener* native_event_listener = - DynamicTo<NativeEventListener>(event_listener); - return native_event_listener && - native_event_listener->IsConditionEventListener(); - } -}; - -bool ConditionEventListener::Matches(const EventListener& listener) const { - if (const ConditionEventListener* condition_event_listener = - DynamicTo<ConditionEventListener>(listener)) { - return animation_ == condition_event_listener->animation_ && - condition_ == condition_event_listener->condition_; - } - return false; -} - -void ConditionEventListener::Invoke(ExecutionContext*, Event* event) { - if (!animation_) - return; - animation_->AddInstanceTime(condition_->GetBeginOrEnd(), - animation_->Elapsed() + condition_->Offset(), - SMILTimeOrigin::kEvent); -} - SVGSMILElement::Condition::Condition(Type type, BeginOrEnd begin_or_end, const AtomicString& base_id, @@ -170,6 +145,7 @@ SVGSMILElement& timed_element) { DCHECK_EQ(type_, kEventBase); DCHECK(!base_element_); + DCHECK(!event_listener_); SVGElement* target; if (base_id_.IsEmpty()) { target = timed_element.targetElement(); @@ -181,7 +157,6 @@ } if (!target) return; - DCHECK(!event_listener_); event_listener_ = MakeGarbageCollected<ConditionEventListener>(&timed_element, this); base_element_ = target; @@ -513,7 +488,7 @@ ParseBeginOrEnd(value.GetString(), kBegin); if (isConnected()) { ConnectConditions(); - InstanceListChanged(kBegin); + InstanceListChanged(); if (time_container_) time_container_->NotifyIntervalsChanged(); } @@ -526,7 +501,7 @@ ParseBeginOrEnd(value.GetString(), kEnd); if (isConnected()) { ConnectConditions(); - InstanceListChanged(kEnd); + InstanceListChanged(); if (time_container_) time_container_->NotifyIntervalsChanged(); } @@ -731,7 +706,7 @@ begin_or_end == kBegin ? begin_times_ : end_times_; InsertSortedAndUnique(list, SMILTimeWithOrigin(time, origin)); - InstanceListChanged(begin_or_end); + InstanceListChanged(); if (time_container_) time_container_->NotifyIntervalsChanged(); } @@ -865,7 +840,7 @@ FindInstanceTime(kBegin, presentation_time, false)); } -void SVGSMILElement::InstanceListChanged(BeginOrEnd begin_or_end) { +void SVGSMILElement::InstanceListChanged() { if (is_waiting_for_first_interval_) { ResolveFirstInterval(); return; @@ -873,41 +848,17 @@ SMILTime current_presentation_time = time_container_ ? time_container_->CurrentDocumentTime() : SMILTime(); DCHECK(!current_presentation_time.IsUnresolved()); - if (begin_or_end == kEnd) { - // If we have no current interval, or the current interval ends before the - // indicated time, then a new 'end' instance time will have no effect. - if (!interval_.IsResolved() || - interval_.EndsBefore(current_presentation_time)) - return; - SMILTime new_end = FindInstanceTime(kEnd, interval_.begin, false); - if (interval_.EndsBefore(new_end)) - return; - new_end = ResolveActiveEnd(interval_.begin, new_end); - if (new_end != interval_.end) { - interval_.end = new_end; - NotifyDependentsOnNewInterval(interval_); - } - return; + DiscardOrRevalidateCurrentInterval(current_presentation_time); + SMILInterval old_interval = interval_; + if (!interval_.IsResolved()) { + // We have no current interval, try to resolve one. + interval_ = + ResolveInterval(SMILTime::Earliest(), current_presentation_time); + } else { + // We have a current interval, check if it needs to be updated. + CheckAndUpdateInterval(current_presentation_time); } - // Never resolve more than one interval when restart is 'never'. - if (GetRestart() == kRestartNever) - return; - SMILTime new_begin = - FindInstanceTime(kBegin, current_presentation_time, true); - if (!new_begin.IsFinite()) - return; - // If the current interval is active and contains the new begin time, then we - // will pick up a potentially new interval during the regular interval - // update. - if (interval_.BeginsBefore(new_begin) && - interval_.EndsAfter(current_presentation_time)) - return; - // Begin time changed, re-resolve the interval. - SMILTime old_begin = interval_.begin; - interval_ = - ResolveInterval(current_presentation_time, current_presentation_time); - DCHECK(interval_.IsResolved()); - if (interval_.begin != old_begin) { + if (interval_ != old_interval) { if (GetActiveState() == kActive && interval_.BeginsAfter(current_presentation_time)) { active_state_ = DetermineActiveState(current_presentation_time); @@ -915,6 +866,30 @@ EndedActiveInterval(); } NotifyDependentsOnNewInterval(interval_); + interval_has_changed_ = false; + } +} + +void SVGSMILElement::DiscardOrRevalidateCurrentInterval( + SMILTime presentation_time) { + if (!interval_.IsResolved()) + return; + // If the current interval has not yet started, discard it and re-resolve. + if (interval_.BeginsAfter(presentation_time)) { + interval_ = {SMILTime::Unresolved(), SMILTime::Unresolved()}; + return; + } + + // If we have a current interval but it has not yet ended, re-resolve the + // end time. + if (interval_.EndsAfter(presentation_time)) { + SMILTime new_end = FindInstanceTime(kEnd, interval_.begin, false); + DCHECK(!new_end.IsUnresolved()); + new_end = ResolveActiveEnd(interval_.begin, new_end); + if (new_end != interval_.end) { + interval_.end = new_end; + NotifyDependentsOnNewInterval(interval_); + } } }
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 75960c0..8020ba62 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
@@ -86,6 +86,7 @@ SMILTime SimpleDuration() const; bool CurrentIntervalIsActive(SMILTime elapsed); + void DiscardOrRevalidateCurrentInterval(SMILTime presentation_time); // Check if the current interval is still current, and if not compute the // next interval. void CheckAndUpdateInterval(SMILTime elapsed); @@ -178,7 +179,7 @@ SMILTime RepeatingDuration() const; const SMILInterval& GetActiveInterval(SMILTime elapsed) const; - void InstanceListChanged(BeginOrEnd); + void InstanceListChanged(); // This represents conditions on elements begin or end list that need to be // resolved on runtime, for example
diff --git a/third_party/blink/renderer/devtools/.eslintrc.js b/third_party/blink/renderer/devtools/.eslintrc.js index 401bb011..3dc9c01 100644 --- a/third_party/blink/renderer/devtools/.eslintrc.js +++ b/third_party/blink/renderer/devtools/.eslintrc.js
@@ -1,17 +1,11 @@ module.exports = { - "root": true, + 'root': true, - "env": { - "browser": true, - "es6": true - }, + 'env': {'browser': true, 'es6': true}, - "parserOptions": { - "ecmaVersion": 9, - "sourceType": "module" - }, + 'parserOptions': {'ecmaVersion': 9, 'sourceType': 'module'}, - /** + /** * ESLint rules * * All available rules: http://eslint.org/docs/rules/ @@ -20,112 +14,95 @@ * "rule-name", [severity, { opts }] * Severity: 2 == error, 1 == warning, 0 == off. */ - "rules": { - /** + 'rules': { + /** * Enforced rules */ - // syntax preferences - "quotes": [2, "single", { - "avoidEscape": true, - "allowTemplateLiterals": true - }], - "semi": 2, - "no-extra-semi": 2, - "comma-style": [2, "last"], - "wrap-iife": [2, "inside"], - "spaced-comment": [2, "always", { - "markers": ["*"] - }], - "eqeqeq": [2], - "accessor-pairs": [2, { - "getWithoutSet": false, - "setWithoutGet": false - }], - "curly": [2, "multi-or-nest", "consistent"], - "new-parens": 2, - "func-call-spacing": 2, - "arrow-parens": [2, "as-needed"], + // syntax preferences + 'quotes': [2, 'single', {'avoidEscape': true, 'allowTemplateLiterals': true}], + 'semi': 2, + 'no-extra-semi': 2, + 'comma-style': [2, 'last'], + 'wrap-iife': [2, 'inside'], + 'spaced-comment': [2, 'always', {'markers': ['*']}], + 'eqeqeq': [2], + 'accessor-pairs': [2, {'getWithoutSet': false, 'setWithoutGet': false}], + 'curly': 2, + 'new-parens': 2, + 'func-call-spacing': 2, + 'arrow-parens': [2, 'as-needed'], - // anti-patterns - "no-with": 2, - "no-multi-str": 2, - "no-caller": 2, - "no-implied-eval": 2, - "no-labels": 2, - "no-new-object": 2, - "no-octal-escape": 2, - "no-self-compare": 2, - "no-shadow-restricted-names": 2, - "no-cond-assign": 2, - "no-debugger": 2, - "no-console": [2, { "allow": ["assert", "context", "error", "timeStamp", "time", "timeEnd", "warn"] }], - "no-dupe-keys": 2, - "no-duplicate-case": 2, - "no-empty-character-class": 2, - "no-unreachable": 2, - "no-unsafe-negation": 2, - "radix": 2, - "valid-typeof": 2, - "no-var": 2, - "prefer-const": 2, - "no-unused-vars": [2, { "args": "none", "vars": "local" }], + // anti-patterns + 'no-with': 2, + 'no-multi-str': 2, + 'no-caller': 2, + 'no-implied-eval': 2, + 'no-labels': 2, + 'no-new-object': 2, + 'no-octal-escape': 2, + 'no-self-compare': 2, + 'no-shadow-restricted-names': 2, + 'no-cond-assign': 2, + 'no-debugger': 2, + 'no-console': [2, {'allow': ['assert', 'context', 'error', 'timeStamp', 'time', 'timeEnd', 'warn']}], + 'no-dupe-keys': 2, + 'no-duplicate-case': 2, + 'no-empty-character-class': 2, + 'no-unreachable': 2, + 'no-unsafe-negation': 2, + 'radix': 2, + 'valid-typeof': 2, + 'no-var': 2, + 'prefer-const': 2, + 'no-unused-vars': [2, {'args': 'none', 'vars': 'local'}], - // es2015 features - "require-yield": 2, - "template-curly-spacing": [2, "never"], + // es2015 features + 'require-yield': 2, + 'template-curly-spacing': [2, 'never'], - // spacing details - "space-infix-ops": 2, - "space-in-parens": [2, "never"], - "space-before-function-paren": [2, { - "anonymous": "never", - "named": "never", - "asyncArrow": "always" - }], - "no-whitespace-before-property": 2, - "keyword-spacing": [2, { - "overrides": { - "if": {"after": true}, - "else": {"after": true}, - "for": {"after": true}, - "while": {"after": true}, - "do": {"after": true}, - "switch": {"after": true}, - "return": {"after": true} - } - }], - "arrow-spacing": [2, { - "after": true, - "before": true - }], + // spacing details + 'space-infix-ops': 2, + 'space-in-parens': [2, 'never'], + 'space-before-function-paren': [2, {'anonymous': 'never', 'named': 'never', 'asyncArrow': 'always'}], + 'no-whitespace-before-property': 2, + 'keyword-spacing': [ + 2, { + 'overrides': { + 'if': {'after': true}, + 'else': {'after': true}, + 'for': {'after': true}, + 'while': {'after': true}, + 'do': {'after': true}, + 'switch': {'after': true}, + 'return': {'after': true} + } + } + ], + 'arrow-spacing': [2, {'after': true, 'before': true}], - // file whitespace - "no-multiple-empty-lines": [2, {"max": 2}], - "no-mixed-spaces-and-tabs": 2, - "no-trailing-spaces": 2, - "linebreak-style": [ 2, "unix" ], + // file whitespace + 'no-multiple-empty-lines': [2, {'max': 2}], + 'no-mixed-spaces-and-tabs': 2, + 'no-trailing-spaces': 2, + 'linebreak-style': [2, 'unix'], - /** + /** * Disabled, aspirational rules */ - "indent": [0, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }], + 'indent': [0, 2, {'SwitchCase': 1, 'CallExpression': {'arguments': 2}, 'MemberExpression': 2}], - // brace-style is disabled, as eslint cannot enforce 1tbs as default, but allman for functions - "brace-style": [0, "allman", { "allowSingleLine": true }], + // brace-style is disabled, as eslint cannot enforce 1tbs as default, but allman for functions + 'brace-style': [0, 'allman', {'allowSingleLine': true}], - // key-spacing is disabled, as some objects use value-aligned spacing, some not. - "key-spacing": [0, { - "beforeColon": false, - "afterColon": true, - "align": "value" - }], - // quote-props is diabled, as property quoting styles are too varied to enforce. - "quote-props": [0, "as-needed"], + // key-spacing is disabled, as some objects use value-aligned spacing, some not. + 'key-spacing': [0, {'beforeColon': false, 'afterColon': true, 'align': 'value'}], + // quote-props is diabled, as property quoting styles are too varied to enforce. + 'quote-props': [0, 'as-needed'], - // no-implicit-globals will prevent accidental globals - "no-implicit-globals": [0] - } + // no-implicit-globals will prevent accidental globals + 'no-implicit-globals': [0] + } };
diff --git a/third_party/blink/renderer/devtools/.gitignore b/third_party/blink/renderer/devtools/.gitignore index bb586679..b827cf2e 100644 --- a/third_party/blink/renderer/devtools/.gitignore +++ b/third_party/blink/renderer/devtools/.gitignore
@@ -19,8 +19,9 @@ package-lock.json .vscode /front_end/*/jsconfig.json +karma-coverage # These are generated for build and would be put in the symlinked folder (thus this folder) front_end/InspectorBackendCommands.js front_end/SupportedCSSProperties.js -front_end/accessibility/ARIAProperties.js \ No newline at end of file +front_end/accessibility/ARIAProperties.js
diff --git a/third_party/blink/renderer/devtools/PRESUBMIT.py b/third_party/blink/renderer/devtools/PRESUBMIT.py index b5dc9a0c..1ada106 100644 --- a/third_party/blink/renderer/devtools/PRESUBMIT.py +++ b/third_party/blink/renderer/devtools/PRESUBMIT.py
@@ -77,11 +77,7 @@ # Use eslint to autofix the braces. # Also fix semicolon to avoid confusing clang-format. - eslint_process = popen([ - local_node.node_path(), - local_node.eslint_path(), '--no-eslintrc', '--fix', '--env=es6', '--parser-options=ecmaVersion:9,sourceType:module', - '--rule={"curly": [2, "multi-or-nest", "consistent"], "semi": 2}' - ] + affected_files) + eslint_process = popen([local_node.node_path(), local_node.eslint_path(), '--config', '.eslintrc.js', '--fix'] + affected_files) eslint_process.communicate() # Need to run clang-format again to align the braces
diff --git a/third_party/blink/renderer/devtools/front_end/Runtime.js b/third_party/blink/renderer/devtools/front_end/Runtime.js index b829afe..7e1d7e0d 100644 --- a/third_party/blink/renderer/devtools/front_end/Runtime.js +++ b/third_party/blink/renderer/devtools/front_end/Runtime.js
@@ -64,8 +64,9 @@ /** @type {!Object<string, !Runtime.ModuleDescriptor>} */ this._descriptorsMap = {}; - for (let i = 0; i < descriptors.length; ++i) + for (let i = 0; i < descriptors.length; ++i) { this._registerModule(descriptors[i]); + } } /** @@ -88,16 +89,19 @@ * @param {Event} e */ function onreadystatechange(e) { - if (xhr.readyState !== XMLHttpRequest.DONE) + if (xhr.readyState !== XMLHttpRequest.DONE) { return; + } // DevTools Proxy server can mask 404s as 200s, check the body to be sure const status = /^HTTP\/1.1 404/.test(e.target.response) ? 404 : xhr.status; if ([0, 200, 304].indexOf(status) === -1) // Testing harness file:/// results in 0. + { reject(new Error('While loading from url ' + url + ' server responded with a status of ' + status)); - else + } else { fulfill(e.target.response); + } } xhr.send(null); } @@ -111,8 +115,9 @@ return Runtime.loadResourcePromise(url).catch(err => { const urlWithFallbackVersion = url.replace(/@[0-9a-f]{40}/, REMOTE_MODULE_FALLBACK_REVISION); // TODO(phulce): mark fallbacks in module.json and modify build script instead - if (urlWithFallbackVersion === url || !url.includes('audits_worker_module')) + if (urlWithFallbackVersion === url || !url.includes('audits_worker_module')) { throw err; + } return Runtime.loadResourcePromise(urlWithFallbackVersion); }); } @@ -123,28 +128,33 @@ * @return {string} */ static normalizePath(path) { - if (path.indexOf('..') === -1 && path.indexOf('.') === -1) + if (path.indexOf('..') === -1 && path.indexOf('.') === -1) { return path; + } const normalizedSegments = []; const segments = path.split('/'); for (let i = 0; i < segments.length; i++) { const segment = segments[i]; - if (segment === '.') + if (segment === '.') { continue; - else if (segment === '..') + } else if (segment === '..') { normalizedSegments.pop(); - else if (segment) + } else if (segment) { normalizedSegments.push(segment); + } } let normalizedPath = normalizedSegments.join('/'); - if (normalizedPath[normalizedPath.length - 1] === '/') + if (normalizedPath[normalizedPath.length - 1] === '/') { return normalizedPath; - if (path[0] === '/' && normalizedPath) + } + if (path[0] === '/' && normalizedPath) { normalizedPath = '/' + normalizedPath; + } if ((path[path.length - 1] === '/') || (segments[segments.length - 1] === '.') || - (segments[segments.length - 1] === '..')) + (segments[segments.length - 1] === '..')) { normalizedPath = normalizedPath + '/'; + } return normalizedPath; } @@ -158,8 +168,9 @@ const sourceURL = (base || self._importScriptPathPrefix) + scriptName; const schemaIndex = sourceURL.indexOf('://') + 3; let pathIndex = sourceURL.indexOf('/', schemaIndex); - if (pathIndex === -1) + if (pathIndex === -1) { pathIndex = sourceURL.length; + } return sourceURL.substring(0, pathIndex) + Runtime.normalizePath(sourceURL.substring(pathIndex)); } @@ -179,8 +190,9 @@ const scriptName = scriptNames[i]; const sourceURL = Runtime.getResourceURL(scriptName, base); - if (_loadedScripts[sourceURL]) + if (_loadedScripts[sourceURL]) { continue; + } urls.push(sourceURL); const loadResourcePromise = base ? Runtime.loadResourcePromiseWithFallback(sourceURL) : Runtime.loadResourcePromise(sourceURL); @@ -278,12 +290,14 @@ const descriptor = configuration[i]; const name = descriptor['name']; const moduleJSON = allDescriptorsByName[name]; - if (moduleJSON) + if (moduleJSON) { moduleJSONPromises.push(Promise.resolve(moduleJSON)); - else + } else { moduleJSONPromises.push(Runtime.loadResourcePromise(name + '/module.json').then(JSON.parse.bind(JSON))); - if (descriptor['type'] === 'autostart') + } + if (descriptor['type'] === 'autostart') { coreModuleNames.push(name); + } } const moduleDescriptors = await Promise.all(moduleJSONPromises); @@ -294,8 +308,9 @@ moduleDescriptors[i].remote = configuration[i]['type'] === 'remote'; } self.runtime = new Runtime(moduleDescriptors); - if (coreModuleNames) + if (coreModuleNames) { await self.runtime._loadAutoStartModules(coreModuleNames); + } Runtime._appStartedPromiseCallback(); } @@ -340,8 +355,9 @@ } static _assert(value, message) { - if (value) + if (value) { return; + } Runtime._originalAssert.call(Runtime._console, value, message + ' ' + new Error().stack); } @@ -358,19 +374,24 @@ */ static _isDescriptorEnabled(descriptor) { const activatorExperiment = descriptor['experiment']; - if (activatorExperiment === '*') + if (activatorExperiment === '*') { return Runtime.experiments.supportEnabled(); + } if (activatorExperiment && activatorExperiment.startsWith('!') && - Runtime.experiments.isEnabled(activatorExperiment.substring(1))) + Runtime.experiments.isEnabled(activatorExperiment.substring(1))) { return false; + } if (activatorExperiment && !activatorExperiment.startsWith('!') && - !Runtime.experiments.isEnabled(activatorExperiment)) + !Runtime.experiments.isEnabled(activatorExperiment)) { return false; + } const condition = descriptor['condition']; - if (condition && !condition.startsWith('!') && !Runtime.queryParam(condition)) + if (condition && !condition.startsWith('!') && !Runtime.queryParam(condition)) { return false; - if (condition && condition.startsWith('!') && Runtime.queryParam(condition.substring(1))) + } + if (condition && condition.startsWith('!') && Runtime.queryParam(condition.substring(1))) { return false; + } return true; } @@ -380,8 +401,9 @@ */ static resolveSourceURL(path) { let sourceURL = self.location.href; - if (self.location.search) + if (self.location.search) { sourceURL = sourceURL.replace(self.location.search, ''); + } sourceURL = sourceURL.substring(0, sourceURL.lastIndexOf('/') + 1) + path; return '\n/*# sourceURL=' + sourceURL + ' */'; } @@ -395,8 +417,9 @@ useTestBase() { Runtime._remoteBase = 'http://localhost:8000/inspector-sources/'; - if (Runtime.queryParam('debugFrontend')) + if (Runtime.queryParam('debugFrontend')) { Runtime._remoteBase += 'debug/'; + } } /** @@ -430,8 +453,9 @@ */ _loadAutoStartModules(moduleNames) { const promises = []; - for (let i = 0; i < moduleNames.length; ++i) + for (let i = 0; i < moduleNames.length; ++i) { promises.push(this.loadModulePromise(moduleNames[i])); + } return Promise.all(promises); } @@ -441,16 +465,19 @@ * @return {boolean} */ _checkExtensionApplicability(extension, predicate) { - if (!predicate) + if (!predicate) { return false; + } const contextTypes = extension.descriptor().contextTypes; - if (!contextTypes) + if (!contextTypes) { return true; + } for (let i = 0; i < contextTypes.length; ++i) { const contextType = this._resolve(contextTypes[i]); const isMatching = !!contextType && predicate(contextType); - if (isMatching) + if (isMatching) { return true; + } } return false; } @@ -461,8 +488,9 @@ * @return {boolean} */ isExtensionApplicableToContext(extension, context) { - if (!context) + if (!context) { return true; + } return this._checkExtensionApplicability(extension, isInstanceOf); /** @@ -480,8 +508,9 @@ * @return {boolean} */ isExtensionApplicableToContextTypes(extension, currentContextTypes) { - if (!extension.descriptor().contextTypes) + if (!extension.descriptor().contextTypes) { return true; + } return this._checkExtensionApplicability(extension, currentContextTypes ? isContextTypeKnown : null); @@ -508,10 +537,12 @@ * @return {boolean} */ function filter(extension) { - if (extension._type !== type && extension._typeClass() !== type) + if (extension._type !== type && extension._typeClass() !== type) { return false; - if (!extension.enabled()) + } + if (!extension.enabled()) { return false; + } return !context || extension.isApplicable(context); } @@ -563,10 +594,12 @@ if (!this._cachedTypeClasses[typeName]) { const path = typeName.split('.'); let object = self; - for (let i = 0; object && (i < path.length); ++i) + for (let i = 0; object && (i < path.length); ++i) { object = object[path[i]]; - if (object) + } + if (object) { this._cachedTypeClasses[typeName] = /** @type function(new:Object) */ (object); + } } return this._cachedTypeClasses[typeName] || null; } @@ -578,8 +611,9 @@ */ sharedInstance(constructorFunction) { if (Runtime._instanceSymbol in constructorFunction && - Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol)) + Object.getOwnPropertySymbols(constructorFunction).includes(Runtime._instanceSymbol)) { return constructorFunction[Runtime._instanceSymbol]; + } const instance = new constructorFunction(); constructorFunction[Runtime._instanceSymbol] = instance; @@ -718,8 +752,9 @@ resource(name) { const fullName = this._name + '/' + name; const content = Runtime.cachedResources[fullName]; - if (!content) + if (!content) { throw new Error(fullName + ' not preloaded. Check module.json'); + } return content; } @@ -727,16 +762,19 @@ * @return {!Promise.<undefined>} */ _loadPromise() { - if (!this.enabled()) + if (!this.enabled()) { return Promise.reject(new Error('Module ' + this._name + ' is not enabled')); + } - if (this._pendingLoadPromise) + if (this._pendingLoadPromise) { return this._pendingLoadPromise; + } const dependencies = this._descriptor.dependencies; const dependencyPromises = []; - for (let i = 0; dependencies && i < dependencies.length; ++i) + for (let i = 0; dependencies && i < dependencies.length; ++i) { dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise()); + } this._pendingLoadPromise = Promise.all(dependencyPromises) .then(this._loadResources.bind(this)) @@ -752,8 +790,9 @@ */ _loadResources() { const resources = this._descriptor['resources']; - if (!resources || !resources.length) + if (!resources || !resources.length) { return Promise.resolve(); + } const promises = []; for (let i = 0; i < resources.length; ++i) { const url = this._modularizeURL(resources[i]); @@ -767,8 +806,9 @@ * @return {!Promise.<undefined>} */ _loadScripts() { - if (!this._descriptor.scripts || !this._descriptor.scripts.length) + if (!this._descriptor.scripts || !this._descriptor.scripts.length) { return Promise.resolve(); + } // Module namespaces. // NOTE: Update scripts/special_case_namespaces.json if you add a special cased namespace. @@ -878,8 +918,9 @@ * @return {?function(new:Object)} */ _typeClass() { - if (!this._hasTypeClass) + if (!this._hasTypeClass) { return null; + } return this._module._manager._resolve(this._type.substring(1)); } @@ -910,13 +951,16 @@ */ _createInstance() { const className = this._className || this._factoryName; - if (!className) + if (!className) { throw new Error('Could not instantiate extension with no class'); + } const constructorFunction = self.eval(/** @type {string} */ (className)); - if (!(constructorFunction instanceof Function)) + if (!(constructorFunction instanceof Function)) { throw new Error('Could not instantiate: ' + className); - if (this._className) + } + if (this._className) { return this._module._manager.sharedInstance(constructorFunction); + } return new constructorFunction(this); } @@ -925,8 +969,9 @@ */ title() { const title = this._descriptor['title-' + Runtime._platform] || this._descriptor['title']; - if (title && Runtime._l10nCallback) + if (title && Runtime._l10nCallback) { return Runtime._l10nCallback(title); + } return title; } @@ -936,11 +981,13 @@ */ hasContextType(contextType) { const contextTypes = this.descriptor().contextTypes; - if (!contextTypes) + if (!contextTypes) { return false; + } for (let i = 0; i < contextTypes.length; ++i) { - if (contextType === this._module._manager._resolve(contextTypes[i])) + if (contextType === this._module._manager._resolve(contextTypes[i])) { return true; + } } return false; } @@ -966,8 +1013,9 @@ const result = []; for (let i = 0; i < this._experiments.length; i++) { const experiment = this._experiments[i]; - if (!this._enabledTransiently[experiment.name]) + if (!this._enabledTransiently[experiment.name]) { result.push(experiment); + } } return result; } @@ -983,8 +1031,9 @@ * @param {!Object} value */ _setExperimentsSetting(value) { - if (!self.localStorage) + if (!self.localStorage) { return; + } self.localStorage['experiments'] = JSON.stringify(value); } @@ -1007,14 +1056,18 @@ this._checkExperiment(experimentName); // Check for explicitly disabled experiments first - the code could call setEnable(false) on the experiment enabled // by default and we should respect that. - if (Runtime._experimentsSetting()[experimentName] === false) + if (Runtime._experimentsSetting()[experimentName] === false) { return false; - if (this._enabledTransiently[experimentName]) + } + if (this._enabledTransiently[experimentName]) { return true; - if (this._serverEnabled.has(experimentName)) + } + if (this._serverEnabled.has(experimentName)) { return true; - if (!this.supportEnabled()) + } + if (!this.supportEnabled()) { return false; + } return !!Runtime._experimentsSetting()[experimentName]; } @@ -1070,8 +1123,9 @@ const cleanedUpExperimentSetting = {}; for (let i = 0; i < this._experiments.length; ++i) { const experimentName = this._experiments[i].name; - if (experimentsSetting[experimentName]) + if (experimentsSetting[experimentName]) { cleanedUpExperimentSetting[experimentName] = true; + } } this._setExperimentsSetting(cleanedUpExperimentSetting); } @@ -1133,8 +1187,9 @@ (function validateRemoteBase() { if (location.href.startsWith('devtools://devtools/bundled/') && Runtime.queryParam('remoteBase')) { const versionMatch = /\/serve_file\/(@[0-9a-zA-Z]+)\/?$/.exec(Runtime.queryParam('remoteBase')); - if (versionMatch) + if (versionMatch) { Runtime._remoteBase = `${location.origin}/remote/serve_file/${versionMatch[1]}/`; + } } })();
diff --git a/third_party/blink/renderer/devtools/front_end/Tests.js b/third_party/blink/renderer/devtools/front_end/Tests.js index f61b3bf..9717a79 100644 --- a/third_party/blink/renderer/devtools/front_end/Tests.js +++ b/third_party/blink/renderer/devtools/front_end/Tests.js
@@ -67,10 +67,11 @@ * @param {string} message Failure description. */ TestSuite.prototype.fail = function(message) { - if (this.controlTaken_) + if (this.controlTaken_) { this.reportFailure_(message); - else + } else { throw message; + } }; /** @@ -82,8 +83,9 @@ TestSuite.prototype.assertEquals = function(expected, actual, opt_message) { if (expected !== actual) { let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\''; - if (opt_message) + if (opt_message) { message = opt_message + '(' + message + ')'; + } this.fail(message); } }; @@ -147,8 +149,9 @@ const methodName = args.shift(); try { this[methodName].apply(this, args); - if (!this.controlTaken_) + if (!this.controlTaken_) { this.reportOk_(); + } } catch (e) { this.reportFailure_(e); } @@ -177,16 +180,18 @@ */ TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) { const orig = receiver[methodName]; - if (typeof orig !== 'function') + if (typeof orig !== 'function') { this.fail('Cannot find method to override: ' + methodName); + } const test = this; receiver[methodName] = function(var_args) { let result; try { result = orig.apply(this, arguments); } finally { - if (!opt_sticky) + if (!opt_sticky) { receiver[methodName] = orig; + } } // In case of exception the override won't be called. try { @@ -223,8 +228,9 @@ } function onSchedule() { - if (scheduleShouldFail) + if (scheduleShouldFail) { test.fail('Unexpected Throttler.schedule'); + } } checkState(); @@ -347,8 +353,9 @@ // frontend is being loaded. TestSuite.prototype.testPauseWhenLoadingDevTools = function() { const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); - if (debuggerModel.debuggerPausedDetails) + if (debuggerModel.debuggerPausedDetails) { return; + } this.showPanel('sources').then(function() { // Script execution can already be paused. @@ -430,8 +437,9 @@ const test = this; function finishRequest(request, finishTime) { - if (!request.responseHeadersText) + if (!request.responseHeadersText) { test.fail('Failure: resource does not have response headers text'); + } const index = request.responseHeadersText.indexOf('Date:'); test.assertEquals( 112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length'); @@ -501,8 +509,9 @@ test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime'); test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime'); } - if (!--pendingRequestCount) + if (!--pendingRequestCount) { test.releaseControl(); + } } this.addSniffer(SDK.NetworkDispatcher.prototype, '_finishNetworkRequest', finishRequest, true); @@ -518,15 +527,17 @@ return SDK.consoleModel.messages().filter(a => a.source !== SDK.ConsoleMessage.MessageSource.Violation); } - if (filteredMessages().length === 1) + if (filteredMessages().length === 1) { firstConsoleMessageReceived.call(this, null); - else + } else { SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); + } function firstConsoleMessageReceived(event) { - if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) + if (event && event.data.source === SDK.ConsoleMessage.MessageSource.Violation) { return; + } SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this); this.evaluateInConsole_('clickLink();', didClickLink.bind(this)); } @@ -585,8 +596,9 @@ function onConsoleMessage(event) { const message = event.data.messageText; - if (message !== 'connected') + if (message !== 'connected') { this.fail('Unexpected message: ' + message); + } this.releaseControl(); } }; @@ -594,8 +606,9 @@ TestSuite.prototype.testSharedWorkerNetworkPanel = function() { this.takeControl(); this.showPanel('network').then(() => { - if (!document.querySelector('#network-container')) + if (!document.querySelector('#network-container')) { this.fail('unable to find #network-container'); + } this.releaseControl(); }); }; @@ -608,8 +621,9 @@ TestSuite.prototype.waitForDebuggerPaused = function() { const debuggerModel = SDK.targetManager.mainTarget().model(SDK.DebuggerModel); - if (debuggerModel.debuggerPausedDetails) + if (debuggerModel.debuggerPausedDetails) { return; + } this.takeControl(); this._waitForScriptPause(this.releaseControl.bind(this)); @@ -709,8 +723,9 @@ signalToShowAutofill(); } // This log comes from the browser unittest code. - if (message === 'didShowSuggestions') + if (message === 'didShowSuggestions') { selectTopAutoFill(); + } } this.takeControl(); @@ -929,10 +944,11 @@ const color = [0, 0, 0]; color[count % 3] = 255; div.style.backgroundColor = 'rgb(' + color.join(',') + ')'; - if (++count > 10) + if (++count > 10) { requestAnimationFrame(callback); - else + } else { requestAnimationFrame(frame); + } } } @@ -951,8 +967,9 @@ function loadFrameImages(frames) { const readyImages = []; - for (const frame of frames) + for (const frame of frames) { frame.imageDataPromise().then(onGotImageData); + } function onGotImageData(data) { const image = new Image(); @@ -963,8 +980,9 @@ function onLoad(event) { readyImages.push(event.target); - if (readyImages.length === frames.length) + if (readyImages.length === frames.length) { validateImagesAndCompleteTest(readyImages); + } } } @@ -983,14 +1001,15 @@ ctx.drawImage(image, 0, 0); const data = ctx.getImageData(0, 0, 1, 1); const color = Array.prototype.join.call(data.data, ','); - if (data.data[0] > 200) + if (data.data[0] > 200) { redCount++; - else if (data.data[1] > 200) + } else if (data.data[1] > 200) { greenCount++; - else if (data.data[2] > 200) + } else if (data.data[2] > 200) { blueCount++; - else + } else { test.fail('Unexpected color: ' + color); + } } test.assertTrue(redCount && greenCount && blueCount, 'Color sanity check failed'); test.releaseControl(); @@ -1037,10 +1056,11 @@ const test = this; test.takeControl(); const messages = SDK.consoleModel.messages(); - if (messages.length === 1) + if (messages.length === 1) { checkMessages(); - else + } else { SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, checkMessages.bind(this), this); + } function checkMessages() { const messages = SDK.consoleModel.messages(); @@ -1059,8 +1079,9 @@ const consoleView = Console.ConsoleView.instance(); const selector = consoleView._consoleContextSelector; const values = []; - for (const item of selector._items) + for (const item of selector._items) { values.push(selector.titleFor(item)); + } test.assertEquals('top', values[0]); test.assertEquals('Simple content script', values[1]); test.releaseControl(); @@ -1082,8 +1103,9 @@ let count = 0; function onResponseReceived(event) { const networkRequest = event.data; - if (!networkRequest.url().startsWith('http')) + if (!networkRequest.url().startsWith('http')) { return; + } switch (++count) { case 1: // Original redirect test.assertEquals(301, networkRequest.statusCode); @@ -1121,18 +1143,20 @@ const messages = SDK.consoleModel.messages(); for (let i = 0; i < messages.length; ++i) { const text = messages[i].messageText; - if (text === 'PASS') + if (text === 'PASS') { return; - else if (/^FAIL/.test(text)) - this.fail(text); // This will throw. + } else if (/^FAIL/.test(text)) { + this.fail(text); + } // This will throw. } // Neither PASS nor FAIL, so wait for more messages. function onConsoleMessage(event) { const text = event.data.messageText; - if (text === 'PASS') + if (text === 'PASS') { this.releaseControl(); - else if (/^FAIL/.test(text)) + } else if (/^FAIL/.test(text)) { this.fail(text); + } } SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this); @@ -1216,24 +1240,29 @@ const input = asyncEvents.get(TimelineModel.TimelineModel.AsyncEventGroup.input) || []; const prefix = 'InputLatency::'; for (const e of input) { - if (!e.name.startsWith(prefix)) + if (!e.name.startsWith(prefix)) { continue; - if (e.steps.length < 2) + } + if (e.steps.length < 2) { continue; + } if (e.name.startsWith(prefix + 'Mouse') && - typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') + typeof TimelineModel.TimelineData.forEvent(e.steps[0]).timeWaitingForMainThread !== 'number') { throw `Missing timeWaitingForMainThread on ${e.name}`; + } expectedEvents.delete(e.name.substr(prefix.length)); } - if (expectedEvents.size) + if (expectedEvents.size) { throw 'Some expected events are not found: ' + Array.from(expectedEvents.keys()).join(','); + } }; TestSuite.prototype.testInspectedElementIs = async function(nodeName) { this.takeControl(); await self.runtime.loadModulePromise('elements'); - if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) + if (!Elements.ElementsPanel._firstInspectElementNodeNameForTest) { await new Promise(f => this.addSniffer(Elements.ElementsPanel, '_firstInspectElementCompletedForTest', f)); + } this.assertEquals(nodeName, Elements.ElementsPanel._firstInspectElementNodeNameForTest); this.releaseControl(); }; @@ -1374,8 +1403,9 @@ const headersArray = []; for (const name in headers) { const nameLower = name.toLowerCase(); - if (loggedHeaders.has(nameLower)) + if (loggedHeaders.has(nameLower)) { headersArray.push(nameLower); + } } headersArray.sort(); test.assertEquals(expectedHeaders.join(', '), headersArray.join(', ')); @@ -1419,15 +1449,18 @@ function onRequestUpdated(event) { const request = event.data; - if (request.resourceType() !== Common.resourceTypes.WebSocket) + if (request.resourceType() !== Common.resourceTypes.WebSocket) { return; - if (!request.requestHeadersText()) + } + if (!request.requestHeadersText()) { return; + } let actualUserAgent = 'no user-agent header'; for (const {name, value} of request.requestHeaders()) { - if (name.toLowerCase() === 'user-agent') + if (name.toLowerCase() === 'user-agent') { actualUserAgent = value; + } } this.assertEquals(testUserAgent, actualUserAgent); this.releaseControl(); @@ -1445,8 +1478,9 @@ */ TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) { const names = []; - for (let i = 0; i < uiSourceCodes.length; i++) + for (let i = 0; i < uiSourceCodes.length; i++) { names.push('"' + uiSourceCodes[i].url() + '"'); + } return names.join(','); }; @@ -1532,10 +1566,11 @@ const test = this; function waitForAllScripts() { - if (test._scriptsAreParsed(expectedScripts)) + if (test._scriptsAreParsed(expectedScripts)) { callback(); - else + } else { test.addSniffer(UI.panels.sources.sourcesView(), '_addUISourceCode', waitForAllScripts); + } } waitForAllScripts(); @@ -1545,10 +1580,11 @@ checkTargets.call(this); function checkTargets() { - if (SDK.targetManager.targets().length >= n) + if (SDK.targetManager.targets().length >= n) { callback.call(null); - else + } else { this.addSniffer(SDK.TargetManager.prototype, 'createTarget', checkTargets.bind(this)); + } } }; @@ -1557,10 +1593,11 @@ checkForExecutionContexts.call(this); function checkForExecutionContexts() { - if (runtimeModel.executionContexts().length >= n) + if (runtimeModel.executionContexts().length >= n) { callback.call(null); - else + } else { this.addSniffer(SDK.RuntimeModel.prototype, '_executionContextCreated', checkForExecutionContexts.bind(this)); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/ARIAAttributesView.js b/third_party/blink/renderer/devtools/front_end/accessibility/ARIAAttributesView.js index 3bfb476..f5a000b 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/ARIAAttributesView.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/ARIAAttributesView.js
@@ -19,14 +19,16 @@ setNode(node) { super.setNode(node); this._treeOutline.removeChildren(); - if (!this.node()) + if (!this.node()) { return; + } const target = this.node().domModel().target(); const attributes = node.attributes(); for (let i = 0; i < attributes.length; ++i) { const attribute = attributes[i]; - if (Accessibility.ARIAAttributesPane._attributes.indexOf(attribute.name) < 0) + if (Accessibility.ARIAAttributesPane._attributes.indexOf(attribute.name) < 0) { continue; + } this._treeOutline.appendChild(new Accessibility.ARIAAttributesTreeElement(this, attribute, target)); } @@ -103,8 +105,9 @@ * @param {!Event} event */ _mouseClick(event) { - if (event.target === this.listItemElement) + if (event.target === this.listItemElement) { return; + } event.consume(true); @@ -114,8 +117,9 @@ _startEditing() { const valueElement = this._valueElement; - if (UI.isBeingEdited(valueElement)) + if (UI.isBeingEdited(valueElement)) { return; + } const previousContent = valueElement.textContent; @@ -140,8 +144,9 @@ } _removePrompt() { - if (!this._prompt) + if (!this._prompt) { return; + } this._prompt.detach(); delete this._prompt; } @@ -154,8 +159,9 @@ this._removePrompt(); // Make the changes to the attribute - if (userInput !== previousContent) + if (userInput !== previousContent) { this._parentPane.node().setAttributeValue(this._attribute.name, userInput); + } } _editingCancelled() { @@ -168,8 +174,9 @@ * @param {!Event} event */ _editingValueKeyDown(previousContent, event) { - if (event.handled) + if (event.handled) { return; + } if (isEnterKey(event)) { this._editingCommitted(event.target.textContent, previousContent); @@ -210,8 +217,9 @@ */ _buildPropertyCompletions(expression, prefix, force) { prefix = prefix.toLowerCase(); - if (!prefix && !force && (this._isEditingName || expression)) + if (!prefix && !force && (this._isEditingName || expression)) { return Promise.resolve([]); + } return Promise.resolve(this._ariaCompletions.filter(value => value.startsWith(prefix)).map(c => ({text: c}))); } };
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/ARIAMetadata.js b/third_party/blink/renderer/devtools/front_end/accessibility/ARIAMetadata.js index 8038ae0..46a19aba 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/ARIAMetadata.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/ARIAMetadata.js
@@ -12,8 +12,9 @@ /** @type {!Map<string, !Accessibility.ARIAMetadata.Attribute>} */ this._attributes = new Map(); - if (config) + if (config) { this._initialize(config); + } } /** @@ -24,8 +25,9 @@ const booleanEnum = ['true', 'false']; for (const attributeConfig of attributes) { - if (attributeConfig.type === 'boolean') + if (attributeConfig.type === 'boolean') { attributeConfig.enum = booleanEnum; + } this._attributes.set(attributeConfig.name, new Accessibility.ARIAMetadata.Attribute(attributeConfig)); } @@ -38,11 +40,13 @@ * @return {!Array<string>} */ valuesForProperty(property) { - if (this._attributes.has(property)) + if (this._attributes.has(property)) { return this._attributes.get(property).getEnum(); + } - if (property === 'role') + if (property === 'role') { return this._roleNames; + } return []; } @@ -52,8 +56,9 @@ * @return {!Accessibility.ARIAMetadata} */ Accessibility.ariaMetadata = function() { - if (!Accessibility.ARIAMetadata._instance) + if (!Accessibility.ARIAMetadata._instance) { Accessibility.ARIAMetadata._instance = new Accessibility.ARIAMetadata(Accessibility.ARIAMetadata._config || null); + } return Accessibility.ARIAMetadata._instance; }; @@ -68,8 +73,9 @@ /** @type {!Array<string>} */ this._enum = []; - if ('enum' in config) + if ('enum' in config) { this._enum = config.enum; + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/AXBreadcrumbsPane.js b/third_party/blink/renderer/devtools/front_end/accessibility/AXBreadcrumbsPane.js index fc4f696..fada19f 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/AXBreadcrumbsPane.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/AXBreadcrumbsPane.js
@@ -36,10 +36,11 @@ * @override */ focus() { - if (this._inspectedNodeBreadcrumb) + if (this._inspectedNodeBreadcrumb) { this._inspectedNodeBreadcrumb.nodeElement().focus(); - else + } else { this.element.focus(); + } } /** @@ -52,8 +53,9 @@ this._rootElement.removeChildren(); - if (!axNode) + if (!axNode) { return; + } const ancestorChain = []; let ancestor = axNode; @@ -68,10 +70,11 @@ let parent = null; for (ancestor of ancestorChain) { breadcrumb = new Accessibility.AXBreadcrumb(ancestor, depth, (ancestor === axNode)); - if (parent) + if (parent) { parent.appendChild(breadcrumb); - else + } else { this._rootElement.appendChild(breadcrumb.element()); + } parent = breadcrumb; depth++; } @@ -91,12 +94,14 @@ parentBreadcrumb.appendChild(childBreadcrumb); // In most cases there will be no children here, but there are some special cases. - for (const child of axNode.children()) + for (const child of axNode.children()) { append(childBreadcrumb, child, localDepth + 1); + } } - for (const child of axNode.children()) + for (const child of axNode.children()) { append(this._inspectedNodeBreadcrumb, child, depth); + } } /** @@ -110,23 +115,28 @@ * @param {!Event} event */ _onKeyDown(event) { - if (!this._preselectedBreadcrumb) + if (!this._preselectedBreadcrumb) { return; - if (!event.composedPath().some(element => element === this._preselectedBreadcrumb.element())) + } + if (!event.composedPath().some(element => element === this._preselectedBreadcrumb.element())) { return; - if (event.shiftKey || event.metaKey || event.ctrlKey) + } + if (event.shiftKey || event.metaKey || event.ctrlKey) { return; + } let handled = false; - if ((event.key === 'ArrowUp' || event.key === 'ArrowLeft') && !event.altKey) + if ((event.key === 'ArrowUp' || event.key === 'ArrowLeft') && !event.altKey) { handled = this._preselectPrevious(); - else if ((event.key === 'ArrowDown' || event.key === 'ArrowRight') && !event.altKey) + } else if ((event.key === 'ArrowDown' || event.key === 'ArrowRight') && !event.altKey) { handled = this._preselectNext(); - else if (isEnterKey(event)) + } else if (isEnterKey(event)) { handled = this._inspectDOMNode(this._preselectedBreadcrumb.axNode()); + } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -134,8 +144,9 @@ */ _preselectPrevious() { const previousBreadcrumb = this._preselectedBreadcrumb.previousBreadcrumb(); - if (!previousBreadcrumb) + if (!previousBreadcrumb) { return false; + } this._setPreselectedBreadcrumb(previousBreadcrumb); return true; } @@ -145,8 +156,9 @@ */ _preselectNext() { const nextBreadcrumb = this._preselectedBreadcrumb.nextBreadcrumb(); - if (!nextBreadcrumb) + if (!nextBreadcrumb) { return false; + } this._setPreselectedBreadcrumb(nextBreadcrumb); return true; } @@ -155,19 +167,23 @@ * @param {?Accessibility.AXBreadcrumb} breadcrumb */ _setPreselectedBreadcrumb(breadcrumb) { - if (breadcrumb === this._preselectedBreadcrumb) + if (breadcrumb === this._preselectedBreadcrumb) { return; + } const hadFocus = this.element.hasFocus(); - if (this._preselectedBreadcrumb) + if (this._preselectedBreadcrumb) { this._preselectedBreadcrumb.setPreselected(false, hadFocus); + } - if (breadcrumb) + if (breadcrumb) { this._preselectedBreadcrumb = breadcrumb; - else + } else { this._preselectedBreadcrumb = this._inspectedNodeBreadcrumb; + } this._preselectedBreadcrumb.setPreselected(true, hadFocus); - if (!breadcrumb && hadFocus) + if (!breadcrumb && hadFocus) { SDK.OverlayModel.hideDOMNodeHighlight(); + } } /** @@ -187,8 +203,9 @@ return; } const breadcrumb = breadcrumbElement.breadcrumb; - if (!breadcrumb.isDOMNode()) + if (!breadcrumb.isDOMNode()) { return; + } this._setHoveredBreadcrumb(breadcrumb); } @@ -196,8 +213,9 @@ * @param {!Event} event */ _onFocusOut(event) { - if (!this._preselectedBreadcrumb || event.target !== this._preselectedBreadcrumb.nodeElement()) + if (!this._preselectedBreadcrumb || event.target !== this._preselectedBreadcrumb.nodeElement()) { return; + } this._setPreselectedBreadcrumb(null); } @@ -217,8 +235,9 @@ breadcrumb.nodeElement().focus(); return; } - if (!breadcrumb.isDOMNode()) + if (!breadcrumb.isDOMNode()) { return; + } this._inspectDOMNode(breadcrumb.axNode()); } @@ -226,11 +245,13 @@ * @param {?Accessibility.AXBreadcrumb} breadcrumb */ _setHoveredBreadcrumb(breadcrumb) { - if (breadcrumb === this._hoveredBreadcrumb) + if (breadcrumb === this._hoveredBreadcrumb) { return; + } - if (this._hoveredBreadcrumb) + if (this._hoveredBreadcrumb) { this._hoveredBreadcrumb.setHovered(false); + } if (breadcrumb) { breadcrumb.setHovered(true); @@ -247,8 +268,9 @@ * @return {boolean} */ _inspectDOMNode(axNode) { - if (!axNode.isDOMNode()) + if (!axNode.isDOMNode()) { return false; + } axNode.deferredDOMNode().resolve(domNode => { this._axSidebarView.setNode(domNode, true /* fromAXTree */); @@ -263,18 +285,21 @@ */ _contextMenuEventFired(event) { const breadcrumbElement = event.target.enclosingNodeOrSelfWithClass('ax-breadcrumb'); - if (!breadcrumbElement) + if (!breadcrumbElement) { return; + } const axNode = breadcrumbElement.breadcrumb.axNode(); - if (!axNode.isDOMNode() || !axNode.deferredDOMNode()) + if (!axNode.isDOMNode() || !axNode.deferredDOMNode()) { return; + } const contextMenu = new UI.ContextMenu(event); contextMenu.viewSection().appendItem(ls`Scroll into view`, () => { axNode.deferredDOMNode().resolvePromise().then(domNode => { - if (!domNode) + if (!domNode) { return; + } domNode.scrollIntoView(); }); }); @@ -332,11 +357,13 @@ } } - if (this._axNode.hasOnlyUnloadedChildren()) + if (this._axNode.hasOnlyUnloadedChildren()) { this._nodeElement.classList.add('children-unloaded'); + } - if (!this._axNode.isDOMNode()) + if (!this._axNode.isDOMNode()) { this._nodeElement.classList.add('no-dom-node'); + } } /** @@ -383,21 +410,25 @@ * @param {boolean} selectedByUser */ setPreselected(preselected, selectedByUser) { - if (this._preselected === preselected) + if (this._preselected === preselected) { return; + } this._preselected = preselected; this._nodeElement.classList.toggle('preselected', preselected); - if (preselected) + if (preselected) { this._nodeElement.setAttribute('tabIndex', 0); - else + } else { this._nodeElement.setAttribute('tabIndex', -1); + } if (this._preselected) { - if (selectedByUser) + if (selectedByUser) { this._nodeElement.focus(); - if (!this._inspected) + } + if (!this._inspected) { this._axNode.highlightDOMNode(); - else + } else { SDK.OverlayModel.hideDOMNodeHighlight(); + } } } @@ -405,8 +436,9 @@ * @param {boolean} hovered */ setHovered(hovered) { - if (this._hovered === hovered) + if (this._hovered === hovered) { return; + } this._hovered = hovered; this._nodeElement.classList.toggle('hovered', hovered); if (this._hovered) { @@ -440,11 +472,13 @@ * @return {?Accessibility.AXBreadcrumb} */ nextBreadcrumb() { - if (this._children.length) + if (this._children.length) { return this._children[0]; + } const nextSibling = this.element().nextSibling; - if (nextSibling) + if (nextSibling) { return nextSibling.breadcrumb; + } return null; } @@ -453,8 +487,9 @@ */ previousBreadcrumb() { const previousSibling = this.element().previousSibling; - if (previousSibling) + if (previousSibling) { return previousSibling.breadcrumb; + } return this._parent; } @@ -473,8 +508,9 @@ * @param {?Protocol.Accessibility.AXValue} role */ _appendRoleElement(role) { - if (!role) + if (!role) { return; + } const roleElement = createElementWithClass('span', 'monospace'); roleElement.classList.add(Accessibility.AXBreadcrumb.RoleStyles[role.type]);
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityModel.js b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityModel.js index 9d64b087..7e84997f 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityModel.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityModel.js
@@ -24,8 +24,9 @@ this._deferredDOMNode = null; } this._ignored = payload.ignored; - if (this._ignored && 'ignoredReasons' in payload) + if (this._ignored && 'ignoredReasons' in payload) { this._ignoredReasons = payload.ignoredReasons; + } this._role = payload.role || null; this._name = payload.name || null; @@ -70,14 +71,16 @@ coreProperties() { const properties = []; - if (this._name) + if (this._name) { properties.push(/** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'name', value: this._name})); + } if (this._description) { properties.push( /** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'description', value: this._description})); } - if (this._value) + if (this._value) { properties.push(/** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'value', value: this._value})); + } return properties; } @@ -146,8 +149,9 @@ } highlightDOMNode() { - if (!this.deferredDOMNode()) + if (!this.deferredDOMNode()) { return; + } // Highlight node in page. this.deferredDOMNode().highlight(); @@ -158,13 +162,15 @@ */ children() { const children = []; - if (!this._childIds) + if (!this._childIds) { return children; + } for (const childId of this._childIds) { const child = this._accessibilityModel.axNodeForId(childId); - if (child) + if (child) { children.push(child); + } } return children; @@ -174,8 +180,9 @@ * @return {number} */ numChildren() { - if (!this._childIds) + if (!this._childIds) { return 0; + } return this._childIds.length; } @@ -183,8 +190,9 @@ * @return {boolean} */ hasOnlyUnloadedChildren() { - if (!this._childIds || !this._childIds.length) + if (!this._childIds || !this._childIds.length) { return false; + } return !this._childIds.some(id => this._accessibilityModel.axNodeForId(id) !== undefined); } @@ -197,18 +205,22 @@ */ printSelfAndChildren(inspectedNode, leadingSpace) { let string = leadingSpace || ''; - if (this._role) + if (this._role) { string += this._role.value; - else + } else { string += '<no role>'; + } string += (this._name ? ' ' + this._name.value : ''); string += ' ' + this._id; - if (this._domNode) + if (this._domNode) { string += ' (' + this._domNode.nodeName() + ')'; - if (this === inspectedNode) + } + if (this === inspectedNode) { string += ' *'; - for (const child of this.children()) + } + for (const child of this.children()) { string += '\n' + child.printSelfAndChildren(inspectedNode, (leadingSpace || '') + ' '); + } return string; } }; @@ -239,15 +251,18 @@ */ async requestPartialAXTree(node) { const payloads = await this._agent.getPartialAXTree(node.id, undefined, undefined, true); - if (!payloads) + if (!payloads) { return; + } - for (const payload of payloads) + for (const payload of payloads) { new Accessibility.AccessibilityNode(this, payload); + } for (const axNode of this._axIdToAXNode.values()) { - for (const axChild of axNode.children()) + for (const axChild of axNode.children()) { axChild._setParentNode(axNode); + } } } @@ -272,8 +287,9 @@ * @return {?Accessibility.AccessibilityNode} */ axNodeForDOMNode(domNode) { - if (!domNode) + if (!domNode) { return null; + } return this._backendDOMNodeIdToAXNode.get(domNode.backendNodeId()); } @@ -291,8 +307,9 @@ */ logTree(inspectedNode) { let rootNode = inspectedNode; - while (rootNode.parentNode()) + while (rootNode.parentNode()) { rootNode = rootNode.parentNode(); + } console.log(rootNode.printSelfAndChildren(inspectedNode)); // eslint-disable-line no-console } };
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js index 56d37a4..6c2d58f7 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilityNodeView.js
@@ -25,8 +25,9 @@ * @override */ setAXNode(axNode) { - if (this._axNode === axNode) + if (this._axNode === axNode) { return; + } this._axNode = axNode; const treeOutline = this._treeOutline; @@ -60,10 +61,12 @@ property, /** @type {!Accessibility.AccessibilityNode} */ (axNode))); } const ignoredReasonsArray = /** @type {!Array<!Protocol.Accessibility.AXProperty>} */ (axNode.ignoredReasons()); - for (const reason of ignoredReasonsArray) + for (const reason of ignoredReasonsArray) { addIgnoredReason(reason); - if (!ignoredReasons.firstChild()) + } + if (!ignoredReasons.firstChild()) { ignoredReasons.element.classList.add('hidden'); + } return; } this.element.classList.remove('ax-ignored-node-pane'); @@ -82,13 +85,15 @@ property, /** @type {!Accessibility.AccessibilityNode} */ (axNode))); } - for (const property of axNode.coreProperties()) + for (const property of axNode.coreProperties()) { addProperty(property); + } const roleProperty = /** @type {!Protocol.Accessibility.AXProperty} */ ({name: 'role', value: axNode.role()}); addProperty(roleProperty); - for (const property of /** @type {!Array.<!Protocol.Accessibility.AXProperty>} */ (axNode.properties())) + for (const property of /** @type {!Array.<!Protocol.Accessibility.AXProperty>} */ (axNode.properties())) { addProperty(property); + } } /** @@ -122,10 +127,11 @@ static createSimpleValueElement(type, value) { let valueElement; const AXValueType = Protocol.Accessibility.AXValueType; - if (!type || type === AXValueType.ValueUndefined || type === AXValueType.ComputedString) + if (!type || type === AXValueType.ValueUndefined || type === AXValueType.ComputedString) { valueElement = createElement('span'); - else + } else { valueElement = createElementWithClass('span', 'monospace'); + } let valueText; const isStringProperty = type && Accessibility.AXNodePropertyTreeElement.StringProperties.has(type); if (isStringProperty) { @@ -136,8 +142,9 @@ valueText = String(value); } - if (type && type in Accessibility.AXNodePropertyTreeElement.TypeStyles) + if (type && type in Accessibility.AXNodePropertyTreeElement.TypeStyles) { valueElement.classList.add(Accessibility.AXNodePropertyTreeElement.TypeStyles[type]); + } valueElement.setTextContentTruncatedIfNeeded(valueText || ''); @@ -228,10 +235,11 @@ } value.relatedNodes.forEach(this.appendRelatedNode, this); - if (value.relatedNodes.length <= 3) + if (value.relatedNodes.length <= 3) { this.expand(); - else + } else { this.collapse(); + } } }; @@ -339,20 +347,22 @@ if (idrefs.length === 1) { const idref = idrefs[0]; const matchingNode = relatedNodes.find(node => node.idref === idref); - if (matchingNode) + if (matchingNode) { this.appendRelatedNodeWithIdref(matchingNode, 0, idref); - else + } else { this.listItemElement.appendChild(new Accessibility.AXRelatedNodeElement({idref: idref}).render()); + } } else { // TODO(aboxhall): exclamation mark if not idreflist type for (let i = 0; i < idrefs.length; ++i) { const idref = idrefs[i]; const matchingNode = relatedNodes.find(node => node.idref === idref); - if (matchingNode) + if (matchingNode) { this.appendRelatedNodeWithIdref(matchingNode, i, idref); - else + } else { this.appendChild(new Accessibility.AXRelatedNodeSourceTreeElement({idref: idref})); + } } } } @@ -366,16 +376,18 @@ const numNodes = relatedNodes.length; if (value.type === Protocol.Accessibility.AXValueType.IdrefList || - value.type === Protocol.Accessibility.AXValueType.Idref) + value.type === Protocol.Accessibility.AXValueType.Idref) { this.appendIDRefValueElement(value); - else + } else { super.appendRelatedNodeListValueElement(value); + } - if (numNodes <= 3) + if (numNodes <= 3) { this.expand(); - else + } else { this.collapse(); + } } /** @@ -436,8 +448,9 @@ } else if (this._source.nativeSourceValue) { this.appendValueElement(this._source.nativeSourceValue); this.listItemElement.createTextChild('\xA0'); - if (this._source.value) + if (this._source.value) { this.appendValueElement(this._source.value); + } } else if (this._source.value) { this.appendValueElement(this._source.value); } else { @@ -447,8 +460,9 @@ this.listItemElement.classList.add('ax-value-source-unused'); } - if (this._source.value && this._source.superseded) + if (this._source.value && this._source.superseded) { this.listItemElement.classList.add('ax-value-source-superseded'); + } } }; @@ -473,8 +487,9 @@ */ onattach() { this.listItemElement.appendChild(this._axRelatedNodeElement.render()); - if (!this._value) + if (!this._value) { return; + } if (this._value.text) { this.listItemElement.appendChild(Accessibility.AXNodePropertyTreeElement.createSimpleValueElement( @@ -605,8 +620,9 @@ reasonElement = UI.formatLocalized('Element not interesting for accessibility.', []); break; } - if (reasonElement) + if (reasonElement) { reasonElement.classList.add('ax-reason'); + } return reasonElement; } @@ -621,7 +637,8 @@ this.listItemElement.appendChild(this._reasonElement); const value = this._property.value; - if (value.type === Protocol.Accessibility.AXValueType.Idref) + if (value.type === Protocol.Accessibility.AXValueType.Idref) { this.appendRelatedNodeListValueElement(value); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilitySidebarView.js b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilitySidebarView.js index 21da831..510cd54 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilitySidebarView.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility/AccessibilitySidebarView.js
@@ -50,20 +50,24 @@ * @param {?Accessibility.AccessibilityNode} axNode */ accessibilityNodeCallback(axNode) { - if (!axNode) + if (!axNode) { return; + } this._axNode = axNode; - if (axNode.isDOMNode()) + if (axNode.isDOMNode()) { this._sidebarPaneStack.showView(this._ariaSubPane, this._axNodeSubPane); - else + } else { this._sidebarPaneStack.removeView(this._ariaSubPane); + } - if (this._axNodeSubPane) + if (this._axNodeSubPane) { this._axNodeSubPane.setAXNode(axNode); - if (this._breadcrumbsSubPane) + } + if (this._breadcrumbsSubPane) { this._breadcrumbsSubPane.setAXNode(axNode); + } } /** @@ -76,8 +80,9 @@ this._axNodeSubPane.setNode(node); this._ariaSubPane.setNode(node); this._breadcrumbsSubPane.setNode(node); - if (!node) + if (!node) { return Promise.resolve(); + } const accessibilityModel = node.domModel().target().model(Accessibility.AccessibilityModel); accessibilityModel.clear(); return accessibilityModel.requestPartialAXTree(node).then(() => { @@ -129,11 +134,13 @@ * @param {!Common.Event} event */ _onAttrChange(event) { - if (!this.node()) + if (!this.node()) { return; + } const node = event.data.node; - if (this.node() !== node) + if (this.node() !== node) { return; + } this.update(); } @@ -141,11 +148,13 @@ * @param {!Common.Event} event */ _onNodeChange(event) { - if (!this.node()) + if (!this.node()) { return; + } const node = event.data; - if (this.node() !== node) + if (this.node() !== node) { return; + } this.update(); } };
diff --git a/third_party/blink/renderer/devtools/front_end/accessibility_test_runner/AccessibilityPaneTestRunner.js b/third_party/blink/renderer/devtools/front_end/accessibility_test_runner/AccessibilityPaneTestRunner.js index 6da6959..244fb7a 100644 --- a/third_party/blink/renderer/devtools/front_end/accessibility_test_runner/AccessibilityPaneTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/accessibility_test_runner/AccessibilityPaneTestRunner.js
@@ -44,8 +44,9 @@ if (accessibilityNode.properties()) { for (const property of accessibilityNode.properties()) { - if ('value' in property) + if ('value' in property) { builder.push(property.name + '="' + property.value.value + '"'); + } } } @@ -66,8 +67,9 @@ const childNodes = treeOutline._rootElement._children; for (const treeElement of childNodes) { - if (treeElement._attribute.name === attribute) + if (treeElement._attribute.name === attribute) { return treeElement; + } } return null;
diff --git a/third_party/blink/renderer/devtools/front_end/animation/AnimationGroupPreviewUI.js b/third_party/blink/renderer/devtools/front_end/animation/AnimationGroupPreviewUI.js index 3ec7be4..61fb6ac 100644 --- a/third_party/blink/renderer/devtools/front_end/animation/AnimationGroupPreviewUI.js +++ b/third_party/blink/renderer/devtools/front_end/animation/AnimationGroupPreviewUI.js
@@ -32,8 +32,9 @@ let duration = 0; for (const anim of this._model.animations()) { const animDuration = anim.source().delay() + anim.source().duration(); - if (animDuration > duration) + if (animDuration > duration) { duration = animDuration; + } } return duration; }
diff --git a/third_party/blink/renderer/devtools/front_end/animation/AnimationModel.js b/third_party/blink/renderer/devtools/front_end/animation/AnimationModel.js index 0d4001c..837dbd4 100644 --- a/third_party/blink/renderer/devtools/front_end/animation/AnimationModel.js +++ b/third_party/blink/renderer/devtools/front_end/animation/AnimationModel.js
@@ -24,8 +24,9 @@ const resourceTreeModel = /** @type {!SDK.ResourceTreeModel} */ (target.model(SDK.ResourceTreeModel)); resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._reset, this); const screenCaptureModel = target.model(SDK.ScreenCaptureModel); - if (screenCaptureModel) + if (screenCaptureModel) { this._screenshotCapture = new Animation.AnimationModel.ScreenshotCapture(this, screenCaptureModel); + } } _reset() { @@ -55,8 +56,9 @@ */ animationStarted(payload) { // We are not interested in animations without effect or target. - if (!payload.source || !payload.source.backendNodeId) + if (!payload.source || !payload.source.backendNodeId) { return; + } const animation = Animation.AnimationModel.Animation.parsePayload(this, payload); @@ -65,8 +67,9 @@ this._pendingAnimations.remove(animation.id()); } else { this._animationsById.set(animation.id(), animation); - if (this._pendingAnimations.indexOf(animation.id()) === -1) + if (this._pendingAnimations.indexOf(animation.id()) === -1) { this._pendingAnimations.push(animation.id()); + } } this._flushPendingAnimationsIfNeeded(); @@ -74,12 +77,14 @@ _flushPendingAnimationsIfNeeded() { for (const id of this._pendingAnimations) { - if (!this._animationsById.get(id)) + if (!this._animationsById.get(id)) { return; + } } - while (this._pendingAnimations.length) + while (this._pendingAnimations.length) { this._matchExistingGroups(this._createGroupFromPendingAnimations()); + } } /** @@ -98,8 +103,9 @@ if (!matchedGroup) { this._animationGroups.set(incomingGroup.id(), incomingGroup); - if (this._screenshotCapture) + if (this._screenshotCapture) { this._screenshotCapture.captureScreenshots(incomingGroup.finiteDuration(), incomingGroup._screenshots); + } } this.dispatchEventToListeners(Animation.AnimationModel.Events.AnimationGroupStarted, matchedGroup || incomingGroup); return !!matchedGroup; @@ -114,10 +120,11 @@ const remainingAnimations = []; for (const id of this._pendingAnimations) { const anim = this._animationsById.get(id); - if (anim.startTime() === groupedAnimations[0].startTime()) + if (anim.startTime() === groupedAnimations[0].startTime()) { groupedAnimations.push(anim); - else + } else { remainingAnimations.push(id); + } } this._pendingAnimations = remainingAnimations; return new Animation.AnimationModel.AnimationGroup(this, groupedAnimations[0].id(), groupedAnimations); @@ -152,14 +159,16 @@ * @return {!Promise} */ resumeModel() { - if (!this._enabled) + if (!this._enabled) { return Promise.resolve(); + } return this._agent.enable(); } ensureEnabled() { - if (this._enabled) + if (this._enabled) { return; + } this._agent.enable(); this._enabled = true; } @@ -258,8 +267,9 @@ * @return {number} */ endTime() { - if (!this.source().iterations) + if (!this.source().iterations) { return Infinity; + } return this.startTime() + this.source().delay() + this.source().duration() * this.source().iterations() + this.source().endDelay(); } @@ -299,8 +309,9 @@ */ overlaps(animation) { // Infinite animations - if (!this.source().iterations() || !animation.source().iterations()) + if (!this.source().iterations() || !animation.source().iterations()) { return true; + } const firstAnimation = this.startTime() < animation.startTime() ? this : animation; const secondAnimation = firstAnimation === this ? animation : this; @@ -325,12 +336,13 @@ */ _updateNodeStyle(duration, delay, node) { let animationPrefix; - if (this.type() === Animation.AnimationModel.Animation.Type.CSSTransition) + if (this.type() === Animation.AnimationModel.Animation.Type.CSSTransition) { animationPrefix = 'transition-'; - else if (this.type() === Animation.AnimationModel.Animation.Type.CSSAnimation) + } else if (this.type() === Animation.AnimationModel.Animation.Type.CSSAnimation) { animationPrefix = 'animation-'; - else + } else { return; + } const cssModel = node.domModel().cssModel(); cssModel.setEffectivePropertyValueForNode(node.id, animationPrefix + 'duration', duration + 'ms'); @@ -372,8 +384,9 @@ constructor(animationModel, payload) { this._animationModel = animationModel; this._payload = payload; - if (payload.keyframesRule) + if (payload.keyframesRule) { this._keyframesRule = new Animation.AnimationModel.KeyframesRule(payload.keyframesRule); + } this._delay = this._payload.delay; this._duration = this._payload.duration; } @@ -404,8 +417,9 @@ */ iterations() { // Animations with zero duration, zero delays and infinite iterations can't be shown. - if (!this.delay() && !this.endDelay() && !this.duration()) + if (!this.delay() && !this.endDelay() && !this.duration()) { return 0; + } return this._payload.iterations || Infinity; } @@ -434,8 +448,9 @@ * @return {!Promise.<!SDK.DOMNode>} */ node() { - if (!this._deferredNode) + if (!this._deferredNode) { this._deferredNode = new SDK.DeferredDOMNode(this._animationModel.target(), this.backendNodeId()); + } return this._deferredNode.resolvePromise(); } @@ -611,8 +626,9 @@ */ finiteDuration() { let maxDuration = 0; - for (let i = 0; i < this._animations.length; ++i) + for (let i = 0; i < this._animations.length; ++i) { maxDuration = Math.max(maxDuration, this._animations[i]._finiteDuration()); + } return maxDuration; } @@ -634,8 +650,9 @@ * @param {boolean} paused */ togglePause(paused) { - if (paused === this._paused) + if (paused === this._paused) { return; + } this._paused = paused; this._animationModel._agent.setPaused(this._animationIds(), paused); } @@ -646,8 +663,9 @@ currentTimePromise() { let longestAnim = null; for (const anim of this._animations) { - if (!longestAnim || anim.endTime() > longestAnim.endTime()) + if (!longestAnim || anim.endTime() > longestAnim.endTime()) { longestAnim = anim; + } } return this._animationModel._agent.getCurrentTime(longestAnim.id()).then(currentTime => currentTime || 0); } @@ -662,19 +680,22 @@ * @return {string} */ function extractId(anim) { - if (anim.type() === Animation.AnimationModel.Animation.Type.WebAnimation) + if (anim.type() === Animation.AnimationModel.Animation.Type.WebAnimation) { return anim.type() + anim.id(); - else + } else { return anim._cssId(); + } } - if (this._animations.length !== group._animations.length) + if (this._animations.length !== group._animations.length) { return false; + } const left = this._animations.map(extractId).sort(); const right = group._animations.map(extractId).sort(); for (let i = 0; i < left.length; i++) { - if (left[i] !== right[i]) + if (left[i] !== right[i]) { return false; + } } return true; } @@ -766,8 +787,9 @@ this._endTime = endTime; } - if (this._capturing) + if (this._capturing) { return; + } this._capturing = true; this._screenCaptureModel.startScreencast( 'jpeg', 80, undefined, 300, 2, this._screencastFrame.bind(this), visible => {}); @@ -786,18 +808,21 @@ return request.endTime >= now; } - if (!this._capturing) + if (!this._capturing) { return; + } const now = window.performance.now(); this._requests = this._requests.filter(isAnimating); - for (const request of this._requests) + for (const request of this._requests) { request.screenshots.push(base64Data); + } } _stopScreencast() { - if (!this._capturing) + if (!this._capturing) { return; + } delete this._stopTimer; delete this._endTime;
diff --git a/third_party/blink/renderer/devtools/front_end/animation/AnimationScreenshotPopover.js b/third_party/blink/renderer/devtools/front_end/animation/AnimationScreenshotPopover.js index a889421..0d9d3cf 100644 --- a/third_party/blink/renderer/devtools/front_end/animation/AnimationScreenshotPopover.js +++ b/third_party/blink/renderer/devtools/front_end/animation/AnimationScreenshotPopover.js
@@ -46,15 +46,17 @@ return; } this._showFrame = !this._showFrame; - if (!this._showFrame) + if (!this._showFrame) { return; + } const numFrames = this._frames.length; this._frames[this._currentFrame % numFrames].style.display = 'none'; this._currentFrame++; this._frames[(this._currentFrame) % numFrames].style.display = 'block'; - if (this._currentFrame % numFrames === numFrames - 1) + if (this._currentFrame % numFrames === numFrames - 1) { this._endDelay = 50; + } this._progressBar.style.width = (this._currentFrame % numFrames + 1) / numFrames * 100 + '%'; } };
diff --git a/third_party/blink/renderer/devtools/front_end/animation/AnimationTimeline.js b/third_party/blink/renderer/devtools/front_end/animation/AnimationTimeline.js index fdf877e..e2b3c01 100644 --- a/third_party/blink/renderer/devtools/front_end/animation/AnimationTimeline.js +++ b/third_party/blink/renderer/devtools/front_end/animation/AnimationTimeline.js
@@ -41,16 +41,18 @@ * @override */ wasShown() { - for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) + for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) { this._addEventListeners(animationModel); + } } /** * @override */ willHide() { - for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) + for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) { this._removeEventListeners(animationModel); + } this._popoverHelper.hidePopover(); } @@ -59,8 +61,9 @@ * @param {!Animation.AnimationModel} animationModel */ modelAdded(animationModel) { - if (this.isShowing()) + if (this.isShowing()) { this._addEventListeners(animationModel); + } } /** @@ -91,8 +94,9 @@ } _nodeChanged() { - for (const nodeUI of this._nodesMap.values()) + for (const nodeUI of this._nodesMap.values()) { nodeUI._nodeChanged(); + } } /** @@ -166,28 +170,32 @@ */ _getPopoverRequest(event) { const element = event.target; - if (!element.isDescendant(this._previewContainer)) + if (!element.isDescendant(this._previewContainer)) { return null; + } return { box: event.target.boxInWindow(), show: popover => { let animGroup; for (const group of this._previewMap.keysArray()) { - if (this._previewMap.get(group).element === element.parentElement) + if (this._previewMap.get(group).element === element.parentElement) { animGroup = group; + } } console.assert(animGroup); const screenshots = animGroup.screenshots(); - if (!screenshots.length) + if (!screenshots.length) { return Promise.resolve(false); + } let fulfill; const promise = new Promise(x => fulfill = x); - if (!screenshots[0].complete) + if (!screenshots[0].complete) { screenshots[0].onload = onFirstScreenshotLoaded.bind(null, screenshots); - else + } else { onFirstScreenshotLoaded(screenshots); + } return promise; /** @@ -213,11 +221,13 @@ */ _setPlaybackRate(playbackRate) { this._playbackRate = playbackRate; - for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) + for (const animationModel of SDK.targetManager.models(Animation.AnimationModel)) { animationModel.setPlaybackRate(this._allPaused ? 0 : this._playbackRate); + } Host.userMetrics.actionTaken(Host.UserMetrics.Action.AnimationsPlaybackRateChanged); - if (this._scrubberPlayer) + if (this._scrubberPlayer) { this._scrubberPlayer.playbackRate = this._effectivePlaybackRate(); + } this._updatePlaybackControls(); } @@ -230,12 +240,13 @@ } _controlButtonToggle() { - if (this._controlState === Animation.AnimationTimeline._ControlState.Play) + if (this._controlState === Animation.AnimationTimeline._ControlState.Play) { this._togglePause(false); - else if (this._controlState === Animation.AnimationTimeline._ControlState.Replay) + } else if (this._controlState === Animation.AnimationTimeline._ControlState.Replay) { this._replay(); - else + } else { this._togglePause(true); + } } _updateControlButton() { @@ -270,15 +281,17 @@ */ _togglePause(pause) { this._selectedGroup.togglePause(pause); - if (this._scrubberPlayer) + if (this._scrubberPlayer) { this._scrubberPlayer.playbackRate = this._effectivePlaybackRate(); + } this._previewMap.get(this._selectedGroup).element.classList.toggle('paused', pause); this._updateControlButton(); } _replay() { - if (!this._selectedGroup) + if (!this._selectedGroup) { return; + } this._selectedGroup.seekTo(0); this._animateTime(0); this._updateControlButton(); @@ -307,8 +320,9 @@ this._duration = this._defaultDuration; this._timelineScrubber.classList.add('hidden'); delete this._selectedGroup; - if (this._scrubberPlayer) + if (this._scrubberPlayer) { this._scrubberPlayer.cancel(); + } delete this._scrubberPlayer; this._currentTime.textContent = ''; this._updateControlButton(); @@ -316,13 +330,15 @@ _reset() { this._clearTimeline(); - if (this._allPaused) + if (this._allPaused) { this._togglePauseAll(); - else + } else { this._setPlaybackRate(this._playbackRate); + } - for (const group of this._groupBuffer) + for (const group of this._groupBuffer) { group.release(); + } this._groupBuffer = []; this._previewMap.clear(); this._previewContainer.removeChildren(); @@ -350,10 +366,11 @@ } if (this._previewMap.get(group)) { - if (this._selectedGroup === group) + if (this._selectedGroup === group) { this._syncScrubber(); - else + } else { this._previewMap.get(group).replay(); + } return; } this._groupBuffer.sort(startTimeComparator); @@ -417,8 +434,9 @@ this._selectedGroup = group; this._previewMap.forEach(applySelectionClass, this); this.setDuration(Math.max(500, group.finiteDuration() + 100)); - for (const anim of group.animations()) + for (const anim of group.animations()) { this._addAnimation(anim); + } this.scheduleRedraw(); this._timelineScrubber.classList.remove('hidden'); this._togglePause(false); @@ -436,8 +454,9 @@ function nodeResolved(node) { nodeUI.nodeResolved(node); uiAnimation.setNode(node); - if (node) + if (node) { node[this._symbol] = nodeUI; + } } let nodeUI = this._nodesMap.get(animation.source().backendNodeId()); @@ -458,8 +477,9 @@ */ _nodeRemoved(event) { const node = event.data.node; - if (node[this._symbol]) + if (node[this._symbol]) { node[this._symbol].nodeRemoved(); + } } _renderGrid() { @@ -490,10 +510,12 @@ scheduleRedraw() { this._renderQueue = []; - for (const ui of this._uiAnimations) + for (const ui of this._uiAnimations) { this._renderQueue.push(ui); - if (this._redrawing) + } + if (this._redrawing) { return; + } this._redrawing = true; this._renderGrid(); this._animationsContainer.window().requestAnimationFrame(this._render.bind(this)); @@ -503,12 +525,14 @@ * @param {number=} timestamp */ _render(timestamp) { - while (this._renderQueue.length && (!timestamp || window.performance.now() - timestamp < 50)) + while (this._renderQueue.length && (!timestamp || window.performance.now() - timestamp < 50)) { this._renderQueue.shift().redraw(); - if (this._renderQueue.length) + } + if (this._renderQueue.length) { this._animationsContainer.window().requestAnimationFrame(this._render.bind(this)); - else + } else { delete this._redrawing; + } } /** @@ -518,8 +542,9 @@ this._cachedTimelineWidth = Math.max(0, this._animationsContainer.offsetWidth - this._timelineControlsWidth) || 0; this._cachedTimelineHeight = this._animationsContainer.offsetHeight; this.scheduleRedraw(); - if (this._scrubberPlayer) + if (this._scrubberPlayer) { this._syncScrubber(); + } delete this._gridOffsetLeft; } @@ -548,8 +573,9 @@ } _syncScrubber() { - if (!this._selectedGroup) + if (!this._selectedGroup) { return; + } this._selectedGroup.currentTimePromise() .then(this._animateTime.bind(this)) .then(this._updateControlButton.bind(this)); @@ -559,8 +585,9 @@ * @param {number} currentTime */ _animateTime(currentTime) { - if (this._scrubberPlayer) + if (this._scrubberPlayer) { this._scrubberPlayer.cancel(); + } this._scrubberPlayer = this._timelineScrubber.animate( [{transform: 'translateX(0px)'}, {transform: 'translateX(' + this.width() + 'px)'}], @@ -582,13 +609,15 @@ * @param {number} timestamp */ _updateScrubber(timestamp) { - if (!this._scrubberPlayer) + if (!this._scrubberPlayer) { return; + } this._currentTime.textContent = Number.millisToString(this._scrubberPlayer.currentTime); - if (this._scrubberPlayer.playState === 'pending' || this._scrubberPlayer.playState === 'running') + if (this._scrubberPlayer.playState === 'pending' || this._scrubberPlayer.playState === 'running') { this.element.window().requestAnimationFrame(this._updateScrubber.bind(this)); - else if (this._scrubberPlayer.playState === 'finished') + } else if (this._scrubberPlayer.playState === 'finished') { this._currentTime.textContent = ''; + } } /** @@ -596,12 +625,14 @@ * @return {boolean} */ _repositionScrubber(event) { - if (!this._selectedGroup) + if (!this._selectedGroup) { return false; + } // Seek to current mouse position. - if (!this._gridOffsetLeft) + if (!this._gridOffsetLeft) { this._gridOffsetLeft = this._grid.totalOffsetLeft() + 10; + } const seekTime = Math.max(0, event.x - this._gridOffsetLeft) / this.pixelMsRatio(); this._selectedGroup.seekTo(seekTime); this._togglePause(true); @@ -618,8 +649,9 @@ * @return {boolean} */ _scrubberDragStart(event) { - if (!this._scrubberPlayer || !this._selectedGroup) + if (!this._scrubberPlayer || !this._selectedGroup) { return false; + } this._originalScrubberTime = this._scrubberPlayer.currentTime; this._timelineScrubber.classList.remove('animation-timeline-end'); @@ -686,8 +718,9 @@ this._node = node; this._nodeChanged(); Common.Linkifier.linkify(node).then(link => this._description.appendChild(link)); - if (!node.ownerDocument) + if (!node.ownerDocument) { this.nodeRemoved(); + } } /** @@ -727,11 +760,13 @@ */ static parse(text) { let match = text.match(/^steps\((\d+), (start|middle)\)$/); - if (match) + if (match) { return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1], 10), match[2]); + } match = text.match(/^steps\((\d+)\)$/); - if (match) + if (match) { return new Animation.AnimationTimeline.StepTimingFunction(parseInt(match[1], 10), 'end'); + } return null; } };
diff --git a/third_party/blink/renderer/devtools/front_end/animation/AnimationUI.js b/third_party/blink/renderer/devtools/front_end/animation/AnimationUI.js index 8c6ebc40..9a3028c 100644 --- a/third_party/blink/renderer/devtools/front_end/animation/AnimationUI.js +++ b/third_party/blink/renderer/devtools/front_end/animation/AnimationUI.js
@@ -15,8 +15,9 @@ this._timeline = timeline; this._parentElement = parentElement; - if (this._animation.source().keyframesRule()) + if (this._animation.source().keyframesRule()) { this._keyframes = this._animation.source().keyframesRule().keyframes(); + } this._nameElement = parentElement.createChild('div', 'animation-name'); this._nameElement.textContent = this._animation.name(); @@ -81,8 +82,9 @@ */ _drawAnimationLine(iteration, parentElement) { const cache = this._cachedElements[iteration]; - if (!cache.animationLine) + if (!cache.animationLine) { cache.animationLine = this._createLine(parentElement, 'animation-line'); + } cache.animationLine.setAttribute( 'x2', (this._duration() * this._timeline.pixelMsRatio() + Animation.AnimationUI.Options.AnimationMargin).toFixed(2)); @@ -133,21 +135,24 @@ circle.style.stroke = this._color; circle.setAttribute('r', Animation.AnimationUI.Options.AnimationMargin / 2); - if (keyframeIndex <= 0) + if (keyframeIndex <= 0) { circle.style.fill = this._color; + } this._cachedElements[iteration].keyframePoints[keyframeIndex] = circle; - if (!attachEvents) + if (!attachEvents) { return; + } let eventType; - if (keyframeIndex === 0) + if (keyframeIndex === 0) { eventType = Animation.AnimationUI.MouseEvents.StartEndpointMove; - else if (keyframeIndex === -1) + } else if (keyframeIndex === -1) { eventType = Animation.AnimationUI.MouseEvents.FinishEndpointMove; - else + } else { eventType = Animation.AnimationUI.MouseEvents.KeyframeMove; + } UI.installDragHandle( circle, this._mouseDown.bind(this, eventType, keyframeIndex), this._mouseMove.bind(this), this._mouseUp.bind(this), 'ew-resize'); @@ -198,8 +203,9 @@ group.removeChildren(); /** @const */ const offsetMap = {'start': 0, 'middle': 0.5, 'end': 1}; /** @const */ const offsetWeight = offsetMap[stepFunction.stepAtPosition]; - for (let i = 0; i < stepFunction.steps; i++) + for (let i = 0; i < stepFunction.steps; i++) { createStepLine(group, (i + offsetWeight) * width / stepFunction.steps, this._color); + } } } @@ -222,21 +228,25 @@ } this._renderIteration(this._activeIntervalGroup, 0); - if (!this._tailGroup) + if (!this._tailGroup) { this._tailGroup = this._activeIntervalGroup.createSVGChild('g', 'animation-tail-iterations'); + } const iterationWidth = this._duration() * this._timeline.pixelMsRatio(); let iteration; for (iteration = 1; iteration < this._animation.source().iterations() && iterationWidth * (iteration - 1) < this._timeline.width(); - iteration++) + iteration++) { this._renderIteration(this._tailGroup, iteration); - while (iteration < this._cachedElements.length) + } + while (iteration < this._cachedElements.length) { this._cachedElements.pop().group.remove(); + } } _renderTransition() { - if (!this._cachedElements[0]) + if (!this._cachedElements[0]) { this._cachedElements[0] = {animationLine: null, keyframePoints: {}, keyframeRender: {}, group: null}; + } this._drawAnimationLine(0, this._activeIntervalGroup); this._renderKeyframe( 0, 0, this._activeIntervalGroup, Animation.AnimationUI.Options.AnimationMargin, @@ -266,8 +276,9 @@ Animation.AnimationUI.Options.AnimationMargin; const width = this._duration() * (this._offset(i + 1) - this._offset(i)) * this._timeline.pixelMsRatio(); this._renderKeyframe(iteration, i, group, leftDistance, width, this._keyframes[i].easing()); - if (i || (!i && iteration === 0)) + if (i || (!i && iteration === 0)) { this._drawPoint(iteration, group, leftDistance, i, iteration === 0); + } } this._drawPoint( iteration, group, @@ -281,8 +292,9 @@ _delay() { let delay = this._animation.source().delay(); if (this._mouseEventType === Animation.AnimationUI.MouseEvents.AnimationDrag || - this._mouseEventType === Animation.AnimationUI.MouseEvents.StartEndpointMove) + this._mouseEventType === Animation.AnimationUI.MouseEvents.StartEndpointMove) { delay += this._movementInMs; + } // FIXME: add support for negative start delay return Math.max(0, delay); } @@ -292,10 +304,11 @@ */ _duration() { let duration = this._animation.source().duration(); - if (this._mouseEventType === Animation.AnimationUI.MouseEvents.FinishEndpointMove) + if (this._mouseEventType === Animation.AnimationUI.MouseEvents.FinishEndpointMove) { duration += this._movementInMs; - else if (this._mouseEventType === Animation.AnimationUI.MouseEvents.StartEndpointMove) - duration -= Math.max(this._movementInMs, -this._animation.source().delay()); // Cannot have negative delay + } else if (this._mouseEventType === Animation.AnimationUI.MouseEvents.StartEndpointMove) { + duration -= Math.max(this._movementInMs, -this._animation.source().delay()); + } // Cannot have negative delay return Math.max(0, duration); } @@ -320,16 +333,19 @@ * @param {!Event} event */ _mouseDown(mouseEventType, keyframeIndex, event) { - if (event.buttons === 2) + if (event.buttons === 2) { return false; - if (this._svg.enclosingNodeOrSelfWithClass('animation-node-removed')) + } + if (this._svg.enclosingNodeOrSelfWithClass('animation-node-removed')) { return false; + } this._mouseEventType = mouseEventType; this._keyframeMoved = keyframeIndex; this._downMouseX = event.clientX; event.consume(true); - if (this._node) + if (this._node) { Common.Revealer.reveal(this._node); + } return true; } @@ -338,8 +354,9 @@ */ _mouseMove(event) { this._movementInMs = (event.clientX - this._downMouseX) / this._timeline.pixelMsRatio(); - if (this._delay() + this._duration() > this._timeline.duration() * 0.8) + if (this._delay() + this._duration() > this._timeline.duration() * 0.8) { this._timeline.setDuration(this._timeline.duration() * 1.2); + } this.redraw(); } @@ -350,10 +367,11 @@ this._movementInMs = (event.clientX - this._downMouseX) / this._timeline.pixelMsRatio(); // Commit changes - if (this._mouseEventType === Animation.AnimationUI.MouseEvents.KeyframeMove) + if (this._mouseEventType === Animation.AnimationUI.MouseEvents.KeyframeMove) { this._keyframes[this._keyframeMoved].setOffset(this._offset(this._keyframeMoved)); - else + } else { this._animation.setTiming(this._duration(), this._delay()); + } this._movementInMs = 0; this.redraw(); @@ -371,8 +389,9 @@ * @param {?SDK.RemoteObject} remoteObject */ function showContextMenu(remoteObject) { - if (!remoteObject) + if (!remoteObject) { return; + } const contextMenu = new UI.ContextMenu(event); contextMenu.appendApplicableItems(remoteObject); contextMenu.show();
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/AppcacheTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/AppcacheTestRunner.js index 14b4089..85f26f9 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/AppcacheTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/AppcacheTestRunner.js
@@ -74,13 +74,15 @@ }; ApplicationTestRunner.frameIdToString = function(frameId) { - if (!ApplicationTestRunner.framesByFrameId) + if (!ApplicationTestRunner.framesByFrameId) { ApplicationTestRunner.framesByFrameId = {}; + } let frame = TestRunner.resourceTreeModel.frameForId(frameId); - if (!frame) + if (!frame) { frame = ApplicationTestRunner.framesByFrameId[frameId]; + } ApplicationTestRunner.framesByFrameId[frameId] = frame; return frame.name; @@ -102,8 +104,9 @@ const model = UI.panels.resources._sidebar._applicationCacheModel; const frameIds = []; - for (const frameId in model._manifestURLsByFrame) + for (const frameId in model._manifestURLsByFrame) { frameIds.push(frameId); + } function compareFunc(a, b) { return ApplicationTestRunner.frameIdToString(a).localeCompare(ApplicationTestRunner.frameIdToString(b)); @@ -153,8 +156,9 @@ record.manifestURL = manifestURL; record.status = status; - if (!ApplicationTestRunner.applicationCacheStatusesRecords[frameId]) + if (!ApplicationTestRunner.applicationCacheStatusesRecords[frameId]) { ApplicationTestRunner.applicationCacheStatusesRecords[frameId] = []; + } ApplicationTestRunner.applicationCacheStatusesRecords[frameId].push(record); @@ -162,8 +166,9 @@ ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId]) { ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId].count--; - if (!ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId].count) + if (!ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId].count) { ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId].callback(); + } } } @@ -179,8 +184,9 @@ return; } - if (!ApplicationTestRunner.awaitedFrameStatusEventsCount) + if (!ApplicationTestRunner.awaitedFrameStatusEventsCount) { ApplicationTestRunner.awaitedFrameStatusEventsCount = {}; + } ApplicationTestRunner.awaitedFrameStatusEventsCount[frameId] = {count: eventsLeft, callback: callback}; };
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js index 6f8f6b9..adc77c0 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/CacheStorageTestRunner.js
@@ -28,10 +28,11 @@ } UI.panels.resources._sidebar.cacheStorageListTreeElement.expand(); - if (!pathFilter) + if (!pathFilter) { TestRunner.addResult('Dumping CacheStorage tree:'); - else + } else { TestRunner.addResult('Dumping CacheStorage tree with URL path filter string "' + pathFilter + '"'); + } const cachesTreeElement = UI.panels.resources._sidebar.cacheStorageListTreeElement; @@ -45,8 +46,9 @@ TestRunner.addResult(' cache: ' + cacheTreeElement.title); let view = cacheTreeElement._view; - if (!view) + if (!view) { cacheTreeElement.onselect(false); + } view = cacheTreeElement._view; await view._updateData(true); if (cacheTreeElement._view._entriesForTest.length === 0) { @@ -89,26 +91,30 @@ for (let i = 0; i < cachesTreeElement.childCount(); ++i) { const cacheTreeElement = cachesTreeElement.childAt(i); - if (cacheTreeElement.title.split(' ')[0] !== cacheName) + if (cacheTreeElement.title.split(' ')[0] !== cacheName) { continue; + } let view = cacheTreeElement._view; - if (!view) + if (!view) { cacheTreeElement.onselect(false); + } view = cacheTreeElement._view; await view._updateData(true); const promiseDumpContent = new Promise(resolve => { view._model.loadCacheData(view._cache, 0, 50, '', async function(entries, totalCount) { for (const entry of entries) { - if (entry.requestURL !== requestUrl) + if (entry.requestURL !== requestUrl) { continue; + } const request = view._createRequest(entry); if (request.requestHeaders().length) { TestRunner.addResult(' the original request has headers; query with headers? ' + withHeader); - if (!withHeader) + if (!withHeader) { request.setRequestHeaders([]); + } } const contentObject = await view._requestContent(request); const content = contentObject.content; @@ -124,18 +130,20 @@ ApplicationTestRunner.deleteCacheFromInspector = async function(cacheName, optionalEntry) { UI.panels.resources._sidebar.cacheStorageListTreeElement.expand(); - if (optionalEntry) + if (optionalEntry) { TestRunner.addResult('Deleting CacheStorage entry ' + optionalEntry + ' in cache ' + cacheName); - else + } else { TestRunner.addResult('Deleting CacheStorage cache ' + cacheName); + } const cachesTreeElement = UI.panels.resources._sidebar.cacheStorageListTreeElement; let promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.prototype, '_updateCacheNames'); UI.panels.resources._sidebar.cacheStorageListTreeElement._refreshCaches(); await promise; - if (!cachesTreeElement.childCount()) + if (!cachesTreeElement.childCount()) { throw 'Error: Could not find CacheStorage cache ' + cacheName; + } for (let i = 0; i < cachesTreeElement.childCount(); i++) { @@ -143,8 +151,9 @@ const title = cacheTreeElement.title; const elementCacheName = title.substring(0, title.lastIndexOf(' - ')); - if (elementCacheName !== cacheName) + if (elementCacheName !== cacheName) { continue; + } if (!optionalEntry) { promise = TestRunner.addSnifferPromise(SDK.ServiceWorkerCacheModel.prototype, '_cacheRemoved'); @@ -156,17 +165,19 @@ promise = TestRunner.addSnifferPromise(Resources.ServiceWorkerCacheView.prototype, '_updateDataCallback'); let view = cacheTreeElement._view; - if (!view) + if (!view) { cacheTreeElement.onselect(false); - else + } else { view._updateData(true); + } view = cacheTreeElement._view; await promise; const entry = view._entriesForTest.find(entry => entry.requestURL === optionalEntry); - if (!entry) + if (!entry) { throw 'Error: Could not find cache entry to delete: ' + optionalEntry; + } await view._model.deleteCacheEntry(view._cache, entry.requestURL); return;
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/IndexedDBTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/IndexedDBTestRunner.js index 9cb4080..d85b66c 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/IndexedDBTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/IndexedDBTestRunner.js
@@ -51,8 +51,9 @@ TestRunner.addResult(' Object store: ' + objectStoreTreeElement.title); const entries = objectStoreTreeElement._view._entries; TestRunner.addResult(' Number of entries: ' + entries.length); - for (let j = 0; j < entries.length; ++j) + for (let j = 0; j < entries.length; ++j) { TestRunner.addResult(' Key = ' + entries[j].key._value + ', value = ' + entries[j].value); + } for (let k = 0; k < objectStoreTreeElement.childCount(); ++k) { const indexTreeElement = objectStoreTreeElement.childAt(k); @@ -60,8 +61,9 @@ indexTreeElement.onselect(false); const entries = indexTreeElement._view._entries; TestRunner.addResult(' Number of entries: ' + entries.length); - for (let j = 0; j < entries.length; ++j) + for (let j = 0; j < entries.length; ++j) { TestRunner.addResult(' Key = ' + entries[j].primaryKey._value + ', value = ' + entries[j].value); + } } } }; @@ -76,8 +78,9 @@ callbacks[callbackId] = callback; let parametersString = 'dispatchCallback.bind(this, "' + callbackIdPrefix + callbackId + '")'; - for (let i = 0; i < parameters.length; ++i) + for (let i = 0; i < parameters.length; ++i) { parametersString += ', ' + JSON.stringify(parameters[i]); + } const requestString = methodName + '(' + parametersString + ')'; TestRunner.evaluateInPageAnonymously(requestString);
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourceTreeTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourceTreeTestRunner.js index 9a13b23..eb4345922 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourceTreeTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourceTreeTestRunner.js
@@ -11,10 +11,11 @@ const results = []; function formatterWrapper(resource) { - if (formatter) + if (formatter) { results.push({resource: resource, text: formatter(resource)}); - else + } else { results.push({resource: resource, text: resource.url}); + } } TestRunner.resourceTreeModel.forAllResources(formatterWrapper); @@ -25,8 +26,9 @@ results.sort(comparator); - for (let i = 0; i < results.length; ++i) + for (let i = 0; i < results.length; ++i) { TestRunner.addResult(results[i].text); + } }; ApplicationTestRunner.dumpResourcesURLMap = function() { @@ -38,32 +40,37 @@ } function comparator(result1, result2) { - if (result1.url > result2.url) + if (result1.url > result2.url) { return 1; + } - if (result2.url > result1.url) + if (result2.url > result1.url) { return -1; + } return 0; } results.sort(comparator); - for (let i = 0; i < results.length; ++i) + for (let i = 0; i < results.length; ++i) { TestRunner.addResult(results[i].url + ' == ' + results[i].resource.url); + } }; ApplicationTestRunner.dumpResourcesTree = function() { function dump(treeItem, prefix) { - if (typeof treeItem._resetBubble === 'function') + if (typeof treeItem._resetBubble === 'function') { treeItem._resetBubble(); + } TestRunner.addResult(prefix + treeItem.listItemElement.textContent); treeItem.expand(); const children = treeItem.children(); - for (let i = 0; children && i < children.length; ++i) + for (let i = 0; children && i < children.length; ++i) { dump(children[i], prefix + ' '); + } } dump(UI.panels.resources._sidebar._resourcesSection._treeElement, '');
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourcesTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourcesTestRunner.js index 3945403..cc92123 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourcesTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/ResourcesTestRunner.js
@@ -29,10 +29,11 @@ }; ApplicationTestRunner.runAfterCachedResourcesProcessed = function(callback) { - if (!TestRunner.resourceTreeModel._cachedResourcesProcessed) + if (!TestRunner.resourceTreeModel._cachedResourcesProcessed) { TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded, callback); - else + } else { callback(); + } }; ApplicationTestRunner.runAfterResourcesAreFinished = function(resourceURLs, callback) { @@ -42,8 +43,9 @@ for (const url of resourceURLsMap) { const resource = ApplicationTestRunner.resourceMatchingURL(url); - if (resource) + if (resource) { resourceURLsMap.delete(url); + } } if (!resourceURLsMap.size) { @@ -54,16 +56,18 @@ checkResources(); - if (resourceURLsMap.size) + if (resourceURLsMap.size) { TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.ResourceAdded, checkResources); + } }; ApplicationTestRunner.showResource = function(resourceURL, callback) { let reported = false; function callbackWrapper(sourceFrame) { - if (reported) + if (reported) { return; + } callback(sourceFrame); reported = true; @@ -72,16 +76,18 @@ function showResourceCallback() { const resource = ApplicationTestRunner.resourceMatchingURL(resourceURL); - if (!resource) + if (!resource) { return; + } UI.panels.resources.showResource(resource, 1); const sourceFrame = UI.panels.resources._resourceViewForResource(resource); - if (sourceFrame.loaded) + if (sourceFrame.loaded) { callbackWrapper(sourceFrame); - else + } else { TestRunner.addSniffer(sourceFrame, 'setContent', callbackWrapper.bind(null, sourceFrame)); + } } ApplicationTestRunner.runAfterResourcesAreFinished([resourceURL], showResourceCallback); @@ -110,8 +116,9 @@ ApplicationTestRunner.dumpCookieDomains = function() { const cookieListChildren = UI.panels.resources._sidebar.cookieListTreeElement.children(); TestRunner.addResult('Available cookie domains:'); - for (const child of cookieListChildren) + for (const child of cookieListChildren) { TestRunner.addResult(child._cookieDomain); + } }; ApplicationTestRunner.dumpCookies = function() { @@ -123,8 +130,9 @@ TestRunner.addResult('Visible cookies'); for (const item of UI.panels.resources._cookieView._cookiesTable._data) { const cookies = item.cookies || []; - for (const cookie of cookies) + for (const cookie of cookies) { TestRunner.addResult(`${cookie.name()}=${cookie.value()}`); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js b/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js index 385c1421..c2639b65 100644 --- a/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/application_test_runner/ServiceWorkersTestRunner.js
@@ -42,8 +42,9 @@ return swView._currentWorkersView._sectionList.childTextNodes() .concat(swView._otherWorkersView._sectionList.childTextNodes()) .map(function(node) { - if (node.textContent === 'Received ' + (new Date(0)).toLocaleString()) + if (node.textContent === 'Received ' + (new Date(0)).toLocaleString()) { return 'Invalid scriptResponseTime (unix epoch)'; + } return node.textContent.replace(/Received.*/, 'Received').replace(/#\d+/, '#N'); }) .join('\n'); @@ -51,8 +52,9 @@ ApplicationTestRunner.deleteServiceWorkerRegistration = function(scope) { TestRunner.serviceWorkerManager.registrations().valuesArray().map(function(registration) { - if (registration.scopeURL === scope) + if (registration.scopeURL === scope) { TestRunner.serviceWorkerManager.deleteRegistration(registration.id); + } }); };
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsController.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsController.js index 1ab901a..23b2b99 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsController.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsController.js
@@ -13,8 +13,9 @@ protocolService.registerStatusCallback( message => this.dispatchEventToListeners(Audits.Events.AuditProgressChanged, {message})); - for (const preset of Audits.Presets) + for (const preset of Audits.Presets) { preset.setting.addChangeListener(this.recomputePageAuditability.bind(this)); + } SDK.targetManager.observeModels(SDK.ServiceWorkerManager, this); SDK.targetManager.addEventListener( @@ -26,8 +27,9 @@ * @param {!SDK.ServiceWorkerManager} serviceWorkerManager */ modelAdded(serviceWorkerManager) { - if (this._manager) + if (this._manager) { return; + } this._manager = serviceWorkerManager; this._serviceWorkerListeners = [ @@ -45,8 +47,9 @@ * @param {!SDK.ServiceWorkerManager} serviceWorkerManager */ modelRemoved(serviceWorkerManager) { - if (this._manager !== serviceWorkerManager) + if (this._manager !== serviceWorkerManager) { return; + } Common.EventTarget.removeEventListeners(this._serviceWorkerListeners); this._manager = null; @@ -57,22 +60,26 @@ * @return {boolean} */ _hasActiveServiceWorker() { - if (!this._manager) + if (!this._manager) { return false; + } const mainTarget = this._manager.target(); - if (!mainTarget) + if (!mainTarget) { return false; + } const inspectedURL = mainTarget.inspectedURL().asParsedURL(); const inspectedOrigin = inspectedURL && inspectedURL.securityOrigin(); for (const registration of this._manager.registrations().values()) { - if (registration.securityOrigin !== inspectedOrigin) + if (registration.securityOrigin !== inspectedOrigin) { continue; + } for (const version of registration.versions.values()) { - if (version.controlledClients.length > 1) + if (version.controlledClients.length > 1) { return true; + } } } @@ -90,8 +97,9 @@ * @return {?string} */ _unauditablePageMessage() { - if (!this._manager) + if (!this._manager) { return null; + } const mainTarget = this._manager.target(); const inspectedURL = mainTarget && mainTarget.inspectedURL(); @@ -111,8 +119,9 @@ const runtimeModel = mainTarget.model(SDK.RuntimeModel); const executionContext = runtimeModel && runtimeModel.defaultExecutionContext(); let inspectedURL = mainTarget.inspectedURL(); - if (!executionContext) + if (!executionContext) { return inspectedURL; + } // Evaluate location.href for a more specific URL than inspectedURL provides so that SPA hash navigation routes // will be respected and audited. @@ -146,8 +155,9 @@ // DevTools handles all the emulation. This tells Lighthouse to not bother with emulation. deviceScreenEmulationMethod: 'provided' }; - for (const runtimeSetting of Audits.RuntimeSettings) + for (const runtimeSetting of Audits.RuntimeSettings) { runtimeSetting.setFlags(flags, runtimeSetting.setting.get()); + } return flags; } @@ -157,8 +167,9 @@ getCategoryIDs() { const categoryIDs = []; for (const preset of Audits.Presets) { - if (preset.setting.get()) + if (preset.setting.get()) { categoryIDs.push(preset.configID); + } } return categoryIDs; } @@ -168,8 +179,9 @@ * @return {!Promise<string>} */ async getInspectedURL(options) { - if (options && options.force || !this._inspectedURL) + if (options && options.force || !this._inspectedURL) { this._inspectedURL = await this._evaluateInspectedURL(); + } return this._inspectedURL; }
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsPanel.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsPanel.js index afb78b4..baf1029 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsPanel.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsPanel.js
@@ -40,8 +40,9 @@ */ _refreshStartAuditUI(evt) { // PageAuditabilityChanged fires multiple times during an audit, which we want to ignore. - if (this._isLHAttached) + if (this._isLHAttached) { return; + } this._unauditableExplanation = evt.data.helpText; this._startView.setUnauditableExplanation(evt.data.helpText); @@ -94,8 +95,9 @@ this._startView.show(this.contentElement); this._startView.setUnauditableExplanation(this._unauditableExplanation); this._startView.setStartButtonEnabled(!this._unauditableExplanation); - if (!this._unauditableExplanation) + if (!this._unauditableExplanation) { this._startView.focusStartButton(); + } this._newButton.setEnabled(false); this._refreshToolbarUI(); @@ -147,8 +149,9 @@ const templatesHTML = Runtime.cachedResources['audits/lighthouse/templates.html']; const templatesDOM = new DOMParser().parseFromString(templatesHTML, 'text/html'); - if (!templatesDOM) + if (!templatesDOM) { return; + } renderer.setTemplateContext(templatesDOM); const el = renderer.renderReport(lighthouseResult, reportContainer); @@ -181,8 +184,9 @@ * @param {!ReportRenderer.RunnerResultArtifacts=} artifacts */ _buildReportUI(lighthouseResult, artifacts) { - if (lighthouseResult === null) + if (lighthouseResult === null) { return; + } const optionElement = new Audits.ReportSelector.Item( lighthouseResult, () => this._renderReport(lighthouseResult, artifacts), this._renderStartView.bind(this)); @@ -196,13 +200,15 @@ */ _handleDrop(dataTransfer) { const items = dataTransfer.items; - if (!items.length) + if (!items.length) { return; + } const item = items[0]; if (item.kind === 'file') { const entry = items[0].webkitGetAsEntry(); - if (!entry.isFile) + if (!entry.isFile) { return; + } entry.file(file => { const reader = new FileReader(); reader.onload = () => this._loadedFromFile(/** @type {string} */ (reader.result)); @@ -216,8 +222,9 @@ */ _loadedFromFile(report) { const data = JSON.parse(report); - if (!data['lighthouseVersion']) + if (!data['lighthouseVersion']) { return; + } this._buildReportUI(/** @type {!ReportRenderer.ReportJSON} */ (data)); } @@ -241,8 +248,9 @@ throw error; } - if (!lighthouseResponse) + if (!lighthouseResponse) { throw new Error('Auditing failed to produce a result'); + } Host.userMetrics.actionTaken(Host.UserMetrics.Action.AuditsFinished); @@ -250,8 +258,9 @@ this._buildReportUI(lighthouseResponse.lhr, lighthouseResponse.artifacts); } catch (err) { await this._resetEmulationAndProtocolConnection(); - if (err instanceof Error) + if (err instanceof Error) { this._statusView.renderBugReport(err); + } } } @@ -290,8 +299,9 @@ emulationModel.deviceOutlineSetting().set(true); for (const device of Emulation.EmulatedDevicesList.instance().standard()) { - if (device.title === 'Nexus 5X') + if (device.title === 'Nexus 5X') { emulationModel.emulate(Emulation.DeviceModeModel.Type.Device, device, device.modes[0], 1); + } } } @@ -300,8 +310,9 @@ } async _resetEmulationAndProtocolConnection() { - if (!this._isLHAttached) + if (!this._isLHAttached) { return; + } this._isLHAttached = false; await this._protocolService.detach();
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsProtocolService.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsProtocolService.js index f2e677f0..6f31a5f0 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsProtocolService.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsProtocolService.js
@@ -62,8 +62,9 @@ _initWorker() { this._backendPromise = Services.serviceManager.createAppService('audits_worker', 'AuditsService').then(backend => { - if (this._backend) + if (this._backend) { return; + } this._backend = backend; this._backend.on('statusUpdate', result => this._status(result.message)); this._backend.on('sendProtocolMessage', result => this._sendProtocolMessage(result.message)); @@ -83,8 +84,9 @@ * @return {!Promise<!ReportRenderer.RunnerResult>} */ _send(method, params) { - if (!this._backendPromise) + if (!this._backendPromise) { this._initWorker(); + } return this._backendPromise.then(_ => this._backend.send(method, params)); }
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsReportRenderer.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsReportRenderer.js index f3f1edf2..daa33ae 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsReportRenderer.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsReportRenderer.js
@@ -11,14 +11,16 @@ * @param {!ReportRenderer.RunnerResultArtifacts=} artifacts */ static addViewTraceButton(el, artifacts) { - if (!artifacts || !artifacts.traces || !artifacts.traces.defaultPass) + if (!artifacts || !artifacts.traces || !artifacts.traces.defaultPass) { return; + } const container = el.querySelector('.lh-audit-group'); const columnsEl = container.querySelector('.lh-columns'); // There will be no columns if just the PWA category. - if (!columnsEl) + if (!columnsEl) { return; + } const defaultPassTrace = artifacts.traces.defaultPass; const timelineButton = UI.createTextButton(Common.UIString('View Trace'), onViewTraceClick, 'view-trace'); @@ -41,16 +43,19 @@ for (const origElement of el.getElementsByClassName('lh-node')) { /** @type {!DetailsRenderer.NodeDetailsJSON} */ const detailsItem = origElement.dataset; - if (!detailsItem.path) + if (!detailsItem.path) { continue; + } const nodeId = await domModel.pushNodeByPathToFrontend(detailsItem.path); - if (!nodeId) + if (!nodeId) { continue; + } const node = domModel.nodeForId(nodeId); - if (!node) + if (!node) { continue; + } const element = await Common.Linkifier.linkify(node, {tooltip: detailsItem.snippet}); origElement.title = ''; @@ -63,8 +68,9 @@ * @param {!Element} el */ static handleDarkMode(el) { - if (UI.themeSupport.themeName() === 'dark') + if (UI.themeSupport.themeName() === 'dark') { el.classList.add('dark'); + } } }; @@ -130,13 +136,15 @@ // Linkified nodes are shadow elements, which aren't exposed via `cloneNode`. await Audits.ReportRenderer.linkifyNodeDetails(clonedReport); - if (this._beforePrint) + if (this._beforePrint) { this._beforePrint(); + } printWindow.focus(); printWindow.print(); printWindow.close(); - if (this._afterPrint) + if (this._afterPrint) { this._afterPrint(); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsReportSelector.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsReportSelector.js index 2af39a1..4ac9fd4 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsReportSelector.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsReportSelector.js
@@ -28,10 +28,11 @@ */ _handleChange(event) { const item = this._selectedItem(); - if (item) + if (item) { item.select(); - else + } else { this._renderNewAuditView(); + } } /** @@ -79,8 +80,9 @@ clearAll() { for (const elem of this._comboBox.options()) { - if (elem === this._newAuditItem) + if (elem === this._newAuditItem) { continue; + } this._itemByOptionElement.get(elem).delete(); this._itemByOptionElement.delete(elem); @@ -123,8 +125,9 @@ } delete() { - if (this._element) + if (this._element) { this._element.remove(); + } this._showLandingCallback(); } };
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsStartView.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsStartView.js index 736a8364..027130c 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsStartView.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsStartView.js
@@ -23,8 +23,9 @@ */ _populateRuntimeSettingAsRadio(settingName, label, parentElement) { const runtimeSetting = Audits.RuntimeSettings.find(item => item.setting.name === settingName); - if (!runtimeSetting || !runtimeSetting.options) + if (!runtimeSetting || !runtimeSetting.options) { throw new Error(`${settingName} is not a setting with options`); + } const control = new Audits.RadioSetting(runtimeSetting.options, runtimeSetting.setting, runtimeSetting.description); parentElement.appendChild(control.element); @@ -37,8 +38,9 @@ */ _populateRuntimeSettingAsCheckbox(settingName, parentElement) { const runtimeSetting = Audits.RuntimeSettings.find(item => item.setting.name === settingName); - if (!runtimeSetting || !runtimeSetting.title) + if (!runtimeSetting || !runtimeSetting.title) { throw new Error(`${settingName} is not a setting with a title`); + } runtimeSetting.setting.setTitle(runtimeSetting.title); const control = new UI.ToolbarSettingCheckbox(runtimeSetting.setting, runtimeSetting.description); @@ -148,18 +150,21 @@ * @param {boolean} isEnabled */ setStartButtonEnabled(isEnabled) { - if (this._helpText) + if (this._helpText) { this._helpText.classList.toggle('hidden', isEnabled); + } - if (this._startButton) + if (this._startButton) { this._startButton.disabled = !isEnabled; + } } /** * @param {?string} text */ setUnauditableExplanation(text) { - if (this._helpText) + if (this._helpText) { this._helpText.textContent = text; + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/audits/AuditsStatusView.js b/third_party/blink/renderer/devtools/front_end/audits/AuditsStatusView.js index c480e788..c8a67a5a 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/AuditsStatusView.js +++ b/third_party/blink/renderer/devtools/front_end/audits/AuditsStatusView.js
@@ -96,8 +96,9 @@ } hide() { - if (this._dialog.isShowing()) + if (this._dialog.isShowing()) { this._dialog.hide(); + } } /** @@ -111,8 +112,9 @@ * @param {?string} message */ updateStatus(message) { - if (!message || !this._statusText) + if (!message || !this._statusText) { return; + } if (message.startsWith('Cancel')) { this._commitTextChange(Common.UIString('Cancelling\u2026')); @@ -142,8 +144,9 @@ * @return {string} */ _getMessageForPhase(phase) { - if (phase.message) + if (phase.message) { return phase.message; + } const deviceType = Audits.RuntimeSettings.find(item => item.setting.name === 'audits.device_type').setting.get(); const throttling = Audits.RuntimeSettings.find(item => item.setting.name === 'audits.throttling').setting.get(); @@ -163,15 +166,17 @@ } _resetProgressBarClasses() { - if (!this._progressBar) + if (!this._progressBar) { return; + } this._progressBar.className = 'audits-progress-bar'; } _scheduleFastFactCheck() { - if (!this._currentPhase || this._scheduledFastFactTimeout) + if (!this._currentPhase || this._scheduledFastFactTimeout) { return; + } this._scheduledFastFactTimeout = setTimeout(() => { this._updateFastFactIfNecessary(); @@ -183,10 +188,12 @@ _updateFastFactIfNecessary() { const now = performance.now(); - if (now - this._textChangedAt < Audits.StatusView.fastFactRotationInterval) + if (now - this._textChangedAt < Audits.StatusView.fastFactRotationInterval) { return; - if (!this._fastFactsQueued.length) + } + if (!this._fastFactsQueued.length) { return; + } const fastFactIndex = Math.floor(Math.random() * this._fastFactsQueued.length); this._scheduleTextChange(ls`\ud83d\udca1 ${this._fastFactsQueued[fastFactIndex]}`); @@ -197,8 +204,9 @@ * @param {string} text */ _commitTextChange(text) { - if (!this._statusText) + if (!this._statusText) { return; + } this._textChangedAt = performance.now(); this._statusText.textContent = text; } @@ -207,8 +215,9 @@ * @param {string} text */ _scheduleTextChange(text) { - if (this._scheduledTextChangeTimeout) + if (this._scheduledTextChangeTimeout) { clearTimeout(this._scheduledTextChangeTimeout); + } const msSinceLastChange = performance.now() - this._textChangedAt; const msToTextChange = Audits.StatusView.minimumTextVisibilityDuration - msSinceLastChange;
diff --git a/third_party/blink/renderer/devtools/front_end/audits/RadioSetting.js b/third_party/blink/renderer/devtools/front_end/audits/RadioSetting.js index ddc84f5..bbe09e5e 100644 --- a/third_party/blink/renderer/devtools/front_end/audits/RadioSetting.js +++ b/third_party/blink/renderer/devtools/front_end/audits/RadioSetting.js
@@ -27,8 +27,9 @@ `; this.element.appendChild(fragment.element()); - if (option.title) + if (option.title) { UI.Tooltip.install(fragment.$('label'), option.title); + } const radioElement = fragment.$('input'); radioElement.addEventListener('change', this._valueChanged.bind(this)); this._radioElements.push(radioElement); @@ -57,8 +58,9 @@ * @param {!Event} event */ _valueChanged(event) { - if (this._ignoreChangeEvents) + if (this._ignoreChangeEvents) { return; + } const selectedRadio = this._radioElements.find(radio => radio.checked); this._setting.set(selectedRadio.value);
diff --git a/third_party/blink/renderer/devtools/front_end/audits_test_runner/AuditsTestRunner.js b/third_party/blink/renderer/devtools/front_end/audits_test_runner/AuditsTestRunner.js index 78af5c4..d595cf6 100644 --- a/third_party/blink/renderer/devtools/front_end/audits_test_runner/AuditsTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/audits_test_runner/AuditsTestRunner.js
@@ -81,8 +81,9 @@ * @return {string} */ AuditsTestRunner._checkboxStateLabel = function(checkboxContainer) { - if (!checkboxContainer) + if (!checkboxContainer) { return 'missing'; + } const label = checkboxContainer.textElement.textContent; const checkedLabel = checkboxContainer.checkboxElement.checked ? 'x' : ' '; @@ -94,8 +95,9 @@ * @return {string} */ AuditsTestRunner._buttonStateLabel = function(button) { - if (!button) + if (!button) { return 'missing'; + } const enabledLabel = button.disabled ? 'disabled' : 'enabled'; const hiddenLabel = window.getComputedStyle(button).getPropertyValue('visibility'); @@ -112,8 +114,9 @@ }); const helpText = containerElement.querySelector('.audits-help-text'); - if (!helpText.classList.contains('hidden')) + if (!helpText.classList.contains('hidden')) { TestRunner.addResult(`Help text: ${helpText.textContent}`); + } TestRunner.addResult(AuditsTestRunner._buttonStateLabel(AuditsTestRunner.getRunButton())); };
diff --git a/third_party/blink/renderer/devtools/front_end/audits_worker.js b/third_party/blink/renderer/devtools/front_end/audits_worker.js index 059a2e09..77fad7f 100644 --- a/third_party/blink/renderer/devtools/front_end/audits_worker.js +++ b/third_party/blink/renderer/devtools/front_end/audits_worker.js
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Release build has Runtime.js bundled. -if (!self.Runtime) +if (!self.Runtime) { self.importScripts('Runtime.js'); +} Runtime.startWorker('audits_worker');
diff --git a/third_party/blink/renderer/devtools/front_end/audits_worker/AuditsService.js b/third_party/blink/renderer/devtools/front_end/audits_worker/AuditsService.js index d3d7ca7..80689072 100644 --- a/third_party/blink/renderer/devtools/front_end/audits_worker/AuditsService.js +++ b/third_party/blink/renderer/devtools/front_end/audits_worker/AuditsService.js
@@ -111,10 +111,12 @@ * @param {function(string|undefined)} cb */ on(eventName, cb) { - if (eventName === 'message') + if (eventName === 'message') { this._onMessage = cb; - if (eventName === 'close') + } + if (eventName === 'close') { this._onClose = cb; + } } _disableLoggingForTest() {
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/BlackboxManager.js b/third_party/blink/renderer/devtools/front_end/bindings/BlackboxManager.js index 0e6aab39..9dfcd49 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/BlackboxManager.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/BlackboxManager.js
@@ -63,8 +63,9 @@ } _clearCacheIfNeeded() { - if (this._isBlackboxedURLCache.size > 1024) + if (this._isBlackboxedURLCache.size > 1024) { this._isBlackboxedURLCache.clear(); + } } /** @@ -75,8 +76,9 @@ const regexPatterns = Common.moduleSetting('skipStackFramesPattern').getAsArray(); const patterns = /** @type {!Array<string>} */ ([]); for (const item of regexPatterns) { - if (!item.disabled && item.pattern) + if (!item.disabled && item.pattern) { patterns.push(item.pattern); + } } return debuggerModel.setBlackboxPatterns(patterns); } @@ -88,8 +90,9 @@ isBlackboxedUISourceCode(uiSourceCode) { const projectType = uiSourceCode.project().type(); const isContentScript = projectType === Workspace.projectTypes.ContentScripts; - if (isContentScript && Common.moduleSetting('skipContentScripts').get()) + if (isContentScript && Common.moduleSetting('skipContentScripts').get()) { return true; + } const url = this._uiSourceCodeURL(uiSourceCode); return url ? this.isBlackboxedURL(url) : false; } @@ -100,10 +103,12 @@ * @return {boolean} */ isBlackboxedURL(url, isContentScript) { - if (this._isBlackboxedURLCache.has(url)) + if (this._isBlackboxedURLCache.has(url)) { return !!this._isBlackboxedURLCache.get(url); - if (isContentScript && Common.moduleSetting('skipContentScripts').get()) + } + if (isContentScript && Common.moduleSetting('skipContentScripts').get()) { return true; + } const regex = Common.moduleSetting('skipStackFramesPattern').asRegExp(); const isBlackboxed = (regex && regex.test(url)) || false; this._isBlackboxedURLCache.set(url, isBlackboxed); @@ -134,11 +139,13 @@ */ async _updateScriptRanges(script, sourceMap) { let hasBlackboxedMappings = false; - if (!Bindings.blackboxManager.isBlackboxedURL(script.sourceURL, script.isContentScript())) + if (!Bindings.blackboxManager.isBlackboxedURL(script.sourceURL, script.isContentScript())) { hasBlackboxedMappings = sourceMap ? sourceMap.sourceURLs().some(url => this.isBlackboxedURL(url)) : false; + } if (!hasBlackboxedMappings) { - if (script[Bindings.BlackboxManager._blackboxedRanges] && await script.setBlackboxedRanges([])) + if (script[Bindings.BlackboxManager._blackboxedRanges] && await script.setBlackboxedRanges([])) { delete script[Bindings.BlackboxManager._blackboxedRanges]; + } this._debuggerWorkspaceBinding.updateLocations(script); return; } @@ -158,8 +165,9 @@ } const oldRanges = script[Bindings.BlackboxManager._blackboxedRanges] || []; - if (!isEqual(oldRanges, newRanges) && await script.setBlackboxedRanges(newRanges)) + if (!isEqual(oldRanges, newRanges) && await script.setBlackboxedRanges(newRanges)) { script[Bindings.BlackboxManager._blackboxedRanges] = newRanges; + } this._debuggerWorkspaceBinding.updateLocations(script); /** @@ -168,11 +176,13 @@ * @return {boolean} */ function isEqual(rangesA, rangesB) { - if (rangesA.length !== rangesB.length) + if (rangesA.length !== rangesB.length) { return false; + } for (let i = 0; i < rangesA.length; ++i) { - if (rangesA[i].lineNumber !== rangesB[i].lineNumber || rangesA[i].columnNumber !== rangesB[i].columnNumber) + if (rangesA[i].lineNumber !== rangesB[i].lineNumber || rangesA[i].columnNumber !== rangesB[i].columnNumber) { return false; + } } return true; } @@ -200,8 +210,9 @@ */ blackboxUISourceCode(uiSourceCode) { const url = this._uiSourceCodeURL(uiSourceCode); - if (url) + if (url) { this._blackboxURL(url); + } } /** @@ -209,8 +220,9 @@ */ unblackboxUISourceCode(uiSourceCode) { const url = this._uiSourceCodeURL(uiSourceCode); - if (url) + if (url) { this._unblackboxURL(url); + } } blackboxContentScripts() { @@ -227,8 +239,9 @@ _blackboxURL(url) { const regexPatterns = Common.moduleSetting('skipStackFramesPattern').getAsArray(); const regexValue = this._urlToRegExpString(url); - if (!regexValue) + if (!regexValue) { return; + } let found = false; for (let i = 0; i < regexPatterns.length; ++i) { const item = regexPatterns[i]; @@ -238,8 +251,9 @@ break; } } - if (!found) + if (!found) { regexPatterns.push({pattern: regexValue}); + } Common.moduleSetting('skipStackFramesPattern').setAsArray(regexPatterns); } @@ -249,19 +263,22 @@ _unblackboxURL(url) { let regexPatterns = Common.moduleSetting('skipStackFramesPattern').getAsArray(); const regexValue = Bindings.blackboxManager._urlToRegExpString(url); - if (!regexValue) + if (!regexValue) { return; + } regexPatterns = regexPatterns.filter(function(item) { return item.pattern !== regexValue; }); for (let i = 0; i < regexPatterns.length; ++i) { const item = regexPatterns[i]; - if (item.disabled) + if (item.disabled) { continue; + } try { const regex = new RegExp(item.pattern); - if (regex.test(url)) + if (regex.test(url)) { item.disabled = true; + } } catch (e) { } } @@ -276,13 +293,15 @@ for (const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)) { promises.push(this._setBlackboxPatterns(debuggerModel)); const sourceMapManager = debuggerModel.sourceMapManager(); - for (const script of debuggerModel.scripts()) + for (const script of debuggerModel.scripts()) { promises.push(this._updateScriptRanges(script, sourceMapManager.sourceMapForClient(script))); + } } await Promise.all(promises); const listeners = Array.from(this._listeners); - for (const listener of listeners) + for (const listener of listeners) { listener(); + } this._patternChangeFinishedForTests(); } @@ -296,25 +315,31 @@ */ _urlToRegExpString(url) { const parsedURL = new Common.ParsedURL(url); - if (parsedURL.isAboutBlank() || parsedURL.isDataURL()) + if (parsedURL.isAboutBlank() || parsedURL.isDataURL()) { return ''; - if (!parsedURL.isValid) + } + if (!parsedURL.isValid) { return '^' + url.escapeForRegExp() + '$'; + } let name = parsedURL.lastPathComponent; - if (name) + if (name) { name = '/' + name; - else if (parsedURL.folderPathComponents) + } else if (parsedURL.folderPathComponents) { name = parsedURL.folderPathComponents + '/'; - if (!name) + } + if (!name) { name = parsedURL.host; - if (!name) + } + if (!name) { return ''; + } const scheme = parsedURL.scheme; let prefix = ''; if (scheme && scheme !== 'http' && scheme !== 'https') { prefix = '^' + scheme + '://'; - if (scheme === 'chrome-extension') + if (scheme === 'chrome-extension') { prefix += parsedURL.host + '\\b'; + } prefix += '.*'; } return prefix + name.escapeForRegExp() + (url.endsWith(name) ? '$' : '\\b');
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js b/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js index 22527be..13a74be 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/BreakpointManager.js
@@ -58,8 +58,9 @@ * @return {string} */ static _breakpointStorageId(url, lineNumber, columnNumber) { - if (!url) + if (!url) { return ''; + } return url + ':' + lineNumber + ':' + columnNumber; } @@ -69,8 +70,9 @@ */ copyBreakpoints(fromURL, toSourceCode) { const breakpointItems = this._storage.breakpointItems(fromURL); - for (const item of breakpointItems) + for (const item of breakpointItems) { this.setBreakpoint(toSourceCode, item.lineNumber, item.columnNumber, item.condition, item.enabled); + } } /** @@ -78,13 +80,15 @@ */ _restoreBreakpoints(uiSourceCode) { const url = uiSourceCode.url(); - if (!url) + if (!url) { return; + } this._storage.mute(); const breakpointItems = this._storage.breakpointItems(url); - for (const item of breakpointItems) + for (const item of breakpointItems) { this._innerSetBreakpoint(uiSourceCode, item.lineNumber, item.columnNumber, item.condition, item.enabled); + } this._storage.unmute(); } @@ -158,8 +162,9 @@ const endLocations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations( uiSourceCode, textRange.endLine, textRange.endColumn); const endLocationByModel = new Map(); - for (const location of endLocations) + for (const location of endLocations) { endLocationByModel.set(location.debuggerModel, location); + } let startLocation = null; let endLocation = null; for (const location of startLocations) { @@ -170,8 +175,9 @@ break; } } - if (!startLocation || !endLocation) + if (!startLocation || !endLocation) { return Promise.resolve([]); + } return startLocation.debuggerModel .getPossibleBreakpoints(startLocation, endLocation, /* restrictToFunction */ false) @@ -186,13 +192,15 @@ let sortedLocations = locations.map(location => this._debuggerWorkspaceBinding.rawLocationToUILocation(location)); sortedLocations = sortedLocations.filter(location => location && location.uiSourceCode === uiSourceCode); sortedLocations.sort(Workspace.UILocation.comparator); - if (!sortedLocations.length) + if (!sortedLocations.length) { return []; + } const result = [sortedLocations[0]]; let lastLocation = sortedLocations[0]; for (let i = 1; i < sortedLocations.length; ++i) { - if (sortedLocations[i].id() === lastLocation.id()) + if (sortedLocations[i].id() === lastLocation.id()) { continue; + } result.push(sortedLocations[i]); lastLocation = sortedLocations[i]; } @@ -214,8 +222,9 @@ */ allBreakpointLocations() { let result = []; - for (const breakpoints of this._breakpointsForUISourceCode.values()) + for (const breakpoints of this._breakpointsForUISourceCode.values()) { result = result.concat(Array.from(breakpoints.values())); + } return result; } @@ -224,8 +233,9 @@ * @param {boolean} removeFromStorage */ _removeBreakpoint(breakpoint, removeFromStorage) { - if (removeFromStorage) + if (removeFromStorage) { this._storage._removeBreakpoint(breakpoint); + } this._breakpointByStorageId.delete(breakpoint._breakpointStorageId()); } @@ -250,14 +260,17 @@ */ _uiLocationRemoved(breakpoint, uiLocation) { const breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode); - if (!breakpoints) + if (!breakpoints) { return; + } const breakpointLocation = breakpoints.get(uiLocation.id()) || null; - if (!breakpointLocation) + if (!breakpointLocation) { return; + } breakpoints.delete(uiLocation.id()); - if (breakpoints.size === 0) + if (breakpoints.size === 0) { this._breakpointsForUISourceCode.delete(uiLocation.uiSourceCode); + } this.dispatchEventToListeners( Bindings.BreakpointManager.Events.BreakpointRemoved, {breakpoint: breakpoint, uiLocation: uiLocation}); } @@ -314,10 +327,12 @@ } refreshInDebugger() { - if (this._isRemoved) + if (this._isRemoved) { return; - for (const breakpoint of this._modelBreakpoints.values()) + } + for (const breakpoint of this._modelBreakpoints.values()) { breakpoint._refreshBreakpoint(); + } } /** @@ -344,14 +359,17 @@ * @param {?Workspace.UISourceCode} primaryUISourceCode */ setPrimaryUISourceCode(primaryUISourceCode) { - if (this._uiLocations.size === 0 && this._defaultUILocation) + if (this._uiLocations.size === 0 && this._defaultUILocation) { this._breakpointManager._uiLocationRemoved(this, this._defaultUILocation); - if (primaryUISourceCode) + } + if (primaryUISourceCode) { this._defaultUILocation = primaryUISourceCode.uiLocation(this._lineNumber, this._columnNumber); - else + } else { this._defaultUILocation = null; - if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) + } + if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) { this._breakpointManager._uiLocationAdded(this, this._defaultUILocation); + } } /** @@ -379,10 +397,12 @@ * @param {!Workspace.UILocation} uiLocation */ _uiLocationAdded(uiLocation) { - if (this._isRemoved) + if (this._isRemoved) { return; - if (this._uiLocations.size === 0 && this._defaultUILocation) + } + if (this._uiLocations.size === 0 && this._defaultUILocation) { this._breakpointManager._uiLocationRemoved(this, this._defaultUILocation); + } this._uiLocations.add(uiLocation); this._breakpointManager._uiLocationAdded(this, uiLocation); } @@ -393,8 +413,9 @@ _uiLocationRemoved(uiLocation) { this._uiLocations.delete(uiLocation); this._breakpointManager._uiLocationRemoved(this, uiLocation); - if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) + if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) { this._breakpointManager._uiLocationAdded(this, this._defaultUILocation); + } } /** @@ -430,8 +451,9 @@ * @param {boolean} enabled */ _updateState(condition, enabled) { - if (this._enabled === enabled && this._condition === condition) + if (this._enabled === enabled && this._condition === condition) { return; + } this._enabled = enabled; this._condition = condition; this._breakpointManager._storage._updateBreakpoint(this); @@ -439,13 +461,16 @@ } _updateBreakpoint() { - if (this._uiLocations.size === 0 && this._defaultUILocation) + if (this._uiLocations.size === 0 && this._defaultUILocation) { this._breakpointManager._uiLocationRemoved(this, this._defaultUILocation); - if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) + } + if (this._uiLocations.size === 0 && this._defaultUILocation && !this._isRemoved) { this._breakpointManager._uiLocationAdded(this, this._defaultUILocation); + } const modelBreakpoints = this._modelBreakpoints.valuesArray(); - for (let i = 0; i < modelBreakpoints.length; ++i) + for (let i = 0; i < modelBreakpoints.length; ++i) { modelBreakpoints[i]._scheduleUpdateInDebugger(); + } } /** @@ -475,8 +500,9 @@ _resetLocations() { this.setPrimaryUISourceCode(null); const modelBreakpoints = this._modelBreakpoints.valuesArray(); - for (let i = 0; i < modelBreakpoints.length; ++i) + for (let i = 0; i < modelBreakpoints.length; ++i) { modelBreakpoints[i]._resetLocations(); + } } }; @@ -506,13 +532,15 @@ this._isUpdating = false; this._cancelCallback = false; this._currentState = null; - if (this._debuggerModel.debuggerEnabled()) + if (this._debuggerModel.debuggerEnabled()) { this._scheduleUpdateInDebugger(); + } } _resetLocations() { - for (const uiLocation of this._uiLocations.values()) + for (const uiLocation of this._uiLocations.values()) { this._breakpoint._uiLocationRemoved(uiLocation); + } this._uiLocations.clear(); this._liveLocations.disposeAll(); @@ -542,8 +570,9 @@ _scriptDiverged() { const uiLocation = this._breakpoint._defaultUILocation; const uiSourceCode = uiLocation ? uiLocation.uiSourceCode : null; - if (!uiSourceCode) + if (!uiSourceCode) { return false; + } const scriptFile = this._debuggerWorkspaceBinding.scriptFile(uiSourceCode, this._debuggerModel); return !!scriptFile && scriptFile.hasDivergedFromVM(); } @@ -618,15 +647,17 @@ result = await this._debuggerModel.setBreakpointInAnonymousScript( newState.scriptId, newState.scriptHash, newState.lineNumber, newState.columnNumber, newState.condition); } - if (result && result.breakpointId) + if (result && result.breakpointId) { this._didSetBreakpointInDebugger(callback, result.breakpointId, result.locations); - else + } else { this._didSetBreakpointInDebugger(callback, null, []); + } } async _refreshBreakpoint() { - if (!this._debuggerId) + if (!this._debuggerId) { return; + } this._resetLocations(); await this._debuggerModel.removeBreakpoint(this._debuggerId); this._didRemoveFromDebugger(); @@ -655,8 +686,9 @@ this._debuggerId = breakpointId; this._debuggerModel.addBreakpointListener(this._debuggerId, this._breakpointResolved, this); for (let i = 0; i < locations.length; ++i) { - if (!this._addResolvedLocation(locations[i])) + if (!this._addResolvedLocation(locations[i])) { break; + } } callback(); } @@ -684,14 +716,16 @@ */ _locationUpdated(liveLocation) { const oldUILocation = this._uiLocations.get(liveLocation); - if (oldUILocation) + if (oldUILocation) { this._breakpoint._uiLocationRemoved(oldUILocation); + } let uiLocation = liveLocation.uiLocation(); if (uiLocation) { const breakpointLocation = this._breakpoint._breakpointManager.findBreakpoint(uiLocation); - if (breakpointLocation && breakpointLocation.uiLocation !== breakpointLocation.breakpoint._defaultUILocation) + if (breakpointLocation && breakpointLocation.uiLocation !== breakpointLocation.breakpoint._defaultUILocation) { uiLocation = null; + } } if (uiLocation) { @@ -708,8 +742,9 @@ */ _addResolvedLocation(location) { const uiLocation = this._debuggerWorkspaceBinding.rawLocationToUILocation(location); - if (!uiLocation) + if (!uiLocation) { return false; + } const breakpointLocation = this._breakpoint._breakpointManager.findBreakpoint(uiLocation); if (breakpointLocation && breakpointLocation.breakpoint !== this._breakpoint) { // location clash @@ -721,13 +756,15 @@ } _cleanUpAfterDebuggerIsGone() { - if (this._isUpdating) + if (this._isUpdating) { this._cancelCallback = true; + } this._resetLocations(); this._currentState = null; - if (this._debuggerId) + if (this._debuggerId) { this._didRemoveFromDebugger(); + } } _removeEventListeners() { @@ -762,8 +799,9 @@ * @return {boolean} */ static equals(stateA, stateB) { - if (!stateA || !stateB) + if (!stateA || !stateB) { return false; + } return stateA.url === stateB.url && stateA.scriptId === stateB.scriptId && stateA.scriptHash === stateB.scriptHash && stateA.lineNumber === stateB.lineNumber && stateA.columnNumber === stateB.columnNumber && stateA.condition === stateB.condition; @@ -805,8 +843,9 @@ * @param {!Bindings.BreakpointManager.Breakpoint} breakpoint */ _updateBreakpoint(breakpoint) { - if (this._muted || !breakpoint._breakpointStorageId()) + if (this._muted || !breakpoint._breakpointStorageId()) { return; + } this._breakpoints.set(breakpoint._breakpointStorageId(), new Bindings.BreakpointManager.Storage.Item(breakpoint)); this._save(); } @@ -815,8 +854,9 @@ * @param {!Bindings.BreakpointManager.Breakpoint} breakpoint */ _removeBreakpoint(breakpoint) { - if (this._muted) + if (this._muted) { return; + } this._breakpoints.delete(breakpoint._breakpointStorageId()); this._save(); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js b/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js index 430be4a..f3b86d8 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js
@@ -61,15 +61,18 @@ */ propertyUILocation(cssProperty, forName) { const style = cssProperty.ownerStyle; - if (!style || style.type !== SDK.CSSStyleDeclaration.Type.Regular || !style.styleSheetId) + if (!style || style.type !== SDK.CSSStyleDeclaration.Type.Regular || !style.styleSheetId) { return null; + } const header = style.cssModel().styleSheetHeaderForId(style.styleSheetId); - if (!header) + if (!header) { return null; + } const range = forName ? cssProperty.nameRange() : cssProperty.valueRange(); - if (!range) + if (!range) { return null; + } const lineNumber = range.startLine; const columnNumber = range.startColumn; @@ -85,8 +88,9 @@ rawLocationToUILocation(rawLocation) { for (let i = this._sourceMappings.length - 1; i >= 0; --i) { const uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation); - if (uiLocation) + if (uiLocation) { return uiLocation; + } } return this._modelToInfo.get(rawLocation.cssModel())._rawLocationToUILocation(rawLocation); } @@ -98,12 +102,14 @@ uiLocationToRawLocations(uiLocation) { for (let i = this._sourceMappings.length - 1; i >= 0; --i) { const rawLocations = this._sourceMappings[i].uiLocationToRawLocations(uiLocation); - if (rawLocations.length) + if (rawLocations.length) { return rawLocations; + } } const rawLocations = []; - for (const modelInfo of this._modelToInfo.values()) + for (const modelInfo of this._modelToInfo.values()) { rawLocations.pushAll(modelInfo._uiLocationToRawLocations(uiLocation)); + } return rawLocations; } @@ -178,18 +184,20 @@ * @param {!Bindings.CSSWorkspaceBinding.LiveLocation} location */ _disposeLocation(location) { - if (location._header) + if (location._header) { this._locations.delete(location._header, location); - else + } else { this._unboundLocations.delete(location._url, location); + } } /** * @param {!SDK.CSSStyleSheetHeader} header */ _updateLocations(header) { - for (const location of this._locations.get(header)) + for (const location of this._locations.get(header)) { location.update(); + } } /** @@ -197,8 +205,9 @@ */ _styleSheetAdded(event) { const header = /** @type {!SDK.CSSStyleSheetHeader} */ (event.data); - if (!header.sourceURL) + if (!header.sourceURL) { return; + } for (const location of this._unboundLocations.get(header.sourceURL)) { location._header = header; @@ -239,11 +248,13 @@ */ _uiLocationToRawLocations(uiLocation) { let rawLocations = this._sassSourceMapping.uiLocationToRawLocations(uiLocation); - if (rawLocations.length) + if (rawLocations.length) { return rawLocations; + } rawLocations = this._stylesSourceMapping.uiLocationToRawLocations(uiLocation); - if (rawLocations.length) + if (rawLocations.length) { return rawLocations; + } return Bindings.resourceMapping.uiLocationToCSSLocations(uiLocation); } @@ -278,8 +289,9 @@ * @return {?Workspace.UILocation} */ uiLocation() { - if (!this._header) + if (!this._header) { return null; + } const rawLocation = new SDK.CSSLocation(this._header, this._lineNumber, this._columnNumber); return Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js index d74e9e1..42b1180 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/CompilerScriptMapping.js
@@ -103,8 +103,9 @@ */ static uiSourceCodeOrigin(uiSourceCode) { const sourceMap = uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]; - if (!sourceMap) + if (!sourceMap) { return null; + } return sourceMap.compiledURL(); } @@ -115,8 +116,9 @@ mapsToSourceCode(rawLocation) { const script = rawLocation.script(); const sourceMap = script ? this._sourceMapManager.sourceMapForClient(script) : null; - if (!sourceMap) + if (!sourceMap) { return true; + } return !!sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber); } @@ -136,28 +138,34 @@ */ rawLocationToUILocation(rawLocation) { const script = rawLocation.script(); - if (!script) + if (!script) { return null; + } const lineNumber = rawLocation.lineNumber - script.lineOffset; let columnNumber = rawLocation.columnNumber; - if (!lineNumber) + if (!lineNumber) { columnNumber -= script.columnOffset; + } const stubUISourceCode = this._stubUISourceCodes.get(script); - if (stubUISourceCode) + if (stubUISourceCode) { return new Workspace.UILocation(stubUISourceCode, lineNumber, columnNumber); + } const sourceMap = this._sourceMapManager.sourceMapForClient(script); - if (!sourceMap) + if (!sourceMap) { return null; + } const entry = sourceMap.findEntry(lineNumber, columnNumber); - if (!entry || !entry.sourceURL) + if (!entry || !entry.sourceURL) { return null; + } const uiSourceCode = script.isContentScript() ? this._contentScriptsProject.uiSourceCodeForURL(entry.sourceURL) : this._regularProject.uiSourceCodeForURL(entry.sourceURL); - if (!uiSourceCode) + if (!uiSourceCode) { return null; + } return uiSourceCode.uiLocation( /** @type {number} */ (entry.sourceLineNumber), /** @type {number} */ (entry.sourceColumnNumber)); } @@ -171,14 +179,17 @@ */ uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) { const sourceMap = uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]; - if (!sourceMap) + if (!sourceMap) { return []; + } const scripts = this._sourceMapManager.clientsForSourceMap(sourceMap); - if (!scripts.length) + if (!scripts.length) { return []; + } const entry = sourceMap.sourceLineMapping(uiSourceCode.url(), lineNumber, columnNumber); - if (!entry) + if (!entry) { return []; + } return scripts.map( script => this._debuggerModel.createRawLocation( script, entry.lineNumber + script.lineOffset, @@ -232,8 +243,9 @@ const binding = bindings.get(sourceURL); if (binding) { binding.removeSourceMap(sourceMap, frameId); - if (!binding._uiSourceCode) + if (!binding._uiSourceCode) { bindings.delete(sourceURL); + } } } this._debuggerWorkspaceBinding.updateLocations(script); @@ -280,8 +292,9 @@ */ static uiLineHasMapping(uiSourceCode, lineNumber) { const sourceMap = uiSourceCode[Bindings.CompilerScriptMapping._sourceMapSymbol]; - if (!sourceMap) + if (!sourceMap) { return true; + } return !!sourceMap.sourceLineMapping(uiSourceCode.url(), lineNumber, 0); } @@ -317,8 +330,9 @@ */ _recreateUISourceCodeIfNeeded(frameId) { const sourceMap = this._referringSourceMaps.peekLast(); - if (this._activeSourceMap === sourceMap) + if (this._activeSourceMap === sourceMap) { return; + } this._activeSourceMap = sourceMap; const newUISourceCode = this._project.createUISourceCode(this._url, Common.resourceTypes.SourceMapScript); @@ -344,8 +358,9 @@ * @param {string} frameId */ addSourceMap(sourceMap, frameId) { - if (this._uiSourceCode) + if (this._uiSourceCode) { Bindings.NetworkProject.addFrameAttribution(this._uiSourceCode, frameId); + } this._referringSourceMaps.push(sourceMap); this._recreateUISourceCodeIfNeeded(frameId); } @@ -358,8 +373,9 @@ Bindings.NetworkProject.removeFrameAttribution( /** @type {!Workspace.UISourceCode} */ (this._uiSourceCode), frameId); const lastIndex = this._referringSourceMaps.lastIndexOf(sourceMap); - if (lastIndex !== -1) + if (lastIndex !== -1) { this._referringSourceMaps.splice(lastIndex, 1); + } if (!this._referringSourceMaps.length) { this._project.removeFile(this._uiSourceCode.url()); this._uiSourceCode = null;
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/ContentProviderBasedProject.js b/third_party/blink/renderer/devtools/front_end/bindings/ContentProviderBasedProject.js index bf59485..d978e76 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/ContentProviderBasedProject.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/ContentProviderBasedProject.js
@@ -252,8 +252,9 @@ break; } } - if (allMatchesFound) + if (allMatchesFound) { result.push(path); + } progress.worked(1); } }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/DebuggerWorkspaceBinding.js b/third_party/blink/renderer/devtools/front_end/bindings/DebuggerWorkspaceBinding.js index b3bba8a..5a28b6d6 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/DebuggerWorkspaceBinding.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/DebuggerWorkspaceBinding.js
@@ -56,8 +56,9 @@ */ updateLocations(script) { const modelData = this._debuggerModelToData.get(script.debuggerModel); - if (modelData) + if (modelData) { modelData._updateLocations(script); + } } /** @@ -93,8 +94,9 @@ */ createCallFrameLiveLocation(location, updateDelegate, locationPool) { const script = location.script(); - if (!script) + if (!script) { return null; + } const debuggerModel = location.debuggerModel; const liveLocation = this.createLiveLocation(location, updateDelegate, locationPool); this._registerCallFrameLiveLocation(debuggerModel, liveLocation); @@ -108,8 +110,9 @@ rawLocationToUILocation(rawLocation) { for (let i = 0; i < this._sourceMappings.length; ++i) { const uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation); - if (uiLocation) + if (uiLocation) { return uiLocation; + } } const modelData = this._debuggerModelToData.get(rawLocation.debuggerModel); return modelData._rawLocationToUILocation(rawLocation); @@ -122,8 +125,9 @@ */ uiSourceCodeForSourceMapSourceURL(debuggerModel, url, isContentScript) { const modelData = this._debuggerModelToData.get(debuggerModel); - if (!modelData) + if (!modelData) { return null; + } return modelData._compilerMapping.uiSourceCodeForURL(url, isContentScript); } @@ -135,12 +139,15 @@ */ uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) { let locations = []; - for (let i = 0; i < this._sourceMappings.length && !locations.length; ++i) + for (let i = 0; i < this._sourceMappings.length && !locations.length; ++i) { locations = this._sourceMappings[i].uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber); - if (locations.length) + } + if (locations.length) { return locations; - for (const modelData of this._debuggerModelToData.values()) + } + for (const modelData of this._debuggerModelToData.values()) { locations.push(...modelData._uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber)); + } return locations; } @@ -153,8 +160,9 @@ this.uiLocationToRawLocations(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber); for (const location of rawLocations) { const uiLocationCandidate = this.rawLocationToUILocation(location); - if (uiLocationCandidate) + if (uiLocationCandidate) { return uiLocationCandidate; + } } return uiLocation; } @@ -175,8 +183,9 @@ */ sourceMapForScript(script) { const modelData = this._debuggerModelToData.get(script.debuggerModel); - if (!modelData) + if (!modelData) { return null; + } return modelData._compilerMapping.sourceMapForScript(script); } @@ -220,8 +229,9 @@ */ _removeLiveLocation(location) { const modelData = this._debuggerModelToData.get(location._script.debuggerModel); - if (modelData) + if (modelData) { modelData._disposeLocation(location); + } } /** @@ -287,8 +297,9 @@ * @param {!SDK.Script} script */ _updateLocations(script) { - for (const location of this._locations.get(script)) + for (const location of this._locations.get(script)) { location.update(); + } } /** @@ -422,23 +433,26 @@ */ dispose() { super.dispose(); - for (const location of this._locations) + for (const location of this._locations) { location.dispose(); + } this._locations = null; this._current = null; } _scheduleUpdate() { - if (this._updateScheduled) + if (this._updateScheduled) { return; + } this._updateScheduled = true; setImmediate(this._updateLocation.bind(this)); } _updateLocation() { this._updateScheduled = false; - if (!this._locations) + if (!this._locations) { return; + } this._current = this._locations.find(location => !location.isBlackboxed()) || this._locations[0]; this.update(); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/DefaultScriptMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/DefaultScriptMapping.js index 26fea96..e0768294 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/DefaultScriptMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/DefaultScriptMapping.js
@@ -68,13 +68,15 @@ */ rawLocationToUILocation(rawLocation) { const script = rawLocation.script(); - if (!script) + if (!script) { return null; + } const uiSourceCode = script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]; const lineNumber = rawLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0); let columnNumber = rawLocation.columnNumber || 0; - if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) + if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) { columnNumber -= script.columnOffset; + } return uiSourceCode.uiLocation(lineNumber, columnNumber); } @@ -87,8 +89,9 @@ */ uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) { const script = uiSourceCode[this._scriptSymbol]; - if (!script) + if (!script) { return []; + } if (script.isInlineScriptWithSourceURL()) { return [this._debuggerModel.createRawLocation( script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset)]; @@ -106,10 +109,11 @@ const uiSourceCode = this._project.createUISourceCode(url, Common.resourceTypes.Script); uiSourceCode[this._scriptSymbol] = script; - if (!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol]) + if (!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol]) { uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol] = new Set([script]); - else + } else { uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].add(script); + } script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol] = uiSourceCode; this._project.addUISourceCodeWithProvider(uiSourceCode, script, null, 'text/javascript'); this._debuggerWorkspaceBinding.updateLocations(script); @@ -121,13 +125,15 @@ _discardedScriptSource(event) { const script = /** @type {!SDK.Script} */ (event.data); const uiSourceCode = script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]; - if (!uiSourceCode) + if (!uiSourceCode) { return; + } delete script[Bindings.DefaultScriptMapping._uiSourceCodeSymbol]; delete uiSourceCode[this._scriptSymbol]; uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].delete(script); - if (!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].size) + if (!uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol].size) { delete uiSourceCode[Bindings.DefaultScriptMapping._scriptsSymbol]; + } this._project.removeUISourceCode(uiSourceCode.url()); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/FileUtils.js b/third_party/blink/renderer/devtools/front_end/bindings/FileUtils.js index d3023d8..0ce7c74 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/FileUtils.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/FileUtils.js
@@ -84,8 +84,9 @@ * @return {!Promise<boolean>} */ read(output) { - if (this._chunkTransferredCallback) + if (this._chunkTransferredCallback) { this._chunkTransferredCallback(this); + } this._output = output; this._reader = new FileReader(); this._reader.onload = this._onChunkLoaded.bind(this); @@ -137,21 +138,25 @@ * @param {!Event} event */ _onChunkLoaded(event) { - if (this._isCanceled) + if (this._isCanceled) { return; + } - if (event.target.readyState !== FileReader.DONE) + if (event.target.readyState !== FileReader.DONE) { return; + } const buffer = this._reader.result; this._loadedSize += buffer.byteLength; const endOfFile = this._loadedSize === this._fileSize; const decodedString = this._decoder.decode(buffer, {stream: !endOfFile}); this._output.write(decodedString); - if (this._isCanceled) + if (this._isCanceled) { return; - if (this._chunkTransferredCallback) + } + if (this._chunkTransferredCallback) { this._chunkTransferredCallback(this); + } if (endOfFile) { this._file = null; @@ -195,8 +200,9 @@ this._writeCallbacks = []; this._fileName = fileName; const saveResponse = await Workspace.fileManager.save(this._fileName, '', true); - if (saveResponse) + if (saveResponse) { Workspace.fileManager.addEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); + } return !!saveResponse; } @@ -217,8 +223,9 @@ */ async close() { this._closed = true; - if (this._writeCallbacks.length) + if (this._writeCallbacks.length) { return; + } Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); Workspace.fileManager.close(this._fileName); } @@ -227,13 +234,16 @@ * @param {!Common.Event} event */ _onAppendDone(event) { - if (event.data !== this._fileName) + if (event.data !== this._fileName) { return; + } this._writeCallbacks.shift()(); - if (this._writeCallbacks.length) + if (this._writeCallbacks.length) { return; - if (!this._closed) + } + if (!this._closed) { return; + } Workspace.fileManager.removeEventListener(Workspace.FileManager.Events.AppendedToURL, this._onAppendDone, this); Workspace.fileManager.close(this._fileName); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/LiveLocation.js b/third_party/blink/renderer/devtools/front_end/bindings/LiveLocation.js index d4b13f7..0e3b042d 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/LiveLocation.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/LiveLocation.js
@@ -90,7 +90,8 @@ } disposeAll() { - for (const location of this._locations) + for (const location of this._locations) { location.dispose(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/NetworkProject.js b/third_party/blink/renderer/devtools/front_end/bindings/NetworkProject.js index cddee9d..43d0093 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/NetworkProject.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/NetworkProject.js
@@ -55,8 +55,9 @@ */ static setInitialFrameAttribution(uiSourceCode, frameId) { const frame = Bindings.NetworkProject._resolveFrame(uiSourceCode, frameId); - if (!frame) + if (!frame) { return; + } /** @type {!Map<string, !{frame: !SDK.ResourceTreeFrame, count: number}>} */ const attribution = new Map(); attribution.set(frameId, {frame: frame, count: 1}); @@ -69,8 +70,9 @@ */ static cloneInitialFrameAttribution(fromUISourceCode, toUISourceCode) { const fromAttribution = fromUISourceCode[Bindings.NetworkProject._frameAttributionSymbol]; - if (!fromAttribution) + if (!fromAttribution) { return; + } /** @type {!Map<string, !{frame: !SDK.ResourceTreeFrame, count: number}>} */ const toAttribution = new Map(); toUISourceCode[Bindings.NetworkProject._frameAttributionSymbol] = toAttribution; @@ -86,14 +88,16 @@ */ static addFrameAttribution(uiSourceCode, frameId) { const frame = Bindings.NetworkProject._resolveFrame(uiSourceCode, frameId); - if (!frame) + if (!frame) { return; + } const frameAttribution = uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]; const attributionInfo = frameAttribution.get(frameId) || {frame: frame, count: 0}; attributionInfo.count += 1; frameAttribution.set(frameId, attributionInfo); - if (attributionInfo.count !== 1) + if (attributionInfo.count !== 1) { return; + } const data = {uiSourceCode: uiSourceCode, frame: frame}; Bindings.networkProjectManager.dispatchEventToListeners( @@ -106,13 +110,15 @@ */ static removeFrameAttribution(uiSourceCode, frameId) { const frameAttribution = uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]; - if (!frameAttribution) + if (!frameAttribution) { return; + } const attributionInfo = frameAttribution.get(frameId); console.assert(attributionInfo, 'Failed to remove frame attribution for url: ' + uiSourceCode.url()); attributionInfo.count -= 1; - if (attributionInfo.count > 0) + if (attributionInfo.count > 0) { return; + } frameAttribution.delete(frameId); const data = {uiSourceCode: uiSourceCode, frame: attributionInfo.frame}; Bindings.networkProjectManager.dispatchEventToListeners( @@ -143,8 +149,9 @@ const target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); const resourceTreeModel = target && target.model(SDK.ResourceTreeModel); const attribution = uiSourceCode[Bindings.NetworkProject._frameAttributionSymbol]; - if (!resourceTreeModel || !attribution) + if (!resourceTreeModel || !attribution) { return []; + } const frames = Array.from(attribution.keys()).map(frameId => resourceTreeModel.frameForId(frameId)); return frames.filter(frame => !!frame); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/PresentationConsoleMessageHelper.js b/third_party/blink/renderer/devtools/front_end/bindings/PresentationConsoleMessageHelper.js index 41c62e7..b12a99b 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/PresentationConsoleMessageHelper.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/PresentationConsoleMessageHelper.js
@@ -64,15 +64,17 @@ */ _consoleMessageAdded(message) { if (!message.isErrorOrWarning() || !message.runtimeModel() || - message.source === SDK.ConsoleMessage.MessageSource.Violation) + message.source === SDK.ConsoleMessage.MessageSource.Violation) { return; + } const debuggerModel = message.runtimeModel().debuggerModel(); debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleMessageAdded(message); } _consoleCleared() { - for (const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)) + for (const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)) { debuggerModel[Bindings.PresentationConsoleMessageManager._symbol]._consoleCleared(); + } } }; @@ -104,10 +106,11 @@ */ _consoleMessageAdded(message) { const rawLocation = this._rawLocation(message); - if (rawLocation) + if (rawLocation) { this._addConsoleMessageToScript(message, rawLocation); - else + } else { this._addPendingConsoleMessage(message); + } } /** @@ -115,15 +118,17 @@ * @return {?SDK.DebuggerModel.Location} */ _rawLocation(message) { - if (message.scriptId) + if (message.scriptId) { return this._debuggerModel.createRawLocationByScriptId(message.scriptId, message.line, message.column); + } const callFrame = message.stackTrace && message.stackTrace.callFrames ? message.stackTrace.callFrames[0] : null; if (callFrame) { return this._debuggerModel.createRawLocationByScriptId( callFrame.scriptId, callFrame.lineNumber, callFrame.columnNumber); } - if (message.url) + if (message.url) { return this._debuggerModel.createRawLocationByURL(message.url, message.line, message.column); + } return null; } @@ -140,10 +145,12 @@ * @param {!SDK.ConsoleMessage} message */ _addPendingConsoleMessage(message) { - if (!message.url) + if (!message.url) { return; - if (!this._pendingConsoleMessages[message.url]) + } + if (!this._pendingConsoleMessages[message.url]) { this._pendingConsoleMessages[message.url] = []; + } this._pendingConsoleMessages[message.url].push(message); } @@ -154,25 +161,29 @@ const script = /** @type {!SDK.Script} */ (event.data); const messages = this._pendingConsoleMessages[script.sourceURL]; - if (!messages) + if (!messages) { return; + } const pendingMessages = []; for (let i = 0; i < messages.length; i++) { const message = messages[i]; const rawLocation = this._rawLocation(message); - if (!rawLocation) + if (!rawLocation) { continue; - if (script.scriptId === rawLocation.scriptId) + } + if (script.scriptId === rawLocation.scriptId) { this._addConsoleMessageToScript(message, rawLocation); - else + } else { pendingMessages.push(message); + } } - if (pendingMessages.length) + if (pendingMessages.length) { this._pendingConsoleMessages[script.sourceURL] = pendingMessages; - else + } else { delete this._pendingConsoleMessages[script.sourceURL]; + } } _consoleCleared() { @@ -181,8 +192,9 @@ } _debuggerReset() { - for (const message of this._presentationConsoleMessages) + for (const message of this._presentationConsoleMessages) { message.dispose(); + } this._presentationConsoleMessages = []; this._locationPool.disposeAll(); } @@ -209,17 +221,20 @@ * @param {!Bindings.LiveLocation} liveLocation */ _updateLocation(liveLocation) { - if (this._uiMessage) + if (this._uiMessage) { this._uiMessage.remove(); + } const uiLocation = liveLocation.uiLocation(); - if (!uiLocation) + if (!uiLocation) { return; + } this._uiMessage = uiLocation.uiSourceCode.addLineMessage(this._level, this._text, uiLocation.lineNumber, uiLocation.columnNumber); } dispose() { - if (this._uiMessage) + if (this._uiMessage) { this._uiMessage.remove(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js index 14f2744..49c8fa8b 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js
@@ -51,20 +51,24 @@ */ cssLocationToUILocation(cssLocation) { const header = cssLocation.header(); - if (!header) + if (!header) { return null; + } const info = this._infoForTarget(cssLocation.cssModel().target()); - if (!info) + if (!info) { return null; + } const uiSourceCode = info._project.uiSourceCodeForURL(cssLocation.url); - if (!uiSourceCode) + if (!uiSourceCode) { return null; + } const offset = header[Bindings.ResourceMapping._offsetSymbol] || TextUtils.TextRange.createFromLocation(header.startLine, header.startColumn); const lineNumber = cssLocation.lineNumber + offset.startLine - header.startLine; let columnNumber = cssLocation.columnNumber; - if (cssLocation.lineNumber === header.startLine) + if (cssLocation.lineNumber === header.startLine) { columnNumber += offset.startColumn - header.startColumn; + } return uiSourceCode.uiLocation(lineNumber, columnNumber); } @@ -74,20 +78,24 @@ */ jsLocationToUILocation(jsLocation) { const script = jsLocation.script(); - if (!script) + if (!script) { return null; + } const info = this._infoForTarget(jsLocation.debuggerModel.target()); - if (!info) + if (!info) { return null; + } const uiSourceCode = info._project.uiSourceCodeForURL(script.sourceURL); - if (!uiSourceCode) + if (!uiSourceCode) { return null; + } const offset = script[Bindings.ResourceMapping._offsetSymbol] || TextUtils.TextRange.createFromLocation(script.lineOffset, script.columnOffset); const lineNumber = jsLocation.lineNumber + offset.startLine - script.lineOffset; let columnNumber = jsLocation.columnNumber; - if (jsLocation.lineNumber === script.lineOffset) + if (jsLocation.lineNumber === script.lineOffset) { columnNumber += offset.startColumn - script.columnOffset; + } return uiSourceCode.uiLocation(lineNumber, columnNumber); } @@ -98,17 +106,21 @@ * @return {!Array<!SDK.DebuggerModel.Location>} */ uiLocationToJSLocations(uiSourceCode, lineNumber, columnNumber) { - if (!uiSourceCode[Bindings.ResourceMapping._symbol]) + if (!uiSourceCode[Bindings.ResourceMapping._symbol]) { return []; + } const target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); - if (!target) + if (!target) { return []; + } const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return []; + } const location = debuggerModel.createRawLocationByURL(uiSourceCode.url(), lineNumber, columnNumber); - if (location && location.script().containsLocation(lineNumber, columnNumber)) + if (location && location.script().containsLocation(lineNumber, columnNumber)) { return [location]; + } return []; } @@ -117,14 +129,17 @@ * @return {!Array<!SDK.CSSLocation>} */ uiLocationToCSSLocations(uiLocation) { - if (!uiLocation.uiSourceCode[Bindings.ResourceMapping._symbol]) + if (!uiLocation.uiSourceCode[Bindings.ResourceMapping._symbol]) { return []; + } const target = Bindings.NetworkProject.targetForUISourceCode(uiLocation.uiSourceCode); - if (!target) + if (!target) { return []; + } const cssModel = target.model(SDK.CSSModel); - if (!cssModel) + if (!cssModel) { return []; + } return cssModel.createRawLocationsByURL( uiLocation.uiSourceCode.url(), uiLocation.lineNumber, uiLocation.columnNumber); } @@ -135,8 +150,9 @@ _resetForTest(target) { const resourceTreeModel = target.model(SDK.ResourceTreeModel); const info = resourceTreeModel ? this._modelToInfo.get(resourceTreeModel) : null; - if (info) + if (info) { info._resetForTest(); + } } }; @@ -169,11 +185,13 @@ */ _styleSheetChanged(event) { const header = this._cssModel.styleSheetHeaderForId(event.data.styleSheetId); - if (!header || !header.isInline) + if (!header || !header.isInline) { return; + } const binding = this._bindings.get(header.resourceURL()); - if (!binding) + if (!binding) { return; + } binding._styleSheetChanged(header, event.data.edit); } @@ -184,17 +202,21 @@ const resourceType = resource.resourceType(); // Only load selected resource types from resources. if (resourceType !== Common.resourceTypes.Image && resourceType !== Common.resourceTypes.Font && - resourceType !== Common.resourceTypes.Document && resourceType !== Common.resourceTypes.Manifest) + resourceType !== Common.resourceTypes.Document && resourceType !== Common.resourceTypes.Manifest) { return false; + } // Ignore non-images and non-fonts. - if (resourceType === Common.resourceTypes.Image && resource.mimeType && !resource.mimeType.startsWith('image')) + if (resourceType === Common.resourceTypes.Image && resource.mimeType && !resource.mimeType.startsWith('image')) { return false; - if (resourceType === Common.resourceTypes.Font && resource.mimeType && !resource.mimeType.includes('font')) + } + if (resourceType === Common.resourceTypes.Font && resource.mimeType && !resource.mimeType.includes('font')) { return false; + } if ((resourceType === Common.resourceTypes.Image || resourceType === Common.resourceTypes.Font) && - resource.contentURL().startsWith('data:')) + resource.contentURL().startsWith('data:')) { return false; + } return true; } @@ -203,8 +225,9 @@ */ _resourceAdded(event) { const resource = /** @type {!SDK.Resource} */ (event.data); - if (!this._acceptsResource(resource)) + if (!this._acceptsResource(resource)) { return; + } let binding = this._bindings.get(resource.url); if (!binding) { @@ -220,8 +243,9 @@ */ _removeFrameResources(frame) { for (const resource of frame.resources()) { - if (!this._acceptsResource(resource)) + if (!this._acceptsResource(resource)) { continue; + } const binding = this._bindings.get(resource.url); if (binding._resources.size === 1) { binding.dispose(); @@ -249,15 +273,17 @@ } _resetForTest() { - for (const binding of this._bindings.valuesArray()) + for (const binding of this._bindings.valuesArray()) { binding.dispose(); + } this._bindings.clear(); } dispose() { Common.EventTarget.removeEventListeners(this._eventListeners); - for (const binding of this._bindings.valuesArray()) + for (const binding of this._bindings.valuesArray()) { binding.dispose(); + } this._bindings.clear(); this._project.removeProject(); } @@ -293,8 +319,9 @@ if (cssModel) { for (const headerId of cssModel.styleSheetIdsForURL(this._uiSourceCode.url())) { const header = cssModel.styleSheetHeaderForId(headerId); - if (header) + if (header) { stylesheets.push(header); + } } } return stylesheets; @@ -306,8 +333,9 @@ _inlineScripts() { const target = Bindings.NetworkProject.targetForUISourceCode(this._uiSourceCode); const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return []; + } return debuggerModel.scriptsForSourceURL(this._uiSourceCode.url()); } @@ -317,12 +345,14 @@ */ async _styleSheetChanged(stylesheet, edit) { this._edits.push({stylesheet, edit}); - if (this._edits.length > 1) - return; // There is already a _styleSheetChanged loop running + if (this._edits.length > 1) { + return; + } // There is already a _styleSheetChanged loop running const content = await this._uiSourceCode.requestContent(); - if (content !== null) + if (content !== null) { this._innerStyleSheetChanged(content); + } this._edits = []; } @@ -345,16 +375,18 @@ for (const script of scripts) { const scriptOffset = script[Bindings.ResourceMapping._offsetSymbol] || TextUtils.TextRange.createFromLocation(script.lineOffset, script.columnOffset); - if (!scriptOffset.follows(oldRange)) + if (!scriptOffset.follows(oldRange)) { continue; + } script[Bindings.ResourceMapping._offsetSymbol] = scriptOffset.rebaseAfterTextEdit(oldRange, newRange); Bindings.debuggerWorkspaceBinding.updateLocations(script); } for (const style of styles) { const styleOffset = style[Bindings.ResourceMapping._offsetSymbol] || TextUtils.TextRange.createFromLocation(style.startLine, style.startColumn); - if (!styleOffset.follows(oldRange)) + if (!styleOffset.follows(oldRange)) { continue; + } style[Bindings.ResourceMapping._offsetSymbol] = styleOffset.rebaseAfterTextEdit(oldRange, newRange); Bindings.cssWorkspaceBinding.updateLocations(style); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/ResourceScriptMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/ResourceScriptMapping.js index 92bcbcf..a7c2d3f 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/ResourceScriptMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/ResourceScriptMapping.js
@@ -86,23 +86,29 @@ */ rawLocationToUILocation(rawLocation) { const script = rawLocation.script(); - if (!script) + if (!script) { return null; + } const project = this._project(script); const uiSourceCode = project.uiSourceCodeForURL(script.sourceURL); - if (!uiSourceCode) + if (!uiSourceCode) { return null; + } const scriptFile = this._uiSourceCodeToScriptFile.get(uiSourceCode); - if (!scriptFile) + if (!scriptFile) { return null; - if ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()) + } + if ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()) { return null; - if (!scriptFile._hasScripts([script])) + } + if (!scriptFile._hasScripts([script])) { return null; + } const lineNumber = rawLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0); let columnNumber = rawLocation.columnNumber || 0; - if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) + if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) { columnNumber -= script.columnOffset; + } return uiSourceCode.uiLocation(lineNumber, columnNumber); } @@ -115,8 +121,9 @@ */ uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) { const scriptFile = this._uiSourceCodeToScriptFile.get(uiSourceCode); - if (!scriptFile) + if (!scriptFile) { return []; + } const script = scriptFile._script; if (script.isInlineScriptWithSourceURL()) { return [this._debuggerModel.createRawLocation( @@ -130,13 +137,15 @@ * @return {boolean} */ _acceptsScript(script) { - if (!script.sourceURL || script.isLiveEdit() || (script.isInlineScript() && !script.hasSourceURL)) + if (!script.sourceURL || script.isLiveEdit() || (script.isInlineScript() && !script.hasSourceURL)) { return false; + } // Filter out embedder injected content scripts. if (script.isContentScript() && !script.hasSourceURL) { const parsedURL = new Common.ParsedURL(script.sourceURL); - if (!parsedURL.isValid) + if (!parsedURL.isValid) { return false; + } } return true; } @@ -146,8 +155,9 @@ */ _parsedScriptSource(event) { const script = /** @type {!SDK.Script} */ (event.data); - if (!this._acceptsScript(script)) + if (!this._acceptsScript(script)) { return; + } this._acceptedScripts.add(script); const originalContentProvider = script.originalContentProvider(); const frameId = Bindings.frameIdForScript(script); @@ -188,8 +198,9 @@ * @param {!SDK.Script} script */ _removeScript(script) { - if (!this._acceptedScripts.has(script)) + if (!this._acceptedScripts.has(script)) { return; + } this._acceptedScripts.delete(script); const project = this._project(script); const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (project.uiSourceCodeForURL(script.sourceURL)); @@ -206,8 +217,9 @@ _executionContextDestroyed(event) { const executionContext = /** @type {!SDK.ExecutionContext} */ (event.data); const scripts = this._debuggerModel.scriptsForExecutionContext(executionContext); - for (const script of scripts) + for (const script of scripts) { this._removeScript(script); + } } /** @@ -215,23 +227,27 @@ */ _globalObjectCleared(event) { const scripts = Array.from(this._acceptedScripts); - for (const script of scripts) + for (const script of scripts) { this._removeScript(script); + } } resetForTest() { const scripts = Array.from(this._acceptedScripts); - for (const script of scripts) + for (const script of scripts) { this._removeScript(script); + } } dispose() { Common.EventTarget.removeEventListeners(this._eventListeners); const scripts = Array.from(this._acceptedScripts); - for (const script of scripts) + for (const script of scripts) { this._removeScript(script); - for (const project of this._projects.values()) + } + for (const project of this._projects.values()) { project.removeProject(); + } this._projects.clear(); } }; @@ -252,8 +268,9 @@ this._resourceScriptMapping = resourceScriptMapping; this._uiSourceCode = uiSourceCode; - if (this._uiSourceCode.contentType().isScript()) + if (this._uiSourceCode.contentType().isScript()) { this._script = scripts[scripts.length - 1]; + } this._uiSourceCode.addEventListener( Workspace.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); @@ -273,19 +290,24 @@ * @return {boolean} */ _isDiverged() { - if (this._uiSourceCode.isDirty()) + if (this._uiSourceCode.isDirty()) { return true; - if (!this._script) + } + if (!this._script) { return false; - if (typeof this._scriptSource === 'undefined') + } + if (typeof this._scriptSource === 'undefined') { return false; + } const workingCopy = this._uiSourceCode.workingCopy(); - if (!workingCopy) + if (!workingCopy) { return false; + } // Match ignoring sourceURL. - if (!workingCopy.startsWith(this._scriptSource.trimRight())) + if (!workingCopy.startsWith(this._scriptSource.trimRight())) { return true; + } const suffix = this._uiSourceCode.workingCopy().substr(this._scriptSource.length); return !!suffix.length && !suffix.match(SDK.Script.sourceURLRegex); } @@ -301,10 +323,12 @@ * @param {!Common.Event} event */ _workingCopyCommitted(event) { - if (this._uiSourceCode.project().canSetFileContent()) + if (this._uiSourceCode.project().canSetFileContent()) { return; - if (!this._script) + } + if (!this._script) { return; + } const debuggerModel = this._resourceScriptMapping._debuggerModel; const breakpoints = Bindings.breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode) .map(breakpointLocation => breakpointLocation.breakpoint); @@ -317,8 +341,9 @@ * @this {Bindings.ResourceScriptFile} */ async function scriptSourceWasSet(error, exceptionDetails) { - if (!error && !exceptionDetails) + if (!error && !exceptionDetails) { this._scriptSource = source; + } this._update(); if (!error && !exceptionDetails) { @@ -339,10 +364,11 @@ } _update() { - if (this._isDiverged() && !this._hasDivergedFromVM) + if (this._isDiverged() && !this._hasDivergedFromVM) { this._divergeFromVM(); - else if (!this._isDiverged() && this._hasDivergedFromVM) + } else if (!this._isDiverged() && this._hasDivergedFromVM) { this._mergeToVM(); + } } _divergeFromVM() { @@ -414,8 +440,9 @@ * @param {string} sourceMapURL */ addSourceMapURL(sourceMapURL) { - if (!this._script) + if (!this._script) { return; + } this._script.debuggerModel.setSourceMapURL(this._script, sourceMapURL); }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/ResourceUtils.js b/third_party/blink/renderer/devtools/front_end/bindings/ResourceUtils.js index 917741b..85bda82 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/ResourceUtils.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/ResourceUtils.js
@@ -34,8 +34,9 @@ Bindings.resourceForURL = function(url) { for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { const resource = resourceTreeModel.resourceForURL(url); - if (resource) + if (resource) { return resource; + } } return null; }; @@ -44,8 +45,9 @@ * @param {function(!SDK.Resource)} callback */ Bindings.forAllResources = function(callback) { - for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) + for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { resourceTreeModel.forAllResources(callback); + } }; /** @@ -53,33 +55,39 @@ * @return {string} */ Bindings.displayNameForURL = function(url) { - if (!url) + if (!url) { return ''; + } const resource = Bindings.resourceForURL(url); - if (resource) + if (resource) { return resource.displayName; + } const uiSourceCode = Workspace.workspace.uiSourceCodeForURL(url); - if (uiSourceCode) + if (uiSourceCode) { return uiSourceCode.displayName(); + } const mainTarget = SDK.targetManager.mainTarget(); const inspectedURL = mainTarget && mainTarget.inspectedURL(); - if (!inspectedURL) + if (!inspectedURL) { return url.trimURL(''); + } const parsedURL = inspectedURL.asParsedURL(); const lastPathComponent = parsedURL ? parsedURL.lastPathComponent : parsedURL; const index = inspectedURL.indexOf(lastPathComponent); if (index !== -1 && index + lastPathComponent.length === inspectedURL.length) { const baseURL = inspectedURL.substring(0, index); - if (url.startsWith(baseURL)) + if (url.startsWith(baseURL)) { return url.substring(index); + } } - if (!parsedURL) + if (!parsedURL) { return url; + } const displayName = url.trimURL(parsedURL.host); return displayName === '/' ? parsedURL.host + '/' : displayName; @@ -93,11 +101,13 @@ */ Bindings.metadataForURL = function(target, frameId, url) { const resourceTreeModel = target.model(SDK.ResourceTreeModel); - if (!resourceTreeModel) + if (!resourceTreeModel) { return null; + } const frame = resourceTreeModel.frameForId(frameId); - if (!frame) + if (!frame) { return null; + } return Bindings.resourceMetadata(frame.resourceForURL(url)); }; @@ -106,8 +116,9 @@ * @return {?Workspace.UISourceCodeMetadata} */ Bindings.resourceMetadata = function(resource) { - if (!resource || (typeof resource.contentSize() !== 'number' && !resource.lastModified())) + if (!resource || (typeof resource.contentSize() !== 'number' && !resource.lastModified())) { return null; + } return new Workspace.UISourceCodeMetadata(resource.lastModified(), resource.contentSize()); }; @@ -117,11 +128,13 @@ */ Bindings.frameIdForScript = function(script) { const executionContext = script.executionContext(); - if (executionContext) + if (executionContext) { return executionContext.frameId || ''; + } // This is to overcome compilation cache which doesn't get reset. const resourceTreeModel = script.debuggerModel.target().model(SDK.ResourceTreeModel); - if (!resourceTreeModel || !resourceTreeModel.mainFrame) + if (!resourceTreeModel || !resourceTreeModel.mainFrame) { return ''; + } return resourceTreeModel.mainFrame.id; };
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/SASSSourceMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/SASSSourceMapping.js index c106236..2c28692 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/SASSSourceMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/SASSSourceMapping.js
@@ -120,8 +120,9 @@ const sassText = /** @type {string} */ (newSources.get(sourceURL)); uiSourceCode.setWorkingCopy(sassText); } - for (const header of headers) + for (const header of headers) { Bindings.cssWorkspaceBinding.updateLocations(header); + } } /** @@ -131,17 +132,21 @@ */ rawLocationToUILocation(rawLocation) { const header = rawLocation.header(); - if (!header) + if (!header) { return null; + } const sourceMap = this._sourceMapManager.sourceMapForClient(header); - if (!sourceMap) + if (!sourceMap) { return null; + } const entry = sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber); - if (!entry || !entry.sourceURL) + if (!entry || !entry.sourceURL) { return null; + } const uiSourceCode = this._project.uiSourceCodeForURL(entry.sourceURL); - if (!uiSourceCode) + if (!uiSourceCode) { return null; + } return uiSourceCode.uiLocation(entry.sourceLineNumber || 0, entry.sourceColumnNumber); } @@ -152,13 +157,15 @@ */ uiLocationToRawLocations(uiLocation) { const sourceMap = uiLocation.uiSourceCode[Bindings.SASSSourceMapping._sourceMapSymbol]; - if (!sourceMap) + if (!sourceMap) { return []; + } const entries = sourceMap.findReverseEntries(uiLocation.uiSourceCode.url(), uiLocation.lineNumber, uiLocation.columnNumber); const locations = []; - for (const header of this._sourceMapManager.clientsForSourceMap(sourceMap)) + for (const header of this._sourceMapManager.clientsForSourceMap(sourceMap)) { locations.pushAll(entries.map(entry => new SDK.CSSLocation(header, entry.lineNumber, entry.columnNumber))); + } return locations; }
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/StylesSourceMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/StylesSourceMapping.js index a6cca5be..e5a3267b 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/StylesSourceMapping.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/StylesSourceMapping.js
@@ -60,11 +60,13 @@ */ rawLocationToUILocation(rawLocation) { const header = rawLocation.header(); - if (!header || !this._acceptsHeader(header)) + if (!header || !this._acceptsHeader(header)) { return null; + } const styleFile = this._styleFiles.get(header.resourceURL()); - if (!styleFile) + if (!styleFile) { return null; + } let lineNumber = rawLocation.lineNumber; let columnNumber = rawLocation.columnNumber; if (header.isInline && header.hasSourceURL) { @@ -81,8 +83,9 @@ */ uiLocationToRawLocations(uiLocation) { const styleFile = uiLocation.uiSourceCode[Bindings.StyleFile._symbol]; - if (!styleFile) + if (!styleFile) { return []; + } const rawLocations = []; for (const header of styleFile._headers) { let lineNumber = uiLocation.lineNumber; @@ -100,10 +103,12 @@ * @param {!SDK.CSSStyleSheetHeader} header */ _acceptsHeader(header) { - if (header.isInline && !header.hasSourceURL && header.origin !== 'inspector') + if (header.isInline && !header.hasSourceURL && header.origin !== 'inspector') { return false; - if (!header.resourceURL()) + } + if (!header.resourceURL()) { return false; + } return true; } @@ -112,8 +117,9 @@ */ _styleSheetAdded(event) { const header = /** @type {!SDK.CSSStyleSheetHeader} */ (event.data); - if (!this._acceptsHeader(header)) + if (!this._acceptsHeader(header)) { return; + } const url = header.resourceURL(); let styleFile = this._styleFiles.get(url); @@ -130,8 +136,9 @@ */ _styleSheetRemoved(event) { const header = /** @type {!SDK.CSSStyleSheetHeader} */ (event.data); - if (!this._acceptsHeader(header)) + if (!this._acceptsHeader(header)) { return; + } const url = header.resourceURL(); const styleFile = this._styleFiles.get(url); if (styleFile._headers.size === 1) { @@ -147,15 +154,17 @@ */ _styleSheetChanged(event) { const header = this._cssModel.styleSheetHeaderForId(event.data.styleSheetId); - if (!header || !this._acceptsHeader(header)) + if (!header || !this._acceptsHeader(header)) { return; + } const styleFile = this._styleFiles.get(header.resourceURL()); styleFile._styleSheetChanged(header); } dispose() { - for (const styleFile of this._styleFiles.values()) + for (const styleFile of this._styleFiles.values()) { styleFile.dispose(); + } this._styleFiles.clear(); Common.EventTarget.removeEventListeners(this._eventListeners); this._project.removeProject(); @@ -219,8 +228,9 @@ */ _styleSheetChanged(header) { console.assert(this._headers.has(header)); - if (this._isUpdatingHeaders || !this._headers.has(header)) + if (this._isUpdatingHeaders || !this._headers.has(header)) { return; + } const mirrorContentBound = this._mirrorContent.bind(this, header, true /* majorChange */); this._throttler.schedule(mirrorContentBound, false /* asSoonAsPossible */); } @@ -229,8 +239,9 @@ * @param {!Common.Event} event */ _workingCopyCommitted(event) { - if (this._isAddingRevision) + if (this._isAddingRevision) { return; + } const mirrorContentBound = this._mirrorContent.bind(this, this._uiSourceCode, true /* majorChange */); this._throttler.schedule(mirrorContentBound, true /* asSoonAsPossible */); } @@ -239,8 +250,9 @@ * @param {!Common.Event} event */ _workingCopyChanged(event) { - if (this._isAddingRevision) + if (this._isAddingRevision) { return; + } const mirrorContentBound = this._mirrorContent.bind(this, this._uiSourceCode, false /* majorChange */); this._throttler.schedule(mirrorContentBound, false /* asSoonAsPossible */); } @@ -278,8 +290,9 @@ this._isUpdatingHeaders = true; const promises = []; for (const header of this._headers) { - if (header === fromProvider) + if (header === fromProvider) { continue; + } promises.push(this._cssModel.setStyleSheetText(header.id, newContent, majorChange)); } // ------ ASYNC ------ @@ -292,8 +305,9 @@ } dispose() { - if (this._terminated) + if (this._terminated) { return; + } this._terminated = true; this._project.removeFile(this._uiSourceCode.url()); Common.EventTarget.removeEventListeners(this._eventListeners);
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/TempFile.js b/third_party/blink/renderer/devtools/front_end/bindings/TempFile.js index f6cba35..c1374ec2 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings/TempFile.js +++ b/third_party/blink/renderer/devtools/front_end/bindings/TempFile.js
@@ -38,8 +38,9 @@ * @param {!Array<string|!Blob>} pieces */ write(pieces) { - if (this._lastBlob) + if (this._lastBlob) { pieces.unshift(this._lastBlob); + } this._lastBlob = new Blob(pieces, {type: 'text/plain'}); } @@ -126,8 +127,9 @@ this._strings.push(string); this._stringsLength += string.length; const flushStringLength = 10 * 1024 * 1024; - if (this._stringsLength > flushStringLength) + if (this._stringsLength > flushStringLength) { this._flush(); + } } /** @@ -144,10 +146,12 @@ } _flush() { - if (!this._strings.length) + if (!this._strings.length) { return; - if (!this._file) + } + if (!this._file) { this._file = new Bindings.TempFile(); + } this._stringsLength = 0; this._file.write(this._strings.splice(0)); } @@ -163,8 +167,9 @@ * @override */ reset() { - if (this._file) + if (this._file) { this._file.remove(); + } this._file = null; /** @type {!Array<string>} */ this._strings = [];
diff --git a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/AutomappingTestRunner.js b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/AutomappingTestRunner.js index 4a4ed69..ddc3518 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/AutomappingTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/AutomappingTestRunner.js
@@ -24,20 +24,23 @@ TestRunner.override(Bindings.ContentProviderBasedProject.prototype, 'requestMetadata', overrideTime, true); } - for (const url in urlToTime) + for (const url in urlToTime) { timeOverrides.set(url, urlToTime[url]); + } function overrideTime(uiSourceCode) { - if (!timeOverrides.has(uiSourceCode.url())) + if (!timeOverrides.has(uiSourceCode.url())) { return originalRequestMetadata.call(this, uiSourceCode); + } const override = timeOverrides.get(uiSourceCode.url()); return originalRequestMetadata.call(this, uiSourceCode).then(onOriginalMetadata.bind(null, override)); } function onOriginalMetadata(timeOverride, metadata) { - if (!timeOverride && !metadata) + if (!timeOverride && !metadata) { return null; + } return new Workspace.UISourceCodeMetadata(timeOverride, (metadata ? metadata.contentSize : null)); } @@ -48,8 +51,9 @@ this._networkProject = new Bindings.ContentProviderBasedProject( this._workspace, 'AUTOMAPPING', Workspace.projectTypes.Network, 'simple website'); - if (workspace !== Workspace.workspace) + if (workspace !== Workspace.workspace) { new Persistence.FileSystemWorkspaceBinding(Persistence.isolatedFileSystemManager, this._workspace); + } this._failedBindingsCount = 0; this._automapping = @@ -60,8 +64,9 @@ BindingsTestRunner.AutomappingTest.prototype = { removeResources: function(urls) { - for (const url of urls) + for (const url of urls) { this._networkProject.removeFile(url); + } }, addNetworkResources: function(assets) { @@ -105,8 +110,9 @@ }, _checkStabilized: function() { - if (!this._stabilizedCallback || this._automapping._sweepThrottler._process) + if (!this._stabilizedCallback || this._automapping._sweepThrottler._process) { return; + } const networkUISourceCodes = this._workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network); const stabilized = this._failedBindingsCount + this._automapping._statuses.size === networkUISourceCodes.length;
diff --git a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/BindingsTestRunner.js b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/BindingsTestRunner.js index 472853f..1bb4941 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/BindingsTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/BindingsTestRunner.js
@@ -8,8 +8,9 @@ */ BindingsTestRunner.cleanupURL = function(url) { - if (!url.startsWith('debugger://')) + if (!url.startsWith('debugger://')) { return url; + } return url.replace(/VM\d+/g, 'VM[XXX]'); }; @@ -31,8 +32,9 @@ let index = 0; for (const entry of diff) { - if (entry[0] === Diff.Diff.Operation.Delete) + if (entry[0] === Diff.Diff.Operation.Delete) { continue; + } if (entry[0] === Diff.Diff.Operation.Equal) { index += entry[1].length; @@ -40,8 +42,9 @@ } // eslint-disable-next-line no-unused-vars - for (const line of entry[1]) + for (const line of entry[1]) { isAdded[index++] = true; + } } const addedEntries = diff.filter(entry => entry[0] === Diff.Diff.Operation.Insert).map(entry => entry[1]); @@ -50,8 +53,9 @@ TestRunner.addResult(`Removed: ${removedLines.length} uiSourceCodes`); - for (const url of removedLines) + for (const url of removedLines) { TestRunner.addResult('[-] ' + url); + } TestRunner.addResult(`Workspace: ${urls.length} uiSourceCodes.`); @@ -67,8 +71,9 @@ BindingsTestRunner.attachFrame = function(frameId, url, evalSourceURL) { let evalSource = `(${attachFrame.toString()})('${frameId}', '${url}')`; - if (evalSourceURL) + if (evalSourceURL) { evalSource += '//# sourceURL=' + evalSourceURL; + } return TestRunner.evaluateInPageAsync(evalSource); @@ -84,8 +89,9 @@ BindingsTestRunner.detachFrame = function(frameId, evalSourceURL) { let evalSource = `(${detachFrame.toString()})('${frameId}')`; - if (evalSourceURL) + if (evalSourceURL) { evalSource += '//# sourceURL=' + evalSourceURL; + } return TestRunner.evaluateInPageAnonymously(evalSource); @@ -98,8 +104,9 @@ BindingsTestRunner.navigateFrame = function(frameId, navigateURL, evalSourceURL) { let evalSource = `(${navigateFrame.toString()})('${frameId}', '${navigateURL}')`; - if (evalSourceURL) + if (evalSourceURL) { evalSource += '//# sourceURL=' + evalSourceURL; + } return TestRunner.evaluateInPageAsync(evalSource); @@ -113,8 +120,9 @@ BindingsTestRunner.attachShadowDOM = function(id, templateSelector, evalSourceURL) { let evalSource = `(${createShadowDOM.toString()})('${id}', '${templateSelector}')`; - if (evalSourceURL) + if (evalSourceURL) { evalSource += '//# sourceURL=' + evalSourceURL; + } return TestRunner.evaluateInPageAnonymously(evalSource); @@ -134,8 +142,9 @@ BindingsTestRunner.detachShadowDOM = function(id, evalSourceURL) { let evalSource = `(${removeShadowDOM.toString()})('${id}')`; - if (evalSourceURL) + if (evalSourceURL) { evalSource += '//# sourceURL=' + evalSourceURL; + } return TestRunner.evaluateInPageAnonymously(evalSource); @@ -153,8 +162,9 @@ function onStyleSheetRemoved(event) { const styleSheetHeader = event.data; - if (!styleSheetHeader.resourceURL().endsWith(urlSuffix)) + if (!styleSheetHeader.resourceURL().endsWith(urlSuffix)) { return; + } TestRunner.cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved, onStyleSheetRemoved); fulfill();
diff --git a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js index 6910f2a..949e485 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js
@@ -29,8 +29,9 @@ result.push(indent + node.name); const newIndent = indent + ' '; - for (const child of node._children) + for (const child of node._children) { dfs(child, newIndent); + } } }, @@ -52,8 +53,9 @@ function created(event) { const fileSystem = event.data; - if (fileSystem.path() !== fileSystemPath) + if (fileSystem.path() !== fileSystemPath) { return; + } Persistence.isolatedFileSystemManager.removeEventListener( Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, created); @@ -76,16 +78,18 @@ for (const folder of folders) { let dir = node._childrenMap[folder]; - if (!dir) + if (!dir) { dir = node.mkdir(folder); + } node = dir; } const file = node.addFile(fileName, content); - if (lastModified) + if (lastModified) { file._timestamp = lastModified; + } return file; } @@ -191,8 +195,9 @@ const name = tokens.pop(); let parentEntry = this; - for (const token of tokens) + for (const token of tokens) { parentEntry = parentEntry._childrenMap[token]; + } let entry = parentEntry._childrenMap[name]; @@ -201,15 +206,17 @@ return; } - if (!entry) + if (!entry) { entry = parentEntry.addFile(name, ''); + } callback(entry); }, getEntry: function(path, options, callback, errorCallback) { - if (path.startsWith('/')) + if (path.startsWith('/')) { path = path.substring(1); + } if (options && options.create) { this._createEntry(path, options, callback, errorCallback); @@ -225,8 +232,9 @@ for (const token of path.split('/')) { entry = entry._childrenMap[token]; - if (!entry) + if (!entry) { break; + } } (entry ? callback(entry) : errorCallback(new DOMException('Path not found: ' + path, 'NotFoundError'))); @@ -273,15 +281,17 @@ this._entry._timestamp += this._modificationTimesDelta; this._entry.content = blob; - if (this.onwriteend) + if (this.onwriteend) { this.onwriteend(); + } }, truncate: function(num) { this._entry._timestamp += this._modificationTimesDelta; this._entry.content = this._entry.content.slice(0, num); - if (this.onwriteend) + if (this.onwriteend) { this.onwriteend(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js index b142dd67..505e014 100644 --- a/third_party/blink/renderer/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/bindings_test_runner/PersistenceTestRunner.js
@@ -29,11 +29,13 @@ for (const uiSourceCode of uiSourceCodes) { const binding = Persistence.persistence.binding(uiSourceCode); - if (!binding) + if (!binding) { continue; + } - if (uiSourceCode.name() === fileName) + if (uiSourceCode.name() === fileName) { return Promise.resolve(binding); + } } return TestRunner.waitForEvent( @@ -75,8 +77,9 @@ _findBinding(urlSuffix) { for (const binding of this._bindings) { - if (binding.network.url().endsWith(urlSuffix)) + if (binding.network.url().endsWith(urlSuffix)) { return binding; + } } return null; @@ -96,8 +99,9 @@ } dispose() { - for (const binding of this._bindings) + for (const binding of this._bindings) { this._persistence.removeBindingForTest(binding); + } this._bindings.clear(); }
diff --git a/third_party/blink/renderer/devtools/front_end/browser_debugger/DOMBreakpointsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/browser_debugger/DOMBreakpointsSidebarPane.js index 7427a35..7689b54 100644 --- a/third_party/blink/renderer/devtools/front_end/browser_debugger/DOMBreakpointsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/browser_debugger/DOMBreakpointsSidebarPane.js
@@ -51,8 +51,9 @@ for (const domDebuggerModel of SDK.targetManager.models(SDK.DOMDebuggerModel)) { domDebuggerModel.retrieveDOMBreakpoints(); - for (const breakpoint of domDebuggerModel.domBreakpoints()) + for (const breakpoint of domDebuggerModel.domBreakpoints()) { this._addBreakpoint(breakpoint); + } } this._highlightedElement = null; @@ -72,8 +73,9 @@ _breakpointToggled(event) { const breakpoint = /** @type {!SDK.DOMDebuggerModel.DOMBreakpoint} */ (event.data); const item = this._items.get(breakpoint); - if (item) + if (item) { item.checkbox.checked = breakpoint.enabled; + } } /** @@ -127,8 +129,9 @@ let currentElement = this._listElement.firstChild; while (currentElement) { - if (currentElement._item && currentElement._item.breakpoint.type < breakpoint.type) + if (currentElement._item && currentElement._item.breakpoint.type < breakpoint.type) { break; + } currentElement = currentElement.nextSibling; } this._listElement.insertBefore(element, currentElement); @@ -156,8 +159,9 @@ */ _checkboxClicked(breakpoint) { const item = this._items.get(breakpoint); - if (!item) + if (!item) { return; + } breakpoint.domDebuggerModel.toggleDOMBreakpoint(breakpoint, item.checkbox.checked); } @@ -179,19 +183,23 @@ return; } const domDebuggerModel = details.debuggerModel.target().model(SDK.DOMDebuggerModel); - if (!domDebuggerModel) + if (!domDebuggerModel) { return; + } const data = domDebuggerModel.resolveDOMBreakpointData(/** @type {!Object} */ (details.auxData)); - if (!data) + if (!data) { return; + } let element = null; for (const item of this._items.values()) { - if (item.breakpoint.node === data.node && item.breakpoint.type === data.type) + if (item.breakpoint.node === data.node && item.breakpoint.type === data.type) { element = item.element; + } } - if (!element) + if (!element) { return; + } UI.viewManager.showView('sources.domBreakpoints'); element.classList.add('breakpoint-hit'); this._highlightedElement = element; @@ -219,20 +227,23 @@ */ appendApplicableItems(event, contextMenu, object) { const node = /** @type {!SDK.DOMNode} */ (object); - if (node.pseudoType()) + if (node.pseudoType()) { return; + } const domDebuggerModel = node.domModel().target().model(SDK.DOMDebuggerModel); - if (!domDebuggerModel) + if (!domDebuggerModel) { return; + } /** * @param {!SDK.DOMDebuggerModel.DOMBreakpoint.Type} type */ function toggleBreakpoint(type) { - if (domDebuggerModel.hasDOMBreakpoint(node, type)) + if (domDebuggerModel.hasDOMBreakpoint(node, type)) { domDebuggerModel.removeDOMBreakpoint(node, type); - else + } else { domDebuggerModel.setDOMBreakpoint(node, type); + } } const breakpointsMenu = contextMenu.debugSection().appendSubMenuItem(Common.UIString('Break on'));
diff --git a/third_party/blink/renderer/devtools/front_end/browser_debugger/EventListenerBreakpointsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/browser_debugger/EventListenerBreakpointsSidebarPane.js index a72ac4ec..f68a3e54 100644 --- a/third_party/blink/renderer/devtools/front_end/browser_debugger/EventListenerBreakpointsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/browser_debugger/EventListenerBreakpointsSidebarPane.js
@@ -17,14 +17,16 @@ const categories = SDK.domDebuggerManager.eventListenerBreakpoints().map(breakpoint => breakpoint.category()); categories.sort(); for (const category of categories) { - if (!this._categories.has(category)) + if (!this._categories.has(category)) { this._createCategory(category); + } } /** @type {!Map<!SDK.DOMDebuggerModel.EventListenerBreakpoint, !BrowserDebugger.EventListenerBreakpointsSidebarPane.Item>} */ this._breakpoints = new Map(); - for (const breakpoint of SDK.domDebuggerManager.eventListenerBreakpoints()) + for (const breakpoint of SDK.domDebuggerManager.eventListenerBreakpoints()) { this._createBreakpoint(breakpoint); + } SDK.targetManager.addModelListener(SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._update, this); SDK.targetManager.addModelListener(SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerResumed, this._update, this); @@ -75,8 +77,9 @@ } const breakpoint = SDK.domDebuggerManager.resolveEventListenerBreakpoint(/** @type {!Object} */ (details.auxData)); - if (!breakpoint) + if (!breakpoint) { return; + } UI.viewManager.showView('sources.eventListenerBreakpoints'); this._categories.get(breakpoint.category()).element.expand(); @@ -109,10 +112,11 @@ let hasDisabled = false; for (const other of this._breakpoints.keys()) { if (other.category() === breakpoint.category()) { - if (other.enabled()) + if (other.enabled()) { hasEnabled = true; - else + } else { hasDisabled = true; + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/browser_debugger/XHRBreakpointsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/browser_debugger/XHRBreakpointsSidebarPane.js index 2fd60a9..dd54216 100644 --- a/third_party/blink/renderer/devtools/front_end/browser_debugger/XHRBreakpointsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/browser_debugger/XHRBreakpointsSidebarPane.js
@@ -92,8 +92,9 @@ let currentElement = /** @type {?Element} */ (this._listElement.firstChild); while (currentElement) { - if (currentElement._url && currentElement._url < element._url) + if (currentElement._url && currentElement._url < element._url) { break; + } currentElement = /** @type {?Element} */ (currentElement.nextSibling); } this._addListElement(element, currentElement); @@ -105,8 +106,9 @@ */ _removeBreakpoint(url) { const element = this._breakpointElements.get(url); - if (!element) + if (!element) { return; + } this._removeListElement(element); this._breakpointElements.delete(url); @@ -214,8 +216,9 @@ } const url = details.auxData['breakpointURL']; const element = this._breakpointElements.get(url); - if (!element) + if (!element) { return; + } UI.viewManager.showView('sources.xhrBreakpoints'); element.classList.add('breakpoint-hit'); this._highlightedElement = element; @@ -223,7 +226,8 @@ _restoreBreakpoints() { const breakpoints = SDK.domDebuggerManager.xhrBreakpoints(); - for (const url of breakpoints.keys()) + for (const url of breakpoints.keys()) { this._setBreakpoint(url, breakpoints.get(url)); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/browser_sdk/LogManager.js b/third_party/blink/renderer/devtools/front_end/browser_sdk/LogManager.js index faf4032..592799f 100644 --- a/third_party/blink/renderer/devtools/front_end/browser_sdk/LogManager.js +++ b/third_party/blink/renderer/devtools/front_end/browser_sdk/LogManager.js
@@ -40,8 +40,9 @@ data.entry.lineNumber, undefined, [data.entry.text, ...(data.entry.args || [])], data.entry.stackTrace, data.entry.timestamp, undefined, undefined, data.entry.workerId); - if (data.entry.networkRequestId) + if (data.entry.networkRequestId) { SDK.networkLog.associateConsoleMessageWithRequest(consoleMessage, data.entry.networkRequestId); + } if (consoleMessage.source === SDK.ConsoleMessage.MessageSource.Worker) { const workerId = consoleMessage.workerId || ''; @@ -49,11 +50,13 @@ // user can see messages from the worker which has been already destroyed. // When opening DevTools, give us some time to connect to the worker and // not report the message twice if the worker is still alive. - if (SDK.targetManager.targetById(workerId)) + if (SDK.targetManager.targetById(workerId)) { return; + } setTimeout(() => { - if (!SDK.targetManager.targetById(workerId)) + if (!SDK.targetManager.targetById(workerId)) { SDK.consoleModel.addMessage(consoleMessage); + } }, 1000); } else { SDK.consoleModel.addMessage(consoleMessage);
diff --git a/third_party/blink/renderer/devtools/front_end/changes/ChangesHighlighter.js b/third_party/blink/renderer/devtools/front_end/changes/ChangesHighlighter.js index 01f9c24..ff05308 100644 --- a/third_party/blink/renderer/devtools/front_end/changes/ChangesHighlighter.js +++ b/third_party/blink/renderer/devtools/front_end/changes/ChangesHighlighter.js
@@ -44,8 +44,9 @@ let lineNumber = from; while (lineNumber < to && lineNumber < lines.length) { const stream = new CodeMirror.StringStream(lines[lineNumber]); - if (stream.eol() && syntaxHighlightMode.blankLine) + if (stream.eol() && syntaxHighlightMode.blankLine) { syntaxHighlightMode.blankLine(syntaxState); + } while (!stream.eol()) { syntaxHighlightMode.token(stream, syntaxState); stream.start = stream.pos; @@ -86,8 +87,9 @@ } fastForward(state, diffRow.baselineLineNumber - 1, diffRow.currentLineNumber - 1); let classes = ''; - if (stream.pos === 0) + if (stream.pos === 0) { classes += ' line-background-' + diffRow.type + ' line-' + diffRow.type; + } const syntaxHighlighterNeedsRefresh = state.diffPosition >= state.syntaxPosition; if (state.diffPosition <= state.syntaxPosition) { @@ -114,10 +116,11 @@ if (stream.eol()) { state.rowNumber++; - if (diffRow.type === Changes.ChangesView.RowType.Deletion) + if (diffRow.type === Changes.ChangesView.RowType.Deletion) { state.baselineLineNumber++; - else + } else { state.currentLineNumber++; + } state.diffPosition = 0; state.syntaxPosition = 0; state.diffTokenIndex = 0; @@ -135,8 +138,9 @@ state.syntaxPosition = 0; state.diffPosition = 0; state.diffTokenIndex = 0; - if (!diffRow) + if (!diffRow) { return ''; + } let style = ''; if (syntaxHighlightMode.blankLine) {
diff --git a/third_party/blink/renderer/devtools/front_end/changes/ChangesSidebar.js b/third_party/blink/renderer/devtools/front_end/changes/ChangesSidebar.js index e1788df..20c1423 100644 --- a/third_party/blink/renderer/devtools/front_end/changes/ChangesSidebar.js +++ b/third_party/blink/renderer/devtools/front_end/changes/ChangesSidebar.js
@@ -29,8 +29,9 @@ */ selectUISourceCode(uiSourceCode, omitFocus) { const treeElement = this._treeElements.get(uiSourceCode); - if (!treeElement) + if (!treeElement) { return; + } treeElement.select(omitFocus); } @@ -49,10 +50,11 @@ * @param {!Common.Event} event */ _uiSourceCodeMofiedStatusChanged(event) { - if (event.data.isModified) + if (event.data.isModified) { this._addUISourceCode(event.data.uiSourceCode); - else + } else { this._removeUISourceCode(event.data.uiSourceCode); + } } /** @@ -81,8 +83,9 @@ const treeElement = new Changes.ChangesSidebar.UISourceCodeTreeElement(uiSourceCode); this._treeElements.set(uiSourceCode, treeElement); this._treeoutline.appendChild(treeElement); - if (!this._treeoutline.selectedTreeElement) + if (!this._treeoutline.selectedTreeElement) { treeElement.select(true); + } } }; @@ -103,8 +106,9 @@ this.listItemElement.classList.add('navigator-' + uiSourceCode.contentType().name() + '-tree-item'); let iconType = 'largeicon-navigator-file'; - if (Snippets.isSnippetsUISourceCode(this.uiSourceCode)) + if (Snippets.isSnippetsUISourceCode(this.uiSourceCode)) { iconType = 'largeicon-navigator-snippet'; + } const defaultIcon = UI.Icon.create(iconType, 'icon'); this.setLeadingIcons([defaultIcon]); @@ -119,13 +123,15 @@ _updateTitle() { let titleText = this.uiSourceCode.displayName(); - if (this.uiSourceCode.isDirty()) + if (this.uiSourceCode.isDirty()) { titleText = '*' + titleText; + } this.title = titleText; let tooltip = this.uiSourceCode.url(); - if (this.uiSourceCode.contentType().isFromSourceMap()) + if (this.uiSourceCode.contentType().isFromSourceMap()) { tooltip = Common.UIString('%s (from source map)', this.uiSourceCode.displayName()); + } this.tooltip = tooltip; }
diff --git a/third_party/blink/renderer/devtools/front_end/changes/ChangesView.js b/third_party/blink/renderer/devtools/front_end/changes/ChangesView.js index ddddec1..aa48a2d5 100644 --- a/third_party/blink/renderer/devtools/front_end/changes/ChangesView.js +++ b/third_party/blink/renderer/devtools/front_end/changes/ChangesView.js
@@ -57,8 +57,9 @@ _revert() { const uiSourceCode = this._selectedUISourceCode; - if (!uiSourceCode) + if (!uiSourceCode) { return; + } this._workspaceDiff.revertToOriginal(uiSourceCode); } @@ -67,8 +68,9 @@ */ _click(event) { const selection = this._editor.selection(); - if (!selection.isEmpty()) + if (!selection.isEmpty()) { return; + } const row = this._diffRows[selection.startLine]; Common.Revealer.reveal( this._selectedUISourceCode.uiLocation(row.currentLineNumber - 1, selection.startColumn), false); @@ -79,13 +81,16 @@ * @param {?Workspace.UISourceCode} uiSourceCode */ _revealUISourceCode(uiSourceCode) { - if (this._selectedUISourceCode === uiSourceCode) + if (this._selectedUISourceCode === uiSourceCode) { return; + } - if (this._selectedUISourceCode) + if (this._selectedUISourceCode) { this._workspaceDiff.unsubscribeFromDiffChange(this._selectedUISourceCode, this._refreshDiff, this); - if (uiSourceCode && this.isShowing()) + } + if (uiSourceCode && this.isShowing()) { this._workspaceDiff.subscribeToDiffChange(uiSourceCode, this._refreshDiff, this); + } this._selectedUISourceCode = uiSourceCode; this._refreshDiff(); @@ -99,8 +104,9 @@ } _refreshDiff() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } if (!this._selectedUISourceCode) { this._renderDiffRows(null); @@ -112,8 +118,9 @@ return; } this._workspaceDiff.requestDiff(uiSourceCode).then(diff => { - if (this._selectedUISourceCode !== uiSourceCode) + if (this._selectedUISourceCode !== uiSourceCode) { return; + } this._renderDiffRows(diff); }); } @@ -157,8 +164,9 @@ currentLines.pushAll(token[1]); break; case Diff.Diff.Operation.Insert: - for (const line of token[1]) + for (const line of token[1]) { this._diffRows.push(createRow(line, Changes.ChangesView.RowType.Addition)); + } insertions += token[1].length; currentLines.pushAll(token[1]); break; @@ -171,8 +179,9 @@ insertions += diff[i][1].length; currentLines.pushAll(diff[i][1]); } else { - for (const line of token[1]) + for (const line of token[1]) { this._diffRows.push(createRow(line, Changes.ChangesView.RowType.Deletion)); + } } break; } @@ -181,16 +190,18 @@ this._maxLineDigits = Math.ceil(Math.log10(Math.max(currentLineNumber, baselineLineNumber))); let insertionText = ''; - if (insertions === 1) + if (insertions === 1) { insertionText = ls`${insertions} insertion (+),`; - else + } else { insertionText = ls`${insertions} insertions (+),`; + } let deletionText = ''; - if (deletions === 1) + if (deletions === 1) { deletionText = ls`${deletions} deletion (-)`; - else + } else { deletionText = ls`${deletions} deletions (-)`; + } this._diffStats.setText(`${insertionText} ${deletionText}`); this._toolbar.setEnabled(true); @@ -218,8 +229,9 @@ function createEqualRows(lines, atStart, atEnd) { const equalRows = []; if (!atStart) { - for (let i = 0; i < paddingLines && i < lines.length; i++) + for (let i = 0; i < paddingLines && i < lines.length; i++) { equalRows.push(createRow(lines[i], Changes.ChangesView.RowType.Equal)); + } if (lines.length > paddingLines * 2 + 1 && !atEnd) { equalRows.push(createRow( Common.UIString('( \u2026 Skipping %d matching lines \u2026 )', lines.length - paddingLines * 2), @@ -229,15 +241,17 @@ if (!atEnd) { const start = Math.max(lines.length - paddingLines - 1, atStart ? 0 : paddingLines); let skip = lines.length - paddingLines - 1; - if (!atStart) + if (!atStart) { skip -= paddingLines; + } if (skip > 0) { baselineLineNumber += skip; currentLineNumber += skip; } - for (let i = start; i < lines.length; i++) + for (let i = start; i < lines.length; i++) { equalRows.push(createRow(lines[i], Changes.ChangesView.RowType.Equal)); + } } return equalRows; } @@ -258,16 +272,21 @@ const className = type === Diff.Diff.Operation.Equal ? '' : 'inner-diff'; const lines = text.split('\n'); for (let i = 0; i < lines.length; i++) { - if (i > 0 && type !== Diff.Diff.Operation.Insert) + if (i > 0 && type !== Diff.Diff.Operation.Insert) { deletionRows.push(createRow('', Changes.ChangesView.RowType.Deletion)); - if (i > 0 && type !== Diff.Diff.Operation.Delete) + } + if (i > 0 && type !== Diff.Diff.Operation.Delete) { insertionRows.push(createRow('', Changes.ChangesView.RowType.Addition)); - if (!lines[i]) + } + if (!lines[i]) { continue; - if (type !== Diff.Diff.Operation.Insert) + } + if (type !== Diff.Diff.Operation.Insert) { deletionRows[deletionRows.length - 1].tokens.push({text: lines[i], className}); - if (type !== Diff.Diff.Operation.Delete) + } + if (type !== Diff.Diff.Operation.Delete) { insertionRows[insertionRows.length - 1].tokens.push({text: lines[i], className}); + } } } return deletionRows.concat(insertionRows); @@ -279,10 +298,12 @@ * @return {!Changes.ChangesView.Row} */ function createRow(text, type) { - if (type === Changes.ChangesView.RowType.Addition) + if (type === Changes.ChangesView.RowType.Addition) { currentLineNumber++; - if (type === Changes.ChangesView.RowType.Deletion) + } + if (type === Changes.ChangesView.RowType.Deletion) { baselineLineNumber++; + } if (type === Changes.ChangesView.RowType.Equal) { baselineLineNumber++; currentLineNumber++; @@ -341,8 +362,9 @@ * @return {!Promise} */ async reveal(diffUILocation, omitFocus) { - if (!(diffUILocation instanceof WorkspaceDiff.DiffUILocation)) + if (!(diffUILocation instanceof WorkspaceDiff.DiffUILocation)) { throw new Error('Internal error: not a diff ui location'); + } /** @type {!Changes.ChangesView} */ const changesView = self.runtime.sharedInstance(Changes.ChangesView); await UI.viewManager.showView('changes.changes');
diff --git a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastDetails.js b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastDetails.js index 5cd8415..0590988 100644 --- a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastDetails.js +++ b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastDetails.js
@@ -124,10 +124,11 @@ const labelAA = this._contrastPassFailAA.createChild('span', 'contrast-link-label'); labelAA.textContent = Common.UIString('AA'); this._contrastPassFailAA.createChild('span').textContent = Common.UIString(': %s', aa.toFixed(1)); - if (this._passesAA) + if (this._passesAA) { this._contrastPassFailAA.appendChild(UI.Icon.create('smallicon-checkmark-square')); - else + } else { this._contrastPassFailAA.appendChild(UI.Icon.create('smallicon-no')); + } const aaa = this._contrastInfo.contrastRatioThreshold('aaa'); const passesAAA = this._contrastInfo.contrastRatio() >= aaa; @@ -135,10 +136,11 @@ const labelAAA = this._contrastPassFailAAA.createChild('span', 'contrast-link-label'); labelAAA.textContent = Common.UIString('AAA'); this._contrastPassFailAAA.createChild('span').textContent = Common.UIString(': %s', aaa.toFixed(1)); - if (passesAAA) + if (passesAAA) { this._contrastPassFailAAA.appendChild(UI.Icon.create('smallicon-checkmark-square')); - else + } else { this._contrastPassFailAAA.appendChild(UI.Icon.create('smallicon-no')); + } [labelAA, labelAAA].forEach(e => e.addEventListener('click', event => ColorPicker.ContrastDetails._showHelp())); @@ -199,8 +201,9 @@ this._toggleMainColorPicker(false); this._expandButton.setGlyph('smallicon-expand-less'); this._expandButton.setTitle(Common.UIString('Show less')); - if (this._contrastUnknown) + if (this._contrastUnknown) { this._toggleBackgroundColorPicker(true); + } } else { this._toggleBackgroundColorPicker(false); this._expandButton.setGlyph('smallicon-expand-more'); @@ -242,12 +245,14 @@ * @param {boolean=} shouldTriggerEvent */ _toggleBackgroundColorPicker(enabled, shouldTriggerEvent = true) { - if (enabled === undefined) + if (enabled === undefined) { enabled = !this._bgColorPickerButton.toggled(); + } this._bgColorPickerButton.setToggled(enabled); - if (shouldTriggerEvent) + if (shouldTriggerEvent) { this.dispatchEventToListeners(ColorPicker.ContrastDetails.Events.BackgroundColorPickerWillBeToggled, enabled); + } InspectorFrontendHost.setEyeDropperActive(enabled); if (enabled) {
diff --git a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastInfo.js b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastInfo.js index 2455768..864766d 100644 --- a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastInfo.js +++ b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastInfo.js
@@ -18,12 +18,14 @@ /** @type {?Common.Color} */ this._bgColor = null; - if (!contrastInfo) + if (!contrastInfo) { return; + } if (!contrastInfo.computedFontSize || !contrastInfo.computedFontWeight || !contrastInfo.backgroundColors || - contrastInfo.backgroundColors.length !== 1) + contrastInfo.backgroundColors.length !== 1) { return; + } this._isNull = false; const isLargeFont = @@ -33,8 +35,9 @@ ColorPicker.ContrastInfo._ContrastThresholds[(isLargeFont ? 'largeFont' : 'normalFont')]; const bgColorText = contrastInfo.backgroundColors[0]; const bgColor = Common.Color.parse(bgColorText); - if (bgColor) + if (bgColor) { this._setBgColorInternal(bgColor); + } } /** @@ -81,8 +84,9 @@ _setBgColorInternal(bgColor) { this._bgColor = bgColor; - if (!this._fgColor) + if (!this._fgColor) { return; + } const fgRGBA = this._fgColor.rgba(); @@ -106,8 +110,9 @@ } _updateContrastRatio() { - if (!this._bgColor || !this._fgColor) + if (!this._bgColor || !this._fgColor) { return; + } this._contrastRatio = Common.Color.calculateContrastRatio(this._fgColor.rgba(), this._bgColor.rgba()); } @@ -116,8 +121,9 @@ * @return {?number} */ contrastRatioThreshold(level) { - if (!this._contrastRatioThresholds) + if (!this._contrastRatioThresholds) { return null; + } return this._contrastRatioThresholds[level]; } @@ -133,10 +139,11 @@ const isBold = (boldWeights.indexOf(fontWeight) !== -1); const fontSizePt = fontSizePx * 72 / 96; - if (isBold) + if (isBold) { return fontSizePt >= 14; - else + } else { return fontSizePt >= 18; + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastOverlay.js b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastOverlay.js index 2ea2863..fe70cf7 100644 --- a/third_party/blink/renderer/devtools/front_end/color_picker/ContrastOverlay.js +++ b/third_party/blink/renderer/devtools/front_end/color_picker/ContrastOverlay.js
@@ -31,8 +31,9 @@ } _update() { - if (!this._visible || this._contrastInfo.isNull() || !this._contrastInfo.contrastRatio()) + if (!this._visible || this._contrastInfo.isNull() || !this._contrastInfo.contrastRatio()) { return; + } this._contrastRatioLinesThrottler.schedule(this._drawContrastRatioLinesBound); } @@ -59,10 +60,11 @@ async _drawContrastRatioLines() { for (const level in this._contrastRatioLines) { const path = this._contrastRatioLineBuilder.drawContrastRatioLine(this._width, this._height, level); - if (path) + if (path) { this._contrastRatioLines[level].setAttribute('d', path); - else + } else { this._contrastRatioLines[level].removeAttribute('d'); + } } } }; @@ -84,8 +86,9 @@ */ drawContrastRatioLine(width, height, level) { const requiredContrast = this._contrastInfo.contrastRatioThreshold(level); - if (!width || !height || !requiredContrast) + if (!width || !height || !requiredContrast) { return null; + } const dS = 0.02; const epsilon = 0.0002; @@ -96,8 +99,9 @@ const color = this._contrastInfo.color(); const bgColor = this._contrastInfo.bgColor(); - if (!color || !bgColor) + if (!color || !bgColor) { return null; + } const fgRGBA = color.rgba(); const fgHSVA = color.hsva(); @@ -142,8 +146,9 @@ let previousSign = Math.sign(dLuminance); for (let guard = 100; guard; guard--) { - if (Math.abs(dLuminance) < epsilon) + if (Math.abs(dLuminance) < epsilon) { return x; + } const sign = Math.sign(dLuminance); if (sign !== previousSign) { @@ -180,8 +185,9 @@ candidateHSVA[V] = lastV + currentSlope * dS; const v = approach(V); - if (v === null) + if (v === null) { break; + } // Approximate the current gradient of the curve. currentSlope = s === 0 ? 0 : (v - lastV) / dS; @@ -198,11 +204,13 @@ s -= dS; candidateHSVA[V] = 1; s = approach(S); - if (s !== null) + if (s !== null) { pathBuilder = pathBuilder.concat(['L', (s * width).toFixed(2), '-0.1']); + } } - if (pathBuilder.length === 0) + if (pathBuilder.length === 0) { return null; + } return pathBuilder.join(' '); } };
diff --git a/third_party/blink/renderer/devtools/front_end/color_picker/Spectrum.js b/third_party/blink/renderer/devtools/front_end/color_picker/Spectrum.js index 65b86456..0e82aae 100644 --- a/third_party/blink/renderer/devtools/front_end/color_picker/Spectrum.js +++ b/third_party/blink/renderer/devtools/front_end/color_picker/Spectrum.js
@@ -168,10 +168,11 @@ this._loadPalettes(); new ColorPicker.Spectrum.PaletteGenerator(palette => { - if (palette.colors.length) + if (palette.colors.length) { this.addPalette(palette); - else if (this._selectedColorPalette.get() === palette.title) + } else if (this._selectedColorPalette.get() === palette.title) { this._paletteSelected(ColorPicker.Spectrum.MaterialPalette); + } }); /** @@ -222,8 +223,9 @@ } _contrastDetailsBackgroundColorPickedToggled({data: enabled}) { - if (enabled) + if (enabled) { this._toggleColorPicker(false); + } } _contrastPanelExpanded() { @@ -239,18 +241,21 @@ const closeButton = new UI.ToolbarButton('Return to color picker', 'largeicon-delete'); closeButton.addEventListener(UI.ToolbarButton.Events.Click, this._togglePalettePanel.bind(this, false)); toolbar.appendToolbarItem(closeButton); - for (const palette of this._palettes.values()) + for (const palette of this._palettes.values()) { this._palettePanel.appendChild(this._createPreviewPaletteElement(palette)); + } } /** * @param {boolean} show */ _togglePalettePanel(show) { - if (this._palettePanelShowing === show) + if (this._palettePanelShowing === show) { return; - if (show) + } + if (show) { this._updatePalettePanel(); + } this._palettePanelShowing = show; this.contentElement.classList.toggle('palette-panel-showing', show); this._focus(); @@ -271,12 +276,14 @@ * @suppress {checkTypes} */ _focus() { - if (!this.isShowing()) + if (!this.isShowing()) { return; - if (this._palettePanelShowing) + } + if (this._palettePanelShowing) { this._palettePanel.focus({preventScroll: true}); - else + } else { this.contentElement.focus(); + } } /** @@ -288,8 +295,9 @@ _createPaletteColor(colorText, colorName, animationDelay) { const element = createElementWithClass('div', 'spectrum-palette-color'); element.style.background = String.sprintf('linear-gradient(%s, %s), url(Images/checker.png)', colorText, colorText); - if (animationDelay) + if (animationDelay) { element.animate([{opacity: 0}, {opacity: 1}], {duration: 100, delay: animationDelay, fill: 'backwards'}); + } element.title = colorName || colorText; return element; } @@ -354,8 +362,9 @@ delete this._shadesCloseHandler; } - if (this._shadesCloseHandler) + if (this._shadesCloseHandler) { this._shadesCloseHandler(); + } this._shadesContainer.classList.remove('hidden'); this._shadesContainer.removeChildren(); @@ -363,8 +372,9 @@ [{transform: 'scaleY(0)', opacity: '0'}, {transform: 'scaleY(1)', opacity: '1'}], {duration: 200, easing: 'cubic-bezier(0.4, 0, 0.2, 1)'}); let shadesTop = this._paletteContainer.offsetTop + colorElement.offsetTop + colorElement.parentElement.offsetTop; - if (this._contrastDetails) + if (this._contrastDetails) { shadesTop += this._contrastDetails.element().offsetHeight; + } this._shadesContainer.style.top = shadesTop + 'px'; this._shadesContainer.style.left = colorElement.offsetLeft + 'px'; colorElement.classList.add('spectrum-shades-shown'); @@ -410,8 +420,9 @@ */ _paletteDragStart(e) { const element = e.deepElementFromPoint(); - if (!element || !element.__mutable) + if (!element || !element.__mutable) { return false; + } const index = this._slotIndexForEvent(e); this._dragElement = element; @@ -426,8 +437,9 @@ * @param {!Event} e */ _paletteDrag(e) { - if (e.pageX < this._paletteContainer.totalOffsetLeft() || e.pageY < this._paletteContainer.totalOffsetTop()) + if (e.pageX < this._paletteContainer.totalOffsetLeft() || e.pageY < this._paletteContainer.totalOffsetTop()) { return; + } const newIndex = this._slotIndexForEvent(e); const offsetX = e.pageX - (newIndex % ColorPicker.Spectrum._itemsPerPaletteRow) * ColorPicker.Spectrum._colorChipSize; @@ -444,15 +456,18 @@ const index = children.indexOf(this._dragElement); /** @type {!Map.<!Element, {left: number, top: number}>} */ const swatchOffsets = new Map(); - for (const swatch of children) + for (const swatch of children) { swatchOffsets.set(swatch, swatch.totalOffset()); + } - if (index !== newIndex) + if (index !== newIndex) { this._paletteContainer.insertBefore(this._dragElement, children[newIndex > index ? newIndex + 1 : newIndex]); + } for (const swatch of children) { - if (swatch === this._dragElement) + if (swatch === this._dragElement) { continue; + } const before = swatchOffsets.get(swatch); const after = swatch.totalOffset(); if (before.left !== after.left || before.top !== after.top) { @@ -473,14 +488,16 @@ * @param {!Event} e */ _paletteDragEnd(e) { - if (this._isDraggingToBin(e)) + if (this._isDraggingToBin(e)) { this._dragElement.remove(); + } this._dragElement.style.removeProperty('transform'); const children = this._paletteContainer.children; const colors = []; for (let i = 0; i < children.length; ++i) { - if (children[i].__color) + if (children[i].__color) { colors.push(children[i].__color); + } } const palette = this._customPaletteSetting.get(); palette.colors = colors; @@ -504,8 +521,9 @@ this._selectedColorPalette = Common.settings.createSetting('selectedColorPalette', ColorPicker.Spectrum.GeneratedPaletteTitle); const palette = this._palettes.get(this._selectedColorPalette.get()); - if (palette) + if (palette) { this._showPalette(palette, true); + } } /** @@ -513,8 +531,9 @@ */ addPalette(palette) { this._palettes.set(palette.title, palette); - if (this._selectedColorPalette.get() === palette.title) + if (this._selectedColorPalette.get() === palette.title) { this._showPalette(palette, true); + } } /** @@ -529,10 +548,12 @@ const titleElement = previewElement.createChild('div', 'palette-preview-title'); titleElement.textContent = palette.title; let i; - for (i = 0; i < colorsPerPreviewRow && i < palette.colors.length; i++) + for (i = 0; i < colorsPerPreviewRow && i < palette.colors.length; i++) { previewElement.appendChild(this._createPaletteColor(palette.colors[i], palette.colorNames[i])); - for (; i < colorsPerPreviewRow; i++) + } + for (; i < colorsPerPreviewRow; i++) { previewElement.createChild('div', 'spectrum-palette-color empty-color'); + } self.onInvokeElement(previewElement, event => { this._paletteSelected(palette); event.consume(true); @@ -553,23 +574,27 @@ */ _resizeForSelectedPalette(force) { const palette = this._palettes.get(this._selectedColorPalette.get()); - if (!palette) + if (!palette) { return; + } let numColors = palette.colors.length; - if (palette === this._customPaletteSetting.get()) + if (palette === this._customPaletteSetting.get()) { numColors++; + } const rowsNeeded = Math.max(1, Math.ceil(numColors / ColorPicker.Spectrum._itemsPerPaletteRow)); - if (this._numPaletteRowsShown === rowsNeeded && !force) + if (this._numPaletteRowsShown === rowsNeeded && !force) { return; + } this._numPaletteRowsShown = rowsNeeded; const paletteColorHeight = 12; const paletteMargin = 12; let paletteTop = 236; if (this._contrastDetails) { - if (this._contrastDetails.expanded()) + if (this._contrastDetails.expanded()) { paletteTop += 78; - else + } else { paletteTop += 36; + } } this.element.style.height = (paletteTop + paletteMargin + (paletteColorHeight + paletteMargin) * rowsNeeded) + 'px'; this.dispatchEventToListeners(ColorPicker.Spectrum.Events.SizeChanged); @@ -582,8 +607,9 @@ */ _paletteColorSelected(colorText, colorName, matchUserFormat) { const color = Common.Color.parse(colorText); - if (!color) + if (!color) { return; + } this._innerSetColor( color.hsva(), colorText, colorName, matchUserFormat ? this._colorFormat : color.format(), ColorPicker.Spectrum._ChangeSource.Other); @@ -604,8 +630,9 @@ * @param {!Event} event */ _showPaletteColorContextMenu(colorIndex, event) { - if (!this._paletteContainerMutable) + if (!this._paletteContainerMutable) { return; + } const contextMenu = new UI.ContextMenu(event); if (colorIndex !== -1) { contextMenu.defaultSection().appendItem( @@ -624,10 +651,11 @@ */ _deletePaletteColors(colorIndex, toRight) { const palette = this._customPaletteSetting.get(); - if (toRight) + if (toRight) { palette.colors.splice(colorIndex + 1, palette.colors.length - colorIndex - 1); - else + } else { palette.colors.splice(colorIndex, 1); + } this._customPaletteSetting.set(palette); this._showPalette(this._customPaletteSetting.get(), false); } @@ -650,35 +678,41 @@ * @param {string} changeSource */ _innerSetColor(hsva, colorString, colorName, colorFormat, changeSource) { - if (hsva !== undefined) + if (hsva !== undefined) { this._hsv = hsva; + } this._colorName = colorName; - if (colorString !== undefined) + if (colorString !== undefined) { this._colorString = colorString; + } if (colorFormat !== undefined) { const cf = Common.Color.Format; console.assert(colorFormat !== cf.Original, 'Spectrum\'s color format cannot be Original'); - if (colorFormat === cf.RGBA) + if (colorFormat === cf.RGBA) { colorFormat = cf.RGB; - else if (colorFormat === cf.HSLA) + } else if (colorFormat === cf.HSLA) { colorFormat = cf.HSL; - else if (colorFormat === cf.HEXA) + } else if (colorFormat === cf.HEXA) { colorFormat = cf.HEX; - else if (colorFormat === cf.ShortHEXA) + } else if (colorFormat === cf.ShortHEXA) { colorFormat = cf.ShortHEX; + } this._colorFormat = colorFormat; } - if (hsva && this._contrastInfo) + if (hsva && this._contrastInfo) { this._contrastInfo.setColor(Common.Color.fromHSVA(hsva)); + } this._updateHelperLocations(); this._updateUI(); - if (changeSource !== ColorPicker.Spectrum._ChangeSource.Input) + if (changeSource !== ColorPicker.Spectrum._ChangeSource.Input) { this._updateInput(); - if (changeSource !== ColorPicker.Spectrum._ChangeSource.Model) + } + if (changeSource !== ColorPicker.Spectrum._ChangeSource.Model) { this.dispatchEventToListeners(ColorPicker.Spectrum.Events.ColorChanged, this.colorString()); + } } /** @@ -699,24 +733,27 @@ * @return {string} */ colorString() { - if (this._colorString) + if (this._colorString) { return this._colorString; + } const cf = Common.Color.Format; const color = this._color(); let colorString = color.asString(this._colorFormat); - if (colorString) + if (colorString) { return colorString; + } - if (this._colorFormat === cf.Nickname) + if (this._colorFormat === cf.Nickname) { colorString = color.asString(color.hasAlpha() ? cf.HEXA : cf.HEX); - else if (this._colorFormat === cf.ShortHEX) + } else if (this._colorFormat === cf.ShortHEX) { colorString = color.asString(color.detectHEXFormat()); - else if (this._colorFormat === cf.HEX) + } else if (this._colorFormat === cf.HEX) { colorString = color.asString(cf.HEXA); - else if (this._colorFormat === cf.HSL) + } else if (this._colorFormat === cf.HSL) { colorString = color.asString(cf.HSLA); - else + } else { colorString = color.asString(cf.RGBA); + } console.assert(colorString); return colorString || ''; @@ -767,8 +804,9 @@ const colorValues = isRgb ? this._color().canonicalRGBA() : this._color().canonicalHSLA(); for (let i = 0; i < 3; ++i) { this._textValues[i].value = colorValues[i]; - if (!isRgb && (i === 1 || i === 2)) + if (!isRgb && (i === 1 || i === 2)) { this._textValues[i].value += '%'; + } } this._textValues[3].value = Math.round(colorValues[3] * 100) / 100; } @@ -777,8 +815,9 @@ _updateUI() { const h = Common.Color.fromHSVA([this._hsv[0], 1, 1, 1]); this._colorElement.style.backgroundColor = /** @type {string} */ (h.asString(Common.Color.Format.RGB)); - if (this._contrastOverlay) + if (this._contrastOverlay) { this._contrastOverlay.setDimensions(this.dragWidth, this.dragHeight); + } this._swatch.setColor(this._color(), this.colorString()); this._colorDragElement.style.backgroundColor = @@ -791,10 +830,11 @@ _formatViewSwitch() { const cf = Common.Color.Format; let format = cf.RGB; - if (this._colorFormat === cf.RGB) + if (this._colorFormat === cf.RGB) { format = cf.HSL; - else if (this._colorFormat === cf.HSL) + } else if (this._colorFormat === cf.HSL) { format = (this._originalFormat === cf.ShortHEX || this._originalFormat === cf.ShortHEXA) ? cf.ShortHEX : cf.HEX; + } this._innerSetColor(undefined, '', undefined /* colorName */, format, ColorPicker.Spectrum._ChangeSource.Other); } @@ -830,12 +870,14 @@ } const color = Common.Color.parse(colorString); - if (!color) + if (!color) { return; + } let colorFormat = undefined; - if (this._colorFormat === cf.HEX || this._colorFormat === cf.ShortHEX) + if (this._colorFormat === cf.HEX || this._colorFormat === cf.ShortHEX) { colorFormat = color.detectHEXFormat(); + } this._innerSetColor( color.hsva(), colorString, undefined /* colorName */, colorFormat, ColorPicker.Spectrum._ChangeSource.Input); } @@ -877,14 +919,16 @@ * @param {!Common.Event=} event */ _toggleColorPicker(enabled, event) { - if (enabled === undefined) + if (enabled === undefined) { enabled = !this._colorPickerButton.toggled(); + } this._colorPickerButton.setToggled(enabled); // This is to make sure that only one picker is open at a time // Also have a look at this._contrastDetailsBackgroundColorPickedToggled - if (this._contrastDetails && enabled && this._contrastDetails.backgroundColorPickerEnabled()) + if (this._contrastDetails && enabled && this._contrastDetails.backgroundColorPickerEnabled()) { this._contrastDetails.toggleBackgroundColorPicker(false); + } InspectorFrontendHost.setEyeDropperActive(enabled); if (enabled) { @@ -938,8 +982,9 @@ this._frequencyMap = new Map(); const stylesheetPromises = []; for (const cssModel of SDK.targetManager.models(SDK.CSSModel)) { - for (const stylesheet of cssModel.allStyleSheets()) + for (const stylesheet of cssModel.allStyleSheets()) { stylesheetPromises.push(this._processStylesheet(stylesheet)); + } } Promise.all(stylesheetPromises).catchException(null).then(this._finish.bind(this)); } @@ -964,16 +1009,20 @@ const hsvb = paletteColors.get(b).hsva(); // First trim the shades of gray - if (hsvb[1] < 0.12 && hsva[1] < 0.12) + if (hsvb[1] < 0.12 && hsva[1] < 0.12) { return hsvb[2] * hsvb[3] - hsva[2] * hsva[3]; - if (hsvb[1] < 0.12) + } + if (hsvb[1] < 0.12) { return -1; - if (hsva[1] < 0.12) + } + if (hsva[1] < 0.12) { return 1; + } // Equal hue -> sort by sat - if (hsvb[0] === hsva[0]) + if (hsvb[0] === hsva[0]) { return hsvb[1] * hsvb[3] - hsva[1] * hsva[3]; + } return (hsvb[0] + 0.94) % 1 - (hsva[0] + 0.94) % 1; } @@ -986,8 +1035,9 @@ while (paletteColors.size < colorsPerRow && colors.length) { const colorText = colors.shift(); const color = Common.Color.parse(colorText); - if (!color || color.nickname() === 'white' || color.nickname() === 'black') + if (!color || color.nickname() === 'white' || color.nickname() === 'black') { continue; + } paletteColors.set(colorText, color); } @@ -1092,10 +1142,11 @@ // Show border if the swatch is white. this._swatchInnerElement.classList.toggle('swatch-inner-white', color.hsla()[2] > 0.9); this._colorString = colorString || null; - if (colorString) + if (colorString) { this._swatchOverlayElement.hidden = false; - else + } else { this._swatchOverlayElement.hidden = true; + } } _onCopyIconClick() {
diff --git a/third_party/blink/renderer/devtools/front_end/common/CharacterIdMap.js b/third_party/blink/renderer/devtools/front_end/common/CharacterIdMap.js index 5241062..f535f98 100644 --- a/third_party/blink/renderer/devtools/front_end/common/CharacterIdMap.js +++ b/third_party/blink/renderer/devtools/front_end/common/CharacterIdMap.js
@@ -21,8 +21,9 @@ toChar(object) { let character = this._elementToCharacter.get(object); if (!character) { - if (this._charCode >= 0xFFFF) + if (this._charCode >= 0xFFFF) { throw new Error('CharacterIdMap ran out of capacity!'); + } character = String.fromCharCode(this._charCode++); this._elementToCharacter.set(object, character); this._characterToElement.set(character, object); @@ -36,8 +37,9 @@ */ fromChar(character) { const object = this._characterToElement.get(character); - if (object === undefined) + if (object === undefined) { return null; + } return object; } }
diff --git a/third_party/blink/renderer/devtools/front_end/common/Color.js b/third_party/blink/renderer/devtools/front_end/common/Color.js index e45868c..a4fc639 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Color.js +++ b/third_party/blink/renderer/devtools/front_end/common/Color.js
@@ -41,8 +41,9 @@ this._originalText = originalText || null; this._originalTextIsValid = !!this._originalText; this._format = format; - if (typeof this._rgba[3] === 'undefined') + if (typeof this._rgba[3] === 'undefined') { this._rgba[3] = 1; + } for (let i = 0; i < 4; ++i) { if (this._rgba[i] < 0) { @@ -85,8 +86,9 @@ const g = parseInt(hex.substring(2, 4), 16); const b = parseInt(hex.substring(4, 6), 16); let a = 1; - if (hex.length === 8) + if (hex.length === 8) { a = parseInt(hex.substring(6, 8), 16) / 255; + } return new Color([r / 255, g / 255, b / 255, a], format, text); } @@ -115,8 +117,9 @@ values = components.split(/\s+/); if (values[3] === '/') { values.splice(3, 1); - if (values.length !== 4) + if (values.length !== 4) { return null; + } } else if ((values.length > 2 && values[2].indexOf('/') !== -1) || (values.length > 3 && values[3].indexOf('/') !== -1)) { const alpha = values.slice(2, 4).join(''); values = values.slice(0, 2).concat(alpha.split(/\//)).concat(values.slice(4)); @@ -124,8 +127,9 @@ return null; } } - if (values.length !== 3 && values.length !== 4 || values.indexOf('') > -1) + if (values.length !== 3 && values.length !== 4 || values.indexOf('') > -1) { return null; + } const hasAlpha = (values[3] !== undefined); if (match[1]) { // rgb/rgba @@ -133,8 +137,9 @@ Color._parseRgbNumeric(values[0]), Color._parseRgbNumeric(values[1]), Color._parseRgbNumeric(values[2]), hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1 ]; - if (rgba.indexOf(null) > -1) + if (rgba.indexOf(null) > -1) { return null; + } return new Color(rgba, hasAlpha ? Format.RGBA : Format.RGB, text); } @@ -143,8 +148,9 @@ Color._parseHueNumeric(values[0]), Color._parseSatLightNumeric(values[1]), Color._parseSatLightNumeric(values[2]), hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1 ]; - if (hsla.indexOf(null) > -1) + if (hsla.indexOf(null) > -1) { return null; + } const rgba = []; Color.hsl2rgb(hsla, rgba); return new Color(rgba, hasAlpha ? Format.HSLA : Format.HSL, text); @@ -177,13 +183,15 @@ * return {number} */ static _parsePercentOrNumber(value) { - if (isNaN(value.replace('%', ''))) + if (isNaN(value.replace('%', ''))) { return null; + } const parsed = parseFloat(value); if (value.indexOf('%') !== -1) { - if (value.indexOf('%') !== value.length - 1) + if (value.indexOf('%') !== value.length - 1) { return null; + } return parsed / 100; } return parsed; @@ -195,11 +203,13 @@ */ static _parseRgbNumeric(value) { const parsed = Color._parsePercentOrNumber(value); - if (parsed === null) + if (parsed === null) { return null; + } - if (value.indexOf('%') !== -1) + if (value.indexOf('%') !== -1) { return parsed; + } return parsed / 255; } @@ -209,16 +219,18 @@ */ static _parseHueNumeric(value) { const angle = value.replace(/(deg|g?rad|turn)$/, ''); - if (isNaN(angle) || value.match(/\s+(deg|g?rad|turn)/)) + if (isNaN(angle) || value.match(/\s+(deg|g?rad|turn)/)) { return null; + } const number = parseFloat(angle); - if (value.indexOf('turn') !== -1) + if (value.indexOf('turn') !== -1) { return number % 1; - else if (value.indexOf('grad') !== -1) + } else if (value.indexOf('grad') !== -1) { return (number / 400) % 1; - else if (value.indexOf('rad') !== -1) + } else if (value.indexOf('rad') !== -1) { return (number / (2 * Math.PI)) % 1; + } return (number / 360) % 1; } @@ -227,8 +239,9 @@ * return {number} */ static _parseSatLightNumeric(value) { - if (value.indexOf('%') !== value.length - 1 || isNaN(value.replace('%', ''))) + if (value.indexOf('%') !== value.length - 1 || isNaN(value.replace('%', ''))) { return null; + } const parsed = parseFloat(value); return Math.min(1, parsed / 100); } @@ -251,10 +264,11 @@ const v = hsva[2]; const t = (2 - s) * v; - if (v === 0 || s === 0) + if (v === 0 || s === 0) { s = 0; - else + } else { s *= v / (t < 1 ? t : 2 - t); + } out_hsla[0] = h; out_hsla[1] = s; @@ -272,29 +286,33 @@ const l = hsl[2]; function hue2rgb(p, q, h) { - if (h < 0) + if (h < 0) { h += 1; - else if (h > 1) + } else if (h > 1) { h -= 1; + } - if ((h * 6) < 1) + if ((h * 6) < 1) { return p + (q - p) * h * 6; - else if ((h * 2) < 1) + } else if ((h * 2) < 1) { return q; - else if ((h * 3) < 2) + } else if ((h * 3) < 2) { return p + (q - p) * ((2 / 3) - h) * 6; - else + } else { return p; + } } - if (s < 0) + if (s < 0) { s = 0; + } let q; - if (l <= 0.5) + if (l <= 0.5) { q = l * (1 + s); - else + } else { q = l + s - (l * s); + } const p = 2 * l - q; @@ -316,8 +334,9 @@ Color._hsva2hsla(hsva, Color.hsva2rgba._tmpHSLA); Color.hsl2rgb(Color.hsva2rgba._tmpHSLA, out_rgba); - for (let i = 0; i < Color.hsva2rgba._tmpHSLA.length; i++) + for (let i = 0; i < Color.hsva2rgba._tmpHSLA.length; i++) { Color.hsva2rgba._tmpHSLA[i] = 0; + } } /** @@ -368,8 +387,9 @@ const bgLuminance = Color.luminance(bgRGBA); const contrastRatio = (Math.max(fgLuminance, bgLuminance) + 0.05) / (Math.min(fgLuminance, bgLuminance) + 0.05); - for (let i = 0; i < Color.calculateContrastRatio._blendedFg.length; i++) + for (let i = 0; i < Color.calculateContrastRatio._blendedFg.length; i++) { Color.calculateContrastRatio._blendedFg[i] = 0; + } return contrastRatio; } @@ -387,10 +407,11 @@ */ static desiredLuminance(luminance, contrast, lighter) { function computeLuminance() { - if (lighter) + if (lighter) { return (luminance + 0.05) * contrast - 0.05; - else + } else { return (luminance + 0.05) / contrast - 0.05; + } } let desiredLuminance = computeLuminance(); if (desiredLuminance < 0 || desiredLuminance > 1) { @@ -408,16 +429,17 @@ const cf = Format; let format; const formatSetting = Common.moduleSetting('colorFormat').get(); - if (formatSetting === cf.Original) + if (formatSetting === cf.Original) { format = cf.Original; - else if (formatSetting === cf.RGB) + } else if (formatSetting === cf.RGB) { format = (color.hasAlpha() ? cf.RGBA : cf.RGB); - else if (formatSetting === cf.HSL) + } else if (formatSetting === cf.HSL) { format = (color.hasAlpha() ? cf.HSLA : cf.HSL); - else if (formatSetting === cf.HEX) + } else if (formatSetting === cf.HEX) { format = color.detectHEXFormat(); - else + } else { format = cf.RGBA; + } return format; } @@ -433,8 +455,9 @@ * @return {!Array.<number>} HSLA with components within [0..1] */ hsla() { - if (this._hsla) + if (this._hsla) { return this._hsla; + } const r = this._rgba[0]; const g = this._rgba[1]; const b = this._rgba[2]; @@ -444,26 +467,28 @@ const add = max + min; let h; - if (min === max) + if (min === max) { h = 0; - else if (r === max) + } else if (r === max) { h = ((1 / 6 * (g - b) / diff) + 1) % 1; - else if (g === max) + } else if (g === max) { h = (1 / 6 * (b - r) / diff) + 1 / 3; - else + } else { h = (1 / 6 * (r - g) / diff) + 2 / 3; + } const l = 0.5 * add; let s; - if (l === 0) + if (l === 0) { s = 0; - else if (l === 1) + } else if (l === 1) { s = 0; - else if (l <= 0.5) + } else if (l <= 0.5) { s = diff / add; - else + } else { s = diff / (2 - add); + } this._hsla = [h, s, l, this._rgba[3]]; return this._hsla; @@ -512,8 +537,9 @@ const hasAlpha = this.hasAlpha(); const cf = Format; - if (canBeShort) + if (canBeShort) { return hasAlpha ? cf.ShortHEXA : cf.ShortHEX; + } return hasAlpha ? cf.HEXA : cf.HEX; } @@ -521,11 +547,13 @@ * @return {?string} */ asString(format) { - if (format === this._format && this._originalTextIsValid) + if (format === this._format && this._originalTextIsValid) { return this._originalText; + } - if (!format) + if (!format) { format = this._format; + } /** * @param {number} value @@ -556,8 +584,9 @@ case Format.Original: return this._originalText; case Format.RGB: - if (this.hasAlpha()) + if (this.hasAlpha()) { return null; + } return String.sprintf( 'rgb(%d, %d, %d)', toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2])); case Format.RGBA: @@ -565,8 +594,9 @@ 'rgba(%d, %d, %d, %f)', toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2]), this._rgba[3]); case Format.HSL: - if (this.hasAlpha()) + if (this.hasAlpha()) { return null; + } const hsl = this.hsla(); return String.sprintf( 'hsl(%d, %d%, %d%)', Math.round(hsl[0] * 360), Math.round(hsl[1] * 100), Math.round(hsl[2] * 100)); @@ -582,25 +612,29 @@ toHexValue(this._rgba[3])) .toLowerCase(); case Format.HEX: - if (this.hasAlpha()) + if (this.hasAlpha()) { return null; + } return String .sprintf('#%s%s%s', toHexValue(this._rgba[0]), toHexValue(this._rgba[1]), toHexValue(this._rgba[2])) .toLowerCase(); case Format.ShortHEXA: const hexFormat = this.detectHEXFormat(); - if (hexFormat !== Format.ShortHEXA && hexFormat !== Format.ShortHEX) + if (hexFormat !== Format.ShortHEXA && hexFormat !== Format.ShortHEX) { return null; + } return String .sprintf( '#%s%s%s%s', toShortHexValue(this._rgba[0]), toShortHexValue(this._rgba[1]), toShortHexValue(this._rgba[2]), toShortHexValue(this._rgba[3])) .toLowerCase(); case Format.ShortHEX: - if (this.hasAlpha()) + if (this.hasAlpha()) { return null; - if (this.detectHEXFormat() !== Format.ShortHEX) + } + if (this.detectHEXFormat() !== Format.ShortHEX) { return null; + } return String .sprintf( '#%s%s%s', toShortHexValue(this._rgba[0]), toShortHexValue(this._rgba[1]), @@ -625,8 +659,9 @@ */ canonicalRGBA() { const rgba = new Array(4); - for (let i = 0; i < 3; ++i) + for (let i = 0; i < 3; ++i) { rgba[i] = Math.round(this._rgba[i] * 255); + } rgba[3] = this._rgba[3]; return rgba; } @@ -639,8 +674,9 @@ Color._rgbaToNickname = {}; for (const nickname in Nicknames) { let rgba = Nicknames[nickname]; - if (rgba.length !== 4) + if (rgba.length !== 4) { rgba = rgba.concat(1); + } Color._rgbaToNickname[rgba] = nickname; } } @@ -654,8 +690,9 @@ toProtocolRGBA() { const rgba = this.canonicalRGBA(); const result = {r: rgba[0], g: rgba[1], b: rgba[2]}; - if (rgba[3] !== 1) + if (rgba[3] !== 1) { result.a = rgba[3]; + } return result; } @@ -935,8 +972,9 @@ * @return {number} */ _indexToValueInSpace(index, space) { - if (typeof space === 'number') + if (typeof space === 'number') { return space; + } const count = space.count || space.max - space.min; index %= count; return space.min + Math.floor(index / (count - 1) * (space.max - space.min));
diff --git a/third_party/blink/renderer/devtools/front_end/common/ContentProvider.js b/third_party/blink/renderer/devtools/front_end/common/ContentProvider.js index adb72086..0431e617 100644 --- a/third_party/blink/renderer/devtools/front_end/common/ContentProvider.js +++ b/third_party/blink/renderer/devtools/front_end/common/ContentProvider.js
@@ -93,8 +93,9 @@ for (let i = 0; i < text.lineCount(); ++i) { const lineContent = text.lineAt(i); regex.lastIndex = 0; - if (regex.exec(lineContent)) + if (regex.exec(lineContent)) { result.push(new Common.ContentProvider.SearchMatch(i, lineContent)); + } } return result; }; @@ -108,8 +109,9 @@ */ export const contentAsDataURL = function(content, mimeType, contentEncoded, charset) { const maxDataUrlSize = 1024 * 1024; - if (content === null || content.length > maxDataUrlSize) + if (content === null || content.length > maxDataUrlSize) { return null; + } return 'data:' + mimeType + (charset ? ';charset=' + charset : '') + (contentEncoded ? ';base64' : '') + ',' + content;
diff --git a/third_party/blink/renderer/devtools/front_end/common/EventTarget.js b/third_party/blink/renderer/devtools/front_end/common/EventTarget.js index 61f4719..6ad716a 100644 --- a/third_party/blink/renderer/devtools/front_end/common/EventTarget.js +++ b/third_party/blink/renderer/devtools/front_end/common/EventTarget.js
@@ -6,8 +6,9 @@ * @param {!Array<!Common.EventTarget.EventDescriptor>} eventList */ export function removeEventListeners(eventList) { - for (const eventInfo of eventList) + for (const eventInfo of eventList) { eventInfo.eventTarget.removeEventListener(eventInfo.eventType, eventInfo.listener, eventInfo.thisObject); + } // Do not hold references on unused event descriptors. eventList.splice(0); }
diff --git a/third_party/blink/renderer/devtools/front_end/common/Linkifier.js b/third_party/blink/renderer/devtools/front_end/common/Linkifier.js index 14c161b..d134a3b 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Linkifier.js +++ b/third_party/blink/renderer/devtools/front_end/common/Linkifier.js
@@ -21,8 +21,9 @@ * @return {!Promise<!Node>} */ export function linkify(object, options) { - if (!object) + if (!object) { return Promise.reject(new Error('Can\'t linkify ' + object)); + } return self.runtime.extension(Common.Linkifier, object) .instance() .then(linkifier => linkifier.linkify(object, options));
diff --git a/third_party/blink/renderer/devtools/front_end/common/Object.js b/third_party/blink/renderer/devtools/front_end/common/Object.js index fa618cbc..44c4c6b 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Object.js +++ b/third_party/blink/renderer/devtools/front_end/common/Object.js
@@ -41,14 +41,17 @@ * @return {!Common.EventTarget.EventDescriptor} */ addEventListener(eventType, listener, thisObject) { - if (!listener) + if (!listener) { console.assert(false); + } - if (!this._listeners) + if (!this._listeners) { this._listeners = new Map(); + } - if (!this._listeners.has(eventType)) + if (!this._listeners.has(eventType)) { this._listeners.set(eventType, []); + } this._listeners.get(eventType).push({thisObject: thisObject, listener: listener}); return {eventTarget: this, eventType: eventType, thisObject: thisObject, listener: listener}; } @@ -76,8 +79,9 @@ removeEventListener(eventType, listener, thisObject) { console.assert(listener); - if (!this._listeners || !this._listeners.has(eventType)) + if (!this._listeners || !this._listeners.has(eventType)) { return; + } const listeners = this._listeners.get(eventType); for (let i = 0; i < listeners.length; ++i) { if (listeners[i].listener === listener && listeners[i].thisObject === thisObject) { @@ -86,8 +90,9 @@ } } - if (!listeners.length) + if (!listeners.length) { this._listeners.delete(eventType); + } } /** @@ -105,14 +110,16 @@ * @param {*=} eventData */ dispatchEventToListeners(eventType, eventData) { - if (!this._listeners || !this._listeners.has(eventType)) + if (!this._listeners || !this._listeners.has(eventType)) { return; + } const event = /** @type {!Common.Event} */ ({data: eventData}); const listeners = this._listeners.get(eventType).slice(0); for (let i = 0; i < listeners.length; ++i) { - if (!listeners[i].disposed) + if (!listeners[i].disposed) { listeners[i].listener.call(listeners[i].thisObject, event); + } } } }
diff --git a/third_party/blink/renderer/devtools/front_end/common/ParsedURL.js b/third_party/blink/renderer/devtools/front_end/common/ParsedURL.js index 26dedde..280a37f 100644 --- a/third_party/blink/renderer/devtools/front_end/common/ParsedURL.js +++ b/third_party/blink/renderer/devtools/front_end/common/ParsedURL.js
@@ -95,10 +95,11 @@ static platformPathToURL(fileSystemPath) { fileSystemPath = fileSystemPath.replace(/\\/g, '/'); if (!fileSystemPath.startsWith('file://')) { - if (fileSystemPath.startsWith('/')) + if (fileSystemPath.startsWith('/')) { fileSystemPath = 'file://' + fileSystemPath; - else + } else { fileSystemPath = 'file:///' + fileSystemPath; + } } return fileSystemPath; } @@ -110,8 +111,9 @@ */ static urlToPlatformPath(fileURL, isWindows) { console.assert(fileURL.startsWith('file://'), 'This must be a file URL.'); - if (isWindows) + if (isWindows) { return fileURL.substr('file:///'.length).replace(/\//g, '\\'); + } return fileURL.substr('file://'.length); } @@ -121,8 +123,9 @@ */ static urlWithoutHash(url) { const hashIndex = url.indexOf('#'); - if (hashIndex !== -1) + if (hashIndex !== -1) { return url.substr(0, hashIndex); + } return url; } @@ -130,8 +133,9 @@ * @return {!RegExp} */ static _urlRegex() { - if (Common.ParsedURL._urlRegexInstance) + if (Common.ParsedURL._urlRegexInstance) { return Common.ParsedURL._urlRegexInstance; + } // RegExp groups: // 1 - scheme, hostname, ?port // 2 - scheme (using the RFC3986 grammar) @@ -180,17 +184,20 @@ static extractExtension(url) { url = Common.ParsedURL.urlWithoutHash(url); const indexOfQuestionMark = url.indexOf('?'); - if (indexOfQuestionMark !== -1) + if (indexOfQuestionMark !== -1) { url = url.substr(0, indexOfQuestionMark); + } const lastIndexOfSlash = url.lastIndexOf('/'); - if (lastIndexOfSlash !== -1) + if (lastIndexOfSlash !== -1) { url = url.substr(lastIndexOfSlash + 1); + } const lastIndexOfDot = url.lastIndexOf('.'); if (lastIndexOfDot !== -1) { url = url.substr(lastIndexOfDot + 1); const lastIndexOfPercent = url.indexOf('%'); - if (lastIndexOfPercent !== -1) + if (lastIndexOfPercent !== -1) { return url.substr(0, lastIndexOfPercent); + } return url; } return ''; @@ -216,20 +223,24 @@ // Return special URLs as-is. const trimmedHref = href.trim(); if (trimmedHref.startsWith('data:') || trimmedHref.startsWith('blob:') || trimmedHref.startsWith('javascript:') || - trimmedHref.startsWith('mailto:')) + trimmedHref.startsWith('mailto:')) { return href; + } // Return absolute URLs as-is. const parsedHref = trimmedHref.asParsedURL(); - if (parsedHref && parsedHref.scheme) + if (parsedHref && parsedHref.scheme) { return trimmedHref; + } const parsedURL = baseURL.asParsedURL(); - if (!parsedURL) + if (!parsedURL) { return null; + } - if (parsedURL.isDataURL()) + if (parsedURL.isDataURL()) { return href; + } if (href.length > 1 && href.charAt(0) === '/' && href.charAt(1) === '/') { // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol). @@ -241,19 +252,23 @@ const queryText = parsedURL.queryParams ? '?' + parsedURL.queryParams : ''; // Empty href resolves to a URL without fragment. - if (!href.length) + if (!href.length) { return securityOrigin + pathText + queryText; + } - if (href.charAt(0) === '#') + if (href.charAt(0) === '#') { return securityOrigin + pathText + queryText + href; + } - if (href.charAt(0) === '?') + if (href.charAt(0) === '?') { return securityOrigin + pathText + href; + } let hrefPath = href.match(/^[^#?]*/)[0]; const hrefSuffix = href.substring(hrefPath.length); - if (hrefPath.charAt(0) !== '/') + if (hrefPath.charAt(0) !== '/') { hrefPath = parsedURL.folderPathComponents + '/' + hrefPath; + } return securityOrigin + Runtime.normalizePath(hrefPath) + hrefSuffix; } @@ -303,21 +318,27 @@ } get displayName() { - if (this._displayName) + if (this._displayName) { return this._displayName; + } - if (this.isDataURL()) + if (this.isDataURL()) { return this.dataURLDisplayName(); - if (this.isBlobURL()) + } + if (this.isBlobURL()) { return this.url; - if (this.isAboutBlank()) + } + if (this.isAboutBlank()) { return this.url; + } this._displayName = this.lastPathComponent; - if (!this._displayName) + if (!this._displayName) { this._displayName = (this.host || '') + '/'; - if (this._displayName === '/') + } + if (this._displayName === '/') { this._displayName = this.url; + } return this._displayName; } @@ -325,10 +346,12 @@ * @return {string} */ dataURLDisplayName() { - if (this._dataURLDisplayName) + if (this._dataURLDisplayName) { return this._dataURLDisplayName; - if (!this.isDataURL()) + } + if (!this.isDataURL()) { return ''; + } this._dataURLDisplayName = this.url.trimEndWithMaxLength(20); return this._dataURLDisplayName; } @@ -365,8 +388,9 @@ * @return {string} */ domain() { - if (this.isDataURL()) + if (this.isDataURL()) { return 'data:'; + } return this.host + (this.port ? ':' + this.port : ''); } @@ -374,8 +398,9 @@ * @return {string} */ securityOrigin() { - if (this.isDataURL()) + if (this.isDataURL()) { return 'data:'; + } const scheme = this.isBlobURL() ? this._blobInnerScheme : this.scheme; return scheme + '://' + this.domain(); } @@ -384,8 +409,9 @@ * @return {string} */ urlWithoutScheme() { - if (this.scheme && this.url.startsWith(this.scheme + '://')) + if (this.scheme && this.url.startsWith(this.scheme + '://')) { return this.url.substring(this.scheme.length + 3); + } return this.url; } } @@ -395,8 +421,9 @@ */ String.prototype.asParsedURL = function() { const parsedURL = new Common.ParsedURL(this.toString()); - if (parsedURL.isValid) + if (parsedURL.isValid) { return parsedURL; + } return null; };
diff --git a/third_party/blink/renderer/devtools/front_end/common/Progress.js b/third_party/blink/renderer/devtools/front_end/common/Progress.js index 2f24102..e60d3ae 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Progress.js +++ b/third_party/blink/renderer/devtools/front_end/common/Progress.js
@@ -84,8 +84,9 @@ } _childDone() { - if (++this._childrenDone !== this._children.length) + if (++this._childrenDone !== this._children.length) { return; + } this._parent.done(); } @@ -105,8 +106,9 @@ for (let i = 0; i < this._children.length; ++i) { const child = this._children[i]; - if (child._totalWork) + if (child._totalWork) { done += child._weight * child._worked / child._totalWork; + } totalWeights += child._weight; } this._parent.setWorked(done / totalWeights); @@ -168,8 +170,9 @@ */ setWorked(worked, title) { this._worked = worked; - if (typeof title !== 'undefined') + if (typeof title !== 'undefined') { this.setTitle(title); + } this._composite._update(); } @@ -209,18 +212,21 @@ * @param {string} title */ setTitle(title) { - if (this._delegate) + if (this._delegate) { this._delegate.setTitle(title); + } } /** * @override */ done() { - if (this._delegate) + if (this._delegate) { this._delegate.done(); - if (this._doneCallback) + } + if (this._doneCallback) { this._doneCallback(); + } } /** @@ -228,8 +234,9 @@ * @param {number} totalWork */ setTotalWork(totalWork) { - if (this._delegate) + if (this._delegate) { this._delegate.setTotalWork(totalWork); + } } /** @@ -238,8 +245,9 @@ * @param {string=} title */ setWorked(worked, title) { - if (this._delegate) + if (this._delegate) { this._delegate.setWorked(worked, title); + } } /** @@ -247,8 +255,9 @@ * @param {number=} worked */ worked(worked) { - if (this._delegate) + if (this._delegate) { this._delegate.worked(worked); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/common/ResourceType.js b/third_party/blink/renderer/devtools/front_end/common/ResourceType.js index 068df21f..cb30bee7 100644 --- a/third_party/blink/renderer/devtools/front_end/common/ResourceType.js +++ b/third_party/blink/renderer/devtools/front_end/common/ResourceType.js
@@ -49,23 +49,31 @@ * @return {!ResourceType} */ static fromMimeType(mimeType) { - if (mimeType.startsWith('text/html')) + if (mimeType.startsWith('text/html')) { return resourceTypes.Document; - if (mimeType.startsWith('text/css')) + } + if (mimeType.startsWith('text/css')) { return resourceTypes.Stylesheet; - if (mimeType.startsWith('image/')) + } + if (mimeType.startsWith('image/')) { return resourceTypes.Image; - if (mimeType.startsWith('text/')) + } + if (mimeType.startsWith('text/')) { return resourceTypes.Script; + } - if (mimeType.includes('font')) + if (mimeType.includes('font')) { return resourceTypes.Font; - if (mimeType.includes('script')) + } + if (mimeType.includes('script')) { return resourceTypes.Script; - if (mimeType.includes('octet')) + } + if (mimeType.includes('octet')) { return resourceTypes.Other; - if (mimeType.includes('application')) + } + if (mimeType.includes('application')) { return resourceTypes.Script; + } return resourceTypes.Other; } @@ -85,8 +93,9 @@ static fromName(name) { for (const resourceTypeId in resourceTypes) { const resourceType = resourceTypes[resourceTypeId]; - if (resourceType.name() === name) + if (resourceType.name() === name) { return resourceType; + } } return null; } @@ -97,8 +106,9 @@ */ static mimeFromURL(url) { const name = Common.ParsedURL.extractName(url); - if (ResourceType._mimeTypeByName.has(name)) + if (ResourceType._mimeTypeByName.has(name)) { return ResourceType._mimeTypeByName.get(name); + } const ext = Common.ParsedURL.extractExtension(url).toLowerCase(); return ResourceType._mimeTypeByExtension.get(ext); @@ -194,12 +204,15 @@ * @return {string} */ canonicalMimeType() { - if (this.isDocument()) + if (this.isDocument()) { return 'text/html'; - if (this.isScript()) + } + if (this.isScript()) { return 'text/javascript'; - if (this.isStyleSheet()) + } + if (this.isStyleSheet()) { return 'text/css'; + } return ''; } }
diff --git a/third_party/blink/renderer/devtools/front_end/common/Revealer.js b/third_party/blink/renderer/devtools/front_end/common/Revealer.js index 467c6e5..af1b783 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Revealer.js +++ b/third_party/blink/renderer/devtools/front_end/common/Revealer.js
@@ -21,8 +21,9 @@ * @return {!Promise.<undefined>} */ export const reveal = function(revealable, omitFocus) { - if (!revealable) + if (!revealable) { return Promise.reject(new Error('Can\'t reveal ' + revealable)); + } return self.runtime.allInstances(Common.Revealer, revealable).then(reveal); /** @@ -31,8 +32,9 @@ */ function reveal(revealers) { const promises = []; - for (let i = 0; i < revealers.length; ++i) + for (let i = 0; i < revealers.length; ++i) { promises.push(revealers[i].reveal(/** @type {!Object} */ (revealable), omitFocus)); + } return Promise.race(promises); } }; @@ -43,8 +45,9 @@ */ export const revealDestination = function(revealable) { const extension = self.runtime.extension(Common.Revealer, revealable); - if (!extension) + if (!extension) { return null; + } return extension.descriptor()['destination']; };
diff --git a/third_party/blink/renderer/devtools/front_end/common/SegmentedRange.js b/third_party/blink/renderer/devtools/front_end/common/SegmentedRange.js index 9436ba1..f11db7c 100644 --- a/third_party/blink/renderer/devtools/front_end/common/SegmentedRange.js +++ b/third_party/blink/renderer/devtools/front_end/common/SegmentedRange.js
@@ -11,8 +11,9 @@ * @param {*} data */ constructor(begin, end, data) { - if (begin > end) + if (begin > end) { console.assert(false, 'Invalid segment'); + } this.begin = begin; this.end = end; this.data = data; @@ -66,8 +67,9 @@ } } // 3. Consume all segments that are entirely covered by the new one. - while (endIndex < this._segments.length && this._segments[endIndex].end <= newSegment.end) + while (endIndex < this._segments.length && this._segments[endIndex].end <= newSegment.end) { ++endIndex; + } // 4. Merge or adjust the succeeding segment if it overlaps. if (endIndex < this._segments.length) { merged = this._tryMerge(newSegment, this._segments[endIndex]); @@ -102,8 +104,9 @@ */ _tryMerge(first, second) { const merged = this._mergeCallback && this._mergeCallback(first, second); - if (!merged) + if (!merged) { return null; + } merged.begin = first.begin; merged.end = Math.max(first.end, second.end); return merged;
diff --git a/third_party/blink/renderer/devtools/front_end/common/Settings.js b/third_party/blink/renderer/devtools/front_end/common/Settings.js index ede3af62..d60d453 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Settings.js +++ b/third_party/blink/renderer/devtools/front_end/common/Settings.js
@@ -73,10 +73,12 @@ } const setting = isRegex ? this.createRegExpSetting(settingName, defaultValue, undefined, storageType) : this.createSetting(settingName, defaultValue, storageType); - if (extension.title()) + if (extension.title()) { setting.setTitle(extension.title()); - if (descriptor['userActionCondition']) + } + if (descriptor['userActionCondition']) { setting.setRequiresUserAction(!!Runtime.queryParam(descriptor['userActionCondition'])); + } setting._extension = extension; this._moduleSettings.set(settingName, setting); } @@ -87,8 +89,9 @@ */ moduleSetting(settingName) { const setting = this._moduleSettings.get(settingName); - if (!setting) + if (!setting) { throw new Error('No setting registered: ' + settingName); + } return setting; } @@ -98,8 +101,9 @@ */ settingForTest(settingName) { const setting = this._registry.get(settingName); - if (!setting) + if (!setting) { throw new Error('No setting registered: ' + settingName); + } return setting; } @@ -111,8 +115,9 @@ */ createSetting(key, defaultValue, storageType) { const storage = this._storageFromType(storageType); - if (!this._registry.get(key)) + if (!this._registry.get(key)) { this._registry.set(key, new Common.Setting(this, key, defaultValue, this._eventSupport, storage)); + } return /** @type {!Common.Setting} */ (this._registry.get(key)); } @@ -231,8 +236,9 @@ Common.console.log('Ten largest settings: '); const sizes = {__proto__: null}; - for (const key in this._object) + for (const key in this._object) { sizes[key] = this._object[key].length; + } const keys = Object.keys(sizes); function comparator(key1, key2) { @@ -241,8 +247,9 @@ keys.sort(comparator); - for (let i = 0; i < 10 && i < keys.length; ++i) + for (let i = 0; i < 10 && i < keys.length; ++i) { Common.console.log('Setting: \'' + keys[i] + '\', size: ' + sizes[keys[i]]); + } } } @@ -315,11 +322,13 @@ * @return {V} */ get() { - if (this._requiresUserAction && !this._hadUserAction) + if (this._requiresUserAction && !this._hadUserAction) { return this._defaultValue; + } - if (typeof this._value !== 'undefined') + if (typeof this._value !== 'undefined') { return this._value; + } this._value = this._defaultValue; if (this._storage.has(this._name)) { @@ -404,8 +413,9 @@ const items = this.getAsArray(); for (let i = 0; i < items.length; ++i) { const item = items[i]; - if (item.pattern && !item.disabled) + if (item.pattern && !item.disabled) { result.push(item.pattern); + } } return result.join('|'); } @@ -437,13 +447,15 @@ * @return {?RegExp} */ asRegExp() { - if (typeof this._regex !== 'undefined') + if (typeof this._regex !== 'undefined') { return this._regex; + } this._regex = null; try { const pattern = this.get(); - if (pattern) + if (pattern) { this._regex = new RegExp(pattern, this._regexFlags || ''); + } } catch (e) { } return this._regex; @@ -466,8 +478,9 @@ return; } const methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion); - for (let i = 0; i < methodsToRun.length; ++i) + for (let i = 0; i < methodsToRun.length; ++i) { this[methodsToRun[i]].call(this); + } versionSetting.set(currentVersion); } @@ -477,8 +490,9 @@ */ _methodsToRunToUpdateVersion(oldVersion, currentVersion) { const result = []; - for (let i = oldVersion; i < currentVersion; ++i) + for (let i = oldVersion; i < currentVersion; ++i) { result.push('_updateVersionFrom' + i + 'To' + (i + 1)); + } return result; } @@ -543,8 +557,9 @@ newValue.horizontal.size = oldSettingH.get(); oldSettingH.remove(); } - if (newValue) + if (newValue) { Common.settings.createSetting(newName, {}).set(newValue); + } } } @@ -590,13 +605,16 @@ for (const name in settingNames) { const setting = Common.settings.createSetting(name, empty); const value = setting.get(); - if (value === empty) + if (value === empty) { continue; + } // Zero out saved percentage sizes, and they will be restored to defaults. - if (value.vertical && value.vertical.size && value.vertical.size < 1) + if (value.vertical && value.vertical.size && value.vertical.size < 1) { value.vertical.size = 0; - if (value.horizontal && value.horizontal.size && value.horizontal.size < 1) + } + if (value.horizontal && value.horizontal.size && value.horizontal.size < 1) { value.horizontal.size = 0; + } setting.set(value); } } @@ -610,13 +628,16 @@ for (let i = 0; i < settingNames.length; ++i) { const setting = Common.settings.createSetting(settingNames[i], ''); let value = setting.get(); - if (!value) + if (!value) { return; - if (typeof value === 'string') + } + if (typeof value === 'string') { value = [value]; + } for (let j = 0; j < value.length; ++j) { - if (typeof value[j] === 'string') + if (typeof value[j] === 'string') { value[j] = {pattern: value[j]}; + } } setting.set(value); } @@ -624,11 +645,13 @@ _updateVersionFrom9To10() { // This one is localStorage specific, which is fine. - if (!window.localStorage) + if (!window.localStorage) { return; + } for (const key in window.localStorage) { - if (key.startsWith('revision-history')) + if (key.startsWith('revision-history')) { window.localStorage.removeItem(key); + } } } @@ -637,8 +660,9 @@ const newSettingName = 'customEmulatedDeviceList'; const oldSetting = Common.settings.createSetting(oldSettingName, undefined); const list = oldSetting.get(); - if (!Array.isArray(list)) + if (!Array.isArray(list)) { return; + } const newList = []; for (let i = 0; i < list.length; ++i) { const value = list[i]; @@ -647,10 +671,12 @@ device['type'] = 'unknown'; device['user-agent'] = value['userAgent']; device['capabilities'] = []; - if (value['touch']) + if (value['touch']) { device['capabilities'].push('touch'); - if (value['mobile']) + } + if (value['mobile']) { device['capabilities'].push('mobile'); + } device['screen'] = {}; device['screen']['vertical'] = {width: value['width'], height: value['height']}; device['screen']['horizontal'] = {width: value['height'], height: value['width']}; @@ -660,8 +686,9 @@ device['show'] = 'Default'; newList.push(device); } - if (newList.length) + if (newList.length) { Common.settings.createSetting(newSettingName, []).set(newList); + } oldSetting.remove(); } @@ -685,8 +712,9 @@ const newValue = {}; for (const fileSystemPath in oldValue) { newValue[fileSystemPath] = []; - for (const entry of oldValue[fileSystemPath]) + for (const entry of oldValue[fileSystemPath]) { newValue[fileSystemPath].push(entry.path); + } } setting.set(newValue); } @@ -694,8 +722,9 @@ _updateVersionFrom15To16() { const setting = Common.settings.createSetting('InspectorView.panelOrder', {}); const tabOrders = setting.get(); - for (const key of Object.keys(tabOrders)) + for (const key of Object.keys(tabOrders)) { tabOrders[key] = (tabOrders[key] + 1) * 10; + } setting.set(tabOrders); } @@ -725,10 +754,11 @@ for (const oldKey in oldValue) { let newKey = oldKey.replace(/\\/g, '/'); if (!newKey.startsWith('file://')) { - if (newKey.startsWith('/')) + if (newKey.startsWith('/')) { newKey = 'file://' + newKey; - else + } else { newKey = 'file:///' + newKey; + } } newValue[newKey] = oldValue[oldKey]; } @@ -744,8 +774,9 @@ const configs = {}; for (const columnId in visibleColumns) { - if (!visibleColumns.hasOwnProperty(columnId)) + if (!visibleColumns.hasOwnProperty(columnId)) { continue; + } configs[columnId.toLowerCase()] = {visible: visibleColumns[columnId]}; } const newSetting = Common.settings.createSetting('networkLogColumns', {}); @@ -833,8 +864,9 @@ function renameInStringSetting(settingName, from, to) { const setting = Common.settings.createSetting(settingName, ''); const value = setting.get(); - if (value === from) + if (value === from) { setting.set(to); + } } renameKeyInObjectSetting('panel-tabOrder', 'audits2', 'audits'); @@ -844,8 +876,9 @@ _updateVersionFrom27To28() { const setting = Common.settings.createSetting('uiTheme', 'systemPreferred'); - if (setting.get() === 'default') + if (setting.get() === 'default') { setting.set('systemPreferred'); + } } _migrateSettingsFromLocalStorage() { @@ -855,12 +888,14 @@ 'fileSystemMapping', 'lastSelectedSourcesSidebarPaneTab', 'previouslyViewedFiles', 'savedURLs', 'watchExpressions', 'workspaceExcludedFolders', 'xhrBreakpoints' ]); - if (!window.localStorage) + if (!window.localStorage) { return; + } for (const key in window.localStorage) { - if (localSettings.has(key)) + if (localSettings.has(key)) { continue; + } const value = window.localStorage[key]; window.localStorage.removeItem(key); Common.settings._globalStorage[key] = value; @@ -874,8 +909,9 @@ _clearBreakpointsWhenTooMany(breakpointsSetting, maxBreakpointsCount) { // If there are too many breakpoints in a storage, it is likely due to a recent bug that caused // periodical breakpoints duplication leading to inspector slowness. - if (breakpointsSetting.get().length > maxBreakpointsCount) + if (breakpointsSetting.get().length > maxBreakpointsCount) { breakpointsSetting.set([]); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/common/TextDictionary.js b/third_party/blink/renderer/devtools/front_end/common/TextDictionary.js index e190f39..adf355a 100644 --- a/third_party/blink/renderer/devtools/front_end/common/TextDictionary.js +++ b/third_party/blink/renderer/devtools/front_end/common/TextDictionary.js
@@ -53,8 +53,9 @@ */ removeWord(word) { let count = this._words.get(word) || 0; - if (!count) + if (!count) { return; + } if (count === 1) { this._words.delete(word); this._index.remove(word);
diff --git a/third_party/blink/renderer/devtools/front_end/common/Throttler.js b/third_party/blink/renderer/devtools/front_end/common/Throttler.js index 21c5f797..95a60b6 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Throttler.js +++ b/third_party/blink/renderer/devtools/front_end/common/Throttler.js
@@ -25,8 +25,9 @@ _processCompleted() { this._lastCompleteTime = this._getTime(); this._isRunningProcess = false; - if (this._process) + if (this._process) { this._innerSchedule(false); + } this._processCompletedForTests(); } @@ -76,12 +77,15 @@ * @param {boolean} forceTimerUpdate */ _innerSchedule(forceTimerUpdate) { - if (this._isRunningProcess) + if (this._isRunningProcess) { return; - if (this._processTimeout && !forceTimerUpdate) + } + if (this._processTimeout && !forceTimerUpdate) { return; - if (this._processTimeout) + } + if (this._processTimeout) { this._clearTimeout(this._processTimeout); + } const timeout = this._asSoonAsPossible ? 0 : this._timeout; this._processTimeout = this._setTimeout(this._onTimeout.bind(this), timeout);
diff --git a/third_party/blink/renderer/devtools/front_end/common/Trie.js b/third_party/blink/renderer/devtools/front_end/common/Trie.js index 22afde9f..9e9143a 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Trie.js +++ b/third_party/blink/renderer/devtools/front_end/common/Trie.js
@@ -41,8 +41,9 @@ * @return {boolean} */ remove(word) { - if (!this.has(word)) + if (!this.has(word)) { return false; + } let node = this._root; --this._wordsInSubtree[this._root]; for (let i = 0; i < word.length; ++i) { @@ -66,8 +67,9 @@ let node = this._root; for (let i = 0; i < word.length; ++i) { node = this._edges[node][word[i]]; - if (!node) + if (!node) { return false; + } } return this._isWord[node]; } @@ -81,8 +83,9 @@ let node = this._root; for (let i = 0; i < prefix.length; ++i) { node = this._edges[node][prefix[i]]; - if (!node) + if (!node) { return []; + } } const results = []; this._dfs(node, prefix, results); @@ -95,11 +98,13 @@ * @param {!Array<string>} results */ _dfs(node, prefix, results) { - if (this._isWord[node]) + if (this._isWord[node]) { results.push(prefix); + } const edges = this._edges[node]; - for (const edge in edges) + for (const edge in edges) { this._dfs(edges[edge], prefix + edge, results); + } } /** @@ -112,10 +117,12 @@ let wordIndex = 0; for (let i = 0; i < word.length; ++i) { node = this._edges[node][word[i]]; - if (!node) + if (!node) { break; - if (!fullWordOnly || this._isWord[node]) + } + if (!fullWordOnly || this._isWord[node]) { wordIndex = i + 1; + } } return word.substring(0, wordIndex); }
diff --git a/third_party/blink/renderer/devtools/front_end/common/UIString.js b/third_party/blink/renderer/devtools/front_end/common/UIString.js index 64b1fcc..c84e84e 100644 --- a/third_party/blink/renderer/devtools/front_end/common/UIString.js +++ b/third_party/blink/renderer/devtools/front_end/common/UIString.js
@@ -54,8 +54,9 @@ * @return {*} */ export function deserializeUIString(serializedMessage) { - if (!serializedMessage) + if (!serializedMessage) { return {}; + } return JSON.parse(serializedMessage); } @@ -110,8 +111,9 @@ * @return {string} */ self.ls = function(strings, vararg) { - if (typeof strings === 'string') + if (typeof strings === 'string') { return strings; + } let substitutionString = Common._substitutionStrings.get(strings); if (!substitutionString) { substitutionString = strings.join('%s');
diff --git a/third_party/blink/renderer/devtools/front_end/common/Worker.js b/third_party/blink/renderer/devtools/front_end/common/Worker.js index a9c31a6..62c243a8 100644 --- a/third_party/blink/renderer/devtools/front_end/common/Worker.js +++ b/third_party/blink/renderer/devtools/front_end/common/Worker.js
@@ -64,8 +64,9 @@ */ postMessage(message) { this._workerPromise.then(worker => { - if (!this._disposed) + if (!this._disposed) { worker.postMessage(message); + } }); }
diff --git a/third_party/blink/renderer/devtools/front_end/components/DockController.js b/third_party/blink/renderer/devtools/front_end/components/DockController.js index 801f25dc..9b77e3f 100644 --- a/third_party/blink/renderer/devtools/front_end/components/DockController.js +++ b/third_party/blink/renderer/devtools/front_end/components/DockController.js
@@ -56,15 +56,18 @@ this._currentDockStateSetting = Common.settings.moduleSetting('currentDockState'); this._currentDockStateSetting.addChangeListener(this._dockSideChanged, this); this._lastDockStateSetting = Common.settings.createSetting('lastDockState', 'bottom'); - if (this._states.indexOf(this._currentDockStateSetting.get()) === -1) + if (this._states.indexOf(this._currentDockStateSetting.get()) === -1) { this._currentDockStateSetting.set('right'); - if (this._states.indexOf(this._lastDockStateSetting.get()) === -1) + } + if (this._states.indexOf(this._lastDockStateSetting.get()) === -1) { this._currentDockStateSetting.set('bottom'); + } } initialize() { - if (!this._canDock) + if (!this._canDock) { return; + } this._titles = [ Common.UIString('Dock to right'), Common.UIString('Dock to bottom'), Common.UIString('Dock to left'), @@ -104,14 +107,17 @@ * @suppressGlobalPropertiesCheck */ setDockSide(dockSide) { - if (this._states.indexOf(dockSide) === -1) + if (this._states.indexOf(dockSide) === -1) { dockSide = this._states[0]; + } - if (this._dockSide === dockSide) + if (this._dockSide === dockSide) { return; + } - if (this._dockSide) + if (this._dockSide) { this._lastDockStateSetting.set(this._dockSide); + } this._savedFocus = document.deepActiveElement(); const eventData = {from: this._dockSide, to: dockSide};
diff --git a/third_party/blink/renderer/devtools/front_end/components/ImagePreview.js b/third_party/blink/renderer/devtools/front_end/components/ImagePreview.js index 5059405..a388f49 100644 --- a/third_party/blink/renderer/devtools/front_end/components/ImagePreview.js +++ b/third_party/blink/renderer/devtools/front_end/components/ImagePreview.js
@@ -13,24 +13,27 @@ static build(target, originalImageURL, showDimensions, options = {}) { const {precomputedFeatures, imageAltText} = options; const resourceTreeModel = target.model(SDK.ResourceTreeModel); - if (!resourceTreeModel) + if (!resourceTreeModel) { return Promise.resolve(/** @type {?Element} */ (null)); + } let resource = resourceTreeModel.resourceForURL(originalImageURL); let imageURL = originalImageURL; if (!isImageResource(resource) && precomputedFeatures && precomputedFeatures.currentSrc) { imageURL = precomputedFeatures.currentSrc; resource = resourceTreeModel.resourceForURL(imageURL); } - if (!isImageResource(resource)) + if (!isImageResource(resource)) { return Promise.resolve(/** @type {?Element} */ (null)); + } let fulfill; const promise = new Promise(x => fulfill = x); const imageElement = createElement('img'); imageElement.addEventListener('load', buildContent, false); imageElement.addEventListener('error', () => fulfill(null), false); - if (imageAltText) + if (imageAltText) { imageElement.alt = imageAltText; + } resource.populateImageSource(imageElement); return promise; @@ -61,8 +64,9 @@ } container.createChild('tr').createChild('td', 'image-container').appendChild(imageElement); - if (description) + if (description) { container.createChild('tr').createChild('td').createChild('span', 'description').textContent = description; + } if (imageURL !== originalImageURL) { container.createChild('tr').createChild('td').createChild('span', 'description').textContent = String.sprintf('currentSrc: %s', imageURL.trimMiddle(100)); @@ -76,13 +80,15 @@ * @return {!Promise<!Object|undefined>} */ static async loadDimensionsForNode(node) { - if (!node.nodeName() || node.nodeName().toLowerCase() !== 'img') + if (!node.nodeName() || node.nodeName().toLowerCase() !== 'img') { return; + } const object = await node.resolveToObject(''); - if (!object) + if (!object) { return; + } const featuresObject = object.callFunctionJSON(features, undefined); object.release();
diff --git a/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js b/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js index 3e74bea..7a1be1a 100644 --- a/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js +++ b/third_party/blink/renderer/devtools/front_end/components/JSPresentationUtils.js
@@ -64,8 +64,9 @@ if (link) { link.addEventListener('contextmenu', populateContextMenu.bind(null, link)); const uiLocation = Components.Linkifier.uiLocation(link); - if (uiLocation && Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode)) + if (uiLocation && Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode)) { shouldHide = true; + } row.createChild('td').textContent = ' @ '; row.createChild('td').appendChild(link); links.push(link); @@ -101,8 +102,9 @@ contextMenu.show(); } - if (!stackTrace) + if (!stackTrace) { return {element, links}; + } appendStackTrace(stackTrace); @@ -118,8 +120,9 @@ UI.asyncStackTraceLabel(asyncStackTrace.description); row.createChild('td'); row.createChild('td'); - if (appendStackTrace(asyncStackTrace)) + if (appendStackTrace(asyncStackTrace)) { row.classList.add('blackboxed'); + } asyncStackTrace = asyncStackTrace.parent; } @@ -129,14 +132,16 @@ const cell = row.createChild('td'); cell.colSpan = 4; const showAllLink = cell.createChild('span', 'link'); - if (totalHiddenCallFramesCount === 1) + if (totalHiddenCallFramesCount === 1) { showAllLink.textContent = ls`Show 1 more frame`; - else + } else { showAllLink.textContent = ls`Show ${totalHiddenCallFramesCount} more frames`; + } showAllLink.addEventListener('click', () => { contentElement.classList.add('show-blackboxed'); - if (contentUpdated) + if (contentUpdated) { contentUpdated(); + } }, false); }
diff --git a/third_party/blink/renderer/devtools/front_end/components/Linkifier.js b/third_party/blink/renderer/devtools/front_end/components/Linkifier.js index d6a0409..6d652b40 100644 --- a/third_party/blink/renderer/devtools/front_end/components/Linkifier.js +++ b/third_party/blink/renderer/devtools/front_end/components/Linkifier.js
@@ -55,8 +55,9 @@ console.assert(!Components.Linkifier._decorator, 'Cannot re-register link decorator.'); Components.Linkifier._decorator = decorator; decorator.addEventListener(Components.LinkDecorator.Events.LinkIconChanged, onLinkIconChanged); - for (const linkifier of Components.Linkifier._instances) + for (const linkifier of Components.Linkifier._instances) { linkifier._updateAllAnchorDecorations(); + } /** * @param {!Common.Event} event @@ -64,15 +65,17 @@ function onLinkIconChanged(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); const links = uiSourceCode[Components.Linkifier._sourceCodeAnchors] || []; - for (const link of links) + for (const link of links) { Components.Linkifier._updateLinkDecorations(link); + } } } _updateAllAnchorDecorations() { for (const anchors of this._anchorsByTarget.values()) { - for (const anchor of anchors) + for (const anchor of anchors) { Components.Linkifier._updateLinkDecorations(anchor); + } } } @@ -82,8 +85,9 @@ */ static _bindUILocation(anchor, uiLocation) { Components.Linkifier._linkInfo(anchor).uiLocation = uiLocation; - if (!uiLocation) + if (!uiLocation) { return; + } const uiSourceCode = uiLocation.uiSourceCode; let sourceCodeAnchors = uiSourceCode[Components.Linkifier._sourceCodeAnchors]; if (!sourceCodeAnchors) { @@ -98,14 +102,16 @@ */ static _unbindUILocation(anchor) { const info = Components.Linkifier._linkInfo(anchor); - if (!info.uiLocation) + if (!info.uiLocation) { return; + } const uiSourceCode = info.uiLocation.uiSourceCode; info.uiLocation = null; const sourceCodeAnchors = uiSourceCode[Components.Linkifier._sourceCodeAnchors]; - if (sourceCodeAnchors) + if (sourceCodeAnchors) { sourceCodeAnchors.delete(anchor); + } } /** @@ -155,17 +161,20 @@ sourceURL, {className: classes, lineNumber: lineNumber, columnNumber: columnNumber, maxLength: this._maxLength}); } - if (!target || target.isDisposed()) + if (!target || target.isDisposed()) { return fallbackAnchor; + } const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return fallbackAnchor; + } const rawLocation = (scriptId ? debuggerModel.createRawLocationByScriptId(scriptId, lineNumber, columnNumber || 0) : null) || debuggerModel.createRawLocationByURL(sourceURL, lineNumber, columnNumber || 0); - if (!rawLocation) + if (!rawLocation) { return fallbackAnchor; + } const anchor = Components.Linkifier._createLink('', classes || ''); const info = Components.Linkifier._linkInfo(anchor); @@ -236,13 +245,15 @@ columnNumber: topFrame.columnNumber, maxLength: this._maxLength }); - if (target.isDisposed()) + if (target.isDisposed()) { return fallbackAnchor; + } const debuggerModel = target.model(SDK.DebuggerModel); const rawLocations = debuggerModel.createRawLocationsByStackTrace(stackTrace); - if (rawLocations.length === 0) + if (rawLocations.length === 0) { return fallbackAnchor; + } const anchor = Components.Linkifier._createLink('', classes || ''); const info = Components.Linkifier._linkInfo(anchor); @@ -283,8 +294,9 @@ } dispose() { - for (const target of this._anchorsByTarget.keysArray()) + for (const target of this._anchorsByTarget.keysArray()) { this.targetRemoved(target); + } SDK.targetManager.unobserveTargets(this); Components.Linkifier._instances.delete(this); } @@ -296,16 +308,18 @@ _updateAnchor(anchor, liveLocation) { Components.Linkifier._unbindUILocation(anchor); const uiLocation = liveLocation.uiLocation(); - if (!uiLocation) + if (!uiLocation) { return; + } Components.Linkifier._bindUILocation(anchor, uiLocation); const text = uiLocation.linkText(true /* skipTrim */); Components.Linkifier._setTrimmedText(anchor, text, this._maxLength); let titleText = uiLocation.uiSourceCode.url(); - if (typeof uiLocation.lineNumber === 'number') + if (typeof uiLocation.lineNumber === 'number') { titleText += ':' + (uiLocation.lineNumber + 1); + } anchor.title = titleText; anchor.classList.toggle('webkit-html-blackbox-link', liveLocation.isBlackboxed()); Components.Linkifier._updateLinkDecorations(anchor); @@ -316,12 +330,15 @@ */ static _updateLinkDecorations(anchor) { const info = Components.Linkifier._linkInfo(anchor); - if (!info || !info.enableDecorator) + if (!info || !info.enableDecorator) { return; - if (!Components.Linkifier._decorator || !info.uiLocation) + } + if (!Components.Linkifier._decorator || !info.uiLocation) { return; - if (info.icon && info.icon.parentElement) + } + if (info.icon && info.icon.parentElement) { anchor.removeChild(info.icon); + } const icon = Components.Linkifier._decorator.linkIcon(info.uiLocation.uiSourceCode); if (icon) { icon.style.setProperty('margin-right', '2px'); @@ -350,15 +367,18 @@ } let linkText = text || Bindings.displayNameForURL(url); - if (typeof lineNumber === 'number' && !text) + if (typeof lineNumber === 'number' && !text) { linkText += ':' + (lineNumber + 1); + } const title = linkText !== url ? url : ''; const link = Components.Linkifier._createLink(linkText, className, maxLength, title, url, preventClick); const info = Components.Linkifier._linkInfo(link); - if (typeof lineNumber === 'number') + if (typeof lineNumber === 'number') { info.lineNumber = lineNumber; - if (typeof columnNumber === 'number') + } + if (typeof columnNumber === 'number') { info.columnNumber = columnNumber; + } return link; } @@ -386,10 +406,12 @@ static _createLink(text, className, maxLength, title, href, preventClick) { const link = createElementWithClass('span', className); link.classList.add('devtools-link'); - if (title) + if (title) { link.title = title; - if (href) + } + if (href) { link.href = href; + } Components.Linkifier._setTrimmedText(link, text, maxLength); link[Components.Linkifier._infoSymbol] = { icon: null, @@ -404,12 +426,14 @@ }; if (!preventClick) { link.addEventListener('click', event => { - if (Components.Linkifier._handleClick(event)) + if (Components.Linkifier._handleClick(event)) { event.consume(true); + } }, false); link.addEventListener('keydown', event => { - if (isEnterKey(event) && Components.Linkifier._handleClick(event)) + if (isEnterKey(event) && Components.Linkifier._handleClick(event)) { event.consume(true); + } }, false); } else { link.classList.add('devtools-link-prevent-click'); @@ -471,8 +495,9 @@ rightIndex++; leftIndex++; } - if (leftIndex > 0 && string.codePointAt(leftIndex - 1) >= 0x10000) + if (leftIndex > 0 && string.codePointAt(leftIndex - 1) >= 0x10000) { leftIndex--; + } return [string.substring(0, leftIndex), string.substring(leftIndex, rightIndex), string.substring(rightIndex)]; } } @@ -499,8 +524,9 @@ */ static _handleClick(event) { const link = /** @type {!Element} */ (event.currentTarget); - if (UI.isBeingEdited(/** @type {!Node} */ (event.target)) || link.hasSelection()) + if (UI.isBeingEdited(/** @type {!Node} */ (event.target)) || link.hasSelection()) { return false; + } const actions = Components.Linkifier._linkActions(link); if (actions.length) { actions[0].handler.call(null); @@ -553,8 +579,9 @@ static _linkActions(link) { const info = Components.Linkifier._linkInfo(link); const result = []; - if (!info) + if (!info) { return result; + } let url = ''; let uiLocation = null; @@ -588,10 +615,11 @@ title: Common.UIString('Open using %s', title), handler: handler.bind(null, contentProvider, lineNumber) }; - if (title === Components.Linkifier._linkHandlerSetting().get()) + if (title === Components.Linkifier._linkHandlerSetting().get()) { result.unshift(action); - else + } else { result.push(action); + } } } if (resource || info.url) { @@ -689,12 +717,14 @@ */ appendApplicableItems(event, contextMenu, target) { let targetNode = /** @type {!Node} */ (target); - while (targetNode && !targetNode[Components.Linkifier._infoSymbol]) + while (targetNode && !targetNode[Components.Linkifier._infoSymbol]) { targetNode = targetNode.parentNodeOrShadowHost(); + } const link = /** @type {?Element} */ (targetNode); const actions = Components.Linkifier._linkActions(link); - for (const action of actions) + for (const action of actions) { contextMenu.section(action.section).appendItem(action.title, action.handler); + } } }; @@ -752,8 +782,9 @@ */ appendApplicableItems(event, contextMenu, target) { const contentProvider = /** @type {!Common.ContentProvider} */ (target); - if (!contentProvider.contentURL()) + if (!contentProvider.contentURL()) { return; + } contextMenu.revealSection().appendItem( UI.openLinkExternallyLabel(), () => InspectorFrontendHost.openInNewTab(contentProvider.contentURL())); @@ -762,8 +793,9 @@ contextMenu.revealSection().appendItem( Common.UIString('Open using %s', title), handler.bind(null, contentProvider, 0)); } - if (contentProvider instanceof SDK.NetworkRequest) + if (contentProvider instanceof SDK.NetworkRequest) { return; + } contextMenu.clipboardSection().appendItem( UI.copyLinkAddressLabel(), () => InspectorFrontendHost.copyText(contentProvider.contentURL()));
diff --git a/third_party/blink/renderer/devtools/front_end/components/Reload.js b/third_party/blink/renderer/devtools/front_end/components/Reload.js index 105f5c97..5544717 100644 --- a/third_party/blink/renderer/devtools/front_end/components/Reload.js +++ b/third_party/blink/renderer/devtools/front_end/components/Reload.js
@@ -3,7 +3,8 @@ // found in the LICENSE file. Components.reload = function() { if (Components.dockController.canDock() && - Components.dockController.dockSide() === Components.DockController.State.Undocked) + Components.dockController.dockSide() === Components.DockController.State.Undocked) { InspectorFrontendHost.setIsDocked(true, function() {}); + } window.location.reload(); };
diff --git a/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js b/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js index 234e7df..5a7f851 100644 --- a/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js +++ b/third_party/blink/renderer/devtools/front_end/components/TargetDetachedDialog.js
@@ -11,8 +11,9 @@ */ constructor(target) { super(target); - if (target.parentTarget()) + if (target.parentTarget()) { return; + } target.registerInspectorDispatcher(this); target.inspectorAgent().enable(); this._hideCrashedDialog = null;
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js index d21cf5a..5560094 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleContextSelector.js
@@ -57,13 +57,16 @@ SDK.OverlayModel.hideDOMNodeHighlight(); if (to && to.frameId) { const overlayModel = to.target().model(SDK.OverlayModel); - if (overlayModel) + if (overlayModel) { overlayModel.highlightFrame(to.frameId); + } } - if (fromElement) + if (fromElement) { fromElement.classList.remove('highlighted'); - if (toElement) + } + if (toElement) { toElement.classList.add('highlighted'); + } } /** @@ -77,8 +80,9 @@ if (executionContext.frameId) { const resourceTreeModel = target.model(SDK.ResourceTreeModel); const frame = resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); - if (frame) + if (frame) { label = label || frame.displayName(); + } } label = label || executionContext.origin; @@ -92,8 +96,9 @@ _depthFor(executionContext) { let target = executionContext.target(); let depth = 0; - if (!executionContext.isDefault) + if (!executionContext.isDefault) { depth++; + } if (executionContext.frameId) { const resourceTreeModel = target.model(SDK.ResourceTreeModel); let frame = resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); @@ -120,12 +125,14 @@ * @return {?Element} */ _badgeFor(executionContext) { - if (!executionContext.frameId || !executionContext.isDefault) + if (!executionContext.frameId || !executionContext.isDefault) { return null; + } const resourceTreeModel = executionContext.target().model(SDK.ResourceTreeModel); const frame = resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); - if (!frame) + if (!frame) { return null; + } const badgePool = new ProductRegistry.BadgePool(); this._badgePoolForExecutionContext.set(executionContext, badgePool); return badgePool.badgeForFrame(frame); @@ -136,8 +143,9 @@ */ _disposeExecutionContextBadge(executionContext) { const badgePool = this._badgePoolForExecutionContext.get(executionContext); - if (!badgePool) + if (!badgePool) { return; + } badgePool.reset(); this._badgePoolForExecutionContext.delete(executionContext); } @@ -148,8 +156,9 @@ _executionContextCreated(executionContext) { this._items.insertWithComparator(executionContext, executionContext.runtimeModel.executionContextComparator()); - if (executionContext === UI.context.flavor(SDK.ExecutionContext)) + if (executionContext === UI.context.flavor(SDK.ExecutionContext)) { this._dropDown.selectItem(executionContext); + } } /** @@ -165,8 +174,9 @@ */ _onExecutionContextChanged(event) { const executionContext = /** @type {!SDK.ExecutionContext} */ (event.data); - if (this._items.indexOf(executionContext) === -1) + if (this._items.indexOf(executionContext) === -1) { return; + } this._executionContextDestroyed(executionContext); this._executionContextCreated(executionContext); } @@ -176,8 +186,9 @@ */ _executionContextDestroyed(executionContext) { const index = this._items.indexOf(executionContext); - if (index === -1) + if (index === -1) { return; + } this._disposeExecutionContextBadge(executionContext); this._items.remove(index); } @@ -203,13 +214,15 @@ * @return {boolean} */ _isTopContext(executionContext) { - if (!executionContext || !executionContext.isDefault) + if (!executionContext || !executionContext.isDefault) { return false; + } const resourceTreeModel = executionContext.target().model(SDK.ResourceTreeModel); const frame = executionContext.frameId && resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); - if (!frame) + if (!frame) { return false; + } return frame.isTopFrame(); } @@ -234,8 +247,9 @@ */ modelRemoved(runtimeModel) { for (let i = this._items.length - 1; i >= 0; i--) { - if (this._items.at(i).runtimeModel === runtimeModel) + if (this._items.at(i).runtimeModel === runtimeModel) { this._executionContextDestroyed(this._items.at(i)); + } } } @@ -271,18 +285,21 @@ const resourceTreeModel = target.model(SDK.ResourceTreeModel); frame = resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); } - if (executionContext.origin.startsWith('chrome-extension://')) + if (executionContext.origin.startsWith('chrome-extension://')) { return Common.UIString('Extension'); + } if (!frame || !frame.parentFrame || frame.parentFrame.securityOrigin !== executionContext.origin) { const url = executionContext.origin.asParsedURL(); - if (url) + if (url) { return url.domain(); + } } if (frame) { const callFrame = frame.findCreationCallFrame(callFrame => !!callFrame.url); - if (callFrame) + if (callFrame) { return new Common.ParsedURL(callFrame.url).domain(); + } return Common.UIString('IFrame'); } return ''; @@ -313,8 +330,9 @@ _callFrameSelectedInUI() { const callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); const callFrameContext = callFrame && callFrame.script.executionContext(); - if (callFrameContext) + if (callFrameContext) { UI.context.setFlavor(SDK.ExecutionContext, callFrameContext); + } } /** @@ -336,8 +354,9 @@ _frameNavigated(event) { const frame = /** @type {!SDK.ResourceTreeFrame} */ (event.data); const runtimeModel = frame.resourceTreeModel().target().model(SDK.RuntimeModel); - if (!runtimeModel) + if (!runtimeModel) { return; + } for (const executionContext of runtimeModel.executionContexts()) { if (frame.id === executionContext.frameId) { this._disposeExecutionContextBadge(executionContext);
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleFilter.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleFilter.js index 5a86749..bb8b8a9 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleFilter.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleFilter.js
@@ -21,8 +21,9 @@ */ static allLevelsFilterValue() { const result = {}; - for (const name of Object.values(SDK.ConsoleMessage.MessageLevel)) + for (const name of Object.values(SDK.ConsoleMessage.MessageLevel)) { result[name] = true; + } return result; } @@ -62,39 +63,47 @@ const message = viewMessage.consoleMessage(); if (this.executionContext && (this.executionContext.runtimeModel !== message.runtimeModel() || - this.executionContext.id !== message.executionContextId)) + this.executionContext.id !== message.executionContextId)) { return false; + } if (message.type === SDK.ConsoleMessage.MessageType.Command || - message.type === SDK.ConsoleMessage.MessageType.Result || message.isGroupMessage()) + message.type === SDK.ConsoleMessage.MessageType.Result || message.isGroupMessage()) { return true; + } - if (message.level && !this.levelsMask[/** @type {string} */ (message.level)]) + if (message.level && !this.levelsMask[/** @type {string} */ (message.level)]) { return false; + } for (const filter of this.parsedFilters) { if (!filter.key) { - if (filter.regex && viewMessage.matchesFilterRegex(filter.regex) === filter.negative) + if (filter.regex && viewMessage.matchesFilterRegex(filter.regex) === filter.negative) { return false; - if (filter.text && viewMessage.matchesFilterText(filter.text) === filter.negative) + } + if (filter.text && viewMessage.matchesFilterText(filter.text) === filter.negative) { return false; + } } else { switch (filter.key) { case Console.ConsoleFilter.FilterType.Context: - if (!passesFilter(filter, message.context, false /* exactMatch */)) + if (!passesFilter(filter, message.context, false /* exactMatch */)) { return false; + } break; case Console.ConsoleFilter.FilterType.Source: const sourceNameForMessage = message.source ? SDK.ConsoleMessage.MessageSourceDisplayName.get( /** @type {!SDK.ConsoleMessage.MessageSource} */ (message.source)) : message.source; - if (!passesFilter(filter, sourceNameForMessage, true /* exactMatch */)) + if (!passesFilter(filter, sourceNameForMessage, true /* exactMatch */)) { return false; + } break; case Console.ConsoleFilter.FilterType.Url: - if (!passesFilter(filter, message.url, false /* exactMatch */)) + if (!passesFilter(filter, message.url, false /* exactMatch */)) { return false; + } break; } } @@ -108,16 +117,20 @@ * @return {boolean} */ function passesFilter(filter, value, exactMatch) { - if (!filter.text) + if (!filter.text) { return !!value === filter.negative; - if (!value) + } + if (!value) { return !filter.text === !filter.negative; + } const filterText = /** @type {string} */ (filter.text).toLowerCase(); const lowerCaseValue = value.toLowerCase(); - if (exactMatch && (lowerCaseValue === filterText) === filter.negative) + if (exactMatch && (lowerCaseValue === filterText) === filter.negative) { return false; - if (!exactMatch && lowerCaseValue.includes(filterText) === filter.negative) + } + if (!exactMatch && lowerCaseValue.includes(filterText) === filter.negative) { return false; + } return true; } }
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsolePanel.js b/third_party/blink/renderer/devtools/front_end/console/ConsolePanel.js index 9a16cf0..c55d029 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsolePanel.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsolePanel.js
@@ -53,8 +53,9 @@ wasShown() { super.wasShown(); const wrapper = Console.ConsolePanel.WrapperView._instance; - if (wrapper && wrapper.isShowing()) + if (wrapper && wrapper.isShowing()) { UI.inspectorView.setDrawerMinimized(true); + } this._view.show(this.element); Console.ConsolePanel._updateContextFlavor(); } @@ -67,8 +68,9 @@ // The minimized drawer has 0 height, and showing Console inside may set // Console's scrollTop to 0. Unminimize before calling show to avoid this. UI.inspectorView.setDrawerMinimized(false); - if (Console.ConsolePanel.WrapperView._instance) + if (Console.ConsolePanel.WrapperView._instance) { Console.ConsolePanel.WrapperView._instance._showViewInWrapper(); + } Console.ConsolePanel._updateContextFlavor(); } @@ -98,10 +100,11 @@ * @override */ wasShown() { - if (!Console.ConsolePanel.instance().isShowing()) + if (!Console.ConsolePanel.instance().isShowing()) { this._showViewInWrapper(); - else + } else { UI.inspectorView.setDrawerMinimized(true); + } Console.ConsolePanel._updateContextFlavor(); }
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js b/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js index 484211f..3024e3c 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js
@@ -13,16 +13,18 @@ /** @type {!Set<!Console.ConsolePin>} */ this._pins = new Set(); this._pinsSetting = Common.settings.createLocalSetting('consolePins', []); - for (const expression of this._pinsSetting.get()) + for (const expression of this._pinsSetting.get()) { this.addPin(expression); + } } /** * @override */ willHide() { - for (const pin of this._pins) + for (const pin of this._pins) { pin.setHovered(false); + } } _savePins() { @@ -50,8 +52,9 @@ } _removeAllPins() { - for (const pin of this._pins) + for (const pin of this._pins) { this._removePin(pin); + } } /** @@ -72,8 +75,9 @@ this.contentElement.appendChild(pin.element()); this._pins.add(pin); this._savePins(); - if (userGesture) + if (userGesture) { pin.focus(); + } this.update(); } @@ -81,10 +85,12 @@ * @override */ doUpdate() { - if (!this._pins.size || !this.isShowing()) + if (!this._pins.size || !this.isShowing()) { return Promise.resolve(); - if (this.isShowing()) + } + if (this.isShowing()) { this.update(); + } const updatePromises = Array.from(this._pins, pin => pin.updatePreview()); return Promise.all(updatePromises).then(this._updatedForTest.bind(this)); } @@ -157,14 +163,16 @@ event.consume(); return; } - if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code) + if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code) { this._editor.setText(this._committedExpression); + } }, true); this._editor.widget().element.addEventListener('focusout', event => { const text = this._editor.text(); const trimmedText = text.trim(); - if (text.length !== trimmedText.length) + if (text.length !== trimmedText.length) { this._editor.setText(trimmedText); + } this._committedExpression = trimmedText; pinPane._savePins(); this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity, Infinity)); @@ -176,11 +184,13 @@ * @param {boolean} hovered */ setHovered(hovered) { - if (this._hovered === hovered) + if (this._hovered === hovered) { return; + } this._hovered = hovered; - if (!hovered && this._lastNode) + if (!hovered && this._lastNode) { SDK.OverlayModel.hideDOMNodeHighlight(); + } } /** @@ -218,8 +228,9 @@ * @return {!Promise} */ async updatePreview() { - if (!this._editor) + if (!this._editor) { return; + } const text = this._editor.textWithCurrentSuggestion().trim(); const isEditing = this._pinElement.hasFocus(); const throwOnSideEffect = isEditing && text !== this._committedExpression; @@ -227,8 +238,9 @@ const executionContext = UI.context.flavor(SDK.ExecutionContext); const {preview, result} = await ObjectUI.JavaScriptREPL.evaluateAndBuildPreview( text, throwOnSideEffect, timeout, !isEditing /* allowErrors */, 'console'); - if (this._lastResult && this._lastExecutionContext) + if (this._lastResult && this._lastExecutionContext) { this._lastExecutionContext.runtimeModel.releaseEvaluationResult(this._lastResult); + } this._lastResult = result || null; this._lastExecutionContext = executionContext || null; @@ -248,13 +260,15 @@ } let node = null; - if (result && result.object && result.object.type === 'object' && result.object.subtype === 'node') + if (result && result.object && result.object.type === 'object' && result.object.subtype === 'node') { node = result.object; + } if (this._hovered) { - if (node) + if (node) { SDK.OverlayModel.highlightObjectAsDOMNode(node); - else if (this._lastNode) + } else if (this._lastNode) { SDK.OverlayModel.hideDOMNodeHighlight(); + } } this._lastNode = node || null;
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js b/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js index 80299e5f..3be491f5 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsolePrompt.js
@@ -67,8 +67,9 @@ this.setText(this._initialText); delete this._initialText; - if (this.hasFocus()) + if (this.hasFocus()) { this.focus(); + } this.element.removeAttribute('tabindex'); this._editor.widget().element.tabIndex = -1; @@ -82,8 +83,9 @@ _eagerSettingChanged() { const enabled = this._eagerEvalSetting.get(); this._eagerPreviewElement.classList.toggle('hidden', !enabled); - if (enabled) + if (enabled) { this._requestPreview(); + } } /** @@ -113,8 +115,9 @@ const {preview, result} = await ObjectUI.JavaScriptREPL.evaluateAndBuildPreview(text, true /* throwOnSideEffect */, 500); this._innerPreviewElement.removeChildren(); - if (preview.deepTextContent() !== this._editor.textWithCurrentSuggestion().trim()) + if (preview.deepTextContent() !== this._editor.textWithCurrentSuggestion().trim()) { this._innerPreviewElement.appendChild(preview); + } if (result && result.object && result.object.subtype === 'node') { this._highlightingNode = true; SDK.OverlayModel.highlightObjectAsDOMNode(result.object); @@ -122,8 +125,9 @@ this._highlightingNode = false; SDK.OverlayModel.hideDOMNodeHighlight(); } - if (result) + if (result) { executionContext.runtimeModel.releaseEvaluationResult(result); + } } /** @@ -144,8 +148,9 @@ } clearAutocomplete() { - if (this._editor) + if (this._editor) { this._editor.clearAutocomplete(); + } } /** @@ -156,18 +161,20 @@ } moveCaretToEndOfPrompt() { - if (this._editor) + if (this._editor) { this._editor.setSelection(TextUtils.TextRange.createFromLocation(Infinity, Infinity)); + } } /** * @param {string} text */ setText(text) { - if (this._editor) + if (this._editor) { this._editor.setText(text); - else + } else { this._initialText = text; + } this.dispatchEventToListeners(Console.ConsolePrompt.Events.TextChanged); } @@ -199,16 +206,18 @@ switch (keyboardEvent.keyCode) { case UI.KeyboardShortcut.Keys.Up.code: const startY = this._editor.visualCoordinates(0, 0).y; - if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== startY) + if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== startY) { break; + } newText = this._history.previous(this.text()); isPrevious = true; break; case UI.KeyboardShortcut.Keys.Down.code: const fullRange = this._editor.fullRange(); const endY = this._editor.visualCoordinates(fullRange.endLine, fullRange.endColumn).y; - if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== endY) + if (keyboardEvent.shiftKey || !selection.isEmpty() || cursorY !== endY) { break; + } newText = this._history.next(); break; case UI.KeyboardShortcut.Keys.P.code: // Ctrl+P = Previous @@ -220,35 +229,40 @@ break; case UI.KeyboardShortcut.Keys.N.code: // Ctrl+N = Next if (Host.isMac() && keyboardEvent.ctrlKey && !keyboardEvent.metaKey && !keyboardEvent.altKey && - !keyboardEvent.shiftKey) + !keyboardEvent.shiftKey) { newText = this._history.next(); + } break; case UI.KeyboardShortcut.Keys.Enter.code: this._enterKeyPressed(keyboardEvent); break; case UI.KeyboardShortcut.Keys.Tab.code: - if (!this.text()) + if (!this.text()) { keyboardEvent.consume(); + } break; } - if (newText === undefined) + if (newText === undefined) { return; + } keyboardEvent.consume(true); this.setText(newText); - if (isPrevious) + if (isPrevious) { this._editor.setSelection(TextUtils.TextRange.createFromLocation(0, Infinity)); - else + } else { this.moveCaretToEndOfPrompt(); + } } /** * @return {!Promise<boolean>} */ async _enterWillEvaluate() { - if (!this._isCaretAtEndOfPrompt()) + if (!this._isCaretAtEndOfPrompt()) { return true; + } return await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(this.text()); } @@ -263,8 +277,9 @@ * @param {!KeyboardEvent} event */ async _enterKeyPressed(event) { - if (event.altKey || event.ctrlKey || event.shiftKey) + if (event.altKey || event.ctrlKey || event.shiftKey) { return; + } event.consume(true); @@ -273,13 +288,15 @@ this.clearAutocomplete(); const str = this.text(); - if (!str.length) + if (!str.length) { return; + } - if (await this._enterWillEvaluate()) + if (await this._enterWillEvaluate()) { await this._appendCommand(str, true); - else + } else { this._editor.newlineAndIndent(); + } this._enterProcessedForTest(); } @@ -297,8 +314,9 @@ SDK.consoleModel.evaluateCommandInConsole( executionContext, message, wrappedResult.text, useCommandLineAPI, /* awaitPromise */ wrappedResult.preprocessed); - if (Console.ConsolePanel.instance().isShowing()) + if (Console.ConsolePanel.instance().isShowing()) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.CommandEvaluatedInConsolePanel); + } } } @@ -312,17 +330,20 @@ */ _historyCompletions(prefix, force) { const text = this.text(); - if (!this._addCompletionsFromHistory || !this._isCaretAtEndOfPrompt() || (!text && !force)) + if (!this._addCompletionsFromHistory || !this._isCaretAtEndOfPrompt() || (!text && !force)) { return []; + } const result = []; const set = new Set(); const data = this._history.historyData(); for (let i = data.length - 1; i >= 0 && result.length < 50; --i) { const item = data[i]; - if (!item.startsWith(text)) + if (!item.startsWith(text)) { continue; - if (set.has(item)) + } + if (set.has(item)) { continue; + } set.add(item); result.push( {text: item.substring(text.length - prefix.length), iconType: 'smallicon-text-prompt', isSecondary: true}); @@ -334,10 +355,11 @@ * @override */ focus() { - if (this._editor) + if (this._editor) { this._editor.widget().focus(); - else + } else { this.element.focus(); + } } /** @@ -400,8 +422,9 @@ } this._historyOffset = 1; - if (text === this._currentHistoryItem()) + if (text === this._currentHistoryItem()) { return; + } this._data.push(text); } @@ -410,8 +433,9 @@ * @param {string} currentText */ _pushCurrentText(currentText) { - if (this._uncommittedIsTop) - this._data.pop(); // Throw away obsolete uncommitted text. + if (this._uncommittedIsTop) { + this._data.pop(); + } // Throw away obsolete uncommitted text. this._uncommittedIsTop = true; this._data.push(currentText); } @@ -421,10 +445,12 @@ * @return {string|undefined} */ previous(currentText) { - if (this._historyOffset > this._data.length) + if (this._historyOffset > this._data.length) { return undefined; - if (this._historyOffset === 1) + } + if (this._historyOffset === 1) { this._pushCurrentText(currentText); + } ++this._historyOffset; return this._currentHistoryItem(); } @@ -433,8 +459,9 @@ * @return {string|undefined} */ next() { - if (this._historyOffset === 1) + if (this._historyOffset === 1) { return undefined; + } --this._historyOffset; return this._currentHistoryItem(); }
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleSidebar.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleSidebar.js index 8154fb9..d3292fc34 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleSidebar.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleSidebar.js
@@ -67,16 +67,18 @@ } clear() { - for (const treeElement of this._treeElements) + for (const treeElement of this._treeElements) { treeElement.clear(); + } } /** * @param {!Console.ConsoleViewMessage} viewMessage */ onMessageAdded(viewMessage) { - for (const treeElement of this._treeElements) + for (const treeElement of this._treeElements) { treeElement.onMessageAdded(viewMessage); + } } /** @@ -84,8 +86,9 @@ * @return {boolean} */ shouldBeVisible(viewMessage) { - if (!this._selectedTreeElement) + if (!this._selectedTreeElement) { return true; + } return this._selectedTreeElement._filter.shouldBeVisible(viewMessage); } @@ -113,8 +116,9 @@ this._filter = filter; this._countElement = this.listItemElement.createChild('span', 'count'); const leadingIcons = [UI.Icon.create('largeicon-navigator-file')]; - if (badge) + if (badge) { leadingIcons.push(badge); + } this.setLeadingIcons(leadingIcons); this._messageCount = 0; } @@ -183,8 +187,9 @@ const message = viewMessage.consoleMessage(); const shouldIncrementCounter = message.type !== SDK.ConsoleMessage.MessageType.Command && message.type !== SDK.ConsoleMessage.MessageType.Result && !message.isGroupMessage(); - if (!this._filter.shouldBeVisible(viewMessage) || !shouldIncrementCounter) + if (!this._filter.shouldBeVisible(viewMessage) || !shouldIncrementCounter) { return; + } const child = this._childElement(message.url); child.incrementAndUpdateCounter(); this._messageCount++; @@ -198,20 +203,23 @@ _childElement(url) { const urlValue = url || null; let child = this._urlTreeElements.get(urlValue); - if (child) + if (child) { return child; + } const filter = this._filter.clone(); const parsedURL = urlValue ? urlValue.asParsedURL() : null; - if (urlValue) + if (urlValue) { filter.name = parsedURL ? parsedURL.displayName : urlValue; - else + } else { filter.name = Common.UIString('<other>'); + } filter.parsedFilters.push({key: Console.ConsoleFilter.FilterType.Url, text: urlValue, negative: false}); const badge = parsedURL ? this._badgePool.badgeForURL(parsedURL) : null; child = new Console.ConsoleSidebar.URLGroupTreeElement(filter, badge); - if (urlValue) + if (urlValue) { child.tooltip = urlValue; + } this._urlTreeElements.set(urlValue, child); this.appendChild(child); return child;
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js index d7ab2c1..7581535 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js
@@ -57,8 +57,9 @@ this._splitWidget.hideSidebar(); this._splitWidget.enableShowModeSaving(); this._isSidebarOpen = this._splitWidget.showMode() === UI.SplitWidget.ShowMode.Both; - if (this._isSidebarOpen) + if (this._isSidebarOpen) { this._filter._levelMenuButton.setEnabled(false); + } this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, event => { this._isSidebarOpen = event.data === UI.SplitWidget.ShowMode.Both; this._filter._levelMenuButton.setEnabled(!this._isSidebarOpen); @@ -151,8 +152,9 @@ const userGestureCheckbox = new UI.ToolbarSettingCheckbox(Common.settings.moduleSetting('consoleUserActivationEval')); settingsToolbarRight.appendToolbarItem(userGestureCheckbox); - if (!this._showSettingsPaneSetting.get()) + if (!this._showSettingsPaneSetting.get()) { settingsPane.element.classList.add('hidden'); + } this._showSettingsPaneSetting.addChangeListener( () => settingsPane.element.classList.toggle('hidden', !this._showSettingsPaneSetting.get())); @@ -212,8 +214,9 @@ this._messagesElement.addEventListener('keydown', this._messagesKeyDown.bind(this), false); this._prompt.element.addEventListener('focusin', () => { - if (this._isScrolledToBottom()) + if (this._isScrolledToBottom()) { this._viewport.setStickToBottom(true); + } }); this._consoleHistoryAutocompleteSetting.addChangeListener(this._consoleHistoryAutocompleteChanged, this); @@ -250,8 +253,9 @@ * @return {!Console.ConsoleView} */ static instance() { - if (!Console.ConsoleView._instance) + if (!Console.ConsoleView._instance) { Console.ConsoleView._instance = new Console.ConsoleView(); + } return Console.ConsoleView._instance; } @@ -264,8 +268,9 @@ this._filter._messageLevelFiltersSetting.get(); this._cancelBuildHiddenCache(); if (this._immediatelyFilterMessagesForTest) { - for (const viewMessage of this._consoleMessages) + for (const viewMessage of this._consoleMessages) { this._computeShouldMessageBeVisible(viewMessage); + } this._updateMessageList(); return; } @@ -390,10 +395,11 @@ * @override */ focus() { - if (this._viewport.hasVirtualSelection()) + if (this._viewport.hasVirtualSelection()) { this._viewport.contentElement().focus(); - else + } else { this._focusPrompt(); + } } _focusPrompt() { @@ -410,10 +416,11 @@ * @override */ restoreScrollPositions() { - if (this._viewport.stickToBottom()) + if (this._viewport.stickToBottom()) { this._immediatelyScrollToBottom(); - else + } else { super.restoreScrollPositions(); + } } /** @@ -422,10 +429,12 @@ onResize() { this._scheduleViewportRefresh(); this._hidePromptSuggestBox(); - if (this._viewport.stickToBottom()) + if (this._viewport.stickToBottom()) { this._immediatelyScrollToBottom(); - for (let i = 0; i < this._visibleViewMessages.length; ++i) + } + for (let i = 0; i < this._visibleViewMessages.length; ++i) { this._visibleViewMessages[i].onResize(); + } } _hidePromptSuggestBox() { @@ -474,8 +483,9 @@ } _updateFilterStatus() { - if (this._hiddenByFilterCount === this._lastShownHiddenByFilterCount) + if (this._hiddenByFilterCount === this._lastShownHiddenByFilterCount) { return; + } this._filterStatusText.setText(ls`${this._hiddenByFilterCount} hidden`); this._filterStatusText.setVisible(!!this._hiddenByFilterCount); this._lastShownHiddenByFilterCount = this._hiddenByFilterCount; @@ -506,10 +516,11 @@ let insertAt; if (!this._consoleMessages.length || - timeComparator(viewMessage, this._consoleMessages[this._consoleMessages.length - 1]) > 0) + timeComparator(viewMessage, this._consoleMessages[this._consoleMessages.length - 1]) > 0) { insertAt = this._consoleMessages.length; - else + } else { insertAt = this._consoleMessages.upperBound(viewMessage, timeComparator); + } const insertedInMiddle = insertAt < this._consoleMessages.length; this._consoleMessages.splice(insertAt, 0, viewMessage); @@ -583,10 +594,11 @@ */ _computeShouldMessageBeVisible(viewMessage) { if (this._filter.shouldBeVisible(viewMessage) && - (!this._isSidebarOpen || this._sidebar.shouldBeVisible(viewMessage))) + (!this._isSidebarOpen || this._sidebar.shouldBeVisible(viewMessage))) { this._shouldBeHiddenCache.delete(viewMessage); - else + } else { this._shouldBeHiddenCache.add(viewMessage); + } } /** @@ -599,27 +611,31 @@ return; } - if (!preventCollapse && this._tryToCollapseMessages(viewMessage, this._visibleViewMessages.peekLast())) + if (!preventCollapse && this._tryToCollapseMessages(viewMessage, this._visibleViewMessages.peekLast())) { return; + } const lastMessage = this._visibleViewMessages.peekLast(); if (viewMessage.consoleMessage().type === SDK.ConsoleMessage.MessageType.EndGroup) { - if (lastMessage && !this._currentGroup.messagesHidden()) + if (lastMessage && !this._currentGroup.messagesHidden()) { lastMessage.incrementCloseGroupDecorationCount(); + } this._currentGroup = this._currentGroup.parentGroup() || this._currentGroup; return; } if (!this._currentGroup.messagesHidden()) { const originatingMessage = viewMessage.consoleMessage().originatingMessage(); - if (lastMessage && originatingMessage && lastMessage.consoleMessage() === originatingMessage) + if (lastMessage && originatingMessage && lastMessage.consoleMessage() === originatingMessage) { viewMessage.toMessageElement().classList.add('console-adjacent-user-command-result'); + } this._visibleViewMessages.push(viewMessage); this._searchMessage(this._visibleViewMessages.length - 1); } - if (viewMessage.consoleMessage().isGroupStartMessage()) + if (viewMessage.consoleMessage().isGroupStartMessage()) { this._currentGroup = new Console.ConsoleGroup(this._currentGroup, viewMessage); + } this._messageAppendedForTests(); } @@ -658,15 +674,17 @@ */ async _onMessageResized(event) { const treeElement = /** @type {!UI.TreeElement} */ (event.data); - if (this._pendingBatchResize || !treeElement.treeOutline) + if (this._pendingBatchResize || !treeElement.treeOutline) { return; + } this._pendingBatchResize = true; await Promise.resolve(); const treeOutlineElement = treeElement.treeOutline.element; this._viewport.setStickToBottom(this._isScrolledToBottom()); // Scroll, in case mutations moved the element below the visible area. - if (treeOutlineElement.offsetHeight <= this._messagesElement.offsetHeight) + if (treeOutlineElement.offsetHeight <= this._messagesElement.offsetHeight) { treeOutlineElement.scrollIntoViewIfNeeded(); + } this._pendingBatchResize = false; } @@ -685,8 +703,9 @@ this._linkifier.reset(); this._badgePool.reset(); this._filter.clear(); - if (hadFocus) + if (hadFocus) { this._prompt.focus(); + } } _handleContextMenuEvent(event) { @@ -715,8 +734,9 @@ if (consoleMessage) { const request = SDK.NetworkLog.requestForConsoleMessage(consoleMessage); - if (request && SDK.NetworkManager.canReplayRequest(request)) + if (request && SDK.NetworkManager.canReplayRequest(request)) { contextMenu.debugSection().appendItem(ls`Replay XHR`, SDK.NetworkManager.replayRequest.bind(null, request)); + } } contextMenu.show(); @@ -735,8 +755,9 @@ /** @const */ const chunkSize = 350; - if (!await stream.open(filename)) + if (!await stream.open(filename)) { return; + } this._progressToolbarItem.element.appendChild(progressIndicator.element); let messageIndex = 0; @@ -768,8 +789,9 @@ viewMessage.consoleMessage().type !== SDK.ConsoleMessage.MessageType.Result && viewMessage.consoleMessage().isEqual(lastMessage.consoleMessage())) { lastMessage.incrementRepeatCount(); - if (viewMessage.isLastInSimilarGroup()) + if (viewMessage.isLastInSimilarGroup()) { lastMessage.setInSimilarGroup(true, true); + } return true; } @@ -785,8 +807,9 @@ let i; for (i = startIndex; i < viewMessages.length; ++i) { this._computeShouldMessageBeVisible(viewMessages[i]); - if (i % 10 === 0 && Date.now() - startTime > 12) + if (i % 10 === 0 && Date.now() - startTime > 12) { break; + } } if (i === viewMessages.length) { @@ -836,8 +859,9 @@ for (let i = 0; i < this._consoleMessages.length; ++i) { const viewMessage = this._consoleMessages[i]; const message = viewMessage.consoleMessage(); - if (alreadyAdded.has(message)) + if (alreadyAdded.has(message)) { continue; + } if (!message.isGroupable()) { this._appendMessageToEnd(viewMessage); @@ -854,8 +878,9 @@ continue; } - if (processedGroupKeys.has(key)) + if (processedGroupKeys.has(key)) { continue; + } if (!viewMessagesInGroup.find(x => this._shouldMessageBeVisible(x))) { // Optimize for speed. @@ -909,8 +934,9 @@ */ _messagesKeyDown(event) { const hasActionModifier = event.ctrlKey || event.altKey || event.metaKey; - if (hasActionModifier || event.key.length !== 1 || UI.isEditing() || this._messagesElement.hasSelection()) + if (hasActionModifier || event.key.length !== 1 || UI.isEditing() || this._messagesElement.hasSelection()) { return; + } this._prompt.moveCaretToEndOfPrompt(); this._focusPrompt(); } @@ -919,8 +945,9 @@ * @param {!Event} event */ _messagesPasted(event) { - if (UI.isEditing()) + if (UI.isEditing()) { return; + } this._prompt.focus(); } @@ -958,8 +985,9 @@ * @param {!Protocol.Runtime.ExceptionDetails=} exceptionDetails */ _printResult(result, originatingConsoleMessage, exceptionDetails) { - if (!result) + if (!result) { return; + } const level = !!exceptionDetails ? SDK.ConsoleMessage.MessageLevel.Error : SDK.ConsoleMessage.MessageLevel.Info; let message; @@ -1026,8 +1054,9 @@ this._regexMatchRanges = []; this._currentMatchRangeIndex = -1; - if (shouldJump) + if (shouldJump) { this._searchShouldJumpBackwards = !!jumpBackwards; + } this._searchProgressIndicator = new UI.ProgressIndicator(); this._searchProgressIndicator.setTitle(Common.UIString('Searching…')); @@ -1064,8 +1093,9 @@ } const startTime = Date.now(); - for (; index < this._visibleViewMessages.length && Date.now() - startTime < 100; ++index) + for (; index < this._visibleViewMessages.length && Date.now() - startTime < 100; ++index) { this._searchMessage(index); + } this._searchableView.updateSearchMatchesCount(this._regexMatchRanges.length); if (typeof this._searchShouldJumpBackwards !== 'undefined' && this._regexMatchRanges.length) { @@ -1089,8 +1119,9 @@ _searchMessage(index) { const message = this._visibleViewMessages[index]; message.setSearchRegex(this._searchRegex); - for (let i = 0; i < message.searchCount(); ++i) + for (let i = 0; i < message.searchCount(); ++i) { this._regexMatchRanges.push({messageIndex: index, matchIndex: i}); + } } /** @@ -1127,8 +1158,9 @@ * @param {number} index */ _jumpToMatch(index) { - if (!this._regexMatchRanges.length) + if (!this._regexMatchRanges.length) { return; + } let matchRange; if (this._currentMatchRangeIndex >= 0) { @@ -1161,8 +1193,9 @@ } _updateStickToBottomOnPointerUp() { - if (!this._muteViewportUpdates) + if (!this._muteViewportUpdates) { return; + } // Delay querying isScrolledToBottom to give time for smooth scroll // events to arrive. The value for the longest timeout duration is @@ -1174,8 +1207,9 @@ */ function updateViewportState() { this._muteViewportUpdates = false; - if (this.isShowing()) + if (this.isShowing()) { this._viewport.setStickToBottom(this._isScrolledToBottom()); + } if (this._maybeDirtyWhileMuted) { this._scheduleViewportRefresh(); delete this._maybeDirtyWhileMuted; @@ -1198,8 +1232,9 @@ const oldStickToBottom = this._viewport.stickToBottom(); const willStickToBottom = this._isScrolledToBottom(); this._viewport.setStickToBottom(willStickToBottom); - if (willStickToBottom && !oldStickToBottom) + if (willStickToBottom && !oldStickToBottom) { this._scheduleViewportRefresh(); + } this._promptTextChangedForTest(); } @@ -1241,8 +1276,9 @@ Common.UIString('Filter'), '', 0.2, 1, Common.UIString('e.g. /event\\d/ -cdn url:a.com'), this._suggestionBuilder.completions.bind(this._suggestionBuilder)); this._textFilterSetting = Common.settings.createSetting('console.textFilter', ''); - if (this._textFilterSetting.get()) + if (this._textFilterSetting.get()) { this._textFilterUI.setValue(this._textFilterSetting.get()); + } this._textFilterUI.addEventListener(UI.ToolbarInput.Event.TextChanged, () => { this._textFilterSetting.set(this._textFilterUI.value()); this._onFilterChanged(); @@ -1271,14 +1307,18 @@ */ onMessageAdded(message) { if (message.type === SDK.ConsoleMessage.MessageType.Command || - message.type === SDK.ConsoleMessage.MessageType.Result || message.isGroupMessage()) + message.type === SDK.ConsoleMessage.MessageType.Result || message.isGroupMessage()) { return; - if (message.context) + } + if (message.context) { this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Context, message.context); - if (message.source) + } + if (message.source) { this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Source, message.source); - if (message.url) + } + if (message.url) { this._suggestionBuilder.addItem(Console.ConsoleFilter.FilterType.Url, message.url); + } } /** @@ -1320,15 +1360,17 @@ for (const name of Object.values(SDK.ConsoleMessage.MessageLevel)) { isAll = isAll && levels[name] === allValue[name]; isDefault = isDefault && levels[name] === defaultValue[name]; - if (levels[name]) + if (levels[name]) { text = text ? Common.UIString('Custom levels') : Common.UIString('%s only', this._levelLabels[name]); + } } - if (isAll) + if (isAll) { text = Common.UIString('All levels'); - else if (isDefault) + } else if (isDefault) { text = Common.UIString('Default levels'); - else + } else { text = text || Common.UIString('Hide all'); + } this._levelMenuButton.element.classList.toggle('warning', !isAll && !isDefault); this._levelMenuButton.setText(text); this._levelMenuButton.setTitle(ls`Log level: ${text}`); @@ -1366,8 +1408,9 @@ * @param {string} url */ addMessageURLFilter(url) { - if (!url) + if (!url) { return; + } const suffix = this._textFilterUI.value() ? ` ${this._textFilterUI.value()}` : ''; this._textFilterUI.setValue(`-url:${url}${suffix}`); this._textFilterSetting.set(this._textFilterUI.value());
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js index a6e2c496..50b60cc 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleViewMessage.js
@@ -73,16 +73,19 @@ * @override */ wasShown() { - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.updateWidths(); + } this._isVisible = true; } onResize() { - if (!this._isVisible) + if (!this._isVisible) { return; - if (this._dataGrid) + } + if (this._dataGrid) { this._dataGrid.onResize(); + } } /** @@ -97,15 +100,17 @@ * @return {number} */ fastHeight() { - if (this._cachedHeight) + if (this._cachedHeight) { return this._cachedHeight; + } // This value reflects the 18px min-height of .console-message, plus the // 1px border of .console-message-wrapper. Keep in sync with consoleView.css. const defaultConsoleRowHeight = 19; if (this._message.type === SDK.ConsoleMessage.MessageType.Table) { const table = this._message.parameters[0]; - if (table && table.preview) + if (table && table.preview) { return defaultConsoleRowHeight * table.preview.properties.length; + } } return defaultConsoleRowHeight; } @@ -123,17 +128,21 @@ _buildTableMessage() { const formattedMessage = createElementWithClass('span', 'source-code'); this._anchorElement = this._buildMessageAnchor(); - if (this._anchorElement) + if (this._anchorElement) { formattedMessage.appendChild(this._anchorElement); + } const badgeElement = this._buildMessageBadge(); - if (badgeElement) + if (badgeElement) { formattedMessage.appendChild(badgeElement); + } let table = this._message.parameters && this._message.parameters.length ? this._message.parameters[0] : null; - if (table) + if (table) { table = this._parameterToRemoteObject(table); - if (!table || !table.preview) + } + if (!table || !table.preview) { return this._buildMessage(); + } const rawValueColumnSymbol = Symbol('rawValueColumn'); const columnNames = []; @@ -142,12 +151,13 @@ for (let i = 0; i < preview.properties.length; ++i) { const rowProperty = preview.properties[i]; let rowSubProperties; - if (rowProperty.valuePreview) + if (rowProperty.valuePreview) { rowSubProperties = rowProperty.valuePreview.properties; - else if (rowProperty.value) + } else if (rowProperty.value) { rowSubProperties = [{name: rawValueColumnSymbol, type: rowProperty.type, value: rowProperty.value}]; - else + } else { continue; + } const rowValue = {}; const maxColumnsToRender = 20; @@ -155,8 +165,9 @@ const cellProperty = rowSubProperties[j]; let columnRendered = columnNames.indexOf(cellProperty.name) !== -1; if (!columnRendered) { - if (columnNames.length === maxColumnsToRender) + if (columnNames.length === maxColumnsToRender) { continue; + } columnRendered = true; columnNames.push(cellProperty.name); } @@ -175,8 +186,9 @@ const rowName = rows[i][0]; const rowValue = rows[i][1]; flatValues.push(rowName); - for (let j = 0; j < columnNames.length; ++j) + for (let j = 0; j < columnNames.length; ++j) { flatValues.push(rowValue[columnNames[j]]); + } } columnNames.unshift(Common.UIString('(index)')); const columnDisplayNames = columnNames.map(name => name === rawValueColumnSymbol ? Common.UIString('Value') : name); @@ -209,10 +221,11 @@ break; case SDK.ConsoleMessage.MessageType.Clear: messageElement = createElementWithClass('span', 'console-info'); - if (Common.moduleSetting('preserveConsoleLog').get()) + if (Common.moduleSetting('preserveConsoleLog').get()) { messageElement.textContent = Common.UIString('console.clear() was prevented due to \'Preserve log\''); - else + } else { messageElement.textContent = Common.UIString('Console was cleared'); + } messageElement.title = ls`Clear all messages with ${UI.shortcutRegistry.shortcutTitleForAction('console.clear')}`; break; @@ -231,8 +244,9 @@ // Fall through. default: { if (this._message.parameters && this._message.parameters.length === 1 && - this._message.parameters[0].type === 'string') + this._message.parameters[0].type === 'string') { messageElement = this._tryFormatAsError(/** @type {string} */ (this._message.parameters[0].value)); + } const args = this._message.parameters || [messageText]; messageElement = messageElement || this._format(args); } @@ -243,15 +257,17 @@ } else { const messageInParameters = this._message.parameters && messageText === /** @type {string} */ (this._message.parameters[0]); - if (this._message.source === SDK.ConsoleMessage.MessageSource.Violation) + if (this._message.source === SDK.ConsoleMessage.MessageSource.Violation) { messageText = Common.UIString('[Violation] %s', messageText); - else if (this._message.source === SDK.ConsoleMessage.MessageSource.Intervention) + } else if (this._message.source === SDK.ConsoleMessage.MessageSource.Intervention) { messageText = Common.UIString('[Intervention] %s', messageText); - else if (this._message.source === SDK.ConsoleMessage.MessageSource.Deprecation) + } else if (this._message.source === SDK.ConsoleMessage.MessageSource.Deprecation) { messageText = Common.UIString('[Deprecation] %s', messageText); + } const args = this._message.parameters || [messageText]; - if (messageInParameters) + if (messageInParameters) { args[0] = messageText; + } messageElement = this._format(args); } } @@ -259,11 +275,13 @@ const formattedMessage = createElementWithClass('span', 'source-code'); this._anchorElement = this._buildMessageAnchor(); - if (this._anchorElement) + if (this._anchorElement) { formattedMessage.appendChild(this._anchorElement); + } const badgeElement = this._buildMessageBadge(); - if (badgeElement) + if (badgeElement) { formattedMessage.appendChild(badgeElement); + } formattedMessage.appendChild(messageElement); return formattedMessage; } @@ -273,8 +291,9 @@ */ _formatAsNetworkRequest() { const request = SDK.NetworkLog.requestForConsoleMessage(this._message); - if (!request) + if (!request) { return null; + } const messageElement = createElement('span'); if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) { messageElement.createTextChild(request.requestMethod + ' '); @@ -283,12 +302,15 @@ linkElement.tabIndex = -1; this._selectableChildren.push({element: linkElement, forceSelect: () => linkElement.focus()}); messageElement.appendChild(linkElement); - if (request.failed) + if (request.failed) { messageElement.createTextChildren(' ', request.localizedFailDescription); - if (request.statusCode !== 0) + } + if (request.statusCode !== 0) { messageElement.createTextChildren(' ', String(request.statusCode)); - if (request.statusText) + } + if (request.statusText) { messageElement.createTextChildren(' (', request.statusText, ')'); + } } else { const messageText = this._message.messageText; const fragment = this._linkifyWithCustomLinkifier(messageText, (text, url, lineNumber, columnNumber) => { @@ -337,8 +359,9 @@ */ _buildMessageBadge() { const badgeElement = this._badgeElement(); - if (!badgeElement) + if (!badgeElement) { return null; + } badgeElement.classList.add('console-message-badge'); return badgeElement; } @@ -347,32 +370,39 @@ * @return {?Element} */ _badgeElement() { - if (this._message._url) + if (this._message._url) { return this._badgePool.badgeForURL(new Common.ParsedURL(this._message._url)); + } if (this._message.stackTrace) { let stackTrace = this._message.stackTrace; while (stackTrace) { for (const callFrame of this._message.stackTrace.callFrames) { - if (callFrame.url) + if (callFrame.url) { return this._badgePool.badgeForURL(new Common.ParsedURL(callFrame.url)); + } } stackTrace = stackTrace.parent; } } - if (!this._message.executionContextId) + if (!this._message.executionContextId) { return null; + } const runtimeModel = this._message.runtimeModel(); - if (!runtimeModel) + if (!runtimeModel) { return null; + } const executionContext = runtimeModel.executionContext(this._message.executionContextId); - if (!executionContext || !executionContext.frameId) + if (!executionContext || !executionContext.frameId) { return null; + } const resourceTreeModel = executionContext.target().model(SDK.ResourceTreeModel); - if (!resourceTreeModel) + if (!resourceTreeModel) { return null; + } const frame = resourceTreeModel.frameForId(executionContext.frameId); - if (!frame || !frame.parentFrame) + if (!frame || !frame.parentFrame) { return null; + } return this._badgePool.badgeForFrame(frame); } @@ -411,15 +441,17 @@ * @param {?Event} event */ function toggleStackTrace(event) { - if (UI.isEditing() || contentElement.hasSelection()) + if (UI.isEditing() || contentElement.hasSelection()) { return; + } this._expandTrace(stackTraceElement.classList.contains('hidden')); event.consume(); } clickableElement.addEventListener('click', toggleStackTrace.bind(this), false); - if (this._message.type === SDK.ConsoleMessage.MessageType.Trace) + if (this._message.type === SDK.ConsoleMessage.MessageType.Trace) { this._expandTrace(true); + } toggleElement._expandStackTraceForTest = this._expandTrace.bind(this, true); return toggleElement; @@ -432,8 +464,9 @@ * @return {?Element} */ _linkifyLocation(url, lineNumber, columnNumber) { - if (!this._message.runtimeModel()) + if (!this._message.runtimeModel()) { return null; + } return this._linkifier.linkifyScriptLocation( this._message.runtimeModel().target(), null, url, lineNumber, columnNumber); } @@ -443,8 +476,9 @@ * @return {?Element} */ _linkifyStackTraceTopFrame(stackTrace) { - if (!this._message.runtimeModel()) + if (!this._message.runtimeModel()) { return null; + } return this._linkifier.linkifyStackTraceTopFrame(this._message.runtimeModel().target(), stackTrace); } @@ -456,8 +490,9 @@ * @return {?Element} */ _linkifyScriptId(scriptId, url, lineNumber, columnNumber) { - if (!this._message.runtimeModel()) + if (!this._message.runtimeModel()) { return null; + } return this._linkifier.linkifyScriptLocation( this._message.runtimeModel().target(), scriptId, url, lineNumber, columnNumber); } @@ -467,13 +502,16 @@ * @return {!SDK.RemoteObject} */ _parameterToRemoteObject(parameter) { - if (parameter instanceof SDK.RemoteObject) + if (parameter instanceof SDK.RemoteObject) { return parameter; + } const runtimeModel = this._message.runtimeModel(); - if (!runtimeModel) + if (!runtimeModel) { return SDK.RemoteObject.fromLocalObject(parameter); - if (typeof parameter === 'object') + } + if (typeof parameter === 'object') { return runtimeModel.createRemoteObject(parameter); + } return runtimeModel.createRemoteObjectFromPrimitiveValue(parameter); } @@ -484,17 +522,20 @@ _format(rawParameters) { // This node is used like a Builder. Values are continually appended onto it. const formattedResult = createElement('span'); - if (this._messagePrefix) + if (this._messagePrefix) { formattedResult.createChild('span').textContent = this._messagePrefix; - if (!rawParameters.length) + } + if (!rawParameters.length) { return formattedResult; + } // Formatting code below assumes that parameters are all wrappers whereas frontend console // API allows passing arbitrary values as messages (strings, numbers, etc.). Wrap them here. // FIXME: Only pass runtime wrappers here. let parameters = []; - for (let i = 0; i < rawParameters.length; ++i) + for (let i = 0; i < rawParameters.length; ++i) { parameters[i] = this._parameterToRemoteObject(rawParameters[i]); + } // There can be string log and string eval result. We distinguish between them based on message type. const shouldFormatMessage = @@ -507,19 +548,22 @@ const result = this._formatWithSubstitutionString( /** @type {string} **/ (parameters[0].description), parameters.slice(1), formattedResult); parameters = result.unusedSubstitutions; - if (parameters.length) + if (parameters.length) { formattedResult.createTextChild(' '); + } } // Single parameter, or unused substitutions from above. for (let i = 0; i < parameters.length; ++i) { // Inline strings when formatting. - if (shouldFormatMessage && parameters[i].type === 'string') + if (shouldFormatMessage && parameters[i].type === 'string') { formattedResult.appendChild(this._linkifyStringAsFragment(parameters[i].description)); - else + } else { formattedResult.appendChild(this._formatParameter(parameters[i], false, true)); - if (i < parameters.length - 1) + } + if (i < parameters.length - 1) { formattedResult.createTextChild(' '); + } } return formattedResult; } @@ -531,8 +575,9 @@ * @return {!Element} */ _formatParameter(output, forceObjectFormat, includePreview) { - if (output.customPreview()) + if (output.customPreview()) { return (new ObjectUI.CustomPreviewComponent(output)).element; + } const type = forceObjectFormat ? 'object' : (output.subtype || output.type); let element; @@ -591,12 +636,14 @@ _formatParameterAsValue(obj) { const result = createElement('span'); const description = obj.description || ''; - if (description.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) + if (description.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) { result.appendChild(UI.createExpandableText(description, Console.ConsoleViewMessage._LongStringVisibleLength)); - else + } else { result.createTextChild(description); - if (obj.objectId) + } + if (obj.objectId) { result.addEventListener('contextmenu', this._contextMenuEventFired.bind(this, obj), false); + } return result; } @@ -618,14 +665,16 @@ titleElement.createTextChild(obj.description || ''); } - if (!obj.hasChildren || obj.customPreview()) + if (!obj.hasChildren || obj.customPreview()) { return titleElement; + } const note = titleElement.createChild('span', 'object-state-note info-note'); - if (this._message.type === SDK.ConsoleMessage.MessageType.QueryObjectResult) + if (this._message.type === SDK.ConsoleMessage.MessageType.QueryObjectResult) { note.title = ls`This value will not be collected until console is cleared.`; - else + } else { note.title = ls`Value below was evaluated just now.`; + } const section = new ObjectUI.ObjectPropertiesSection(obj, titleElement, this._linkifier); section.element.classList.add('console-view-object-properties-section'); @@ -686,8 +735,9 @@ */ _renderPropertyPreviewOrAccessor(object, propertyPath) { const property = propertyPath.peekLast(); - if (property.type === 'accessor') + if (property.type === 'accessor') { return this._formatAsAccessorProperty(object, propertyPath.map(property => property.name), false); + } return this._previewFormatter.renderPropertyPreview( property.type, /** @type {string} */ (property.subtype), property.value); } @@ -700,8 +750,9 @@ const result = createElement('span'); const domModel = remoteObject.runtimeModel().target().model(SDK.DOMModel); - if (!domModel) + if (!domModel) { return result; + } domModel.pushObjectAsNodeToFrontend(remoteObject).then(async node => { if (!node) { result.appendChild(this._formatParameterAsObject(remoteObject, false)); @@ -779,8 +830,9 @@ function onInvokeGetterClick(result) { const wasThrown = result.wasThrown; const object = result.object; - if (!object) + if (!object) { return; + } rootElement.removeChildren(); if (wasThrown) { const element = rootElement.createChild('span'); @@ -795,10 +847,11 @@ const subtype = object.subtype; let description = ''; if (type !== 'function' && object.description) { - if (type === 'string' || subtype === 'regexp') + if (type === 'string' || subtype === 'regexp') { description = object.description.trimMiddle(maxLength); - else + } else { description = object.description.trimEndWithMaxLength(maxLength); + } } rootElement.appendChild(this._previewFormatter.renderPropertyPreview(type, subtype, description)); } @@ -831,16 +884,19 @@ } function floatFormatter(obj) { - if (typeof obj.value !== 'number') + if (typeof obj.value !== 'number') { return 'NaN'; + } return obj.value; } function integerFormatter(obj) { - if (obj.type === 'bigint') + if (obj.type === 'bigint') { return obj.description; - if (typeof obj.value !== 'number') + } + if (typeof obj.value !== 'number') { return 'NaN'; + } return Math.floor(obj.value); } @@ -855,8 +911,9 @@ buffer.setAttribute('style', obj.description); for (let i = 0; i < buffer.style.length; i++) { const property = buffer.style[i]; - if (isWhitelistedProperty(property)) + if (isWhitelistedProperty(property)) { currentStyle[property] = buffer.style[property]; + } } } @@ -867,8 +924,9 @@ '-webkit-border', '-webkit-font', '-webkit-margin', '-webkit-padding', '-webkit-text' ]; for (let i = 0; i < prefixes.length; i++) { - if (property.startsWith(prefixes[i])) + if (property.startsWith(prefixes[i])) { return true; + } } return false; } @@ -900,8 +958,9 @@ a.appendChild(b); return a; } - if (typeof b === 'undefined') + if (typeof b === 'undefined') { return a; + } if (!currentStyle) { a.appendChild(this._linkifyStringAsFragment(String(b))); return a; @@ -917,12 +976,14 @@ wrapper.appendChild(lineFragment); applyCurrentStyle(wrapper); for (const child of wrapper.children) { - if (child.classList.contains('devtools-link')) + if (child.classList.contains('devtools-link')) { this._applyForcedVisibleStyle(child); + } } a.appendChild(wrapper); - if (i < lines.length - 1) + if (i < lines.length - 1) { a.appendChild(createElement('br')); + } } return a; } @@ -931,8 +992,9 @@ * @param {!Element} element */ function applyCurrentStyle(element) { - for (const key in currentStyle) + for (const key in currentStyle) { element.style[key] = currentStyle[key]; + } } // String.format does treat formattedResult like a Builder, result is an object. @@ -950,10 +1012,11 @@ element.style.setProperty('color', themedColor, 'important'); let backgroundColor = 'hsl(0, 0%, 100%)'; - if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) + if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) { backgroundColor = 'hsl(0, 100%, 97%)'; - else if (this._message.level === SDK.ConsoleMessage.MessageLevel.Warning || this._shouldRenderAsWarning()) + } else if (this._message.level === SDK.ConsoleMessage.MessageLevel.Warning || this._shouldRenderAsWarning()) { backgroundColor = 'hsl(50, 100%, 95%)'; + } const themedBackgroundColor = UI.themeSupport.patchColorText(backgroundColor, UI.ThemeSupport.ColorUsage.Background); element.style.setProperty('background-color', themedBackgroundColor, 'important'); @@ -980,12 +1043,14 @@ } updateTimestamp() { - if (!this._contentElement) + if (!this._contentElement) { return; + } if (Common.moduleSetting('consoleTimestampsEnabled').get()) { - if (!this._timestampElement) + if (!this._timestampElement) { this._timestampElement = createElementWithClass('span', 'console-timestamp'); + } this._timestampElement.textContent = UI.formatTimestamp(this._message.timestamp, false) + ' '; this._timestampElement.title = UI.formatTimestamp(this._message.timestamp, true); this._contentElement.insertBefore(this._timestampElement, this._contentElement.firstChild); @@ -1027,8 +1092,9 @@ } resetCloseGroupDecorationCount() { - if (!this._closeGroupDecorationCount) + if (!this._closeGroupDecorationCount) { return; + } this._closeGroupDecorationCount = 0; this._updateCloseGroupDecorations(); } @@ -1039,8 +1105,9 @@ } _updateCloseGroupDecorations() { - if (!this._nestingLevelMarkers) + if (!this._nestingLevelMarkers) { return; + } for (let i = 0, n = this._nestingLevelMarkers.length; i < n; ++i) { const marker = this._nestingLevelMarkers[i]; marker.classList.toggle('group-closed', n - i <= this._closeGroupDecorationCount); @@ -1051,8 +1118,9 @@ * @return {number} */ _focusedChildIndex() { - if (!this._selectableChildren.length) + if (!this._selectableChildren.length) { return -1; + } return this._selectableChildren.findIndex(child => child.element.hasFocus()); } @@ -1060,10 +1128,12 @@ * @param {!Event} event */ _onKeyDown(event) { - if (UI.isEditing() || !this._element.hasFocus() || this._element.hasSelection()) + if (UI.isEditing() || !this._element.hasFocus() || this._element.hasSelection()) { return; - if (this.maybeHandleOnKeyDown(event)) + } + if (this.maybeHandleOnKeyDown(event)) { event.consume(true); + } } /** @@ -1080,16 +1150,18 @@ return true; } } - if (!this._selectableChildren.length) + if (!this._selectableChildren.length) { return false; + } if (event.key === 'ArrowLeft') { this._element.focus(); return true; } if (event.key === 'ArrowRight') { - if (isWrapperFocused && this._selectNearestVisibleChild(0)) + if (isWrapperFocused && this._selectNearestVisibleChild(0)) { return true; + } } if (event.key === 'ArrowUp') { const firstVisibleChild = this._nearestVisibleChild(0); @@ -1101,10 +1173,12 @@ } } if (event.key === 'ArrowDown') { - if (isWrapperFocused && this._selectNearestVisibleChild(0)) + if (isWrapperFocused && this._selectNearestVisibleChild(0)) { return true; - if (!isWrapperFocused && this._selectNearestVisibleChild(focusedChildIndex + 1)) + } + if (!isWrapperFocused && this._selectNearestVisibleChild(focusedChildIndex + 1)) { return true; + } } return false; } @@ -1130,34 +1204,39 @@ */ _nearestVisibleChild(fromIndex, backwards) { const childCount = this._selectableChildren.length; - if (fromIndex < 0 || fromIndex >= childCount) + if (fromIndex < 0 || fromIndex >= childCount) { return null; + } const direction = backwards ? -1 : 1; let index = fromIndex; while (!this._selectableChildren[index].element.offsetParent) { index += direction; - if (index < 0 || index >= childCount) + if (index < 0 || index >= childCount) { return null; + } } return this._selectableChildren[index]; } focusLastChildOrSelf() { - if (this._element && !this._selectNearestVisibleChild(this._selectableChildren.length - 1, true /* backwards */)) + if (this._element && !this._selectNearestVisibleChild(this._selectableChildren.length - 1, true /* backwards */)) { this._element.focus(); + } } /** * @return {!Element} */ contentElement() { - if (this._contentElement) + if (this._contentElement) { return this._contentElement; + } const contentElement = createElementWithClass('div', 'console-message'); - if (this._messageLevelIcon) + if (this._messageLevelIcon) { contentElement.appendChild(this._messageLevelIcon); + } this._contentElement = contentElement; let formattedMessage; @@ -1167,12 +1246,13 @@ this._message.level === SDK.ConsoleMessage.MessageLevel.Error || this._message.level === SDK.ConsoleMessage.MessageLevel.Warning || this._message.type === SDK.ConsoleMessage.MessageType.Trace); - if (this._message.runtimeModel() && shouldIncludeTrace) + if (this._message.runtimeModel() && shouldIncludeTrace) { formattedMessage = this._buildMessageWithStackTrace(); - else if (this._message.type === SDK.ConsoleMessage.MessageType.Table) + } else if (this._message.type === SDK.ConsoleMessage.MessageType.Table) { formattedMessage = this._buildTableMessage(); - else + } else { formattedMessage = this._buildMessage(); + } contentElement.appendChild(formattedMessage); this.updateTimestamp(); @@ -1183,8 +1263,9 @@ * @return {!Element} */ toMessageElement() { - if (this._element) + if (this._element) { return this._element; + } this._element = createElement('div'); this._element.tabIndex = -1; @@ -1194,23 +1275,27 @@ } updateMessageElement() { - if (!this._element) + if (!this._element) { return; + } this._element.className = 'console-message-wrapper'; this._element.removeChildren(); - if (this._message.isGroupStartMessage()) + if (this._message.isGroupStartMessage()) { this._element.classList.add('console-group-title'); - if (this._message.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI) + } + if (this._message.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI) { this._element.classList.add('console-from-api'); + } if (this._inSimilarGroup) { this._similarGroupMarker = this._element.createChild('div', 'nesting-level-marker'); this._similarGroupMarker.classList.toggle('group-closed', this._lastInSimilarGroup); } this._nestingLevelMarkers = []; - for (let i = 0; i < this._nestingLevel; ++i) + for (let i = 0; i < this._nestingLevel; ++i) { this._nestingLevelMarkers.push(this._element.createChild('div', 'nesting-level-marker')); + } this._updateCloseGroupDecorations(); this._element.message = this; @@ -1220,8 +1305,9 @@ break; case SDK.ConsoleMessage.MessageLevel.Info: this._element.classList.add('console-info-level'); - if (this._message.type === SDK.ConsoleMessage.MessageType.System) + if (this._message.type === SDK.ConsoleMessage.MessageType.System) { this._element.classList.add('console-system-type'); + } break; case SDK.ConsoleMessage.MessageLevel.Warning: this._element.classList.add('console-warning-level'); @@ -1231,12 +1317,14 @@ break; } this._updateMessageLevelIcon(); - if (this._shouldRenderAsWarning()) + if (this._shouldRenderAsWarning()) { this._element.classList.add('console-warning-level'); + } this._element.appendChild(this.contentElement()); - if (this._repeatCount > 1) + if (this._repeatCount > 1) { this._showRepeatCountElement(); + } } /** @@ -1261,12 +1349,14 @@ iconType = 'smallicon-error'; accessibleName = ls`Error`; } - if (!iconType && !this._messageLevelIcon) + if (!iconType && !this._messageLevelIcon) { return; + } if (iconType && !this._messageLevelIcon) { this._messageLevelIcon = UI.Icon.create('', 'message-level-icon'); - if (this._contentElement) + if (this._contentElement) { this._contentElement.insertBefore(this._messageLevelIcon, this._contentElement.firstChild); + } } this._messageLevelIcon.setIconType(iconType); UI.ARIAUtils.setAccessibleName(this._messageLevelIcon, accessibleName); @@ -1281,12 +1371,14 @@ resetIncrementRepeatCount() { this._repeatCount = 1; - if (!this._repeatCountElement) + if (!this._repeatCountElement) { return; + } this._repeatCountElement.remove(); - if (this._contentElement) + if (this._contentElement) { this._contentElement.classList.remove('repeated-message'); + } delete this._repeatCountElement; } @@ -1304,8 +1396,9 @@ } _showRepeatCountElement() { - if (!this._element) + if (!this._element) { return; + } if (!this._repeatCountElement) { this._repeatCountElement = createElementWithClass('span', 'console-message-repeat-count', 'dt-small-bubble'); @@ -1322,18 +1415,20 @@ default: this._repeatCountElement.type = 'info'; } - if (this._shouldRenderAsWarning()) + if (this._shouldRenderAsWarning()) { this._repeatCountElement.type = 'warning'; + } this._element.insertBefore(this._repeatCountElement, this._contentElement); this._contentElement.classList.add('repeated-message'); } this._repeatCountElement.textContent = this._repeatCount; let accessibleName = ls`Repeat ${this._repeatCount}`; - if (this._message.level === SDK.ConsoleMessage.MessageLevel.Warning) + if (this._message.level === SDK.ConsoleMessage.MessageLevel.Warning) { accessibleName = ls`Warning ${accessibleName}`; - else if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) + } else if (this._message.level === SDK.ConsoleMessage.MessageLevel.Error) { accessibleName = ls`Error ${accessibleName}`; + } UI.ARIAUtils.setAccessibleName(this._repeatCountElement, accessibleName); } @@ -1348,8 +1443,9 @@ const lines = []; const nodes = this.contentElement().childTextNodes(); const messageContent = nodes.map(Components.Linkifier.untruncatedNodeText).join(''); - for (let i = 0; i < this.repeatCount(); ++i) + for (let i = 0; i < this.repeatCount(); ++i) { lines.push(messageContent); + } return lines.join('\n'); } @@ -1357,20 +1453,23 @@ * @param {?RegExp} regex */ setSearchRegex(regex) { - if (this._searchHiglightNodeChanges && this._searchHiglightNodeChanges.length) + if (this._searchHiglightNodeChanges && this._searchHiglightNodeChanges.length) { UI.revertDomChanges(this._searchHiglightNodeChanges); + } this._searchRegex = regex; this._searchHighlightNodes = []; this._searchHiglightNodeChanges = []; - if (!this._searchRegex) + if (!this._searchRegex) { return; + } const text = this.contentElement().deepTextContent(); let match; this._searchRegex.lastIndex = 0; const sourceRanges = []; - while ((match = this._searchRegex.exec(text)) && match[0]) + while ((match = this._searchRegex.exec(text)) && match[0]) { sourceRanges.push(new TextUtils.SourceRange(match.index, match[0].length)); + } if (sourceRanges.length) { this._searchHighlightNodes = @@ -1413,8 +1512,9 @@ const errorPrefixes = ['EvalError', 'ReferenceError', 'SyntaxError', 'TypeError', 'RangeError', 'Error', 'URIError']; - if (!this._message.runtimeModel() || !errorPrefixes.some(startsWith)) + if (!this._message.runtimeModel() || !errorPrefixes.some(startsWith)) { return null; + } const debuggerModel = this._message.runtimeModel().debuggerModel(); const baseURL = this._message.runtimeModel().target().inspectedURL(); @@ -1424,11 +1524,13 @@ for (let i = 0; i < lines.length; ++i) { position += i > 0 ? lines[i - 1].length + 1 : 0; const isCallFrameLine = /^\s*at\s/.test(lines[i]); - if (!isCallFrameLine && links.length) + if (!isCallFrameLine && links.length) { return null; + } - if (!isCallFrameLine) + if (!isCallFrameLine) { continue; + } let openBracketIndex = -1; let closeBracketIndex = -1; @@ -1436,11 +1538,13 @@ const inBrackets = /\([^\)\(]+\)/g; let lastMatch = null; let currentMatch; - while ((currentMatch = inBracketsWithLineAndColumn.exec(lines[i]))) + while ((currentMatch = inBracketsWithLineAndColumn.exec(lines[i]))) { lastMatch = currentMatch; + } if (!lastMatch) { - while ((currentMatch = inBrackets.exec(lines[i]))) + while ((currentMatch = inBrackets.exec(lines[i]))) { lastMatch = currentMatch; + } } if (lastMatch) { openBracketIndex = lastMatch.index; @@ -1451,16 +1555,20 @@ const right = hasOpenBracket ? closeBracketIndex : lines[i].length; const linkCandidate = lines[i].substring(left, right); const splitResult = Common.ParsedURL.splitLineAndColumn(linkCandidate); - if (!splitResult) + if (!splitResult) { return null; + } - if (splitResult.url === '<anonymous>') + if (splitResult.url === '<anonymous>') { continue; + } let url = parseOrScriptMatch(splitResult.url); - if (!url && Common.ParsedURL.isRelativeURL(splitResult.url)) + if (!url && Common.ParsedURL.isRelativeURL(splitResult.url)) { url = parseOrScriptMatch(Common.ParsedURL.completeURL(baseURL, splitResult.url)); - if (!url) + } + if (!url) { return null; + } links.push({ url: url, @@ -1471,8 +1579,9 @@ }); } - if (!links.length) + if (!links.length) { return null; + } const formattedResult = createElement('span'); let start = 0; @@ -1486,8 +1595,9 @@ start = links[i].positionRight; } - if (start !== string.length) + if (start !== string.length) { formattedResult.appendChild(this._linkifyStringAsFragment(string.substring(start))); + } return formattedResult; @@ -1496,13 +1606,16 @@ * @return {?string} */ function parseOrScriptMatch(url) { - if (!url) + if (!url) { return null; + } const parsedURL = url.asParsedURL(); - if (parsedURL) + if (parsedURL) { return parsedURL.url; - if (debuggerModel.scriptsForSourceURL(url).length) + } + if (debuggerModel.scriptsForSourceURL(url).length) { return url; + } return null; } } @@ -1513,22 +1626,25 @@ * @return {!DocumentFragment} */ _linkifyWithCustomLinkifier(string, linkifier) { - if (string.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) + if (string.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) { return UI.createExpandableText(string, Console.ConsoleViewMessage._LongStringVisibleLength); + } const container = createDocumentFragment(); const tokens = Console.ConsoleViewMessage._tokenizeMessageText(string); for (const token of tokens) { - if (!token.text) + if (!token.text) { continue; + } switch (token.type) { case 'url': { const realURL = (token.text.startsWith('www.') ? 'http://' + token.text : token.text); const splitResult = Common.ParsedURL.splitLineAndColumn(realURL); let linkNode; - if (splitResult) + if (splitResult) { linkNode = linkifier(token.text, splitResult.url, splitResult.lineNumber, splitResult.columnNumber); - else + } else { linkNode = linkifier(token.text, token.value); + } container.appendChild(linkNode); break; } @@ -1579,8 +1695,9 @@ Console.ConsoleViewMessage._tokenizerRegexes = Array.from(handlers.keys()); Console.ConsoleViewMessage._tokenizerTypes = Array.from(handlers.values()); } - if (string.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) + if (string.length > Console.ConsoleViewMessage._MaxTokenizableStringLength) { return [{text: string, type: undefined}]; + } const results = TextUtils.TextUtils.splitStringByRegexes(string, Console.ConsoleViewMessage._tokenizerRegexes); return results.map( result => ({text: result.value, type: Console.ConsoleViewMessage._tokenizerTypes[result.regexIndex]})); @@ -1590,8 +1707,9 @@ * @return {string} */ groupKey() { - if (!this._groupKey) + if (!this._groupKey) { this._groupKey = this._message.groupCategoryKey() + ':' + this.groupTitle(); + } return this._groupKey; } @@ -1602,16 +1720,17 @@ const tokens = Console.ConsoleViewMessage._tokenizeMessageText(this._message.messageText); const result = tokens.reduce((acc, token) => { let text = token.text; - if (token.type === 'url') + if (token.type === 'url') { text = Common.UIString('<URL>'); - else if (token.type === 'time') + } else if (token.type === 'time') { text = Common.UIString('took <N>ms'); - else if (token.type === 'event') + } else if (token.type === 'event') { text = Common.UIString('<some> event'); - else if (token.type === 'milestone') + } else if (token.type === 'milestone') { text = Common.UIString(' M<XX>'); - else if (token.type === 'autofill') + } else if (token.type === 'autofill') { text = Common.UIString('<attribute>'); + } return acc + text; }, ''); return result.replace(/[%]o/g, ''); @@ -1644,8 +1763,9 @@ */ _setCollapsed(collapsed) { this._collapsed = collapsed; - if (this._expandGroupIcon) + if (this._expandGroupIcon) { this._expandGroupIcon.setIconType(this._collapsed ? 'smallicon-triangle-right' : 'smallicon-triangle-down'); + } this._onToggle.call(null); } @@ -1682,10 +1802,11 @@ this._expandGroupIcon = UI.Icon.create(iconType, 'expand-group-icon'); // Intercept focus to avoid highlight on click. this._contentElement.tabIndex = -1; - if (this._repeatCountElement) + if (this._repeatCountElement) { this._repeatCountElement.insertBefore(this._expandGroupIcon, this._repeatCountElement.firstChild); - else + } else { this._element.insertBefore(this._expandGroupIcon, this._contentElement); + } this._element.addEventListener('click', () => this._setCollapsed(!this._collapsed)); } return this._element; @@ -1696,8 +1817,9 @@ */ _showRepeatCountElement() { super._showRepeatCountElement(); - if (this._repeatCountElement && this._expandGroupIcon) + if (this._repeatCountElement && this._expandGroupIcon) { this._repeatCountElement.insertBefore(this._expandGroupIcon, this._repeatCountElement.firstChild); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js index ae47b5c3..72c9945c 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleViewport.js
@@ -92,10 +92,11 @@ */ setStickToBottom(value) { this._stickToBottom = value; - if (this._stickToBottom) + if (this._stickToBottom) { this._observer.observe(this._contentElement, this._observerConfig); - else + } else { this._observer.disconnect(); + } } /** @@ -115,11 +116,13 @@ * @param {!Event} event */ _onCopy(event) { - if (this._muteCopyHandler) + if (this._muteCopyHandler) { return; + } const text = this._selectedText(); - if (!text) + if (!text) { return; + } event.preventDefault(); event.clipboardData.setData('text/plain', text); } @@ -129,8 +132,9 @@ */ _onFocusIn(event) { const renderedIndex = this._renderedItems.findIndex(item => item.element().isSelfOrAncestor(event.target)); - if (renderedIndex !== -1) + if (renderedIndex !== -1) { this._virtualSelectedIndex = this._firstActiveIndex + renderedIndex; + } let focusLastChild = false; // Make default selection when moving from external (e.g. prompt) to the container. if (this._virtualSelectedIndex === -1 && this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget)) && @@ -150,8 +154,9 @@ */ _onFocusOut(event) { // Remove selection when focus moves to external location (e.g. prompt). - if (this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget))) + if (this._isOutsideViewport(/** @type {?Element} */ (event.relatedTarget))) { this._virtualSelectedIndex = -1; + } this._updateFocusedItem(); } @@ -168,8 +173,9 @@ */ _onDragStart(event) { const text = this._selectedText(); - if (!text) + if (!text) { return false; + } event.dataTransfer.clearData(); event.dataTransfer.setData('text/plain', text); event.dataTransfer.effectAllowed = 'copy'; @@ -180,8 +186,9 @@ * @param {!Event} event */ _onKeyDown(event) { - if (UI.isEditing() || !this._itemCount || event.shiftKey) + if (UI.isEditing() || !this._itemCount || event.shiftKey) { return; + } let isArrowUp = false; switch (event.key) { case 'ArrowUp': @@ -193,10 +200,11 @@ } break; case 'ArrowDown': - if (this._virtualSelectedIndex < this._itemCount - 1) + if (this._virtualSelectedIndex < this._itemCount - 1) { this._virtualSelectedIndex++; - else + } else { return; + } break; case 'Home': this._virtualSelectedIndex = 0; @@ -219,8 +227,9 @@ const selectedElement = this.renderedElementAt(this._virtualSelectedIndex); const changed = this._lastSelectedElement !== selectedElement; const containerHasFocus = this._contentElement === this.element.ownerDocument.deepActiveElement(); - if (this._lastSelectedElement && changed) + if (this._lastSelectedElement && changed) { this._lastSelectedElement.classList.remove('console-selected'); + } if (selectedElement && (focusLastChild || changed || containerHasFocus) && this.element.hasFocus()) { selectedElement.classList.add('console-selected'); // Do not focus the message if something within holds focus (e.g. object). @@ -231,10 +240,11 @@ focusWithoutScroll(selectedElement); } } - if (this._itemCount && !this._contentElement.hasFocus()) + if (this._itemCount && !this._contentElement.hasFocus()) { this._contentElement.tabIndex = 0; - else + } else { this._contentElement.tabIndex = -1; + } this._lastSelectedElement = selectedElement; /** @@ -257,8 +267,9 @@ invalidate() { delete this._cachedProviderElements; this._itemCount = this._provider.itemCount(); - if (this._virtualSelectedIndex > this._itemCount - 1) + if (this._virtualSelectedIndex > this._itemCount - 1) { this._virtualSelectedIndex = this._itemCount - 1; + } this._rebuildCumulativeHeights(); this.refresh(); } @@ -268,8 +279,9 @@ * @return {?Console.ConsoleViewportElement} */ _providerElement(index) { - if (!this._cachedProviderElements) + if (!this._cachedProviderElements) { this._cachedProviderElements = new Array(this._itemCount); + } let element = this._cachedProviderElements[index]; if (!element) { element = this._provider.itemElement(index); @@ -284,10 +296,11 @@ let height = 0; this._cumulativeHeights = new Int32Array(this._itemCount); for (let i = 0; i < this._itemCount; ++i) { - if (firstActiveIndex <= i && i - firstActiveIndex < this._renderedItems.length && i <= lastActiveIndex) + if (firstActiveIndex <= i && i - firstActiveIndex < this._renderedItems.length && i <= lastActiveIndex) { height += this._renderedItems[i - firstActiveIndex].element().offsetHeight; - else + } else { height += this._provider.fastHeight(i); + } this._cumulativeHeights[i] = height; } } @@ -327,8 +340,9 @@ * @suppressGlobalPropertiesCheck */ _isSelectionBackwards(selection) { - if (!selection || !selection.rangeCount) + if (!selection || !selection.rangeCount) { return false; + } const range = document.createRange(); range.setStart(selection.anchorNode, selection.anchorOffset); range.setEnd(selection.focusNode, selection.focusOffset); @@ -424,10 +438,11 @@ anchorElement = this._anchorSelection.node; anchorOffset = this._anchorSelection.offset; } else { - if (this._anchorSelection.item < this._firstActiveIndex) + if (this._anchorSelection.item < this._firstActiveIndex) { anchorElement = this._topGapElement; - else if (this._anchorSelection.item > this._lastActiveIndex) + } else if (this._anchorSelection.item > this._lastActiveIndex) { anchorElement = this._bottomGapElement; + } anchorOffset = this._selectionIsBackward ? 1 : 0; } @@ -437,10 +452,11 @@ headElement = this._headSelection.node; headOffset = this._headSelection.offset; } else { - if (this._headSelection.item < this._firstActiveIndex) + if (this._headSelection.item < this._firstActiveIndex) { headElement = this._topGapElement; - else if (this._headSelection.item > this._lastActiveIndex) + } else if (this._headSelection.item > this._lastActiveIndex) { headElement = this._bottomGapElement; + } headOffset = this._selectionIsBackward ? 0 : 1; } @@ -450,17 +466,20 @@ refresh() { this._observer.disconnect(); this._innerRefresh(); - if (this._stickToBottom) + if (this._stickToBottom) { this._observer.observe(this._contentElement, this._observerConfig); + } } _innerRefresh() { - if (!this._visibleHeight()) - return; // Do nothing for invisible controls. + if (!this._visibleHeight()) { + return; + } // Do nothing for invisible controls. if (!this._itemCount) { - for (let i = 0; i < this._renderedItems.length; ++i) + for (let i = 0; i < this._renderedItems.length; ++i) { this._renderedItems[i].willHide(); + } this._renderedItems = []; this._contentElement.removeChildren(); this._topGapElement.style.height = '0px'; @@ -512,10 +531,12 @@ this._partialViewportUpdate(prepare.bind(this)); this._contentElement.style.removeProperty('height'); // Should be the last call in the method as it might force layout. - if (shouldRestoreSelection) + if (shouldRestoreSelection) { this._restoreSelection(selection); - if (this._stickToBottom) + } + if (this._stickToBottom) { this.element.scrollTop = 10000000; + } } /** @@ -523,11 +544,13 @@ */ _partialViewportUpdate(prepare) { const itemsToRender = new Set(); - for (let i = this._firstActiveIndex; i <= this._lastActiveIndex; ++i) + for (let i = this._firstActiveIndex; i <= this._lastActiveIndex; ++i) { itemsToRender.add(this._providerElement(i)); + } const willBeHidden = this._renderedItems.filter(item => !itemsToRender.has(item)); - for (let i = 0; i < willBeHidden.length; ++i) + for (let i = 0; i < willBeHidden.length; ++i) { willBeHidden[i].willHide(); + } prepare(); let hadFocus = false; for (let i = 0; i < willBeHidden.length; ++i) { @@ -541,19 +564,22 @@ const element = viewportElement.element(); if (element !== anchor) { const shouldCallWasShown = !element.parentElement; - if (shouldCallWasShown) + if (shouldCallWasShown) { wasShown.push(viewportElement); + } this._contentElement.insertBefore(element, anchor); } else { anchor = anchor.nextSibling; } } - for (let i = 0; i < wasShown.length; ++i) + for (let i = 0; i < wasShown.length; ++i) { wasShown[i].wasShown(); + } this._renderedItems = Array.from(itemsToRender); - if (hadFocus) + if (hadFocus) { this._contentElement.focus(); + } this._updateFocusedItem(); } @@ -562,8 +588,9 @@ */ _selectedText() { this._updateSelectionModel(this.element.getComponentSelection()); - if (!this._headSelection || !this._anchorSelection) + if (!this._headSelection || !this._anchorSelection) { return null; + } let startSelection = null; let endSelection = null; @@ -618,14 +645,16 @@ let node = itemElement; while ((node = node.traverseNextNode(itemElement)) && node !== selectionNode) { if (node.nodeType !== Node.TEXT_NODE || node.parentElement.nodeName === 'STYLE' || - node.parentElement.nodeName === 'SCRIPT') + node.parentElement.nodeName === 'SCRIPT') { continue; + } chars += Components.Linkifier.untruncatedNodeText(node).length; } // If the selected node text was truncated, treat any non-zero offset as the full length. const untruncatedContainerLength = Components.Linkifier.untruncatedNodeText(selectionNode).length; - if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length) + if (offset > 0 && untruncatedContainerLength !== selectionNode.textContent.length) { offset = untruncatedContainerLength; + } return chars + offset; } @@ -640,8 +669,9 @@ * @return {number} */ firstVisibleIndex() { - if (!this._cumulativeHeights.length) + if (!this._cumulativeHeights.length) { return -1; + } this._rebuildCumulativeHeightsIfNeeded(); return this._cumulativeHeights.lowerBound(this.element.scrollTop + 1); } @@ -650,8 +680,9 @@ * @return {number} */ lastVisibleIndex() { - if (!this._cumulativeHeights.length) + if (!this._cumulativeHeights.length) { return -1; + } this._rebuildCumulativeHeightsIfNeeded(); const scrollBottom = this.element.scrollTop + this.element.clientHeight; const right = this._itemCount - 1; @@ -662,8 +693,9 @@ * @return {?Element} */ renderedElementAt(index) { - if (index === -1 || index < this._firstActiveIndex || index > this._lastActiveIndex) + if (index === -1 || index < this._firstActiveIndex || index > this._lastActiveIndex) { return null; + } return this._renderedItems[index - this._firstActiveIndex].element(); } @@ -674,17 +706,21 @@ scrollItemIntoView(index, makeLast) { const firstVisibleIndex = this.firstVisibleIndex(); const lastVisibleIndex = this.lastVisibleIndex(); - if (index > firstVisibleIndex && index < lastVisibleIndex) + if (index > firstVisibleIndex && index < lastVisibleIndex) { return; + } // If the prompt is visible, then the last item must be fully on screen. - if (index === lastVisibleIndex && this._cumulativeHeights[index] <= this.element.scrollTop + this._visibleHeight()) + if (index === lastVisibleIndex && + this._cumulativeHeights[index] <= this.element.scrollTop + this._visibleHeight()) { return; - if (makeLast) + } + if (makeLast) { this.forceScrollItemToBeLast(index); - else if (index <= firstVisibleIndex) + } else if (index <= firstVisibleIndex) { this.forceScrollItemToBeFirst(index); - else if (index >= lastVisibleIndex) + } else if (index >= lastVisibleIndex) { this.forceScrollItemToBeLast(index); + } } /** @@ -695,8 +731,9 @@ this.setStickToBottom(false); this._rebuildCumulativeHeightsIfNeeded(); this.element.scrollTop = index > 0 ? this._cumulativeHeights[index - 1] : 0; - if (this.element.isScrolledToBottom()) + if (this.element.isScrolledToBottom()) { this.setStickToBottom(true); + } this.refresh(); // After refresh, the item is in DOM, but may not be visible (items above were larger than expected). this.renderedElementAt(index).scrollIntoView(true /* alignTop */); @@ -710,8 +747,9 @@ this.setStickToBottom(false); this._rebuildCumulativeHeightsIfNeeded(); this.element.scrollTop = this._cumulativeHeights[index] - this._visibleHeight(); - if (this.element.isScrolledToBottom()) + if (this.element.isScrolledToBottom()) { this.setStickToBottom(true); + } this.refresh(); // After refresh, the item is in DOM, but may not be visible (items above were larger than expected). this.renderedElementAt(index).scrollIntoView(false /* alignTop */);
diff --git a/third_party/blink/renderer/devtools/front_end/console_counters/WarningErrorCounter.js b/third_party/blink/renderer/devtools/front_end/console_counters/WarningErrorCounter.js index be51d80..172463d 100644 --- a/third_party/blink/renderer/devtools/front_end/console_counters/WarningErrorCounter.js +++ b/third_party/blink/renderer/devtools/front_end/console_counters/WarningErrorCounter.js
@@ -24,14 +24,16 @@ }); const violationShadowRoot = UI.createShadowRootWithCoreStyles(this._violationCounter, 'console_counters/errorWarningCounter.css'); - if (Runtime.experiments.isEnabled('spotlight')) + if (Runtime.experiments.isEnabled('spotlight')) { countersWrapper.appendChild(this._violationCounter); + } this._errors = this._createItem(shadowRoot, 'smallicon-error'); this._warnings = this._createItem(shadowRoot, 'smallicon-warning'); - if (Runtime.experiments.isEnabled('spotlight')) + if (Runtime.experiments.isEnabled('spotlight')) { this._violations = this._createItem(violationShadowRoot, 'smallicon-info'); + } this._titles = []; this._errorCount = -1; this._warningCount = -1; @@ -85,8 +87,9 @@ const errors = SDK.consoleModel.errors(); const warnings = SDK.consoleModel.warnings(); const violations = SDK.consoleModel.violations(); - if (errors === this._errorCount && warnings === this._warningCount && violations === this._violationCount) + if (errors === this._errorCount && warnings === this._warningCount && violations === this._violationCount) { return Promise.resolve(); + } this._errorCount = errors; this._warningCount = warnings; this._violationCount = violations; @@ -97,29 +100,34 @@ this._toolbarItem.setVisible(!!(errors || warnings || violations)); let errorCountTitle = ''; - if (errors === 1) + if (errors === 1) { errorCountTitle = ls`${errors} error`; - else + } else { errorCountTitle = ls`${errors} errors`; + } this._updateItem(this._errors, errors, false); - if (errors) + if (errors) { this._titles.push(errorCountTitle); + } let warningCountTitle = ''; - if (warnings === 1) + if (warnings === 1) { warningCountTitle = ls`${warnings} warning`; - else + } else { warningCountTitle = ls`${warnings} warnings`; + } this._updateItem(this._warnings, warnings, !errors); - if (warnings) + if (warnings) { this._titles.push(warningCountTitle); + } if (Runtime.experiments.isEnabled('spotlight')) { let violationCountTitle = ''; - if (violations === 1) + if (violations === 1) { violationCountTitle = ls`${violations} violation`; - else + } else { violationCountTitle = ls`${violations} violations`; + } this._updateItem(this._violations, violations, true); this._violationCounter.title = violationCountTitle; }
diff --git a/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js b/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js index 451be30..4f1696a 100644 --- a/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/console_test_runner/ConsoleTestRunner.js
@@ -33,8 +33,9 @@ const originalViewportStyle = consoleView._viewport.element.style; const originalSize = {width: originalViewportStyle.width, height: originalViewportStyle.height}; ConsoleTestRunner.disableConsoleViewport(); - if (consoleView._needsFullUpdate) + if (consoleView._needsFullUpdate) { consoleView._updateMessageList(); + } const viewMessages = consoleView._visibleViewMessages; for (let i = 0; i < viewMessages.length; ++i) { const uiMessage = viewMessages[i]; @@ -49,8 +50,9 @@ let depth = 0; let depthTest = node; while (depthTest !== element) { - if (depthTest.nodeType === Node.ELEMENT_NODE && depthTest.className) + if (depthTest.nodeType === Node.ELEMENT_NODE && depthTest.className) { depth++; + } depthTest = depthTest.parentNodeOrShadowHost(); } classNames.push( @@ -63,16 +65,18 @@ } if (ConsoleTestRunner.dumpConsoleTableMessage(uiMessage, false, result)) { - if (dumpClassNames) + if (dumpClassNames) { result.push(classNames.join('\n')); + } } else { let messageText = formatter(element, message); messageText = messageText.replace(/VM\d+/g, 'VM'); result.push(messageText + (dumpClassNames ? ' ' + classNames.join('\n') : '')); } - if (printOriginatingCommand && uiMessage.consoleMessage().originatingMessage()) + if (printOriginatingCommand && uiMessage.consoleMessage().originatingMessage()) { result.push('Originating from: ' + uiMessage.consoleMessage().originatingMessage().messageText); + } } consoleView._viewport.element.style.width = originalSize.width; consoleView._viewport.element.style.height = originalSize.height; @@ -106,16 +110,19 @@ * @return {boolean} */ ConsoleTestRunner.dumpConsoleTableMessage = function(viewMessage, forceInvalidate, results) { - if (forceInvalidate) + if (forceInvalidate) { Console.ConsoleView.instance()._viewport.invalidate(); + } const table = viewMessage.element(); const headers = table.querySelectorAll('th > div:first-child'); - if (!headers.length) + if (!headers.length) { return false; + } let headerLine = ''; - for (let i = 0; i < headers.length; i++) + for (let i = 0; i < headers.length; i++) { headerLine += headers[i].textContent + ' | '; + } addResult('HEADER ' + headerLine); @@ -125,21 +132,24 @@ const row = rows[i]; let rowLine = ''; const items = row.querySelectorAll('td > span'); - for (let j = 0; j < items.length; j++) + for (let j = 0; j < items.length; j++) { rowLine += items[j].textContent + ' | '; + } - if (rowLine.trim()) + if (rowLine.trim()) { addResult('ROW ' + rowLine); + } } /** * @param {string} x */ function addResult(x) { - if (results) + if (results) { results.push(x); - else + } else { TestRunner.addResult(x); + } } return true; @@ -177,8 +187,9 @@ * @param {boolean=} dontForceMainContext */ ConsoleTestRunner.evaluateInConsole = function(code, callback, dontForceMainContext) { - if (!dontForceMainContext) + if (!dontForceMainContext) { ConsoleTestRunner.selectMainExecutionContext(); + } callback = TestRunner.safeWrap(callback); const consoleView = Console.ConsoleView.instance(); @@ -291,8 +302,9 @@ const messageText = ConsoleTestRunner.prepareConsoleMessageText(element); TestRunner.addResult(messageText); const spans = element.querySelectorAll('.console-message-text *'); - for (let j = 0; j < spans.length; ++j) + for (let j = 0; j < spans.length; ++j) { TestRunner.addResult('Styled text #' + j + ': ' + (spans[j].style.cssText || 'NO STYLES DEFINED')); + } } }; @@ -308,8 +320,9 @@ const messageText = ConsoleTestRunner.prepareConsoleMessageText(element); result.push(messageText + ' ' + element.getAttribute('class') + ' > ' + contentElement.getAttribute('class')); } - if (sortMessages) + if (sortMessages) { result.sort(); + } TestRunner.addResults(result); }; @@ -323,10 +336,12 @@ ConsoleTestRunner.dumpConsoleCounters = async function() { const counter = ConsoleCounters.WarningErrorCounter._instanceForTest; - if (counter._updatingForTest) + if (counter._updatingForTest) { await TestRunner.addSnifferPromise(counter, '_updatedForTest'); - for (let index = 0; index < counter._titles.length; ++index) + } + for (let index = 0; index < counter._titles.length; ++index) { TestRunner.addResult(counter._titles[index]); + } ConsoleTestRunner.dumpConsoleClassesBrief(); }; @@ -340,8 +355,9 @@ const messageViews = Console.ConsoleView.instance()._visibleViewMessages; // Initiate round-trips to fetch necessary data for further rendering. - for (let i = 0; i < messageViews.length; ++i) + for (let i = 0; i < messageViews.length; ++i) { messageViews[i].element(); + } TestRunner.deprecatedRunAfterPendingDispatches(expandTreeElements); @@ -349,24 +365,30 @@ for (let i = 0; i < messageViews.length; ++i) { const element = messageViews[i].element(); for (let node = element; node; node = node.traverseNextNode(element)) { - if (node.treeElementForTest) + if (node.treeElementForTest) { node.treeElementForTest.expand(); - if (node._expandStackTraceForTest) + } + if (node._expandStackTraceForTest) { node._expandStackTraceForTest(); - if (!node._section) + } + if (!node._section) { continue; - if (sectionFilter && !sectionFilter(node._section)) + } + if (sectionFilter && !sectionFilter(node._section)) { continue; + } node._section.expand(); - if (!deepFilter) + if (!deepFilter) { continue; + } const treeElements = node._section.rootElement().children(); for (let j = 0; j < treeElements.length; ++j) { for (let treeElement = treeElements[j]; treeElement; treeElement = treeElement.traverseNextTreeElement(true, null, true)) { - if (deepFilter(treeElement)) + if (deepFilter(treeElement)) { treeElement.expand(); + } } } } @@ -406,8 +428,9 @@ function propertyExpandableUpdated() { --propertiesCount; if (propertiesCount === 0) { - for (let i = 0; i < properties.length; ++i) + for (let i = 0; i < properties.length; ++i) { properties[i].click(); + } TestRunner.deprecatedRunAfterPendingDispatches(callback); } else { TestRunner.addSniffer( @@ -422,8 +445,9 @@ ConsoleTestRunner.expandConsoleMessagesErrorParameters = function(callback) { const messageViews = Console.ConsoleView.instance()._visibleViewMessages; // Initiate round-trips to fetch necessary data for further rendering. - for (let i = 0; i < messageViews.length; ++i) + for (let i = 0; i < messageViews.length; ++i) { messageViews[i].element(); + } TestRunner.deprecatedRunAfterPendingDispatches(callback); }; @@ -432,8 +456,9 @@ */ ConsoleTestRunner.waitForRemoteObjectsConsoleMessages = function(callback) { const messages = Console.ConsoleView.instance()._visibleViewMessages; - for (let i = 0; i < messages.length; ++i) + for (let i = 0; i < messages.length; ++i) { messages[i].toMessageElement(); + } TestRunner.deprecatedRunAfterPendingDispatches(callback); }; @@ -451,10 +476,11 @@ let fulfill; const promise = new Promise(x => (fulfill = x)); const prompt = Console.ConsoleView.instance()._prompt; - if (prompt._editor) + if (prompt._editor) { fulfill(prompt._editor); - else + } else { TestRunner.addSniffer(Console.ConsolePrompt.prototype, '_editorSetForTest', _ => fulfill(prompt._editor)); + } return promise; }; @@ -478,10 +504,11 @@ */ ConsoleTestRunner.waitUntilNthMessageReceived = function(count, callback) { function override() { - if (--count === 0) + if (--count === 0) { TestRunner.safeWrap(callback)(); - else + } else { TestRunner.addSniffer(SDK.consoleModel, 'addMessage', override, false); + } } TestRunner.addSniffer(SDK.consoleModel, 'addMessage', override, false); }; @@ -563,8 +590,9 @@ let charCount = 0; while ((node = node.traverseNextTextNode(container))) { const length = node.textContent.length; - if (charCount + length >= offset) + if (charCount + length >= offset) { return {container: node, offset: offset - charCount}; + } charCount += length; } @@ -626,8 +654,9 @@ for (let i = 0; i < consoleView._visibleViewMessages.length; i++) { // Created message elements may have a bounding rect, but not be connected to DOM. const item = consoleView._visibleViewMessages[i]; - if (!item._element || !item._element.isConnected) + if (!item._element || !item._element.isConnected) { continue; + } const itemRect = item._element.getBoundingClientRect(); const isVisible = (itemRect.bottom > viewportRect.top + 1) && (itemRect.top <= viewportRect.bottom - 1); if (isVisible) {
diff --git a/third_party/blink/renderer/devtools/front_end/cookie_table/CookiesTable.js b/third_party/blink/renderer/devtools/front_end/cookie_table/CookiesTable.js index 35ac3d9..2e181eaa 100644 --- a/third_party/blink/renderer/devtools/front_end/cookie_table/CookiesTable.js +++ b/third_party/blink/renderer/devtools/front_end/cookie_table/CookiesTable.js
@@ -103,11 +103,13 @@ this._dataGrid.setStriped(true); this._dataGrid.setName('cookiesTable'); this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this._rebuildTable, this); - if (renderInline) + if (renderInline) { this._dataGrid.renderInline(); + } - if (selectedCallback) + if (selectedCallback) { this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, selectedCallback, this); + } /** @type {?string} */ this._lastEditedColumnId = null; @@ -182,18 +184,21 @@ * @return {?SDK.Cookie} */ _findSelectedCookie(selectionCookies, cookies) { - if (!cookies) + if (!cookies) { return null; + } const current = selectionCookies.current; const foundCurrent = cookies.find(cookie => this._isSameCookie(cookie, current)); - if (foundCurrent) + if (foundCurrent) { return foundCurrent; + } const neighbor = selectionCookies.neighbor; const foundNeighbor = cookies.find(cookie => this._isSameCookie(cookie, neighbor)); - if (foundNeighbor) + if (foundNeighbor) { return foundNeighbor; + } return null; } @@ -238,10 +243,12 @@ this._populateNode(this._dataGrid.rootNode(), item.cookies, selectedCookie, lastEditedColumnId); } } - if (selectionCookies.current && lastEditedColumnId && !this._dataGrid.selectedNode) + if (selectionCookies.current && lastEditedColumnId && !this._dataGrid.selectedNode) { this._addInactiveNode(this._dataGrid.rootNode(), selectionCookies.current, lastEditedColumnId); - if (this._saveCallback) + } + if (this._saveCallback) { this._dataGrid.addCreationNode(false); + } } /** @@ -252,8 +259,9 @@ */ _populateNode(parentNode, cookies, selectedCookie, lastEditedColumnId) { parentNode.removeChildren(); - if (!cookies) + if (!cookies) { return; + } this._sortCookies(cookies); for (let i = 0; i < cookies.length; ++i) { @@ -262,8 +270,9 @@ parentNode.appendChild(cookieNode); if (this._isSameCookie(cookie, selectedCookie)) { cookieNode.select(); - if (lastEditedColumnId !== null) + if (lastEditedColumnId !== null) { this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode, lastEditedColumnId); + } } } } @@ -278,14 +287,16 @@ parentNode.appendChild(cookieNode); cookieNode.select(); cookieNode.setInactive(true); - if (editedColumnId !== null) + if (editedColumnId !== null) { this._dataGrid.startEditingNextEditableColumnOfDataGridNode(cookieNode, editedColumnId); + } } _totalSize(cookies) { let totalSize = 0; - for (let i = 0; cookies && i < cookies.length; ++i) + for (let i = 0; cookies && i < cookies.length; ++i) { totalSize += cookies[i].size(); + } return totalSize; } @@ -329,27 +340,32 @@ * @return {number} */ function expiresCompare(cookie1, cookie2) { - if (cookie1.session() !== cookie2.session()) + if (cookie1.session() !== cookie2.session()) { return sortDirection * (cookie1.session() ? 1 : -1); + } - if (cookie1.session()) + if (cookie1.session()) { return 0; + } - if (cookie1.maxAge() && cookie2.maxAge()) + if (cookie1.maxAge() && cookie2.maxAge()) { return sortDirection * (cookie1.maxAge() - cookie2.maxAge()); - if (cookie1.expires() && cookie2.expires()) + } + if (cookie1.expires() && cookie2.expires()) { return sortDirection * (cookie1.expires() - cookie2.expires()); + } return sortDirection * (cookie1.expires() ? 1 : -1); } let comparator; const columnId = this._dataGrid.sortColumnId() || 'name'; - if (columnId === 'expires') + if (columnId === 'expires') { comparator = expiresCompare; - else if (columnId === 'size') + } else if (columnId === 'size') { comparator = numberCompare; - else + } else { comparator = compareTo.bind(null, columnId); + } cookies.sort(comparator); } @@ -373,10 +389,11 @@ if (cookie.maxAge()) { data[SDK.Cookie.Attributes.Expires] = Number.secondsToString(parseInt(cookie.maxAge(), 10)); } else if (cookie.expires()) { - if (cookie.expires() < 0) + if (cookie.expires() < 0) { data[SDK.Cookie.Attributes.Expires] = CookieTable.CookiesTable._expiresSessionValue; - else + } else { data[SDK.Cookie.Attributes.Expires] = new Date(cookie.expires()).toISOString(); + } } else { data[SDK.Cookie.Attributes.Expires] = cookie.type() === SDK.Cookie.Type.Request ? ls`N/A` : CookieTable.CookiesTable._expiresSessionValue; @@ -398,8 +415,9 @@ * @param {!DataGrid.DataGridNode} node */ _onDeleteCookie(node) { - if (node.cookie && this._deleteCallback) + if (node.cookie && this._deleteCallback) { this._deleteCallback(node.cookie, () => this._refresh()); + } } /** @@ -411,26 +429,32 @@ _onUpdateCookie(editingNode, columnIdentifier, oldText, newText) { this._lastEditedColumnId = columnIdentifier; this._setDefaults(editingNode); - if (this._isValidCookieData(editingNode.data)) + if (this._isValidCookieData(editingNode.data)) { this._saveNode(editingNode); - else + } else { editingNode.setDirty(true); + } } /** * @param {!DataGrid.DataGridNode} node */ _setDefaults(node) { - if (node.data[SDK.Cookie.Attributes.Name] === null) + if (node.data[SDK.Cookie.Attributes.Name] === null) { node.data[SDK.Cookie.Attributes.Name] = ''; - if (node.data[SDK.Cookie.Attributes.Value] === null) + } + if (node.data[SDK.Cookie.Attributes.Value] === null) { node.data[SDK.Cookie.Attributes.Value] = ''; - if (node.data[SDK.Cookie.Attributes.Domain] === null) + } + if (node.data[SDK.Cookie.Attributes.Domain] === null) { node.data[SDK.Cookie.Attributes.Domain] = this._cookieDomain; - if (node.data[SDK.Cookie.Attributes.Path] === null) + } + if (node.data[SDK.Cookie.Attributes.Path] === null) { node.data[SDK.Cookie.Attributes.Path] = '/'; - if (node.data[SDK.Cookie.Attributes.Expires] === null) + } + if (node.data[SDK.Cookie.Attributes.Expires] === null) { node.data[SDK.Cookie.Attributes.Expires] = CookieTable.CookiesTable._expiresSessionValue; + } } /** @@ -441,10 +465,11 @@ const newCookie = this._createCookieFromData(node.data); node.cookie = newCookie; this._saveCallback(newCookie, oldCookie).then(success => { - if (success) + if (success) { this._refresh(); - else + } else { node.setDirty(true); + } }); } @@ -456,14 +481,18 @@ const cookie = new SDK.Cookie(data[SDK.Cookie.Attributes.Name], data[SDK.Cookie.Attributes.Value], null); cookie.addAttribute(SDK.Cookie.Attributes.Domain, data[SDK.Cookie.Attributes.Domain]); cookie.addAttribute(SDK.Cookie.Attributes.Path, data[SDK.Cookie.Attributes.Path]); - if (data.expires && data.expires !== CookieTable.CookiesTable._expiresSessionValue) + if (data.expires && data.expires !== CookieTable.CookiesTable._expiresSessionValue) { cookie.addAttribute(SDK.Cookie.Attributes.Expires, (new Date(data[SDK.Cookie.Attributes.Expires])).toUTCString()); - if (data[SDK.Cookie.Attributes.HttpOnly]) + } + if (data[SDK.Cookie.Attributes.HttpOnly]) { cookie.addAttribute(SDK.Cookie.Attributes.HttpOnly); - if (data[SDK.Cookie.Attributes.Secure]) + } + if (data[SDK.Cookie.Attributes.Secure]) { cookie.addAttribute(SDK.Cookie.Attributes.Secure); - if (data[SDK.Cookie.Attributes.SameSite]) + } + if (data[SDK.Cookie.Attributes.SameSite]) { cookie.addAttribute(SDK.Cookie.Attributes.SameSite, data[SDK.Cookie.Attributes.SameSite]); + } cookie.setSize(data[SDK.Cookie.Attributes.Name].length + data[SDK.Cookie.Attributes.Value].length); return cookie; } @@ -482,8 +511,9 @@ * @returns {boolean} */ _isValidDomain(domain) { - if (!domain) + if (!domain) { return true; + } const parsedURL = ('http://' + domain).asParsedURL(); return !!parsedURL && parsedURL.domain() === domain; } @@ -506,8 +536,9 @@ } _refresh() { - if (this._refreshCallback) + if (this._refreshCallback) { this._refreshCallback(); + } } }; @@ -529,8 +560,9 @@ */ createCells(element) { super.createCells(element); - if (this._blockedReasons && this._blockedReasons.length) + if (this._blockedReasons && this._blockedReasons.length) { element.classList.add('flagged-cookie-attribute-row'); + } } /** @@ -548,8 +580,9 @@ const attributeMatches = blockedReason.attribute === /** @type {!SDK.Cookie.Attributes} */ (columnId); const useNameColumn = !blockedReason.attribute && columnId === SDK.Cookie.Attributes.Name; if (attributeMatches || useNameColumn) { - if (blockedReasonString) + if (blockedReasonString) { blockedReasonString += '\n'; + } blockedReasonString += blockedReason.uiString; } }
diff --git a/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js b/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js index 9fd998f..e4d24ba 100644 --- a/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js +++ b/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js
@@ -23,14 +23,16 @@ /** @type {!Multimap<!Common.ContentProvider, !Workspace.UISourceCode>} */ this._uiSourceCodeByContentProvider = new Multimap(); - for (const uiSourceCode of Workspace.workspace.uiSourceCodes()) + for (const uiSourceCode of Workspace.workspace.uiSourceCodes()) { uiSourceCode.addLineDecoration(0, Coverage.CoverageDecorationManager._decoratorType, this); + } Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._onUISourceCodeAdded, this); } reset() { - for (const uiSourceCode of Workspace.workspace.uiSourceCodes()) + for (const uiSourceCode of Workspace.workspace.uiSourceCodes()) { uiSourceCode.removeDecorationsForType(Coverage.CoverageDecorationManager._decoratorType); + } } dispose() { @@ -58,8 +60,9 @@ async usageByLine(uiSourceCode) { const result = []; const content = await uiSourceCode.requestContent(); - if (!content) + if (!content) { return []; + } const sourceText = new TextUtils.Text(/** @type {string} */ (content)); await this._updateTexts(uiSourceCode, sourceText); const lineEndings = sourceText.lineEndings(); @@ -75,25 +78,32 @@ for (let startIndex = 0, endIndex = 0; startIndex < startLocations.length; ++startIndex) { const start = startLocations[startIndex]; while (endIndex < endLocations.length && - Coverage.CoverageDecorationManager._compareLocations(start, endLocations[endIndex]) >= 0) + Coverage.CoverageDecorationManager._compareLocations(start, endLocations[endIndex]) >= 0) { ++endIndex; - if (endIndex >= endLocations.length || endLocations[endIndex].id !== start.id) + } + if (endIndex >= endLocations.length || endLocations[endIndex].id !== start.id) { continue; + } const end = endLocations[endIndex++]; const text = this._textByProvider.get(end.contentProvider); - if (!text) + if (!text) { continue; + } const textValue = text.value(); let startOffset = Math.min(text.offsetFromPosition(start.line, start.column), textValue.length - 1); let endOffset = Math.min(text.offsetFromPosition(end.line, end.column), textValue.length - 1); - while (startOffset <= endOffset && /\s/.test(textValue[startOffset])) + while (startOffset <= endOffset && /\s/.test(textValue[startOffset])) { ++startOffset; - while (startOffset <= endOffset && /\s/.test(textValue[endOffset])) + } + while (startOffset <= endOffset && /\s/.test(textValue[endOffset])) { --endOffset; - if (startOffset <= endOffset) + } + if (startOffset <= endOffset) { used = this._coverageModel.usageForRange(end.contentProvider, startOffset, endOffset); - if (used) + } + if (used) { break; + } } result.push(used); } @@ -109,8 +119,9 @@ const promises = []; for (let line = 0; line < text.lineCount(); ++line) { for (const entry of this._rawLocationsForSourceLocation(uiSourceCode, line, 0)) { - if (this._textByProvider.has(entry.contentProvider)) + if (this._textByProvider.has(entry.contentProvider)) { continue; + } this._textByProvider.set(entry.contentProvider, null); this._uiSourceCodeByContentProvider.set(entry.contentProvider, uiSourceCode); promises.push(this._updateTextForProvider(entry.contentProvider)); @@ -144,8 +155,9 @@ const script = location.script(); if (script.isInlineScript() && contentType.isDocument()) { location.lineNumber -= script.lineOffset; - if (!location.lineNumber) + if (!location.lineNumber) { location.columnNumber -= script.columnOffset; + } } result.push({ id: `js:${location.scriptId}`, @@ -160,12 +172,14 @@ Bindings.cssWorkspaceBinding.uiLocationToRawLocations(new Workspace.UILocation(uiSourceCode, line, column)); for (const location of rawStyleLocations) { const header = location.header(); - if (!header) + if (!header) { continue; + } if (header.isInline && contentType.isDocument()) { location.lineNumber -= header.startLine; - if (!location.lineNumber) + if (!location.lineNumber) { location.columnNumber -= header.startColumn; + } } result.push({ id: `css:${location.styleSheetId}`, @@ -232,12 +246,14 @@ _innerDecorate(uiSourceCode, textEditor, lineUsage) { const gutterType = Coverage.CoverageView.LineDecorator._gutterType; this._uninstallGutter(textEditor); - if (lineUsage.length) + if (lineUsage.length) { this._installGutter(textEditor, uiSourceCode.url()); + } for (let line = 0; line < lineUsage.length; ++line) { // Do not decorate the line if we don't have data. - if (typeof lineUsage[line] !== 'boolean') + if (typeof lineUsage[line] !== 'boolean') { continue; + } const className = lineUsage[line] ? 'text-editor-coverage-used-marker' : 'text-editor-coverage-unused-marker'; const gutterElement = createElementWithClass('div', className); textEditor.setGutterDecoration(line, gutterType, gutterElement); @@ -251,8 +267,9 @@ makeGutterClickHandler(url) { function handleGutterClick(event) { const eventData = /** @type {!SourceFrame.SourcesTextEditor.GutterClickEventData} */ (event.data); - if (eventData.gutterType !== Coverage.CoverageView.LineDecorator._gutterType) + if (eventData.gutterType !== Coverage.CoverageView.LineDecorator._gutterType) { return; + } const coverageViewId = 'coverage'; UI.viewManager.showView(coverageViewId).then(() => UI.viewManager.view(coverageViewId).widget()).then(widget => { const matchFormattedSuffix = url.match(/(.*):formatted$/);
diff --git a/third_party/blink/renderer/devtools/front_end/coverage/CoverageListView.js b/third_party/blink/renderer/devtools/front_end/coverage/CoverageListView.js index a2b0231..2f9bb853 100644 --- a/third_party/blink/renderer/devtools/front_end/coverage/CoverageListView.js +++ b/third_party/blink/renderer/devtools/front_end/coverage/CoverageListView.js
@@ -56,8 +56,9 @@ for (const entry of coverageInfo) { let node = this._nodeForCoverageInfo.get(entry); if (node) { - if (this._filterCallback(node._coverageInfo)) + if (this._filterCallback(node._coverageInfo)) { hadUpdates = node._refreshIfNeeded(maxSize) || hadUpdates; + } continue; } node = new Coverage.CoverageListView.GridNode(entry, maxSize); @@ -67,8 +68,9 @@ hadUpdates = true; } } - if (hadUpdates) + if (hadUpdates) { this._sortingChanged(); + } } reset() { @@ -85,18 +87,22 @@ for (const node of this._nodeForCoverageInfo.values()) { const shouldBeVisible = this._filterCallback(node._coverageInfo); const isVisible = !!node.parent; - if (shouldBeVisible) + if (shouldBeVisible) { node._setHighlight(this._highlightRegExp); - if (shouldBeVisible === isVisible) + } + if (shouldBeVisible === isVisible) { continue; + } hadTreeUpdates = true; - if (!shouldBeVisible) + if (!shouldBeVisible) { node.remove(); - else + } else { this._dataGrid.rootNode().appendChild(node); + } } - if (hadTreeUpdates) + if (hadTreeUpdates) { this._sortingChanged(); + } } selectByUrl(url) { @@ -116,35 +122,40 @@ * @param {!Event} event */ _onKeyDown(event) { - if (!isEnterKey(event)) + if (!isEnterKey(event)) { return; + } event.consume(true); this._revealSourceForSelectedNode(); } async _revealSourceForSelectedNode() { const node = this._dataGrid.selectedNode; - if (!node) + if (!node) { return; + } const coverageInfo = /** @type {!Coverage.CoverageListView.GridNode} */ (node)._coverageInfo; let sourceCode = Workspace.workspace.uiSourceCodeForURL(coverageInfo.url()); - if (!sourceCode) + if (!sourceCode) { return; + } const content = await sourceCode.requestContent(); if (TextUtils.isMinified(content)) { const formatData = await Sources.sourceFormatter.format(sourceCode); // ------------ ASYNC ------------ sourceCode = formatData.formattedSourceCode; } - if (this._dataGrid.selectedNode !== node) + if (this._dataGrid.selectedNode !== node) { return; + } Common.Revealer.reveal(sourceCode); } _sortingChanged() { const columnId = this._dataGrid.sortColumnId(); - if (!columnId) + if (!columnId) { return; + } let sortFunction; switch (columnId) { case 'url': @@ -211,12 +222,14 @@ */ static _typeToString(type) { const types = []; - if (type & Coverage.CoverageType.CSS) + if (type & Coverage.CoverageType.CSS) { types.push(Common.UIString('CSS')); - if (type & Coverage.CoverageType.JavaScriptCoarse) + } + if (type & Coverage.CoverageType.JavaScriptCoarse) { types.push(Common.UIString('JS (coarse)')); - else if (type & Coverage.CoverageType.JavaScript) + } else if (type & Coverage.CoverageType.JavaScript) { types.push(Common.UIString('JS')); + } return types.join('+'); } }; @@ -242,8 +255,9 @@ * @param {?RegExp} highlightRegExp */ _setHighlight(highlightRegExp) { - if (this._highlightRegExp === highlightRegExp) + if (this._highlightRegExp === highlightRegExp) { return; + } this._highlightRegExp = highlightRegExp; this.refresh(); } @@ -253,8 +267,9 @@ * @return {boolean} */ _refreshIfNeeded(maxSize) { - if (this._lastUsedSize === this._coverageInfo.usedSize() && maxSize === this._maxSize) + if (this._lastUsedSize === this._coverageInfo.usedSize() && maxSize === this._maxSize) { return false; + } this._lastUsedSize = this._coverageInfo.usedSize(); this._maxSize = maxSize; this.refresh(); @@ -277,13 +292,15 @@ const splitURL = /^(.*)(\/[^/]*)$/.exec(this._url); prefix.textContent = splitURL ? splitURL[1] : this._url; suffix.textContent = splitURL ? splitURL[2] : ''; - if (this._highlightRegExp) + if (this._highlightRegExp) { this._highlight(outer, this._url); + } break; case 'type': cell.textContent = Coverage.CoverageListView._typeToString(this._coverageInfo.type()); - if (this._coverageInfo.type() & Coverage.CoverageType.JavaScriptCoarse) + if (this._coverageInfo.type() & Coverage.CoverageType.JavaScriptCoarse) { cell.title = Common.UIString('JS coverage is function-level only. Reload the page for block-level coverage.'); + } break; case 'size': cell.textContent = Number.withThousandsSeparator(this._coverageInfo.size() || 0); @@ -311,8 +328,9 @@ */ _highlight(element, textContent) { const matches = this._highlightRegExp.exec(textContent); - if (!matches || !matches.length) + if (!matches || !matches.length) { return; + } const range = new TextUtils.SourceRange(matches.index, matches[0].length); UI.highlightRangesWithStyleClass(element, [range], 'filter-highlight'); }
diff --git a/third_party/blink/renderer/devtools/front_end/coverage/CoverageModel.js b/third_party/blink/renderer/devtools/front_end/coverage/CoverageModel.js index 1b9a8a4..7be7a9a 100644 --- a/third_party/blink/renderer/devtools/front_end/coverage/CoverageModel.js +++ b/third_party/blink/renderer/devtools/front_end/coverage/CoverageModel.js
@@ -61,8 +61,9 @@ * @return {!Promise<boolean>} */ async start() { - if (this._suspensionState !== Coverage.SuspensionState.Active) + if (this._suspensionState !== Coverage.SuspensionState.Active) { throw Error('Cannot start CoverageModel while it is not active.'); + } const promises = []; if (this._cssModel) { // Note there's no JS coverage since JS won't ever return @@ -84,10 +85,12 @@ async stop() { await this.stopPolling(); const promises = []; - if (this._cpuProfilerModel) + if (this._cpuProfilerModel) { promises.push(this._cpuProfilerModel.stopPreciseCoverage()); - if (this._cssModel) + } + if (this._cssModel) { promises.push(this._cssModel.stopCoverage()); + } await Promise.all(promises); } @@ -100,8 +103,9 @@ * @return {!Promise} */ async startPolling() { - if (this._currentPollPromise || this._suspensionState !== Coverage.SuspensionState.Active) + if (this._currentPollPromise || this._suspensionState !== Coverage.SuspensionState.Active) { return; + } await this._pollLoop(); } @@ -112,8 +116,9 @@ this._clearTimer(); this._currentPollPromise = this._pollAndCallback(); await this._currentPollPromise; - if (this._suspensionState === Coverage.SuspensionState.Active || this._performanceTraceRecording) + if (this._suspensionState === Coverage.SuspensionState.Active || this._performanceTraceRecording) { this._pollTimer = setTimeout(() => this._pollLoop(), Coverage.CoverageModel._coveragePollingPeriodMs); + } } async stopPolling() { @@ -128,16 +133,18 @@ * @return {!Promise<undefined>} */ async _pollAndCallback() { - if (this._suspensionState === Coverage.SuspensionState.Suspended && !this._performanceTraceRecording) + if (this._suspensionState === Coverage.SuspensionState.Suspended && !this._performanceTraceRecording) { return; + } const updates = await this._takeAllCoverage(); // This conditional should never trigger, as all intended ways to stop // polling are awaiting the `_currentPollPromise` before suspending. console.assert( this._suspensionState !== Coverage.SuspensionState.Suspended || this._performanceTraceRecording, 'CoverageModel was suspended while polling.'); - if (updates.length) + if (updates.length) { this.dispatchEventToListeners(Coverage.CoverageModel.Events.CoverageUpdated, updates); + } } _clearTimer() { @@ -155,8 +162,9 @@ * @return {!Promise<undefined>} */ async preSuspendModel(reason) { - if (this._suspensionState !== Coverage.SuspensionState.Active) + if (this._suspensionState !== Coverage.SuspensionState.Active) { return; + } this._suspensionState = Coverage.SuspensionState.Suspending; if (reason === 'performance-timeline') { this._performanceTraceRecording = true; @@ -220,18 +228,21 @@ _clearCSS() { for (const entry of this._coverageByContentProvider.values()) { - if (entry.type() !== Coverage.CoverageType.CSS) + if (entry.type() !== Coverage.CoverageType.CSS) { continue; + } const contentProvider = /** @type {!SDK.CSSStyleSheetHeader} */ (entry.contentProvider()); this._coverageByContentProvider.delete(contentProvider); const key = `${contentProvider.startLine}:${contentProvider.startColumn}`; const urlEntry = this._coverageByURL.get(entry.url()); - if (!urlEntry || !urlEntry._coverageInfoByLocation.delete(key)) + if (!urlEntry || !urlEntry._coverageInfoByLocation.delete(key)) { continue; + } urlEntry._size -= entry._size; urlEntry._usedSize -= entry._usedSize; - if (!urlEntry._coverageInfoByLocation.size) + if (!urlEntry._coverageInfoByLocation.size) { this._coverageByURL.delete(entry.url()); + } } } @@ -247,8 +258,9 @@ * @return {!Promise<!Array<!Coverage.CoverageInfo>>} */ async _takeJSCoverage() { - if (!this._cpuProfilerModel) + if (!this._cpuProfilerModel) { return []; + } const now = Date.now(); let freshRawCoverageData = await this._cpuProfilerModel.takePreciseCoverage(); if (this._bestEffortCoveragePromise) { @@ -257,18 +269,21 @@ freshRawCoverageData = bestEffortCoverage.concat(freshRawCoverageData); } if (this._suspensionState !== Coverage.SuspensionState.Active) { - if (freshRawCoverageData.length > 0) + if (freshRawCoverageData.length > 0) { this._jsBacklog.push({rawCoverageData: freshRawCoverageData, stamp: now}); + } return []; } const results = []; - for (const {rawCoverageData, stamp} of this._jsBacklog) + for (const {rawCoverageData, stamp} of this._jsBacklog) { results.push(this._processJSCoverage(rawCoverageData, stamp)); + } this._jsBacklog = []; - if (freshRawCoverageData.length > 0) + if (freshRawCoverageData.length > 0) { results.push(this._processJSCoverage(freshRawCoverageData, now)); + } return results.flat(); } @@ -280,8 +295,9 @@ const updatedEntries = []; for (const entry of scriptsCoverage) { const script = this._debuggerModel.scriptForId(entry.scriptId); - if (!script) + if (!script) { continue; + } const ranges = []; let type = Coverage.CoverageType.JavaScript; @@ -290,16 +306,19 @@ // if back-end explicitly provides blockLevel field, otherwise presume blockLevel // coverage is not available. Also, ignore non-block level functions that weren't // ever called. - if (func.isBlockCoverage === false && !(func.ranges.length === 1 && !func.ranges[0].count)) + if (func.isBlockCoverage === false && !(func.ranges.length === 1 && !func.ranges[0].count)) { type |= Coverage.CoverageType.JavaScriptCoarse; - for (const range of func.ranges) + } + for (const range of func.ranges) { ranges.push(range); + } } const subentry = this._addCoverage( script, script.contentLength, script.lineOffset, script.columnOffset, ranges, /** @type {!Coverage.CoverageType} */ (type), stamp); - if (subentry) + if (subentry) { updatedEntries.push(subentry); + } } return updatedEntries; } @@ -308,23 +327,27 @@ * @return {!Promise<!Array<!Coverage.CoverageInfo>>} */ async _takeCSSCoverage() { - if (!this._cssModel) + if (!this._cssModel) { return []; + } const now = Date.now(); const freshRawCoverageData = await this._cssModel.takeCoverageDelta(); if (this._suspensionState !== Coverage.SuspensionState.Active) { - if (freshRawCoverageData.length > 0) + if (freshRawCoverageData.length > 0) { this._cssBacklog.push({rawCoverageData: freshRawCoverageData, stamp: now}); + } return []; } const results = []; - for (const {rawCoverageData, stamp} of this._cssBacklog) + for (const {rawCoverageData, stamp} of this._cssBacklog) { results.push(this._processCSSCoverage(rawCoverageData, stamp)); + } this._cssBacklog = []; - if (freshRawCoverageData.length > 0) + if (freshRawCoverageData.length > 0) { results.push(this._processCSSCoverage(freshRawCoverageData, now)); + } return results.flat(); } @@ -338,8 +361,9 @@ const rulesByStyleSheet = new Map(); for (const rule of ruleUsageList) { const styleSheetHeader = this._cssModel.styleSheetHeaderForId(rule.styleSheetId); - if (!styleSheetHeader) + if (!styleSheetHeader) { continue; + } let ranges = rulesByStyleSheet.get(styleSheetHeader); if (!ranges) { ranges = []; @@ -353,8 +377,9 @@ const subentry = this._addCoverage( styleSheetHeader, styleSheetHeader.contentLength, styleSheetHeader.startLine, styleSheetHeader.startColumn, ranges, Coverage.CoverageType.CSS, stamp); - if (subentry) + if (subentry) { updatedEntries.push(subentry); + } } return updatedEntries; } @@ -391,8 +416,9 @@ function append(end, count) { const last = result.peekLast(); if (last) { - if (last.end === end) + if (last.end === end) { return; + } if (last.count === count) { last.end = end; return; @@ -415,8 +441,9 @@ */ _addCoverage(contentProvider, contentLength, startLine, startColumn, ranges, type, stamp) { const url = contentProvider.contentURL(); - if (!url) + if (!url) { return null; + } let urlCoverage = this._coverageByURL.get(url); if (!urlCoverage) { urlCoverage = new Coverage.URLCoverageInfo(url); @@ -426,12 +453,14 @@ const coverageInfo = urlCoverage._ensureEntry(contentProvider, contentLength, startLine, startColumn, type); this._coverageByContentProvider.set(contentProvider, coverageInfo); const segments = Coverage.CoverageModel._convertToDisjointSegments(ranges, stamp); - if (segments.length && segments.peekLast().end < contentLength) + if (segments.length && segments.peekLast().end < contentLength) { segments.push({end: contentLength, stamp: stamp}); + } const oldUsedSize = coverageInfo._usedSize; coverageInfo.mergeCoverage(segments); - if (coverageInfo._usedSize === oldUsedSize) + if (coverageInfo._usedSize === oldUsedSize) { return null; + } urlCoverage._usedSize += coverageInfo._usedSize - oldUsedSize; return coverageInfo; } @@ -450,8 +479,9 @@ for (const urlInfoKey of coverageByUrlKeys) { const urlInfo = this._coverageByURL.get(urlInfoKey); const url = urlInfo.url(); - if (url.startsWith('extensions::') || url.startsWith('chrome-extension://')) + if (url.startsWith('extensions::') || url.startsWith('chrome-extension://')) { continue; + } // For .html resources, multiple scripts share URL, but have different offsets. let useFullText = false; @@ -478,10 +508,11 @@ const offset = fullText ? fullText.offsetFromPosition(info._lineOffset, info._columnOffset) : 0; let start = 0; for (const segment of info._segments) { - if (segment.count) + if (segment.count) { entry.ranges.push({start: start + offset, end: segment.end + offset}); - else + } else { start = segment.end; + } } } result.push(entry); @@ -494,10 +525,11 @@ const entry = {url, ranges: [], text: await info.contentProvider().requestContent()}; let start = 0; for (const segment of info._segments) { - if (segment.count) + if (segment.count) { entry.ranges.push({start: start, end: segment.end}); - else + } else { start = segment.end; + } } result.push(entry); } @@ -590,8 +622,9 @@ const key = `${lineOffset}:${columnOffset}`; let entry = this._coverageInfoByLocation.get(key); - if ((type & Coverage.CoverageType.JavaScript) && !this._coverageInfoByLocation.size) + if ((type & Coverage.CoverageType.JavaScript) && !this._coverageInfoByLocation.size) { this._isContentScript = /** @type {!SDK.Script} */ (contentProvider).isContentScript(); + } this._type |= type; if (entry) { @@ -599,8 +632,9 @@ return entry; } - if ((type & Coverage.CoverageType.JavaScript) && !this._coverageInfoByLocation.size) + if ((type & Coverage.CoverageType.JavaScript) && !this._coverageInfoByLocation.size) { this._isContentScript = /** @type {!SDK.Script} */ (contentProvider).isContentScript(); + } entry = new Coverage.CoverageInfo(contentProvider, contentLength, lineOffset, columnOffset, type); this._coverageInfoByLocation.set(key, entry); @@ -676,8 +710,9 @@ usageForRange(start, end) { let index = this._segments.upperBound(start, (position, segment) => position - segment.end); for (; index < this._segments.length && this._segments[index].end < end; ++index) { - if (this._segments[index].count) + if (this._segments[index].count) { return true; + } } return index < this._segments.length && !!this._segments[index].count; } @@ -699,20 +734,25 @@ const end = Math.min(a.end, b.end); const last = result.peekLast(); const stamp = Math.min(a.stamp, b.stamp); - if (!last || last.count !== count || last.stamp !== stamp) + if (!last || last.count !== count || last.stamp !== stamp) { result.push({end: end, count: count, stamp: stamp}); - else + } else { last.end = end; - if (a.end <= b.end) + } + if (a.end <= b.end) { indexA++; - if (a.end >= b.end) + } + if (a.end >= b.end) { indexB++; + } } - for (; indexA < segmentsA.length; indexA++) + for (; indexA < segmentsA.length; indexA++) { result.push(segmentsA[indexA]); - for (; indexB < segmentsB.length; indexB++) + } + for (; indexB < segmentsB.length; indexB++) { result.push(segmentsB[indexB]); + } return result; } @@ -722,8 +762,9 @@ let last = 0; for (const segment of this._segments) { - if (!this._statsByTimestamp.has(segment.stamp)) + if (!this._statsByTimestamp.has(segment.stamp)) { this._statsByTimestamp.set(segment.stamp, 0); + } if (segment.count) { const used = segment.end - last;
diff --git a/third_party/blink/renderer/devtools/front_end/coverage/CoverageView.js b/third_party/blink/renderer/devtools/front_end/coverage/CoverageView.js index d2fd173..6760ab1 100644 --- a/third_party/blink/renderer/devtools/front_end/coverage/CoverageView.js +++ b/third_party/blink/renderer/devtools/front_end/coverage/CoverageView.js
@@ -86,8 +86,9 @@ } _clear() { - if (this._model) + if (this._model) { this._model.reset(); + } this._reset(); } @@ -106,17 +107,19 @@ _toggleRecording() { const enable = !this._toggleRecordAction.toggled(); - if (enable) + if (enable) { this._startRecording(false); - else + } else { this.stopRecording(); + } } async ensureRecordingStarted() { const enable = !this._toggleRecordAction.toggled(); - if (enable) + if (enable) { await this._startRecording(false); + } } /** @@ -125,15 +128,18 @@ async _startRecording(reload) { this._reset(); const mainTarget = SDK.targetManager.mainTarget(); - if (!mainTarget) + if (!mainTarget) { return; + } - if (!this._model || reload) + if (!this._model || reload) { this._model = mainTarget.model(Coverage.CoverageModel); + } Host.userMetrics.actionTaken(Host.UserMetrics.Action.CoverageStarted); const success = await this._model.start(); - if (!success) + if (!success) { return; + } this._model.addEventListener(Coverage.CoverageModel.Events.CoverageUpdated, this._onCoverageDataReceived, this); this._resourceTreeModel = /** @type {?SDK.ResourceTreeModel} */ (mainTarget.model(SDK.ResourceTreeModel)); if (this._resourceTreeModel) { @@ -144,16 +150,19 @@ new Coverage.CoverageDecorationManager(/** @type {!Coverage.CoverageModel} */ (this._model)); this._toggleRecordAction.setToggled(true); this._clearButton.setEnabled(false); - if (this._startWithReloadButton) + if (this._startWithReloadButton) { this._startWithReloadButton.setEnabled(false); + } this._filterInput.setEnabled(true); - if (this._landingPage.isShowing()) + if (this._landingPage.isShowing()) { this._landingPage.detach(); + } this._listView.show(this._coverageResultsElement); - if (reload && this._resourceTreeModel) + if (reload && this._resourceTreeModel) { this._resourceTreeModel.reloadPage(); - else + } else { this._model.startPolling(); + } } _onCoverageDataReceived(event) { @@ -170,8 +179,9 @@ await this._model.stop(); this._model.removeEventListener(Coverage.CoverageModel.Events.CoverageUpdated, this._onCoverageDataReceived, this); this._toggleRecordAction.setToggled(false); - if (this._startWithReloadButton) + if (this._startWithReloadButton) { this._startWithReloadButton.setEnabled(true); + } this._clearButton.setEnabled(true); } @@ -195,8 +205,9 @@ let total = 0; let unused = 0; for (const info of this._model.entries()) { - if (!this._isVisible(true, info)) + if (!this._isVisible(true, info)) { continue; + } total += info.size(); unused += info.unusedSize(); } @@ -209,8 +220,9 @@ } _onFilterChanged() { - if (!this._listView) + if (!this._listView) { return; + } const text = this._filterInput.value(); this._textFilterRegExp = text ? createPlainTextSearchRegex(text, 'i') : null; this._listView.updateFilterAndHighlight(this._textFilterRegExp); @@ -224,10 +236,12 @@ */ _isVisible(ignoreTextFilter, coverageInfo) { const url = coverageInfo.url(); - if (url.startsWith(Coverage.CoverageView._extensionBindingsURLPrefix)) + if (url.startsWith(Coverage.CoverageView._extensionBindingsURLPrefix)) { return false; - if (coverageInfo.isContentScript() && !this._showContentScriptsSetting.get()) + } + if (coverageInfo.isContentScript() && !this._showContentScriptsSetting.get()) { return false; + } return ignoreTextFilter || !this._textFilterRegExp || this._textFilterRegExp.test(url); } @@ -235,8 +249,9 @@ const fos = new Bindings.FileOutputStream(); const fileName = `Coverage-${new Date().toISO8601Compact()}.json`; const accepted = await fos.open(fileName); - if (!accepted) + if (!accepted) { return; + } this._model.exportReport(fos); }
diff --git a/third_party/blink/renderer/devtools/front_end/coverage_test_runner/CoverageTestRunner.js b/third_party/blink/renderer/devtools/front_end/coverage_test_runner/CoverageTestRunner.js index 8724d4a..2156750 100644 --- a/third_party/blink/renderer/devtools/front_end/coverage_test_runner/CoverageTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/coverage_test_runner/CoverageTestRunner.js
@@ -82,8 +82,9 @@ const rootNode = coverageListView._dataGrid.rootNode(); for (const child of rootNode.children) { - if (child._coverageInfo.url().endsWith(url)) + if (child._coverageInfo.url().endsWith(url)) { return child; + } } return null; @@ -98,8 +99,9 @@ let markerType = ' '; const lineInfo = codeMirror.lineInfo(line); - if (!lineInfo) + if (!lineInfo) { continue; + } const gutterElement = lineInfo.gutterMarkers && lineInfo.gutterMarkers['CodeMirror-gutter-coverage']; @@ -121,8 +123,9 @@ const data = child._coverageInfo; const url = TestRunner.formatters.formatAsURL(data.url()); - if (url.startsWith('test://')) + if (url.startsWith('test://')) { continue; + } const type = Coverage.CoverageListView._typeToString(data.type()); TestRunner.addResult(`${url} ${type} used: ${data.usedSize()} unused: ${data.unusedSize()} total: ${data.size()}`);
diff --git a/third_party/blink/renderer/devtools/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js b/third_party/blink/renderer/devtools/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js index 49abf7dd..cfc48a30 100644 --- a/third_party/blink/renderer/devtools/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js
@@ -45,8 +45,9 @@ }; CPUProfilerTestRunner._profileHeaderAdded = function(profile) { - if (CPUProfilerTestRunner._showProfileWhenAdded === profile.title) + if (CPUProfilerTestRunner._showProfileWhenAdded === profile.title) { UI.panels.js_profiler.showProfile(profile); + } }; CPUProfilerTestRunner.waitUntilProfileViewIsShown = function(title, callback) { @@ -54,10 +55,11 @@ const profilesPanel = UI.panels.js_profiler; if (profilesPanel.visibleView && profilesPanel.visibleView.profile && - profilesPanel.visibleView._profileHeader.title === title) + profilesPanel.visibleView._profileHeader.title === title) { callback(profilesPanel.visibleView); - else + } else { CPUProfilerTestRunner._waitUntilProfileViewIsShownCallback = {title: title, callback: callback}; + } };
diff --git a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewCompletedView.js b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewCompletedView.js index 60e9a35..d568ff5e 100644 --- a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewCompletedView.js +++ b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewCompletedView.js
@@ -30,8 +30,9 @@ _sideBarItemSelected(event) { const section = this._fragment.$(event.data); - if (!section) + if (!section) { return; + } section.scrollIntoView(); } @@ -45,8 +46,9 @@ } _render(data) { - if (!(data && ('textColors' in data) && ('backgroundColors' in data))) + if (!(data && ('textColors' in data) && ('backgroundColors' in data))) { return; + } const {elementStyleStats, elementCount, backgroundColors, textColors, globalStyleStats} = data; @@ -153,8 +155,9 @@ return Array.from(colors) .map(colorText => { const color = Common.Color.parse(colorText); - if (color.rgba()[3] === 0) + if (color.rgba()[3] === 0) { return; + } return color; })
diff --git a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewModel.js b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewModel.js index 6f64b33..484f56db 100644 --- a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewModel.js +++ b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewModel.js
@@ -59,8 +59,9 @@ const {result} = await this._runtimeAgent.invoke_evaluate({expression, returnByValue: true}); // TODO(paullewis): Handle errors properly. - if (result.type !== 'object') + if (result.type !== 'object') { return; + } return result.value; } @@ -79,15 +80,17 @@ }; const matches = await this._cssAgent.invoke_getMatchedStylesForNode({nodeId}); - if (!matches || !matches.matchedCSSRules || !matches.matchedCSSRules.length) + if (!matches || !matches.matchedCSSRules || !matches.matchedCSSRules.length) { return; + } matches.matchedCSSRules.forEach(cssRule => { const {matchingSelectors} = cssRule; const {origin, selectorList} = cssRule.rule; const isExternalSheet = origin === 'regular'; - if (!isExternalSheet || !selectorList) + if (!isExternalSheet || !selectorList) { return; + } const selectors = matchingSelectors.map(idx => selectorList.selectors[idx]); @@ -113,10 +116,11 @@ } else { // Type or non-simple selector. const specialChars = /[#\.:\[\]|\+>~]/; - if (specialChars.test(selector)) + if (specialChars.test(selector)) { stats.nonSimple.add(selector); - else + } else { stats.type.add(selector); + } } } }
diff --git a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewPanel.js b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewPanel.js index 0520b58..d163d05 100644 --- a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewPanel.js +++ b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewPanel.js
@@ -88,8 +88,9 @@ // 1. Get the global style stats. const globalStyleStats = await this._model.getGlobalStylesheetStats(); - if (globalStyleStats) + if (globalStyleStats) { this._globalStyleStats = globalStyleStats; + } // 2. Get the total element count. this._elementCount = document.length; @@ -108,16 +109,18 @@ // 3a. Capture any colors from the computed styles. if (computedStyles) { const backgroundColor = this._getStyleValue(computedStyles, 'background-color'); - if (backgroundColor) + if (backgroundColor) { this._backgroundColors.add(backgroundColor); + } if (node.nodeType === Node.TEXT_NODE) { const textColor = this._getStyleValue(computedStyles, 'color'); this._textColors.add(textColor); const fontSize = this._getStyleValue(computedStyles, 'font-size'); - if (!this._fontSizes.has(fontSize)) + if (!this._fontSizes.has(fontSize)) { this._fontSizes.set(fontSize, 0); + } this._fontSizes.set(fontSize, this._fontSizes.get(fontSize) + 1); } @@ -126,11 +129,13 @@ // 3b. Tally the selector stats. if (styleStats) { for (const section of Object.keys(this._elementStyleStats)) { - if (!styleStats[section]) + if (!styleStats[section]) { continue; + } - for (const value of styleStats[section]) + for (const value of styleStats[section]) { this._elementStyleStats[section].add(value); + } } } @@ -143,8 +148,9 @@ _getStyleValue(styles, name) { const item = styles.filter(style => style.name === name); - if (!item.length) + if (!item.length) { return; + } return item[0].value; }
diff --git a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewSidebarPanel.js b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewSidebarPanel.js index 3955421..9e36316 100644 --- a/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewSidebarPanel.js +++ b/third_party/blink/renderer/devtools/front_end/css_overview/CSSOverviewSidebarPanel.js
@@ -40,14 +40,16 @@ _deselectAllItems() { const items = this.contentElement.querySelectorAll(`.${CssOverview.CSSOverviewSidebarPanel.ITEM_CLASS_NAME}`); - for (const item of items) + for (const item of items) { item.classList.remove(CssOverview.CSSOverviewSidebarPanel.SELECTED); + } } _onItemClick(event) { const target = event.path[0]; - if (!target.classList.contains(CssOverview.CSSOverviewSidebarPanel.ITEM_CLASS_NAME)) + if (!target.classList.contains(CssOverview.CSSOverviewSidebarPanel.ITEM_CLASS_NAME)) { return; + } const {id} = target.dataset; this.select(id); @@ -56,11 +58,13 @@ select(id) { const target = this.contentElement.querySelector(`[data-id=${CSS.escape(id)}]`); - if (!target) + if (!target) { return; + } - if (target.classList.contains(CssOverview.CSSOverviewSidebarPanel.SELECTED)) + if (target.classList.contains(CssOverview.CSSOverviewSidebarPanel.SELECTED)) { return; + } this._deselectAllItems(); target.classList.add(CssOverview.CSSOverviewSidebarPanel.SELECTED);
diff --git a/third_party/blink/renderer/devtools/front_end/data_grid/DataGrid.js b/third_party/blink/renderer/devtools/front_end/data_grid/DataGrid.js index f0dbc4b..80a64e7 100644 --- a/third_party/blink/renderer/devtools/front_end/data_grid/DataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/data_grid/DataGrid.js
@@ -58,8 +58,9 @@ // FIXME: Add a createCallback which is different from editCallback and has different // behavior when creating a new node. - if (editCallback) + if (editCallback) { this._dataTable.addEventListener('dblclick', this._ondblclick.bind(this), false); + } this._dataTable.addEventListener('mousedown', this._mouseDownInDataTable.bind(this)); this._dataTable.addEventListener('click', this._clickInDataTable.bind(this), true); @@ -161,16 +162,19 @@ */ _innerAddColumn(column, position) { const columnId = column.id; - if (columnId in this._columns) + if (columnId in this._columns) { this._innerRemoveColumn(columnId); + } - if (position === undefined) + if (position === undefined) { position = this._columnsArray.length; + } this._columnsArray.splice(position, 0, column); this._columns[columnId] = column; - if (column.disclosure) + if (column.disclosure) { this.disclosureColumnId = columnId; + } const cell = createElement('th'); cell.className = columnId + '-column'; @@ -178,10 +182,11 @@ this._headerTableHeaders[columnId] = cell; const div = createElement('div'); - if (column.titleDOMFragment) + if (column.titleDOMFragment) { div.appendChild(column.titleDOMFragment); - else + } else { div.textContent = column.title; + } cell.appendChild(div); if (column.sort) { @@ -211,14 +216,16 @@ */ _innerRemoveColumn(columnId) { const column = this._columns[columnId]; - if (!column) + if (!column) { return; + } delete this._columns[columnId]; const index = this._columnsArray.findIndex(columnConfig => columnConfig.id === columnId); this._columnsArray.splice(index, 1); const cell = this._headerTableHeaders[columnId]; - if (cell.parentElement) + if (cell.parentElement) { cell.parentElement.removeChild(cell); + } delete this._headerTableHeaders[columnId]; } @@ -276,8 +283,9 @@ setVerticalPadding(top, bottom) { const topPx = top + 'px'; const bottomPx = (top || bottom) ? bottom + 'px' : 'auto'; - if (this._topFillerRow.style.height === topPx && this._bottomFillerRow.style.height === bottomPx) + if (this._topFillerRow.style.height === topPx && this._bottomFillerRow.style.height === bottomPx) { return; + } this._topFillerRow.style.height = topPx; this._bottomFillerRow.style.height = bottomPx; this.dispatchEventToListeners(DataGrid.DataGrid.Events.PaddingChanged); @@ -314,12 +322,14 @@ * @param {!Event} event */ _ondblclick(event) { - if (this._editing || this._editingNode) + if (this._editing || this._editingNode) { return; + } const columnId = this.columnIdFromNode(/** @type {!Node} */ (event.target)); - if (!columnId || !this._columns[columnId].editable) + if (!columnId || !this._columns[columnId].editable) { return; + } this._startEditing(/** @type {!Node} */ (event.target)); } @@ -346,8 +356,9 @@ const column = this._columns[columnIdentifier]; const cellIndex = this._visibleColumnsArray.indexOf(column); const nextEditableColumn = this._nextEditableColumn(cellIndex); - if (nextEditableColumn !== -1) + if (nextEditableColumn !== -1) { this._startEditingColumnOfDataGridNode(node, nextEditableColumn); + } } /** @@ -355,13 +366,15 @@ */ _startEditing(target) { const element = /** @type {?Element} */ (target.enclosingNodeOrSelfWithNodeName('td')); - if (!element) + if (!element) { return; + } this._editingNode = this.dataGridNodeFromNode(target); if (!this._editingNode) { - if (!this.creationNode) + if (!this.creationNode) { return; + } this._editingNode = this.creationNode; } @@ -372,8 +385,9 @@ } this._editing = true; - if (element[DataGrid.DataGrid._longTextSymbol]) + if (element[DataGrid.DataGrid._longTextSymbol]) { element.textContent = element[DataGrid.DataGrid._longTextSymbol]; + } UI.InplaceEditor.startEditing(element, this._startEditingConfig(element)); element.getComponentSelection().selectAllChildren(element); @@ -417,13 +431,15 @@ * @this {DataGrid.DataGrid} */ function moveToNextIfNeeded(wasChange) { - if (!moveDirection) + if (!moveDirection) { return; + } if (moveDirection === 'forward') { const firstEditableColumn = this._nextEditableColumn(-1); - if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange) + if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange) { return; + } const nextEditableColumn = this._nextEditableColumn(cellIndex); if (nextEditableColumn !== -1) { @@ -453,8 +469,9 @@ const lastEditableColumn = this._nextEditableColumn(this._visibleColumnsArray.length, true); const nextDataGridNode = currentEditingNode.traversePreviousNode(true, true); - if (nextDataGridNode) + if (nextDataGridNode) { this._startEditingColumnOfDataGridNode(nextDataGridNode, lastEditableColumn); + } return; } } @@ -475,8 +492,9 @@ // the text that used to be there, and the new text. this._editCallback(this._editingNode, columnId, textBeforeEditing, newText); - if (this._editingNode.isCreationNode) + if (this._editingNode.isCreationNode) { this.addCreationNode(false); + } this._editingCancelled(element); moveToNextIfNeeded.call(this, true); @@ -499,8 +517,9 @@ const increment = moveBackward ? -1 : 1; const columns = this._visibleColumnsArray; for (let i = cellIndex + increment; (i >= 0) && (i < columns.length); i += increment) { - if (columns[i].editable) + if (columns[i].editable) { return i; + } } return -1; } @@ -509,8 +528,9 @@ * @return {?string} */ sortColumnId() { - if (!this._sortColumnCell) + if (!this._sortColumnCell) { return null; + } return this._sortColumnCell[DataGrid.DataGrid._columnIdSymbol]; } @@ -518,10 +538,12 @@ * @return {?string} */ sortOrder() { - if (!this._sortColumnCell || this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending)) + if (!this._sortColumnCell || this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Ascending)) { return DataGrid.DataGrid.Order.Ascending; - if (this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Descending)) + } + if (this._sortColumnCell.classList.contains(DataGrid.DataGrid.Order.Descending)) { return DataGrid.DataGrid.Order.Descending; + } return null; } @@ -539,18 +561,21 @@ * @return {!Array.<number>} */ _autoSizeWidths(widths, minPercent, maxPercent) { - if (minPercent) + if (minPercent) { minPercent = Math.min(minPercent, Math.floor(100 / widths.length)); + } let totalWidth = 0; - for (let i = 0; i < widths.length; ++i) + for (let i = 0; i < widths.length; ++i) { totalWidth += widths[i]; + } let totalPercentWidth = 0; for (let i = 0; i < widths.length; ++i) { let width = Math.round(100 * widths[i] / totalWidth); - if (minPercent && width < minPercent) + if (minPercent && width < minPercent) { width = minPercent; - else if (maxPercent && width > maxPercent) + } else if (maxPercent && width > maxPercent) { width = maxPercent; + } totalPercentWidth += width; widths[i] = width; } @@ -561,8 +586,9 @@ if (widths[i] > minPercent) { --widths[i]; --recoupPercent; - if (!recoupPercent) + if (!recoupPercent) { break; + } } } } @@ -572,8 +598,9 @@ if (widths[i] < maxPercent) { ++widths[i]; ++recoupPercent; - if (!recoupPercent) + if (!recoupPercent) { break; + } } } } @@ -589,8 +616,9 @@ */ autoSizeColumns(minPercent, maxPercent, maxDescentLevel) { let widths = []; - for (let i = 0; i < this._columnsArray.length; ++i) + for (let i = 0; i < this._columnsArray.length; ++i) { widths.push((this._columnsArray[i].title || '').length); + } maxDescentLevel = maxDescentLevel || 0; const children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1); @@ -598,15 +626,17 @@ const node = children[i]; for (let j = 0; j < this._columnsArray.length; ++j) { const text = String(node.data[this._columnsArray[j].id]); - if (text.length > widths[j]) + if (text.length > widths[j]) { widths[j] = text.length; + } } } widths = this._autoSizeWidths(widths, minPercent, maxPercent); - for (let i = 0; i < this._columnsArray.length; ++i) + for (let i = 0; i < this._columnsArray.length; ++i) { this._columnsArray[i].weight = widths[i]; + } this._columnWidthsInitialized = false; this.updateWidths(); } @@ -618,12 +648,15 @@ * @return {!Array<!NODE_TYPE>} */ _enumerateChildren(rootNode, result, maxLevel) { - if (!rootNode._isRoot) + if (!rootNode._isRoot) { result.push(rootNode); - if (!maxLevel) + } + if (!maxLevel) { return []; - for (let i = 0; i < rootNode.children.length; ++i) + } + for (let i = 0; i < rootNode.children.length; ++i) { this._enumerateChildren(rootNode.children[i], result, maxLevel - 1); + } return result; } @@ -655,8 +688,9 @@ const numColumns = cells.length - 1; // Do not process corner column. for (let i = 0; i < numColumns; i++) { const column = this._visibleColumnsArray[i]; - if (!column.weight) + if (!column.weight) { column.weight = 100 * cells[i].offsetWidth / tableWidth || 10; + } } this._columnWidthsInitialized = true; } @@ -672,21 +706,24 @@ } _loadColumnWeights() { - if (!this._columnWeightsSetting) + if (!this._columnWeightsSetting) { return; + } const weights = this._columnWeightsSetting.get(); for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; const weight = weights[column.id]; - if (weight) + if (weight) { column.weight = weight; + } } this._applyColumnWeights(); } _saveColumnWeights() { - if (!this._columnWeightsSetting) + if (!this._columnWeightsSetting) { return; + } const weights = {}; for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; @@ -704,8 +741,9 @@ _applyColumnWeights() { let tableWidth = this.element.offsetWidth - this._cornerWidth; - if (tableWidth <= 0) + if (tableWidth <= 0) { return; + } let sumOfWeights = 0.0; const fixedColumnWidths = []; @@ -747,14 +785,16 @@ this._visibleColumnsArray = []; for (let i = 0; i < this._columnsArray.length; ++i) { const column = this._columnsArray[i]; - if (columnsVisibility[column.id]) + if (columnsVisibility[column.id]) { this._visibleColumnsArray.push(column); + } } this._refreshHeader(); this._applyColumnWeights(); const nodes = this._enumerateChildren(this.rootNode(), [], -1); - for (let i = 0; i < nodes.length; ++i) + for (let i = 0; i < nodes.length; ++i) { nodes[i].refresh(); + } } get scrollContainer() { @@ -767,8 +807,9 @@ const left = []; const resizers = this._resizers; - while (resizers.length > numColumns - 1) + while (resizers.length > numColumns - 1) { resizers.pop().remove(); + } for (let i = 0; i < numColumns - 1; i++) { // Get the width of the cell in the first (and only) row of the @@ -801,12 +842,14 @@ } addCreationNode(hasChildren) { - if (this.creationNode) + if (this.creationNode) { this.creationNode.makeNormal(); + } const emptyData = {}; - for (const column in this._columns) + for (const column in this._columns) { emptyData[column] = null; + } this.creationNode = new DataGrid.CreationDataGridNode(emptyData, hasChildren); this.rootNode().appendChild(this.creationNode); } @@ -815,27 +858,31 @@ * @param {!Event} event */ _keyDown(event) { - if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing || UI.isEditing()) + if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing || UI.isEditing()) { return; + } let handled = false; let nextSelectedNode; if (event.key === 'ArrowUp' && !event.altKey) { nextSelectedNode = this.selectedNode.traversePreviousNode(true); - while (nextSelectedNode && !nextSelectedNode.selectable) + while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traversePreviousNode(true); + } handled = nextSelectedNode ? true : false; } else if (event.key === 'ArrowDown' && !event.altKey) { nextSelectedNode = this.selectedNode.traverseNextNode(true); - while (nextSelectedNode && !nextSelectedNode.selectable) + while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traverseNextNode(true); + } handled = nextSelectedNode ? true : false; } else if (event.key === 'ArrowLeft') { if (this.selectedNode.expanded) { - if (event.altKey) + if (event.altKey) { this.selectedNode.collapseRecursively(); - else + } else { this.selectedNode.collapse(); + } handled = true; } else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) { handled = true; @@ -856,10 +903,11 @@ nextSelectedNode = this.selectedNode.children[0]; handled = nextSelectedNode ? true : false; } else { - if (event.altKey) + if (event.altKey) { this.selectedNode.expandRecursively(); - else + } else { this.selectedNode.expand(); + } } } } else if (event.keyCode === 8 || event.keyCode === 46) { @@ -880,8 +928,9 @@ nextSelectedNode.reveal(); nextSelectedNode.select(); } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -890,25 +939,30 @@ */ updateSelectionBeforeRemoval(root, onlyAffectsSubtree) { let ancestor = this.selectedNode; - while (ancestor && ancestor !== root) + while (ancestor && ancestor !== root) { ancestor = ancestor.parent; + } // Selection is not in the subtree being deleted. - if (!ancestor) + if (!ancestor) { return; + } let nextSelectedNode; // Skip subtree being deleted when looking for the next selectable node. for (ancestor = root; ancestor && !ancestor.nextSibling; ancestor = ancestor.parent) { } - if (ancestor) + if (ancestor) { nextSelectedNode = ancestor.nextSibling; - while (nextSelectedNode && !nextSelectedNode.selectable) + } + while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traverseNextNode(true); + } if (!nextSelectedNode || nextSelectedNode.isCreationNode) { nextSelectedNode = root.traversePreviousNode(true); - while (nextSelectedNode && !nextSelectedNode.selectable) + while (nextSelectedNode && !nextSelectedNode.selectable) { nextSelectedNode = nextSelectedNode.traversePreviousNode(true); + } } if (nextSelectedNode) { nextSelectedNode.reveal(); @@ -941,8 +995,9 @@ */ _clickInHeaderCell(event) { const cell = event.target.enclosingNodeOrSelfWithNodeName('th'); - if (!cell) + if (!cell) { return; + } this._sortByColumnHeaderCell(cell); } @@ -950,15 +1005,18 @@ * @param {!Node} cell */ _sortByColumnHeaderCell(cell) { - if ((cell[DataGrid.DataGrid._columnIdSymbol] === undefined) || !cell.classList.contains('sortable')) + if ((cell[DataGrid.DataGrid._columnIdSymbol] === undefined) || !cell.classList.contains('sortable')) { return; + } let sortOrder = DataGrid.DataGrid.Order.Ascending; - if ((cell === this._sortColumnCell) && this.isSortOrderAscending()) + if ((cell === this._sortColumnCell) && this.isSortOrderAscending()) { sortOrder = DataGrid.DataGrid.Order.Descending; + } - if (this._sortColumnCell) + if (this._sortColumnCell) { this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending, DataGrid.DataGrid.Order.Descending); + } this._sortColumnCell = cell; cell.classList.add(sortOrder); @@ -974,8 +1032,9 @@ * @param {!DataGrid.DataGrid.Order} sortOrder */ markColumnAsSortedBy(columnId, sortOrder) { - if (this._sortColumnCell) + if (this._sortColumnCell) { this._sortColumnCell.classList.remove(DataGrid.DataGrid.Order.Ascending, DataGrid.DataGrid.Order.Descending); + } this._sortColumnCell = this._headerTableHeaders[columnId]; this._sortColumnCell.classList.add(sortOrder); } @@ -994,18 +1053,21 @@ _mouseDownInDataTable(event) { const target = /** @type {!Node} */ (event.target); const gridNode = this.dataGridNodeFromNode(target); - if (!gridNode || !gridNode.selectable || gridNode.isEventWithinDisclosureTriangle(event)) + if (!gridNode || !gridNode.selectable || gridNode.isEventWithinDisclosureTriangle(event)) { return; + } const columnId = this.columnIdFromNode(target); - if (columnId && this._columns[columnId].nonSelectable) + if (columnId && this._columns[columnId].nonSelectable) { return; + } if (event.metaKey) { - if (gridNode.selected) + if (gridNode.selected) { gridNode.deselect(); - else + } else { gridNode.select(); + } } else { gridNode.select(); this.dispatchEventToListeners(DataGrid.DataGrid.Events.OpenedNode, gridNode); @@ -1046,16 +1108,18 @@ } if (target.isSelfOrDescendant(this._headerTableBody)) { - if (this._headerContextMenuCallback) + if (this._headerContextMenuCallback) { this._headerContextMenuCallback(contextMenu); - else + } else { contextMenu.show(); + } return; } const gridNode = this.dataGridNodeFromNode(target); - if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode)) + if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode)) { contextMenu.defaultSection().appendItem(Common.UIString('Refresh'), this._refreshCallback.bind(this)); + } if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { if (this._editCallback) { @@ -1069,10 +1133,12 @@ } } } - if (this._deleteCallback && gridNode !== this.creationNode) + if (this._deleteCallback && gridNode !== this.creationNode) { contextMenu.defaultSection().appendItem(Common.UIString('Delete'), this._deleteCallback.bind(this, gridNode)); - if (this._rowContextMenuCallback) + } + if (this._rowContextMenuCallback) { this._rowContextMenuCallback(contextMenu, gridNode); + } } contextMenu.show(); @@ -1083,19 +1149,22 @@ */ _clickInDataTable(event) { const gridNode = this.dataGridNodeFromNode(/** @type {!Node} */ (event.target)); - if (!gridNode || !gridNode.hasChildren() || !gridNode.isEventWithinDisclosureTriangle(event)) + if (!gridNode || !gridNode.hasChildren() || !gridNode.isEventWithinDisclosureTriangle(event)) { return; + } if (gridNode.expanded) { - if (event.altKey) + if (event.altKey) { gridNode.collapseRecursively(); - else + } else { gridNode.collapse(); + } } else { - if (event.altKey) + if (event.altKey) { gridNode.expandRecursively(); - else + } else { gridNode.expand(); + } } } @@ -1125,8 +1194,9 @@ */ _resizerDragging(event) { const resizer = this._currentResizer; - if (!resizer) + if (!resizer) { return; + } // Constrain the dragpoint to be within the containing div of the // datagrid. @@ -1137,8 +1207,9 @@ // column directly to the left and the column directly to the right. let leftCellIndex = resizer.__index; let rightCellIndex = leftCellIndex + 1; - for (let i = 0; i < leftCellIndex; i++) + for (let i = 0; i < leftCellIndex; i++) { leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth; + } // Differences for other resize methods if (this._resizeMethod === DataGrid.DataGrid.ResizeMethod.Last) { @@ -1154,8 +1225,9 @@ // Give each column some padding so that they don't disappear. const leftMinimum = leftEdgeOfPreviousColumn + DataGrid.DataGrid.ColumnResizePadding; const rightMaximum = rightEdgeOfNextColumn - DataGrid.DataGrid.ColumnResizePadding; - if (leftMinimum > rightMaximum) + if (leftMinimum > rightMaximum) { return; + } dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum); @@ -1195,12 +1267,14 @@ * @return {number} */ columnOffset(columnId) { - if (!this.element.offsetWidth) + if (!this.element.offsetWidth) { return 0; + } for (let i = 1; i < this._visibleColumnsArray.length; ++i) { if (columnId === this._visibleColumnsArray[i].id) { - if (this._resizers[i - 1]) + if (this._resizers[i - 1]) { return this._resizers[i - 1].__position; + } } } return 0; @@ -1210,8 +1284,9 @@ * @return {!DataGrid.DataGridWidget} */ asWidget() { - if (!this._dataGridWidget) + if (!this._dataGridWidget) { this._dataGridWidget = new DataGrid.DataGridWidget(this); + } return this._dataGridWidget; } @@ -1351,18 +1426,24 @@ this._element = createElementWithClass('tr', 'data-grid-data-grid-node'); this._element._dataGridNode = this; - if (this._hasChildren) + if (this._hasChildren) { this._element.classList.add('parent'); - if (this.expanded) + } + if (this.expanded) { this._element.classList.add('expanded'); - if (this.selected) + } + if (this.selected) { this._element.classList.add('selected'); - if (this.revealed) + } + if (this.revealed) { this._element.classList.add('revealed'); - if (this.dirty) + } + if (this.dirty) { this._element.classList.add('dirty'); - if (this.inactive) + } + if (this.inactive) { this._element.classList.add('inactive'); + } return this._element; } @@ -1387,8 +1468,9 @@ createCells(element) { element.removeChildren(); const columnsArray = this.dataGrid._visibleColumnsArray; - for (let i = 0; i < columnsArray.length; ++i) + for (let i = 0; i < columnsArray.length; ++i) { element.appendChild(this.createCell(columnsArray[i].id)); + } element.appendChild(this._createTDWithClass('corner')); } @@ -1411,8 +1493,9 @@ * @return {boolean} */ get revealed() { - if (this._revealed !== undefined) + if (this._revealed !== undefined) { return this._revealed; + } let currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { @@ -1432,16 +1515,19 @@ * @param {boolean} x */ set revealed(x) { - if (this._revealed === x) + if (this._revealed === x) { return; + } this._revealed = x; - if (this._element) + if (this._element) { this._element.classList.toggle('revealed', this._revealed); + } - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = x && this.expanded; + } } /** @@ -1455,15 +1541,18 @@ * @param {boolean} dirty */ setDirty(dirty) { - if (this._dirty === dirty) + if (this._dirty === dirty) { return; + } this._dirty = dirty; - if (!this._element) + if (!this._element) { return; - if (dirty) + } + if (dirty) { this._element.classList.add('dirty'); - else + } else { this._element.classList.remove('dirty'); + } } @@ -1478,15 +1567,18 @@ * @param {boolean} inactive */ setInactive(inactive) { - if (this._inactive === inactive) + if (this._inactive === inactive) { return; + } this._inactive = inactive; - if (!this._element) + if (!this._element) { return; - if (inactive) + } + if (inactive) { this._element.classList.add('inactive'); - else + } else { this._element.classList.remove('inactive'); + } } /** @@ -1500,13 +1592,15 @@ * @param {boolean} x */ setHasChildren(x) { - if (this._hasChildren === x) + if (this._hasChildren === x) { return; + } this._hasChildren = x; - if (!this._element) + if (!this._element) { return; + } this._element.classList.toggle('parent', this._hasChildren); this._element.classList.toggle('expanded', this._hasChildren && this.expanded); @@ -1516,12 +1610,14 @@ * @return {number} */ get depth() { - if (this._depth !== undefined) + if (this._depth !== undefined) { return this._depth; - if (this.parent && !this.parent._isRoot) + } + if (this.parent && !this.parent._isRoot) { this._depth = this.parent.depth + 1; - else + } else { this._depth = 0; + } return this._depth; } @@ -1544,8 +1640,9 @@ */ set shouldRefreshChildren(x) { this._shouldRefreshChildren = x; - if (x && this.expanded) + if (x && this.expanded) { this.expand(); + } } /** @@ -1559,10 +1656,11 @@ * @param {boolean} x */ set selected(x) { - if (x) + if (x) { this.select(); - else + } else { this.deselect(); + } } /** @@ -1576,17 +1674,20 @@ * @param {boolean} x */ set expanded(x) { - if (x) + if (x) { this.expand(); - else + } else { this.collapse(); + } } refresh() { - if (!this.dataGrid) + if (!this.dataGrid) { this._element = null; - if (!this._element) + } + if (!this._element) { return; + } this.createCells(this._element); } @@ -1597,8 +1698,9 @@ _createTDWithClass(className) { const cell = createElementWithClass('td', className); const cellClass = this.dataGrid._cellClass; - if (cellClass) + if (cellClass) { cell.classList.add(cellClass); + } return cell; } @@ -1611,13 +1713,15 @@ cell[DataGrid.DataGrid._columnIdSymbol] = columnId; const alignment = this.dataGrid._columns[columnId].align; - if (alignment) + if (alignment) { cell.classList.add(alignment); + } if (columnId === this.dataGrid.disclosureColumnId) { cell.classList.add('disclosure'); - if (this.leftPadding) + if (this.leftPadding) { cell.style.setProperty('padding-left', this.leftPadding + 'px'); + } } return cell; @@ -1630,10 +1734,11 @@ createCell(columnId) { const cell = this.createTD(columnId); const data = this.data[columnId]; - if (data instanceof Node) + if (data instanceof Node) { cell.appendChild(data); - else if (data !== null) + } else if (data !== null) { DataGrid.DataGrid.setElementText(cell, /** @type {string} */ (data), !!this.dataGrid._columns[columnId].longText); + } return cell; } @@ -1659,12 +1764,15 @@ // @TODO(allada) This is a hack to make sure ViewportDataGrid can clean up these caches. Try Not To Use. delete this._depth; delete this._revealed; - if (onlyCaches) + if (onlyCaches) { return; - if (this.previousSibling) + } + if (this.previousSibling) { this.previousSibling.nextSibling = this.nextSibling; - if (this.nextSibling) + } + if (this.nextSibling) { this.nextSibling.previousSibling = this.previousSibling; + } this.dataGrid = null; this.parent = null; this.nextSibling = null; @@ -1677,16 +1785,20 @@ * @param {number} index */ insertChild(child, index) { - if (!child) + if (!child) { throw 'insertChild: Node can\'t be undefined or null.'; + } if (child.parent === this) { const currentIndex = this.children.indexOf(child); - if (currentIndex < 0) + if (currentIndex < 0) { console.assert(false, 'Inconsistent DataGrid state'); - if (currentIndex === index) + } + if (currentIndex === index) { return; - if (currentIndex < index) + } + if (currentIndex < index) { --index; + } } child.remove(); @@ -1709,40 +1821,48 @@ current = current.traverseNextNode(false, child, true); } - if (this.expanded) + if (this.expanded) { child._attach(); - if (!this.revealed) + } + if (!this.revealed) { child.revealed = false; + } } remove() { - if (this.parent) + if (this.parent) { this.parent.removeChild(this); + } } /** * @param {!NODE_TYPE} child */ removeChild(child) { - if (!child) + if (!child) { throw 'removeChild: Node can\'t be undefined or null.'; - if (child.parent !== this) + } + if (child.parent !== this) { throw 'removeChild: Node is not a child of this node.'; + } - if (this.dataGrid) + if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(child, false); + } child._detach(); child.resetNode(); this.children.remove(child, true); - if (this.children.length <= 0) + if (this.children.length <= 0) { this.setHasChildren(false); + } } removeChildren() { - if (this.dataGrid) + if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(this, true); + } for (let i = 0; i < this.children.length; ++i) { const child = this.children[i]; child._detach(); @@ -1757,37 +1877,44 @@ * @param {number} myIndex */ recalculateSiblings(myIndex) { - if (!this.parent) + if (!this.parent) { return; + } const previousChild = this.parent.children[myIndex - 1] || null; - if (previousChild) + if (previousChild) { previousChild.nextSibling = this; + } this.previousSibling = previousChild; const nextChild = this.parent.children[myIndex + 1] || null; - if (nextChild) + if (nextChild) { nextChild.previousSibling = this; + } this.nextSibling = nextChild; } collapse() { - if (this._isRoot) + if (this._isRoot) { return; - if (this._element) + } + if (this._element) { this._element.classList.remove('expanded'); + } this._expanded = false; - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = false; + } } collapseRecursively() { let item = this; while (item) { - if (item.expanded) + if (item.expanded) { item.collapse(); + } item = item.traverseNextNode(false, this, true); } } @@ -1796,27 +1923,32 @@ } expand() { - if (!this._hasChildren || this.expanded) + if (!this._hasChildren || this.expanded) { return; - if (this._isRoot) + } + if (this._isRoot) { return; + } if (this.revealed && !this._shouldRefreshChildren) { - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i].revealed = true; + } } if (this._shouldRefreshChildren) { - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i]._detach(); + } this.populate(); if (this._attached) { for (let i = 0; i < this.children.length; ++i) { const child = this.children[i]; - if (this.revealed) + if (this.revealed) { child.revealed = true; + } child._attach(); } } @@ -1824,8 +1956,9 @@ this._shouldRefreshChildren = false; } - if (this._element) + if (this._element) { this._element.classList.add('expanded'); + } this._expanded = true; } @@ -1839,12 +1972,14 @@ } reveal() { - if (this._isRoot) + if (this._isRoot) { return; + } let currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { - if (!currentAncestor.expanded) + if (!currentAncestor.expanded) { currentAncestor.expand(); + } currentAncestor = currentAncestor.parent; } @@ -1855,25 +1990,30 @@ * @param {boolean=} supressSelectedEvent */ select(supressSelectedEvent) { - if (!this.dataGrid || !this.selectable || this.selected) + if (!this.dataGrid || !this.selectable || this.selected) { return; + } - if (this.dataGrid.selectedNode) + if (this.dataGrid.selectedNode) { this.dataGrid.selectedNode.deselect(); + } this._selected = true; this.dataGrid.selectedNode = this; - if (this._element) + if (this._element) { this._element.classList.add('selected'); + } - if (!supressSelectedEvent) + if (!supressSelectedEvent) { this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.SelectedNode, this); + } } revealAndSelect() { - if (this._isRoot) + if (this._isRoot) { return; + } this.reveal(); this.select(); } @@ -1882,17 +2022,20 @@ * @param {boolean=} supressDeselectedEvent */ deselect(supressDeselectedEvent) { - if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) + if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) { return; + } this._selected = false; this.dataGrid.selectedNode = null; - if (this._element) + if (this._element) { this._element.classList.remove('selected'); + } - if (!supressDeselectedEvent) + if (!supressDeselectedEvent) { this.dataGrid.dispatchEventToListeners(DataGrid.DataGrid.Events.DeselectedNode); + } } /** @@ -1903,36 +2046,43 @@ * @return {?NODE_TYPE} */ traverseNextNode(skipHidden, stayWithin, dontPopulate, info) { - if (!dontPopulate && this._hasChildren) + if (!dontPopulate && this._hasChildren) { this.populate(); + } - if (info) + if (info) { info.depthChange = 0; + } let node = (!skipHidden || this.revealed) ? this.children[0] : null; if (node && (!skipHidden || this.expanded)) { - if (info) + if (info) { info.depthChange = 1; + } return node; } - if (this === stayWithin) + if (this === stayWithin) { return null; + } node = (!skipHidden || this.revealed) ? this.nextSibling : null; - if (node) + if (node) { return node; + } node = this; while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) { - if (info) + if (info) { info.depthChange -= 1; + } node = node.parent; } - if (!node) + if (!node) { return null; + } return (!skipHidden || node.revealed) ? node.nextSibling : null; } @@ -1944,21 +2094,25 @@ */ traversePreviousNode(skipHidden, dontPopulate) { let node = (!skipHidden || this.revealed) ? this.previousSibling : null; - if (!dontPopulate && node && node._hasChildren) + if (!dontPopulate && node && node._hasChildren) { node.populate(); + } while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) { - if (!dontPopulate && node._hasChildren) + if (!dontPopulate && node._hasChildren) { node.populate(); + } node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null); } - if (node) + if (node) { return node; + } - if (!this.parent || this.parent._isRoot) + if (!this.parent || this.parent._isRoot) { return null; + } return this.parent; } @@ -1968,19 +2122,22 @@ * @return {boolean} */ isEventWithinDisclosureTriangle(event) { - if (!this._hasChildren) + if (!this._hasChildren) { return false; + } const cell = event.target.enclosingNodeOrSelfWithNodeName('td'); - if (!cell || !cell.classList.contains('disclosure')) + if (!cell || !cell.classList.contains('disclosure')) { return false; + } const left = cell.totalOffsetLeft() + this.leftPadding; return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth; } _attach() { - if (!this.dataGrid || this._attached) + if (!this.dataGrid || this._attached) { return; + } this._attached = true; @@ -1989,39 +2146,47 @@ this.dataGrid.dataTableBody.insertBefore(this.element(), previousElement.nextSibling); if (this.expanded) { - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i]._attach(); + } } } _detach() { - if (!this._attached) + if (!this._attached) { return; + } this._attached = false; - if (this._element) + if (this._element) { this._element.remove(); + } - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i]._detach(); + } } savePosition() { - if (this._savedPosition) + if (this._savedPosition) { return; + } - if (!this.parent) + if (!this.parent) { throw 'savePosition: Node must have a parent.'; + } this._savedPosition = {parent: this.parent, index: this.parent.children.indexOf(this)}; } restorePosition() { - if (!this._savedPosition) + if (!this._savedPosition) { return; + } - if (this.parent !== this._savedPosition.parent) + if (this.parent !== this._savedPosition.parent) { this._savedPosition.parent.insertChild(this, this._savedPosition.index); + } this._savedPosition = null; } @@ -2091,8 +2256,9 @@ */ detachChildWidgets() { super.detachChildWidgets(); - for (const dataGrid of this._dataGrids) + for (const dataGrid of this._dataGrids) { this.element.removeChild(dataGrid.element); + } this._dataGrids = []; } }; \ No newline at end of file
diff --git a/third_party/blink/renderer/devtools/front_end/data_grid/ShowMoreDataGridNode.js b/third_party/blink/renderer/devtools/front_end/data_grid/ShowMoreDataGridNode.js index 0ac60d7c..f5ccb47 100644 --- a/third_party/blink/renderer/devtools/front_end/data_grid/ShowMoreDataGridNode.js +++ b/third_party/blink/renderer/devtools/front_end/data_grid/ShowMoreDataGridNode.js
@@ -105,8 +105,9 @@ const cell = this.createTD(columnIdentifier); if (!this._hasCells) { this._hasCells = true; - if (this.depth) + if (this.depth) { cell.style.setProperty('padding-left', (this.depth * this.dataGrid.indentWidth) + 'px'); + } cell.appendChild(this.showNext); cell.appendChild(this.showAll); cell.appendChild(this.showLast);
diff --git a/third_party/blink/renderer/devtools/front_end/data_grid/SortableDataGrid.js b/third_party/blink/renderer/devtools/front_end/data_grid/SortableDataGrid.js index 56df1218..b2f76edc 100644 --- a/third_party/blink/renderer/devtools/front_end/data_grid/SortableDataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/data_grid/SortableDataGrid.js
@@ -76,18 +76,21 @@ */ static create(columnNames, values) { const numColumns = columnNames.length; - if (!numColumns) + if (!numColumns) { return null; + } const columns = /** @type {!Array<!DataGrid.DataGrid.ColumnDescriptor>} */ ([]); - for (let i = 0; i < columnNames.length; ++i) + for (let i = 0; i < columnNames.length; ++i) { columns.push({id: String(i), title: columnNames[i], width: columnNames[i].length, sortable: true}); + } const nodes = []; for (let i = 0; i < values.length / numColumns; ++i) { const data = {}; - for (let j = 0; j < columnNames.length; ++j) + for (let j = 0; j < columnNames.length; ++j) { data[j] = values[numColumns * i + j]; + } const node = new DataGrid.SortableDataGridNode(data); node.selectable = false; @@ -97,16 +100,18 @@ const dataGrid = new DataGrid.SortableDataGrid(columns); const length = nodes.length; const rootNode = dataGrid.rootNode(); - for (let i = 0; i < length; ++i) + for (let i = 0; i < length; ++i) { rootNode.appendChild(nodes[i]); + } dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, sortDataGrid); function sortDataGrid() { const nodes = dataGrid.rootNode().children; const sortColumnId = dataGrid.sortColumnId(); - if (!sortColumnId) + if (!sortColumnId) { return; + } let columnIsNumeric = true; for (let i = 0; i < nodes.length; i++) { @@ -167,9 +172,11 @@ _sortChildren() { this.children.sort(this.dataGrid._sortingFunction); - for (let i = 0; i < this.children.length; ++i) + for (let i = 0; i < this.children.length; ++i) { this.children[i].recalculateSiblings(i); - for (const child of this.children) + } + for (const child of this.children) { child._sortChildren(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/data_grid/ViewportDataGrid.js b/third_party/blink/renderer/devtools/front_end/data_grid/ViewportDataGrid.js index d60f61f..4ee8468e2f 100644 --- a/third_party/blink/renderer/devtools/front_end/data_grid/ViewportDataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/data_grid/ViewportDataGrid.js
@@ -73,8 +73,9 @@ * @override */ onResize() { - if (this._stickToBottom) + if (this._stickToBottom) { this.scrollContainer.scrollTop = this.scrollContainer.scrollHeight - this.scrollContainer.clientHeight; + } this.scheduleUpdate(); super.onResize(); } @@ -91,8 +92,9 @@ */ _onScroll(event) { this._stickToBottom = this.scrollContainer.isScrolledToBottom(); - if (this._lastScrollTop !== this.scrollContainer.scrollTop) + if (this._lastScrollTop !== this.scrollContainer.scrollTop) { this.scheduleUpdate(true); + } } /** @@ -106,11 +108,13 @@ * @param {boolean=} isFromUser */ scheduleUpdate(isFromUser) { - if (this._stickToBottom && isFromUser) + if (this._stickToBottom && isFromUser) { this._stickToBottom = this.scrollContainer.isScrolledToBottom(); + } this._updateIsFromUser = this._updateIsFromUser || isFromUser; - if (this._updateAnimationFrameId) + if (this._updateAnimationFrameId) { return; + } this._updateAnimationFrameId = this.element.window().requestAnimationFrame(this._update.bind(this)); } @@ -137,25 +141,29 @@ */ _calculateVisibleNodes(clientHeight, scrollTop) { const nodes = this.rootNode().flatChildren(); - if (this._inline) + if (this._inline) { return {topPadding: 0, bottomPadding: 0, contentHeight: 0, visibleNodes: nodes, offset: 0}; + } const size = nodes.length; let i = 0; let y = 0; - for (; i < size && y + nodes[i].nodeSelfHeight() < scrollTop; ++i) + for (; i < size && y + nodes[i].nodeSelfHeight() < scrollTop; ++i) { y += nodes[i].nodeSelfHeight(); + } const start = i; const topPadding = y; - for (; i < size && y < scrollTop + clientHeight; ++i) + for (; i < size && y < scrollTop + clientHeight; ++i) { y += nodes[i].nodeSelfHeight(); + } const end = i; let bottomPadding = 0; - for (; i < size; ++i) + for (; i < size; ++i) { bottomPadding += nodes[i].nodeSelfHeight(); + } return { topPadding: topPadding, @@ -172,8 +180,9 @@ _contentHeight() { const nodes = this.rootNode().flatChildren(); let result = 0; - for (let i = 0, size = nodes.length; i < size; ++i) + for (let i = 0, size = nodes.length; i < size; ++i) { result += nodes[i].nodeSelfHeight(); + } return result; } @@ -187,8 +196,9 @@ let scrollTop = this.scrollContainer.scrollTop; const currentScrollTop = scrollTop; const maxScrollTop = Math.max(0, this._contentHeight() - clientHeight); - if (!this._updateIsFromUser && this._stickToBottom) + if (!this._updateIsFromUser && this._stickToBottom) { scrollTop = maxScrollTop; + } this._updateIsFromUser = false; scrollTop = Math.min(maxScrollTop, scrollTop); @@ -212,8 +222,9 @@ const nodes = this.rootNode().flatChildren(); const index = nodes.indexOf(visibleNodes[0]); this._updateStripesClass(!!(index % 2)); - if (this._stickToBottom && index !== -1 && !!(index % 2) !== this._firstVisibleIsStriped) + if (this._stickToBottom && index !== -1 && !!(index % 2) !== this._firstVisibleIsStriped) { offset += 1; + } } this._firstVisibleIsStriped = !!(offset % 2); @@ -222,16 +233,18 @@ const node = visibleNodes[i]; const element = node.element(); node.setStriped((offset + i) % 2 === 0); - if (element !== previousElement.nextSibling) + if (element !== previousElement.nextSibling) { tBody.insertBefore(element, previousElement.nextSibling); + } node.revealed = true; previousElement = element; } this.setVerticalPadding(viewportState.topPadding, viewportState.bottomPadding); this._lastScrollTop = scrollTop; - if (scrollTop !== currentScrollTop) + if (scrollTop !== currentScrollTop) { this.scrollContainer.scrollTop = scrollTop; + } const contentFits = viewportState.contentHeight <= clientHeight && viewportState.topPadding + viewportState.bottomPadding === 0; if (contentFits !== this.element.classList.contains('data-grid-fits-viewport')) { @@ -248,11 +261,13 @@ _revealViewportNode(node) { const nodes = this.rootNode().flatChildren(); const index = nodes.indexOf(node); - if (index === -1) + if (index === -1) { return; + } let fromY = 0; - for (let i = 0; i < index; ++i) + for (let i = 0; i < index; ++i) { fromY += nodes[i].nodeSelfHeight(); + } const toY = fromY + node.nodeSelfHeight(); let scrollTop = this.scrollContainer.scrollTop; @@ -327,16 +342,18 @@ clearFlatNodes() { this._flatNodes = null; const parent = /** @type {!DataGrid.ViewportDataGridNode} */ (this.parent); - if (parent) + if (parent) { parent.clearFlatNodes(); + } } /** * @return {!Array<!DataGrid.ViewportDataGridNode>} */ flatChildren() { - if (this._flatNodes) + if (this._flatNodes) { return this._flatNodes; + } /** @type {!Array<!DataGrid.ViewportDataGridNode>} */ const flatNodes = []; /** @type {!Array<!Array<!DataGrid.ViewportDataGridNode>>} */ @@ -371,22 +388,27 @@ this.clearFlatNodes(); if (child.parent === this) { const currentIndex = this.children.indexOf(child); - if (currentIndex < 0) + if (currentIndex < 0) { console.assert(false, 'Inconsistent DataGrid state'); - if (currentIndex === index) + } + if (currentIndex === index) { return; - if (currentIndex < index) + } + if (currentIndex < index) { --index; + } } child.remove(); child.parent = this; child.dataGrid = this.dataGrid; - if (!this.children.length) + if (!this.children.length) { this.setHasChildren(true); + } this.children.splice(index, 0, child); child.recalculateSiblings(index); - if (this.expanded) + if (this.expanded) { this.dataGrid.scheduleUpdateStructure(); + } } /** @@ -395,22 +417,28 @@ */ removeChild(child) { this.clearFlatNodes(); - if (this.dataGrid) + if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(child, false); - if (child.previousSibling) + } + if (child.previousSibling) { child.previousSibling.nextSibling = child.nextSibling; - if (child.nextSibling) + } + if (child.nextSibling) { child.nextSibling.previousSibling = child.previousSibling; - if (child.parent !== this) + } + if (child.parent !== this) { throw 'removeChild: Node is not a child of this node.'; + } this.children.remove(child, true); child._unlink(); - if (!this.children.length) + if (!this.children.length) { this.setHasChildren(false); - if (this.expanded) + } + if (this.expanded) { this.dataGrid.scheduleUpdateStructure(); + } } /** @@ -418,19 +446,23 @@ */ removeChildren() { this.clearFlatNodes(); - if (this.dataGrid) + if (this.dataGrid) { this.dataGrid.updateSelectionBeforeRemoval(this, true); - for (let i = 0; i < this.children.length; ++i) + } + for (let i = 0; i < this.children.length; ++i) { this.children[i]._unlink(); + } this.children = []; - if (this.expanded) + if (this.expanded) { this.dataGrid.scheduleUpdateStructure(); + } } _unlink() { - if (this.attached()) + if (this.attached()) { this.existingElement().remove(); + } this.resetNode(); } @@ -438,15 +470,17 @@ * @override */ collapse() { - if (!this.expanded) + if (!this.expanded) { return; + } this.clearFlatNodes(); /** * @suppress {accessControls} */ this._expanded = false; - if (this.existingElement()) + if (this.existingElement()) { this.existingElement().classList.remove('expanded'); + } this.dataGrid.scheduleUpdateStructure(); } @@ -454,8 +488,9 @@ * @override */ expand() { - if (this.expanded) + if (this.expanded) { return; + } this.dataGrid._stickToBottom = false; this.clearFlatNodes(); super.expand();
diff --git a/third_party/blink/renderer/devtools/front_end/data_grid_test_runner/DataGridTestRunner.js b/third_party/blink/renderer/devtools/front_end/data_grid_test_runner/DataGridTestRunner.js index 8a11a8f8..2e802be 100644 --- a/third_party/blink/renderer/devtools/front_end/data_grid_test_runner/DataGridTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/data_grid_test_runner/DataGridTestRunner.js
@@ -8,22 +8,27 @@ */ DataGridTestRunner.dumpDataGrid = function(root, descentIntoCollapsed, prefix) { - if (!prefix) + if (!prefix) { prefix = ''; + } const suffix = root.selected ? ' <- selected' : ''; const columnKeys = root.dataGrid._columnsArray.map(column => column.id); const outputColumns = []; for (const key of columnKeys) { - if (key in root.data) + if (key in root.data) { outputColumns.push(root.data[key]); + } } - if (outputColumns.length) + if (outputColumns.length) { TestRunner.addResult(prefix + outputColumns.join(' | ') + suffix); + } - if (!descentIntoCollapsed && !root.expanded) + if (!descentIntoCollapsed && !root.expanded) { return; - for (const child of root.children) + } + for (const child of root.children) { DataGridTestRunner.dumpDataGrid(child, descentIntoCollapsed, prefix + ' '); + } }; DataGridTestRunner.validateDataGrid = function(root) { @@ -32,17 +37,21 @@ for (let i = 0; i < children.length; ++i) { const child = children[i]; - if (child.parent !== root) + if (child.parent !== root) { throw 'Wrong parent for child ' + child.data.id + ' of ' + root.data.id; + } - if (child.nextSibling !== ((i + 1 === children.length ? null : children[i + 1]))) + if (child.nextSibling !== ((i + 1 === children.length ? null : children[i + 1]))) { throw 'Wrong child.nextSibling for ' + child.data.id + ' (' + i + ' of ' + children.length + ') '; + } - if (child.previousSibling !== ((i ? children[i - 1] : null))) + if (child.previousSibling !== ((i ? children[i - 1] : null))) { throw 'Wrong child.previousSibling for ' + child.data.id + ' (' + i + ' of ' + children.length + ') '; + } - if (child.parent && !child.parent._isRoot && child.depth !== root.depth + 1) + if (child.parent && !child.parent._isRoot && child.depth !== root.depth + 1) { throw 'Wrong depth for ' + child.data.id + ' expected ' + (root.depth + 1) + ' but got ' + child.depth; + } DataGridTestRunner.validateDataGrid(child); } @@ -50,14 +59,16 @@ const selectedNode = root.dataGrid.selectedNode; if (!root.parent && selectedNode) { - if (!selectedNode.selectable) + if (!selectedNode.selectable) { throw 'Selected node is not selectable'; + } let node = selectedNode; for (; node && node !== root; node = node.parent) { } - if (!node) + if (!node) { throw 'Selected node (' + selectedNode.data.id + ') is not within the DataGrid'; + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js b/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js index 59f72dd..581f019e 100644 --- a/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js +++ b/third_party/blink/renderer/devtools/front_end/devices/DevicesView.js
@@ -56,8 +56,9 @@ * @return {!Devices.DevicesView} */ static _instance() { - if (!Devices.DevicesView._instanceObject) + if (!Devices.DevicesView._instanceObject) { Devices.DevicesView._instanceObject = new Devices.DevicesView(); + } return Devices.DevicesView._instanceObject; } @@ -66,8 +67,9 @@ * @param {!UI.Widget} view */ _selectSidebarListItem(listItem, view) { - if (this._selectedListItem === listItem) + if (this._selectedListItem === listItem) { return; + } if (this._selectedListItem) { this._selectedListItem.classList.remove('selected'); @@ -89,13 +91,15 @@ .slice() .filter(d => d.adbSerial.toUpperCase() !== 'WEBRTC' && d.adbSerial.toUpperCase() !== 'LOCALHOST'); for (const device of this._devices) { - if (!device.adbConnected) + if (!device.adbConnected) { device.adbModel = Common.UIString('Unknown'); + } } const ids = new Set(); - for (const device of this._devices) + for (const device of this._devices) { ids.add(device.id); + } let selectedRemoved = false; for (const deviceId of this._viewById.keys()) { @@ -104,8 +108,9 @@ this._listItemById.remove(deviceId); this._viewById.remove(deviceId); listItem.remove(); - if (listItem === this._selectedListItem) + if (listItem === this._selectedListItem) { selectedRemoved = true; + } } } @@ -128,8 +133,9 @@ view.update(device); } - if (selectedRemoved) + if (selectedRemoved) { this._selectSidebarListItem(this._discoveryListItem, this._discoveryView); + } this._updateFooter(); } @@ -161,13 +167,15 @@ const status = /** @type {!Adb.PortForwardingStatus} */ (event.data); for (const deviceId in status) { const view = this._viewById.get(deviceId); - if (view) + if (view) { view.portForwardingStatusChanged(status[deviceId]); + } } for (const deviceId of this._viewById.keys()) { const view = this._viewById.get(deviceId); - if (view && !(deviceId in status)) + if (view && !(deviceId in status)) { view.portForwardingStatusChanged({ports: {}, browserId: ''}); + } } } @@ -225,8 +233,9 @@ this._portForwardingView = new Devices.DevicesView.PortForwardingView((enabled, config) => { this._config.portForwardingEnabled = enabled; this._config.portForwardingConfig = {}; - for (const rule of config) + for (const rule of config) { this._config.portForwardingConfig[rule.port] = rule.address; + } InspectorFrontendHost.setDevicesDiscoveryConfig(this._config); }); this._portForwardingView.show(this.element); @@ -348,8 +357,9 @@ commitEdit(rule, editor, isNew) { rule.port = editor.control('port').value.trim(); rule.address = editor.control('address').value.trim(); - if (isNew) + if (isNew) { this._portForwardingConfig.push(rule); + } this._update(); } @@ -369,8 +379,9 @@ * @return {!UI.ListWidget.Editor<!Adb.PortForwardingRule>} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -403,8 +414,9 @@ errorMessage = ls`Device port must be a number`; } else { const port = parseInt(match[1], 10); - if (port < 1024 || port > 65535) + if (port < 1024 || port > 65535) { errorMessage = ls`Device port number must be between 1024 and 65535`; + } for (let i = 0; i < this._portForwardingConfig.length; ++i) { if (i !== index && this._portForwardingConfig[i].port === value) { errorMessage = ls`Device port numbers can only be used once`; @@ -413,8 +425,9 @@ } } - if (errorMessage) + if (errorMessage) { return {valid: false, errorMessage}; + } return {valid: true}; } @@ -436,12 +449,14 @@ errorMessage = ls`Local address must match this pattern: dev.example.corp:3333`; } else { const port = parseInt(match[2], 10); - if (port > 65535) + if (port > 65535) { errorMessage = ls`Port number must be not greater than 65535`; + } } - if (errorMessage) + if (errorMessage) { return {valid: false, errorMessage}; + } return {valid: true}; } } @@ -480,19 +495,22 @@ * @param {!Adb.Device} device */ update(device) { - if (!this._device || this._device.adbModel !== device.adbModel) + if (!this._device || this._device.adbModel !== device.adbModel) { this._deviceTitle.textContent = device.adbModel; + } - if (!this._device || this._device.adbSerial !== device.adbSerial) + if (!this._device || this._device.adbSerial !== device.adbSerial) { this._deviceSerial.textContent = '#' + device.adbSerial; + } this._deviceOffline.classList.toggle('hidden', device.adbConnected); this._noBrowsers.classList.toggle('hidden', !device.adbConnected || !!device.browsers.length); this._browsers.classList.toggle('hidden', !device.adbConnected || !device.browsers.length); const browserIds = new Set(); - for (const browser of device.browsers) + for (const browser of device.browsers) { browserIds.add(browser.id); + } for (const browserId of this._browserById.keys()) { if (!browserIds.has(browserId)) { @@ -584,15 +602,17 @@ _updateBrowserSection(section, browser) { if (!section.browser || section.browser.adbBrowserName !== browser.adbBrowserName || section.browser.adbBrowserVersion !== browser.adbBrowserVersion) { - if (browser.adbBrowserVersion) + if (browser.adbBrowserVersion) { section.title.textContent = String.sprintf('%s (%s)', browser.adbBrowserName, browser.adbBrowserVersion); - else + } else { section.title.textContent = browser.adbBrowserName; + } } const pageIds = new Set(); - for (const page of browser.pages) + for (const page of browser.pages) { pageIds.add(page.id); + } for (const pageId of section.pageSections.keys()) { if (!pageIds.has(pageId)) { @@ -610,13 +630,15 @@ section.pages.appendChild(pageSection.element); } this._updatePageSection(pageSection, page); - if (!index && section.pages.firstChild !== pageSection.element) + if (!index && section.pages.firstChild !== pageSection.element) { section.pages.insertBefore(pageSection.element, section.pages.firstChild); + } } const kViewMoreCount = 3; - for (let index = 0, element = section.pages.firstChild; element; element = element.nextSibling, ++index) + for (let index = 0, element = section.pages.firstChild; element; element = element.nextSibling, ++index) { element.classList.toggle('device-view-more-page', index >= kViewMoreCount); + } section.viewMore.classList.toggle('device-needs-view-more', browser.pages.length > kViewMoreCount); section.newTab.classList.toggle('hidden', !browser.adbBrowserChromeVersion); section.browser = browser; @@ -654,8 +676,9 @@ * @param {string} action */ function doAction(action) { - if (section.page) + if (section.page) { InspectorFrontendHost.performActionOnRemotePage(section.page.id, action); + } } } @@ -682,8 +705,9 @@ */ portForwardingStatusChanged(status) { const json = JSON.stringify(status); - if (json === this._cachedPortStatus) + if (json === this._cachedPortStatus) { return; + } this._cachedPortStatus = json; this._portStatus.removeChildren(); @@ -693,17 +717,19 @@ const error = []; let empty = true; for (const port in status.ports) { - if (!status.ports.hasOwnProperty(port)) + if (!status.ports.hasOwnProperty(port)) { continue; + } empty = false; const portStatus = status.ports[port]; const portNumber = createElementWithClass('div', 'device-view-port-number monospace'); portNumber.textContent = ':' + port; - if (portStatus >= 0) + if (portStatus >= 0) { this._portStatus.appendChild(portNumber); - else + } else { this._portStatus.insertBefore(portNumber, this._portStatus.firstChild); + } const portIcon = createElementWithClass('div', 'device-view-port-icon'); if (portStatus >= 0) { @@ -719,12 +745,15 @@ } const title = []; - if (connected.length) + if (connected.length) { title.push(Common.UIString('Connected: %s', connected.join(', '))); - if (transient.length) + } + if (transient.length) { title.push(Common.UIString('Transient: %s', transient.join(', '))); - if (error.length) + } + if (error.length) { title.push(Common.UIString('Error: %s', error.join(', '))); + } this._portStatus.title = title.join('; '); this._portStatus.classList.toggle('hidden', empty); }
diff --git a/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js b/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js index ce5344ac..51dd595 100644 --- a/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js +++ b/third_party/blink/renderer/devtools/front_end/devtools_compatibility.js
@@ -39,8 +39,9 @@ embedderMessageAck(id, arg) { const callback = this._callbacks[id]; delete this._callbacks[id]; - if (callback) + if (callback) { callback(arg); + } } /** @@ -50,11 +51,13 @@ */ sendMessageToEmbedder(method, args, callback) { const callId = ++this._lastCallId; - if (callback) + if (callback) { this._callbacks[callId] = callback; + } const message = {'id': callId, 'method': method}; - if (args.length) + if (args.length) { message.params = args; + } DevToolsHost.sendMessageToEmbedder(JSON.stringify(message)); } @@ -80,10 +83,11 @@ // The addExtensions command is sent as the onload event happens for // DevTools front-end. We should buffer this command until the frontend // is ready for it. - if (this._addExtensionCallback) + if (this._addExtensionCallback) { extensions.forEach(this._addExtensionCallback); - else + } else { this._pendingExtensionDescriptors.pushAll(extensions); + } } } @@ -287,10 +291,11 @@ */ setInspectedTabId(tabId) { // Support for legacy front-ends (<M41). - if (window['WebInspector'] && window['WebInspector']['setInspectedTabId']) + if (window['WebInspector'] && window['WebInspector']['setInspectedTabId']) { window['WebInspector']['setInspectedTabId'](tabId); - else + } else { this._dispatchOnInspectorFrontendAPI('setInspectedTabId', [tabId]); + } } /** @@ -387,8 +392,9 @@ // Support for legacy (<57) frontends. if (window.Runtime && window.Runtime.queryParam) { const panelToOpen = window.Runtime.queryParam('panel'); - if (panelToOpen) + if (panelToOpen) { window.DevToolsAPI.showPanel(panelToOpen); + } } } @@ -558,8 +564,9 @@ */ recordEnumeratedHistogram(actionName, actionCode, bucketSize) { // Support for M49 frontend. - if (actionName === 'DevTools.DrawerShown') + if (actionName === 'DevTools.DrawerShown') { return; + } DevToolsAPI.sendMessageToEmbedder('recordEnumeratedHistogram', [actionName, actionCode, bucketSize], null); } @@ -1074,16 +1081,18 @@ function objectObserve(object, observer) { if (window['WebInspector']) { const settingPrototype = /** @type {!Object} */ (window['WebInspector']['Setting']['prototype']); - if (typeof settingPrototype['remove'] === 'function') + if (typeof settingPrototype['remove'] === 'function') { settingPrototype['remove'] = settingRemove; + } } /** @type {!Set<string>} */ const changedProperties = new Set(); let scheduled = false; function scheduleObserver() { - if (scheduled) + if (scheduled) { return; + } scheduled = true; setImmediate(callObserver); } @@ -1129,8 +1138,9 @@ }); } - for (let i = 0; i < properties.length; ++i) + for (let i = 0; i < properties.length; ++i) { defineProperty(properties[i]); + } } window.Object.observe = objectObserve; @@ -1202,20 +1212,23 @@ */ function keyCodeToKeyIdentifier(keyCode) { let result = staticKeyIdentifiers.get(keyCode); - if (result !== undefined) + if (result !== undefined) { return result; + } result = 'U+'; const hexString = keyCode.toString(16).toUpperCase(); - for (let i = hexString.length; i < 4; ++i) + for (let i = hexString.length; i < 4; ++i) { result += '0'; + } result += hexString; return result; } function installBackwardsCompatibility() { const majorVersion = getRemoteMajorVersion(); - if (!majorVersion) + if (!majorVersion) { return; + } /** @type {!Array<string>} */ const styleRules = []; @@ -1236,15 +1249,17 @@ const origAdd = DOMTokenList.prototype.add; DOMTokenList.prototype.add = function(...tokens) { - if (tokens[0].startsWith('insertion-point') || tokens[0].startsWith('tabbed-pane-header')) + if (tokens[0].startsWith('insertion-point') || tokens[0].startsWith('tabbed-pane-header')) { this._myElement.slot = '.' + tokens[0]; + } return origAdd.apply(this, tokens); }; const origCreateElement = Document.prototype.createElement; Document.prototype.createElement = function(tagName, ...rest) { - if (tagName === 'content') + if (tagName === 'content') { tagName = 'slot'; + } const element = origCreateElement.call(this, tagName, ...rest); element.classList._myElement = element; return element; @@ -1261,8 +1276,9 @@ const origCreateElementWithClass = Document.prototype.createElementWithClass; Document.prototype.createElementWithClass = function(tagName, className, ...rest) { - if (tagName !== 'button' || (className !== 'soft-dropdown' && className !== 'dropdown-button')) + if (tagName !== 'button' || (className !== 'soft-dropdown' && className !== 'dropdown-button')) { return origCreateElementWithClass.call(this, tagName, className, ...rest); + } const element = origCreateElementWithClass.call(this, 'div', className, ...rest); element.tabIndex = 0; element.role = 'button'; @@ -1273,10 +1289,11 @@ // Document.prototype.createElementWithClass is a DevTools method, so we // need to wait for DOMContentLoaded in order to override it. if (window.document.head && - (window.document.readyState === 'complete' || window.document.readyState === 'interactive')) + (window.document.readyState === 'complete' || window.document.readyState === 'interactive')) { overrideCreateElementWithClass(); - else + } else { window.addEventListener('DOMContentLoaded', overrideCreateElementWithClass); + } } // Custom Elements V0 polyfill @@ -1289,13 +1306,15 @@ const element = document.createElement(localName || typeExtension); const skip = new Set(['constructor', '__proto__']); for (const key of Object.keys(Object.getOwnPropertyDescriptors(prototype.__proto__ || {}))) { - if (skip.has(key)) + if (skip.has(key)) { continue; + } element[key] = prototype[key]; } element.setAttribute('is', typeExtension); - if (element['createdCallback']) + if (element['createdCallback']) { element['createdCallback'](); + } return element; }; fakeRegistry.set(typeExtension, callback); @@ -1305,8 +1324,9 @@ const origCreateElement = Document.prototype.createElement; Document.prototype.createElement = function(tagName, fakeCustomElementType) { const fakeConstructor = fakeRegistry.get(fakeCustomElementType); - if (fakeConstructor) + if (fakeConstructor) { return fakeConstructor(); + } return origCreateElement.call(this, tagName, fakeCustomElementType); }; @@ -1316,8 +1336,9 @@ // classList.toggle('a'); const originalDOMTokenListToggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function(token, force) { - if (arguments.length === 1) + if (arguments.length === 1) { force = !this.contains(token); + } return originalDOMTokenListToggle.call(this, token, !!force); }; } @@ -1335,8 +1356,9 @@ */ ShadowRoot.prototype.elementFromPoint = function(x, y) { const originalResult = ShadowRoot.prototype.__originalShadowRootElementFromPoint.apply(this, arguments); - if (this.host && originalResult === this.host) + if (this.host && originalResult === this.host) { return null; + } return originalResult; }; } @@ -1354,8 +1376,9 @@ }); } - if (majorVersion <= 50) + if (majorVersion <= 50) { installObjectObserve(); + } if (majorVersion <= 45) { /** @@ -1389,8 +1412,9 @@ window.CSSPrimitiveValue = CSSPrimitiveValue; } - if (majorVersion <= 45) + if (majorVersion <= 45) { styleRules.push('* { min-width: 0; min-height: 0; }'); + } if (majorVersion <= 51) { // Support for quirky border-image behavior (<M51), see: @@ -1404,8 +1428,9 @@ '.coverage-toolbar-container, .animation-timeline-toolbar-container, .computed-properties { flex-basis: auto; }'); } - if (majorVersion <= 50) + if (majorVersion <= 50) { Event.prototype.deepPath = undefined; + } if (majorVersion <= 54) { window.FileError = /** @type {!function (new: FileError) : ?} */ ({ @@ -1425,8 +1450,9 @@ function getRemoteMajorVersion() { try { const remoteVersion = new URLSearchParams(window.location.search).get('remoteVersion'); - if (!remoteVersion) + if (!remoteVersion) { return null; + } const majorVersion = parseInt(remoteVersion.split('.')[0], 10); return majorVersion; } catch (e) { @@ -1438,8 +1464,9 @@ * @param {!Array<string>} styleRules */ function installExtraStyleRules(styleRules) { - if (!styleRules.length) + if (!styleRules.length) { return; + } const styleText = styleRules.join('\n'); document.head.appendChild(createStyleElement(styleText));
diff --git a/third_party/blink/renderer/devtools/front_end/diff/Diff.js b/third_party/blink/renderer/devtools/front_end/diff/Diff.js index 0111d08..1bdced6 100644 --- a/third_party/blink/renderer/devtools/front_end/diff/Diff.js +++ b/third_party/blink/renderer/devtools/front_end/diff/Diff.js
@@ -11,8 +11,9 @@ charDiff: function(text1, text2, cleanup) { const differ = new diff_match_patch(); const diff = differ.diff_main(text1, text2); - if (cleanup) + if (cleanup) { differ.diff_cleanupSemantic(diff); + } return diff; }, @@ -31,8 +32,9 @@ const lineDiff = []; for (let i = 0; i < diff.length; i++) { const lines = []; - for (let j = 0; j < diff[i][1].length; j++) + for (let j = 0; j < diff[i][1].length; j++) { lines.push(idMap.fromChar(diff[i][1][j])); + } lineDiff.push({0: diff[i][0], 1: lines}); }
diff --git a/third_party/blink/renderer/devtools/front_end/dom_extension/DOMExtension.js b/third_party/blink/renderer/devtools/front_end/dom_extension/DOMExtension.js index 33f0662..13f217d 100644 --- a/third_party/blink/renderer/devtools/front_end/dom_extension/DOMExtension.js +++ b/third_party/blink/renderer/devtools/front_end/dom_extension/DOMExtension.js
@@ -42,15 +42,17 @@ let endNode; let endOffset = 0; - if (!stayWithinNode) + if (!stayWithinNode) { stayWithinNode = this; + } if (!direction || direction === 'backward' || direction === 'both') { let node = this; while (node) { if (node === stayWithinNode) { - if (!startNode) + if (!startNode) { startNode = stayWithinNode; + } break; } @@ -65,8 +67,9 @@ } } - if (startNode) + if (startNode) { break; + } node = node.traversePreviousNode(stayWithinNode); } @@ -84,8 +87,9 @@ let node = this; while (node) { if (node === stayWithinNode) { - if (!endNode) + if (!endNode) { endNode = stayWithinNode; + } break; } @@ -100,8 +104,9 @@ } } - if (endNode) + if (endNode) { break; + } node = node.traverseNextNode(stayWithinNode); } @@ -129,11 +134,13 @@ */ Node.prototype.traverseNextTextNode = function(stayWithin) { let node = this.traverseNextNode(stayWithin); - if (!node) + if (!node) { return null; + } const nonTextTags = {'STYLE': 1, 'SCRIPT': 1}; - while (node && (node.nodeType !== Node.TEXT_NODE || nonTextTags[node.parentElement.nodeName])) + while (node && (node.nodeType !== Node.TEXT_NODE || nonTextTags[node.parentElement.nodeName])) { node = node.traverseNextNode(stayWithin); + } return node; }; @@ -145,23 +152,27 @@ */ Element.prototype.positionAt = function(x, y, relativeTo) { let shift = {x: 0, y: 0}; - if (relativeTo) + if (relativeTo) { shift = relativeTo.boxInWindow(this.ownerDocument.defaultView); + } - if (typeof x === 'number') + if (typeof x === 'number') { this.style.setProperty('left', (shift.x + x) + 'px'); - else + } else { this.style.removeProperty('left'); + } - if (typeof y === 'number') + if (typeof y === 'number') { this.style.setProperty('top', (shift.y + y) + 'px'); - else + } else { this.style.removeProperty('top'); + } - if (typeof x === 'number' || typeof y === 'number') + if (typeof x === 'number' || typeof y === 'number') { this.style.setProperty('position', 'absolute'); - else + } else { this.style.removeProperty('position'); + } }; /** @@ -183,8 +194,9 @@ Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray) { for (let node = this; node && node !== this.ownerDocument; node = node.parentNodeOrShadowHost()) { for (let i = 0; i < nameArray.length; ++i) { - if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase()) + if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase()) { return node; + } } } return null; @@ -218,11 +230,13 @@ if (node.nodeType === Node.ELEMENT_NODE) { let containsAll = true; for (let i = 0; i < classNames.length && containsAll; ++i) { - if (!node.classList.contains(classNames[i])) + if (!node.classList.contains(classNames[i])) { containsAll = false; + } } - if (containsAll) + if (containsAll) { return /** @type {!Element} */ (node); + } } } return null; @@ -234,8 +248,9 @@ Node.prototype.enclosingShadowRoot = function() { let parentNode = this.parentNodeOrShadowHost(); while (parentNode) { - if (parentNode instanceof ShadowRoot) + if (parentNode instanceof ShadowRoot) { return parentNode; + } parentNode = parentNode.parentNodeOrShadowHost(); } return null; @@ -253,15 +268,19 @@ * @return {?Element} */ Node.prototype.parentElementOrShadowHost = function() { - if (this.nodeType === Node.DOCUMENT_FRAGMENT_NODE && this.host) + if (this.nodeType === Node.DOCUMENT_FRAGMENT_NODE && this.host) { return /** @type {!Element} */ (this.host); + } const node = this.parentNode; - if (!node) + if (!node) { return null; - if (node.nodeType === Node.ELEMENT_NODE) + } + if (node.nodeType === Node.ELEMENT_NODE) { return /** @type {!Element} */ (node); - if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) + } + if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { return /** @type {!Element} */ (node.host); + } return null; }; @@ -269,10 +288,12 @@ * @return {?Node} */ Node.prototype.parentNodeOrShadowHost = function() { - if (this.parentNode) + if (this.parentNode) { return this.parentNode; - if (this.nodeType === Node.DOCUMENT_FRAGMENT_NODE && this.host) + } + if (this.nodeType === Node.DOCUMENT_FRAGMENT_NODE && this.host) { return this.host; + } return null; }; @@ -281,8 +302,9 @@ */ Node.prototype.getComponentSelection = function() { let parent = this.parentNode; - while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) + while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { parent = parent.parentNode; + } return parent instanceof ShadowRoot ? parent.getSelection() : this.window().getSelection(); }; @@ -294,14 +316,16 @@ if (this instanceof Element) { const slots = this.querySelectorAll('slot'); for (const slot of slots) { - if (Array.prototype.some.call(slot.assignedNodes(), node => node.hasSelection())) + if (Array.prototype.some.call(slot.assignedNodes(), node => node.hasSelection())) { return true; + } } } const selection = this.getComponentSelection(); - if (selection.type !== 'Range') + if (selection.type !== 'Range') { return false; + } return selection.containsNode(this, true) || selection.anchorNode.isSelfOrDescendant(this) || selection.focusNode.isSelfOrDescendant(this); }; @@ -314,8 +338,9 @@ }; Element.prototype.removeChildren = function() { - if (this.firstChild) + if (this.firstChild) { this.textContent = ''; + } }; /** @@ -347,8 +372,9 @@ */ Document.prototype.createElementWithClass = function(elementName, className, customElementType) { const element = this.createElement(elementName, {is: customElementType}); - if (className) + if (className) { element.className = className; + } return element; }; @@ -370,8 +396,9 @@ */ Document.prototype.createSVGElement = function(childType, className) { const element = this.createElementNS('http://www.w3.org/2000/svg', childType); - if (className) + if (className) { element.setAttribute('class', className); + } return element; }; @@ -423,8 +450,9 @@ * @param {...string} var_args */ Element.prototype.createTextChildren = function(var_args) { - for (let i = 0, n = arguments.length; i < n; ++i) + for (let i = 0, n = arguments.length; i < n; ++i) { this.createTextChild(arguments[i]); + } }; DocumentFragment.prototype.createTextChildren = Element.prototype.createTextChildren; @@ -527,8 +555,9 @@ while (curWindow && curElement) { anchorBox.x += curElement.totalOffsetLeft(); anchorBox.y += curElement.totalOffsetTop(); - if (curWindow === targetWindow) + if (curWindow === targetWindow) { break; + } curElement = curWindow.frameElement; curWindow = curWindow.parent; } @@ -543,8 +572,9 @@ */ Event.prototype.consume = function(preventDefault) { this.stopImmediatePropagation(); - if (preventDefault) + if (preventDefault) { this.preventDefault(); + } this.handled = true; }; @@ -557,8 +587,9 @@ start = start || 0; end = end || this.textContent.length; - if (start < 0) + if (start < 0) { start = end + start; + } const selection = this.getComponentSelection(); selection.removeAllRanges(); @@ -576,8 +607,9 @@ // Calculate selection offset relative to the current element. const selection = this.getComponentSelection(); - if (!selection.containsNode(this, true)) + if (!selection.containsNode(this, true)) { return null; + } let leftOffset = selection.anchorOffset; let node = selection.anchorNode; @@ -597,8 +629,9 @@ * @param {...!Node} var_args */ Node.prototype.appendChildren = function(var_args) { - for (let i = 0, n = arguments.length; i < n; ++i) + for (let i = 0, n = arguments.length; i < n; ++i) { this.appendChild(arguments[i]); + } }; /** @@ -620,8 +653,9 @@ const result = []; const nonTextTags = {'STYLE': 1, 'SCRIPT': 1}; while (node) { - if (!nonTextTags[node.parentElement.nodeName]) + if (!nonTextTags[node.parentElement.nodeName]) { result.push(node); + } node = node.traverseNextTextNode(this); } return result; @@ -632,13 +666,15 @@ * @return {boolean} */ Node.prototype.isAncestor = function(node) { - if (!node) + if (!node) { return false; + } let currentNode = node.parentNodeOrShadowHost(); while (currentNode) { - if (this === currentNode) + if (this === currentNode) { return true; + } currentNode = currentNode.parentNodeOrShadowHost(); } return false; @@ -673,25 +709,30 @@ * @return {?Node} */ Node.prototype.traverseNextNode = function(stayWithin) { - if (this.shadowRoot) + if (this.shadowRoot) { return this.shadowRoot; + } const distributedNodes = this instanceof HTMLSlotElement ? this.assignedNodes() : []; - if (distributedNodes.length) + if (distributedNodes.length) { return distributedNodes[0]; + } - if (this.firstChild) + if (this.firstChild) { return this.firstChild; + } let node = this; while (node) { - if (stayWithin && node === stayWithin) + if (stayWithin && node === stayWithin) { return null; + } const sibling = nextSibling(node); - if (sibling) + if (sibling) { return sibling; + } node = node.assignedSlot || node.parentNodeOrShadowHost(); } @@ -701,13 +742,15 @@ * @return {?Node} */ function nextSibling(node) { - if (!node.assignedSlot) + if (!node.assignedSlot) { return node.nextSibling; + } const distributedNodes = node.assignedSlot.assignedNodes(); const position = Array.prototype.indexOf.call(distributedNodes, node); - if (position + 1 < distributedNodes.length) + if (position + 1 < distributedNodes.length) { return distributedNodes[position + 1]; + } return null; } @@ -719,13 +762,16 @@ * @return {?Node} */ Node.prototype.traversePreviousNode = function(stayWithin) { - if (stayWithin && this === stayWithin) + if (stayWithin && this === stayWithin) { return null; + } let node = this.previousSibling; - while (node && node.lastChild) + while (node && node.lastChild) { node = node.lastChild; - if (node) + } + if (node) { return node; + } return this.parentNodeOrShadowHost(); }; @@ -754,8 +800,10 @@ */ Event.prototype.deepElementFromPoint = function() { // Some synthetic events have zero coordinates which lead to a wrong element. Better return nothing in this case. - if (!this.which && !this.pageX && !this.pageY && !this.clientX && !this.clientY && !this.movementX && !this.movementY) + if (!this.which && !this.pageX && !this.pageY && !this.clientX && !this.clientY && !this.movementX && + !this.movementY) { return null; + } const root = this.target && this.target.getComponentRoot(); return root ? root.deepElementFromPoint(this.pageX, this.pageY) : null; }; @@ -770,8 +818,9 @@ let node = null; while (container) { const innerNode = container.elementFromPoint(x, y); - if (!innerNode || node === innerNode) + if (!innerNode || node === innerNode) { break; + } node = innerNode; container = node.shadowRoot; } @@ -785,8 +834,9 @@ */ Document.prototype.deepActiveElement = function() { let activeElement = this.activeElement; - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { activeElement = activeElement.shadowRoot.activeElement; + } return activeElement; }; @@ -805,8 +855,9 @@ */ Node.prototype.getComponentRoot = function() { let node = this; - while (node && node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && node.nodeType !== Node.DOCUMENT_NODE) + while (node && node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && node.nodeType !== Node.DOCUMENT_NODE) { node = node.parentNode; + } return /** @type {?Document|?DocumentFragment} */ (node); }; @@ -816,8 +867,9 @@ */ self.onInvokeElement = function(element, callback) { element.addEventListener('keydown', event => { - if (self.isEnterOrSpaceKey(event)) + if (self.isEnterOrSpaceKey(event)) { callback(event); + } }); element.addEventListener('click', event => callback(event)); }; @@ -854,8 +906,9 @@ (function() { const originalToggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype['toggle'] = function(token, force) { - if (arguments.length === 1) + if (arguments.length === 1) { force = !this.contains(token); + } return originalToggle.call(this, token, !!force); }; })();
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ClassesPaneWidget.js b/third_party/blink/renderer/devtools/front_end/elements/ClassesPaneWidget.js index ff33a6d..6d3fd26 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ClassesPaneWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ClassesPaneWidget.js
@@ -48,19 +48,22 @@ * @param {!Event} event */ _onKeyDown(event) { - if (!isEnterKey(event) && !isEscKey(event)) + if (!isEnterKey(event) && !isEscKey(event)) { return; + } if (isEnterKey(event)) { event.consume(); - if (this._prompt.acceptAutoComplete()) + if (this._prompt.acceptAutoComplete()) { return; + } } let text = event.target.textContent; if (isEscKey(event)) { - if (!text.isWhitespace()) + if (!text.isWhitespace()) { event.consume(true); + } text = ''; } @@ -68,20 +71,23 @@ event.target.textContent = ''; const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return; + } const classNames = this._splitTextIntoClasses(text); - for (const className of classNames) + for (const className of classNames) { this._toggleClass(node, className, true); + } this._installNodeClasses(node); this._update(); } _onTextChanged() { const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return; + } this._installNodeClasses(node); } @@ -90,8 +96,9 @@ */ _onDOMMutated(event) { const node = /** @type {!SDK.DOMNode} */ (event.data); - if (this._mutatingNodes.has(node)) + if (this._mutatingNodes.has(node)) { return; + } delete node[Elements.ClassesPaneWidget._classesSymbol]; this._update(); } @@ -116,18 +123,21 @@ } _update() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } let node = UI.context.flavor(SDK.DOMNode); - if (node) + if (node) { node = node.enclosingElementOrSelf(); + } this._classesContainer.removeChildren(); this._input.disabled = !node; - if (!node) + if (!node) { return; + } const classes = this._nodeClasses(node); const keys = classes.keysArray(); @@ -147,8 +157,9 @@ */ _onClick(className, event) { const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return; + } const enabled = event.target.checked; this._toggleClass(node, className, enabled); this._installNodeClasses(node); @@ -166,8 +177,9 @@ result = new Map(); for (let i = 0; i < classes.length; ++i) { const className = classes[i].trim(); - if (!className.length) + if (!className.length) { continue; + } result.set(className, true); } node[Elements.ClassesPaneWidget._classesSymbol] = result; @@ -192,13 +204,15 @@ const classes = this._nodeClasses(node); const activeClasses = new Set(); for (const className of classes.keys()) { - if (classes.get(className)) + if (classes.get(className)) { activeClasses.add(className); + } } const additionalClasses = this._splitTextIntoClasses(this._prompt.textWithCurrentSuggestion()); - for (const className of additionalClasses) + for (const className of additionalClasses) { activeClasses.add(className); + } const newClasses = activeClasses.valuesArray(); newClasses.sort(); @@ -287,8 +301,9 @@ const cssModel = selectedNode.domModel().cssModel(); const allStyleSheets = cssModel.allStyleSheets(); for (const stylesheet of allStyleSheets) { - if (stylesheet.frameId !== this._selectedFrameId) + if (stylesheet.frameId !== this._selectedFrameId) { continue; + } const cssPromise = cssModel.classNamesPromise(stylesheet.id).then(classes => completions.addAll(classes)); promises.push(cssPromise); } @@ -307,22 +322,26 @@ * @return {!Promise<!UI.SuggestBox.Suggestions>} */ _buildClassNameCompletions(expression, prefix, force) { - if (!prefix || force) + if (!prefix || force) { this._classNamesPromise = null; + } const selectedNode = UI.context.flavor(SDK.DOMNode); - if (!selectedNode || (!prefix && !force && !expression.trim())) + if (!selectedNode || (!prefix && !force && !expression.trim())) { return Promise.resolve([]); + } - if (!this._classNamesPromise || this._selectedFrameId !== selectedNode.frameId()) + if (!this._classNamesPromise || this._selectedFrameId !== selectedNode.frameId()) { this._classNamesPromise = this._getClassNames(selectedNode); + } return this._classNamesPromise.then(completions => { const classesMap = this._nodeClasses(/** @type {!SDK.DOMNode} */ (selectedNode)); completions = completions.filter(value => !classesMap.get(value)); - if (prefix[0] === '.') + if (prefix[0] === '.') { completions = completions.map(value => '.' + value); + } return completions.filter(value => value.startsWith(prefix)).sort().map(completion => ({text: completion})); }); }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ColorSwatchPopoverIcon.js b/third_party/blink/renderer/devtools/front_end/elements/ColorSwatchPopoverIcon.js index c2bb78b..e8426ce 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ColorSwatchPopoverIcon.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ColorSwatchPopoverIcon.js
@@ -43,14 +43,16 @@ this._bezierEditor.addEventListener(InlineEditor.BezierEditor.Events.BezierChanged, this._boundBezierChanged); this._swatchPopoverHelper.show(this._bezierEditor, this._swatch.iconElement(), this._onPopoverHidden.bind(this)); this._scrollerElement = this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper'); - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.addEventListener('scroll', this._boundOnScroll, false); + } this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); const uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation, true /* omitFocus */); + } } /** @@ -72,8 +74,9 @@ * @param {boolean} commitEdit */ _onPopoverHidden(commitEdit) { - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.removeEventListener('scroll', this._boundOnScroll, false); + } this._bezierEditor.removeEventListener(InlineEditor.BezierEditor.Events.BezierChanged, this._boundBezierChanged); delete this._bezierEditor; @@ -120,14 +123,17 @@ const colors = []; const colorNames = []; for (const cssVariable of cssVariables) { - if (cssVariable === this._treeElement.property.name) + if (cssVariable === this._treeElement.property.name) { continue; + } const value = matchedStyles.computeCSSVariable(style, cssVariable); - if (!value) + if (!value) { continue; + } const color = Common.Color.parse(value); - if (!color) + if (!color) { continue; + } colors.push(value); colorNames.push(cssVariable); } @@ -165,8 +171,9 @@ const color = this._swatch.color(); let format = this._swatch.format(); - if (format === Common.Color.Format.Original) + if (format === Common.Color.Format.Original) { format = color.format(); + } this._spectrum = new ColorPicker.Spectrum(this._contrastInfo); this._spectrum.setColor(color, format); this._spectrum.addPalette(this._generateCSSVariablesPalette()); @@ -175,14 +182,16 @@ this._spectrum.addEventListener(ColorPicker.Spectrum.Events.ColorChanged, this._boundSpectrumChanged); this._swatchPopoverHelper.show(this._spectrum, this._swatch.iconElement(), this._onPopoverHidden.bind(this)); this._scrollerElement = this._swatch.enclosingNodeOrSelfWithClass('style-panes-wrapper'); - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.addEventListener('scroll', this._boundOnScroll, false); + } this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); const uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation, true /* omitFocus */); + } } /** @@ -197,12 +206,14 @@ */ _spectrumChanged(event) { const color = Common.Color.parse(/** @type {string} */ (event.data)); - if (!color) + if (!color) { return; + } this._swatch.setColor(color); const colorName = this._spectrum.colorName(); - if (colorName && colorName.startsWith('--')) + if (colorName && colorName.startsWith('--')) { this._swatch.setText(`var(${colorName})`); + } this._treeElement.applyStyleText(this._treeElement.renderedPropertyText(), false); } @@ -218,8 +229,9 @@ * @param {boolean} commitEdit */ _onPopoverHidden(commitEdit) { - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.removeEventListener('scroll', this._boundOnScroll, false); + } this._spectrum.removeEventListener(ColorPicker.Spectrum.Events.ColorChanged, this._boundSpectrumChanged); delete this._spectrum; @@ -285,14 +297,16 @@ this._cssShadowEditor.addEventListener(InlineEditor.CSSShadowEditor.Events.ShadowChanged, this._boundShadowChanged); this._swatchPopoverHelper.show(this._cssShadowEditor, this._iconElement, this._onPopoverHidden.bind(this)); this._scrollerElement = this._iconElement.enclosingNodeOrSelfWithClass('style-panes-wrapper'); - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.addEventListener('scroll', this._boundOnScroll, false); + } this._originalPropertyText = this._treeElement.property.propertyText; this._treeElement.parentPane().setEditingStyle(true); const uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this._treeElement.property, false /* forName */); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation, true /* omitFocus */); + } } /** @@ -314,8 +328,9 @@ * @param {boolean} commitEdit */ _onPopoverHidden(commitEdit) { - if (this._scrollerElement) + if (this._scrollerElement) { this._scrollerElement.removeEventListener('scroll', this._boundOnScroll, false); + } this._cssShadowEditor.removeEventListener( InlineEditor.CSSShadowEditor.Events.ShadowChanged, this._boundShadowChanged);
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleModel.js b/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleModel.js index 6236deae..f39900f5 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleModel.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleModel.js
@@ -40,8 +40,9 @@ * @param {?SDK.CSSModel} cssModel */ _updateModel(cssModel) { - if (this._cssModel === cssModel) + if (this._cssModel === cssModel) { return; + } Common.EventTarget.removeEventListeners(this._eventListeners); this._cssModel = cssModel; const domModel = cssModel ? cssModel.domModel() : null; @@ -75,8 +76,10 @@ _onDOMModelChanged(event) { // Any attribute removal or modification can affect the styles of "related" nodes. const node = /** @type {!SDK.DOMNode} */ (event.data); - if (!this._node || this._node !== node && node.parentNode !== this._node.parentNode && !node.isAncestor(this._node)) + if (!this._node || + this._node !== node && node.parentNode !== this._node.parentNode && !node.isAncestor(this._node)) { return; + } this._onComputedStyleChanged(null); } @@ -92,8 +95,9 @@ delete this._frameResizedTimer; } - if (this._frameResizedTimer) + if (this._frameResizedTimer) { clearTimeout(this._frameResizedTimer); + } this._frameResizedTimer = setTimeout(refreshContents.bind(this), 100); } @@ -111,8 +115,9 @@ fetchComputedStyle() { const elementNode = this._elementNode(); const cssModel = this.cssModel(); - if (!elementNode || !cssModel) + if (!elementNode || !cssModel) { return Promise.resolve(/** @type {?Elements.ComputedStyleModel.ComputedStyle} */ (null)); + } if (!this._computedStylePromise) { this._computedStylePromise =
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleWidget.js b/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleWidget.js index b0cd17b4..1a8cf0d 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ComputedStyleWidget.js
@@ -109,8 +109,9 @@ */ _fetchMatchedCascade() { const node = this._computedStyleModel.node(); - if (!node || !this._computedStyleModel.cssModel()) + if (!node || !this._computedStyleModel.cssModel()) { return Promise.resolve(/** @type {?SDK.CSSMatchedStyles} */ (null)); + } return this._computedStyleModel.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this)); @@ -130,8 +131,9 @@ */ _processColor(text) { const color = Common.Color.parse(text); - if (!color) + if (!color) { return createTextNode(text); + } const swatch = InlineEditor.ColorSwatch.create(); swatch.setColor(color); swatch.setFormat(Common.Color.detectColorFormat(color)); @@ -146,8 +148,9 @@ /** @type {!Set<string>} */ const expandedProperties = new Set(); for (const treeElement of this._propertiesOutline.rootElement().children()) { - if (!treeElement.expanded) + if (!treeElement.expanded) { continue; + } const propertyName = treeElement[Elements.ComputedStyleWidget._propertySymbol].name; expandedProperties.add(propertyName); } @@ -171,12 +174,15 @@ const propertyValue = nodeStyle.computedStyle.get(propertyName); const canonicalName = SDK.cssMetadata().canonicalPropertyName(propertyName); const inherited = !inhertiedProperties.has(canonicalName); - if (!showInherited && inherited && !(propertyName in this._alwaysShowComputedProperties)) + if (!showInherited && inherited && !(propertyName in this._alwaysShowComputedProperties)) { continue; - if (!showInherited && propertyName.startsWith('--')) + } + if (!showInherited && propertyName.startsWith('--')) { continue; - if (propertyName !== canonicalName && propertyValue === nodeStyle.computedStyle.get(canonicalName)) + } + if (propertyName !== canonicalName && propertyValue === nodeStyle.computedStyle.get(canonicalName)) { continue; + } const propertyElement = createElement('div'); propertyElement.classList.add('computed-style-property'); @@ -208,8 +214,9 @@ const isOdd = this._propertiesOutline.rootElement().children().length % 2 === 0; treeElement.listItemElement.classList.toggle('odd-row', isOdd); this._propertiesOutline.appendChild(treeElement); - if (!this._propertiesOutline.selectedTreeElement) + if (!this._propertiesOutline.selectedTreeElement) { treeElement.select(!hadFocus); + } const trace = propertyTraces.get(propertyName); if (trace) { @@ -220,8 +227,9 @@ const gotoSourceElement = UI.Icon.create('mediumicon-arrow-in-circle', 'goto-source-icon'); gotoSourceElement.addEventListener('click', this._navigateToSource.bind(this, activeProperty)); propertyValueElement.appendChild(gotoSourceElement); - if (expandedProperties.has(propertyName)) + if (expandedProperties.has(propertyName)) { treeElement.expand(); + } } } @@ -233,10 +241,12 @@ * @return {number} */ function propertySorter(a, b) { - if (a.startsWith('--') ^ b.startsWith('--')) + if (a.startsWith('--') ^ b.startsWith('--')) { return a.startsWith('--') ? 1 : -1; - if (a.startsWith('-webkit') ^ b.startsWith('-webkit')) + } + if (a.startsWith('-webkit') ^ b.startsWith('-webkit')) { return a.startsWith('-webkit') ? 1 : -1; + } const canonical1 = SDK.cssMetadata().canonicalPropertyName(a); const canonical2 = SDK.cssMetadata().canonicalPropertyName(b); return canonical1.compareTo(canonical2); @@ -247,10 +257,11 @@ * @param {!Event} event */ function handleClick(treeElement, event) { - if (!treeElement.expanded) + if (!treeElement.expanded) { treeElement.expand(); - else + } else { treeElement.collapse(); + } event.consume(); } } @@ -277,10 +288,11 @@ for (const property of tracedProperties) { const trace = createElement('div'); trace.classList.add('property-trace'); - if (matchedStyles.propertyState(property) === SDK.CSSMatchedStyles.PropertyState.Overloaded) + if (matchedStyles.propertyState(property) === SDK.CSSMatchedStyles.PropertyState.Overloaded) { trace.classList.add('property-trace-inactive'); - else + } else { activeProperty = property; + } const renderer = new Elements.StylesSidebarPropertyRenderer(null, node, property.name, /** @type {string} */ (property.value)); @@ -321,10 +333,12 @@ for (const style of matchedStyles.nodeStyles()) { const allProperties = style.allProperties(); for (const property of allProperties) { - if (!property.activeInStyle() || !matchedStyles.propertyState(property)) + if (!property.activeInStyle() || !matchedStyles.propertyState(property)) { continue; - if (!result.has(property.name)) + } + if (!result.has(property.name)) { result.set(property.name, []); + } result.get(property.name).push(property); } } @@ -339,8 +353,9 @@ const result = new Set(); for (const style of matchedStyles.nodeStyles()) { for (const property of style.allProperties()) { - if (!matchedStyles.propertyState(property)) + if (!matchedStyles.propertyState(property)) { continue; + } result.add(SDK.cssMetadata().canonicalPropertyName(property.name)); } }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/DOMLinkifier.js b/third_party/blink/renderer/devtools/front_end/elements/DOMLinkifier.js index a8301ac..0723d3a 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/DOMLinkifier.js +++ b/third_party/blink/renderer/devtools/front_end/elements/DOMLinkifier.js
@@ -12,8 +12,9 @@ Elements.DOMLinkifier.decorateNodeLabel = function(node, parentElement, tooltipContent) { const originalNode = node; const isPseudo = node.nodeType() === Node.ELEMENT_NODE && node.pseudoType(); - if (isPseudo && node.parentNode) + if (isPseudo && node.parentNode) { node = node.parentNode; + } let title = node.nodeNameInCorrectCase(); @@ -65,8 +66,9 @@ * @return {!Node} */ Elements.DOMLinkifier.linkifyNodeReference = function(node, options = {}) { - if (!node) + if (!node) { return createTextNode(Common.UIString('<node>')); + } const root = createElementWithClass('span', 'monospace'); const shadowRoot = UI.createShadowRootWithCoreStyles(root, 'elements/domLinkifier.css'); @@ -127,10 +129,12 @@ * @return {!Node} */ linkify(object, options) { - if (object instanceof SDK.DOMNode) + if (object instanceof SDK.DOMNode) { return Elements.DOMLinkifier.linkifyNodeReference(object, options); - if (object instanceof SDK.DeferredDOMNode) + } + if (object instanceof SDK.DeferredDOMNode) { return Elements.DOMLinkifier.linkifyDeferredNodeReference(object, options); + } throw new Error('Can\'t linkify non-node'); } };
diff --git a/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js b/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js index 52c1607..6ddbbaa 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js +++ b/third_party/blink/renderer/devtools/front_end/elements/DOMPath.js
@@ -10,8 +10,9 @@ * @return {string} */ Elements.DOMPath.fullQualifiedSelector = function(node, justSelector) { - if (node.nodeType() !== Node.ELEMENT_NODE) + if (node.nodeType() !== Node.ELEMENT_NODE) { return node.localName() || node.nodeName().toLowerCase(); + } return Elements.DOMPath.cssPath(node, justSelector); }; @@ -21,18 +22,21 @@ * @return {string} */ Elements.DOMPath.cssPath = function(node, optimized) { - if (node.nodeType() !== Node.ELEMENT_NODE) + if (node.nodeType() !== Node.ELEMENT_NODE) { return ''; + } const steps = []; let contextNode = node; while (contextNode) { const step = Elements.DOMPath._cssPathStep(contextNode, !!optimized, contextNode === node); - if (!step) - break; // Error - bail out early. - steps.push(step); - if (step.optimized) + if (!step) { break; + } // Error - bail out early. + steps.push(step); + if (step.optimized) { + break; + } contextNode = contextNode.parentNode; } @@ -47,8 +51,9 @@ Elements.DOMPath.canGetJSPath = function(node) { let wp = node; while (wp) { - if (wp.ancestorShadowRoot() && wp.ancestorShadowRoot().shadowRootType() !== SDK.DOMNode.ShadowRootTypes.Open) + if (wp.ancestorShadowRoot() && wp.ancestorShadowRoot().shadowRootType() !== SDK.DOMNode.ShadowRootTypes.Open) { return false; + } wp = wp.ancestorShadowHost(); } return true; @@ -60,8 +65,9 @@ * @return {string} */ Elements.DOMPath.jsPath = function(node, optimized) { - if (node.nodeType() !== Node.ELEMENT_NODE) + if (node.nodeType() !== Node.ELEMENT_NODE) { return ''; + } const path = []; let wp = node; @@ -73,10 +79,11 @@ let result = ''; for (let i = 0; i < path.length; ++i) { const string = JSON.stringify(path[i]); - if (i) + if (i) { result += `.shadowRoot.querySelector(${string})`; - else + } else { result += `document.querySelector(${string})`; + } } return result; }; @@ -88,24 +95,29 @@ * @return {?Elements.DOMPath.Step} */ Elements.DOMPath._cssPathStep = function(node, optimized, isTargetNode) { - if (node.nodeType() !== Node.ELEMENT_NODE) + if (node.nodeType() !== Node.ELEMENT_NODE) { return null; + } const id = node.getAttribute('id'); if (optimized) { - if (id) + if (id) { return new Elements.DOMPath.Step(idSelector(id), true); + } const nodeNameLower = node.nodeName().toLowerCase(); - if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') + if (nodeNameLower === 'body' || nodeNameLower === 'head' || nodeNameLower === 'html') { return new Elements.DOMPath.Step(node.nodeNameInCorrectCase(), true); + } } const nodeName = node.nodeNameInCorrectCase(); - if (id) + if (id) { return new Elements.DOMPath.Step(nodeName + idSelector(id), true); + } const parent = node.parentNode; - if (!parent || parent.nodeType() === Node.DOCUMENT_NODE) + if (!parent || parent.nodeType() === Node.DOCUMENT_NODE) { return new Elements.DOMPath.Step(nodeName, true); + } /** * @param {!SDK.DOMNode} node @@ -113,8 +125,9 @@ */ function prefixedElementClassNames(node) { const classAttribute = node.getAttribute('class'); - if (!classAttribute) + if (!classAttribute) { return []; + } return classAttribute.split(/\s+/g).filter(Boolean).map(function(name) { // The prefix is required to store "__proto__" in a object-based map. @@ -138,17 +151,20 @@ const siblings = parent.children(); for (let i = 0; (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) { const sibling = siblings[i]; - if (sibling.nodeType() !== Node.ELEMENT_NODE) + if (sibling.nodeType() !== Node.ELEMENT_NODE) { continue; + } elementIndex += 1; if (sibling === node) { ownIndex = elementIndex; continue; } - if (needsNthChild) + if (needsNthChild) { continue; - if (sibling.nodeNameInCorrectCase() !== nodeName) + } + if (sibling.nodeNameInCorrectCase() !== nodeName) { continue; + } needsClassNames = true; const ownClassNames = new Set(prefixedOwnClassNamesArray); @@ -159,8 +175,9 @@ const siblingClassNamesArray = prefixedElementClassNames(sibling); for (let j = 0; j < siblingClassNamesArray.length; ++j) { const siblingClass = siblingClassNamesArray[j]; - if (!ownClassNames.has(siblingClass)) + if (!ownClassNames.has(siblingClass)) { continue; + } ownClassNames.delete(siblingClass); if (!ownClassNames.size) { needsNthChild = true; @@ -171,13 +188,15 @@ let result = nodeName; if (isTargetNode && nodeName.toLowerCase() === 'input' && node.getAttribute('type') && !node.getAttribute('id') && - !node.getAttribute('class')) + !node.getAttribute('class')) { result += '[type=' + CSS.escape(node.getAttribute('type')) + ']'; + } if (needsNthChild) { result += ':nth-child(' + (ownIndex + 1) + ')'; } else if (needsClassNames) { - for (const prefixedName of prefixedOwnClassNamesArray) + for (const prefixedName of prefixedOwnClassNamesArray) { result += '.' + CSS.escape(prefixedName.slice(1)); + } } return new Elements.DOMPath.Step(result, false); @@ -189,18 +208,21 @@ * @return {string} */ Elements.DOMPath.xPath = function(node, optimized) { - if (node.nodeType() === Node.DOCUMENT_NODE) + if (node.nodeType() === Node.DOCUMENT_NODE) { return '/'; + } const steps = []; let contextNode = node; while (contextNode) { const step = Elements.DOMPath._xPathValue(contextNode, optimized); - if (!step) - break; // Error - bail out early. - steps.push(step); - if (step.optimized) + if (!step) { break; + } // Error - bail out early. + steps.push(step); + if (step.optimized) { + break; + } contextNode = contextNode.parentNode; } @@ -216,13 +238,15 @@ Elements.DOMPath._xPathValue = function(node, optimized) { let ownValue; const ownIndex = Elements.DOMPath._xPathIndex(node); - if (ownIndex === -1) - return null; // Error. + if (ownIndex === -1) { + return null; + } // Error. switch (node.nodeType()) { case Node.ELEMENT_NODE: - if (optimized && node.getAttribute('id')) + if (optimized && node.getAttribute('id')) { return new Elements.DOMPath.Step('//*[@id="' + node.getAttribute('id') + '"]', true); + } ownValue = node.localName(); break; case Node.ATTRIBUTE_NODE: @@ -246,8 +270,9 @@ break; } - if (ownIndex > 0) + if (ownIndex > 0) { ownValue += '[' + ownIndex + ']'; + } return new Elements.DOMPath.Step(ownValue, node.nodeType() === Node.DOCUMENT_NODE); }; @@ -259,14 +284,17 @@ Elements.DOMPath._xPathIndex = function(node) { // Returns -1 in case of error, 0 if no siblings matching the same expression, <XPath index among the same expression-matching sibling nodes> otherwise. function areNodesSimilar(left, right) { - if (left === right) + if (left === right) { return true; + } - if (left.nodeType() === Node.ELEMENT_NODE && right.nodeType() === Node.ELEMENT_NODE) + if (left.nodeType() === Node.ELEMENT_NODE && right.nodeType() === Node.ELEMENT_NODE) { return left.localName() === right.localName(); + } - if (left.nodeType() === right.nodeType()) + if (left.nodeType() === right.nodeType()) { return true; + } // XPath treats CDATA as text nodes. const leftType = left.nodeType() === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType(); @@ -275,8 +303,9 @@ } const siblings = node.parentNode ? node.parentNode.children() : null; - if (!siblings) - return 0; // Root node - no siblings. + if (!siblings) { + return 0; + } // Root node - no siblings. let hasSameNamedElements; for (let i = 0; i < siblings.length; ++i) { if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) { @@ -284,13 +313,15 @@ break; } } - if (!hasSameNamedElements) + if (!hasSameNamedElements) { return 0; + } let ownIndex = 1; // XPath indices start with 1. for (let i = 0; i < siblings.length; ++i) { if (areNodesSimilar(node, siblings[i])) { - if (siblings[i] === node) + if (siblings[i] === node) { return ownIndex; + } ++ownIndex; } }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementStatePaneWidget.js b/third_party/blink/renderer/devtools/front_end/elements/ElementStatePaneWidget.js index a2fd799d..ede7770 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementStatePaneWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementStatePaneWidget.js
@@ -20,8 +20,9 @@ */ function clickListener(event) { const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return; + } node.domModel().cssModel().forcePseudoState(node, event.target.state, event.target.checked); } @@ -64,13 +65,16 @@ * @param {?SDK.CSSModel} cssModel */ _updateModel(cssModel) { - if (this._cssModel === cssModel) + if (this._cssModel === cssModel) { return; - if (this._cssModel) + } + if (this._cssModel) { this._cssModel.removeEventListener(SDK.CSSModel.Events.PseudoStateForced, this._update, this); + } this._cssModel = cssModel; - if (this._cssModel) + if (this._cssModel) { this._cssModel.addEventListener(SDK.CSSModel.Events.PseudoStateForced, this._update, this); + } } /** @@ -81,12 +85,14 @@ } _update() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } let node = UI.context.flavor(SDK.DOMNode); - if (node) + if (node) { node = node.enclosingElementOrSelf(); + } this._updateModel(node ? node.domModel().cssModel() : null); if (node) {
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsBreadcrumbs.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsBreadcrumbs.js index ec4017e7..dd1d6bc9 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsBreadcrumbs.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsBreadcrumbs.js
@@ -28,8 +28,9 @@ * @param {!Array.<!SDK.DOMNode>} nodes */ updateNodes(nodes) { - if (!nodes.length) + if (!nodes.length) { return; + } const crumbs = this.crumbsElement; for (let crumb = crumbs.firstChild; crumb; crumb = crumb.nextSibling) { @@ -52,13 +53,15 @@ const nodeUnderMouse = event.target; const crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass('crumb'); const node = /** @type {?SDK.DOMNode} */ (crumbElement ? crumbElement[this._nodeSymbol] : null); - if (node) + if (node) { node.highlight(); + } } _mouseMovedOutOfCrumbs(event) { - if (this._currentDOMNode) + if (this._currentDOMNode) { SDK.OverlayModel.hideDOMNodeHighlight(); + } } @@ -82,8 +85,9 @@ while (currentCrumb) { const hidden = currentCrumb.classList.contains('hidden'); const collapsed = currentCrumb.classList.contains('collapsed'); - if (!hidden && !collapsed) + if (!hidden && !collapsed) { break; + } crumb = currentCrumb; currentCrumb = currentCrumb.nextSiblingElement; } @@ -99,8 +103,9 @@ _determineElementTitle(domNode) { switch (domNode.nodeType()) { case Node.ELEMENT_NODE: - if (domNode.pseudoType()) + if (domNode.pseudoType()) { return '::' + domNode.pseudoType(); + } return null; case Node.TEXT_NODE: return Common.UIString('(text)'); @@ -119,8 +124,9 @@ * @param {boolean=} force */ update(force) { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const currentDOMNode = this._currentDOMNode; const crumbs = this.crumbsElement; @@ -148,8 +154,9 @@ crumbs.removeChildren(); for (let current = currentDOMNode; current; current = current.parentNode) { - if (current.nodeType() === Node.DOCUMENT_NODE) + if (current.nodeType() === Node.DOCUMENT_NODE) { continue; + } crumb = createElementWithClass('span', 'crumb'); crumb[this._nodeSymbol] = current; @@ -165,8 +172,9 @@ Elements.DOMLinkifier.decorateNodeLabel(current, crumb); } - if (current === currentDOMNode) + if (current === currentDOMNode) { crumb.classList.add('selected'); + } crumbs.insertBefore(crumb, crumbs.firstChild); } @@ -193,8 +201,9 @@ } // Find the focused crumb index. - if (crumb === focusedCrumb) + if (crumb === focusedCrumb) { focusedIndex = i; + } crumb.classList.remove('compact', 'collapsed', 'hidden'); } @@ -248,12 +257,14 @@ * @param {!Element=} focusedCrumb */ updateSizes(focusedCrumb) { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const crumbs = this.crumbsElement; - if (!crumbs.firstChild) + if (!crumbs.firstChild) { return; + } const selections = this._resetCrumbStylesAndFindSelections(focusedCrumb); const sizes = this._measureElementSizes(); @@ -265,8 +276,9 @@ let totalSize = 0; for (let i = 0; i < crumbs.childNodes.length; ++i) { const crumb = crumbs.childNodes[i]; - if (crumb.classList.contains('hidden')) + if (crumb.classList.contains('hidden')) { continue; + } if (crumb.classList.contains('collapsed')) { totalSize += sizes.collapsed; continue; @@ -277,8 +289,9 @@ return totalSize + rightPadding < sizes.available; } - if (crumbsAreSmallerThanContainer()) - return; // No need to compact the crumbs, they all fit at full size. + if (crumbsAreSmallerThanContainer()) { + return; + } // No need to compact the crumbs, they all fit at full size. const BothSides = 0; const AncestorSide = -1; @@ -294,10 +307,12 @@ function shrinkCrumbAtIndex(index) { const shrinkCrumb = crumbs.children[index]; - if (shrinkCrumb && shrinkCrumb !== significantCrumb) + if (shrinkCrumb && shrinkCrumb !== significantCrumb) { shrinkingFunction(shrinkCrumb); - if (crumbsAreSmallerThanContainer()) - return true; // No need to compact the crumbs more. + } + if (crumbsAreSmallerThanContainer()) { + return true; + } // No need to compact the crumbs more. return false; } @@ -307,8 +322,9 @@ // Crumbs are shrunk on only one side (based on direction) of the signifcant crumb. let index = (direction > 0 ? 0 : crumbs.childNodes.length - 1); while (index !== significantIndex) { - if (shrinkCrumbAtIndex(index)) + if (shrinkCrumbAtIndex(index)) { return true; + } index += (direction > 0 ? 1 : -1); } } else { @@ -320,12 +336,14 @@ const startDistance = significantIndex - startIndex; const endDistance = endIndex - significantIndex; let index; - if (startDistance >= endDistance) + if (startDistance >= endDistance) { index = startIndex++; - else + } else { index = endIndex--; - if (shrinkCrumbAtIndex(index)) + } + if (shrinkCrumbAtIndex(index)) { return true; + } } } @@ -388,8 +406,9 @@ * @param {!Element} crumb */ function compact(crumb) { - if (crumb.classList.contains('hidden')) + if (crumb.classList.contains('hidden')) { return; + } crumb.classList.add('compact'); } @@ -398,12 +417,14 @@ * @param {boolean=} dontCoalesce */ function collapse(crumb, dontCoalesce) { - if (crumb.classList.contains('hidden')) + if (crumb.classList.contains('hidden')) { return; + } crumb.classList.add('collapsed'); crumb.classList.remove('compact'); - if (!dontCoalesce) + if (!dontCoalesce) { coalesceCollapsedCrumbs(); + } } if (!focusedCrumb) { @@ -411,29 +432,35 @@ // crumbs that the user might not care much about. // Compact child crumbs. - if (makeCrumbsSmaller(compact, ChildSide)) + if (makeCrumbsSmaller(compact, ChildSide)) { return; + } // Collapse child crumbs. - if (makeCrumbsSmaller(collapse, ChildSide)) + if (makeCrumbsSmaller(collapse, ChildSide)) { return; + } } // Compact ancestor crumbs, or from both sides if focused. - if (makeCrumbsSmaller(compact, focusedCrumb ? BothSides : AncestorSide)) + if (makeCrumbsSmaller(compact, focusedCrumb ? BothSides : AncestorSide)) { return; + } // Collapse ancestor crumbs, or from both sides if focused. - if (makeCrumbsSmaller(collapse, focusedCrumb ? BothSides : AncestorSide)) + if (makeCrumbsSmaller(collapse, focusedCrumb ? BothSides : AncestorSide)) { return; + } - if (!selectedCrumb) + if (!selectedCrumb) { return; + } // Compact the selected crumb. compact(selectedCrumb); - if (crumbsAreSmallerThanContainer()) + if (crumbsAreSmallerThanContainer()) { return; + } // Collapse the selected crumb as a last resort. Pass true to prevent coalescing. collapse(selectedCrumb, true);
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js index 6835482..c4449be 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js
@@ -60,8 +60,9 @@ this._contentElement.id = 'elements-content'; // FIXME: crbug.com/425984 - if (Common.moduleSetting('domWordWrap').get()) + if (Common.moduleSetting('domWordWrap').get()) { this._contentElement.classList.add('elements-wrap'); + } Common.moduleSetting('domWordWrap').addChangeListener(this._domWordWrapSettingChanged.bind(this)); crumbsContainer.id = 'elements-crumbs'; @@ -149,8 +150,9 @@ treeOutline.wireToDOMModel(domModel); // Perform attach if necessary. - if (this.isShowing()) + if (this.isShowing()) { this.wasShown(); + } } /** @@ -160,12 +162,14 @@ modelRemoved(domModel) { const treeOutline = Elements.ElementsTreeOutline.forDOMModel(domModel); treeOutline.unwireFromDOMModel(domModel); - if (domModel.parentModel()) + if (domModel.parentModel()) { return; + } this._treeOutlines.remove(treeOutline); const header = this._treeOutlineHeaders.get(treeOutline); - if (header) + if (header) { header.remove(); + } this._treeOutlineHeaders.delete(treeOutline); treeOutline.element.remove(); } @@ -175,28 +179,34 @@ */ _targetNameChanged(target) { const domModel = target.model(SDK.DOMModel); - if (!domModel) + if (!domModel) { return; + } const treeOutline = Elements.ElementsTreeOutline.forDOMModel(domModel); - if (!treeOutline) + if (!treeOutline) { return; + } const header = this._treeOutlineHeaders.get(treeOutline); - if (!header) + if (!header) { return; + } header.removeChildren(); header.createChild('div', 'elements-tree-header-frame').textContent = Common.UIString('Frame'); header.appendChild(Components.Linkifier.linkifyURL(target.inspectedURL(), {text: target.name()})); } _updateTreeOutlineVisibleWidth() { - if (!this._treeOutlines.length) + if (!this._treeOutlines.length) { return; + } let width = this._splitWidget.element.offsetWidth; - if (this._splitWidget.isVertical()) + if (this._splitWidget.isVertical()) { width -= this._splitWidget.sidebarSize(); - for (let i = 0; i < this._treeOutlines.length; ++i) + } + for (let i = 0; i < this._treeOutlines.length; ++i) { this._treeOutlines[i].setVisibleWidth(width); + } this._breadcrumbs.updateSizes(); } @@ -205,8 +215,9 @@ * @override */ focus() { - if (this._treeOutlines.length) + if (this._treeOutlines.length) { this._treeOutlines[0].focus(); + } } /** @@ -228,8 +239,9 @@ // Attach heavy component lazily if (treeOutline.element.parentElement !== this._contentElement) { const header = this._treeOutlineHeaders.get(treeOutline); - if (header) + if (header) { this._contentElement.appendChild(header); + } this._contentElement.appendChild(treeOutline.element); } } @@ -238,8 +250,9 @@ const domModels = SDK.targetManager.models(SDK.DOMModel); for (const domModel of domModels) { - if (domModel.parentModel()) + if (domModel.parentModel()) { continue; + } const treeOutline = Elements.ElementsTreeOutline.forDOMModel(domModel); treeOutline.setVisible(true); @@ -265,11 +278,13 @@ // Detach heavy component on hide this._contentElement.removeChild(treeOutline.element); const header = this._treeOutlineHeaders.get(treeOutline); - if (header) + if (header) { this._contentElement.removeChild(header); + } } - if (this._popoverHelper) + if (this._popoverHelper) { this._popoverHelper.hidePopover(); + } super.willHide(); UI.context.setFlavor(Elements.ElementsPanel, null); } @@ -289,16 +304,18 @@ const selectedNode = /** @type {?SDK.DOMNode} */ (event.data.node); const focus = /** @type {boolean} */ (event.data.focus); for (const treeOutline of this._treeOutlines) { - if (!selectedNode || Elements.ElementsTreeOutline.forDOMModel(selectedNode.domModel()) !== treeOutline) + if (!selectedNode || Elements.ElementsTreeOutline.forDOMModel(selectedNode.domModel()) !== treeOutline) { treeOutline.selectDOMNode(null); + } } this._breadcrumbs.setSelectedNode(selectedNode); UI.context.setFlavor(SDK.DOMNode, selectedNode); - if (!selectedNode) + if (!selectedNode) { return; + } selectedNode.setAsInspectedNode(); if (focus) { this._selectedNodeOnReset = selectedNode; @@ -330,15 +347,17 @@ this._searchableView.resetSearch(); if (!domModel.existingDocument()) { - if (this.isShowing()) + if (this.isShowing()) { domModel.requestDocument(); + } return; } this._hasNonDefaultSelectedNode = false; - if (this._omitDefaultSelection) + if (this._omitDefaultSelection) { return; + } const savedSelectedNodeOnReset = this._selectedNodeOnReset; restoreNode.call(this, domModel, this._selectedNodeOnReset); @@ -353,8 +372,9 @@ const restoredNodeId = nodePath ? await domModel.pushNodeByPathToFrontend(nodePath) : null; - if (savedSelectedNodeOnReset !== this._selectedNodeOnReset) + if (savedSelectedNodeOnReset !== this._selectedNodeOnReset) { return; + } let node = restoredNodeId ? domModel.nodeForId(restoredNodeId) : null; if (!node) { const inspectedDocument = domModel.existingDocument(); @@ -372,14 +392,17 @@ * @param {?SDK.DOMNode} node */ _setDefaultSelectedNode(node) { - if (!node || this._hasNonDefaultSelectedNode || this._pendingNodeReveal) + if (!node || this._hasNonDefaultSelectedNode || this._pendingNodeReveal) { return; + } const treeOutline = Elements.ElementsTreeOutline.forDOMModel(node.domModel()); - if (!treeOutline) + if (!treeOutline) { return; + } this.selectDOMNode(node); - if (treeOutline.selectedTreeElement) + if (treeOutline.selectedTreeElement) { treeOutline.selectedTreeElement.expand(); + } } /** @@ -407,13 +430,15 @@ const query = searchConfig.query; const whitespaceTrimmedQuery = query.trim(); - if (!whitespaceTrimmedQuery.length) + if (!whitespaceTrimmedQuery.length) { return; + } - if (!this._searchConfig || this._searchConfig.query !== query) + if (!this._searchConfig || this._searchConfig.query !== query) { this.searchCanceled(); - else + } else { this._hideSearchHighlights(); + } this._searchConfig = searchConfig; @@ -433,22 +458,26 @@ this._searchResults = []; for (let i = 0; i < resultCounts.length; ++i) { const resultCount = resultCounts[i]; - for (let j = 0; j < resultCount; ++j) + for (let j = 0; j < resultCount; ++j) { this._searchResults.push({domModel: domModels[i], index: j, node: undefined}); + } } this._searchableView.updateSearchMatchesCount(this._searchResults.length); - if (!this._searchResults.length) + if (!this._searchResults.length) { return; - if (this._currentSearchResultIndex >= this._searchResults.length) + } + if (this._currentSearchResultIndex >= this._searchResults.length) { this._currentSearchResultIndex = undefined; + } let index = this._currentSearchResultIndex; if (shouldJump) { - if (this._currentSearchResultIndex === undefined) + if (this._currentSearchResultIndex === undefined) { index = jumpBackwards ? -1 : 0; - else + } else { index = jumpBackwards ? index - 1 : index + 1; + } this._jumpToSearchResult(index); } } @@ -457,8 +486,9 @@ _domWordWrapSettingChanged(event) { // FIXME: crbug.com/425984 this._contentElement.classList.toggle('elements-wrap', event.data); - for (let i = 0; i < this._treeOutlines.length; ++i) + for (let i = 0; i < this._treeOutlines.length; ++i) { this._treeOutlines[i].setWordWrap(/** @type {boolean} */ (event.data)); + } } switchToAndFocus(node) { @@ -473,21 +503,25 @@ */ _getPopoverRequest(event) { let link = event.target; - while (link && !link[Elements.ElementsTreeElement.HrefSymbol]) + while (link && !link[Elements.ElementsTreeElement.HrefSymbol]) { link = link.parentElementOrShadowHost(); - if (!link) + } + if (!link) { return null; + } return { box: link.boxInWindow(), show: async popover => { const node = this.selectedDOMNode(); - if (!node) + if (!node) { return false; + } const preview = await Components.ImagePreview.build( node.domModel().target(), link[Elements.ElementsTreeElement.HrefSymbol], true); - if (preview) + if (preview) { popover.contentElement.appendChild(preview); + } return !!preview; } }; @@ -502,8 +536,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchResults) + if (!this._searchResults) { return; + } this.performSearch(this._searchConfig, true); } @@ -511,8 +546,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchResults) + if (!this._searchResults) { return; + } this.performSearch(this._searchConfig, true, true); } @@ -538,8 +574,9 @@ const searchResult = searchResults[index]; this._searchableView.updateCurrentMatchIndex(index); - if (searchResult.node === null) + if (searchResult.node === null) { return; + } if (typeof searchResult.node === 'undefined') { // No data for slot, request it. @@ -556,21 +593,25 @@ treeElement.highlightSearchResults(this._searchConfig.query); treeElement.reveal(); const matches = treeElement.listItemElement.getElementsByClassName(UI.highlightedSearchResultClassName); - if (matches.length) + if (matches.length) { matches[0].scrollIntoViewIfNeeded(false); + } } } _hideSearchHighlights() { - if (!this._searchResults || !this._searchResults.length || this._currentSearchResultIndex === undefined) + if (!this._searchResults || !this._searchResults.length || this._currentSearchResultIndex === undefined) { return; + } const searchResult = this._searchResults[this._currentSearchResultIndex]; - if (!searchResult.node) + if (!searchResult.node) { return; + } const treeOutline = Elements.ElementsTreeOutline.forDOMModel(searchResult.node.domModel()); const treeElement = treeOutline.findTreeElement(searchResult.node); - if (treeElement) + if (treeElement) { treeElement.hideSearchHighlights(); + } } /** @@ -579,8 +620,9 @@ selectedDOMNode() { for (let i = 0; i < this._treeOutlines.length; ++i) { const treeOutline = this._treeOutlines[i]; - if (treeOutline.selectedDOMNode()) + if (treeOutline.selectedDOMNode()) { return treeOutline.selectedDOMNode(); + } } return null; } @@ -592,10 +634,11 @@ selectDOMNode(node, focus) { for (const treeOutline of this._treeOutlines) { const outline = Elements.ElementsTreeOutline.forDOMModel(node.domModel()); - if (outline === treeOutline) + if (outline === treeOutline) { treeOutline.selectDOMNode(node, focus); - else + } else { treeOutline.selectDOMNode(null); + } } } @@ -620,8 +663,9 @@ * @return {?Elements.ElementsTreeOutline} */ _treeOutlineForNode(node) { - if (!node) + if (!node) { return null; + } return Elements.ElementsTreeOutline.forDOMModel(node.domModel()); } @@ -640,8 +684,9 @@ */ _leaveUserAgentShadowDOM(node) { let userAgentShadowRoot; - while ((userAgentShadowRoot = node.ancestorUserAgentShadowRoot()) && userAgentShadowRoot.parentNode) + while ((userAgentShadowRoot = node.ancestorUserAgentShadowRoot()) && userAgentShadowRoot.parentNode) { node = userAgentShadowRoot.parentNode; + } return node; } @@ -655,8 +700,9 @@ this._omitDefaultSelection = true; node = Common.moduleSetting('showUAShadowDOM').get() ? node : this._leaveUserAgentShadowDOM(node); - if (!omitHighlight) + if (!omitHighlight) { node.highlightForTwoSeconds(); + } return UI.viewManager.showView('elements', false, !focus).then(() => { this.selectDOMNode(node, focus); @@ -672,8 +718,9 @@ } _showUAShadowDOMChanged() { - for (let i = 0; i < this._treeOutlines.length; ++i) + for (let i = 0; i < this._treeOutlines.length; ++i) { this._treeOutlines[i].update(); + } } /** @@ -686,13 +733,15 @@ // Fallback to cover unforeseen cases where text selection has ended. const uninstallHackOnMousemove = event => { - if (event.buttons === 0) + if (event.buttons === 0) { uninstallHack.call(this); + } }; stylePaneWrapperElement.addEventListener('mousedown', event => { - if (event.which !== 1) + if (event.which !== 1) { return; + } this._splitWidget.element.classList.add('disable-resizer-for-elements-hack'); stylePaneWrapperElement.style.setProperty('height', `${stylePaneWrapperElement.offsetHeight}px`); const largeLength = 1000000; @@ -729,20 +778,23 @@ } _updateSidebarPosition() { - if (this.sidebarPaneView && this.sidebarPaneView.tabbedPane().shouldHideOnDetach()) - return; // We can't reparent extension iframes. + if (this.sidebarPaneView && this.sidebarPaneView.tabbedPane().shouldHideOnDetach()) { + return; + } // We can't reparent extension iframes. let splitMode; const position = Common.moduleSetting('sidebarPosition').get(); - if (position === 'right' || (position === 'auto' && UI.inspectorView.element.offsetWidth > 680)) + if (position === 'right' || (position === 'auto' && UI.inspectorView.element.offsetWidth > 680)) { splitMode = Elements.ElementsPanel._splitMode.Vertical; - else if (UI.inspectorView.element.offsetWidth > 415) + } else if (UI.inspectorView.element.offsetWidth > 415) { splitMode = Elements.ElementsPanel._splitMode.Horizontal; - else + } else { splitMode = Elements.ElementsPanel._splitMode.Slim; + } - if (this.sidebarPaneView && splitMode === this._splitMode) + if (this.sidebarPaneView && splitMode === this._splitMode) { return; + } this._splitMode = splitMode; const extensionSidebarPanes = Extensions.extensionServer.sidebarPanes(); @@ -770,10 +822,11 @@ * @this {Elements.ElementsPanel} */ function showMetrics(inComputedStyle) { - if (inComputedStyle) + if (inComputedStyle) { this._metricsWidget.show(computedStylePanesWrapper.element, this._computedStyleWidget.element); - else + } else { this._metricsWidget.show(matchedStylePanesWrapper.element); + } } /** @@ -782,22 +835,25 @@ */ function tabSelected(event) { const tabId = /** @type {string} */ (event.data.tabId); - if (tabId === Common.UIString('Computed')) + if (tabId === Common.UIString('Computed')) { showMetrics.call(this, true); - else if (tabId === Common.UIString('Styles')) + } else if (tabId === Common.UIString('Styles')) { showMetrics.call(this, false); + } } this.sidebarPaneView = UI.viewManager.createTabbedLocation(() => UI.viewManager.showView('elements')); const tabbedPane = this.sidebarPaneView.tabbedPane(); - if (this._popoverHelper) + if (this._popoverHelper) { this._popoverHelper.hidePopover(); + } this._popoverHelper = new UI.PopoverHelper(tabbedPane.element, this._getPopoverRequest.bind(this)); this._popoverHelper.setHasPadding(true); this._popoverHelper.setTimeout(0); - if (this._splitMode !== Elements.ElementsPanel._splitMode.Vertical) + if (this._splitMode !== Elements.ElementsPanel._splitMode.Vertical) { this._splitWidget.installResizer(tabbedPane.headerElement()); + } const stylesView = new UI.SimpleView(Common.UIString('Styles')); this.sidebarPaneView.appendView(stylesView); @@ -826,11 +882,13 @@ showMetrics.call(this, this._splitMode === Elements.ElementsPanel._splitMode.Horizontal); this.sidebarPaneView.appendApplicableItems('elements-sidebar'); - for (let i = 0; i < extensionSidebarPanes.length; ++i) + for (let i = 0; i < extensionSidebarPanes.length; ++i) { this._addExtensionSidebarPane(extensionSidebarPanes[i]); + } - if (lastSelectedTabId) + if (lastSelectedTabId) { this.sidebarPaneView.tabbedPane().selectTab(lastSelectedTabId); + } this._splitWidget.setSidebarWidget(this.sidebarPaneView.tabbedPane()); } @@ -847,8 +905,9 @@ * @param {!Extensions.ExtensionSidebarPane} pane */ _addExtensionSidebarPane(pane) { - if (pane.panelName() === this.name) + if (pane.panelName() === this.name) { this.sidebarPaneView.appendView(pane); + } } }; @@ -877,12 +936,14 @@ */ appendApplicableItems(event, contextMenu, object) { if (!(object instanceof SDK.RemoteObject && (/** @type {!SDK.RemoteObject} */ (object)).isNode()) && - !(object instanceof SDK.DOMNode) && !(object instanceof SDK.DeferredDOMNode)) + !(object instanceof SDK.DOMNode) && !(object instanceof SDK.DeferredDOMNode)) { return; + } // Skip adding "Reveal..." menu item for our own tree outline. - if (Elements.ElementsPanel.instance().element.isAncestor(/** @type {!Node} */ (event.target))) + if (Elements.ElementsPanel.instance().element.isAncestor(/** @type {!Node} */ (event.target))) { return; + } const commandCallback = Common.Revealer.reveal.bind(Common.Revealer, object); contextMenu.revealSection().appendItem(Common.UIString('Reveal in Elements panel'), commandCallback); } @@ -916,10 +977,11 @@ (/** @type {!SDK.DeferredDOMNode} */ (node)).resolve(onNodeResolved); } else if (node instanceof SDK.RemoteObject) { const domModel = /** @type {!SDK.RemoteObject} */ (node).runtimeModel().target().model(SDK.DOMModel); - if (domModel) + if (domModel) { domModel.pushObjectAsNodeToFrontend(node).then(onNodeResolved); - else + } else { reject(new Error('Could not resolve a node to reveal.')); + } } else { reject(new Error('Can\'t reveal a non-node.')); panel._pendingNodeReveal = false; @@ -971,11 +1033,13 @@ */ handleAction(context, actionId) { const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return true; + } const treeOutline = Elements.ElementsTreeOutline.forDOMModel(node.domModel()); - if (!treeOutline) + if (!treeOutline) { return true; + } switch (actionId) { case 'elements.hide-element':
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsSidebarPane.js index 1f76f3d..bda591c8 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsSidebarPane.js
@@ -43,8 +43,9 @@ update() { this._updateWhenVisible = !this.isShowing(); - if (this._updateWhenVisible) + if (this._updateWhenVisible) { return; + } this._updateThrottler.schedule(innerUpdate.bind(this)); /** @@ -61,8 +62,9 @@ */ wasShown() { super.wasShown(); - if (this._updateWhenVisible) + if (this._updateWhenVisible) { this.update(); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js index 2f51fb3..cfd01cac 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElement.js
@@ -49,8 +49,9 @@ this._elementCloseTag = elementCloseTag; - if (this._node.nodeType() === Node.ELEMENT_NODE && !elementCloseTag) + if (this._node.nodeType() === Node.ELEMENT_NODE && !elementCloseTag) { this._canAddAttributes = true; + } this._searchQuery = null; this._expandedChildrenLimit = Elements.ElementsTreeElement.InitialChildrenLimit; this._decorationsThrottler = new Common.Throttler(100); @@ -70,8 +71,9 @@ */ static visibleShadowRoots(node) { let roots = node.shadowRoots(); - if (roots.length && !Common.moduleSetting('showUAShadowDOM').get()) + if (roots.length && !Common.moduleSetting('showUAShadowDOM').get()) { roots = roots.filter(filter); + } /** * @param {!SDK.DOMNode} root @@ -88,16 +90,20 @@ */ static canShowInlineText(node) { if (node.contentDocument() || node.importedDocument() || node.templateContent() || - Elements.ElementsTreeElement.visibleShadowRoots(node).length || node.hasPseudoElements()) + Elements.ElementsTreeElement.visibleShadowRoots(node).length || node.hasPseudoElements()) { return false; - if (node.nodeType() !== Node.ELEMENT_NODE) + } + if (node.nodeType() !== Node.ELEMENT_NODE) { return false; - if (!node.firstChild || node.firstChild !== node.lastChild || node.firstChild.nodeType() !== Node.TEXT_NODE) + } + if (!node.firstChild || node.firstChild !== node.lastChild || node.firstChild.nodeType() !== Node.TEXT_NODE) { return false; + } const textChild = node.firstChild; const maxInlineTextChildLength = 80; - if (textChild.nodeValue().length < maxInlineTextChildLength) + if (textChild.nodeValue().length < maxInlineTextChildLength) { return true; + } return false; } @@ -156,8 +162,9 @@ * @param {string} searchQuery */ highlightSearchResults(searchQuery) { - if (this._searchQuery !== searchQuery) + if (this._searchQuery !== searchQuery) { this._hideSearchHighlight(); + } this._searchQuery = searchQuery; this._searchHighlightsVisible = true; @@ -170,8 +177,9 @@ } _hideSearchHighlight() { - if (!this._highlightResult) + if (!this._highlightResult) { return; + } function updateEntryHide(entry) { switch (entry.type) { @@ -184,8 +192,9 @@ } } - for (let i = (this._highlightResult.length - 1); i >= 0; --i) + for (let i = (this._highlightResult.length - 1); i >= 0; --i) { updateEntryHide(this._highlightResult[i]); + } delete this._highlightResult; } @@ -194,8 +203,9 @@ * @param {boolean} inClipboard */ setInClipboard(inClipboard) { - if (this._inClipboard === inClipboard) + if (this._inClipboard === inClipboard) { return; + } this._inClipboard = inClipboard; this.listItemElement.classList.toggle('in-clipboard', inClipboard); } @@ -205,8 +215,9 @@ } set hovered(x) { - if (this._hovered === x) + if (this._hovered === x) { return; + } this._hovered = x; @@ -236,8 +247,9 @@ _createSelection() { const listItemElement = this.listItemElement; - if (!listItemElement) + if (!listItemElement) { return; + } if (!this.selectionElement) { this.selectionElement = createElement('div'); @@ -260,16 +272,18 @@ * @override */ onbind() { - if (!this._elementCloseTag) + if (!this._elementCloseTag) { this._node[this.treeOutline.treeElementSymbol()] = this; + } } /** * @override */ onunbind() { - if (this._node[this.treeOutline.treeElementSymbol()] === this) + if (this._node[this.treeOutline.treeElementSymbol()] === this) { this._node[this.treeOutline.treeElementSymbol()] = null; + } } /** @@ -305,8 +319,9 @@ * @override */ onexpand() { - if (this._elementCloseTag) + if (this._elementCloseTag) { return; + } this.updateTitle(); } @@ -315,8 +330,9 @@ * @override */ oncollapse() { - if (this._elementCloseTag) + if (this._elementCloseTag) { return; + } this.updateTitle(); } @@ -328,8 +344,9 @@ * @return {boolean} */ select(omitFocus, selectedByUser) { - if (this._editing) + if (this._editing) { return false; + } return super.select(omitFocus, selectedByUser); } @@ -368,8 +385,9 @@ onenter() { // On Enter or Return start editing the first attribute // or create a new attribute on the selected element. - if (this._editing) + if (this._editing) { return false; + } this._startEditing(); @@ -383,12 +401,14 @@ selectOnMouseDown(event) { super.selectOnMouseDown(event); - if (this._editing) + if (this._editing) { return; + } // Prevent selecting the nearest word on double click. - if (event.detail >= 2) + if (event.detail >= 2) { event.preventDefault(); + } } /** @@ -396,14 +416,17 @@ * @return {boolean} */ ondblclick(event) { - if (this._editing || this._elementCloseTag) + if (this._editing || this._elementCloseTag) { return false; + } - if (this._startEditingTarget(/** @type {!Element} */ (event.target))) + if (this._startEditingTarget(/** @type {!Element} */ (event.target))) { return false; + } - if (this.isExpandable() && !this.expanded) + if (this.isExpandable() && !this.expanded) { this.expand(); + } return false; } @@ -431,27 +454,33 @@ * @return {boolean} */ _startEditingTarget(eventTarget) { - if (this.treeOutline.selectedDOMNode() !== this._node) + if (this.treeOutline.selectedDOMNode() !== this._node) { return false; + } - if (this._node.nodeType() !== Node.ELEMENT_NODE && this._node.nodeType() !== Node.TEXT_NODE) + if (this._node.nodeType() !== Node.ELEMENT_NODE && this._node.nodeType() !== Node.TEXT_NODE) { return false; + } const textNode = eventTarget.enclosingNodeOrSelfWithClass('webkit-html-text-node'); - if (textNode) + if (textNode) { return this._startEditingTextNode(textNode); + } const attribute = eventTarget.enclosingNodeOrSelfWithClass('webkit-html-attribute'); - if (attribute) + if (attribute) { return this._startEditingAttribute(attribute, eventTarget); + } const tagName = eventTarget.enclosingNodeOrSelfWithClass('webkit-html-tag-name'); - if (tagName) + if (tagName) { return this._startEditingTagName(tagName); + } const newAttribute = eventTarget.enclosingNodeOrSelfWithClass('add-attribute'); - if (newAttribute) + if (newAttribute) { return this._addNewAttribute(); + } return false; } @@ -505,8 +534,9 @@ populateNodeContextMenu(contextMenu) { // Add free-form node-related actions. const isEditable = this.hasEditableNode(); - if (isEditable && !this._editing) + if (isEditable && !this._editing) { contextMenu.editSection().appendItem(Common.UIString('Edit as HTML'), this._editAsHTML.bind(this)); + } const isShadowRoot = this._node.isShadowRoot(); // Place it here so that all "Copy"-ing items stick together. @@ -552,16 +582,18 @@ treeOutline.isToggledToHidden(this._node)); menuItem.setShortcut(UI.shortcutRegistry.shortcutTitleForAction('elements.hide-element')); - if (isEditable) + if (isEditable) { contextMenu.editSection().appendItem(Common.UIString('Delete element'), this.remove.bind(this)); + } contextMenu.viewSection().appendItem(ls`Expand recursively`, this.expandRecursively.bind(this)); contextMenu.viewSection().appendItem(ls`Collapse children`, this.collapseChildren.bind(this)); } _startEditing() { - if (this.treeOutline.selectedDOMNode() !== this._node) + if (this.treeOutline.selectedDOMNode() !== this._node) { return; + } const listItem = this.listItemElement; @@ -577,8 +609,9 @@ if (this._node.nodeType() === Node.TEXT_NODE) { const textNode = listItem.getElementsByClassName('webkit-html-text-node')[0]; - if (textNode) + if (textNode) { return this._startEditingTextNode(textNode); + } return; } } @@ -603,11 +636,13 @@ for (let i = 0, len = attributeElements.length; i < len; ++i) { if (attributeElements[i].textContent === attributeName) { for (let elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) { - if (elem.nodeType !== Node.ELEMENT_NODE) + if (elem.nodeType !== Node.ELEMENT_NODE) { continue; + } - if (elem.classList.contains('webkit-html-attribute-value')) + if (elem.classList.contains('webkit-html-attribute-value')) { return this._startEditingAttribute(elem.parentNode, elem); + } } } } @@ -616,12 +651,14 @@ _startEditingAttribute(attribute, elementForSelection) { console.assert(this.listItemElement.isAncestor(attribute)); - if (UI.isBeingEdited(attribute)) + if (UI.isBeingEdited(attribute)) { return true; + } const attributeNameElement = attribute.getElementsByClassName('webkit-html-attribute-name')[0]; - if (!attributeNameElement) + if (!attributeNameElement) { return false; + } const attributeName = attributeNameElement.textContent; const attributeValueElement = attribute.getElementsByClassName('webkit-html-attribute-value')[0]; @@ -636,11 +673,13 @@ return; } - if (node.nodeType !== Node.ELEMENT_NODE) + if (node.nodeType !== Node.ELEMENT_NODE) { return; + } - for (let child = node.firstChild; child; child = child.nextSibling) + for (let child = node.firstChild; child; child = child.nextSibling) { removeZeroWidthSpaceRecursive(child); + } } const attributeValue = attributeName && attributeValueElement ? this._node.getAttribute(attributeName) : undefined; @@ -664,8 +703,9 @@ return ''; } - if (!attributeValueElement.textContent.asParsedURL()) + if (!attributeValueElement.textContent.asParsedURL()) { config.setPostKeydownFinishHandler(postKeyDownFinishHandler); + } this._editing = UI.InplaceEditor.startEditing(attribute, config); @@ -678,18 +718,21 @@ * @param {!Element} textNodeElement */ _startEditingTextNode(textNodeElement) { - if (UI.isBeingEdited(textNodeElement)) + if (UI.isBeingEdited(textNodeElement)) { return true; + } let textNode = this._node; // We only show text nodes inline in elements if the element only // has a single child, and that child is a text node. - if (textNode.nodeType() === Node.ELEMENT_NODE && textNode.firstChild) + if (textNode.nodeType() === Node.ELEMENT_NODE && textNode.firstChild) { textNode = textNode.firstChild; + } const container = textNodeElement.enclosingNodeOrSelfWithClass('webkit-html-text-node'); - if (container) - container.textContent = textNode.nodeValue(); // Strip the CSS or JS highlighting if present. + if (container) { + container.textContent = textNode.nodeValue(); + } // Strip the CSS or JS highlighting if present. const config = new UI.InplaceEditor.Config( this._textNodeEditingCommitted.bind(this, textNode), this._editingCancelled.bind(this)); this._editing = UI.InplaceEditor.startEditing(textNodeElement, config); @@ -704,16 +747,19 @@ _startEditingTagName(tagNameElement) { if (!tagNameElement) { tagNameElement = this.listItemElement.getElementsByClassName('webkit-html-tag-name')[0]; - if (!tagNameElement) + if (!tagNameElement) { return false; + } } const tagName = tagNameElement.textContent; - if (Elements.ElementsTreeElement.EditTagBlacklist.has(tagName.toLowerCase())) + if (Elements.ElementsTreeElement.EditTagBlacklist.has(tagName.toLowerCase())) { return false; + } - if (UI.isBeingEdited(tagNameElement)) + if (UI.isBeingEdited(tagNameElement)) { return true; + } const closingTagElement = this._distinctClosingTagElement(); @@ -721,16 +767,18 @@ * @param {!Event} event */ function keyupListener(event) { - if (closingTagElement) + if (closingTagElement) { closingTagElement.textContent = '</' + tagNameElement.textContent + '>'; + } } /** * @param {!Event} event */ const keydownListener = event => { - if (event.key !== ' ') + if (event.key !== ' ') { return; + } this._editing.commit(); event.consume(true); }; @@ -770,11 +818,13 @@ * @param {?string} maybeInitialValue */ _startEditingAsHTML(commitCallback, disposeCallback, maybeInitialValue) { - if (maybeInitialValue === null) + if (maybeInitialValue === null) { return; + } let initialValue = maybeInitialValue; // To suppress a compiler warning. - if (this._editing) + if (this._editing) { return; + } initialValue = this._convertWhitespaceToEntities(initialValue).text; @@ -788,8 +838,9 @@ child = child.nextSibling; } // Hide children item. - if (this.childrenListElement) + if (this.childrenListElement) { this.childrenListElement.style.display = 'none'; + } // Append editor. this.listItemElement.appendChild(this._htmlEditElement); @@ -816,8 +867,9 @@ editor.widget().focus(); editor.widget().element.addEventListener('focusout', event => { // The relatedTarget is null when no element gains focus, e.g. switching windows. - if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(editor.widget().element)) + if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(editor.widget().element)) { this._editing.commit(); + } }, false); editor.widget().element.addEventListener('keydown', keydown.bind(this), true); @@ -852,8 +904,9 @@ this.listItemElement.removeChild(this._htmlEditElement); delete this._htmlEditElement; // Unhide children item. - if (this.childrenListElement) + if (this.childrenListElement) { this.childrenListElement.style.removeProperty('display'); + } // Unhide header items. let child = this.listItemElement.firstChild; while (child) { @@ -896,11 +949,13 @@ * @this {Elements.ElementsTreeElement} */ function moveToNextAttributeIfNeeded(error) { - if (error) + if (error) { this._editingCancelled(element, attributeName); + } - if (!moveDirection) + if (!moveDirection) { return; + } treeOutline.runPendingUpdates(); treeOutline.focus(); @@ -908,19 +963,22 @@ // Search for the attribute's position, and then decide where to move to. const attributes = this._node.attributes(); for (let i = 0; i < attributes.length; ++i) { - if (attributes[i].name !== attributeName) + if (attributes[i].name !== attributeName) { continue; + } if (moveDirection === 'backward') { - if (i === 0) + if (i === 0) { this._startEditingTagName(); - else + } else { this._triggerEditAttribute(attributes[i - 1].name); + } } else { - if (i === attributes.length - 1) + if (i === attributes.length - 1) { this._addNewAttribute(); - else + } else { this._triggerEditAttribute(attributes[i + 1].name); + } } return; } @@ -929,18 +987,21 @@ if (moveDirection === 'backward') { if (newText === ' ') { // Moving from "New Attribute" that was not edited - if (attributes.length > 0) + if (attributes.length > 0) { this._triggerEditAttribute(attributes[attributes.length - 1].name); + } } else { // Moving from "New Attribute" that holds new value - if (attributes.length > 1) + if (attributes.length > 1) { this._triggerEditAttribute(attributes[attributes.length - 2].name); + } } } else if (moveDirection === 'forward') { - if (!newText.isWhitespace()) + if (!newText.isWhitespace()) { this._addNewAttribute(); - else + } else { this._startEditingTagName(); + } } } @@ -959,8 +1020,9 @@ function cancel() { const closingTagElement = self._distinctClosingTagElement(); - if (closingTagElement) + if (closingTagElement) { closingTagElement.textContent = '</' + tagName + '>'; + } self._editingCancelled(element, tagName); moveToNextAttributeIfNeeded.call(self); @@ -976,10 +1038,11 @@ } const attributes = this._node.attributes(); - if (attributes.length > 0) + if (attributes.length > 0) { this._triggerEditAttribute(attributes[0].name); - else + } else { this._addNewAttribute(); + } } newText = newText.trim(); @@ -1056,8 +1119,9 @@ updateTitle(updateRecord, onlySearchQueryChanged) { // If we are editing, return early to prevent canceling the edit. // After editing is committed updateTitle will be called. - if (this._editing) + if (this._editing) { return; + } if (onlySearchQueryChanged) { this._hideSearchHighlight(); @@ -1068,13 +1132,15 @@ this.childrenListElement.classList.add('shadow-root'); let depth = 4; for (let node = this._node; depth && node; node = node.parentNode) { - if (node.nodeType() === Node.DOCUMENT_FRAGMENT_NODE) + if (node.nodeType() === Node.DOCUMENT_FRAGMENT_NODE) { depth--; + } } - if (!depth) + if (!depth) { this.childrenListElement.classList.add('shadow-root-deep'); - else + } else { this.childrenListElement.classList.add('shadow-root-depth-' + depth); + } } const highlightElement = createElement('span'); highlightElement.className = 'highlight'; @@ -1112,11 +1178,13 @@ updateDecorations() { this._gutterContainer.style.left = (-this._computeLeftIndent()) + 'px'; - if (this.isClosingTag()) + if (this.isClosingTag()) { return; + } - if (this._node.nodeType() !== Node.ELEMENT_NODE) + if (this._node.nodeType() !== Node.ELEMENT_NODE) { return; + } this._decorationsThrottler.schedule(this._updateDecorationsInternal.bind(this)); } @@ -1125,14 +1193,15 @@ * @return {!Promise} */ _updateDecorationsInternal() { - if (!this.treeOutline) + if (!this.treeOutline) { return Promise.resolve(); + } const node = this._node; - if (!this.treeOutline._decoratorExtensions) - /** @type {!Array.<!Runtime.Extension>} */ + if (!this.treeOutline._decoratorExtensions) { this.treeOutline._decoratorExtensions = self.runtime.extensions(Elements.MarkerDecorator); + } const markerToExtension = new Map(); for (let i = 0; i < this.treeOutline._decoratorExtensions.length; ++i) { @@ -1151,8 +1220,9 @@ */ function visitor(n, marker) { const extension = markerToExtension.get(marker); - if (!extension) + if (!extension) { return; + } promises.push(extension.instance().then(collectDecoration.bind(null, n))); } @@ -1162,8 +1232,9 @@ */ function collectDecoration(n, decorator) { const decoration = decorator.decorate(n); - if (!decoration) + if (!decoration) { return; + } (n === node ? decorations : descendantDecorations).push(decoration); } @@ -1177,8 +1248,9 @@ this._decorationsElement.classList.add('hidden'); this._gutterContainer.classList.toggle('has-decorations', decorations.length || descendantDecorations.length); - if (!decorations.length && !descendantDecorations.length) + if (!decorations.length && !descendantDecorations.length) { return; + } const colors = new Set(); const titles = createElement('div'); @@ -1188,8 +1260,9 @@ titleElement.textContent = decoration.title; colors.add(decoration.color); } - if (this.expanded && !decorations.length) + if (this.expanded && !decorations.length) { return; + } const descendantColors = new Set(); if (descendantDecorations.length) { @@ -1205,8 +1278,9 @@ let offset = 0; processColors.call(this, colors, 'elements-gutter-decoration'); - if (!this.expanded) + if (!this.expanded) { processColors.call(this, descendantColors, 'elements-gutter-decoration elements-has-decorated-children'); + } UI.Tooltip.install(this._decorationsElement, titles); /** @@ -1220,8 +1294,9 @@ this._decorationsElement.classList.remove('hidden'); child.style.backgroundColor = color; child.style.borderColor = color; - if (offset) + if (offset) { child.style.marginLeft = offset + 'px'; + } offset += 3; } } @@ -1279,13 +1354,15 @@ const attrNameElement = attrSpanElement.createChild('span', 'webkit-html-attribute-name'); attrNameElement.textContent = name; - if (hasText) + if (hasText) { attrSpanElement.createTextChild('=\u200B"'); + } const attrValueElement = attrSpanElement.createChild('span', 'webkit-html-attribute-value'); - if (updateRecord && updateRecord.isAttributeModified(name)) + if (updateRecord && updateRecord.isAttributeModified(name)) { UI.runCSSAnimationOnce(hasText ? attrValueElement : attrNameElement, 'dom-update-highlight'); + } /** * @this {Elements.ElementsTreeElement} @@ -1300,8 +1377,9 @@ return span; } value = value.replace(closingPunctuationRegex, '$&\u200B'); - if (value.startsWith('data:')) + if (value.startsWith('data:')) { value = value.trimMiddle(60); + } const link = node.nodeName().toLowerCase() === 'a' ? UI.XLink.create(rewrittenHref, value, '', true /* preventClick */) : Components.Linkifier.linkifyURL(rewrittenHref, {text: value, preventClick: true}); @@ -1310,15 +1388,17 @@ } const nodeName = node ? node.nodeName().toLowerCase() : ''; - if (nodeName && (name === 'src' || name === 'href')) + if (nodeName && (name === 'src' || name === 'href')) { attrValueElement.appendChild(linkifyValue.call(this, value)); - else if ((nodeName === 'img' || nodeName === 'source') && name === 'srcset') + } else if ((nodeName === 'img' || nodeName === 'source') && name === 'srcset') { attrValueElement.appendChild(linkifySrcset.call(this, value)); - else + } else { setValueWithEntities.call(this, attrValueElement, value); + } - if (hasText) + if (hasText) { attrSpanElement.createTextChild('"'); + } /** * @param {string} value @@ -1336,8 +1416,9 @@ const fragment = createDocumentFragment(); let i = 0; while (value.length) { - if (i++ > 0) + if (i++ > 0) { fragment.createTextChild(' '); + } value = value.trim(); // The url and descriptor may end with a separating comma. let url = ''; @@ -1350,10 +1431,11 @@ } else { url = value.substring(0, indexOfSpace); const indexOfComma = value.indexOf(',', indexOfSpace); - if (indexOfComma !== -1) + if (indexOfComma !== -1) { descriptor = value.substring(indexOfSpace, indexOfComma + 1); - else + } else { descriptor = value.substring(indexOfSpace); + } } if (url) { @@ -1365,8 +1447,9 @@ fragment.appendChild(linkifyValue.call(this, url)); } } - if (descriptor) + if (descriptor) { fragment.createTextChild(descriptor); + } value = value.substring(url.length + descriptor.length); } return fragment; @@ -1393,8 +1476,9 @@ _buildTagDOM(parentElement, tagName, isClosingTag, isDistinctTreeElement, updateRecord) { const node = this._node; const classes = ['webkit-html-tag']; - if (isClosingTag && isDistinctTreeElement) + if (isClosingTag && isDistinctTreeElement) { classes.push('close'); + } const tagElement = parentElement.createChild('span', classes.join(' ')); tagElement.createTextChild('<'); const tagNameElement = @@ -1412,8 +1496,9 @@ if (updateRecord) { let hasUpdates = updateRecord.hasRemovedAttributes() || updateRecord.hasRemovedChildren(); hasUpdates |= !this.expanded && updateRecord.hasChangedChildren(); - if (hasUpdates) + if (hasUpdates) { UI.runCSSAnimationOnce(tagNameElement, 'dom-update-highlight'); + } } } @@ -1440,8 +1525,9 @@ lastIndexAfterEntity = i + 1; } } - if (result) + if (result) { result += text.substring(lastIndexAfterEntity); + } return {text: result || text, entityRanges: entityRanges}; } @@ -1491,15 +1577,18 @@ UI.highlightRangesWithStyleClass(textNodeElement, result.entityRanges, 'webkit-html-entity-value'); titleDOM.createTextChild('\u200B'); this._buildTagDOM(titleDOM, tagName, true, false, updateRecord); - if (updateRecord && updateRecord.hasChangedChildren()) + if (updateRecord && updateRecord.hasChangedChildren()) { UI.runCSSAnimationOnce(textNodeElement, 'dom-update-highlight'); - if (updateRecord && updateRecord.isCharDataModified()) + } + if (updateRecord && updateRecord.isCharDataModified()) { UI.runCSSAnimationOnce(textNodeElement, 'dom-update-highlight'); + } break; } - if (this.treeOutline.isXMLMimeType || !Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName)) + if (this.treeOutline.isXMLMimeType || !Elements.ElementsTreeElement.ForbiddenClosingTagElements.has(tagName)) { this._buildTagDOM(titleDOM, tagName, true, false, updateRecord); + } break; case Node.TEXT_NODE: @@ -1524,8 +1613,9 @@ textNodeElement.textContent = result.text; UI.highlightRangesWithStyleClass(textNodeElement, result.entityRanges, 'webkit-html-entity-value'); titleDOM.createTextChild('"'); - if (updateRecord && updateRecord.isCharDataModified()) + if (updateRecord && updateRecord.isCharDataModified()) { UI.runCSSAnimationOnce(textNodeElement, 'dom-update-highlight'); + } } break; @@ -1539,14 +1629,16 @@ docTypeElement.createTextChild('<!doctype ' + node.nodeName()); if (node.publicId) { docTypeElement.createTextChild(' PUBLIC "' + node.publicId + '"'); - if (node.systemId) + if (node.systemId) { docTypeElement.createTextChild(' "' + node.systemId + '"'); + } } else if (node.systemId) { docTypeElement.createTextChild(' SYSTEM "' + node.systemId + '"'); } - if (node.internalSubset) + if (node.internalSubset) { docTypeElement.createTextChild(' [' + node.internalSubset + ']'); + } docTypeElement.createTextChild('>'); break; @@ -1576,14 +1668,17 @@ } remove() { - if (this._node.pseudoType()) + if (this._node.pseudoType()) { return; + } const parentElement = this.parent; - if (!parentElement) + if (!parentElement) { return; + } - if (!this._node.parentNode || this._node.parentNode.nodeType() === Node.DOCUMENT_NODE) + if (!this._node.parentNode || this._node.parentNode.nodeType() === Node.DOCUMENT_NODE) { return; + } this._node.removeNode(); } @@ -1597,15 +1692,17 @@ return; } - if (startEditing === false) + if (startEditing === false) { return; + } /** * @param {?Protocol.Error} error */ function selectNode(error) { - if (callback) + if (callback) { callback(!error); + } } /** @@ -1613,13 +1710,15 @@ * @param {string} value */ function commitChange(initialValue, value) { - if (initialValue !== value) + if (initialValue !== value) { node.setOuterHTML(value, selectNode); + } } function disposeCallback() { - if (callback) + if (callback) { callback(false); + } } const node = this._node; @@ -1646,20 +1745,25 @@ const node = this._node; const cssModel = node.domModel().cssModel(); const cascade = await cssModel.cachedMatchedCascadeForNode(node); - if (!cascade) + if (!cascade) { return; + } /** @type {!Array<string>} */ const lines = []; for (const style of cascade.nodeStyles().reverse()) { for (const property of style.leadingProperties()) { - if (!property.parsedOk || property.disabled || !property.activeInStyle() || property.implicit) + if (!property.parsedOk || property.disabled || !property.activeInStyle() || property.implicit) { continue; - if (cascade.isInherited(style) && !SDK.cssMetadata().isPropertyInherited(property.name)) + } + if (cascade.isInherited(style) && !SDK.cssMetadata().isPropertyInherited(property.name)) { continue; - if (style.parentRule && style.parentRule.isUserAgent()) + } + if (style.parentRule && style.parentRule.isUserAgent()) { continue; - if (cascade.propertyState(property) !== SDK.CSSMatchedStyles.PropertyState.Active) + } + if (cascade.propertyState(property) !== SDK.CSSMatchedStyles.PropertyState.Active) { continue; + } lines.push(`${property.name}: ${property.value};`); } } @@ -1667,8 +1771,9 @@ } _highlightSearchResults() { - if (!this._searchQuery || !this._searchHighlightsVisible) + if (!this._searchQuery || !this._searchHighlightsVisible) { return; + } this._hideSearchHighlight(); const text = this.listItemElement.textContent; @@ -1682,8 +1787,9 @@ } // Fall back for XPath, etc. matches. - if (!matchRanges.length) + if (!matchRanges.length) { matchRanges.push(new TextUtils.SourceRange(0, text.length)); + } this._highlightResult = []; UI.highlightSearchResults(this.listItemElement, matchRanges, this._highlightResult);
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElementHighlighter.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElementHighlighter.js index ab4d25da..3786f527 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElementHighlighter.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeElementHighlighter.js
@@ -24,8 +24,9 @@ * @param {!Common.Event} event */ _highlightNode(event) { - if (!Common.moduleSetting('highlightNodeOnHoverInOverlay').get()) + if (!Common.moduleSetting('highlightNodeOnHoverInOverlay').get()) { return; + } const domNode = /** @type {!SDK.DOMNode} */ (event.data); @@ -53,8 +54,9 @@ if (this._currentHighlightedElement) { let currentTreeElement = this._currentHighlightedElement; while (currentTreeElement !== this._alreadyExpandedParentElement) { - if (currentTreeElement.expanded) + if (currentTreeElement.expanded) { currentTreeElement.collapse(); + } currentTreeElement = currentTreeElement.parent; } @@ -66,8 +68,9 @@ let deepestExpandedParent = node; const treeElementSymbol = this._treeOutline.treeElementSymbol(); while (deepestExpandedParent && - (!deepestExpandedParent[treeElementSymbol] || !deepestExpandedParent[treeElementSymbol].expanded)) + (!deepestExpandedParent[treeElementSymbol] || !deepestExpandedParent[treeElementSymbol].expanded)) { deepestExpandedParent = deepestExpandedParent.parentNode; + } this._alreadyExpandedParentElement = deepestExpandedParent ? deepestExpandedParent[treeElementSymbol] : this._treeOutline.rootElement(); @@ -76,15 +79,17 @@ this._currentHighlightedElement = treeElement; this._treeOutline.setHoverEffect(treeElement); - if (treeElement) + if (treeElement) { treeElement.reveal(true); + } this._isModifyingTreeOutline = false; } _clearState() { - if (this._isModifyingTreeOutline) + if (this._isModifyingTreeOutline) { return; + } delete this._currentHighlightedElement; delete this._alreadyExpandedParentElement;
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js index fc26b10c..ccfbb84 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsTreeOutline.js
@@ -47,8 +47,9 @@ this._element = this.element; this._element.classList.add('elements-tree-outline', 'source-code'); - if (hideGutter) + if (hideGutter) { this._element.classList.add('elements-hide-gutter'); + } UI.ARIAUtils.setAccessibleName(this._element, Common.UIString('Page DOM')); this._element.addEventListener('focusout', this._onfocusout.bind(this), false); this._element.addEventListener('mousedown', this._onmousedown.bind(this), false); @@ -102,8 +103,9 @@ _onShowHTMLCommentsChange() { const selectedNode = this.selectedDOMNode(); - if (selectedNode && selectedNode.nodeType() === Node.COMMENT_NODE && !this._showHTMLCommentsSetting.get()) + if (selectedNode && selectedNode.nodeType() === Node.COMMENT_NODE && !this._showHTMLCommentsSetting.get()) { this.selectDOMNode(selectedNode.parentNode); + } this.update(); } @@ -141,8 +143,9 @@ */ setVisibleWidth(width) { this._visibleWidth = width; - if (this._multilineEditing) + if (this._multilineEditing) { this._multilineEditing.resize(); + } } /** @@ -151,15 +154,17 @@ _setClipboardData(data) { if (this._clipboardNodeData) { const treeElement = this.findTreeElement(this._clipboardNodeData.node); - if (treeElement) + if (treeElement) { treeElement.setInClipboard(false); + } delete this._clipboardNodeData; } if (data) { const treeElement = this.findTreeElement(data.node); - if (treeElement) + if (treeElement) { treeElement.setInClipboard(true); + } this._clipboardNodeData = data; } } @@ -168,8 +173,9 @@ * @param {!SDK.DOMNode} removedNode */ resetClipboardIfNeeded(removedNode) { - if (this._clipboardNodeData && this._clipboardNodeData.node === removedNode) + if (this._clipboardNodeData && this._clipboardNodeData.node === removedNode) { this._setClipboardData(null); + } } /** @@ -188,16 +194,19 @@ const originalEvent = event['original']; // Don't prevent the normal copy if the user has a selection. - if (originalEvent.target.hasSelection()) + if (originalEvent.target.hasSelection()) { return; + } // Do not interfere with text editing. - if (UI.isEditing()) + if (UI.isEditing()) { return; + } const targetNode = this.selectedDOMNode(); - if (!targetNode) + if (!targetNode) { return; + } originalEvent.clipboardData.clearData(); event.handled = true; @@ -210,8 +219,9 @@ * @param {?SDK.DOMNode} node */ performCopyOrCut(isCut, node) { - if (isCut && (node.isShadowRoot() || node.ancestorUserAgentShadowRoot())) + if (isCut && (node.isShadowRoot() || node.ancestorUserAgentShadowRoot())) { return; + } node.copyNode(); this._setClipboardData({node: node, isCut: isCut}); @@ -222,18 +232,22 @@ * @return {boolean} */ canPaste(targetNode) { - if (targetNode.isShadowRoot() || targetNode.ancestorUserAgentShadowRoot()) + if (targetNode.isShadowRoot() || targetNode.ancestorUserAgentShadowRoot()) { return false; + } - if (!this._clipboardNodeData) + if (!this._clipboardNodeData) { return false; + } const node = this._clipboardNodeData.node; - if (this._clipboardNodeData.isCut && (node === targetNode || node.isAncestor(targetNode))) + if (this._clipboardNodeData.isCut && (node === targetNode || node.isAncestor(targetNode))) { return false; + } - if (targetNode.domModel() !== node.domModel()) + if (targetNode.domModel() !== node.domModel()) { return false; + } return true; } @@ -241,8 +255,9 @@ * @param {!SDK.DOMNode} targetNode */ pasteNode(targetNode) { - if (this.canPaste(targetNode)) + if (this.canPaste(targetNode)) { this._performPaste(targetNode); + } } /** @@ -250,12 +265,14 @@ */ _onPaste(event) { // Do not interfere with text editing. - if (UI.isEditing()) + if (UI.isEditing()) { return; + } const targetNode = this.selectedDOMNode(); - if (!targetNode || !this.canPaste(targetNode)) + if (!targetNode || !this.canPaste(targetNode)) { return; + } event.handled = true; this._performPaste(targetNode); @@ -278,11 +295,13 @@ * @this {Elements.ElementsTreeOutline} */ function expandCallback(error, nodeId) { - if (error) + if (error) { return; + } const pastedNode = targetNode.domModel().nodeForId(nodeId); - if (!pastedNode) + if (!pastedNode) { return; + } this.selectDOMNode(pastedNode); } } @@ -291,19 +310,22 @@ * @param {boolean} visible */ setVisible(visible) { - if (visible === this._visible) + if (visible === this._visible) { return; + } this._visible = visible; if (!this._visible) { this._popoverHelper.hidePopover(); - if (this._multilineEditing) + if (this._multilineEditing) { this._multilineEditing.cancel(); + } return; } this.runPendingUpdates(); - if (this._selectedDOMNode) + if (this._selectedDOMNode) { this._revealAndSelectNode(this._selectedDOMNode, false); + } } get rootDOMNode() { @@ -311,8 +333,9 @@ } set rootDOMNode(x) { - if (this._rootDOMNode === x) + if (this._rootDOMNode === x) { return; + } this._rootDOMNode = x; @@ -349,8 +372,9 @@ // and the select() call would change the selectedDOMNode and reenter this setter. So to // avoid calling _selectedNodeChanged() twice, first check if _selectedDOMNode is the same // node as the one passed in. - if (this._selectedDOMNode === node) + if (this._selectedDOMNode === node) { this._selectedNodeChanged(!!focus); + } } /** @@ -358,19 +382,22 @@ */ editing() { const node = this.selectedDOMNode(); - if (!node) + if (!node) { return false; + } const treeElement = this.findTreeElement(node); - if (!treeElement) + if (!treeElement) { return false; + } return treeElement.isEditing() || false; } update() { const selectedNode = this.selectedDOMNode(); this.removeChildren(); - if (!this.rootDOMNode) + if (!this.rootDOMNode) { return; + } if (this._includeRootDOMNode) { const treeElement = this._createElementTreeElement(this.rootDOMNode); @@ -384,8 +411,9 @@ } } - if (selectedNode) + if (selectedNode) { this._revealAndSelectNode(selectedNode, true); + } } /** @@ -422,12 +450,14 @@ * @return {?UI.TreeElement} */ _lookUpTreeElement(node) { - if (!node) + if (!node) { return null; + } const cachedElement = node[this._treeElementSymbol]; - if (cachedElement) + if (cachedElement) { return cachedElement; + } // Walk up the parent pointers from the desired node const ancestors = []; @@ -435,11 +465,14 @@ for (currentNode = node.parentNode; currentNode; currentNode = currentNode.parentNode) { ancestors.push(currentNode); if (currentNode[this._treeElementSymbol]) // stop climbing as soon as we hit + { break; + } } - if (!currentNode) + if (!currentNode) { return null; + } // Walk down to populate each ancestor's children, to fill in the tree and the cache. for (let i = ancestors.length - 1; i >= 0; --i) { @@ -447,8 +480,9 @@ const treeElement = ancestors[i][this._treeElementSymbol]; if (treeElement) { treeElement.onpopulate(); // fill the cache with the children of treeElement - if (child.index >= treeElement.expandedChildrenLimit()) + if (child.index >= treeElement.expandedChildrenLimit()) { this.setExpandedChildrenLimit(treeElement, child.index + 1); + } } } @@ -461,18 +495,21 @@ */ createTreeElementFor(node) { let treeElement = this.findTreeElement(node); - if (treeElement) + if (treeElement) { return treeElement; - if (!node.parentNode) + } + if (!node.parentNode) { return null; + } treeElement = this.createTreeElementFor(node.parentNode); return treeElement ? this._showChild(treeElement, node) : null; } set suppressRevealAndSelect(x) { - if (this._suppressRevealAndSelect === x) + if (this._suppressRevealAndSelect === x) { return; + } this._suppressRevealAndSelect = x; } @@ -481,16 +518,20 @@ * @param {boolean} omitFocus */ _revealAndSelectNode(node, omitFocus) { - if (this._suppressRevealAndSelect) + if (this._suppressRevealAndSelect) { return; + } - if (!this._includeRootDOMNode && node === this.rootDOMNode && this.rootDOMNode) + if (!this._includeRootDOMNode && node === this.rootDOMNode && this.rootDOMNode) { node = this.rootDOMNode.firstChild; - if (!node) + } + if (!node) { return; + } const treeElement = this.createTreeElementFor(node); - if (!treeElement) + if (!treeElement) { return; + } treeElement.revealAndSelect(omitFocus); } @@ -515,10 +556,11 @@ const elementUnderMouse = this.treeElementFromPoint(x, y); const elementAboveMouse = this.treeElementFromPoint(x, y - 2); let element; - if (elementUnderMouse === elementAboveMouse) + if (elementUnderMouse === elementAboveMouse) { element = elementUnderMouse; - else + } else { element = this.treeElementFromPoint(x, y + 2); + } return element; } @@ -529,10 +571,12 @@ */ _getPopoverRequest(event) { let link = event.target; - while (link && !link[Elements.ElementsTreeElement.HrefSymbol]) + while (link && !link[Elements.ElementsTreeElement.HrefSymbol]) { link = link.parentElementOrShadowHost(); - if (!link) + } + if (!link) { return null; + } return { box: link.boxInWindow(), @@ -542,8 +586,9 @@ const precomputedFeatures = await Components.ImagePreview.loadDimensionsForNode(node); const preview = await Components.ImagePreview.build( node.domModel().target(), link[Elements.ElementsTreeElement.HrefSymbol], true, {precomputedFeatures}); - if (preview) + if (preview) { popover.contentElement.appendChild(preview); + } return !!preview; } }; @@ -559,8 +604,9 @@ _onmousedown(event) { const element = this._treeElementFromEvent(event); - if (!element || element.isEventWithinDisclosureTriangle(event)) + if (!element || element.isEventWithinDisclosureTriangle(event)) { return; + } element.select(); } @@ -569,8 +615,9 @@ * @param {?UI.TreeElement} treeElement */ setHoverEffect(treeElement) { - if (this._previousHoveredElement === treeElement) + if (this._previousHoveredElement === treeElement) { return; + } if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; @@ -585,8 +632,9 @@ _onmousemove(event) { const element = this._treeElementFromEvent(event); - if (element && this._previousHoveredElement === element) + if (element && this._previousHoveredElement === element) { return; + } this.setHoverEffect(element); this._highlightTreeElement( @@ -603,8 +651,9 @@ return; } - if (element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement) + if (element instanceof Elements.ElementsTreeOutline.ShortcutTreeElement) { element.domModel().overlayModel().highlightInOverlay({deferredNode: element.deferredNode()}, 'all', showInfo); + } } _onmouseleave(event) { @@ -613,17 +662,21 @@ } _ondragstart(event) { - if (event.target.hasSelection()) + if (event.target.hasSelection()) { return false; - if (event.target.nodeName === 'A') + } + if (event.target.nodeName === 'A') { return false; + } const treeElement = this._validDragSourceOrTarget(this._treeElementFromEvent(event)); - if (!treeElement) + if (!treeElement) { return false; + } - if (treeElement.node().nodeName() === 'BODY' || treeElement.node().nodeName() === 'HEAD') + if (treeElement.node().nodeName() === 'BODY' || treeElement.node().nodeName() === 'HEAD') { return false; + } event.dataTransfer.setData('text/plain', treeElement.listItemElement.textContent.replace(/\u200b/g, '')); event.dataTransfer.effectAllowed = 'copyMove'; @@ -635,17 +688,20 @@ } _ondragover(event) { - if (!this._treeElementBeingDragged) + if (!this._treeElementBeingDragged) { return false; + } const treeElement = this._validDragSourceOrTarget(this._treeElementFromEvent(event)); - if (!treeElement) + if (!treeElement) { return false; + } let node = treeElement.node(); while (node) { - if (node === this._treeElementBeingDragged._node) + if (node === this._treeElementBeingDragged._node) { return false; + } node = node.parentNode; } @@ -667,16 +723,19 @@ * @return {?Elements.ElementsTreeElement} */ _validDragSourceOrTarget(treeElement) { - if (!treeElement) + if (!treeElement) { return null; + } - if (!(treeElement instanceof Elements.ElementsTreeElement)) + if (!(treeElement instanceof Elements.ElementsTreeElement)) { return null; + } const elementsTreeElement = /** @type {!Elements.ElementsTreeElement} */ (treeElement); const node = elementsTreeElement.node(); - if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE) + if (!node.parentNode || node.parentNode.nodeType() !== Node.ELEMENT_NODE) { return null; + } return elementsTreeElement; } @@ -684,16 +743,18 @@ _ondrop(event) { event.preventDefault(); const treeElement = this._treeElementFromEvent(event); - if (treeElement instanceof Elements.ElementsTreeElement) + if (treeElement instanceof Elements.ElementsTreeElement) { this._doMove(treeElement); + } } /** * @param {!Elements.ElementsTreeElement} treeElement */ _doMove(treeElement) { - if (!this._treeElementBeingDragged) + if (!this._treeElementBeingDragged) { return; + } let parentNode; let anchorNode; @@ -729,8 +790,9 @@ _contextMenuEventFired(event) { const treeElement = this._treeElementFromEvent(event); - if (treeElement instanceof Elements.ElementsTreeElement) + if (treeElement instanceof Elements.ElementsTreeElement) { this.showContextMenu(treeElement, event); + } } /** @@ -738,26 +800,29 @@ * @param {!Event} event */ showContextMenu(treeElement, event) { - if (UI.isEditing()) + if (UI.isEditing()) { return; + } const contextMenu = new UI.ContextMenu(event); const isPseudoElement = !!treeElement.node().pseudoType(); const isTag = treeElement.node().nodeType() === Node.ELEMENT_NODE && !isPseudoElement; let textNode = event.target.enclosingNodeOrSelfWithClass('webkit-html-text-node'); - if (textNode && textNode.classList.contains('bogus')) + if (textNode && textNode.classList.contains('bogus')) { textNode = null; + } const commentNode = event.target.enclosingNodeOrSelfWithClass('webkit-html-comment'); contextMenu.saveSection().appendItem( ls`Store as global variable`, this._saveNodeToTempVariable.bind(this, treeElement.node())); - if (textNode) + if (textNode) { treeElement.populateTextContextMenu(contextMenu, textNode); - else if (isTag) + } else if (isTag) { treeElement.populateTagContextMenu(contextMenu, event); - else if (commentNode) + } else if (commentNode) { treeElement.populateNodeContextMenu(contextMenu); - else if (isPseudoElement) + } else if (isPseudoElement) { treeElement.populateScrollIntoView(contextMenu); + } contextMenu.appendApplicableItems(treeElement.node()); contextMenu.show(); @@ -780,14 +845,17 @@ */ _onKeyDown(event) { const keyboardEvent = /** @type {!KeyboardEvent} */ (event); - if (UI.isEditing()) + if (UI.isEditing()) { return; + } const node = this.selectedDOMNode(); - if (!node) + if (!node) { return; + } const treeElement = node[this._treeElementSymbol]; - if (!treeElement) + if (!treeElement) { return; + } if (UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent) && node.parentNode) { if (keyboardEvent.key === 'ArrowUp' && node.previousSibling) { @@ -811,11 +879,13 @@ */ toggleEditAsHTML(node, startEditing, callback) { const treeElement = node[this._treeElementSymbol]; - if (!treeElement || !treeElement.hasEditableNode()) + if (!treeElement || !treeElement.hasEditableNode()) { return; + } - if (node.pseudoType()) + if (node.pseudoType()) { return; + } const parentNode = node.parentNode; const index = node.index; @@ -828,24 +898,28 @@ * @param {boolean} success */ function editingFinished(success) { - if (callback) + if (callback) { callback(); - if (!success) + } + if (!success) { return; + } // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. this.runPendingUpdates(); const newNode = parentNode ? parentNode.children()[index] || parentNode : null; - if (!newNode) + if (!newNode) { return; + } this.selectDOMNode(newNode, true); if (wasExpanded) { const newTreeItem = this.findTreeElement(newNode); - if (newTreeItem) + if (newTreeItem) { newTreeItem.expand(); + } } } } @@ -857,21 +931,24 @@ * @return {?Elements.ElementsTreeElement} nodeId */ selectNodeAfterEdit(wasExpanded, error, newNode) { - if (error) + if (error) { return null; + } // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date. this.runPendingUpdates(); - if (!newNode) + if (!newNode) { return null; + } this.selectDOMNode(newNode, true); const newTreeItem = this.findTreeElement(newNode); if (wasExpanded) { - if (newTreeItem) + if (newTreeItem) { newTreeItem.expand(); + } } return newTreeItem; } @@ -887,14 +964,16 @@ async toggleHideElement(node) { const pseudoType = node.pseudoType(); const effectiveNode = pseudoType ? node.parentNode : node; - if (!effectiveNode) + if (!effectiveNode) { return; + } const hidden = node.marker('hidden-marker'); const object = await effectiveNode.resolveToObject(''); - if (!object) + if (!object) { return; + } await object.callFunction(toggleClassAndInjectStyleRule, [{value: pseudoType}, {value: !hidden}]); object.release(); @@ -923,14 +1002,17 @@ this.classList.toggle(className, hidden); let localRoot = this; - while (localRoot.parentNode) + while (localRoot.parentNode) { localRoot = localRoot.parentNode; - if (localRoot.nodeType === Node.DOCUMENT_NODE) + } + if (localRoot.nodeType === Node.DOCUMENT_NODE) { localRoot = document.head; + } let style = localRoot.querySelector('style#' + styleTagId); - if (style) + if (style) { return; + } style = document.createElement('style'); style.id = styleTagId; @@ -1007,8 +1089,9 @@ * @return {?Elements.ElementsTreeOutline.UpdateRecord} */ _updateRecordForHighlight(node) { - if (!this._visible) + if (!this._visible) { return null; + } return this._updateRecords.get(node) || null; } @@ -1018,8 +1101,9 @@ _documentUpdated(event) { const domModel = /** @type {!SDK.DOMModel} */ (event.data); this._reset(); - if (domModel.existingDocument()) + if (domModel.existingDocument()) { this.rootDOMNode = domModel.existingDocument(); + } } /** @@ -1047,8 +1131,9 @@ const node = /** @type {!SDK.DOMNode} */ (event.data); this._addUpdateRecord(node).charDataModified(); // Text could be large and force us to render itself as the child in the tree outline. - if (node.parentNode && node.parentNode.firstChild === node.parentNode.lastChild) + if (node.parentNode && node.parentNode.firstChild === node.parentNode.lastChild) { this._addUpdateRecord(node.parentNode).childrenModified(); + } this._updateModifiedNodesSoon(); } @@ -1091,10 +1176,12 @@ } _updateModifiedNodesSoon() { - if (!this._updateRecords.size) + if (!this._updateRecords.size) { return; - if (this._updateModifiedNodesTimeout) + } + if (this._updateModifiedNodesTimeout) { return; + } this._updateModifiedNodesTimeout = setTimeout(this._updateModifiedNodes.bind(this), 50); } @@ -1120,17 +1207,19 @@ this.update(); } else { for (const node of this._updateRecords.keys()) { - if (this._updateRecords.get(node).hasChangedChildren()) + if (this._updateRecords.get(node).hasChangedChildren()) { this._updateModifiedParentNode(node); - else + } else { this._updateModifiedNode(node); + } } } if (hidePanelWhileUpdating) { this._element.classList.remove('hidden'); - if (originalScrollTop) + if (originalScrollTop) { treeOutlineContainerElement.scrollTop = originalScrollTop; + } } this._updateRecords.clear(); @@ -1139,8 +1228,9 @@ _updateModifiedNode(node) { const treeElement = this.findTreeElement(node); - if (treeElement) + if (treeElement) { treeElement.updateTitle(this._updateRecordForHighlight(node)); + } } _updateModifiedParentNode(node) { @@ -1148,8 +1238,9 @@ if (parentTreeElement) { parentTreeElement.setExpandable(this._hasVisibleChildren(node)); parentTreeElement.updateTitle(this._updateRecordForHighlight(node)); - if (parentTreeElement.populated) + if (parentTreeElement.populated) { this._updateChildren(parentTreeElement); + } } } @@ -1158,8 +1249,9 @@ * @returns {!Promise} */ populateTreeElement(treeElement) { - if (treeElement.childCount() || !treeElement.isExpandable()) + if (treeElement.childCount() || !treeElement.isExpandable()) { return Promise.resolve(); + } return new Promise(resolve => { treeElement.node().getChildNodes(() => { @@ -1179,8 +1271,9 @@ const treeElement = new Elements.ElementsTreeElement(node, closingTag); treeElement.setExpandable(!closingTag && this._hasVisibleChildren(node)); if (node.nodeType() === Node.ELEMENT_NODE && node.parentNode && node.parentNode.nodeType() === Node.DOCUMENT_NODE && - !node.parentNode.parentNode) + !node.parentNode.parentNode) { treeElement.setCollapsible(false); + } treeElement.selectable = this._selectEnabled; return treeElement; } @@ -1191,15 +1284,18 @@ * @return {?Elements.ElementsTreeElement} */ _showChild(treeElement, child) { - if (treeElement.isClosingTag()) + if (treeElement.isClosingTag()) { return null; + } const index = this._visibleChildren(treeElement.node()).indexOf(child); - if (index === -1) + if (index === -1) { return null; + } - if (index >= treeElement.expandedChildrenLimit()) + if (index >= treeElement.expandedChildrenLimit()) { this.setExpandedChildrenLimit(treeElement, index + 1); + } return /** @type {!Elements.ElementsTreeElement} */ (treeElement.childAt(index)); } @@ -1211,32 +1307,38 @@ let visibleChildren = Elements.ElementsTreeElement.visibleShadowRoots(node); const contentDocument = node.contentDocument(); - if (contentDocument) + if (contentDocument) { visibleChildren.push(contentDocument); + } const importedDocument = node.importedDocument(); - if (importedDocument) + if (importedDocument) { visibleChildren.push(importedDocument); + } const templateContent = node.templateContent(); - if (templateContent) + if (templateContent) { visibleChildren.push(templateContent); + } const beforePseudoElement = node.beforePseudoElement(); - if (beforePseudoElement) + if (beforePseudoElement) { visibleChildren.push(beforePseudoElement); + } if (node.childNodeCount()) { // Children may be stale when the outline is not wired to receive DOMModel updates. let children = node.children() || []; - if (!this._showHTMLCommentsSetting.get()) + if (!this._showHTMLCommentsSetting.get()) { children = children.filter(n => n.nodeType() !== Node.COMMENT_NODE); + } visibleChildren = visibleChildren.concat(children); } const afterPseudoElement = node.afterPseudoElement(); - if (afterPseudoElement) + if (afterPseudoElement) { visibleChildren.push(afterPseudoElement); + } return visibleChildren; } @@ -1246,22 +1348,30 @@ * @return {boolean} */ _hasVisibleChildren(node) { - if (node.isIframe()) + if (node.isIframe()) { return true; - if (node.isPortal()) + } + if (node.isPortal()) { return true; - if (node.contentDocument()) + } + if (node.contentDocument()) { return true; - if (node.importedDocument()) + } + if (node.importedDocument()) { return true; - if (node.templateContent()) + } + if (node.templateContent()) { return true; - if (Elements.ElementsTreeElement.visibleShadowRoots(node).length) + } + if (Elements.ElementsTreeElement.visibleShadowRoots(node).length) { return true; - if (node.hasPseudoElements()) + } + if (node.hasPseudoElements()) { return true; - if (node.isInsertionPoint()) + } + if (node.isInsertionPoint()) { return true; + } return !!node.childNodeCount() && !Elements.ElementsTreeElement.canShowInlineText(node); } @@ -1296,12 +1406,14 @@ * @param {number} expandedChildrenLimit */ setExpandedChildrenLimit(treeElement, expandedChildrenLimit) { - if (treeElement.expandedChildrenLimit() === expandedChildrenLimit) + if (treeElement.expandedChildrenLimit() === expandedChildrenLimit) { return; + } treeElement.setExpandedChildrenLimit(expandedChildrenLimit); - if (treeElement.treeOutline && !this._treeElementsBeingUpdated.has(treeElement)) + if (treeElement.treeOutline && !this._treeElementsBeingUpdated.has(treeElement)) { this._updateModifiedParentNode(treeElement.node()); + } } /** @@ -1310,8 +1422,9 @@ _updateChildren(treeElement) { if (!treeElement.isExpandable()) { const selectedTreeElement = treeElement.treeOutline.selectedTreeElement; - if (selectedTreeElement && selectedTreeElement.hasAncestor(treeElement)) + if (selectedTreeElement && selectedTreeElement.hasAncestor(treeElement)) { treeElement.select(true); + } treeElement.removeChildren(); return; } @@ -1340,22 +1453,26 @@ * @param {number} targetIndex */ _moveChild(treeElement, child, targetIndex) { - if (treeElement.indexOfChild(child) === targetIndex) + if (treeElement.indexOfChild(child) === targetIndex) { return; + } const wasSelected = child.selected; - if (child.parent) + if (child.parent) { child.parent.removeChild(child); + } treeElement.insertChild(child, targetIndex); - if (wasSelected) + if (wasSelected) { child.select(); + } } /** * @param {!Elements.ElementsTreeElement} treeElement */ _innerUpdateChildren(treeElement) { - if (this._treeElementsBeingUpdated.has(treeElement)) + if (this._treeElementsBeingUpdated.has(treeElement)) { return; + } this._treeElementsBeingUpdated.add(treeElement); @@ -1393,11 +1510,13 @@ } else { // No existing element found, insert a new element. const newElement = this.insertChildElement(treeElement, child, i); - if (this._updateRecordForHighlight(node) && treeElement.expanded) + if (this._updateRecordForHighlight(node) && treeElement.expanded) { Elements.ElementsTreeElement.animateOnDOMUpdate(newElement); + } // If a node was inserted in the middle of existing list dynamically we might need to increase the limit. - if (treeElement.childCount() > treeElement.expandedChildrenLimit()) + if (treeElement.childCount() > treeElement.expandedChildrenLimit()) { this.setExpandedChildrenLimit(treeElement, treeElement.expandedChildrenLimit() + 1); + } } } @@ -1405,8 +1524,9 @@ const expandedChildCount = treeElement.childCount(); if (visibleChildren.length > expandedChildCount) { const targetButtonIndex = expandedChildCount; - if (!treeElement.expandAllButtonElement) + if (!treeElement.expandAllButtonElement) { treeElement.expandAllButtonElement = this._createExpandAllButtonTreeElement(treeElement); + } treeElement.insertChild(treeElement.expandAllButtonElement, targetButtonIndex); treeElement.expandAllButtonElement.button.textContent = Common.UIString('Show All Nodes (%d More)', visibleChildren.length - expandedChildCount); @@ -1416,13 +1536,15 @@ // Insert shortcuts to distrubuted children. if (node.isInsertionPoint()) { - for (const distributedNode of node.distributedNodes()) + for (const distributedNode of node.distributedNodes()) { treeElement.appendChild(new Elements.ElementsTreeOutline.ShortcutTreeElement(distributedNode)); + } } // Insert close tag. - if (node.nodeType() === Node.ELEMENT_NODE && treeElement.isExpandable()) + if (node.nodeType() === Node.ELEMENT_NODE && treeElement.isExpandable()) { this.insertChildElement(treeElement, node, treeElement.childCount(), true); + } this._treeElementsBeingUpdated.delete(treeElement); } @@ -1433,8 +1555,9 @@ _markersChanged(event) { const node = /** @type {!SDK.DOMNode} */ (event.data); const treeElement = node[this._treeElementSymbol]; - if (treeElement) + if (treeElement) { treeElement.updateDecorations(); + } } }; @@ -1483,10 +1606,12 @@ * @param {string} attrName */ attributeModified(attrName) { - if (this._removedAttributes && this._removedAttributes.has(attrName)) + if (this._removedAttributes && this._removedAttributes.has(attrName)) { this._removedAttributes.delete(attrName); - if (!this._modifiedAttributes) + } + if (!this._modifiedAttributes) { this._modifiedAttributes = /** @type {!Set.<string>} */ (new Set()); + } this._modifiedAttributes.add(attrName); } @@ -1494,10 +1619,12 @@ * @param {string} attrName */ attributeRemoved(attrName) { - if (this._modifiedAttributes && this._modifiedAttributes.has(attrName)) + if (this._modifiedAttributes && this._modifiedAttributes.has(attrName)) { this._modifiedAttributes.delete(attrName); - if (!this._removedAttributes) + } + if (!this._removedAttributes) { this._removedAttributes = /** @type {!Set.<string>} */ (new Set()); + } this._removedAttributes.add(attrName); } @@ -1575,12 +1702,13 @@ * @param {function(!Error)} reject */ function renderPromise(resolve, reject) { - if (object instanceof SDK.DOMNode) + if (object instanceof SDK.DOMNode) { onNodeResolved(/** @type {!SDK.DOMNode} */ (object)); - else if (object instanceof SDK.DeferredDOMNode) + } else if (object instanceof SDK.DeferredDOMNode) { (/** @type {!SDK.DeferredDOMNode} */ (object)).resolve(onNodeResolved); - else + } else { reject(new Error('Can\'t reveal not a node.')); + } /** @@ -1593,8 +1721,9 @@ } const treeOutline = new Elements.ElementsTreeOutline(false, true /* selectEnabled */, true /* hideGutter */); treeOutline.rootDOMNode = node; - if (!treeOutline.firstChild().isExpandable()) + if (!treeOutline.firstChild().isExpandable()) { treeOutline._element.classList.add('single-node'); + } treeOutline.setVisible(true); treeOutline.element.treeElementForTest = treeOutline.firstChild(); treeOutline.setShowSelectionOnKeyboardFocus(true, true); @@ -1616,8 +1745,9 @@ this.listItemElement.createChild('div', 'selection fill'); const title = this.listItemElement.createChild('span', 'elements-tree-shortcut-title'); let text = nodeShortcut.nodeName.toLowerCase(); - if (nodeShortcut.nodeType === Node.ELEMENT_NODE) + if (nodeShortcut.nodeType === Node.ELEMENT_NODE) { text = '<' + text + '>'; + } title.textContent = '\u21AA ' + text; const link = Elements.DOMLinkifier.linkifyDeferredNodeReference(nodeShortcut.deferredNode); @@ -1639,8 +1769,9 @@ * @param {boolean} x */ set hovered(x) { - if (this._hovered === x) + if (this._hovered === x) { return; + } this._hovered = x; this.listItemElement.classList.toggle('hovered', x); } @@ -1665,8 +1796,9 @@ * @return {boolean} */ onselect(selectedByUser) { - if (!selectedByUser) + if (!selectedByUser) { return true; + } this._nodeShortcut.deferredNode.highlight(); this._nodeShortcut.deferredNode.resolve(resolved.bind(this)); /**
diff --git a/third_party/blink/renderer/devtools/front_end/elements/EventListenersWidget.js b/third_party/blink/renderer/devtools/front_end/elements/EventListenersWidget.js index 3b861ffc..2f897dd 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/EventListenersWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/EventListenersWidget.js
@@ -64,8 +64,9 @@ */ function addDispatchFilterOption(name, value) { const option = dispatchFilter.createOption(name, value); - if (value === this._dispatchFilterBySetting.get()) + if (value === this._dispatchFilterBySetting.get()) { dispatchFilter.select(option); + } } addDispatchFilterOption.call(this, Common.UIString('All'), Elements.EventListenersWidget.DispatchFilterBy.All); addDispatchFilterOption.call( @@ -150,8 +151,9 @@ if (node.frameId()) { for (let i = 0; i < executionContexts.length; ++i) { const executionContext = executionContexts[i]; - if (executionContext.frameId === node.frameId() && executionContext.isDefault) + if (executionContext.frameId === node.frameId() && executionContext.isDefault) { context = executionContext; + } } } else { context = executionContexts[0];
diff --git a/third_party/blink/renderer/devtools/front_end/elements/InspectElementModeController.js b/third_party/blink/renderer/devtools/front_end/elements/InspectElementModeController.js index 58fe9c5..a2e8462a 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/InspectElementModeController.js +++ b/third_party/blink/renderer/devtools/front_end/elements/InspectElementModeController.js
@@ -47,10 +47,12 @@ this._showDetailedInspectTooltipSetting.addChangeListener(this._showDetailedInspectTooltipChanged.bind(this)); document.addEventListener('keydown', event => { - if (event.keyCode !== UI.KeyboardShortcut.Keys.Esc.code) + if (event.keyCode !== UI.KeyboardShortcut.Keys.Esc.code) { return; - if (!this._isInInspectElementMode()) + } + if (!this._isInInspectElementMode()) { return; + } this._setMode(Protocol.Overlay.InspectMode.None); event.consume(true); }, true); @@ -63,8 +65,9 @@ modelAdded(overlayModel) { // When DevTools are opening in the inspect element mode, the first target comes in // much later than the InspectorFrontendAPI.enterInspectElementMode event. - if (this._mode === Protocol.Overlay.InspectMode.None) + if (this._mode === Protocol.Overlay.InspectMode.None) { return; + } overlayModel.setInspectMode(this._mode, this._showDetailedInspectTooltipSetting.get()); } @@ -101,17 +104,20 @@ * @param {!Protocol.Overlay.InspectMode} mode */ _setMode(mode) { - if (SDK.targetManager.allTargetsSuspended()) + if (SDK.targetManager.allTargetsSuspended()) { return; + } this._mode = mode; - for (const overlayModel of SDK.targetManager.models(SDK.OverlayModel)) + for (const overlayModel of SDK.targetManager.models(SDK.OverlayModel)) { overlayModel.setInspectMode(mode, this._showDetailedInspectTooltipSetting.get()); + } this._toggleSearchAction.setToggled(this._isInInspectElementMode()); } _suspendStateChanged() { - if (!SDK.targetManager.allTargetsSuspended()) + if (!SDK.targetManager.allTargetsSuspended()) { return; + } this._mode = Protocol.Overlay.InspectMode.None; this._toggleSearchAction.setToggled(false); @@ -141,12 +147,14 @@ * @return {boolean} */ handleAction(context, actionId) { - if (!Elements.inspectElementModeController) + if (!Elements.inspectElementModeController) { return false; - if (actionId === 'elements.toggle-element-search') + } + if (actionId === 'elements.toggle-element-search') { Elements.inspectElementModeController._toggleInspectMode(); - else if (actionId === 'elements.capture-area-screenshot') + } else if (actionId === 'elements.capture-area-screenshot') { Elements.inspectElementModeController._captureScreenshotMode(); + } return true; } };
diff --git a/third_party/blink/renderer/devtools/front_end/elements/MetricsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/elements/MetricsSidebarPane.js index 0b7eb87..e6a08e0 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/MetricsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/elements/MetricsSidebarPane.js
@@ -46,8 +46,9 @@ doUpdate() { // "style" attribute might have changed. Update metrics unless they are being edited // (if a CSS property is added, a StyleSheetChanged event is dispatched). - if (this._isEditingMetrics) + if (this._isEditingMetrics) { return Promise.resolve(); + } // FIXME: avoid updates of a collapsed pane. const node = this.node(); @@ -62,8 +63,9 @@ * @this {Elements.MetricsSidebarPane} */ function callback(style) { - if (!style || this.node() !== node) + if (!style || this.node() !== node) { return; + } this._updateMetrics(style); } /** @@ -71,8 +73,9 @@ * @this {Elements.MetricsSidebarPane} */ function inlineStyleCallback(inlineStyleResult) { - if (inlineStyleResult && this.node() === node) + if (inlineStyleResult && this.node() === node) { this._inlineStyle = inlineStyleResult.inlineStyle; + } } const promises = [ @@ -119,8 +122,9 @@ _highlightDOMNode(showHighlight, mode, event) { event.consume(); if (showHighlight && this.node()) { - if (this._highlightMode === mode) + if (this._highlightMode === mode) { return; + } this._highlightMode = mode; this.node().highlight(mode); } else { @@ -130,10 +134,11 @@ for (let i = 0; this._boxElements && i < this._boxElements.length; ++i) { const element = this._boxElements[i]; - if (!this.node() || mode === 'all' || element._name === mode) + if (!this.node() || mode === 'all' || element._name === mode) { element.style.backgroundColor = element._backgroundColor; - else + } else { element.style.backgroundColor = ''; + } } } @@ -156,10 +161,11 @@ function createBoxPartElement(style, name, side, suffix) { const propertyName = (name !== 'position' ? name + '-' : '') + side + suffix; let value = style.get(propertyName); - if (value === '' || (name !== 'position' && value === '0px')) + if (value === '' || (name !== 'position' && value === '0px')) { value = '\u2012'; - else if (name === 'position' && value === 'auto') + } else if (name === 'position' && value === 'auto') { value = '\u2012'; + } value = value.replace(/px$/, ''); value = Number.toFixedIfFloating(value); @@ -240,12 +246,15 @@ for (let i = 0; i < boxes.length; ++i) { const name = boxes[i]; - if (name === 'margin' && noMarginDisplayType[style.get('display')]) + if (name === 'margin' && noMarginDisplayType[style.get('display')]) { continue; - if (name === 'padding' && noPaddingDisplayType[style.get('display')]) + } + if (name === 'padding' && noPaddingDisplayType[style.get('display')]) { continue; - if (name === 'position' && noPositionType[style.get('position')]) + } + if (name === 'position' && noPositionType[style.get('position')]) { continue; + } const boxElement = createElement('div'); boxElement.className = name; @@ -282,8 +291,9 @@ boxElement.appendChild(createElement('br')); boxElement.appendChild(createBoxPartElement.call(this, style, name, 'left', suffix)); - if (previousBox) + if (previousBox) { boxElement.appendChild(previousBox); + } boxElement.appendChild(createBoxPartElement.call(this, style, name, 'right', suffix)); boxElement.appendChild(createElement('br')); @@ -309,8 +319,9 @@ * @param {!Map.<string, string>} computedStyle */ startEditing(targetElement, box, styleProperty, computedStyle) { - if (UI.isBeingEdited(targetElement)) + if (UI.isBeingEdited(targetElement)) { return; + } const context = {box: box, styleProperty: styleProperty, computedStyle: computedStyle}; const boundKeyDown = this._handleKeyDown.bind(this, context, styleProperty); @@ -345,8 +356,9 @@ * @return {string} */ function customNumberHandler(prefix, number, suffix) { - if (styleProperty !== 'margin' && number < 0) + if (styleProperty !== 'margin' && number < 0) { number = 0; + } return prefix + number + suffix; } @@ -365,8 +377,9 @@ if (!this.originalPropertyData) { // An added property, remove the last property in the style. const pastLastSourcePropertyIndex = this._inlineStyle.pastLastSourcePropertyIndex(); - if (pastLastSourcePropertyIndex) + if (pastLastSourcePropertyIndex) { this._inlineStyle.allProperties()[pastLastSourcePropertyIndex - 1].setText('', false); + } } else { this._inlineStyle.allProperties()[this.originalPropertyData.index].setText( this.originalPropertyData.propertyText, false); @@ -382,18 +395,21 @@ return this.editingCancelled(element, context); // nothing changed, so cancel } - if (commitEditor && userInput === previousContent) - return this.editingCancelled(element, context); // nothing changed, so cancel + if (commitEditor && userInput === previousContent) { + return this.editingCancelled(element, context); + } // nothing changed, so cancel - if (context.box !== 'position' && (!userInput || userInput === '\u2012')) + if (context.box !== 'position' && (!userInput || userInput === '\u2012')) { userInput = '0px'; - else if (context.box === 'position' && (!userInput || userInput === '\u2012')) + } else if (context.box === 'position' && (!userInput || userInput === '\u2012')) { userInput = 'auto'; + } userInput = userInput.toLowerCase(); // Append a "px" unit if the user input was just a number. - if (/^\d+$/.test(userInput)) + if (/^\d+$/.test(userInput)) { userInput += 'px'; + } const styleProperty = context.styleProperty; const computedStyle = context.computedStyle; @@ -408,12 +424,14 @@ const borderBox = this._getBox(computedStyle, 'border'); const paddingBox = this._getBox(computedStyle, 'padding'); let userValuePx = Number(userInput.replace(/px$/, '')); - if (isNaN(userValuePx)) + if (isNaN(userValuePx)) { return; - if (styleProperty === 'width') + } + if (styleProperty === 'width') { userValuePx += borderBox.left + borderBox.right + paddingBox.left + paddingBox.right; - else + } else { userValuePx += borderBox.top + borderBox.bottom + paddingBox.top + paddingBox.bottom; + } userInput = userValuePx + 'px'; } @@ -423,8 +441,9 @@ const allProperties = this._inlineStyle.allProperties(); for (let i = 0; i < allProperties.length; ++i) { const property = allProperties[i]; - if (property.name !== context.styleProperty || !property.activeInStyle()) + if (property.name !== context.styleProperty || !property.activeInStyle()) { continue; + } this.previousPropertyDataCandidate = property; property.setValue(userInput, commitEditor, true, callback.bind(this)); @@ -438,16 +457,20 @@ * @this {Elements.MetricsSidebarPane} */ function callback(success) { - if (!success) + if (!success) { return; - if (!('originalPropertyData' in this)) + } + if (!('originalPropertyData' in this)) { this.originalPropertyData = this.previousPropertyDataCandidate; + } - if (typeof this._highlightMode !== 'undefined') + if (typeof this._highlightMode !== 'undefined') { this.node().highlight(this._highlightMode); + } - if (commitEditor) + if (commitEditor) { this.update(); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/PlatformFontsWidget.js b/third_party/blink/renderer/devtools/front_end/elements/PlatformFontsWidget.js index 3bec7d9c..78ffdc0f 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/PlatformFontsWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/PlatformFontsWidget.js
@@ -57,8 +57,9 @@ doUpdate() { const cssModel = this._sharedModel.cssModel(); const node = this._sharedModel.node(); - if (!node || !cssModel) + if (!node || !cssModel) { return Promise.resolve(); + } return cssModel.platformFontsPromise(node.id).then(this._refreshUI.bind(this, node)); } @@ -68,15 +69,17 @@ * @param {?Array.<!Protocol.CSS.PlatformFontUsage>} platformFonts */ _refreshUI(node, platformFonts) { - if (this._sharedModel.node() !== node) + if (this._sharedModel.node() !== node) { return; + } this._fontStatsSection.removeChildren(); const isEmptySection = !platformFonts || !platformFonts.length; this._sectionTitle.classList.toggle('hidden', isEmptySection); - if (isEmptySection) + if (isEmptySection) { return; + } platformFonts.sort(function(a, b) { return b.glyphCount - a.glyphCount;
diff --git a/third_party/blink/renderer/devtools/front_end/elements/PropertiesWidget.js b/third_party/blink/renderer/devtools/front_end/elements/PropertiesWidget.js index 199c94ca0..b6c3e4e 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/PropertiesWidget.js +++ b/third_party/blink/renderer/devtools/front_end/elements/PropertiesWidget.js
@@ -73,34 +73,39 @@ this._lastRequestedNode = this._node; const object = await this._node.resolveToObject(Elements.PropertiesWidget._objectGroupName); - if (!object) + if (!object) { return; + } const result = await object.callFunction(protoList); object.release(); - if (!result.object || result.wasThrown) + if (!result.object || result.wasThrown) { return; + } const propertiesResult = await result.object.getOwnProperties(false /* generatePreview */); result.object.release(); - if (!propertiesResult || !propertiesResult.properties) + if (!propertiesResult || !propertiesResult.properties) { return; + } const properties = propertiesResult.properties; const expanded = []; const sections = this.sections || []; - for (let i = 0; i < sections.length; ++i) + for (let i = 0; i < sections.length; ++i) { expanded.push(sections[i].expanded); + } this.contentElement.removeChildren(); this.sections = []; // Get array of property user-friendly names. for (let i = 0; i < properties.length; ++i) { - if (!parseInt(properties[i].name, 10)) + if (!parseInt(properties[i].name, 10)) { continue; + } const property = properties[i].value; let title = property.description; title = title.replace(/Prototype$/, ''); @@ -108,8 +113,9 @@ section.element.classList.add('properties-widget-section'); this.sections.push(section); this.contentElement.appendChild(section.element); - if (expanded[this.sections.length - 1]) + if (expanded[this.sections.length - 1]) { section.expand(); + } section.addEventListener(UI.TreeOutline.Events.ElementExpanded, this._propertyExpanded, this); } @@ -134,20 +140,23 @@ */ _propertyExpanded(event) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.DOMPropertiesExpanded); - for (const section of this.sections) + for (const section of this.sections) { section.removeEventListener(UI.TreeOutline.Events.ElementExpanded, this._propertyExpanded, this); + } } /** * @param {!Common.Event} event */ _onNodeChange(event) { - if (!this._node) + if (!this._node) { return; + } const data = event.data; const node = /** @type {!SDK.DOMNode} */ (data instanceof SDK.DOMNode ? data : data.node); - if (this._node !== node) + if (this._node !== node) { return; + } this.update(); } };
diff --git a/third_party/blink/renderer/devtools/front_end/elements/StylePropertyHighlighter.js b/third_party/blink/renderer/devtools/front_end/elements/StylePropertyHighlighter.js index 17839b4..91092f64 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/StylePropertyHighlighter.js +++ b/third_party/blink/renderer/devtools/front_end/elements/StylePropertyHighlighter.js
@@ -19,8 +19,9 @@ // Expand all shorthands. for (const section of this._styleSidebarPane.allSections()) { for (let treeElement = section.propertiesTreeOutline.firstChild(); treeElement; - treeElement = treeElement.nextSibling) + treeElement = treeElement.nextSibling) { treeElement.onpopulate(); + } } let highlightTreeElement = null; for (const section of this._styleSidebarPane.allSections()) { @@ -32,12 +33,14 @@ } treeElement = treeElement.traverseNextTreeElement(false, null, true); } - if (highlightTreeElement) + if (highlightTreeElement) { break; + } } - if (!highlightTreeElement) + if (!highlightTreeElement) { return; + } highlightTreeElement.parent.expand(); highlightTreeElement.listItemElement.scrollIntoViewIfNeeded();
diff --git a/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js b/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js index aa58fcf..97fe7d8 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js +++ b/third_party/blink/renderer/devtools/front_end/elements/StylePropertyTreeElement.js
@@ -25,8 +25,9 @@ this.isShorthand = isShorthand; this._applyStyleThrottler = new Common.Throttler(0); this._newProperty = newProperty; - if (this._newProperty) + if (this._newProperty) { this.listItemElement.textContent = ''; + } this._expandedDueToFilter = false; this.valueElement = null; this.nameElement = null; @@ -71,8 +72,9 @@ * @param {boolean} x */ setOverloaded(x) { - if (x === this._overloaded) + if (x === this._overloaded) { return; + } this._overloaded = x; this._updateState(); } @@ -95,12 +97,14 @@ this.onpopulate(); let hasMatchingChildren = false; - for (let i = 0; i < this.childCount(); ++i) + for (let i = 0; i < this.childCount(); ++i) { hasMatchingChildren |= this.childAt(i)._updateFilter(); + } if (!regex) { - if (this._expandedDueToFilter) + if (this._expandedDueToFilter) { this.collapse(); + } this._expandedDueToFilter = false; } else if (hasMatchingChildren && !this.expanded) { this.expand(); @@ -119,8 +123,9 @@ _processColor(text) { // We can be called with valid non-color values of |text| (like 'none' from border style) const color = Common.Color.parse(text); - if (!color) + if (!color) { return createTextNode(text); + } if (!this._editable()) { const swatch = InlineEditor.ColorSwatch.create(); @@ -142,8 +147,9 @@ */ _processVar(text) { const computedValue = this._matchedStyles.computeValue(this._style, text); - if (!computedValue) + if (!computedValue) { return createTextNode(text); + } const color = Common.Color.parse(computedValue); if (!color) { const node = createElement('span'); @@ -172,8 +178,9 @@ async _addColorContrastInfo(swatch) { const swatchPopoverHelper = this._parentPane.swatchPopoverHelper(); const swatchIcon = new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, swatch); - if (this.property.name !== 'color' || !this._parentPane.cssModel() || !this.node()) + if (this.property.name !== 'color' || !this._parentPane.cssModel() || !this.node()) { return; + } const cssModel = this._parentPane.cssModel(); const contrastInfo = new ColorPicker.ContrastInfo(await cssModel.backgroundColorsPromise(this.node().id)); swatchIcon.setContrastInfo(contrastInfo); @@ -191,8 +198,9 @@ * @return {!Node} */ _processBezier(text) { - if (!this._editable() || !UI.Geometry.CubicBezier.parse(text)) + if (!this._editable() || !UI.Geometry.CubicBezier.parse(text)) { return createTextNode(text); + } const swatchPopoverHelper = this._parentPane.swatchPopoverHelper(); const swatch = InlineEditor.BezierSwatch.create(); swatch.setBezierText(text); @@ -206,27 +214,32 @@ * @return {!Node} */ _processShadow(propertyValue, propertyName) { - if (!this._editable()) + if (!this._editable()) { return createTextNode(propertyValue); + } let shadows; - if (propertyName === 'text-shadow') + if (propertyName === 'text-shadow') { shadows = InlineEditor.CSSShadowModel.parseTextShadow(propertyValue); - else + } else { shadows = InlineEditor.CSSShadowModel.parseBoxShadow(propertyValue); - if (!shadows.length) + } + if (!shadows.length) { return createTextNode(propertyValue); + } const container = createDocumentFragment(); const swatchPopoverHelper = this._parentPane.swatchPopoverHelper(); for (let i = 0; i < shadows.length; i++) { - if (i !== 0) - container.appendChild(createTextNode(', ')); // Add back commas and spaces between each shadow. + if (i !== 0) { + container.appendChild(createTextNode(', ')); + } // Add back commas and spaces between each shadow. // TODO(flandy): editing the property value should use the original value with all spaces. const cssShadowSwatch = InlineEditor.CSSShadowSwatch.create(); cssShadowSwatch.setCSSShadow(shadows[i]); new Elements.ShadowSwatchPopoverHelper(this, swatchPopoverHelper, cssShadowSwatch); const colorSwatch = cssShadowSwatch.colorSwatch(); - if (colorSwatch) + if (colorSwatch) { new Elements.ColorSwatchPopoverIcon(this, swatchPopoverHelper, colorSwatch); + } container.appendChild(cssShadowSwatch); } return container; @@ -239,8 +252,9 @@ */ _processGrid(propertyValue, propertyName) { const splitResult = TextUtils.TextUtils.splitStringByRegexes(propertyValue, [SDK.CSSMetadata.GridAreaRowRegex]); - if (splitResult.length <= 1) + if (splitResult.length <= 1) { return createTextNode(propertyValue); + } const indent = Common.moduleSetting('textEditorIndent').get(); const container = createDocumentFragment(); @@ -253,35 +267,41 @@ } _updateState() { - if (!this.listItemElement) + if (!this.listItemElement) { return; + } - if (this._style.isPropertyImplicit(this.name)) + if (this._style.isPropertyImplicit(this.name)) { this.listItemElement.classList.add('implicit'); - else + } else { this.listItemElement.classList.remove('implicit'); + } const hasIgnorableError = !this.property.parsedOk && Elements.StylesSidebarPane.ignoreErrorsForProperty(this.property); - if (hasIgnorableError) + if (hasIgnorableError) { this.listItemElement.classList.add('has-ignorable-error'); - else + } else { this.listItemElement.classList.remove('has-ignorable-error'); + } - if (this.inherited()) + if (this.inherited()) { this.listItemElement.classList.add('inherited'); - else + } else { this.listItemElement.classList.remove('inherited'); + } - if (this.overloaded()) + if (this.overloaded()) { this.listItemElement.classList.add('overloaded'); - else + } else { this.listItemElement.classList.remove('overloaded'); + } - if (this.property.disabled) + if (this.property.disabled) { this.listItemElement.classList.add('disabled'); - else + } else { this.listItemElement.classList.remove('disabled'); + } } /** @@ -307,8 +327,9 @@ _updatePane() { const section = this.section(); - if (section) + if (section) { section.refreshUpdate(this); + } } /** @@ -316,15 +337,17 @@ */ async _toggleDisabled(disabled) { const oldStyleRange = this._style.range; - if (!oldStyleRange) + if (!oldStyleRange) { return; + } this._parentPane.setUserOperation(true); const success = await this.property.setDisabled(disabled); this._parentPane.setUserOperation(false); - if (!success) + if (!success) { return; + } this._matchedStyles.resetActiveProperties(); this._updatePane(); this.styleTextAppliedForTest(); @@ -336,8 +359,9 @@ */ async onpopulate() { // Only populate once and if this property is a shorthand. - if (this.childCount() || !this.isShorthand) + if (this.childCount() || !this.isShorthand) { return; + } const longhandProperties = this._style.longhandProperties(this.name); for (let i = 0; i < longhandProperties.length; ++i) { @@ -365,13 +389,15 @@ this.updateTitle(); this.listItemElement.addEventListener('mousedown', event => { - if (event.which === 1) + if (event.which === 1) { this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol] = this; + } }, false); this.listItemElement.addEventListener('mouseup', this._mouseUp.bind(this)); this.listItemElement.addEventListener('click', event => { - if (!event.target.hasSelection() && event.target !== this.listItemElement) + if (!event.target.hasSelection() && event.target !== this.listItemElement) { event.consume(true); + } }); } @@ -390,18 +416,21 @@ } _updateExpandElement() { - if (!this._expandElement) + if (!this._expandElement) { return; - if (this.expanded) + } + if (this.expanded) { this._expandElement.setIconType('smallicon-triangle-down'); - else + } else { this._expandElement.setIconType('smallicon-triangle-right'); + } } updateTitleIfComputedValueChanged() { const computedValue = this._matchedStyles.computeValue(this.property.ownerStyle, this.property.value); - if (computedValue === this._lastComputedValue) + if (computedValue === this._lastComputedValue) { return; + } this._lastComputedValue = computedValue; this._innerUpdateTitle(); } @@ -413,10 +442,11 @@ _innerUpdateTitle() { this._updateState(); - if (this.isExpandable()) + if (this.isExpandable()) { this._expandElement = UI.Icon.create('smallicon-triangle-right', 'expand-icon'); - else + } else { this._expandElement = null; + } const propertyRenderer = new Elements.StylesSidebarPropertyRenderer(this._style.parentRule, this.node(), this.name, this.value); @@ -430,11 +460,13 @@ this.listItemElement.removeChildren(); this.nameElement = propertyRenderer.renderName(); - if (this.property.name.startsWith('--')) + if (this.property.name.startsWith('--')) { this.nameElement.title = this._matchedStyles.computeCSSVariable(this._style, this.property.name) || ''; + } this.valueElement = propertyRenderer.renderValue(); - if (!this.treeOutline) + if (!this.treeOutline) { return; + } const indent = Common.moduleSetting('textEditorIndent').get(); this.listItemElement.createChild('span', 'styles-clipboard-only') @@ -443,12 +475,14 @@ const lineBreakValue = this.valueElement.firstElementChild && this.valueElement.firstElementChild.tagName === 'BR'; const separator = lineBreakValue ? ':' : ': '; this.listItemElement.createChild('span', 'styles-name-value-separator').textContent = separator; - if (this._expandElement) + if (this._expandElement) { this.listItemElement.appendChild(this._expandElement); + } this.listItemElement.appendChild(this.valueElement); this.listItemElement.createTextChild(';'); - if (this.property.disabled) + if (this.property.disabled) { this.listItemElement.createChild('span', 'styles-clipboard-only').createTextChild(' */'); + } if (!this.property.parsedOk) { // Avoid having longhands under an invalid shorthand. @@ -458,8 +492,9 @@ this.listItemElement.insertBefore( Elements.StylesSidebarPane.createExclamationMark(this.property), this.listItemElement.firstChild); } - if (!this.property.activeInStyle()) + if (!this.property.activeInStyle()) { this.listItemElement.classList.add('inactive'); + } this._updateFilter(); if (this.property.parsedOk && this.section() && this.parent.root) { @@ -484,17 +519,21 @@ _mouseUp(event) { const activeTreeElement = this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol]; this._parentPane[Elements.StylePropertyTreeElement.ActiveSymbol] = null; - if (activeTreeElement !== this) + if (activeTreeElement !== this) { return; - if (this.listItemElement.hasSelection()) + } + if (this.listItemElement.hasSelection()) { return; - if (UI.isBeingEdited(/** @type {!Node} */ (event.target))) + } + if (UI.isBeingEdited(/** @type {!Node} */ (event.target))) { return; + } event.consume(true); - if (event.target === this.listItemElement) + if (event.target === this.listItemElement) { return; + } if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && this.section().navigable) { this._navigateToSource(/** @type {!Element} */ (event.target)); @@ -529,12 +568,14 @@ * @param {boolean=} omitFocus */ _navigateToSource(element, omitFocus) { - if (!this.section().navigable) + if (!this.section().navigable) { return; + } const propertyNameClicked = element === this.nameElement; const uiLocation = Bindings.cssWorkspaceBinding.propertyUILocation(this.property, propertyNameClicked); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation, omitFocus); + } } /** @@ -542,30 +583,36 @@ */ startEditing(selectElement) { // FIXME: we don't allow editing of longhand properties under a shorthand right now. - if (this.parent.isShorthand) + if (this.parent.isShorthand) { return; + } - if (this._expandElement && selectElement === this._expandElement) + if (this._expandElement && selectElement === this._expandElement) { return; + } const section = this.section(); - if (section && !section.editable) + if (section && !section.editable) { return; + } if (selectElement) { selectElement = selectElement.enclosingNodeOrSelfWithClass('webkit-css-property') || selectElement.enclosingNodeOrSelfWithClass('value'); } - if (!selectElement) + if (!selectElement) { selectElement = this.nameElement; + } - if (UI.isBeingEdited(selectElement)) + if (UI.isBeingEdited(selectElement)) { return; + } const isEditingName = selectElement === this.nameElement; if (!isEditingName) { - if (SDK.cssMetadata().isGridAreaDefiningProperty(this.name)) + if (SDK.cssMetadata().isGridAreaDefiningProperty(this.name)) { this.valueElement.textContent = restoreGridIndents(this.value); + } this.valueElement.textContent = restoreURLs(this.valueElement.textContent, this.value); } @@ -585,13 +632,15 @@ function restoreURLs(fieldValue, modelValue) { const urlRegex = /\b(url\([^)]*\))/g; const splitFieldValue = fieldValue.split(urlRegex); - if (splitFieldValue.length === 1) + if (splitFieldValue.length === 1) { return fieldValue; + } const modelUrlRegex = new RegExp(urlRegex); for (let i = 1; i < splitFieldValue.length; i += 2) { const match = modelUrlRegex.exec(modelValue); - if (match) + if (match) { splitFieldValue[i] = match[0]; + } } return splitFieldValue.join(''); } @@ -609,8 +658,9 @@ // Lie about our children to prevent expanding on double click and to collapse shorthands. this.setExpandable(false); - if (selectElement.parentElement) + if (selectElement.parentElement) { selectElement.parentElement.classList.add('child-editing'); + } selectElement.textContent = selectElement.textContent; // remove color swatch and the like /** @@ -620,11 +670,13 @@ */ function pasteHandler(context, event) { const data = event.clipboardData.getData('Text'); - if (!data) + if (!data) { return; + } const colonIdx = data.indexOf(':'); - if (colonIdx < 0) + if (colonIdx < 0) { return; + } const name = data.substring(0, colonIdx).trim(); const value = data.substring(colonIdx + 1).trim(); @@ -651,16 +703,18 @@ */ function blurListener(context, event) { let text = event.target.textContent; - if (!context.isEditingName) + if (!context.isEditingName) { text = this.value || text; + } this._editingCommitted(text, context, ''); } this._originalPropertyText = this.property.propertyText; this._parentPane.setEditingStyle(true, this); - if (selectElement.parentElement) + if (selectElement.parentElement) { selectElement.parentElement.scrollIntoViewIfNeeded(false); + } this._prompt = new Elements.StylesSidebarPane.CSSPropertyPrompt(this, isEditingName); this._prompt.setAutocompletionTimeout(0); @@ -685,8 +739,9 @@ * @param {!Event} event */ _editingNameValueKeyDown(context, event) { - if (event.handled) + if (event.handled) { return; + } let result; @@ -738,12 +793,14 @@ let openQuote = ''; for (let i = 0; i < cursorPosition; ++i) { const ch = text[i]; - if (ch === '\\' && openQuote !== '') - ++i; // skip next character inside string - else if (!openQuote && (ch === '"' || ch === '\'')) + if (ch === '\\' && openQuote !== '') { + ++i; + } // skip next character inside string + else if (!openQuote && (ch === '"' || ch === '\'')) { openQuote = ch; - else if (openQuote === ch) + } else if (openQuote === ch) { openQuote = ''; + } } return !openQuote; } @@ -766,8 +823,9 @@ * @return {!Promise} */ async _applyFreeFlowStyleTextEdit(context) { - if (!this._prompt || !this._parentPane.node()) + if (!this._prompt || !this._parentPane.node()) { return; + } const enteredText = this._prompt.text(); if (context.isEditingName && enteredText.includes(':')) { @@ -776,23 +834,27 @@ } const valueText = this._prompt.textWithCurrentSuggestion(); - if (valueText.includes(';')) + if (valueText.includes(';')) { return; + } // Prevent destructive side-effects during live-edit. crbug.com/433889 const isPseudo = !!this._parentPane.node().pseudoType(); if (isPseudo) { - if (this.name.toLowerCase() === 'content') + if (this.name.toLowerCase() === 'content') { return; + } const lowerValueText = valueText.trim().toLowerCase(); - if (lowerValueText.startsWith('content:') || lowerValueText === 'display: none') + if (lowerValueText.startsWith('content:') || lowerValueText === 'display: none') { return; + } } if (context.isEditingName) { - if (valueText.includes(':')) + if (valueText.includes(':')) { await this.applyStyleText(valueText, false); - else if (this._hasBeenEditedIncrementally) + } else if (this._hasBeenEditedIncrementally) { await this._applyOriginalStyle(context); + } } else { await this.applyStyleText(`${this.nameElement.textContent}: ${valueText}`, false); } @@ -811,12 +873,14 @@ */ editingEnded(context) { this.setExpandable(context.hasChildren); - if (context.expanded) + if (context.expanded) { this.expand(); + } const editedElement = context.isEditingName ? this.nameElement : this.valueElement; // The proxyElement has been deleted, no need to remove listener. - if (editedElement.parentElement) + if (editedElement.parentElement) { editedElement.parentElement.classList.remove('child-editing'); + } this._parentPane.setEditingStyle(false); } @@ -828,10 +892,11 @@ editingCancelled(element, context) { this._removePrompt(); - if (this._hasBeenEditedIncrementally) + if (this._hasBeenEditedIncrementally) { this._applyOriginalStyle(context); - else if (this._newProperty) + } else if (this._newProperty) { this.treeOutline.removeChild(this); + } this.updateTitle(); // This should happen last, as it clears the info necessary to restore the property value after [Page]Up/Down changes. @@ -851,9 +916,9 @@ */ _findSibling(moveDirection) { let target = this; - do + do { target = (moveDirection === 'forward' ? target.nextSibling : target.previousSibling); - while (target && target.inherited()); + } while (target && target.inherited()); return target; } @@ -884,10 +949,11 @@ moveDirection === 'backward' && isEditingName) { moveTo = moveTo._findSibling(moveDirection); if (!moveTo) { - if (moveDirection === 'forward' && (!this._newProperty || userInput)) + if (moveDirection === 'forward' && (!this._newProperty || userInput)) { createNewProperty = true; - else if (moveDirection === 'backward') + } else if (moveDirection === 'backward') { moveToSelector = true; + } } } @@ -905,20 +971,23 @@ } else if (blankInput || (this._newProperty && this.valueElement.textContent.isWhitespace())) { propertyText = ''; } else { - if (isEditingName) + if (isEditingName) { propertyText = userInput + ': ' + this.property.value; - else + } else { propertyText = this.property.name + ': ' + userInput; + } } await this.applyStyleText(propertyText, true); moveToNextCallback.call(this, this._newProperty, !blankInput, section); } else { - if (isEditingName) + if (isEditingName) { this.property.name = userInput; - else + } else { this.property.value = userInput; - if (!isDataPasted && !this._newProperty) + } + if (!isDataPasted && !this._newProperty) { this.updateTitle(); + } moveToNextCallback.call(this, this._newProperty, false, section); } @@ -930,8 +999,9 @@ * @this {Elements.StylePropertyTreeElement} */ function moveToNextCallback(alreadyNew, valueChanged, section) { - if (!moveDirection) + if (!moveDirection) { return; + } // User just tabbed through without changes. if (moveTo && moveTo.parent) { @@ -943,8 +1013,9 @@ // Recalculate the new treeElement for the same property we were going to edit next. if (moveTo && !moveTo.parent) { const rootElement = section.propertiesTreeOutline.rootElement(); - if (moveDirection === 'forward' && blankInput && !isEditingName) + if (moveDirection === 'forward' && blankInput && !isEditingName) { --moveToIndex; + } if (moveToIndex >= rootElement.childCount() && !this._newProperty) { createNewProperty = true; } else { @@ -952,8 +1023,9 @@ if (treeElement) { let elementToEdit = !isEditingName || isPropertySplitPaste ? treeElement.nameElement : treeElement.valueElement; - if (alreadyNew && blankInput) + if (alreadyNew && blankInput) { elementToEdit = moveDirection === 'forward' ? treeElement.nameElement : treeElement.valueElement; + } treeElement.startEditing(elementToEdit); return; } else if (!alreadyNew) { @@ -964,8 +1036,9 @@ // Create a new attribute in this section (or move to next editable selector if possible). if (createNewProperty) { - if (alreadyNew && !valueChanged && (isEditingName ^ (moveDirection === 'backward'))) + if (alreadyNew && !valueChanged && (isEditingName ^ (moveDirection === 'backward'))) { return; + } section.addNewBlankProperty().startEditing(); return; @@ -975,19 +1048,21 @@ moveTo = this._findSibling(moveDirection); const sectionToEdit = (moveTo || moveDirection === 'backward') ? section : section.nextEditableSibling(); if (sectionToEdit) { - if (sectionToEdit.style().parentRule) + if (sectionToEdit.style().parentRule) { sectionToEdit.startEditingSelector(); - else + } else { sectionToEdit.moveEditorFromSelector(moveDirection); + } } return; } if (moveToSelector) { - if (section.style().parentRule) + if (section.style().parentRule) { section.startEditingSelector(); - else + } else { section.moveEditorFromSelector(moveDirection); + } } } } @@ -1020,12 +1095,14 @@ * @return {!Promise} */ async _innerApplyStyleText(styleText, majorChange, property) { - if (!this.treeOutline) + if (!this.treeOutline) { return; + } const oldStyleRange = this._style.range; - if (!oldStyleRange) + if (!oldStyleRange) { return; + } const hasBeenEditedIncrementally = this._hasBeenEditedIncrementally; styleText = styleText.replace(/[\xA0\t]/g, ' ').trim(); // Replace with whitespace. @@ -1040,8 +1117,9 @@ // Append a ";" if the new text does not end in ";". // FIXME: this does not handle trailing comments. - if (styleText.length && !/;\s*$/.test(styleText)) + if (styleText.length && !/;\s*$/.test(styleText)) { styleText += ';'; + } const overwriteProperty = !this._newProperty || hasBeenEditedIncrementally; let success = await this.property.setText(styleText, majorChange, overwriteProperty); // Revert to the original text if applying the new text failed @@ -1054,10 +1132,11 @@ if (!success) { if (majorChange) { // It did not apply, cancel editing. - if (this._newProperty) + if (this._newProperty) { this.treeOutline.removeChild(this); - else + } else { this.updateTitle(); + } } this.styleTextAppliedForTest(); return; @@ -1067,8 +1146,9 @@ this._hasBeenEditedIncrementally = true; this.property = property || this._style.propertyAt(this.property.index); - if (currentNode === this.node()) + if (currentNode === this.node()) { this._updatePane(); + } this.styleTextAppliedForTest(); }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js b/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js index 7ddc0a9..94560a2fc 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js
@@ -97,8 +97,9 @@ static createExclamationMark(property) { const exclamationElement = createElement('span', 'dt-icon-label'); exclamationElement.className = 'exclamation-mark'; - if (!Elements.StylesSidebarPane.ignoreErrorsForProperty(property)) + if (!Elements.StylesSidebarPane.ignoreErrorsForProperty(property)) { exclamationElement.type = 'smallicon-warning'; + } exclamationElement.title = SDK.cssMetadata().isCSSPropertyName(property.name) ? Common.UIString('Invalid property value') : Common.UIString('Unknown property name'); @@ -120,26 +121,32 @@ const name = property.name.toLowerCase(); // IE hack. - if (name.charAt(0) === '_') + if (name.charAt(0) === '_') { return true; + } // IE has a different format for this. - if (name === 'filter') + if (name === 'filter') { return true; + } // Common IE-specific property prefix. - if (name.startsWith('scrollbar-')) + if (name.startsWith('scrollbar-')) { return true; - if (hasUnknownVendorPrefix(name)) + } + if (hasUnknownVendorPrefix(name)) { return true; + } const value = property.value.toLowerCase(); // IE hack. - if (value.endsWith('\\9')) + if (value.endsWith('\\9')) { return true; - if (hasUnknownVendorPrefix(value)) + } + if (hasUnknownVendorPrefix(value)) { return true; + } return false; } @@ -164,8 +171,9 @@ * @param {!Event} event */ function keydownHandler(event) { - if (event.key !== 'Escape' || !input.value) + if (event.key !== 'Escape' || !input.value) { return; + } event.consume(true); input.value = ''; searchHandler(); @@ -207,11 +215,13 @@ */ _sectionsContainerKeyDown(event) { const activeElement = this._sectionsContainer.ownerDocument.deepActiveElement(); - if (!activeElement) + if (!activeElement) { return; + } const section = activeElement._section; - if (!section) + if (!section) { return; + } switch (event.key) { case 'ArrowUp': @@ -241,8 +251,9 @@ _sectionsContainerFocusChanged() { // When a styles section is focused, shift+tab should leave the section. // Leaving tabIndex = 0 on the first element would cause it to be focused instead. - if (this._sectionBlocks[0] && this._sectionBlocks[0].sections[0]) + if (this._sectionBlocks[0] && this._sectionBlocks[0].sections[0]) { this._sectionBlocks[0].sections[0].element.tabIndex = this._sectionsContainer.hasFocus() ? -1 : 0; + } } /** @@ -250,8 +261,9 @@ */ _onAddButtonLongClick(event) { const cssModel = this.cssModel(); - if (!cssModel) + if (!cssModel) { return; + } const headers = cssModel.styleSheetHeaders().filter(styleSheetResourceHeader); /** @type {!Array.<{text: string, handler: function()}>} */ @@ -306,26 +318,31 @@ _refreshUpdate(editedSection, editedTreeElement) { if (editedTreeElement) { for (const section of this.allSections()) { - if (section.isBlank) + if (section.isBlank) { continue; + } section._updateVarFunctions(editedTreeElement); } } - if (this._isEditingStyle) + if (this._isEditingStyle) { return; + } const node = this.node(); - if (!node) + if (!node) { return; + } for (const section of this.allSections()) { - if (section.isBlank) + if (section.isBlank) { continue; + } section.update(section === editedSection); } - if (this._filterRegex) + if (this._filterRegex) { this._updateFilter(); + } this._nodeStylesUpdatedForTest(node, false); } @@ -354,8 +371,9 @@ } _resetCache() { - if (this.cssModel()) + if (this.cssModel()) { this.cssModel().discardCachedMatchedCascade(); + } } /** @@ -363,8 +381,9 @@ */ _fetchMatchedCascade() { const node = this.node(); - if (!node || !this.cssModel()) + if (!node || !this.cssModel()) { return Promise.resolve(/** @type {?SDK.CSSMatchedStyles} */ (null)); + } return this.cssModel().cachedMatchedCascadeForNode(node).then(validateStyles.bind(this)); @@ -383,8 +402,9 @@ * @param {!Elements.StylePropertyTreeElement=} treeElement */ setEditingStyle(editing, treeElement) { - if (this._isEditingStyle === editing) + if (this._isEditingStyle === editing) { return; + } this.contentElement.classList.toggle('is-editing-style', editing); this._isEditingStyle = editing; this._setActiveProperty(null); @@ -394,21 +414,25 @@ * @param {?Elements.StylePropertyTreeElement} treeElement */ _setActiveProperty(treeElement) { - if (this._isActivePropertyHighlighted) + if (this._isActivePropertyHighlighted) { SDK.OverlayModel.hideDOMNodeHighlight(); + } this._isActivePropertyHighlighted = false; - if (!this.node()) + if (!this.node()) { return; + } - if (!treeElement || treeElement.overloaded() || treeElement.inherited()) + if (!treeElement || treeElement.overloaded() || treeElement.inherited()) { return; + } const rule = treeElement.property.ownerStyle.parentRule; const selectorList = rule ? rule.selectorText() : undefined; for (const mode of ['padding', 'border', 'margin']) { - if (!treeElement.name.startsWith(mode)) + if (!treeElement.name.startsWith(mode)) { continue; + } this.node().domModel().overlayModel().highlightInOverlay( {node: /** @type {!SDK.DOMNode} */ (this.node()), selectorList}, mode); this._isActivePropertyHighlighted = true; @@ -423,13 +447,15 @@ onCSSModelChanged(event) { const edit = event && event.data ? /** @type {?SDK.CSSModel.Edit} */ (event.data.edit) : null; if (edit) { - for (const section of this.allSections()) + for (const section of this.allSections()) { section._styleSheetEdited(edit); + } return; } - if (this._userOperation || this._isEditingStyle) + if (this._userOperation || this._isEditingStyle) { return; + } this._resetCache(); this.update(); @@ -442,8 +468,9 @@ let index = 0; for (const block of this._sectionBlocks) { for (const section of block.sections) { - if (section.element.hasFocus()) + if (section.element.hasFocus()) { return index; + } index++; } } @@ -456,8 +483,9 @@ */ continueEditingElement(sectionIndex, propertyIndex) { const section = this.allSections()[sectionIndex]; - if (section) + if (section) { section.propertiesTreeOutline.rootElement().childAt(propertyIndex).startEditing(); + } } /** @@ -468,10 +496,11 @@ // Elements.ElementsSidebarPane's throttler schedules this method. Usually, // rebuild is suppressed while editing (see onCSSModelChanged()), but we need a // 'force' flag since the currently running throttler process cannot be canceled. - if (this._needsForceUpdate) + if (this._needsForceUpdate) { this._needsForceUpdate = false; - else if (this._isEditingStyle || this._userOperation) + } else if (this._isEditingStyle || this._userOperation) { return; + } const focusedIndex = this.focusedSectionIndex(); this._linkifier.reset(); @@ -488,8 +517,9 @@ await this._rebuildSectionsForMatchedStyleRules(/** @type {!SDK.CSSMatchedStyles} */ (matchedStyles)); let pseudoTypes = []; const keys = matchedStyles.pseudoTypes(); - if (keys.delete(Protocol.DOM.PseudoType.Before)) + if (keys.delete(Protocol.DOM.PseudoType.Before)) { pseudoTypes.push(Protocol.DOM.PseudoType.Before); + } pseudoTypes = pseudoTypes.concat(keys.valuesArray().sort()); for (const pseudoType of pseudoTypes) { const block = Elements.SectionBlock.createPseudoTypeBlock(pseudoType); @@ -502,31 +532,36 @@ for (const keyframesRule of matchedStyles.keyframes()) { const block = Elements.SectionBlock.createKeyframesBlock(keyframesRule.name().text); - for (const keyframe of keyframesRule.keyframes()) + for (const keyframe of keyframesRule.keyframes()) { block.sections.push(new Elements.KeyframePropertiesSection(this, matchedStyles, keyframe.style)); + } this._sectionBlocks.push(block); } let index = 0; for (const block of this._sectionBlocks) { const titleElement = block.titleElement(); - if (titleElement) + if (titleElement) { this._sectionsContainer.appendChild(titleElement); + } for (const section of block.sections) { this._sectionsContainer.appendChild(section.element); - if (index === focusedIndex) + if (index === focusedIndex) { section.element.focus(); + } index++; } } - if (focusedIndex >= index) + if (focusedIndex >= index) { this._sectionBlocks[0].sections[0].element.focus(); + } this._sectionsContainerFocusChanged(); - if (this._filterRegex) + if (this._filterRegex) { this._updateFilter(); - else + } else { this._noMatchesElement.classList.toggle('hidden', this._sectionBlocks.length > 0); + } this._nodeStylesUpdatedForTest(/** @type {!SDK.DOMNode} */ (node), true); if (this._decorator) { @@ -566,8 +601,9 @@ async _createNewRuleInViaInspectorStyleSheet() { const cssModel = this.cssModel(); const node = this.node(); - if (!cssModel || !node) + if (!cssModel || !node) { return; + } this.setUserOperation(true); const styleSheetHeader = await cssModel.requestViaInspectorStylesheet(/** @type {!SDK.DOMNode} */ (node)); @@ -580,8 +616,9 @@ * @param {?SDK.CSSStyleSheetHeader} styleSheetHeader */ async _createNewRuleInStyleSheet(styleSheetHeader) { - if (!styleSheetHeader) + if (!styleSheetHeader) { return; + } const text = await styleSheetHeader.requestContent() || ''; const lines = text.split('\n'); const range = TextUtils.TextRange.createFromLocation(lines.length - 1, lines[lines.length - 1].length); @@ -603,8 +640,9 @@ for (const block of this._sectionBlocks) { const index = block.sections.indexOf(insertAfterSection); - if (index === -1) + if (index === -1) { continue; + } block.sections.splice(index + 1, 0, blankSection); blankSection.startEditingSelector(); } @@ -616,8 +654,9 @@ removeSection(section) { for (const block of this._sectionBlocks) { const index = block.sections.indexOf(section); - if (index === -1) + if (index === -1) { continue; + } block.sections.splice(index, 1); section.element.remove(); } @@ -632,8 +671,9 @@ _updateFilter() { let hasAnyVisibleBlock = false; - for (const block of this._sectionBlocks) + for (const block of this._sectionBlocks) { hasAnyVisibleBlock |= block.updateFilter(); + } this._noMatchesElement.classList.toggle('hidden', !!hasAnyVisibleBlock); } @@ -650,8 +690,9 @@ */ allSections() { let sections = []; - for (const block of this._sectionBlocks) + for (const block of this._sectionBlocks) { sections = sections.concat(block.sections); + } return sections; } @@ -687,25 +728,29 @@ * @param {?UI.ToolbarToggle} toggle */ showToolbarPane(widget, toggle) { - if (this._pendingWidgetToggle) + if (this._pendingWidgetToggle) { this._pendingWidgetToggle.setToggled(false); + } this._pendingWidgetToggle = toggle; - if (this._animatedToolbarPane) + if (this._animatedToolbarPane) { this._pendingWidget = widget; - else + } else { this._startToolbarPaneAnimation(widget); + } - if (widget && toggle) + if (widget && toggle) { toggle.setToggled(true); + } } /** * @param {?UI.Widget} widget */ _startToolbarPaneAnimation(widget) { - if (widget === this._currentToolbarPane) + if (widget === this._currentToolbarPane) { return; + } if (widget && this._currentToolbarPane) { this._currentToolbarPane.detach(); @@ -717,13 +762,15 @@ this._animatedToolbarPane = widget; - if (this._currentToolbarPane) + if (this._currentToolbarPane) { this._toolbarPaneElement.style.animationName = 'styles-element-state-pane-slideout'; - else if (widget) + } else if (widget) { this._toolbarPaneElement.style.animationName = 'styles-element-state-pane-slidein'; + } - if (widget) + if (widget) { widget.show(this._toolbarPaneElement); + } const listener = onAnimationEnd.bind(this); this._toolbarPaneElement.addEventListener('animationend', listener, false); @@ -735,12 +782,14 @@ this._toolbarPaneElement.style.removeProperty('animation-name'); this._toolbarPaneElement.removeEventListener('animationend', listener, false); - if (this._currentToolbarPane) + if (this._currentToolbarPane) { this._currentToolbarPane.detach(); + } this._currentToolbarPane = this._animatedToolbarPane; - if (this._currentToolbarPane) + if (this._currentToolbarPane) { this._currentToolbarPane.focus(); + } this._animatedToolbarPane = null; if (this._pendingWidget) { @@ -802,10 +851,12 @@ */ updateFilter() { let hasAnyVisibleSection = false; - for (const section of this.sections) + for (const section of this.sections) { hasAnyVisibleSection |= section._updateFilter(); - if (this._titleElement) + } + if (this._titleElement) { this._titleElement.classList.toggle('hidden', !hasAnyVisibleSection); + } return !!hasAnyVisibleSection; } @@ -899,8 +950,9 @@ this._titleElement.appendChild(selectorContainer); this._selectorContainer = selectorContainer; - if (this.navigable) + if (this.navigable) { this.element.classList.add('navigable'); + } if (!this.editable) { this.element.classList.add('read-only'); @@ -919,14 +971,16 @@ * @return {!Node} */ static createRuleOriginNode(matchedStyles, linkifier, rule) { - if (!rule) + if (!rule) { return createTextNode(''); + } let ruleLocation; - if (rule instanceof SDK.CSSStyleRule) + if (rule instanceof SDK.CSSStyleRule) { ruleLocation = rule.style.range; - else if (rule instanceof SDK.CSSKeyframeRule) + } else if (rule instanceof SDK.CSSKeyframeRule) { ruleLocation = rule.key().range; + } const header = rule.styleSheetId ? matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId) : null; if (ruleLocation && rule.styleSheetId && header && !header.isAnonymousInlineStyleSheet()) { @@ -934,12 +988,15 @@ matchedStyles.cssModel(), linkifier, rule.styleSheetId, ruleLocation); } - if (rule.isUserAgent()) + if (rule.isUserAgent()) { return createTextNode(Common.UIString('user agent stylesheet')); - if (rule.isInjected()) + } + if (rule.isInjected()) { return createTextNode(Common.UIString('injected stylesheet')); - if (rule.isViaInspector()) + } + if (rule.isViaInspector()) { return createTextNode(Common.UIString('via inspector')); + } if (header && header.ownerNode) { const link = Elements.DOMLinkifier.linkifyDeferredNodeReference(header.ownerNode, {preventKeyboardFocus: true}); @@ -969,8 +1026,9 @@ * @param {!Event} event */ _onKeyDown(event) { - if (UI.isEditing() || !this.editable || event.altKey || event.ctrlKey || event.metaKey) + if (UI.isEditing() || !this.editable || event.altKey || event.ctrlKey || event.metaKey) { return; + } switch (event.key) { case 'Enter': case ' ': @@ -979,8 +1037,9 @@ break; default: // Filter out non-printable key strokes. - if (event.key.length === 1) + if (event.key.length === 1) { this.addNewBlankProperty(0).startEditing(); + } break; } } @@ -1013,20 +1072,23 @@ this._setSectionHovered(hasCtrlOrMeta); const treeElement = this.propertiesTreeOutline.treeElementFromEvent(event); - if (treeElement instanceof Elements.StylePropertyTreeElement) + if (treeElement instanceof Elements.StylePropertyTreeElement) { this._parentPane._setActiveProperty(/** @type {!Elements.StylePropertyTreeElement} */ (treeElement)); - else + } else { this._parentPane._setActiveProperty(null); - if (!this._selectedSinceMouseDown && this.element.getComponentSelection().toString()) + } + if (!this._selectedSinceMouseDown && this.element.getComponentSelection().toString()) { this._selectedSinceMouseDown = true; + } } /** * @param {!Element} container */ _createHoverMenuToolbar(container) { - if (!this.editable) + if (!this.editable) { return; + } const items = []; const textShadowButton = new UI.ToolbarButton(Common.UIString('Add text-shadow'), 'largeicon-text-shadow'); @@ -1061,8 +1123,9 @@ } const sectionToolbar = new UI.Toolbar('sidebar-pane-section-toolbar', container); - for (let i = 0; i < items.length; ++i) + for (let i = 0; i < items.length; ++i) { sectionToolbar.appendToolbarItem(items[i]); + } const menuButton = new UI.ToolbarButton('', 'largeicon-menu'); menuButton.element.tabIndex = -1; @@ -1077,8 +1140,9 @@ * @param {boolean} value */ function setItemsVisibility(items, value) { - for (let i = 0; i < items.length; ++i) + for (let i = 0; i < items.length; ++i) { items[i].setVisible(value); + } menuButton.setVisible(!value); } } @@ -1095,22 +1159,26 @@ */ _headerText() { const node = this._matchedStyles.nodeForStyle(this._style); - if (this._style.type === SDK.CSSStyleDeclaration.Type.Inline) + if (this._style.type === SDK.CSSStyleDeclaration.Type.Inline) { return this._matchedStyles.isInherited(this._style) ? Common.UIString('Style Attribute') : 'element.style'; - if (this._style.type === SDK.CSSStyleDeclaration.Type.Attributes) + } + if (this._style.type === SDK.CSSStyleDeclaration.Type.Attributes) { return ls`${node.nodeNameInCorrectCase()}[Attributes Style]`; + } return this._style.parentRule.selectorText(); } _onMouseOutSelector() { - if (this._hoverTimer) + if (this._hoverTimer) { clearTimeout(this._hoverTimer); + } SDK.OverlayModel.hideDOMNodeHighlight(); } _onMouseEnterSelector() { - if (this._hoverTimer) + if (this._hoverTimer) { clearTimeout(this._hoverTimer); + } this._hoverTimer = setTimeout(this._highlight.bind(this), 300); } @@ -1120,8 +1188,9 @@ _highlight(mode = 'all') { SDK.OverlayModel.hideDOMNodeHighlight(); const node = this._parentPane.node(); - if (!node) + if (!node) { return; + } const selectorList = this._style.parentRule ? this._style.parentRule.selectorText() : undefined; node.domModel().overlayModel().highlightInOverlay({node, selectorList}, mode); } @@ -1131,13 +1200,15 @@ */ firstSibling() { const parent = this.element.parentElement; - if (!parent) + if (!parent) { return null; + } let childElement = parent.firstChild; while (childElement) { - if (childElement._section) + if (childElement._section) { return childElement._section; + } childElement = childElement.nextSibling; } @@ -1149,13 +1220,15 @@ */ lastSibling() { const parent = this.element.parentElement; - if (!parent) + if (!parent) { return null; + } let childElement = parent.lastChild; while (childElement) { - if (childElement._section) + if (childElement._section) { return childElement._section; + } childElement = childElement.previousSibling; } @@ -1167,9 +1240,9 @@ */ nextSibling() { let curElement = this.element; - do + do { curElement = curElement.nextSibling; - while (curElement && !curElement._section); + } while (curElement && !curElement._section); return curElement ? curElement._section : null; } @@ -1179,9 +1252,9 @@ */ previousSibling() { let curElement = this.element; - do + do { curElement = curElement.previousSibling; - while (curElement && !curElement._section); + } while (curElement && !curElement._section); return curElement ? curElement._section : null; } @@ -1207,8 +1280,9 @@ treeElement.property.value = '0 0 black'; treeElement.updateTitle(); const shadowSwatchPopoverHelper = Elements.ShadowSwatchPopoverHelper.forTreeElement(treeElement); - if (shadowSwatchPopoverHelper) + if (shadowSwatchPopoverHelper) { shadowSwatchPopoverHelper.showPopover(); + } } /** @@ -1221,8 +1295,9 @@ treeElement.property.value = 'black'; treeElement.updateTitle(); const colorSwatch = Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement); - if (colorSwatch) + if (colorSwatch) { colorSwatch.showPopover(); + } } /** @@ -1235,8 +1310,9 @@ treeElement.property.value = 'white'; treeElement.updateTitle(); const colorSwatch = Elements.ColorSwatchPopoverIcon.forTreeElement(treeElement); - if (colorSwatch) + if (colorSwatch) { colorSwatch.showPopover(); + } } /** @@ -1244,10 +1320,11 @@ */ _styleSheetEdited(edit) { const rule = this._style.parentRule; - if (rule) + if (rule) { rule.rebase(edit); - else + } else { this._style.rebase(edit); + } this._updateMediaList(); this._updateRuleOrigin(); @@ -1260,8 +1337,9 @@ for (let i = mediaRules.length - 1; i >= 0; --i) { const media = mediaRules[i]; // Don't display trivial non-print media types. - if (!media.text.includes('(') && media.text !== 'print') + if (!media.text.includes('(') && media.text !== 'print') { continue; + } const mediaDataElement = this._mediaListElement.createChild('div', 'media'); const mediaContainerElement = mediaDataElement.createChild('span'); const mediaTextElement = mediaContainerElement.createChild('span', 'media-text'); @@ -1290,8 +1368,9 @@ _updateMediaList() { this._mediaListElement.removeChildren(); - if (this._style.parentRule && this._style.parentRule instanceof SDK.CSSStyleRule) + if (this._style.parentRule && this._style.parentRule instanceof SDK.CSSStyleRule) { this._createMediaList(this._style.parentRule.media); + } } /** @@ -1312,14 +1391,15 @@ */ nextEditableSibling() { let curSection = this; - do + do { curSection = curSection.nextSibling(); - while (curSection && !curSection.editable); + } while (curSection && !curSection.editable); if (!curSection) { curSection = this.firstSibling(); - while (curSection && !curSection.editable) + while (curSection && !curSection.editable) { curSection = curSection.nextSibling(); + } } return (curSection && curSection.editable) ? curSection : null; @@ -1330,14 +1410,15 @@ */ previousEditableSibling() { let curSection = this; - do + do { curSection = curSection.previousSibling(); - while (curSection && !curSection.editable); + } while (curSection && !curSection.editable); if (!curSection) { curSection = this.lastSibling(); - while (curSection && !curSection.editable) + while (curSection && !curSection.editable) { curSection = curSection.previousSibling(); + } } return (curSection && curSection.editable) ? curSection : null; @@ -1356,8 +1437,9 @@ _updateVarFunctions(editedTreeElement) { let child = this.propertiesTreeOutline.firstChild(); while (child) { - if (child !== editedTreeElement) + if (child !== editedTreeElement) { child.updateTitleIfComputedValueChanged(); + } child = child.traverseNextTreeElement(false /* skipUnrevealed */, null /* stayWithin */, true /* dontPopulate */); } } @@ -1384,10 +1466,12 @@ * @param {!Event=} event */ _showAllItems(event) { - if (event) + if (event) { event.consume(); - if (this._forceShowAll) + } + if (this._forceShowAll) { return; + } this._forceShowAll = true; this.onpopulate(); } @@ -1402,14 +1486,16 @@ Elements.StylePropertiesSection.MaxProperties + properties.length - this._originalPropertiesCount; for (const property of properties) { - if (!this._forceShowAll && count >= maxProperties) + if (!this._forceShowAll && count >= maxProperties) { break; + } count++; const isShorthand = !!style.longhandProperties(property.name).length; const inherited = this.isPropertyInherited(property.name); const overloaded = this._isPropertyOverloaded(property); - if (style.parentRule && style.parentRule.isUserAgent() && inherited) + if (style.parentRule && style.parentRule.isUserAgent() && inherited) { continue; + } const item = new Elements.StylePropertyTreeElement( this._parentPane, this._matchedStyles, property, isShorthand, inherited, overloaded, false); this.propertiesTreeOutline.appendChild(item); @@ -1437,32 +1523,37 @@ _updateFilter() { let hasMatchingChild = false; this._showAllItems(); - for (const child of this.propertiesTreeOutline.rootElement().children()) + for (const child of this.propertiesTreeOutline.rootElement().children()) { hasMatchingChild |= child._updateFilter(); + } const regex = this._parentPane.filterRegex(); const hideRule = !hasMatchingChild && !!regex && !regex.test(this.element.deepTextContent()); this.element.classList.toggle('hidden', hideRule); - if (!hideRule && this._style.parentRule) + if (!hideRule && this._style.parentRule) { this._markSelectorHighlights(); + } return !hideRule; } _markSelectorMatches() { const rule = this._style.parentRule; - if (!rule) + if (!rule) { return; + } this._mediaListElement.classList.toggle('media-matches', this._matchedStyles.mediaMatches(this._style)); const selectorTexts = rule.selectors.map(selector => selector.text); const matchingSelectorIndexes = this._matchedStyles.matchingSelectors(/** @type {!SDK.CSSStyleRule} */ (rule)); const matchingSelectors = /** @type {!Array<boolean>} */ (new Array(selectorTexts.length).fill(false)); - for (const matchingIndex of matchingSelectorIndexes) + for (const matchingIndex of matchingSelectorIndexes) { matchingSelectors[matchingIndex] = true; + } - if (this._parentPane._isEditingStyle) + if (this._parentPane._isEditingStyle) { return; + } const fragment = this._hoverableSelectorsMode ? this._renderHoverableSelectors(selectorTexts, matchingSelectors) : this._renderSimplifiedSelectors(selectorTexts, matchingSelectors); @@ -1479,8 +1570,9 @@ _renderHoverableSelectors(selectors, matchingSelectors) { const fragment = createDocumentFragment(); for (let i = 0; i < selectors.length; ++i) { - if (i) + if (i) { fragment.createTextChild(', '); + } fragment.appendChild(this._createSelectorElement(selectors[i], matchingSelectors[i], i)); } return fragment; @@ -1495,8 +1587,9 @@ _createSelectorElement(text, isMatching, navigationIndex) { const element = createElementWithClass('span', 'simple-selector'); element.classList.toggle('selector-matches', isMatching); - if (typeof navigationIndex === 'number') + if (typeof navigationIndex === 'number') { element._selectorIndex = navigationIndex; + } element.textContent = text; return element; } @@ -1518,8 +1611,9 @@ currentMatching = matchingSelectors[i]; text += selectors[i] + (i === selectors.length - 1 ? '' : ', '); } - if (text) + if (text) { fragment.appendChild(this._createSelectorElement(text, currentMatching)); + } return fragment; } @@ -1545,8 +1639,9 @@ * @param {!Event} event */ _handleSelectorContainerClick(event) { - if (this._checkWillCancelEditing() || !this.editable) + if (this._checkWillCancelEditing() || !this.editable) { return; + } if (event.target === this._selectorContainer) { this.addNewBlankProperty(0).startEditing(); event.consume(true); @@ -1574,8 +1669,10 @@ * @param {!Event} event */ _handleEmptySpaceClick(event) { - if (!this.editable || this.element.hasSelection() || this._checkWillCancelEditing() || this._selectedSinceMouseDown) + if (!this.editable || this.element.hasSelection() || this._checkWillCancelEditing() || + this._selectedSinceMouseDown) { return; + } if (event.target.classList.contains('header') || this.element.classList.contains('read-only') || event.target.enclosingNodeOrSelfWithClass('media')) { @@ -1583,10 +1680,11 @@ return; } const deepTarget = event.deepElementFromPoint(); - if (deepTarget.treeElement) + if (deepTarget.treeElement) { this.addNewBlankProperty(deepTarget.treeElement.property.index + 1).startEditing(); - else + } else { this.addNewBlankProperty().startEditing(); + } event.consume(true); } @@ -1596,8 +1694,9 @@ * @param {!Event} event */ _handleMediaRuleClick(media, element, event) { - if (UI.isBeingEdited(element)) + if (UI.isBeingEdited(element)) { return; + } if (UI.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */ (event)) && this.navigable) { const location = media.rawLocation(); @@ -1606,14 +1705,16 @@ return; } const uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(location); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation); + } event.consume(true); return; } - if (!this.editable) + if (!this.editable) { return; + } const config = new UI.InplaceEditor.Config( this._editingMediaCommitted.bind(this, media), this._editingMediaCancelled.bind(this, element), undefined, @@ -1669,8 +1770,9 @@ this._parentPane.setEditingStyle(false); this._editingMediaFinished(element); - if (newContent) + if (newContent) { newContent = newContent.trim(); + } /** * @param {boolean} success @@ -1703,8 +1805,9 @@ event.consume(true); return; } - if (this.element.hasSelection()) + if (this.element.hasSelection()) { return; + } this._startEditingAtFirstPosition(); event.consume(true); } @@ -1717,17 +1820,20 @@ const cssModel = this._parentPane.cssModel(); const rule = this._style.parentRule; const header = cssModel.styleSheetHeaderForId(/** @type {string} */ (rule.styleSheetId)); - if (!header) + if (!header) { return; + } const rawLocation = new SDK.CSSLocation(header, rule.lineNumberInSource(index), rule.columnNumberInSource(index)); const uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation, !focus); + } } _startEditingAtFirstPosition() { - if (!this.editable) + if (!this.editable) { return; + } if (!this._style.parentRule) { this.moveEditorFromSelector('forward'); @@ -1739,8 +1845,9 @@ startEditingSelector() { const element = this._selectorElement; - if (UI.isBeingEdited(element)) + if (UI.isBeingEdited(element)) { return; + } element.scrollIntoViewIfNeeded(false); // Reset selector marks in group, and normalize whitespace. @@ -1752,8 +1859,9 @@ element.getComponentSelection().selectAllChildren(element); this._parentPane.setEditingStyle(true); - if (element.classList.contains('simple-selector')) + if (element.classList.contains('simple-selector')) { this._navigateToSelectorSource(0, false); + } } /** @@ -1762,21 +1870,25 @@ moveEditorFromSelector(moveDirection) { this._markSelectorMatches(); - if (!moveDirection) + if (!moveDirection) { return; + } if (moveDirection === 'forward') { let firstChild = this.propertiesTreeOutline.firstChild(); - while (firstChild && firstChild.inherited()) + while (firstChild && firstChild.inherited()) { firstChild = firstChild.nextSibling; - if (!firstChild) + } + if (!firstChild) { this.addNewBlankProperty().startEditing(); - else + } else { firstChild.startEditing(firstChild.nameElement); + } } else { const previousSection = this.previousEditableSibling(); - if (!previousSection) + if (!previousSection) { return; + } previousSection.addNewBlankProperty().startEditing(); } @@ -1791,8 +1903,9 @@ */ editingSelectorCommitted(element, newContent, oldContent, context, moveDirection) { this._editingSelectorEnded(); - if (newContent) + if (newContent) { newContent = newContent.trim(); + } if (newContent === oldContent) { // Revert to a trimmed version of the selector if need be. this._selectorElement.textContent = newContent; @@ -1800,8 +1913,9 @@ return; } const rule = this._style.parentRule; - if (!rule) + if (!rule) { return; + } /** * @this {Elements.StylePropertiesSection} @@ -1830,8 +1944,9 @@ * @this {Elements.StylePropertiesSection} */ function onSelectorsUpdated(rule, success) { - if (!success) + if (!success) { return Promise.resolve(); + } return this._matchedStyles.recomputeMatchingSelectors(rule).then(updateSourceRanges.bind(this, rule)); } @@ -1848,8 +1963,9 @@ console.assert(rule instanceof SDK.CSSStyleRule); const oldSelectorRange = rule.selectorRange(); - if (!oldSelectorRange) + if (!oldSelectorRange) { return Promise.resolve(); + } return rule.setSelectorText(newContent) .then(onSelectorsUpdated.bind(this, /** @type {!SDK.CSSStyleRule} */ (rule), oldSelectorRange)); } @@ -1895,8 +2011,9 @@ this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(Elements.StylePropertiesSection._linkifyRuleLocation( cssModel, this._parentPane._linkifier, styleSheetId, this._actualRuleLocation())); - if (insertAfterStyle && insertAfterStyle.parentRule) + if (insertAfterStyle && insertAfterStyle.parentRule) { this._createMediaList(insertAfterStyle.parentRule.media); + } this.element.classList.add('blank-section'); } @@ -1961,22 +2078,26 @@ const doesSelectorAffectSelectedNode = this._matchedStyles.matchingSelectors(newRule).length > 0; this._makeNormal(newRule); - if (!doesSelectorAffectSelectedNode) + if (!doesSelectorAffectSelectedNode) { this.propertiesTreeOutline.element.classList.add('no-affect'); + } this._updateRuleOrigin(); this._parentPane.setUserOperation(false); this._editingSelectorEnded(); if (this.element.parentElement) // Might have been detached already. + { this.moveEditorFromSelector(moveDirection); + } this._markSelectorMatches(); this._editingSelectorCommittedForTest(); } - if (newContent) + if (newContent) { newContent = newContent.trim(); + } this._parentPane.setUserOperation(true); const cssModel = this._parentPane.cssModel(); @@ -2041,15 +2162,17 @@ * @this {Elements.KeyframePropertiesSection} */ function updateSourceRanges(success) { - if (!success) + if (!success) { return; + } this._parentPane._refreshUpdate(this); } console.assert(rule instanceof SDK.CSSKeyframeRule); const oldRange = rule.key().range; - if (!oldRange) + if (!oldRange) { return Promise.resolve(); + } return rule.setKeyText(newContent).then(updateSourceRanges.bind(this)); } @@ -2105,8 +2228,9 @@ this._cssCompletions = []; if (isEditingName) { this._cssCompletions = SDK.cssMetadata().allProperties(); - if (!treeElement.node().isSVGNode()) + if (!treeElement.node().isSVGNode()) { this._cssCompletions = this._cssCompletions.filter(property => !SDK.cssMetadata().isSVGProperty(property)); + } } else { this._cssCompletions = SDK.cssMetadata().propertyValues(treeElement.nameElement.textContent); } @@ -2114,10 +2238,11 @@ this._treeElement = treeElement; this._isEditingName = isEditingName; this._cssVariables = treeElement.matchedStyles().availableCSSVariables(treeElement.property.ownerStyle); - if (this._cssVariables.length < 1000) + if (this._cssVariables.length < 1000) { this._cssVariables.sort(String.naturalOrderComparator); - else + } else { this._cssVariables.sort(); + } if (!isEditingName) { this.disableDefaultSuggestionForEmptyInput(); @@ -2153,8 +2278,9 @@ } break; case 'Enter': - if (event.shiftKey) + if (event.shiftKey) { return; + } // Accept any available autocompletions and advance to the next field. this.tabKeyPressed(); event.preventDefault(); @@ -2211,8 +2337,9 @@ * @this {Elements.StylesSidebarPane.CSSPropertyPrompt} */ function customNumberHandler(prefix, number, suffix) { - if (number !== 0 && !suffix.length && SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) + if (number !== 0 && !suffix.length && SDK.cssMetadata().isLengthProperty(this._treeElement.property.name)) { suffix = 'px'; + } return prefix + number + suffix; } @@ -2220,8 +2347,9 @@ if (!this._isEditingName && this._treeElement.valueElement && UI.handleElementValueModifications( event, this._treeElement.valueElement, finishHandler.bind(this), this._isValueSuggestion.bind(this), - customNumberHandler.bind(this))) + customNumberHandler.bind(this))) { return true; + } return false; } @@ -2231,8 +2359,9 @@ * @return {boolean} */ _isValueSuggestion(word) { - if (!word) + if (!word) { return false; + } word = word.toLowerCase(); return this._cssCompletions.indexOf(word) !== -1 || word.startsWith('--'); } @@ -2246,29 +2375,34 @@ _buildPropertyCompletions(expression, query, force) { const lowerQuery = query.toLowerCase(); const editingVariable = !this._isEditingName && expression.trim().endsWith('var('); - if (!query && !force && !editingVariable && (this._isEditingName || expression)) + if (!query && !force && !editingVariable && (this._isEditingName || expression)) { return Promise.resolve([]); + } const prefixResults = []; const anywhereResults = []; - if (!editingVariable) + if (!editingVariable) { this._cssCompletions.forEach(completion => filterCompletions.call(this, completion, false /* variable */)); + } if (this._isEditingName) { const nameValuePresets = SDK.cssMetadata().nameValuePresets(this._treeElement.node().isSVGNode()); nameValuePresets.forEach( preset => filterCompletions.call(this, preset, false /* variable */, true /* nameValue */)); } - if (this._isEditingName || editingVariable) + if (this._isEditingName || editingVariable) { this._cssVariables.forEach(variable => filterCompletions.call(this, variable, true /* variable */)); + } const results = prefixResults.concat(anywhereResults); - if (!this._isEditingName && !results.length && query.length > 1 && '!important'.startsWith(lowerQuery)) + if (!this._isEditingName && !results.length && query.length > 1 && '!important'.startsWith(lowerQuery)) { results.push({text: '!important'}); + } const userEnteredText = query.replace('-', ''); if (userEnteredText && (userEnteredText === userEnteredText.toUpperCase())) { for (let i = 0; i < results.length; ++i) { - if (!results[i].text.startsWith('--')) + if (!results[i].text.startsWith('--')) { results[i].text = results[i].text.toUpperCase(); + } } } results.forEach(result => { @@ -2286,8 +2420,9 @@ }); if (this._isColorAware && !this._isEditingName) { results.sort((a, b) => { - if (!!a.subtitleRenderer === !!b.subtitleRenderer) + if (!!a.subtitleRenderer === !!b.subtitleRenderer) { return 0; + } return a.subtitleRenderer ? -1 : 1; }); } @@ -2307,12 +2442,14 @@ this._treeElement.matchedStyles().computeCSSVariable(this._treeElement.property.ownerStyle, completion); if (computedValue) { const color = Common.Color.parse(computedValue); - if (color) + if (color) { result.subtitleRenderer = swatchRenderer.bind(null, color); + } } } - if (nameValue) + if (nameValue) { result.hideGhostText = true; + } if (index === 0) { result.priority = this._isEditingName ? SDK.cssMetadata().propertyUsageWeight(completion) : 1; prefixResults.push(result); @@ -2411,8 +2548,9 @@ renderValue() { const valueElement = createElement('span'); valueElement.className = 'value'; - if (!this._propertyValue) + if (!this._propertyValue) { return valueElement; + } if (this._shadowHandler && (this._propertyName === 'box-shadow' || this._propertyName === 'text-shadow' || this._propertyName === '-webkit-box-shadow') && @@ -2456,15 +2594,17 @@ // Strip "url(" and ")" along with whitespace. let url = text.substring(4, text.length - 1).trim(); const isQuoted = /^'.*'$/.test(url) || /^".*"$/.test(url); - if (isQuoted) + if (isQuoted) { url = url.substring(1, url.length - 1); + } const container = createDocumentFragment(); container.createTextChild('url('); let hrefUrl = null; - if (this._rule && this._rule.resourceURL()) + if (this._rule && this._rule.resourceURL()) { hrefUrl = Common.ParsedURL.completeURL(this._rule.resourceURL(), url); - else if (this._node) + } else if (this._node) { hrefUrl = this._node.resolveURL(url); + } container.appendChild(Components.Linkifier.linkifyURL(hrefUrl || url, {text: url, preventClick: true})); container.createTextChild(')'); return container;
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/EditDOMTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/EditDOMTestRunner.js index 56efb45..d50240d 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/EditDOMTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/EditDOMTestRunner.js
@@ -57,8 +57,9 @@ const treeElement = ElementsTestRunner.firstElementsTreeOutline().findTreeElement(node); let textElement = treeElement.listItemElement.getElementsByClassName(className)[0]; - if (!textElement && treeElement.childrenListElement) + if (!textElement && treeElement.childrenListElement) { textElement = treeElement.childrenListElement.getElementsByClassName(className)[0]; + } treeElement._startEditingTarget(textElement); return textElement; @@ -69,8 +70,9 @@ editorElement.textContent = newValue; editorElement.dispatchEvent(TestRunner.createKeyEvent('Enter')); - if (useSniffer) + if (useSniffer) { TestRunner.addSniffer(Elements.ElementsTreeOutline.prototype, '_updateModifiedNodes', step2); - else + } else { TestRunner.deprecatedRunAfterPendingDispatches(step2); + } };
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsPanelShadowSelectionOnRefreshTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsPanelShadowSelectionOnRefreshTestRunner.js index 335966c..c0134e6 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsPanelShadowSelectionOnRefreshTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsPanelShadowSelectionOnRefreshTestRunner.js
@@ -28,8 +28,9 @@ } function maybeDumpSelectedNode() { - if (!reloaded || !selected) + if (!reloaded || !selected) { return; + } const selectedElement = ElementsTestRunner.firstElementsTreeOutline().selectedTreeElement; const nodeName = (selectedElement ? selectedElement.node().nodeNameInCorrectCase() : 'null');
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js index ad3b35f..816012f 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/ElementsTestRunner.js
@@ -53,21 +53,24 @@ let pendingRequests = 0; async function processChildren(node) { try { - if (result) + if (result) { return; + } - if (node._childDocumentPromiseForTesting) + if (node._childDocumentPromiseForTesting) { await node._childDocumentPromiseForTesting; + } const pseudoElementsMap = node.pseudoElements(); const pseudoElements = pseudoElementsMap ? pseudoElementsMap.valuesArray() : []; const children = (node.children() || []).concat(node.shadowRoots()).concat(pseudoElements); - if (node.templateContent()) + if (node.templateContent()) { children.push(node.templateContent()); - else if (node.contentDocument()) + } else if (node.contentDocument()) { children.push(node.contentDocument()); - else if (node.importedDocument()) + } else if (node.importedDocument()) { children.push(node.importedDocument()); + } for (let i = 0; i < children.length; ++i) { const childNode = children[i]; @@ -83,8 +86,9 @@ pendingRequests--; } - if (!result && !pendingRequests) + if (!result && !pendingRequests) { callback(null); + } } const doc = TestRunner.domModel.existingDocument() || await TestRunner.domModel.requestDocument(); @@ -111,8 +115,9 @@ for (let i = 0; i < listenerTypes.length; ++i) { listenerTypes[i].expand(); const listenerItems = listenerTypes[i].children(); - for (let j = 0; j < listenerItems.length; ++j) + for (let j = 0; j < listenerItems.length; ++j) { listenerItems[j].expand(); + } } TestRunner.deprecatedRunAfterPendingDispatches(objectsExpanded); } @@ -120,8 +125,9 @@ function objectsExpanded() { const listenerTypes = eventListenersView._treeOutline.rootElement().children(); for (let i = 0; i < listenerTypes.length; ++i) { - if (!listenerTypes[i].children().length) + if (!listenerTypes[i].children().length) { continue; + } const eventType = listenerTypes[i]._title; TestRunner.addResult(''); TestRunner.addResult('======== ' + eventType + ' ========'); @@ -158,31 +164,35 @@ for (const treeElement of children) { const property = treeElement[Elements.ComputedStyleWidget._propertySymbol]; - if (property.name === 'width' || property.name === 'height') + if (property.name === 'width' || property.name === 'height') { continue; + } let dumpText = ''; dumpText += text(treeElement.title.querySelector('.property-name')); dumpText += text(treeElement.title.querySelector('.property-value')); TestRunner.addResult(dumpText); - if (doNotAutoExpand && !treeElement.expanded) + if (doNotAutoExpand && !treeElement.expanded) { continue; + } for (const trace of treeElement.children()) { const title = trace.title; let dumpText = ''; - if (trace.title.classList.contains('property-trace-inactive')) + if (trace.title.classList.contains('property-trace-inactive')) { dumpText += 'OVERLOADED '; + } dumpText += text(title.querySelector('.property-trace-value')); dumpText += ' - '; dumpText += text(title.querySelector('.property-trace-selector')); const link = title.querySelector('.trace-link'); - if (link) + if (link) { dumpText += ' ' + extractLinkText(link); + } TestRunner.addResult(' ' + dumpText); } @@ -201,8 +211,9 @@ for (const treeElement of children) { const property = treeElement[Elements.ComputedStyleWidget._propertySymbol]; - if (property.name === name) + if (property.name === name) { return treeElement; + } } return null; @@ -362,8 +373,9 @@ for (const block of sectionBlocks) { for (const section of block.sections) { - if (section.element.classList.contains('hidden')) + if (section.element.classList.contains('hidden')) { continue; + } dumpRenderedSection(section); } @@ -373,8 +385,9 @@ TestRunner.addResult(section._selectorElement.textContent + ' {'); const rootElement = section.propertiesTreeOutline.rootElement(); - for (let i = 0; i < rootElement.childCount(); ++i) + for (let i = 0; i < rootElement.childCount(); ++i) { dumpRenderedProperty(rootElement.childAt(i)); + } TestRunner.addResult('}'); } @@ -384,20 +397,23 @@ text += property.nameElement.textContent; text += ':'; - if (property.isExpandable()) + if (property.isExpandable()) { text += (property.expanded ? 'v' : '>'); - else + } else { text += ' '; + } text += property.valueElement.textContent; - if (property.listItemElement.classList.contains('filter-match')) + if (property.listItemElement.classList.contains('filter-match')) { text = 'F' + text.substring(1); + } TestRunner.addResult(text); - if (!property.expanded) + if (!property.expanded) { return; + } const indent = new Array(8).join(' '); @@ -406,8 +422,9 @@ let text = indent; text += String.sprintf('%s: %s', childProperty.nameElement.textContent, childProperty.valueElement.textContent); - if (childProperty.listItemElement.classList.contains('filter-match')) + if (childProperty.listItemElement.classList.contains('filter-match')) { text = 'F' + text.substring(1); + } TestRunner.addResult(text); } @@ -418,19 +435,22 @@ excludeComputed, excludeMatched, omitLonghands, includeSelectorGroupMarks, printInnerText) { const sectionBlocks = UI.panels.elements._stylesWidget._sectionBlocks; - if (!excludeComputed) + if (!excludeComputed) { ElementsTestRunner.dumpComputedStyle(false /* doNotAutoExpand */, printInnerText); + } for (const block of sectionBlocks) { for (const section of block.sections) { - if (section.style().parentRule && excludeMatched) + if (section.style().parentRule && excludeMatched) { continue; + } if (section.element.previousSibling && section.element.previousSibling.className === 'sidebar-separator') { let nodeDescription = ''; - if (section.element.previousSibling.firstElementChild) + if (section.element.previousSibling.firstElementChild) { nodeDescription = text(section.element.previousSibling.firstElementChild.shadowRoot.lastChild); + } TestRunner.addResult('======== ' + text(section.element.previousSibling) + nodeDescription + ' ========'); } @@ -445,8 +465,9 @@ }; function printStyleSection(section, omitLonghands, includeSelectorGroupMarks, printInnerText) { - if (!section) + if (!section) { return; + } TestRunner.addResult( '[expanded] ' + ((section.propertiesTreeOutline.element.classList.contains('no-affect') ? '[no-affect] ' : ''))); @@ -470,8 +491,9 @@ TestRunner.addResult(selectorText); ElementsTestRunner.dumpStyleTreeOutline(section.propertiesTreeOutline, (omitLonghands ? 1 : 2), printInnerText); - if (!section._showAllButton.classList.contains('hidden')) + if (!section._showAllButton.classList.contains('hidden')) { TestRunner.addResult(text(section._showAllButton)); + } TestRunner.addResult(''); function text(node) { @@ -482,8 +504,9 @@ function extractLinkText(element) { const anchor = element.querySelector('.devtools-link'); - if (!anchor) + if (!anchor) { return element.textContent; + } const anchorText = anchor.textContent; const info = Components.Linkifier._linkInfo(anchor); @@ -499,10 +522,11 @@ let result = ''; for (let node = element.firstChild; node; node = node.nextSibling) { - if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('selector-matches')) + if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('selector-matches')) { result += '[$' + node.textContent + '$]'; - else + } else { result += node.textContent; + } } return result; @@ -559,10 +583,11 @@ ElementsTestRunner.dumpObjectPropertySectionDeep = function(section) { function domNodeToString(node) { - if (node) + if (node) { return '\'' + node.textContent + '\''; - else + } else { return 'null'; + } } function dumpTreeElementRecursively(treeElement, prefix) { @@ -573,14 +598,16 @@ TestRunner.addResult(prefix + treeElement.title); } - for (let i = 0; i < treeElement.childCount(); i++) + for (let i = 0; i < treeElement.childCount(); i++) { dumpTreeElementRecursively(treeElement.childAt(i), prefix + ' '); + } } const childNodes = section.propertiesTreeOutline.rootElement().children(); - for (let i = 0; i < childNodes.length; i++) + for (let i = 0; i < childNodes.length; i++) { dumpTreeElementRecursively(childNodes[i], ''); + } }; @@ -595,8 +622,9 @@ for (const section of block.sections) { const treeItem = ElementsTestRunner.getFirstPropertyTreeItemForSection(section, propertyName); - if (treeItem) + if (treeItem) { return treeItem; + } } } @@ -609,8 +637,9 @@ for (let i = 0; i < outline.childCount(); ++i) { const treeItem = outline.childAt(i); - if (treeItem.name === propertyName) + if (treeItem.name === propertyName) { return treeItem; + } } return null; @@ -619,28 +648,33 @@ ElementsTestRunner.dumpStyleTreeOutline = function(treeItem, depth, printInnerText) { const children = treeItem.rootElement().children(); - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { ElementsTestRunner.dumpStyleTreeItem(children[i], '', depth || 2, printInnerText); + } }; ElementsTestRunner.dumpStyleTreeItem = function(treeItem, prefix, depth, printInnerText) { const textContent = printInnerText ? treeItem.listItemElement.innerText : TestRunner.textContentWithoutStyles(treeItem.listItemElement); - if (textContent.indexOf(' width:') !== -1 || textContent.indexOf(' height:') !== -1) + if (textContent.indexOf(' width:') !== -1 || textContent.indexOf(' height:') !== -1) { return; + } - if (treeItem.listItemElement.classList.contains('inherited')) + if (treeItem.listItemElement.classList.contains('inherited')) { return; + } let typePrefix = ''; if (treeItem.listItemElement.classList.contains('overloaded') || treeItem.listItemElement.classList.contains('inactive') || - treeItem.listItemElement.classList.contains('not-parsed-ok')) + treeItem.listItemElement.classList.contains('not-parsed-ok')) { typePrefix += '/-- overloaded --/ '; + } - if (treeItem.listItemElement.classList.contains('disabled')) + if (treeItem.listItemElement.classList.contains('disabled')) { typePrefix += '/-- disabled --/ '; + } TestRunner.addResult(prefix + typePrefix + textContent); @@ -648,8 +682,9 @@ treeItem.expand(); const children = treeItem.children(); - for (let i = 0; children && i < children.length; ++i) + for (let i = 0; children && i < children.length; ++i) { ElementsTestRunner.dumpStyleTreeItem(children[i], prefix + ' ', depth); + } } }; @@ -661,18 +696,21 @@ function dumpMap(name, map) { const result = []; - for (const id of map.keys()) + for (const id of map.keys()) { result.push(id + '=' + map.get(id)); + } - if (!result.length) + if (!result.length) { return ''; + } return name + ':[' + result.join(',') + ']'; } function markersDataDump(treeItem) { - if (treeItem._elementCloseTag) + if (treeItem._elementCloseTag) { return ''; + } let markers = ''; const node = treeItem._node; @@ -682,14 +720,16 @@ const dump = (node._subtreeMarkerCount ? 'subtreeMarkerCount:' + node._subtreeMarkerCount : ''); if (dump) { - if (markers) + if (markers) { markers += ', '; + } markers += dump; } - if (markers) + if (markers) { markers = ' [' + markers + ']'; + } } return markers; @@ -700,10 +740,11 @@ let expander; if (treeItem.isExpandable()) { - if (treeItem.expanded) + if (treeItem.expanded) { expander = '- '; - else + } else { expander = '+ '; + } } else { expander = ' '; } @@ -722,23 +763,26 @@ } } - if (resultsArray) + if (resultsArray) { resultsArray.push(value); - else + } else { TestRunner.addResult(value); + } } - if (!treeItem.expanded) + if (!treeItem.expanded) { return; + } const children = treeItem.children(); const newPrefix = (treeItem.root ? '' : prefix + ' '); for (let i = 0; depth && children && i < children.length; ++i) { - if (!children[i]._elementCloseTag) + if (!children[i]._elementCloseTag) { print(children[i], newPrefix, depth - 1); - else + } else { print(children[i], prefix, depth); + } } } @@ -755,11 +799,13 @@ const treeOutline = ElementsTestRunner.firstElementsTreeOutline(); print((rootNode ? treeOutline.findTreeElement(rootNode) : treeOutline.rootElement()), '', depth || 10000); - if (!hasHighlights) + if (!hasHighlights) { TestRunner.addResult('<No highlights>'); + } - if (callback) + if (callback) { callback(); + } } function print(treeItem, prefix, depth) { @@ -786,15 +832,17 @@ } } - if (!treeItem.expanded) + if (!treeItem.expanded) { return; + } const children = treeItem.children(); const newPrefix = (treeItem.root ? '' : prefix + ' '); for (let i = 0; depth && children && i < children.length; ++i) { - if (!children[i]._elementCloseTag) + if (!children[i]._elementCloseTag) { print(children[i], newPrefix, depth - 1); + } } } }; @@ -841,39 +889,46 @@ }; ElementsTestRunner.dumpDOMAgentTree = function(node) { - if (!TestRunner.domModel._document) + if (!TestRunner.domModel._document) { return; + } function dump(node, prefix) { TestRunner.addResult(prefix + node.nodeName()); prefix = prefix + ' '; - if (node.templateContent()) + if (node.templateContent()) { dump(node.templateContent(), prefix); + } - if (node.contentDocument()) + if (node.contentDocument()) { dump(node.contentDocument(), prefix); + } - if (node.importedDocument()) + if (node.importedDocument()) { dump(node.importedDocument(), prefix); + } const shadowRoots = node.shadowRoots(); - for (let i = 0; i < shadowRoots.length; ++i) + for (let i = 0; i < shadowRoots.length; ++i) { dump(shadowRoots[i], prefix); + } const children = node.children(); - for (let i = 0; children && i < children.length; ++i) + for (let i = 0; children && i < children.length; ++i) { dump(children[i], prefix); + } } dump(node, ''); }; ElementsTestRunner.rangeText = function(range) { - if (!range) + if (!range) { return '[undefined-undefined]'; + } return '[' + range.startLine + ':' + range.startColumn + '-' + range.endLine + ':' + range.endColumn + ']'; }; @@ -941,31 +996,36 @@ const indent = ' '; ElementsTestRunner.dumpRulesArray = function(rules, currentIndent) { - if (!rules) + if (!rules) { return; + } currentIndent = currentIndent || ''; - for (let i = 0; i < rules.length; ++i) + for (let i = 0; i < rules.length; ++i) { ElementsTestRunner.dumpRule(rules[i], currentIndent); + } }; ElementsTestRunner.dumpRuleMatchesArray = function(matches, currentIndent) { - if (!matches) + if (!matches) { return; + } currentIndent = currentIndent || ''; - for (let i = 0; i < matches.length; ++i) + for (let i = 0; i < matches.length; ++i) { ElementsTestRunner.dumpRule(matches[i].rule, currentIndent); + } }; ElementsTestRunner.dumpRule = function(rule, currentIndent) { function selectorRange() { const selectors = rule.selectorList.selectors; - if (!selectors || !selectors[0].range) + if (!selectors || !selectors[0].range) { return ''; + } const ranges = []; @@ -1071,8 +1131,9 @@ }; ElementsTestRunner.dumpBreadcrumb = function(message) { - if (message) + if (message) { TestRunner.addResult(message + ':'); + } const result = []; const crumbs = UI.panels.elements._breadcrumbs.crumbsElement; @@ -1090,8 +1151,9 @@ const selectors = []; const matchingSelectors = matchedStyles.matchingSelectors(rule); - for (let i = 0; i < matchingSelectors.length; ++i) + for (let i = 0; i < matchingSelectors.length; ++i) { selectors.push(rule.selectors[matchingSelectors[i]].text); + } return '[' + selectors.join(', ') + ']'; }; @@ -1113,8 +1175,9 @@ function onBlankSection(selector, callback) { const section = ElementsTestRunner.firstMatchedStyleSection(); - if (typeof selector === 'string') + if (typeof selector === 'string') { section._selectorElement.textContent = selector; + } section._selectorElement.dispatchEvent(TestRunner.createKeyEvent('Enter')); ElementsTestRunner.waitForSelectorCommitted(callback.bind(null, section)); @@ -1139,8 +1202,9 @@ if (!info) { TestRunner.addResult(`${idValue}: No distance info`); } else { - if (info['style']) + if (info['style']) { info['style'] = '<style data>'; + } TestRunner.addResult(idValue + JSON.stringify(info, null, 2)); } callback(); @@ -1154,8 +1218,9 @@ if (!info) { TestRunner.addResult(`${idValue}: No style info`); } else { - if (info['font-family']) + if (info['font-family']) { info['font-family'] = '<font-family value>'; + } TestRunner.addResult(idValue + JSON.stringify(info, null, 2)); } };
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/SetOuterHTMLTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/SetOuterHTMLTestRunner.js index 485eba4..adf3f7d0 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/SetOuterHTMLTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/SetOuterHTMLTestRunner.js
@@ -28,8 +28,9 @@ for (const key in SDK.DOMModel.Events) { const eventName = SDK.DOMModel.Events[key]; - if (eventName === SDK.DOMModel.Events.MarkersChanged || eventName === SDK.DOMModel.Events.DOMMutated) + if (eventName === SDK.DOMModel.Events.MarkersChanged || eventName === SDK.DOMModel.Events.DOMMutated) { continue; + } TestRunner.domModel.addEventListener( eventName, ElementsTestRunner.recordEvent.bind(ElementsTestRunner, eventName)); @@ -40,15 +41,17 @@ }; ElementsTestRunner.recordEvent = function(eventName, event) { - if (!event.data) + if (!event.data) { return; + } const node = event.data.node || event.data; const parent = event.data.parent; for (let currentNode = parent || node; currentNode; currentNode = currentNode.parentNode) { - if (currentNode.getAttribute('id') === 'output') + if (currentNode.getAttribute('id') === 'output') { return; + } } ElementsTestRunner.events.push('Event ' + eventName.toString() + ': ' + node.nodeName()); @@ -94,8 +97,9 @@ TestRunner.addResult('Wrapper identity: ' + result.value); ElementsTestRunner.events.sort(); - for (let i = 0; i < ElementsTestRunner.events.length; ++i) + for (let i = 0; i < ElementsTestRunner.events.length; ++i) { TestRunner.addResult(ElementsTestRunner.events[i]); + } ElementsTestRunner.events = []; const text = await TestRunner.DOMAgent.getOuterHTML(ElementsTestRunner.containerId); @@ -103,8 +107,9 @@ TestRunner.addResult(text); TestRunner.addResult('==========>8=========='); - if (last) + if (last) { TestRunner.addResult('\n\n\n'); + } next(); };
diff --git a/third_party/blink/renderer/devtools/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js b/third_party/blink/renderer/devtools/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js index 7e7e946..49eb5fff 100644 --- a/third_party/blink/renderer/devtools/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js
@@ -14,8 +14,9 @@ for (let i = 0; i < medias.length; ++i) { const media = medias[i]; - if (!media.range) + if (!media.range) { continue; + } ranges.push({range: media.range, name: 'media #' + i}); } @@ -23,14 +24,16 @@ for (let i = 0; i < rule.selectors.length; ++i) { const selector = rule.selectors[i]; - if (!selector.range) + if (!selector.range) { continue; + } ranges.push({range: selector.range, name: 'selector #' + i}); } - if (rule.style.range) + if (rule.style.range) { ranges.push({range: rule.style.range, name: 'style range'}); + } const properties = rule.style.allProperties(); @@ -38,8 +41,9 @@ for (let i = 0; i < properties.length; ++i) { const property = properties[i]; - if (!property.range) + if (!property.range) { continue; + } ranges.push({range: property.range, name: 'property >>' + property.text + '<<'}); } @@ -120,8 +124,9 @@ for (const section of block.sections) { const rule = section.style().parentRule; - if (rule) + if (rule) { rules.push(rule); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/AdvancedApp.js b/third_party/blink/renderer/devtools/front_end/emulation/AdvancedApp.js index 80754b5..49c8d16 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/AdvancedApp.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/AdvancedApp.js
@@ -15,8 +15,9 @@ * @return {!Emulation.AdvancedApp} */ static _instance() { - if (!Emulation.AdvancedApp._appInstance) + if (!Emulation.AdvancedApp._appInstance) { Emulation.AdvancedApp._appInstance = new Emulation.AdvancedApp(); + } return Emulation.AdvancedApp._appInstance; } @@ -56,11 +57,13 @@ * @param {!Common.Event} event */ _openToolboxWindow(event) { - if (/** @type {string} */ (event.data.to) !== Components.DockController.State.Undocked) + if (/** @type {string} */ (event.data.to) !== Components.DockController.State.Undocked) { return; + } - if (this._toolboxWindow) + if (this._toolboxWindow) { return; + } const url = window.location.href.replace('devtools_app.html', 'toolbox.html'); this._toolboxWindow = window.open(url, undefined); @@ -82,10 +85,11 @@ } _updateDeviceModeView() { - if (this._isDocked()) + if (this._isDocked()) { this._rootSplitWidget.setMainWidget(this._deviceModeView); - else if (this._toolboxRootView) + } else if (this._toolboxRootView) { this._deviceModeView.show(this._toolboxRootView.element); + } } /** @@ -125,8 +129,9 @@ */ _onAfterDockSideChange(event) { // We may get here on the first dock side change while loading without BeforeDockSideChange. - if (!this._changingDockSide) + if (!this._changingDockSide) { return; + } if (/** @type {string} */ (event.data.from) === Components.DockController.State.Undocked) { // Restore docked layout in case of smooth transition. this._updateForDocked(/** @type {string} */ (event.data.to)); @@ -169,13 +174,16 @@ * @param {!Common.Event} event */ _onSetInspectedPageBounds(event) { - if (this._changingDockSide) + if (this._changingDockSide) { return; + } const window = this._inspectedPagePlaceholder.element.window(); - if (!window.innerWidth || !window.innerHeight) + if (!window.innerWidth || !window.innerHeight) { return; - if (!this._inspectedPagePlaceholder.isShowing()) + } + if (!this._inspectedPagePlaceholder.isShowing()) { return; + } const bounds = /** @type {{x: number, y: number, width: number, height: number}} */ (event.data); console.timeStamp('AdvancedApp.setInspectedPageBounds'); InspectorFrontendHost.setInspectedPageBounds(bounds);
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeModel.js b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeModel.js index 27510aa..348889d 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeModel.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeModel.js
@@ -20,22 +20,27 @@ this._scaleSetting = Common.settings.createSetting('emulation.deviceScale', 1); // We've used to allow zero before. - if (!this._scaleSetting.get()) + if (!this._scaleSetting.get()) { this._scaleSetting.set(1); + } this._scaleSetting.addChangeListener(this._scaleSettingChanged, this); this._widthSetting = Common.settings.createSetting('emulation.deviceWidth', 400); - if (this._widthSetting.get() < Emulation.DeviceModeModel.MinDeviceSize) + if (this._widthSetting.get() < Emulation.DeviceModeModel.MinDeviceSize) { this._widthSetting.set(Emulation.DeviceModeModel.MinDeviceSize); - if (this._widthSetting.get() > Emulation.DeviceModeModel.MaxDeviceSize) + } + if (this._widthSetting.get() > Emulation.DeviceModeModel.MaxDeviceSize) { this._widthSetting.set(Emulation.DeviceModeModel.MaxDeviceSize); + } this._widthSetting.addChangeListener(this._widthSettingChanged, this); this._heightSetting = Common.settings.createSetting('emulation.deviceHeight', 0); - if (this._heightSetting.get() && this._heightSetting.get() < Emulation.DeviceModeModel.MinDeviceSize) + if (this._heightSetting.get() && this._heightSetting.get() < Emulation.DeviceModeModel.MinDeviceSize) { this._heightSetting.set(Emulation.DeviceModeModel.MinDeviceSize); - if (this._heightSetting.get() > Emulation.DeviceModeModel.MaxDeviceSize) + } + if (this._heightSetting.get() > Emulation.DeviceModeModel.MaxDeviceSize) { this._heightSetting.set(Emulation.DeviceModeModel.MaxDeviceSize); + } this._heightSetting.addChangeListener(this._heightSettingChanged, this); this._uaSetting = Common.settings.createSetting('emulation.deviceUA', Emulation.DeviceModeModel.UA.Mobile); @@ -75,14 +80,15 @@ let valid = false; let errorMessage; - if (!/^[\d]+$/.test(value)) + if (!/^[\d]+$/.test(value)) { errorMessage = ls`Width must be a number.`; - else if (value > Emulation.DeviceModeModel.MaxDeviceSize) + } else if (value > Emulation.DeviceModeModel.MaxDeviceSize) { errorMessage = ls`Width must be less than or equal to ${Emulation.DeviceModeModel.MaxDeviceSize}.`; - else if (value < Emulation.DeviceModeModel.MinDeviceSize) + } else if (value < Emulation.DeviceModeModel.MinDeviceSize) { errorMessage = ls`Width must be greater than or equal to ${Emulation.DeviceModeModel.MinDeviceSize}.`; - else + } else { valid = true; + } return {valid, errorMessage}; } @@ -95,14 +101,15 @@ let valid = false; let errorMessage; - if (!/^[\d]+$/.test(value)) + if (!/^[\d]+$/.test(value)) { errorMessage = ls`Height must be a number.`; - else if (value > Emulation.DeviceModeModel.MaxDeviceSize) + } else if (value > Emulation.DeviceModeModel.MaxDeviceSize) { errorMessage = ls`Height must be less than or equal to ${Emulation.DeviceModeModel.MaxDeviceSize}.`; - else if (value < Emulation.DeviceModeModel.MinDeviceSize) + } else if (value < Emulation.DeviceModeModel.MinDeviceSize) { errorMessage = ls`Height must be greater than or equal to ${Emulation.DeviceModeModel.MinDeviceSize}.`; - else + } else { valid = true; + } return {valid, errorMessage}; } @@ -169,8 +176,9 @@ this._mode = null; } - if (type !== Emulation.DeviceModeModel.Type.None) + if (type !== Emulation.DeviceModeModel.Type.None) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.DeviceModeEnabled); + } this._calculateAndEmulate(resetPageScaleFactor); } @@ -198,8 +206,9 @@ setHeight(height) { const max = Math.min(Emulation.DeviceModeModel.MaxDeviceSize, this._preferredScaledHeight()); height = Math.max(Math.min(height, max), 0); - if (height === this._preferredScaledHeight()) + if (height === this._preferredScaledHeight()) { height = 0; + } this._heightSetting.set(height); } @@ -406,8 +415,9 @@ * @param {!SDK.EmulationModel} emulationModel */ modelRemoved(emulationModel) { - if (this._emulationModel === emulationModel) + if (this._emulationModel === emulationModel) { this._emulationModel = null; + } } /** @@ -460,11 +470,13 @@ */ _currentOutline() { let outline = new UI.Insets(0, 0, 0, 0); - if (this._type !== Emulation.DeviceModeModel.Type.Device) + if (this._type !== Emulation.DeviceModeModel.Type.Device) { return outline; + } const orientation = this._device.orientationByName(this._mode.orientation); - if (this._deviceOutlineSetting.get()) + if (this._deviceOutlineSetting.get()) { outline = orientation.outlineInsets || outline; + } return outline; } @@ -472,8 +484,9 @@ * @return {!UI.Insets} */ _currentInsets() { - if (this._type !== Emulation.DeviceModeModel.Type.Device) + if (this._type !== Emulation.DeviceModeModel.Type.Device) { return new UI.Insets(0, 0, 0, 0); + } return this._mode.insets; } @@ -481,8 +494,9 @@ * @param {boolean} resetPageScaleFactor */ _calculateAndEmulate(resetPageScaleFactor) { - if (!this._emulationModel) + if (!this._emulationModel) { this._onModelAvailable = this._calculateAndEmulate.bind(this, resetPageScaleFactor); + } const mobile = this._isMobile(); if (this._type === Emulation.DeviceModeModel.Type.Device) { const orientation = this._device.orientationByName(this._mode.orientation); @@ -514,11 +528,13 @@ this._applyTouch(false, false); } else if (this._type === Emulation.DeviceModeModel.Type.Responsive) { let screenWidth = this._widthSetting.get(); - if (!screenWidth || screenWidth > this._preferredScaledWidth()) + if (!screenWidth || screenWidth > this._preferredScaledWidth()) { screenWidth = this._preferredScaledWidth(); + } let screenHeight = this._heightSetting.get(); - if (!screenHeight || screenHeight > this._preferredScaledHeight()) + if (!screenHeight || screenHeight > this._preferredScaledHeight()) { screenHeight = this._preferredScaledHeight(); + } const defaultDeviceScaleFactor = mobile ? Emulation.DeviceModeModel.defaultMobileScaleFactor : 0; this._fitScale = this._calculateFitScale(this._widthSetting.get(), this._heightSetting.get()); this._appliedUserAgentType = this._uaSetting.get(); @@ -535,8 +551,9 @@ this._uaSetting.get() === Emulation.DeviceModeModel.UA.Mobile); } const overlayModel = this._emulationModel ? this._emulationModel.overlayModel() : null; - if (overlayModel) + if (overlayModel) { overlayModel.setShowViewportSizeOnResize(this._type === Emulation.DeviceModeModel.Type.None); + } this.dispatchEventToListeners(Emulation.DeviceModeModel.Events.Updated); } @@ -560,12 +577,15 @@ let sharpScale = scale; while (sharpScale > scale * 0.7) { let sharp = true; - if (screenWidth) + if (screenWidth) { sharp = sharp && Number.isInteger((screenWidth - insetsWidth) * sharpScale / 100); - if (screenHeight) + } + if (screenHeight) { sharp = sharp && Number.isInteger((screenHeight - insetsHeight) * sharpScale / 100); - if (sharp) + } + if (sharp) { return sharpScale / 100; + } sharpScale -= 1; } return scale / 100; @@ -646,11 +666,13 @@ pageHeight = 0; } - if (!this._emulationModel) + if (!this._emulationModel) { return; + } - if (resetPageScaleFactor) + if (resetPageScaleFactor) { this._emulationModel.resetPageScaleFactor(); + } if (pageWidth || pageHeight || mobile || deviceScaleFactor || scale !== 1 || screenOrientation) { const metrics = { width: pageWidth, @@ -664,8 +686,9 @@ positionY: positionY, dontSetVisibleSize: true }; - if (screenOrientation) + if (screenOrientation) { metrics.screenOrientation = {type: screenOrientation, angle: screenOrientationAngle}; + } this._emulationModel.emulateDevice(metrics); } else { this._emulationModel.emulateDevice(null); @@ -680,19 +703,22 @@ async captureScreenshot(fullSize, clip) { const screenCaptureModel = this._emulationModel ? this._emulationModel.target().model(SDK.ScreenCaptureModel) : null; - if (!screenCaptureModel) + if (!screenCaptureModel) { return null; + } const overlayModel = this._emulationModel ? this._emulationModel.overlayModel() : null; - if (overlayModel) + if (overlayModel) { overlayModel.setShowViewportSizeOnResize(false); + } // Emulate full size device if necessary. let deviceMetrics; if (fullSize) { const metrics = await screenCaptureModel.fetchLayoutMetrics(); - if (!metrics) + if (!metrics) { return null; + } // Cap the height to not hit the GPU limit. const contentHeight = Math.min((1 << 14) / this._appliedDeviceScaleFactor, metrics.contentHeight); @@ -739,8 +765,9 @@ _applyTouch(touchEnabled, mobile) { this._touchEnabled = touchEnabled; this._touchMobile = mobile; - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.emulateTouch(touchEnabled, mobile); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeToolbar.js b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeToolbar.js index 00ce4a2..c8445957 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeToolbar.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeToolbar.js
@@ -117,8 +117,9 @@ * @return {{valid: boolean, errorMessage: (string|undefined)}} */ function validateHeight(value) { - if (!value) + if (!value) { return {valid: true}; + } return Emulation.DeviceModeModel.heightValidator(value); } } @@ -317,8 +318,9 @@ * @param {boolean=} disabled */ function appendToggleItem(section, setting, title1, title2, disabled) { - if (typeof disabled === 'undefined') + if (typeof disabled === 'undefined') { disabled = model.type() === Emulation.DeviceModeModel.Type.None; + } section.appendItem(setting.get() ? title1 : title2, setting.set.bind(setting, !setting.get()), disabled); } } @@ -407,8 +409,9 @@ * @this {Emulation.DeviceModeToolbar} */ function appendGroup(devices) { - if (!devices.length) + if (!devices.length) { return; + } const section = contextMenu.section(); for (const device of devices) { section.appendCheckboxItem( @@ -422,15 +425,17 @@ */ _deviceListChanged() { const device = this._model.device(); - if (!device) + if (!device) { return; + } const devices = this._allDevices(); if (devices.indexOf(device) === -1) { - if (devices.length) + if (devices.length) { this._emulateDevice(devices[0]); - else + } else { this._model.emulate(Emulation.DeviceModeModel.Type.Responsive, null, null); + } } } @@ -481,13 +486,15 @@ */ function addOrientation(orientation, title) { const modes = device.modesForOrientation(orientation); - if (!modes.length) + if (!modes.length) { return; + } if (modes.length === 1) { addMode(modes[0], title); } else { - for (let index = 0; index < modes.length; index++) + for (let index = 0; index < modes.length; index++) { addMode(modes[index], title + ' \u2013 ' + modes[index].title); + } } } @@ -556,10 +563,12 @@ } let deviceItemTitle = Common.UIString('None'); - if (this._model.type() === Emulation.DeviceModeModel.Type.Responsive) + if (this._model.type() === Emulation.DeviceModeModel.Type.Responsive) { deviceItemTitle = Common.UIString('Responsive'); - if (this._model.type() === Emulation.DeviceModeModel.Type.Device) + } + if (this._model.type() === Emulation.DeviceModeModel.Type.Device) { deviceItemTitle = this._model.device().title; + } this._deviceSelectItem.setText(deviceItemTitle); if (this._model.device() !== this._cachedModelDevice) {
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeView.js b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeView.js index 2691b18..1ea2b77 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeView.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeView.js
@@ -116,10 +116,12 @@ const resizer = new UI.ResizerWidget(); resizer.addElement(element); let cursor = widthFactor ? 'ew-resize' : 'ns-resize'; - if (widthFactor * heightFactor > 0) + if (widthFactor * heightFactor > 0) { cursor = 'nwse-resize'; - if (widthFactor * heightFactor < 0) + } + if (widthFactor * heightFactor < 0) { cursor = 'nesw-resize'; + } resizer.setCursor(cursor); resizer.addEventListener(UI.ResizerWidget.Events.ResizeStart, this._onResizeStart, this); resizer.addEventListener( @@ -143,8 +145,9 @@ * @param {!Common.Event} event */ _onResizeUpdate(widthFactor, heightFactor, event) { - if (event.data.shiftKey !== !!this._slowPositionStart) + if (event.data.shiftKey !== !!this._slowPositionStart) { this._slowPositionStart = event.data.shiftKey ? {x: event.data.currentX, y: event.data.currentY} : null; + } let cssOffsetX = event.data.currentX - event.data.startX; let cssOffsetY = event.data.currentY - event.data.startY; @@ -159,16 +162,19 @@ const dipOffsetX = cssOffsetX * UI.zoomManager.zoomFactor(); let newWidth = this._resizeStart.width + dipOffsetX * widthFactor; newWidth = Math.round(newWidth / this._model.scale()); - if (newWidth >= Emulation.DeviceModeModel.MinDeviceSize && newWidth <= Emulation.DeviceModeModel.MaxDeviceSize) + if (newWidth >= Emulation.DeviceModeModel.MinDeviceSize && newWidth <= Emulation.DeviceModeModel.MaxDeviceSize) { this._model.setWidth(newWidth); + } } if (heightFactor) { const dipOffsetY = cssOffsetY * UI.zoomManager.zoomFactor(); let newHeight = this._resizeStart.height + dipOffsetY * heightFactor; newHeight = Math.round(newHeight / this._model.scale()); - if (newHeight >= Emulation.DeviceModeModel.MinDeviceSize && newHeight <= Emulation.DeviceModeModel.MaxDeviceSize) + if (newHeight >= Emulation.DeviceModeModel.MinDeviceSize && + newHeight <= Emulation.DeviceModeModel.MaxDeviceSize) { this._model.setHeight(newHeight); + } } } @@ -192,8 +198,9 @@ element.style.height = rect.height + 'px'; } - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const zoomFactor = UI.zoomManager.zoomFactor(); let callDoResize = false; @@ -237,10 +244,11 @@ const mediaInspectorVisible = this._showMediaInspectorSetting.get() && this._model.type() !== Emulation.DeviceModeModel.Type.None; if (mediaInspectorVisible !== this._cachedMediaInspectorVisible) { - if (mediaInspectorVisible) + if (mediaInspectorVisible) { this._mediaInspector.show(this._mediaInspectorContainer); - else + } else { this._mediaInspector.detach(); + } contentAreaResized = true; callDoResize = true; this._cachedMediaInspectorVisible = mediaInspectorVisible; @@ -263,8 +271,9 @@ if (this._model.scale() !== this._cachedScale) { updateRulers = true; callDoResize = true; - for (const block of this._presetBlocks) + for (const block of this._presetBlocks) { block.style.width = block.__width * this._model.scale() + 'px'; + } this._cachedScale = this._model.scale(); } @@ -272,8 +281,9 @@ this._loadImage(this._screenImage, this._model.screenImage()); this._loadImage(this._outlineImage, this._model.outlineImage()); this._mediaInspector.setAxisTransform(this._model.scale()); - if (callDoResize) + if (callDoResize) { this.doResize(); + } if (updateRulers) { this._topRuler.render(this._model.scale()); this._leftRuler.render(this._model.scale()); @@ -284,8 +294,9 @@ this._cachedCssScreenRect ? this._cachedCssScreenRect.left : 0, this._cachedCssScreenRect ? this._cachedCssScreenRect.top : 0); } - if (contentAreaResized) + if (contentAreaResized) { this._contentAreaResized(); + } } /** @@ -293,11 +304,13 @@ * @param {string} srcset */ _loadImage(element, srcset) { - if (element.getAttribute('srcset') === srcset) + if (element.getAttribute('srcset') === srcset) { return; + } element.setAttribute('srcset', srcset); - if (!srcset) + if (!srcset) { element.classList.toggle('hidden', true); + } } /** @@ -312,8 +325,9 @@ * @param {!Element} element */ setNonEmulatedAvailableSize(element) { - if (this._model.type() !== Emulation.DeviceModeModel.Type.None) + if (this._model.type() !== Emulation.DeviceModeModel.Type.None) { return; + } const zoomFactor = UI.zoomManager.zoomFactor(); const rect = element.getBoundingClientRect(); const availableSize = new UI.Size(Math.max(rect.width * zoomFactor, 1), Math.max(rect.height * zoomFactor, 1)); @@ -353,8 +367,9 @@ * @override */ onResize() { - if (this.isShowing()) + if (this.isShowing()) { this._contentAreaResized(); + } } /** @@ -377,8 +392,9 @@ */ async captureScreenshot() { const screenshot = await this._model.captureScreenshot(false); - if (screenshot === null) + if (screenshot === null) { return; + } const pageImage = new Image(); pageImage.src = 'data:image/png;base64,' + screenshot; @@ -396,10 +412,12 @@ const ctx = canvas.getContext('2d'); ctx.imageSmoothingEnabled = false; - if (this._model.outlineImage()) + if (this._model.outlineImage()) { await this._paintImage(ctx, this._model.outlineImage(), outlineRect.relativeTo(outlineRect)); - if (this._model.screenImage()) + } + if (this._model.screenImage()) { await this._paintImage(ctx, this._model.screenImage(), screenRect.relativeTo(outlineRect)); + } ctx.drawImage(pageImage, Math.floor(contentLeft), Math.floor(contentTop)); this._saveScreenshot(canvas); }; @@ -410,8 +428,9 @@ */ async captureFullSizeScreenshot() { const screenshot = await this._model.captureScreenshot(true); - if (screenshot === null) + if (screenshot === null) { return; + } return this._saveScreenshotBase64(screenshot); } @@ -421,8 +440,9 @@ */ async captureAreaScreenshot(clip) { const screenshot = await this._model.captureScreenshot(false, clip); - if (screenshot === null) + if (screenshot === null) { return; + } return this._saveScreenshotBase64(screenshot); } @@ -468,8 +488,9 @@ _saveScreenshot(canvas) { const url = this._model.inspectedURL(); let fileName = url ? url.trimURL().removeURLFragment() : ''; - if (this._model.type() === Emulation.DeviceModeModel.Type.Device) + if (this._model.type() === Emulation.DeviceModeModel.Type.Device) { fileName += Common.UIString('(%s)', this._model.device().title); + } const link = createElement('a'); link.download = fileName + '.png'; canvas.toBlob(blob => { @@ -531,41 +552,50 @@ const dipSize = size * zoomFactor / this._scale; const count = Math.ceil(dipSize / 5); let step = 1; - if (this._scale < 0.8) + if (this._scale < 0.8) { step = 2; - if (this._scale < 0.6) + } + if (this._scale < 0.6) { step = 4; - if (this._scale < 0.4) + } + if (this._scale < 0.4) { step = 8; - if (this._scale < 0.2) + } + if (this._scale < 0.2) { step = 16; - if (this._scale < 0.1) + } + if (this._scale < 0.1) { step = 32; + } for (let i = count; i < this._count; i++) { - if (!(i % step)) + if (!(i % step)) { this._contentElement.lastChild.remove(); + } } for (let i = this._count; i < count; i++) { - if (i % step) + if (i % step) { continue; + } const marker = this._contentElement.createChild('div', 'device-mode-ruler-marker'); if (i) { - if (this._horizontal) + if (this._horizontal) { marker.style.left = (5 * i) * this._scale / zoomFactor + 'px'; - else + } else { marker.style.top = (5 * i) * this._scale / zoomFactor + 'px'; + } if (!(i % 20)) { const text = marker.createChild('div', 'device-mode-ruler-text'); text.textContent = i * 5; text.addEventListener('click', this._onMarkerClick.bind(this, i * 5), false); } } - if (!(i % 10)) + if (!(i % 10)) { marker.classList.add('device-mode-ruler-marker-large'); - else if (!(i % 5)) + } else if (!(i % 5)) { marker.classList.add('device-mode-ruler-marker-medium'); + } } this._count = count;
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeWrapper.js b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeWrapper.js index dc0b3e7d..91f0680 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeWrapper.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/DeviceModeWrapper.js
@@ -34,15 +34,17 @@ * @return {boolean} */ _captureScreenshot(fullSize, clip) { - if (!this._deviceModeView) + if (!this._deviceModeView) { this._deviceModeView = new Emulation.DeviceModeView(); + } this._deviceModeView.setNonEmulatedAvailableSize(this._inspectedPagePlaceholder.element); - if (fullSize) + if (fullSize) { this._deviceModeView.captureFullSizeScreenshot(); - else if (clip) + } else if (clip) { this._deviceModeView.captureAreaScreenshot(clip); - else + } else { this._deviceModeView.captureScreenshot(); + } return true; } @@ -61,19 +63,22 @@ this._toggleDeviceModeAction.setToggled(this._showDeviceModeSetting.get()); if (!force) { const showing = this._deviceModeView && this._deviceModeView.isShowing(); - if (this._showDeviceModeSetting.get() === showing) + if (this._showDeviceModeSetting.get() === showing) { return; + } } if (this._showDeviceModeSetting.get()) { - if (!this._deviceModeView) + if (!this._deviceModeView) { this._deviceModeView = new Emulation.DeviceModeView(); + } this._deviceModeView.show(this.element); this._inspectedPagePlaceholder.clearMinimumSize(); this._inspectedPagePlaceholder.show(this._deviceModeView.element); } else { - if (this._deviceModeView) + if (this._deviceModeView) { this._deviceModeView.detach(); + } this._inspectedPagePlaceholder.restoreMinimumSize(); this._inspectedPagePlaceholder.show(this.element); } @@ -102,8 +107,9 @@ case 'emulation.capture-node-screenshot': { const node = UI.context.flavor(SDK.DOMNode); - if (!node) + if (!node) { return true; + } async function captureClip() { const object = await node.resolveToObject(); const result = await object.callFunction(function() {
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/DevicesSettingsTab.js b/third_party/blink/renderer/devtools/front_end/emulation/DevicesSettingsTab.js index d975994..3148155 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/DevicesSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/DevicesSettingsTab.js
@@ -46,21 +46,24 @@ } _devicesUpdated() { - if (this._muteUpdate) + if (this._muteUpdate) { return; + } this._list.clear(); let devices = this._emulatedDevicesList.custom().slice(); - for (let i = 0; i < devices.length; ++i) + for (let i = 0; i < devices.length; ++i) { this._list.appendItem(devices[i], true); + } this._list.appendSeparator(); devices = this._emulatedDevicesList.standard().slice(); devices.sort(Emulation.EmulatedDevice.deviceComparator); - for (let i = 0; i < devices.length; ++i) + for (let i = 0; i < devices.length; ++i) { this._list.appendItem(devices[i], false); + } } /** @@ -68,10 +71,11 @@ */ _muteAndSaveDeviceList(custom) { this._muteUpdate = true; - if (custom) + if (custom) { this._emulatedDevicesList.saveCustomDevices(); - else + } else { this._emulatedDevicesList.saveStandardDevices(); + } this._muteUpdate = false; } @@ -154,14 +158,17 @@ {title: '', orientation: Emulation.EmulatedDevice.Horizontal, insets: new UI.Insets(0, 0, 0, 0), image: null}); device.capabilities = []; const uaType = editor.control('ua-type').value; - if (uaType === Emulation.DeviceModeModel.UA.Mobile || uaType === Emulation.DeviceModeModel.UA.MobileNoTouch) + if (uaType === Emulation.DeviceModeModel.UA.Mobile || uaType === Emulation.DeviceModeModel.UA.MobileNoTouch) { device.capabilities.push(Emulation.EmulatedDevice.Capability.Mobile); - if (uaType === Emulation.DeviceModeModel.UA.Mobile || uaType === Emulation.DeviceModeModel.UA.DesktopTouch) + } + if (uaType === Emulation.DeviceModeModel.UA.Mobile || uaType === Emulation.DeviceModeModel.UA.DesktopTouch) { device.capabilities.push(Emulation.EmulatedDevice.Capability.Touch); - if (isNew) + } + if (isNew) { this._emulatedDevicesList.addCustomDevice(device); - else + } else { this._emulatedDevicesList.saveCustomDevices(); + } this._addCustomButton.scrollIntoViewIfNeeded(); this._addCustomButton.focus(); } @@ -180,10 +187,11 @@ editor.control('scale').value = this._toNumericInputValue(device.deviceScaleFactor); editor.control('user-agent').value = device.userAgent; let uaType; - if (device.mobile()) + if (device.mobile()) { uaType = device.touch() ? Emulation.DeviceModeModel.UA.Mobile : Emulation.DeviceModeModel.UA.MobileNoTouch; - else + } else { uaType = device.touch() ? Emulation.DeviceModeModel.UA.DesktopTouch : Emulation.DeviceModeModel.UA.Desktop; + } editor.control('ua-type').value = uaType; return editor; } @@ -192,8 +200,9 @@ * @return {!UI.ListWidget.Editor} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -234,12 +243,13 @@ let errorMessage; const value = input.value.trim(); - if (value.length >= Emulation.DeviceModeModel.MaxDeviceNameLength) + if (value.length >= Emulation.DeviceModeModel.MaxDeviceNameLength) { errorMessage = ls`Device name must be less than ${Emulation.DeviceModeModel.MaxDeviceNameLength} characters.`; - else if (value.length === 0) + } else if (value.length === 0) { errorMessage = ls`Device name cannot be empty.`; - else + } else { valid = true; + } return {valid, errorMessage}; }
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/EmulatedDevices.js b/third_party/blink/renderer/devtools/front_end/emulation/EmulatedDevices.js index 732abc9..81d092ed 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/EmulatedDevices.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/EmulatedDevices.js
@@ -47,13 +47,15 @@ */ function parseValue(object, key, type, defaultValue) { if (typeof object !== 'object' || object === null || !object.hasOwnProperty(key)) { - if (typeof defaultValue !== 'undefined') + if (typeof defaultValue !== 'undefined') { return defaultValue; + } throw new Error('Emulated device is missing required property \'' + key + '\''); } const value = object[key]; - if (typeof value !== type || value === null) + if (typeof value !== type || value === null) { throw new Error('Emulated device property \'' + key + '\' has wrong type \'' + typeof value + '\''); + } return value; } @@ -64,8 +66,9 @@ */ function parseIntValue(object, key) { const value = /** @type {number} */ (parseValue(object, key, 'number')); - if (value !== Math.abs(value)) + if (value !== Math.abs(value)) { throw new Error('Emulated device value \'' + key + '\' must be integer'); + } return value; } @@ -88,19 +91,22 @@ result.width = parseIntValue(json, 'width'); if (result.width < 0 || result.width > Emulation.DeviceModeModel.MaxDeviceSize || - result.width < Emulation.DeviceModeModel.MinDeviceSize) + result.width < Emulation.DeviceModeModel.MinDeviceSize) { throw new Error('Emulated device has wrong width: ' + result.width); + } result.height = parseIntValue(json, 'height'); if (result.height < 0 || result.height > Emulation.DeviceModeModel.MaxDeviceSize || - result.height < Emulation.DeviceModeModel.MinDeviceSize) + result.height < Emulation.DeviceModeModel.MinDeviceSize) { throw new Error('Emulated device has wrong height: ' + result.height); + } const outlineInsets = parseValue(json['outline'], 'insets', 'object', null); if (outlineInsets) { result.outlineInsets = parseInsets(outlineInsets); - if (result.outlineInsets.left < 0 || result.outlineInsets.top < 0) + if (result.outlineInsets.left < 0 || result.outlineInsets.top < 0) { throw new Error('Emulated device has wrong outline insets'); + } result.outlineImage = /** @type {string} */ (parseValue(json['outline'], 'image', 'string')); } return /** @type {!Emulation.EmulatedDevice.Orientation} */ (result); @@ -113,39 +119,45 @@ result.userAgent = SDK.MultitargetNetworkManager.patchUserAgentWithChromeVersion(rawUserAgent); const capabilities = parseValue(json, 'capabilities', 'object', []); - if (!Array.isArray(capabilities)) + if (!Array.isArray(capabilities)) { throw new Error('Emulated device capabilities must be an array'); + } result.capabilities = []; for (let i = 0; i < capabilities.length; ++i) { - if (typeof capabilities[i] !== 'string') + if (typeof capabilities[i] !== 'string') { throw new Error('Emulated device capability must be a string'); + } result.capabilities.push(capabilities[i]); } result.deviceScaleFactor = /** @type {number} */ (parseValue(json['screen'], 'device-pixel-ratio', 'number')); - if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100) + if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100) { throw new Error('Emulated device has wrong deviceScaleFactor: ' + result.deviceScaleFactor); + } result.vertical = parseOrientation(parseValue(json['screen'], 'vertical', 'object')); result.horizontal = parseOrientation(parseValue(json['screen'], 'horizontal', 'object')); const modes = parseValue(json, 'modes', 'object', []); - if (!Array.isArray(modes)) + if (!Array.isArray(modes)) { throw new Error('Emulated device modes must be an array'); + } result.modes = []; for (let i = 0; i < modes.length; ++i) { const mode = {}; mode.title = /** @type {string} */ (parseValue(modes[i], 'title', 'string')); mode.orientation = /** @type {string} */ (parseValue(modes[i], 'orientation', 'string')); if (mode.orientation !== Emulation.EmulatedDevice.Vertical && - mode.orientation !== Emulation.EmulatedDevice.Horizontal) + mode.orientation !== Emulation.EmulatedDevice.Horizontal) { throw new Error('Emulated device mode has wrong orientation \'' + mode.orientation + '\''); + } const orientation = result.orientationByName(mode.orientation); mode.insets = parseInsets(parseValue(modes[i], 'insets', 'object')); if (mode.insets.top < 0 || mode.insets.left < 0 || mode.insets.right < 0 || mode.insets.bottom < 0 || mode.insets.top + mode.insets.bottom > orientation.height || - mode.insets.left + mode.insets.right > orientation.width) + mode.insets.left + mode.insets.right > orientation.width) { throw new Error('Emulated device mode \'' + mode.title + '\'has wrong mode insets'); + } mode.image = /** @type {string} */ (parseValue(modes[i], 'image', 'string', null)); result.modes.push(mode); @@ -169,10 +181,12 @@ static deviceComparator(device1, device2) { const order1 = (device1._extension && device1._extension.descriptor()['order']) || -1; const order2 = (device2._extension && device2._extension.descriptor()['order']) || -1; - if (order1 > order2) + if (order1 > order2) { return 1; - if (order2 > order1) + } + if (order2 > order1) { return -1; + } return device1.title < device2.title ? -1 : (device1.title > device2.title ? 1 : 0); } @@ -197,8 +211,9 @@ modesForOrientation(orientation) { const result = []; for (let index = 0; index < this.modes.length; index++) { - if (this.modes[index].orientation === orientation) + if (this.modes[index].orientation === orientation) { result.push(this.modes[index]); + } } return result; } @@ -228,8 +243,9 @@ mode['insets']['top'] = this.modes[i].insets.top; mode['insets']['right'] = this.modes[i].insets.right; mode['insets']['bottom'] = this.modes[i].insets.bottom; - if (this.modes[i].image) + if (this.modes[i].image) { mode['image'] = this.modes[i].image; + } json['modes'].push(mode); } @@ -264,10 +280,12 @@ * @return {string} */ modeImage(mode) { - if (!mode.image) + if (!mode.image) { return ''; - if (!this._extension) + } + if (!this._extension) { return mode.image; + } return this._extension.module().substituteURL(mode.image); } @@ -277,10 +295,12 @@ */ outlineImage(mode) { const orientation = this.orientationByName(mode.orientation); - if (!orientation.outlineImage) + if (!orientation.outlineImage) { return ''; - if (!this._extension) + } + if (!this._extension) { return orientation.outlineImage; + } return this._extension.module().substituteURL(orientation.outlineImage); } @@ -296,8 +316,9 @@ * @return {boolean} */ show() { - if (this._show === Emulation.EmulatedDevice._Show.Default) + if (this._show === Emulation.EmulatedDevice._Show.Default) { return this._showByDefault; + } return this._show === Emulation.EmulatedDevice._Show.Always; } @@ -377,16 +398,18 @@ this._customSetting = Common.settings.createSetting('customEmulatedDeviceList', []); /** @type {!Array.<!Emulation.EmulatedDevice>} */ this._custom = []; - if (!this._listFromJSONV1(this._customSetting.get(), this._custom)) + if (!this._listFromJSONV1(this._customSetting.get(), this._custom)) { this.saveCustomDevices(); + } } /** * @return {!Emulation.EmulatedDevicesList} */ static instance() { - if (!Emulation.EmulatedDevicesList._instance) + if (!Emulation.EmulatedDevicesList._instance) { Emulation.EmulatedDevicesList._instance = new Emulation.EmulatedDevicesList(); + } return /** @type {!Emulation.EmulatedDevicesList} */ (Emulation.EmulatedDevicesList._instance); } @@ -409,8 +432,9 @@ * @return {boolean} */ _listFromJSONV1(jsonArray, result) { - if (!Array.isArray(jsonArray)) + if (!Array.isArray(jsonArray)) { return false; + } let success = true; for (let i = 0; i < jsonArray.length; ++i) { const device = Emulation.EmulatedDevice.fromJSONV1(jsonArray[i]); @@ -493,13 +517,15 @@ */ _copyShowValues(from, to) { const deviceById = new Map(); - for (let i = 0; i < from.length; ++i) + for (let i = 0; i < from.length; ++i) { deviceById.set(from[i].title, from[i]); + } for (let i = 0; i < to.length; ++i) { const title = to[i].title; - if (deviceById.has(title)) + if (deviceById.has(title)) { to[i].copyShowFrom(/** @type {!Emulation.EmulatedDevice} */ (deviceById.get(title))); + } } } };
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js b/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js index 1f1b282..1975239 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js
@@ -40,8 +40,9 @@ this._list.clear(); const conditions = this._customSetting.get(); - for (let i = 0; i < conditions.length; ++i) + for (let i = 0; i < conditions.length; ++i) { this._list.appendItem(conditions[i], true); + } this._list.appendSeparator(); } @@ -96,8 +97,9 @@ geolocation.long = long ? parseFloat(long) : 0; const list = this._customSetting.get(); - if (isNew) + if (isNew) { list.push(geolocation); + } this._customSetting.set(list); } @@ -119,8 +121,9 @@ * @return {!UI.ListWidget.Editor} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -159,13 +162,15 @@ const value = input.value.trim(); let errorMessage; - if (!value.length) + if (!value.length) { errorMessage = ls`Location name cannot be empty`; - else if (value.length > maxLength) + } else if (value.length > maxLength) { errorMessage = ls`Location name must be less than ${maxLength} characters`; + } - if (errorMessage) + if (errorMessage) { return {valid: false, errorMessage}; + } return {valid: true}; } @@ -180,19 +185,22 @@ const maxLat = 90; const value = input.value.trim(); - if (!value) + if (!value) { return {valid: true}; + } let errorMessage; - if (!/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)) + if (!/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)) { errorMessage = ls`Latitude must be a number`; - else if (parseFloat(value) < minLat) + } else if (parseFloat(value) < minLat) { errorMessage = ls`Latitude must be greater than or equal to ${minLat}`; - else if (parseFloat(value) > maxLat) + } else if (parseFloat(value) > maxLat) { errorMessage = ls`Latitude must be less than or equal to ${maxLat}`; + } - if (errorMessage) + if (errorMessage) { return {valid: false, errorMessage}; + } return {valid: true}; } @@ -207,19 +215,22 @@ const maxLong = 180; const value = input.value.trim(); - if (!value) + if (!value) { return {valid: true}; + } let errorMessage; - if (!/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)) + if (!/^-?[\d]+(\.\d+)?|\.\d+$/.test(value)) { errorMessage = ls`Longitude must be a number`; - else if (parseFloat(value) < minLong) + } else if (parseFloat(value) < minLong) { errorMessage = ls`Longitude must be greater than or equal to ${minLong}`; - else if (parseFloat(value) > maxLong) + } else if (parseFloat(value) > maxLong) { errorMessage = ls`Longitude must be less than or equal to ${maxLong}`; + } - if (errorMessage) + if (errorMessage) { return {valid: false, errorMessage}; + } return {valid: true}; } }
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/InspectedPagePlaceholder.js b/third_party/blink/renderer/devtools/front_end/emulation/InspectedPagePlaceholder.js index d9f1787e..1515264 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/InspectedPagePlaceholder.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/InspectedPagePlaceholder.js
@@ -17,8 +17,9 @@ * @override */ onResize() { - if (this._updateId) + if (this._updateId) { this.element.window().cancelAnimationFrame(this._updateId); + } this._updateId = this.element.window().requestAnimationFrame(this.update.bind(this, false)); }
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/MediaQueryInspector.js b/third_party/blink/renderer/devtools/front_end/emulation/MediaQueryInspector.js index 04f62dac..e8f9748 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/MediaQueryInspector.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/MediaQueryInspector.js
@@ -32,8 +32,9 @@ */ modelAdded(cssModel) { // FIXME: adapt this to multiple targets. - if (this._cssModel) + if (this._cssModel) { return; + } this._cssModel = cssModel; this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); this._cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); @@ -47,8 +48,9 @@ * @param {!SDK.CSSModel} cssModel */ modelRemoved(cssModel) { - if (cssModel !== this._cssModel) + if (cssModel !== this._cssModel) { return; + } this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); @@ -61,8 +63,9 @@ * @param {number} scale */ setAxisTransform(scale) { - if (Math.abs(this._scale - scale) < 1e-8) + if (Math.abs(this._scale - scale) < 1e-8) { return; + } this._scale = scale; this._renderMediaQueries(); } @@ -72,8 +75,9 @@ */ _onMediaQueryClicked(event) { const mediaQueryMarker = event.target.enclosingNodeOrSelfWithClass('media-inspector-bar'); - if (!mediaQueryMarker) + if (!mediaQueryMarker) { return; + } const model = mediaQueryMarker._model; if (model.section() === Emulation.MediaQueryInspector.Section.Max) { @@ -85,29 +89,33 @@ return; } const currentWidth = this._getWidthCallback(); - if (currentWidth !== model.minWidthExpression().computedLength()) + if (currentWidth !== model.minWidthExpression().computedLength()) { this._setWidthCallback(model.minWidthExpression().computedLength()); - else + } else { this._setWidthCallback(model.maxWidthExpression().computedLength()); + } } /** * @param {!Event} event */ _onContextMenu(event) { - if (!this._cssModel || !this._cssModel.isEnabled()) + if (!this._cssModel || !this._cssModel.isEnabled()) { return; + } const mediaQueryMarker = event.target.enclosingNodeOrSelfWithClass('media-inspector-bar'); - if (!mediaQueryMarker) + if (!mediaQueryMarker) { return; + } const locations = mediaQueryMarker._locations; const uiLocations = new Map(); for (let i = 0; i < locations.length; ++i) { const uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(locations[i]); - if (!uiLocation) + if (!uiLocation) { continue; + } const descriptor = String.sprintf( '%s:%d:%d', uiLocation.uiSourceCode.url(), uiLocation.lineNumber + 1, uiLocation.columnNumber + 1); uiLocations.set(descriptor, uiLocation); @@ -132,14 +140,16 @@ } _scheduleMediaQueriesUpdate() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } this._mediaThrottler.schedule(this._refetchMediaQueries.bind(this)); } _refetchMediaQueries() { - if (!this.isShowing() || !this._cssModel) + if (!this.isShowing() || !this._cssModel) { return Promise.resolve(); + } return this._cssModel.mediaQueriesPromise().then(this._rebuildMediaQueries.bind(this)); } @@ -152,8 +162,9 @@ const filtered = []; for (let i = 0; i < models.length; ++i) { const last = filtered.peekLast(); - if (!last || !last.equals(models[i])) + if (!last || !last.equals(models[i])) { filtered.push(models[i]); + } } return filtered; } @@ -165,23 +176,27 @@ let queryModels = []; for (let i = 0; i < cssMedias.length; ++i) { const cssMedia = cssMedias[i]; - if (!cssMedia.mediaList) + if (!cssMedia.mediaList) { continue; + } for (let j = 0; j < cssMedia.mediaList.length; ++j) { const mediaQuery = cssMedia.mediaList[j]; const queryModel = Emulation.MediaQueryInspector.MediaQueryUIModel.createFromMediaQuery(cssMedia, mediaQuery); - if (queryModel && queryModel.rawLocation()) + if (queryModel && queryModel.rawLocation()) { queryModels.push(queryModel); + } } } queryModels.sort(compareModels); queryModels = this._squashAdjacentEqual(queryModels); let allEqual = this._cachedQueryModels && this._cachedQueryModels.length === queryModels.length; - for (let i = 0; allEqual && i < queryModels.length; ++i) + for (let i = 0; allEqual && i < queryModels.length; ++i) { allEqual = allEqual && this._cachedQueryModels[i].equals(queryModels[i]); - if (allEqual) + } + if (allEqual) { return; + } this._cachedQueryModels = queryModels; this._renderMediaQueries(); @@ -196,8 +211,9 @@ } _renderMediaQueries() { - if (!this._cachedQueryModels || !this.isShowing()) + if (!this._cachedQueryModels || !this.isShowing()) { return; + } const markers = []; let lastMarker = null; @@ -216,8 +232,9 @@ let container = null; for (let i = 0; i < markers.length; ++i) { - if (!i || markers[i].model.section() !== markers[i - 1].model.section()) + if (!i || markers[i].model.section() !== markers[i - 1].model.section()) { container = this.contentElement.createChild('div', 'media-inspector-marker-container'); + } const marker = markers[i]; const bar = this._createElementFromMediaQueryModel(marker.model); bar._model = marker.model; @@ -329,12 +346,13 @@ this._minWidthExpression = minWidthExpression; this._maxWidthExpression = maxWidthExpression; this._active = active; - if (maxWidthExpression && !minWidthExpression) + if (maxWidthExpression && !minWidthExpression) { this._section = Emulation.MediaQueryInspector.Section.Max; - else if (minWidthExpression && maxWidthExpression) + } else if (minWidthExpression && maxWidthExpression) { this._section = Emulation.MediaQueryInspector.Section.MinMax; - else + } else { this._section = Emulation.MediaQueryInspector.Section.Min; + } } /** @@ -351,8 +369,9 @@ for (let i = 0; i < expressions.length; ++i) { const expression = expressions[i]; const feature = expression.feature(); - if (feature.indexOf('width') === -1) + if (feature.indexOf('width') === -1) { continue; + } const pixels = expression.computedLength(); if (feature.startsWith('max-') && pixels < maxWidthPixels) { maxWidthExpression = expression; @@ -362,8 +381,9 @@ minWidthPixels = pixels; } } - if (minWidthPixels > maxWidthPixels || (!maxWidthExpression && !minWidthExpression)) + if (minWidthPixels > maxWidthPixels || (!maxWidthExpression && !minWidthExpression)) { return null; + } return new Emulation.MediaQueryInspector.MediaQueryUIModel( cssMedia, minWidthExpression, maxWidthExpression, mediaQuery.active()); @@ -394,26 +414,33 @@ * @return {number} */ compareTo(other) { - if (this.section() !== other.section()) + if (this.section() !== other.section()) { return this.section() - other.section(); + } if (this.dimensionsEqual(other)) { const myLocation = this.rawLocation(); const otherLocation = other.rawLocation(); - if (!myLocation && !otherLocation) + if (!myLocation && !otherLocation) { return this.mediaText().compareTo(other.mediaText()); - if (myLocation && !otherLocation) + } + if (myLocation && !otherLocation) { return 1; - if (!myLocation && otherLocation) + } + if (!myLocation && otherLocation) { return -1; - if (this.active() !== other.active()) + } + if (this.active() !== other.active()) { return this.active() ? -1 : 1; + } return myLocation.url.compareTo(otherLocation.url) || myLocation.lineNumber - otherLocation.lineNumber || myLocation.columnNumber - otherLocation.columnNumber; } - if (this.section() === Emulation.MediaQueryInspector.Section.Max) + if (this.section() === Emulation.MediaQueryInspector.Section.Max) { return other.maxWidthExpression().computedLength() - this.maxWidthExpression().computedLength(); - if (this.section() === Emulation.MediaQueryInspector.Section.Min) + } + if (this.section() === Emulation.MediaQueryInspector.Section.Min) { return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength(); + } return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength() || other.maxWidthExpression().computedLength() - this.maxWidthExpression().computedLength(); } @@ -436,8 +463,9 @@ * @return {?SDK.CSSLocation} */ rawLocation() { - if (!this._rawLocation) + if (!this._rawLocation) { this._rawLocation = this._cssMedia.rawLocation(); + } return this._rawLocation; }
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js b/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js index a3d9235..184b1e8 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js
@@ -31,8 +31,9 @@ * @return {!Emulation.SensorsView} */ static instance() { - if (!Emulation.SensorsView._instanceObject) + if (!Emulation.SensorsView._instanceObject) { Emulation.SensorsView._instanceObject = new Emulation.SensorsView(); + } return Emulation.SensorsView._instanceObject; } @@ -65,8 +66,9 @@ fields.appendChild(manageButton); const fillCustomSettings = () => { this._customLocationsGroup.removeChildren(); - for (const geolocation of customGeolocations.get()) + for (const geolocation of customGeolocations.get()) { this._customLocationsGroup.appendChild(new Option(geolocation.title, JSON.stringify(geolocation))); + } }; customGeolocations.addChangeListener(fillCustomSettings); fillCustomSettings(); @@ -131,8 +133,9 @@ this._geolocationOverrideEnabled = true; const geolocation = SDK.EmulationModel.Geolocation.parseUserInput( this._latitudeInput.value.trim(), this._longitudeInput.value.trim(), ''); - if (!geolocation) + if (!geolocation) { return; + } this._geolocation = geolocation; } else if (value === Emulation.SensorsView.NonPresetOptions.Unavailable) { this._geolocationOverrideEnabled = true; @@ -146,15 +149,17 @@ } this._applyGeolocation(); - if (value === Emulation.SensorsView.NonPresetOptions.Custom) + if (value === Emulation.SensorsView.NonPresetOptions.Custom) { this._latitudeInput.focus(); + } } _applyGeolocationUserInput() { const geolocation = SDK.EmulationModel.Geolocation.parseUserInput( this._latitudeInput.value.trim(), this._longitudeInput.value.trim(), ''); - if (!geolocation) + if (!geolocation) { return; + } this._setSelectElementLabel(this._locationSelectElement, Emulation.SensorsView.NonPresetOptions.Custom); this._geolocation = geolocation; @@ -162,10 +167,12 @@ } _applyGeolocation() { - if (this._geolocationOverrideEnabled) + if (this._geolocationOverrideEnabled) { this._geolocationSetting.set(this._geolocation.toSetting()); - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + } + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.emulateGeolocation(this._geolocationOverrideEnabled ? this._geolocation : null); + } } _createDeviceOrientationSection() { @@ -195,8 +202,9 @@ const groupElement = this._orientationSelectElement.createChild('optgroup'); groupElement.label = orientationGroups[i].title; const group = orientationGroups[i].value; - for (let j = 0; j < group.length; ++j) + for (let j = 0; j < group.length; ++j) { groupElement.appendChild(new Option(group[j].title, group[j].orientation)); + } } this._orientationSelectElement.selectedIndex = 0; fields.appendChild(this._orientationSelectElement); @@ -260,10 +268,12 @@ } _applyDeviceOrientation() { - if (this._deviceOrientationOverrideEnabled) + if (this._deviceOrientationOverrideEnabled) { this._deviceOrientationSetting.set(this._deviceOrientation.toSetting()); - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + } + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.emulateDeviceOrientation(this._deviceOrientationOverrideEnabled ? this._deviceOrientation : null); + } } /** @@ -295,8 +305,9 @@ * @param {!Emulation.SensorsView.DeviceOrientationModificationSource} modificationSource */ _setDeviceOrientation(deviceOrientation, modificationSource) { - if (!deviceOrientation) + if (!deviceOrientation) { return; + } /** * @param {number} angle @@ -371,10 +382,11 @@ * @param {boolean} animate */ _setBoxOrientation(deviceOrientation, animate) { - if (animate) + if (animate) { this._stageElement.classList.add('is-animating'); - else + } else { this._stageElement.classList.remove('is-animating'); + } // The CSS transform should not depend on matrix3d, which does not interpolate well. const matrix = new WebKitCSSMatrix(); @@ -390,8 +402,9 @@ */ _onBoxDrag(event) { const mouseMoveVector = this._calculateRadiusVector(event.x, event.y); - if (!mouseMoveVector) + if (!mouseMoveVector) { return true; + } event.consume(true); let axis, angle; @@ -424,14 +437,16 @@ * @return {boolean} */ _onBoxDragStart(event) { - if (!this._deviceOrientationOverrideEnabled) + if (!this._deviceOrientationOverrideEnabled) { return false; + } this._mouseDownVector = this._calculateRadiusVector(event.x, event.y); this._originalBoxMatrix = this._boxMatrix; - if (!this._mouseDownVector) + if (!this._mouseDownVector) { return false; + } event.consume(true); return true; @@ -448,8 +463,9 @@ const sphereX = (x - rect.left - rect.width / 2) / radius; const sphereY = (y - rect.top - rect.height / 2) / radius; const sqrSum = sphereX * sphereX + sphereY * sphereY; - if (sqrSum > 0.5) + if (sqrSum > 0.5) { return new UI.Geometry.Vector(sphereX, sphereY, 0.5 / Math.sqrt(sqrSum)); + } return new UI.Geometry.Vector(sphereX, sphereY, Math.sqrt(1 - sqrSum)); } @@ -471,8 +487,9 @@ UI.ARIAUtils.markAsAlert(reloadWarning); function applyTouch() { - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.overrideEmulateTouch(select.value === 'enabled'); + } reloadWarning.classList.remove('hidden'); const resourceTreeModel = SDK.targetManager.models(SDK.ResourceTreeModel)[0]; if (resourceTreeModel) {
diff --git a/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersUtils.js b/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersUtils.js index 1c43ba0..c857ab5 100644 --- a/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersUtils.js +++ b/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersUtils.js
@@ -40,16 +40,20 @@ * @return {!Promise<undefined>} */ function createEventListeners(result) { - if (!result.properties) + if (!result.properties) { throw new Error('Object properties is empty'); + } const promises = []; for (const property of result.properties) { - if (property.name === 'eventListeners' && property.value) + if (property.name === 'eventListeners' && property.value) { promises.push(convertToEventListeners(property.value).then(storeEventListeners)); - if (property.name === 'internalHandlers' && property.value) + } + if (property.name === 'internalHandlers' && property.value) { promises.push(convertToInternalHandlers(property.value).then(storeInternalHandlers)); - if (property.name === 'errorString' && property.value) + } + if (property.name === 'errorString' && property.value) { printErrorString(property.value); + } } return /** @type {!Promise<undefined>} */ (Promise.all(promises)); } @@ -162,8 +166,9 @@ * @param {!SDK.RemoteObject} functionObject */ function storeRemoveFunction(functionObject) { - if (functionObject.type !== 'function') + if (functionObject.type !== 'function') { return; + } removeFunctionObject = functionObject; } @@ -173,8 +178,9 @@ * @return {!SDK.EventListener} */ function createEventListener() { - if (!location) + if (!location) { throw new Error('Empty event listener\'s location'); + } return new SDK.EventListener( /** @type {!SDK.DOMDebuggerModel} */ (domDebuggerModel), object, type, useCapture, passive, once, handler, originalHandler, location, removeFunctionObject, SDK.EventListener.Origin.FrameworkUser); @@ -233,8 +239,9 @@ * @return {!SDK.RemoteObject} */ function assertCallFunctionResult(result) { - if (result.wasThrown || !result.object) + if (result.wasThrown || !result.object) { throw new Error('Exception in callFunction or empty result'); + } return result.object; } @@ -290,8 +297,9 @@ let internalHandlers = []; let fetchers = [jQueryFetcher]; try { - if (self.devtoolsFrameworkEventListeners && isArrayLike(self.devtoolsFrameworkEventListeners)) + if (self.devtoolsFrameworkEventListeners && isArrayLike(self.devtoolsFrameworkEventListeners)) { fetchers = fetchers.concat(self.devtoolsFrameworkEventListeners); + } } catch (e) { errorLines.push('devtoolsFrameworkEventListeners call produced error: ' + toString(e)); } @@ -312,8 +320,9 @@ } } const result = {eventListeners: eventListeners}; - if (internalHandlers.length) + if (internalHandlers.length) { result.internalHandlers = internalHandlers; + } if (errorLines.length) { let errorString = 'Framework Event Listeners API Errors:\n\t' + errorLines.join('\n\t'); errorString = errorString.substr(0, errorString.length - 1); @@ -326,8 +335,9 @@ * @return {boolean} */ function isArrayLike(obj) { - if (!obj || typeof obj !== 'object') + if (!obj || typeof obj !== 'object') { return false; + } try { if (typeof obj.splice === 'function') { const len = obj.length; @@ -345,26 +355,33 @@ function checkEventListener(eventListener) { try { let errorString = ''; - if (!eventListener) + if (!eventListener) { errorString += 'empty event listener, '; + } const type = eventListener.type; - if (!type || (typeof type !== 'string')) + if (!type || (typeof type !== 'string')) { errorString += 'event listener\'s type isn\'t string or empty, '; + } const useCapture = eventListener.useCapture; - if (typeof useCapture !== 'boolean') + if (typeof useCapture !== 'boolean') { errorString += 'event listener\'s useCapture isn\'t boolean or undefined, '; + } const passive = eventListener.passive; - if (typeof passive !== 'boolean') + if (typeof passive !== 'boolean') { errorString += 'event listener\'s passive isn\'t boolean or undefined, '; + } const once = eventListener.once; - if (typeof once !== 'boolean') + if (typeof once !== 'boolean') { errorString += 'event listener\'s once isn\'t boolean or undefined, '; + } const handler = eventListener.handler; - if (!handler || (typeof handler !== 'function')) + if (!handler || (typeof handler !== 'function')) { errorString += 'event listener\'s handler isn\'t a function or empty, '; + } const remove = eventListener.remove; - if (remove && (typeof remove !== 'function')) + if (remove && (typeof remove !== 'function')) { errorString += 'event listener\'s remove isn\'t a function, '; + } if (!errorString) { return {type: type, useCapture: useCapture, passive: passive, once: once, handler: handler, remove: remove}; } else { @@ -382,8 +399,9 @@ * @return {function()|null} */ function checkInternalHandler(handler) { - if (handler && (typeof handler === 'function')) + if (handler && (typeof handler === 'function')) { return handler; + } errorLines.push('internal handler isn\'t a function or empty'); return null; } @@ -410,11 +428,13 @@ } function jQueryFetcher(node) { - if (!node || !(node instanceof Node)) + if (!node || !(node instanceof Node)) { return {eventListeners: []}; + } const jQuery = /** @type {?{fn,data,_data}}*/ (window['jQuery']); - if (!jQuery || !jQuery.fn) + if (!jQuery || !jQuery.fn) { return {eventListeners: []}; + } const jQueryFunction = /** @type {function(!Node)} */ (jQuery); const data = jQuery._data || jQuery.data; @@ -440,8 +460,9 @@ } } const nodeData = data(node); - if (nodeData && typeof nodeData.handle === 'function') + if (nodeData && typeof nodeData.handle === 'function') { internalHandlers.push(nodeData.handle); + } } const entry = jQueryFunction(node)[0]; if (entry) { @@ -456,8 +477,9 @@ } } } - if (entry && entry['$handle']) + if (entry && entry['$handle']) { internalHandlers.push(entry['$handle']); + } } return {eventListeners: eventListeners, internalHandlers: internalHandlers}; } @@ -469,12 +491,14 @@ * @this {?Object} */ function jQueryRemove(selector, type, handler) { - if (!this || !(this instanceof Node)) + if (!this || !(this instanceof Node)) { return; + } const node = /** @type {!Node} */ (this); const jQuery = /** @type {?{fn,data,_data}}*/ (window['jQuery']); - if (!jQuery || !jQuery.fn) + if (!jQuery || !jQuery.fn) { return; + } const jQueryFunction = /** @type {function(!Node)} */ (jQuery); jQueryFunction(node).off(type, selector, handler); }
diff --git a/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersView.js b/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersView.js index a4c1e2b..1d2bfd8 100644 --- a/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersView.js +++ b/third_party/blink/renderer/devtools/front_end/event_listeners/EventListenersView.js
@@ -56,8 +56,9 @@ const promises = []; const domDebuggerModel = object.runtimeModel().target().model(SDK.DOMDebuggerModel); // TODO(kozyatinskiy): figure out how this should work for |window| when there is no DOMDebugger. - if (domDebuggerModel) + if (domDebuggerModel) { promises.push(domDebuggerModel.eventListeners(object).then(storeEventListeners)); + } promises.push(EventListeners.frameworkEventListeners(object).then(storeFrameworkEventListenersObject)); return Promise.all(promises).then(markInternalEventListeners).then(addEventListeners.bind(this)); @@ -79,8 +80,9 @@ * @return {!Promise<undefined>} */ function markInternalEventListeners() { - if (!frameworkEventListenersObject.internalHandlers) + if (!frameworkEventListenersObject.internalHandlers) { return Promise.resolve(undefined); + } return frameworkEventListenersObject.internalHandlers.object() .callFunctionJSON(isInternalEventListener, eventListeners.map(handlerArgument)) .then(setIsInternal); @@ -101,8 +103,9 @@ function isInternalEventListener() { const isInternal = []; const internalHandlersSet = new Set(this); - for (const handler of arguments) + for (const handler of arguments) { isInternal.push(internalHandlersSet.has(handler)); + } return isInternal; } @@ -111,8 +114,9 @@ */ function setIsInternal(isInternal) { for (let i = 0; i < eventListeners.length; ++i) { - if (isInternal[i]) + if (isInternal[i]) { eventListeners[i].markAsFramework(); + } } } } @@ -131,8 +135,9 @@ * @param {?Array<!SDK.EventListener>} eventListeners */ _addObjectEventListeners(object, eventListeners) { - if (!eventListeners) + if (!eventListeners) { return; + } for (const eventListener of eventListeners) { const treeItem = this._getOrCreateTreeElementForType(eventListener.type()); treeItem.addObjectEventListener(eventListener, object); @@ -151,14 +156,18 @@ for (const listenerElement of eventType.children()) { const listenerOrigin = listenerElement.eventListener().origin(); let hidden = false; - if (listenerOrigin === SDK.EventListener.Origin.FrameworkUser && !showFramework) + if (listenerOrigin === SDK.EventListener.Origin.FrameworkUser && !showFramework) { hidden = true; - if (listenerOrigin === SDK.EventListener.Origin.Framework && showFramework) + } + if (listenerOrigin === SDK.EventListener.Origin.Framework && showFramework) { hidden = true; - if (!showPassive && listenerElement.eventListener().passive()) + } + if (!showPassive && listenerElement.eventListener().passive()) { hidden = true; - if (!showBlocking && !listenerElement.eventListener().passive()) + } + if (!showBlocking && !listenerElement.eventListener().passive()) { hidden = true; + } listenerElement.hidden = hidden; hiddenEventType = hiddenEventType && hidden; } @@ -188,19 +197,23 @@ for (const eventType of this._treeOutline.rootElement().children()) { eventType.hidden = !eventType.firstChild(); allHidden = allHidden && eventType.hidden; - if (!firstVisibleChild && !eventType.hidden) + if (!firstVisibleChild && !eventType.hidden) { firstVisibleChild = eventType; + } } - if (allHidden && !this._emptyHolder.parentNode) + if (allHidden && !this._emptyHolder.parentNode) { this.element.appendChild(this._emptyHolder); - if (firstVisibleChild) + } + if (firstVisibleChild) { firstVisibleChild.select(true /* omitFocus */); + } } reset() { const eventTypes = this._treeOutline.rootElement().children(); - for (const eventType of eventTypes) + for (const eventType of eventTypes) { eventType.removeChildren(); + } this._linkifier.reset(); } @@ -230,8 +243,9 @@ * @return {number} */ static comparator(element1, element2) { - if (element1.title === element2.title) + if (element1.title === element2.title) { return 0; + } return element1.title > element2.title ? 1 : -1; } @@ -276,8 +290,9 @@ properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('useCapture', eventListener.useCapture())); properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('passive', eventListener.passive())); properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue('once', eventListener.once())); - if (typeof eventListener.handler() !== 'undefined') + if (typeof eventListener.handler() !== 'undefined') { properties.push(new SDK.RemoteObjectProperty('handler', eventListener.handler())); + } ObjectUI.ObjectPropertyTreeElement.populateWithProperties(this, properties, [], true, null); } @@ -333,12 +348,14 @@ _removeListenerBar() { const parent = this.parent; parent.removeChild(this); - if (!parent.childCount()) + if (!parent.childCount()) { parent.collapse(); + } let allHidden = true; for (let i = 0; i < parent.childCount(); ++i) { - if (!parent.childAt(i).hidden) + if (!parent.childAt(i).hidden) { allHidden = false; + } } parent.hidden = allHidden; }
diff --git a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionAPI.js b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionAPI.js index 367c4285..9f02d8ac 100644 --- a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionAPI.js +++ b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionAPI.js
@@ -31,8 +31,9 @@ /* eslint-disable indent */ function defineCommonExtensionSymbols(apiPrivate) { - if (!apiPrivate.panels) + if (!apiPrivate.panels) { apiPrivate.panels = {}; + } apiPrivate.panels.SearchAction = { CancelSearch: 'cancelSearch', PerformSearch: 'performSearch', @@ -98,8 +99,9 @@ const keysToForwardSet = new Set(keysToForward); const chrome = window.chrome || {}; const devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, 'devtools'); - if (devtools_descriptor) + if (devtools_descriptor) { return; + } const apiPrivate = {}; @@ -126,10 +128,12 @@ EventSinkImpl.prototype = { addListener: function(callback) { - if (typeof callback !== 'function') + if (typeof callback !== 'function') { throw 'addListener: callback is not a function'; - if (this._listeners.length === 0) + } + if (this._listeners.length === 0) { extensionServer.sendRequest({command: commands.Subscribe, type: this._type}); + } this._listeners.push(callback); extensionServer.registerHandler('notify-' + this._type, this._dispatch.bind(this)); }, @@ -143,8 +147,9 @@ break; } } - if (this._listeners.length === 0) + if (this._listeners.length === 0) { extensionServer.sendRequest({command: commands.Unsubscribe, type: this._type}); + } }, /** @@ -152,15 +157,17 @@ */ _fire: function(vararg) { const listeners = this._listeners.slice(); - for (let i = 0; i < listeners.length; ++i) + for (let i = 0; i < listeners.length; ++i) { listeners[i].apply(null, arguments); + } }, _dispatch: function(request) { - if (this._customDispatch) + if (this._customDispatch) { this._customDispatch.call(this, request); - else + } else { this._fire.apply(this, request.arguments); + } } }; @@ -239,8 +246,9 @@ function panelGetter(name) { return panels[name]; } - for (const panel in panels) + for (const panel in panels) { Object.defineProperty(this, panel, {get: panelGetter.bind(null, panel), enumerable: true}); + } this.applyStyleSheet = function(styleSheet) { extensionServer.sendRequest({command: commands.ApplyStyleSheet, styleSheet: styleSheet}); }; @@ -266,14 +274,16 @@ } } - if (!callback) + if (!callback) { extensionServer.unregisterHandler(events.OpenResource); - else + } else { extensionServer.registerHandler(events.OpenResource, callbackWrapper); + } // Only send command if we either removed an existing handler or added handler and had none before. - if (hadHandler === !callback) + if (hadHandler === !callback) { extensionServer.sendRequest({command: commands.SetOpenResourceHandler, 'handlerPresent': !!callback}); + } }, openResource: function(url, lineNumber, callback) { @@ -296,10 +306,11 @@ */ function dispatchShowEvent(message) { const frameIndex = message.arguments[0]; - if (typeof frameIndex === 'number') + if (typeof frameIndex === 'number') { this._fire(window.parent.frames[frameIndex]); - else + } else { this._fire(); + } } if (id) { @@ -410,8 +421,9 @@ }, show: function() { - if (!userAction) + if (!userAction) { return; + } const request = {command: commands.ShowPanel, id: this._id}; extensionServer.sendRequest(request); @@ -441,8 +453,9 @@ rootTitle: rootTitle, evaluateOnPage: true, }; - if (typeof evaluateOptions === 'object') + if (typeof evaluateOptions === 'object') { request.evaluateOptions = evaluateOptions; + } extensionServer.sendRequest(request, extractCallbackArgument(arguments)); }, @@ -573,14 +586,16 @@ eval: function(expression, evaluateOptions) { const callback = extractCallbackArgument(arguments); function callbackWrapper(result) { - if (result.isError || result.isException) + if (result.isError || result.isException) { callback(undefined, result); - else + } else { callback(result.value); + } } const request = {command: commands.EvaluateOnInspectedPage, expression: expression}; - if (typeof evaluateOptions === 'object') + if (typeof evaluateOptions === 'object') { request.evaluateOptions = evaluateOptions; + } extensionServer.sendRequest(request, callback && callbackWrapper); return null; }, @@ -636,18 +651,23 @@ function forwardKeyboardEvent(event) { let modifiers = 0; - if (event.shiftKey) + if (event.shiftKey) { modifiers |= 1; - if (event.ctrlKey) + } + if (event.ctrlKey) { modifiers |= 2; - if (event.altKey) + } + if (event.altKey) { modifiers |= 4; - if (event.metaKey) + } + if (event.metaKey) { modifiers |= 8; + } const num = (event.keyCode & 255) | (modifiers << 8); // We only care about global hotkeys, not about random text - if (!keysToForwardSet.has(num)) + if (!keysToForwardSet.has(num)) { return; + } event.preventDefault(); const requestPayload = { eventType: event.type, @@ -662,8 +682,9 @@ keyCode: event.keyCode }; keyboardEventRequestQueue.push(requestPayload); - if (!forwardTimer) + if (!forwardTimer) { forwardTimer = setTimeout(forwardEventQueue, 0); + } } function forwardEventQueue() { @@ -700,8 +721,9 @@ * @param {function()=} callback */ sendRequest: function(message, callback) { - if (typeof callback === 'function') + if (typeof callback === 'function') { message.requestId = this._registerCallback(callback); + } this._port.postMessage(message); }, @@ -744,27 +766,32 @@ _onMessage: function(event) { const request = event.data; const handler = this._handlers[request.command]; - if (handler) + if (handler) { handler.call(this, request); + } } }; function populateInterfaceClass(interfaze, implementation) { for (const member in implementation) { - if (member.charAt(0) === '_') + if (member.charAt(0) === '_') { continue; + } let descriptor = null; // Traverse prototype chain until we find the owner. - for (let owner = implementation; owner && !descriptor; owner = owner.__proto__) + for (let owner = implementation; owner && !descriptor; owner = owner.__proto__) { descriptor = Object.getOwnPropertyDescriptor(owner, member); - if (!descriptor) + } + if (!descriptor) { continue; - if (typeof descriptor.value === 'function') + } + if (typeof descriptor.value === 'function') { interfaze[member] = descriptor.value.bind(implementation); - else if (typeof descriptor.get === 'function') + } else if (typeof descriptor.get === 'function') { interfaze.__defineGetter__(member, descriptor.get.bind(implementation)); - else + } else { Object.defineProperty(interfaze, member, descriptor); + } } } @@ -789,14 +816,16 @@ const properties = Object.getOwnPropertyNames(coreAPI); for (let i = 0; i < properties.length; ++i) { const descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]); - if (descriptor) + if (descriptor) { Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor); + } } chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow; } - if (extensionInfo.exposeWebInspectorNamespace) + if (extensionInfo.exposeWebInspectorNamespace) { window.webInspector = coreAPI; + } testHook(extensionServer, coreAPI); } @@ -810,8 +839,9 @@ */ self.buildExtensionAPIInjectedScript = function(extensionInfo, inspectedTabId, themeName, keysToForward, testHook) { const argumentsJSON = [extensionInfo, inspectedTabId || null, themeName, keysToForward].map(_ => JSON.stringify(_)).join(','); - if (!testHook) + if (!testHook) { testHook = () => {}; + } return '(function(injectedScriptId){ ' + defineCommonExtensionSymbols.toString() + ';' + '(' + injectedExtensionAPI.toString() + ')(' + argumentsJSON + ',' + testHook + ', injectedScriptId);' + '})';
diff --git a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js index fa58d122..90534e4 100644 --- a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js +++ b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionPanel.js
@@ -144,12 +144,15 @@ * @param {boolean=} disabled */ update(iconURL, tooltip, disabled) { - if (typeof iconURL === 'string') + if (typeof iconURL === 'string') { this._toolbarButton.setBackgroundImage(iconURL); - if (typeof tooltip === 'string') + } + if (typeof tooltip === 'string') { this._toolbarButton.setTitle(tooltip); - if (typeof disabled === 'boolean') + } + if (typeof disabled === 'boolean') { this._toolbarButton.setEnabled(!disabled); + } } /** @@ -223,14 +226,16 @@ this._objectPropertiesView.detach(); delete this._objectPropertiesView; } - if (this._extensionView) + if (this._extensionView) { this._extensionView.detach(true); + } this._extensionView = new Extensions.ExtensionView(this._server, this._id, url, 'extension fill'); this._extensionView.show(this.element); - if (!this.element.style.height) + if (!this.element.style.height) { this.setHeight('150px'); + } } /** @@ -248,15 +253,17 @@ * @param {boolean=} wasThrown */ _onEvaluate(title, callback, error, result, wasThrown) { - if (error || !result) + if (error || !result) { callback(error.toString()); - else + } else { this._setObject(result, title, callback); + } } _createObjectPropertiesView() { - if (this._objectPropertiesView) + if (this._objectPropertiesView) { return; + } if (this._extensionView) { this._extensionView.detach(true); delete this._extensionView; @@ -282,8 +289,9 @@ callback(); return; } - if (result.tree && result.tree.firstChild()) + if (result.tree && result.tree.firstChild()) { result.tree.firstChild().expand(); + } this._objectPropertiesView.element.appendChild(result.node); callback(); });
diff --git a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionServer.js b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionServer.js index c1a2a097..a2d05e6 100644 --- a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionServer.js +++ b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionServer.js
@@ -131,8 +131,9 @@ } _inspectedURLChanged(event) { - if (event.data !== SDK.targetManager.mainTarget()) + if (event.data !== SDK.targetManager.mainTarget()) { return; + } this._requests = {}; const url = event.data.inspectedURL(); this._postNotification(Extensions.extensionAPI.Events.InspectedURLChanged, url); @@ -169,11 +170,13 @@ */ _postNotification(type, vararg) { const subscribers = this._subscribers[type]; - if (!subscribers) + if (!subscribers) { return; + } const message = {command: 'notify-' + type, arguments: Array.prototype.slice.call(arguments, 1)}; - for (let i = 0; i < subscribers.length; ++i) + for (let i = 0; i < subscribers.length; ++i) { subscribers[i].postMessage(message); + } } _onSubscribe(message, port) { @@ -182,40 +185,46 @@ subscribers.push(port); } else { this._subscribers[message.type] = [port]; - if (this._subscriptionStartHandlers[message.type]) + if (this._subscriptionStartHandlers[message.type]) { this._subscriptionStartHandlers[message.type](); + } } } _onUnsubscribe(message, port) { const subscribers = this._subscribers[message.type]; - if (!subscribers) + if (!subscribers) { return; + } subscribers.remove(port); if (!subscribers.length) { delete this._subscribers[message.type]; - if (this._subscriptionStopHandlers[message.type]) + if (this._subscriptionStopHandlers[message.type]) { this._subscriptionStopHandlers[message.type](); + } } } _onAddRequestHeaders(message) { const id = message.extensionId; - if (typeof id !== 'string') + if (typeof id !== 'string') { return this._status.E_BADARGTYPE('extensionId', typeof id, 'string'); + } let extensionHeaders = this._extraHeaders[id]; if (!extensionHeaders) { extensionHeaders = {}; this._extraHeaders[id] = extensionHeaders; } - for (const name in message.headers) + for (const name in message.headers) { extensionHeaders[name] = message.headers[name]; + } const allHeaders = /** @type {!Protocol.Network.Headers} */ ({}); for (const extension in this._extraHeaders) { const headers = this._extraHeaders[extension]; for (const name in headers) { - if (typeof headers[name] === 'string') + if (typeof headers[name] === 'string') { allHeaders[name] = headers[name]; + } } } @@ -227,8 +236,9 @@ * @suppressGlobalPropertiesCheck */ _onApplyStyleSheet(message) { - if (!Runtime.experiments.isEnabled('applyCustomStylesheet')) + if (!Runtime.experiments.isEnabled('applyCustomStylesheet')) { return; + } const styleSheet = createElement('style'); styleSheet.textContent = message.styleSheet; document.head.appendChild(styleSheet); @@ -236,8 +246,9 @@ UI.themeSupport.addCustomStylesheet(message.styleSheet); // Add to all the shadow roots that have already been created for (let node = document.body; node; node = node.traverseNextNode(document.body)) { - if (node instanceof ShadowRoot) + if (node instanceof ShadowRoot) { UI.themeSupport.injectCustomStyleSheets(node); + } } } @@ -245,8 +256,9 @@ const id = message.id; // The ids are generated on the client API side and must be unique, so the check below // shouldn't be hit unless someone is bypassing the API. - if (id in this._clientObjects || UI.inspectorView.hasPanel(id)) + if (id in this._clientObjects || UI.inspectorView.hasPanel(id)) { return this._status.E_EXISTS(id); + } const page = this._expandResourcePath(port._extensionOrigin, message.page); let persistentId = port._extensionOrigin + message.title; @@ -261,15 +273,17 @@ _onShowPanel(message) { let panelViewId = message.id; const panelView = this._clientObjects[message.id]; - if (panelView && panelView instanceof Extensions.ExtensionServerPanelView) + if (panelView && panelView instanceof Extensions.ExtensionServerPanelView) { panelViewId = panelView.viewId(); + } UI.inspectorView.showPanel(panelViewId); } _onCreateToolbarButton(message, port) { const panelView = this._clientObjects[message.panel]; - if (!panelView || !(panelView instanceof Extensions.ExtensionServerPanelView)) + if (!panelView || !(panelView instanceof Extensions.ExtensionServerPanelView)) { return this._status.E_NOTFOUND(message.panel); + } const button = new Extensions.ExtensionButton( this, message.id, this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); @@ -289,8 +303,9 @@ _onUpdateButton(message, port) { const button = this._clientObjects[message.id]; - if (!button || !(button instanceof Extensions.ExtensionButton)) + if (!button || !(button instanceof Extensions.ExtensionButton)) { return this._status.E_NOTFOUND(message.id); + } button.update(this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); return this._status.OK(); } @@ -300,15 +315,17 @@ */ _onCompleteTraceSession(message) { const session = this._traceSessions.get(message.id); - if (!session) + if (!session) { return this._status.E_NOTFOUND(message.id); + } this._traceSessions.delete(message.id); session.complete(message.url, message.timeOffset); } _onCreateSidebarPane(message) { - if (message.panel !== 'elements' && message.panel !== 'sources') + if (message.panel !== 'elements' && message.panel !== 'sources') { return this._status.E_NOTFOUND(message.panel); + } const id = message.id; const sidebar = new Extensions.ExtensionSidebarPane(this, message.panel, message.title, id); this._sidebarPanes.push(sidebar); @@ -327,16 +344,18 @@ _onSetSidebarHeight(message) { const sidebar = this._clientObjects[message.id]; - if (!sidebar) + if (!sidebar) { return this._status.E_NOTFOUND(message.id); + } sidebar.setHeight(message.height); return this._status.OK(); } _onSetSidebarContent(message, port) { const sidebar = this._clientObjects[message.id]; - if (!sidebar) + if (!sidebar) { return this._status.E_NOTFOUND(message.id); + } /** * @this {Extensions.ExtensionServer} @@ -354,8 +373,9 @@ _onSetSidebarPage(message, port) { const sidebar = this._clientObjects[message.id]; - if (!sidebar) + if (!sidebar) { return this._status.E_NOTFOUND(message.id); + } sidebar.setPage(this._expandResourcePath(port._extensionOrigin, message.page)); } @@ -383,10 +403,11 @@ _onSetOpenResourceHandler(message, port) { const name = this._registeredExtensions[port._extensionOrigin].name || ('Extension ' + port._extensionOrigin); - if (message.handlerPresent) + if (message.handlerPresent) { Components.Linkifier.registerLinkHandler(name, this._handleOpenURL.bind(this, port)); - else + } else { Components.Linkifier.unregisterLinkHandler(name); + } } _handleOpenURL(port, contentProvider, lineNumber) { @@ -399,8 +420,9 @@ SDK.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent === 'string' ? options.userAgent : ''); let injectedScript; - if (options.injectedScript) + if (options.injectedScript) { injectedScript = '(function(){' + options.injectedScript + '})()'; + } SDK.ResourceTreeModel.reloadAllPages(!!options.ignoreCache, injectedScript); return this._status.OK(); } @@ -414,12 +436,13 @@ */ function callback(error, object, wasThrown) { let result; - if (error || !object) + if (error || !object) { result = this._status.E_PROTOCOLERROR(error.toString()); - else if (wasThrown) + } else if (wasThrown) { result = {isException: true, value: object.description}; - else + } else { result = {value: object.value}; + } this._dispatchCallback(message.requestId, port, result); } @@ -430,8 +453,9 @@ async _onGetHAR() { const requests = SDK.networkLog.requests(); const harLog = await SDK.HARLog.build(requests); - for (let i = 0; i < harLog.entries.length; ++i) + for (let i = 0; i < harLog.entries.length; ++i) { harLog.entries[i]._requestId = this._requestId(requests[i]); + } return harLog; } @@ -453,15 +477,17 @@ * @this {Extensions.ExtensionServer} */ function pushResourceData(contentProvider) { - if (!resources.has(contentProvider.contentURL())) + if (!resources.has(contentProvider.contentURL())) { resources.set(contentProvider.contentURL(), this._makeResource(contentProvider)); + } } let uiSourceCodes = Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.Network); uiSourceCodes = uiSourceCodes.concat(Workspace.workspace.uiSourceCodesForProjectType(Workspace.projectTypes.ContentScripts)); uiSourceCodes.forEach(pushResourceData.bind(this)); - for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) + for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { resourceTreeModel.forAllResources(pushResourceData.bind(this)); + } return resources.valuesArray(); } @@ -478,16 +504,18 @@ _onGetRequestContent(message, port) { const request = this._requestById(message.id); - if (!request) + if (!request) { return this._status.E_NOTFOUND(message.id); + } this._getResourceContent(request, message, port); } _onGetResourceContent(message, port) { const url = /** @type {string} */ (message.url); const contentProvider = Workspace.workspace.uiSourceCodeForURL(url) || Bindings.resourceForURL(url); - if (!contentProvider) + if (!contentProvider) { return this._status.E_NOTFOUND(url); + } this._getResourceContent(contentProvider, message, port); } @@ -505,13 +533,15 @@ const uiSourceCode = Workspace.workspace.uiSourceCodeForURL(url); if (!uiSourceCode || !uiSourceCode.contentType().isDocumentOrScriptOrStyleSheet()) { const resource = SDK.ResourceTreeModel.resourceForURL(url); - if (!resource) + if (!resource) { return this._status.E_NOTFOUND(url); + } return this._status.E_NOTSUPPORTED('Resource is not editable'); } uiSourceCode.setWorkingCopy(message.content); - if (message.commit) + if (message.commit) { uiSourceCode.commitWorkingCopy(); + } callbackWrapper.call(this, null); } @@ -574,16 +604,18 @@ let keyCode = entry.keyCode; if (!keyCode) { // This is required only for synthetic events (e.g. dispatched in tests). - if (entry.key === 'Escape') + if (entry.key === 'Escape') { keyCode = 27; + } } return keyCode || 0; } } _dispatchCallback(requestId, port, result) { - if (requestId) + if (requestId) { port.postMessage({command: 'callback', requestId: requestId, result: result}); + } } _initExtensions() { @@ -698,7 +730,9 @@ _registerExtension(origin, port) { if (!this._registeredExtensions.hasOwnProperty(origin)) { if (origin !== window.location.origin) // Just ignore inspector frames. + { console.error('Ignoring unauthorized client request from ' + origin); + } return; } port._extensionOrigin = origin; @@ -707,21 +741,24 @@ } _onWindowMessage(event) { - if (event.data === 'registerExtension') + if (event.data === 'registerExtension') { this._registerExtension(event.origin, event.ports[0]); + } } async _onmessage(event) { const message = event.data; let result; - if (message.command in this._handlers) + if (message.command in this._handlers) { result = await this._handlers[message.command](message, event.target); - else + } else { result = this._status.E_NOTSUPPORTED(message.command); + } - if (result && message.requestId) + if (result && message.requestId) { this._dispatchCallback(message.requestId, event.target, result); + } } _registerHandler(command, callback) { @@ -782,8 +819,9 @@ } _expandResourcePath(extensionPath, resourcePath) { - if (!resourcePath) + if (!resourcePath) { return; + } return extensionPath + this._normalizePath(resourcePath); } @@ -792,15 +830,18 @@ const result = []; for (let i = 0; i < source.length; ++i) { - if (source[i] === '.') + if (source[i] === '.') { continue; + } // Ignore empty path components resulting from //, as well as a leading and traling slashes. - if (source[i] === '') + if (source[i] === '') { continue; - if (source[i] === '..') + } + if (source[i] === '..') { result.pop(); - else + } else { result.push(source[i]); + } } return '/' + result.join('/'); } @@ -841,18 +882,20 @@ frame = resourceTreeModel && resourceTreeModel.mainFrame; } if (!frame) { - if (options.frameURL) + if (options.frameURL) { console.warn('evaluate: there is no frame with URL ' + options.frameURL); - else + } else { console.warn('evaluate: the main frame is not yet available'); + } return this._status.E_NOTFOUND(options.frameURL || '<top>'); } let contextSecurityOrigin; - if (options.useContentScriptContext) + if (options.useContentScriptContext) { contextSecurityOrigin = securityOrigin; - else if (options.scriptExecutionContext) + } else if (options.scriptExecutionContext) { contextSecurityOrigin = options.scriptExecutionContext; + } const runtimeModel = frame.resourceTreeModel().target().model(SDK.RuntimeModel); const executionContexts = runtimeModel ? runtimeModel.executionContexts() : []; @@ -860,8 +903,9 @@ for (let i = 0; i < executionContexts.length; ++i) { const executionContext = executionContexts[i]; if (executionContext.frameId === frame.id && executionContext.origin === contextSecurityOrigin && - !executionContext.isDefault) + !executionContext.isDefault) { context = executionContext; + } } if (!context) { console.warn('The JavaScript context ' + contextSecurityOrigin + ' was not found in the frame ' + frame.url); @@ -870,11 +914,13 @@ } else { for (let i = 0; i < executionContexts.length; ++i) { const executionContext = executionContexts[i]; - if (executionContext.frameId === frame.id && executionContext.isDefault) + if (executionContext.frameId === frame.id && executionContext.isDefault) { context = executionContext; + } } - if (!context) + if (!context) { return this._status.E_FAILED(frame.url + ' has no execution context'); + } } context
diff --git a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionView.js b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionView.js index 48c5594..032585e 100644 --- a/third_party/blink/renderer/devtools/front_end/extensions/ExtensionView.js +++ b/third_party/blink/renderer/devtools/front_end/extensions/ExtensionView.js
@@ -63,23 +63,26 @@ * @override */ wasShown() { - if (typeof this._frameIndex === 'number') + if (typeof this._frameIndex === 'number') { this._server.notifyViewShown(this._id, this._frameIndex); + } } /** * @override */ willHide() { - if (typeof this._frameIndex === 'number') + if (typeof this._frameIndex === 'number') { this._server.notifyViewHidden(this._id); + } } _onLoad() { const frames = window.frames; this._frameIndex = Array.prototype.indexOf.call(frames, this._iframe.contentWindow); - if (this.isShowing()) + if (this.isShowing()) { this._server.notifyViewShown(this._id, this._frameIndex); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/extensions_test_runner/ExtensionsTestRunner.js b/third_party/blink/renderer/devtools/front_end/extensions_test_runner/ExtensionsTestRunner.js index da568e6..875fb75 100644 --- a/third_party/blink/renderer/devtools/front_end/extensions_test_runner/ExtensionsTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/extensions_test_runner/ExtensionsTestRunner.js
@@ -36,8 +36,9 @@ } ExtensionsTestRunner.showPanel = function(panelId) { - if (panelId === 'extension') + if (panelId === 'extension') { panelId = UI.inspectorView._tabbedPane._tabs[UI.inspectorView._tabbedPane._tabs.length - 1].id; + } return UI.inspectorView.showPanel(panelId); }; @@ -48,8 +49,9 @@ ExtensionsTestRunner.runExtensionTests = async function(tests) { const result = await TestRunner.RuntimeAgent.evaluate('location.href', 'console', false); - if (!result) + if (!result) { return; + } ExtensionsTestRunner._pendingTests = (ExtensionsTestRunner._codeToEvaluateBeforeTests || '') + tests.join('\n'); const pageURL = result.value;
diff --git a/third_party/blink/renderer/devtools/front_end/formatter/FormatterWorkerPool.js b/third_party/blink/renderer/devtools/front_end/formatter/FormatterWorkerPool.js index 08aa4b4..038dc2d 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter/FormatterWorkerPool.js +++ b/third_party/blink/renderer/devtools/front_end/formatter/FormatterWorkerPool.js
@@ -22,14 +22,17 @@ } _processNextTask() { - if (!this._taskQueue.length) + if (!this._taskQueue.length) { return; + } let freeWorker = this._workerTasks.keysArray().find(worker => !this._workerTasks.get(worker)); - if (!freeWorker && this._workerTasks.size < Formatter.FormatterWorkerPool.MaxWorkers) + if (!freeWorker && this._workerTasks.size < Formatter.FormatterWorkerPool.MaxWorkers) { freeWorker = this._createWorker(); - if (!freeWorker) + } + if (!freeWorker) { return; + } const task = this._taskQueue.shift(); this._workerTasks.set(freeWorker, task); @@ -381,7 +384,8 @@ * @return {!Formatter.FormatterWorkerPool} */ Formatter.formatterWorkerPool = function() { - if (!Formatter._formatterWorkerPool) + if (!Formatter._formatterWorkerPool) { Formatter._formatterWorkerPool = new Formatter.FormatterWorkerPool(); + } return Formatter._formatterWorkerPool; };
diff --git a/third_party/blink/renderer/devtools/front_end/formatter/ScriptFormatter.js b/third_party/blink/renderer/devtools/front_end/formatter/ScriptFormatter.js index 0dbe74b..7b02690a 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter/ScriptFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/formatter/ScriptFormatter.js
@@ -39,10 +39,11 @@ * @param {function(string, !Formatter.FormatterSourceMapping)} callback */ Formatter.Formatter.format = function(contentType, mimeType, content, callback) { - if (contentType.isDocumentOrScriptOrStyleSheet()) + if (contentType.isDocumentOrScriptOrStyleSheet()) { new Formatter.ScriptFormatter(mimeType, content, callback); - else + } else { new Formatter.ScriptIdentityFormatter(mimeType, content, callback); + } }; /** @@ -64,10 +65,11 @@ Formatter.Formatter.positionToLocation = function(lineEndings, position) { const lineNumber = lineEndings.upperBound(position - 1); let columnNumber; - if (!lineNumber) + if (!lineNumber) { columnNumber = position; - else + } else { columnNumber = position - lineEndings[lineNumber - 1] - 1; + } return [lineNumber, columnNumber]; }; @@ -221,8 +223,9 @@ _convertPosition(positions1, positions2, position) { const index = positions1.upperBound(position) - 1; let convertedPosition = positions2[index] + position - positions1[index]; - if (index < positions2.length - 1 && convertedPosition > positions2[index + 1]) + if (index < positions2.length - 1 && convertedPosition > positions2[index + 1]) { convertedPosition = positions2[index + 1]; + } return convertedPosition; } };
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker.js b/third_party/blink/renderer/devtools/front_end/formatter_worker.js index 644ad39..26dd25ea 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker.js
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Release build has Runtime.js bundled. -if (!self.Runtime) +if (!self.Runtime) { self.importScripts('Runtime.js'); +} Runtime.startWorker('formatter_worker');
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/AcornTokenizer.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/AcornTokenizer.js index e20b79d2..d8f75e69 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/AcornTokenizer.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/AcornTokenizer.js
@@ -69,8 +69,9 @@ * @return {!Acorn.TokenOrComment} */ _nextTokenInternal() { - if (this._comments.length) + if (this._comments.length) { return this._comments.shift(); + } const token = this._bufferedToken; this._bufferedToken = this._tokenizer.getToken(); @@ -82,8 +83,9 @@ */ nextToken() { const token = this._nextTokenInternal(); - if (token.type === acorn.tokTypes.eof) + if (token.type === acorn.tokTypes.eof) { return null; + } this._textCursor.advance(token.start); this._tokenLineStart = this._textCursor.lineNumber(); @@ -98,8 +100,9 @@ * @return {?Acorn.TokenOrComment} */ peekToken() { - if (this._comments.length) + if (this._comments.length) { return this._comments[0]; + } return this._bufferedToken.type !== acorn.tokTypes.eof ? this._bufferedToken : null; }
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSFormatter.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSFormatter.js index 194da08..a48db66 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSFormatter.js
@@ -65,29 +65,35 @@ _tokenCallback(token, type, startPosition) { startPosition += this._fromOffset; const startLine = this._lineEndings.lowerBound(startPosition); - if (startLine !== this._lastLine) + if (startLine !== this._lastLine) { this._state.eatWhitespace = true; - if (/^property/.test(type) && !this._state.inPropertyValue) + } + if (/^property/.test(type) && !this._state.inPropertyValue) { this._state.seenProperty = true; + } this._lastLine = startLine; const isWhitespace = /^\s+$/.test(token); if (isWhitespace) { - if (!this._state.eatWhitespace) + if (!this._state.eatWhitespace) { this._builder.addSoftSpace(); + } return; } this._state.eatWhitespace = false; - if (token === '\n') + if (token === '\n') { return; + } if (token !== '}') { - if (this._state.afterClosingBrace) + if (this._state.afterClosingBrace) { this._builder.addNewLine(true); + } this._state.afterClosingBrace = false; } if (token === '}') { - if (this._state.inPropertyValue) + if (this._state.inPropertyValue) { this._builder.addNewLine(); + } this._builder.decreaseNestingLevel(); this._state.afterClosingBrace = true; this._state.inPropertyValue = false; @@ -108,8 +114,9 @@ this._builder.addToken(token, startPosition); - if (type === 'comment' && !this._state.inPropertyValue && !this._state.seenProperty) + if (type === 'comment' && !this._state.inPropertyValue && !this._state.seenProperty) { this._builder.addNewLine(); + } if (token === ';' && this._state.inPropertyValue) { this._state.inPropertyValue = false; this._builder.addNewLine();
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSRuleParser.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSRuleParser.js index b2c4c54..40f4cf7 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSRuleParser.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/CSSRuleParser.js
@@ -99,8 +99,9 @@ } else if (tokenType.has('comment')) { // The |processToken| is called per-line, so no token spans more than one line. // Support only a one-line comments. - if (tokenValue.substring(0, 2) !== '/*' || tokenValue.substring(tokenValue.length - 2) !== '*/') + if (tokenValue.substring(0, 2) !== '/*' || tokenValue.substring(tokenValue.length - 2) !== '*/') { break; + } const uncommentedText = tokenValue.substring(2, tokenValue.length - 2); const fakeRule = 'a{\n' + uncommentedText + '}'; disabledRules = [];
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/ESTreeWalker.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/ESTreeWalker.js index 93f03cb..fcaa3060 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/ESTreeWalker.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/ESTreeWalker.js
@@ -40,8 +40,9 @@ node = /** @type {!ESTree.Node} */ (result); } - if (!node) + if (!node) { return; + } node.parent = parent; if (this._beforeVisit.call(null, node) === FormatterWorker.ESTreeWalker.SkipSubtree) { @@ -66,10 +67,11 @@ } else { for (let i = 0; i < walkOrder.length; ++i) { const entity = node[walkOrder[i]]; - if (Array.isArray(entity)) + if (Array.isArray(entity)) { this._walkArray(entity, node); - else + } else { this._innerWalk(entity, node); + } } } @@ -81,8 +83,9 @@ * @param {?ESTree.Node} parentNode */ _walkArray(nodeArray, parentNode) { - for (let i = 0; i < nodeArray.length; ++i) + for (let i = 0; i < nodeArray.length; ++i) { this._innerWalk(nodeArray[i], parentNode); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/FormattedContentBuilder.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/FormattedContentBuilder.js index 4a2feb2..756fca5 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/FormattedContentBuilder.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/FormattedContentBuilder.js
@@ -45,8 +45,9 @@ */ addToken(token, offset) { const last = this._formattedContent.peekLast(); - if (this._enforceSpaceBetweenWords && last && /\w/.test(last[last.length - 1]) && /\w/.test(token)) + if (this._enforceSpaceBetweenWords && last && /\w/.test(last[last.length - 1]) && /\w/.test(token)) { this.addSoftSpace(); + } this._appendFormatting(); @@ -56,8 +57,9 @@ } addSoftSpace() { - if (!this._hardSpaces) + if (!this._hardSpaces) { this._softSpace = true; + } } addHardSpace() { @@ -70,12 +72,14 @@ */ addNewLine(noSquash) { // Avoid leading newlines. - if (!this._formattedContentLength) + if (!this._formattedContentLength) { return; - if (noSquash) + } + if (noSquash) { ++this._newLines; - else + } else { this._newLines = this._newLines || 1; + } } increaseNestingLevel() { @@ -83,21 +87,24 @@ } decreaseNestingLevel() { - if (this._nestingLevel > 0) + if (this._nestingLevel > 0) { this._nestingLevel -= 1; + } } _appendFormatting() { if (this._newLines) { - for (let i = 0; i < this._newLines; ++i) + for (let i = 0; i < this._newLines; ++i) { this._addText('\n'); + } this._addText(this._indent()); } else if (this._softSpace) { this._addText(' '); } if (this._hardSpaces) { - for (let i = 0; i < this._hardSpaces; ++i) + for (let i = 0; i < this._hardSpaces; ++i) { this._addText(' '); + } } this._newLines = 0; this._softSpace = false; @@ -123,16 +130,19 @@ */ _indent() { const cachedValue = this._cachedIndents.get(this._nestingLevel); - if (cachedValue) + if (cachedValue) { return cachedValue; + } let fullIndent = ''; - for (let i = 0; i < this._nestingLevel; ++i) + for (let i = 0; i < this._nestingLevel; ++i) { fullIndent += this._indentString; + } // Cache a maximum of 20 nesting level indents. - if (this._nestingLevel <= 20) + if (this._nestingLevel <= 20) { this._cachedIndents.set(this._nestingLevel, fullIndent); + } return fullIndent; } @@ -148,8 +158,9 @@ * @param {number} originalPosition */ _addMappingIfNeeded(originalPosition) { - if (originalPosition - this._lastOriginalPosition === this._formattedContentLength - this._lastFormattedPosition) + if (originalPosition - this._lastOriginalPosition === this._formattedContentLength - this._lastFormattedPosition) { return; + } this._mapping.original.push(originalPosition); this._lastOriginalPosition = originalPosition; this._mapping.formatted.push(this._formattedContentLength);
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/FormatterWorker.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/FormatterWorker.js index debe39f..c37f746 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/FormatterWorker.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/FormatterWorker.js
@@ -46,8 +46,9 @@ while (!stream.eol()) { const style = mode.token(stream, state); const value = stream.current(); - if (callback(value, style, stream.start, stream.start + value.length) === FormatterWorker.AbortTokenization) + if (callback(value, style, stream.start, stream.start + value.length) === FormatterWorker.AbortTokenization) { return; + } stream.start = stream.pos; } } @@ -59,8 +60,9 @@ self.onmessage = function(event) { const method = /** @type {string} */ (event.data.method); const params = /** @type !{indentString: string, content: string, mimeType: string} */ (event.data.params); - if (!method) + if (!method) { return; + } switch (method) { case 'format': @@ -116,8 +118,9 @@ let result = ''; try { let token = tokenizer.getToken(); - while (token.type !== acorn.tokTypes.eof && FormatterWorker.AcornTokenizer.punctuator(token)) + while (token.type !== acorn.tokTypes.eof && FormatterWorker.AcornTokenizer.punctuator(token)) { token = tokenizer.getToken(); + } const startIndex = token.start; let endIndex = token.end; @@ -126,14 +129,16 @@ const isIdentifier = FormatterWorker.AcornTokenizer.identifier(token); const isThis = FormatterWorker.AcornTokenizer.keyword(token, 'this'); const isString = token.type === acorn.tokTypes.string; - if (!isThis && !isIdentifier && !isString) + if (!isThis && !isIdentifier && !isString) { break; + } endIndex = token.end; token = tokenizer.getToken(); while (FormatterWorker.AcornTokenizer.punctuator(token, '.[]')) { - if (FormatterWorker.AcornTokenizer.punctuator(token, '[')) + if (FormatterWorker.AcornTokenizer.punctuator(token, '[')) { openBracketsCounter++; + } if (FormatterWorker.AcornTokenizer.punctuator(token, ']')) { endIndex = openBracketsCounter > 0 ? token.end : endIndex; @@ -169,8 +174,9 @@ let containsReturn = false; class Visitor { ClassDeclaration(node) { - if (node.parent === body) + if (node.parent === body) { changes.push({text: node.id.name + '=', start: node.start, end: node.start}); + } } FunctionDeclaration(node) { changes.push({text: node.id.name + '=', start: node.start, end: node.start}); @@ -189,17 +195,20 @@ containsAwait = true; } ForOfStatement(node) { - if (node.await) + if (node.await) { containsAwait = true; + } } ReturnStatement(node) { containsReturn = true; } VariableDeclaration(node) { - if (node.kind !== 'var' && node.parent !== body) + if (node.kind !== 'var' && node.parent !== body) { return; - if (node.parent.type === 'ForOfStatement' && node.parent.left === node) + } + if (node.parent.type === 'ForOfStatement' && node.parent.left === node) { return; + } const onlyOneDeclaration = node.declarations.length === 1; changes.push( {text: onlyOneDeclaration ? 'void' : 'void (', start: node.start, end: node.start + node.kind.length}); @@ -225,8 +234,9 @@ * @this {Object} */ function visit(node) { - if (node.type in this) + if (node.type in this) { return this[node.type](node); + } } // Top-level return is not allowed. if (!containsAwait || containsReturn) { @@ -236,10 +246,11 @@ const last = body.body[body.body.length - 1]; if (last.type === 'ExpressionStatement') { changes.push({text: 'return (', start: last.start, end: last.start}); - if (wrapped[last.end - 1] !== ';') + if (wrapped[last.end - 1] !== ';') { changes.push({text: ')', start: last.end, end: last.end}); - else + } else { changes.push({text: ')', start: last.end - 1, end: last.end - 1}); + } } while (changes.length) { const change = changes.pop(); @@ -276,17 +287,20 @@ */ function beforeVisit(node) { if (isFunction(node)) { - if (node.id) + if (node.id) { identifiers.push(node.id); + } return FormatterWorker.ESTreeWalker.SkipSubtree; } - if (node.type !== 'Identifier') + if (node.type !== 'Identifier') { return; + } if (node.parent && node.parent.type === 'MemberExpression' && node.parent.property === node && - !node.parent.computed) + !node.parent.computed) { return; + } identifiers.push(node); } @@ -296,8 +310,9 @@ } const functionNode = root.body[0]; - for (const param of functionNode.params) + for (const param of functionNode.params) { walker.walk(param); + } walker.walk(functionNode.body); const reduced = identifiers.map(id => ({name: id.name, offset: id.start})); postMessage(reduced); @@ -351,8 +366,9 @@ * @return {?{baseExpression: string, possibleSideEffects:boolean, receiver: string, argumentIndex: number, functionName: string}} */ FormatterWorker.findLastFunctionCall = function(content) { - if (content.length > 10000) + if (content.length > 10000) { return null; + } try { const tokenizer = acorn.tokenizer(content, {ecmaVersion: FormatterWorker.ACORN_ECMA_VERSION}); while (tokenizer.getToken().type !== acorn.tokTypes.eof) { @@ -363,17 +379,19 @@ const suffix = '000)'; const base = FormatterWorker._lastCompleteExpression(content, suffix, new Set(['CallExpression', 'NewExpression'])); - if (!base) + if (!base) { return null; + } const callee = base.baseNode['callee']; let functionName = ''; const functionProperty = callee.type === 'Identifier' ? callee : callee.property; if (functionProperty) { - if (functionProperty.type === 'Identifier') + if (functionProperty.type === 'Identifier') { functionName = functionProperty.name; - else if (functionProperty.type === 'Literal') + } else if (functionProperty.type === 'Literal') { functionName = functionProperty.value; + } } const argumentIndex = base.baseNode['arguments'].length - 1; @@ -394,8 +412,9 @@ * @return {!Array<string>} */ FormatterWorker.argumentsList = function(content) { - if (content.length > 10000) + if (content.length > 10000) { return []; + } let parsed = null; try { // Try to parse as a function, anonymous function, or arrow function. @@ -409,21 +428,25 @@ } catch (e) { } } - if (!parsed || !parsed.body || !parsed.body[0] || !parsed.body[0].expression) + if (!parsed || !parsed.body || !parsed.body[0] || !parsed.body[0].expression) { return []; + } const expression = parsed.body[0].expression; let params = null; switch (expression.type) { case 'ClassExpression': - if (!expression.body.body) + if (!expression.body.body) { break; + } const constructor = expression.body.body.find(method => method.kind === 'constructor'); - if (constructor) + if (constructor) { params = constructor.value.params; + } break; case 'ObjectExpression': - if (!expression.properties[0] || !expression.properties[0].value) + if (!expression.properties[0] || !expression.properties[0].value) { break; + } params = expression.properties[0].value.params; break; case 'FunctionExpression': @@ -431,8 +454,9 @@ params = expression.params; break; } - if (!params) + if (!params) { return []; + } return params.map(paramName); function paramName(param) { @@ -457,8 +481,9 @@ * @return {?{baseExpression: string, possibleSideEffects:boolean}} */ FormatterWorker.findLastExpression = function(content) { - if (content.length > 10000) + if (content.length > 10000) { return null; + } try { const tokenizer = acorn.tokenizer(content, {ecmaVersion: FormatterWorker.ACORN_ECMA_VERSION}); while (tokenizer.getToken().type !== acorn.tokTypes.eof) { @@ -472,12 +497,14 @@ acorn.parse(content + suffix, {ecmaVersion: FormatterWorker.ACORN_ECMA_VERSION}); } catch (parseError) { // If this is an invalid location for a '.', don't attempt to give autocomplete - if (parseError.message.startsWith('Unexpected token') && parseError.pos === content.length) + if (parseError.message.startsWith('Unexpected token') && parseError.pos === content.length) { return null; + } } const base = FormatterWorker._lastCompleteExpression(content, suffix, new Set(['MemberExpression', 'Identifier'])); - if (!base) + if (!base) { return null; + } const {baseExpression, baseNode} = base; const possibleSideEffects = FormatterWorker._nodeHasPossibleSideEffects(baseNode); return {baseExpression, possibleSideEffects}; @@ -502,21 +529,26 @@ } catch (e) { } } - if (!ast) + if (!ast) { return null; + } let baseNode = null; const walker = new FormatterWorker.ESTreeWalker(node => { - if (baseNode || node.end < ast.end) + if (baseNode || node.end < ast.end) { return FormatterWorker.ESTreeWalker.SkipSubtree; - if (types.has(node.type)) + } + if (types.has(node.type)) { baseNode = node; + } }); walker.walk(ast); - if (!baseNode) + if (!baseNode) { return null; + } let baseExpression = parsedContent.substring(baseNode.start, parsedContent.length - suffix.length); - if (baseExpression.startsWith('{')) + if (baseExpression.startsWith('{')) { baseExpression = `(${baseExpression})`; + } return {baseNode, baseExpression}; }; @@ -531,10 +563,12 @@ ]); let possibleSideEffects = false; const sideEffectwalker = new FormatterWorker.ESTreeWalker(node => { - if (!possibleSideEffects && !sideEffectFreeTypes.has(node.type)) + if (!possibleSideEffects && !sideEffectFreeTypes.has(node.type)) { possibleSideEffects = true; - if (possibleSideEffects) + } + if (possibleSideEffects) { return FormatterWorker.ESTreeWalker.SkipSubtree; + } }); sideEffectwalker.walk(/** @type {!ESTree.Node} */ (baseNode)); return possibleSideEffects; @@ -572,6 +606,7 @@ }; (function disableLoggingForTest() { - if (Runtime.queryParam('test')) + if (Runtime.queryParam('test')) { console.error = () => undefined; + } })();
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/HTMLFormatter.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/HTMLFormatter.js index 8419e5ed..8c7a8e7 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/HTMLFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/HTMLFormatter.js
@@ -40,13 +40,15 @@ * @param {!FormatterWorker.HTMLModel.Element} element */ _walk(element) { - if (element.parent) + if (element.parent) { this._formatTokensTill(element.parent, element.openTag.startOffset); + } this._beforeOpenTag(element); this._formatTokensTill(element, element.openTag.endOffset); this._afterOpenTag(element); - for (let i = 0; i < element.children.length; ++i) + for (let i = 0; i < element.children.length; ++i) { this._walk(element.children[i]); + } this._formatTokensTill(element, element.closeTag.startOffset); this._beforeCloseTag(element); @@ -58,8 +60,9 @@ * @param {!FormatterWorker.HTMLModel.Element} element */ _beforeOpenTag(element) { - if (!element.children.length || element === this._model.document()) + if (!element.children.length || element === this._model.document()) { return; + } this._builder.addNewLine(); } @@ -67,8 +70,9 @@ * @param {!FormatterWorker.HTMLModel.Element} element */ _afterOpenTag(element) { - if (!element.children.length || element === this._model.document()) + if (!element.children.length || element === this._model.document()) { return; + } this._builder.increaseNestingLevel(); this._builder.addNewLine(); } @@ -77,8 +81,9 @@ * @param {!FormatterWorker.HTMLModel.Element} element */ _beforeCloseTag(element) { - if (!element.children.length || element === this._model.document()) + if (!element.children.length || element === this._model.document()) { return; + } this._builder.decreaseNestingLevel(); this._builder.addNewLine(); } @@ -95,8 +100,9 @@ * @param {!FormatterWorker.HTMLModel.Token} token */ _formatToken(element, token) { - if (token.value.isWhitespace()) + if (token.value.isWhitespace()) { return; + } if (token.type.has('comment') || token.type.has('meta')) { this._builder.addNewLine(); this._builder.addToken(token.value.trim(), token.startOffset); @@ -126,8 +132,9 @@ return; } - if (!isBodyToken && token.type.has('attribute')) + if (!isBodyToken && token.type.has('attribute')) { this._builder.addSoftSpace(); + } this._builder.addToken(token.value, token.startOffset); } @@ -137,14 +144,17 @@ * @return {boolean} */ _scriptTagIsJavaScript(element) { - if (!element.openTag.attributes.has('type')) + if (!element.openTag.attributes.has('type')) { return true; + } let type = element.openTag.attributes.get('type').toLowerCase(); - if (!type) + if (!type) { return true; + } const isWrappedInQuotes = /^(["\'])(.*)\1$/.exec(type.trim()); - if (isWrappedInQuotes) + if (isWrappedInQuotes) { type = isWrappedInQuotes[2]; + } return FormatterWorker.HTMLFormatter.SupportedJavaScriptMimeTypes.has(type.trim()); } }; @@ -187,12 +197,14 @@ while (true) { tokenizer(text.substring(lastOffset), processToken.bind(this, lastOffset)); - if (lastOffset >= text.length) + if (lastOffset >= text.length) { break; + } const element = this._stack.peekLast(); lastOffset = lowerCaseText.indexOf('</' + element.name, lastOffset); - if (lastOffset === -1) + if (lastOffset === -1) { lastOffset = text.length; + } const tokenStart = element.openTag.endOffset; const tokenEnd = lastOffset; const tokenValue = text.substring(tokenStart, tokenEnd); @@ -226,8 +238,9 @@ const element = this._stack.peekLast(); if (element && (element.name === 'script' || element.name === 'style') && - element.openTag.endOffset === lastOffset) + element.openTag.endOffset === lastOffset) { return FormatterWorker.AbortTokenization; + } } } @@ -306,20 +319,23 @@ _onTagComplete(tag) { if (tag.isOpenTag) { const topElement = this._stack.peekLast(); - if (topElement !== this._document && topElement.openTag.selfClosingTag) + if (topElement !== this._document && topElement.openTag.selfClosingTag) { this._popElement(autocloseTag(topElement, topElement.openTag.endOffset)); - else if ( + } else if ( (topElement.name in FormatterWorker.HTMLModel.AutoClosingTags) && - FormatterWorker.HTMLModel.AutoClosingTags[topElement.name].has(tag.name)) + FormatterWorker.HTMLModel.AutoClosingTags[topElement.name].has(tag.name)) { this._popElement(autocloseTag(topElement, tag.startOffset)); + } this._pushElement(tag); return; } - while (this._stack.length > 1 && this._stack.peekLast().name !== tag.name) + while (this._stack.length > 1 && this._stack.peekLast().name !== tag.name) { this._popElement(autocloseTag(this._stack.peekLast(), tag.startOffset)); - if (this._stack.length === 1) + } + if (this._stack.length === 1) { return; + } this._popElement(tag); /**
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptFormatter.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptFormatter.js index 2ef7b32..8db99f9 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptFormatter.js
@@ -74,8 +74,9 @@ } else if (format[i] === '<') { this._builder.decreaseNestingLevel(); } else if (format[i] === 't') { - if (this._tokenizer.tokenLineStart() - this._lastLineNumber > 1) + if (this._tokenizer.tokenLineStart() - this._lastLineNumber > 1) { this._builder.addNewLine(true); + } this._lastLineNumber = this._tokenizer.tokenLineEnd(); this._builder.addToken(this._content.substring(token.start, token.end), this._fromOffset + token.start); } @@ -86,8 +87,9 @@ * @param {!ESTree.Node} node */ _beforeVisit(node) { - if (!node.parent) + if (!node.parent) { return; + } while (this._tokenizer.peekToken() && this._tokenizer.peekToken().start < node.start) { const token = /** @type {!Acorn.TokenOrComment} */ (this._tokenizer.nextToken()); const format = this._formatToken(node.parent, token); @@ -113,12 +115,15 @@ */ _inForLoopHeader(node) { const parent = node.parent; - if (!parent) + if (!parent) { return false; - if (parent.type === 'ForStatement') + } + if (parent.type === 'ForStatement') { return node === parent.init || node === parent.test || node === parent.update; - if (parent.type === 'ForInStatement' || parent.type === 'ForOfStatement') + } + if (parent.type === 'ForInStatement' || parent.type === 'ForOfStatement') { return node === parent.left || parent.right; + } return false; } @@ -129,132 +134,172 @@ */ _formatToken(node, token) { const AT = FormatterWorker.AcornTokenizer; - if (AT.lineComment(token)) + if (AT.lineComment(token)) { return 'tn'; - if (AT.blockComment(token)) + } + if (AT.blockComment(token)) { return 'tn'; + } if (node.type === 'ContinueStatement' || node.type === 'BreakStatement') { return node.label && AT.keyword(token) ? 'ts' : 't'; } else if (node.type === 'Identifier') { return 't'; } else if (node.type === 'ReturnStatement') { - if (AT.punctuator(token, ';')) + if (AT.punctuator(token, ';')) { return 't'; + } return node.argument ? 'ts' : 't'; } else if (node.type === 'Property') { - if (AT.punctuator(token, ':')) + if (AT.punctuator(token, ':')) { return 'ts'; + } return 't'; } else if (node.type === 'ArrayExpression') { - if (AT.punctuator(token, ',')) + if (AT.punctuator(token, ',')) { return 'ts'; + } return 't'; } else if (node.type === 'LabeledStatement') { - if (AT.punctuator(token, ':')) + if (AT.punctuator(token, ':')) { return 'ts'; + } } else if ( node.type === 'LogicalExpression' || node.type === 'AssignmentExpression' || node.type === 'BinaryExpression') { - if (AT.punctuator(token) && !AT.punctuator(token, '()')) + if (AT.punctuator(token) && !AT.punctuator(token, '()')) { return 'sts'; + } } else if (node.type === 'ConditionalExpression') { - if (AT.punctuator(token, '?:')) + if (AT.punctuator(token, '?:')) { return 'sts'; + } } else if (node.type === 'VariableDeclarator') { - if (AT.punctuator(token, '=')) + if (AT.punctuator(token, '=')) { return 'sts'; + } } else if (node.type === 'ObjectPattern') { - if (node.parent && node.parent.type === 'VariableDeclarator' && AT.punctuator(token, '{')) + if (node.parent && node.parent.type === 'VariableDeclarator' && AT.punctuator(token, '{')) { return 'st'; - if (AT.punctuator(token, ',')) + } + if (AT.punctuator(token, ',')) { return 'ts'; + } } else if (node.type === 'FunctionDeclaration') { - if (AT.punctuator(token, ',)')) + if (AT.punctuator(token, ',)')) { return 'ts'; + } } else if (node.type === 'FunctionExpression') { - if (AT.punctuator(token, ',)')) + if (AT.punctuator(token, ',)')) { return 'ts'; - if (AT.keyword(token, 'function')) + } + if (AT.keyword(token, 'function')) { return node.id ? 'ts' : 't'; + } } else if (node.type === 'WithStatement') { - if (AT.punctuator(token, ')')) + if (AT.punctuator(token, ')')) { return node.body && node.body.type === 'BlockStatement' ? 'ts' : 'tn>'; + } } else if (node.type === 'SwitchStatement') { - if (AT.punctuator(token, '{')) + if (AT.punctuator(token, '{')) { return 'tn>'; - if (AT.punctuator(token, '}')) + } + if (AT.punctuator(token, '}')) { return 'n<tn'; - if (AT.punctuator(token, ')')) + } + if (AT.punctuator(token, ')')) { return 'ts'; + } } else if (node.type === 'SwitchCase') { - if (AT.keyword(token, 'case')) + if (AT.keyword(token, 'case')) { return 'n<ts'; - if (AT.keyword(token, 'default')) + } + if (AT.keyword(token, 'default')) { return 'n<t'; - if (AT.punctuator(token, ':')) + } + if (AT.punctuator(token, ':')) { return 'tn>'; + } } else if (node.type === 'VariableDeclaration') { if (AT.punctuator(token, ',')) { let allVariablesInitialized = true; const declarations = /** @type {!Array.<!ESTree.Node>} */ (node.declarations); - for (let i = 0; i < declarations.length; ++i) + for (let i = 0; i < declarations.length; ++i) { allVariablesInitialized = allVariablesInitialized && !!declarations[i].init; + } return !this._inForLoopHeader(node) && allVariablesInitialized ? 'nSSts' : 'ts'; } } else if (node.type === 'BlockStatement') { - if (AT.punctuator(token, '{')) + if (AT.punctuator(token, '{')) { return node.body.length ? 'tn>' : 't'; - if (AT.punctuator(token, '}')) + } + if (AT.punctuator(token, '}')) { return node.body.length ? 'n<t' : 't'; + } } else if (node.type === 'CatchClause') { - if (AT.punctuator(token, ')')) + if (AT.punctuator(token, ')')) { return 'ts'; + } } else if (node.type === 'ObjectExpression') { - if (!node.properties.length) + if (!node.properties.length) { return 't'; - if (AT.punctuator(token, '{')) + } + if (AT.punctuator(token, '{')) { return 'tn>'; - if (AT.punctuator(token, '}')) + } + if (AT.punctuator(token, '}')) { return 'n<t'; - if (AT.punctuator(token, ',')) + } + if (AT.punctuator(token, ',')) { return 'tn'; + } } else if (node.type === 'IfStatement') { - if (AT.punctuator(token, ')')) + if (AT.punctuator(token, ')')) { return node.consequent && node.consequent.type === 'BlockStatement' ? 'ts' : 'tn>'; + } if (AT.keyword(token, 'else')) { const preFormat = node.consequent && node.consequent.type === 'BlockStatement' ? 'st' : 'n<t'; let postFormat = 'n>'; - if (node.alternate && (node.alternate.type === 'BlockStatement' || node.alternate.type === 'IfStatement')) + if (node.alternate && (node.alternate.type === 'BlockStatement' || node.alternate.type === 'IfStatement')) { postFormat = 's'; + } return preFormat + postFormat; } } else if (node.type === 'CallExpression') { - if (AT.punctuator(token, ',')) + if (AT.punctuator(token, ',')) { return 'ts'; + } } else if (node.type === 'SequenceExpression' && AT.punctuator(token, ',')) { return node.parent && node.parent.type === 'SwitchCase' ? 'ts' : 'tn'; } else if (node.type === 'ForStatement' || node.type === 'ForOfStatement' || node.type === 'ForInStatement') { - if (AT.punctuator(token, ';')) + if (AT.punctuator(token, ';')) { return 'ts'; - if (AT.keyword(token, 'in') || AT.identifier(token, 'of')) + } + if (AT.keyword(token, 'in') || AT.identifier(token, 'of')) { return 'sts'; + } - if (AT.punctuator(token, ')')) + if (AT.punctuator(token, ')')) { return node.body && node.body.type === 'BlockStatement' ? 'ts' : 'tn>'; + } } else if (node.type === 'WhileStatement') { - if (AT.punctuator(token, ')')) + if (AT.punctuator(token, ')')) { return node.body && node.body.type === 'BlockStatement' ? 'ts' : 'tn>'; + } } else if (node.type === 'DoWhileStatement') { const blockBody = node.body && node.body.type === 'BlockStatement'; - if (AT.keyword(token, 'do')) + if (AT.keyword(token, 'do')) { return blockBody ? 'ts' : 'tn>'; - if (AT.keyword(token, 'while')) + } + if (AT.keyword(token, 'while')) { return blockBody ? 'sts' : 'n<ts'; + } } else if (node.type === 'ClassBody') { - if (AT.punctuator(token, '{')) + if (AT.punctuator(token, '{')) { return 'stn>'; - if (AT.punctuator(token, '}')) + } + if (AT.punctuator(token, '}')) { return '<ntn'; + } return 't'; } else if (node.type === 'YieldExpression') { return 't'; @@ -270,43 +315,57 @@ */ _finishNode(node) { if (node.type === 'WithStatement') { - if (node.body && node.body.type !== 'BlockStatement') + if (node.body && node.body.type !== 'BlockStatement') { return 'n<'; + } } else if (node.type === 'VariableDeclaration') { - if (!this._inForLoopHeader(node)) + if (!this._inForLoopHeader(node)) { return 'n'; + } } else if (node.type === 'ForStatement' || node.type === 'ForOfStatement' || node.type === 'ForInStatement') { - if (node.body && node.body.type !== 'BlockStatement') + if (node.body && node.body.type !== 'BlockStatement') { return 'n<'; + } } else if (node.type === 'BlockStatement') { - if (node.parent && node.parent.type === 'IfStatement' && node.parent.alternate && node.parent.consequent === node) + if (node.parent && node.parent.type === 'IfStatement' && node.parent.alternate && + node.parent.consequent === node) { return ''; + } if (node.parent && node.parent.type === 'FunctionExpression' && node.parent.parent && - node.parent.parent.type === 'Property') + node.parent.parent.type === 'Property') { return ''; + } if (node.parent && node.parent.type === 'FunctionExpression' && node.parent.parent && - node.parent.parent.type === 'VariableDeclarator') + node.parent.parent.type === 'VariableDeclarator') { return ''; + } if (node.parent && node.parent.type === 'FunctionExpression' && node.parent.parent && - node.parent.parent.type === 'CallExpression') + node.parent.parent.type === 'CallExpression') { return ''; - if (node.parent && node.parent.type === 'DoWhileStatement') + } + if (node.parent && node.parent.type === 'DoWhileStatement') { return ''; - if (node.parent && node.parent.type === 'TryStatement' && node.parent.block === node) + } + if (node.parent && node.parent.type === 'TryStatement' && node.parent.block === node) { return 's'; - if (node.parent && node.parent.type === 'CatchClause' && node.parent.parent.finalizer) + } + if (node.parent && node.parent.type === 'CatchClause' && node.parent.parent.finalizer) { return 's'; + } return 'n'; } else if (node.type === 'WhileStatement') { - if (node.body && node.body.type !== 'BlockStatement') + if (node.body && node.body.type !== 'BlockStatement') { return 'n<'; + } } else if (node.type === 'IfStatement') { if (node.alternate) { - if (node.alternate.type !== 'BlockStatement' && node.alternate.type !== 'IfStatement') + if (node.alternate.type !== 'BlockStatement' && node.alternate.type !== 'IfStatement') { return '<'; + } } else if (node.consequent) { - if (node.consequent.type !== 'BlockStatement') + if (node.consequent.type !== 'BlockStatement') { return '<'; + } } } else if ( node.type === 'BreakStatement' || node.type === 'ContinueStatement' || node.type === 'ThrowStatement' ||
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptOutline.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptOutline.js index 8e3787f..3f0f74d 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptOutline.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/JavaScriptOutline.js
@@ -43,10 +43,12 @@ (node.type === 'MethodDefinition' || node.type === 'Property') && isNameNode(node.key) && isFunctionNode(node.value)) { const namePrefix = []; - if (node.kind === 'get' || node.kind === 'set') + if (node.kind === 'get' || node.kind === 'set') { namePrefix.push(node.kind); - if (node.static) + } + if (node.static) { namePrefix.push('static'); + } reportFunction(node.key, node.value, namePrefix.join(' ')); } } @@ -71,12 +73,15 @@ */ function reportFunction(nameNode, functionNode, namePrefix) { let name = stringifyNameNode(nameNode); - if (functionNode.generator) + if (functionNode.generator) { name = '*' + name; - if (namePrefix) + } + if (namePrefix) { name = namePrefix + ' ' + name; - if (functionNode.async) + } + if (functionNode.async) { name = 'async ' + name; + } textCursor.advance(nameNode.start); addOutlineItem({ @@ -92,10 +97,12 @@ * @return {boolean} */ function isNameNode(node) { - if (!node) + if (!node) { return false; - if (node.type === 'MemberExpression') + } + if (node.type === 'MemberExpression') { return !node.computed && node.property.type === 'Identifier'; + } return node.type === 'Identifier'; } @@ -104,8 +111,9 @@ * @return {boolean} */ function isFunctionNode(node) { - if (!node) + if (!node) { return false; + } return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; } @@ -122,8 +130,9 @@ * @return {string} */ function stringifyNameNode(node) { - if (node.type === 'MemberExpression') + if (node.type === 'MemberExpression') { node = /** @type {!ESTree.Node} */ (node.property); + } console.assert(node.type === 'Identifier', 'Cannot extract identifier from unknown type: ' + node.type); return /** @type {string} */ (node.name); } @@ -135,12 +144,13 @@ function stringifyArguments(params) { const result = []; for (const param of params) { - if (param.type === 'Identifier') + if (param.type === 'Identifier') { result.push(param.name); - else if (param.type === 'RestElement' && param.argument.type === 'Identifier') + } else if (param.type === 'RestElement' && param.argument.type === 'Identifier') { result.push('...' + param.argument.name); - else + } else { console.error('Error: unexpected function parameter type: ' + param.type); + } } return '(' + result.join(', ') + ')'; } @@ -150,8 +160,9 @@ */ function addOutlineItem(item) { outlineChunk.push(item); - if (textCursor.offset() - lastReportedOffset < chunkSize) + if (textCursor.offset() - lastReportedOffset < chunkSize) { return; + } postMessage({chunk: outlineChunk, isLastChunk: false}); outlineChunk = []; lastReportedOffset = textCursor.offset();
diff --git a/third_party/blink/renderer/devtools/front_end/formatter_worker/RelaxedJSONParser.js b/third_party/blink/renderer/devtools/front_end/formatter_worker/RelaxedJSONParser.js index cf08019..812d4a8 100644 --- a/third_party/blink/renderer/devtools/front_end/formatter_worker/RelaxedJSONParser.js +++ b/third_party/blink/renderer/devtools/front_end/formatter_worker/RelaxedJSONParser.js
@@ -50,8 +50,9 @@ walker.walk(root); - if (hasExpression) + if (hasExpression) { return null; + } return rootTip.length ? rootTip[0] : null; /** @@ -71,10 +72,11 @@ */ function applyValue(value) { stackData.tip[stackData.key] = value; - if (stackData.parentIsArray) + if (stackData.parentIsArray) { stackData.key++; - else + } else { stackData.state = null; + } } /** @@ -130,8 +132,9 @@ case 'ExpressionStatement': break; default: - if (stackData.state === States.ExpectValue) + if (stackData.state === States.ExpectValue) { applyValue(extractValue(node)); + } return FormatterWorker.ESTreeWalker.SkipSubtree; } } @@ -140,8 +143,9 @@ * @param {!ESTree.Node} node */ function afterVisit(node) { - if (node.type === 'ObjectExpression' || node.type === 'ArrayExpression') + if (node.type === 'ObjectExpression' || node.type === 'ArrayExpression') { popStack(); + } } /** @@ -153,8 +157,9 @@ const originalNode = node; let value; if (node.type === 'UnaryExpression' && (node.operator === '-' || node.operator === '+')) { - if (node.operator === '-') + if (node.operator === '-') { isNegative = true; + } node = /** @type {!ESTree.Node} */ (node.argument); }
diff --git a/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js b/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js index 1fa99ec..354b99fb 100644 --- a/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js +++ b/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js
@@ -7,8 +7,9 @@ * @param {*} data */ constructor(data) { - if (!data || typeof data !== 'object') + if (!data || typeof data !== 'object') { throw 'First parameter is expected to be an object'; + } } /** @@ -17,8 +18,9 @@ */ static _safeDate(data) { const date = new Date(data); - if (!Number.isNaN(date.getTime())) + if (!Number.isNaN(date.getTime())) { return date; + } throw 'Invalid date format'; } @@ -28,8 +30,9 @@ */ static _safeNumber(data) { const result = Number(data); - if (!Number.isNaN(result)) + if (!Number.isNaN(result)) { return result; + } throw 'Casting to number results in NaN'; } @@ -66,11 +69,13 @@ customAsNumber(name) { // Har specification says starting with '_' is a custom property, but closure uses '_' as a private property. let value = /** @type {!Object} */ (this)['_' + name]; - if (value === undefined) + if (value === undefined) { return; + } value = Number(value); - if (Number.isNaN(value)) + if (Number.isNaN(value)) { return; + } return value; } @@ -105,8 +110,9 @@ this.creator = new HARImporter.HARCreator(data['creator']); this.browser = data['browser'] ? new HARImporter.HARCreator(data['browser']) : undefined; this.pages = Array.isArray(data['pages']) ? data['pages'].map(page => new HARImporter.HARPage(page)) : []; - if (!Array.isArray(data['entries'])) + if (!Array.isArray(data['entries'])) { throw 'log.entries is expected to be an array'; + } this.entries = data['entries'].map(entry => new HARImporter.HAREntry(entry)); this.comment = HARImporter.HARBase._optionalString(data['comment']); } @@ -180,8 +186,9 @@ * @return {!HARImporter.HARInitiator|undefined} */ _importInitiator(initiator) { - if (typeof initiator !== 'object') + if (typeof initiator !== 'object') { return; + } return new HARImporter.HARInitiator(initiator); } @@ -191,13 +198,15 @@ * @return {!Array<!HARImporter.HARInitiator>|undefined} */ _importWebSocketMessages(inputMessages) { - if (!Array.isArray(inputMessages)) + if (!Array.isArray(inputMessages)) { return; + } const outputMessages = []; for (const message of inputMessages) { - if (typeof message !== 'object') + if (typeof message !== 'object') { return; + } outputMessages.push(new HARImporter.HARWebSocketMessage(message)); } return outputMessages;
diff --git a/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js b/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js index 9d675ef..bd3508a 100644 --- a/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js +++ b/third_party/blink/renderer/devtools/front_end/har_importer/HARImporter.js
@@ -10,8 +10,9 @@ static requestsFromHARLog(log) { /** @type {!Map<string, !HARImporter.HARPage>} */ const pages = new Map(); - for (const page of log.pages) + for (const page of log.pages) { pages.set(page.id, page); + } log.entries.sort((a, b) => a.startedDateTime - b.startedDateTime); @@ -40,8 +41,9 @@ pageLoads.set(entry.pageref, pageLoad); } HARImporter.Importer._fillRequestFromHAREntry(request, entry, pageLoad); - if (pageLoad) + if (pageLoad) { pageLoad.bindRequest(request); + } requests.push(request); } return requests; @@ -67,23 +69,26 @@ */ static _fillRequestFromHAREntry(request, entry, pageLoad) { // Request data. - if (entry.request.postData) + if (entry.request.postData) { request.setRequestFormData(true, entry.request.postData.text); - else + } else { request.setRequestFormData(false, null); + } request.connectionId = entry.connection || ''; request.requestMethod = entry.request.method; request.setRequestHeaders(entry.request.headers); // Response data. - if (entry.response.content.mimeType && entry.response.content.mimeType !== 'x-unknown') + if (entry.response.content.mimeType && entry.response.content.mimeType !== 'x-unknown') { request.mimeType = entry.response.content.mimeType; + } request.responseHeaders = entry.response.headers; request.statusCode = entry.response.status; request.statusText = entry.response.statusText; let protocol = entry.response.httpVersion.toLowerCase(); - if (protocol === 'http/2.0') + if (protocol === 'http/2.0') { protocol = 'h2'; + } request.protocol = protocol.replace(/^http\/2\.0?\+quic/, 'http/2+quic'); // Timing data. @@ -96,19 +101,22 @@ const bodySize = entry.response.bodySize > 0 ? entry.response.bodySize : 0; request.resourceSize = contentSize || (headersSize + bodySize); let transferSize = entry.response.customAsNumber('transferSize'); - if (transferSize === undefined) + if (transferSize === undefined) { transferSize = entry.response.headersSize + entry.response.bodySize; + } request.setTransferSize(transferSize >= 0 ? transferSize : 0); const fromCache = entry.customAsString('fromCache'); - if (fromCache === 'memory') + if (fromCache === 'memory') { request.setFromMemoryCache(); - else if (fromCache === 'disk') + } else if (fromCache === 'disk') { request.setFromDiskCache(); + } const contentData = {error: null, content: null, encoded: entry.response.content.encoding === 'base64'}; - if (entry.response.content.text !== undefined) + if (entry.response.content.text !== undefined) { contentData.content = entry.response.content.text; + } request.setContentDataProvider(async () => contentData); // Timing data. @@ -119,20 +127,25 @@ request.setResourceType(HARImporter.Importer._getResourceType(request, entry, pageLoad)); const priority = entry.customAsString('priority'); - if (Protocol.Network.ResourcePriority.hasOwnProperty(priority)) + if (Protocol.Network.ResourcePriority.hasOwnProperty(priority)) { request.setPriority(/** @type {!Protocol.Network.ResourcePriority} */ (priority)); + } const messages = entry.customAsArray('webSocketMessages'); if (messages) { for (const message of messages) { - if (message.time === undefined) + if (message.time === undefined) { continue; - if (!Object.values(SDK.NetworkRequest.WebSocketFrameType).includes(message.type)) + } + if (!Object.values(SDK.NetworkRequest.WebSocketFrameType).includes(message.type)) { continue; - if (message.opcode === undefined) + } + if (message.opcode === undefined) { continue; - if (message.data === undefined) + } + if (message.data === undefined) { continue; + } const mask = message.type === SDK.NetworkRequest.WebSocketFrameType.Send; request.addFrame( @@ -153,20 +166,24 @@ const customResourceTypeName = entry.customAsString('resourceType'); if (customResourceTypeName) { const customResourceType = Common.ResourceType.fromName(customResourceTypeName); - if (customResourceType) + if (customResourceType) { return customResourceType; + } } - if (pageLoad && pageLoad.mainRequest === request) + if (pageLoad && pageLoad.mainRequest === request) { return Common.resourceTypes.Document; + } const resourceTypeFromMime = Common.ResourceType.fromMimeType(entry.response.content.mimeType); - if (resourceTypeFromMime !== Common.resourceTypes.Other) + if (resourceTypeFromMime !== Common.resourceTypes.Other) { return resourceTypeFromMime; + } const resourceTypeFromUrl = Common.ResourceType.fromURL(entry.request.url); - if (resourceTypeFromUrl) + if (resourceTypeFromUrl) { return resourceTypeFromUrl; + } return Common.resourceTypes.Other; } @@ -183,8 +200,9 @@ * @return {number} */ function accumulateTime(timing) { - if (timing === undefined || timing < 0) + if (timing === undefined || timing < 0) { return -1; + } lastEntry += timing; return lastEntry; } @@ -195,8 +213,9 @@ // SSL is part of connect for both HAR and Chrome's format so subtract it here. const ssl = timings.ssl >= 0 ? timings.ssl : 0; - if (timings.connect > 0) + if (timings.connect > 0) { timings.connect -= ssl; + } const timing = { proxyStart: proxy > 0 ? lastEntry - proxy : -1, proxyEnd: proxy > 0 ? lastEntry : -1,
diff --git a/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js b/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js index 30509ab..e119b9c0 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js
@@ -135,14 +135,17 @@ HeapProfilerTestRunner.HeapNode.prototype = { linkNode: function(node, type, nameOrIndex) { - if (!this._builder) + if (!this._builder) { throw new Error('parent node is not connected to a snapshot'); + } - if (!node._builder) + if (!node._builder) { node._setBuilder(this._builder); + } - if (nameOrIndex === undefined) + if (nameOrIndex === undefined) { nameOrIndex = this._edgesCount; + } ++this._edgesCount; @@ -156,8 +159,9 @@ }, _setBuilder: function(builder) { - if (this._builder) + if (this._builder) { throw new Error('node reusing is prohibited'); + } this._builder = builder; this._ordinal = this._builder._registerNode(this); @@ -172,8 +176,9 @@ rawSnapshot.nodes.push(0); rawSnapshot.nodes.push(Object.keys(this._edges).length); - for (const i in this._edges) + for (const i in this._edges) { this._edges[i]._serialize(rawSnapshot); + } } }; @@ -185,8 +190,9 @@ HeapProfilerTestRunner.HeapEdge.prototype = { _serialize: function(rawSnapshot) { - if (!this._targetNode._builder) + if (!this._targetNode._builder) { throw new Error('Inconsistent state of node: ' + this._name + ' no builder assigned'); + } const builder = this._targetNode._builder; rawSnapshot.edges.push(builder.lookupEdgeType(this._type)); @@ -249,8 +255,9 @@ 'strings': [] }; - for (let i = 0; i < this._nodes.length; ++i) + for (let i = 0; i < this._nodes.length; ++i) { this._nodes[i]._serialize(rawSnapshot); + } rawSnapshot.strings = this._strings.slice(); const meta = rawSnapshot.snapshot.meta; @@ -270,25 +277,29 @@ }, lookupNodeType: function(typeName) { - if (typeName === undefined) + if (typeName === undefined) { throw new Error('wrong node type: ' + typeName); + } - if (!(typeName in this._nodeTypesMap)) + if (!(typeName in this._nodeTypesMap)) { throw new Error('wrong node type name: ' + typeName); + } return this._nodeTypesMap[typeName]; }, lookupEdgeType: function(typeName) { - if (!(typeName in this._edgeTypesMap)) + if (!(typeName in this._edgeTypesMap)) { throw new Error('wrong edge type name: ' + typeName); + } return this._edgeTypesMap[typeName]; }, lookupOrAddString: function(string) { - if (string in this._string2id) + if (string in this._string2id) { return this._string2id[string]; + } this._string2id[string] = this._strings.length; this._strings.push(string); @@ -364,8 +375,9 @@ function runner() { if (!testSuiteTests.length) { - if (completeTestStack) + if (completeTestStack) { TestRunner.addResult('FAIL: test already completed at ' + completeTestStack); + } HeapProfilerTestRunner.completeProfilerTest(); completeTestStack = new Error().stack; @@ -387,13 +399,15 @@ HeapProfilerTestRunner.assertColumnContentsEqual = function(reference, actual) { const length = Math.min(reference.length, actual.length); - for (let i = 0; i < length; ++i) + for (let i = 0; i < length; ++i) { TestRunner.assertEquals(reference[i], actual[i], 'row ' + i); + } - if (reference.length > length) + if (reference.length > length) { TestRunner.addResult('extra rows in reference array:\n' + reference.slice(length).join('\n')); - else if (actual.length > length) + } else if (actual.length > length) { TestRunner.addResult('extra rows in actual array:\n' + actual.slice(length).join('\n')); + } }; HeapProfilerTestRunner.checkArrayIsSorted = function(contents, sortType, sortOrder) { @@ -515,13 +529,15 @@ const parent = row || this._currentGrid().rootNode(); for (let node = parent.children[0]; node; node = node.traverseNextNode(true, parent, true)) { - if (!node.selectable) + if (!node.selectable) { continue; + } let content = node.element().children[columnOrdinal]; - if (content.firstElementChild) + if (content.firstElementChild) { content = content.firstElementChild; + } result.push(content.textContent); } @@ -537,8 +553,9 @@ }; for (let node = row.children[0]; node; node = node.traverseNextNode(true, row, true)) { - if (filter(node)) + if (filter(node)) { ++result; + } } return result; @@ -549,10 +566,11 @@ row.once(Profiler.HeapSnapshotGridNode.Events.PopulateComplete).then(() => setTimeout(() => callback(row), 0)); (function expand() { - if (row.hasChildren()) + if (row.hasChildren()) { row.expand(); - else + } else { setTimeout(expand, 0); + } })(); }; @@ -578,8 +596,9 @@ HeapProfilerTestRunner.findButtonsNode = function(row, startNode) { for (let node = startNode || row.children[0]; node; node = node.traverseNextNode(true, row, true)) { - if (!node.selectable && node.showNext) + if (!node.selectable && node.showNext) { return node; + } } return null; }; @@ -592,8 +611,9 @@ parent = parent || this._currentGrid().rootNode(); for (let node = parent.children[0]; node; node = node.traverseNextNode(true, parent, true)) { - if (matcher(node)) + if (matcher(node)) { return node; + } } return null; @@ -625,8 +645,9 @@ HeapProfilerTestRunner._takeAndOpenSnapshotCallback = callback; TestRunner.override(TestRunner.HeapProfilerAgent, 'takeHeapSnapshot', pushGeneratedSnapshot); - if (!UI.context.flavor(SDK.HeapProfilerModel)) + if (!UI.context.flavor(SDK.HeapProfilerModel)) { await new Promise(resolve => UI.context.addFlavorChangeListener(SDK.HeapProfilerModel, resolve)); + } profileType._takeHeapSnapshot(); }; @@ -641,10 +662,12 @@ function finishHeapSnapshot() { const profiles = heapProfileType.getProfiles(); - if (!profiles.length) + if (!profiles.length) { throw 'FAILED: no profiles found.'; - if (profiles.length > 1) + } + if (profiles.length > 1) { throw `FAILED: wrong number of recorded profiles was found. profiles.length = ${profiles.length}`; + } const profile = profiles[0]; UI.panels.heap_profiler.showProfile(profile); @@ -693,8 +716,9 @@ }; HeapProfilerTestRunner._profileHeaderAdded = function(profile) { - if (HeapProfilerTestRunner._showProfileWhenAdded === profile.title) + if (HeapProfilerTestRunner._showProfileWhenAdded === profile.title) { UI.panels.heap_profiler.showProfile(profile); + } }; HeapProfilerTestRunner._waitUntilProfileViewIsShown = function(title, callback) { @@ -702,10 +726,11 @@ const profilesPanel = UI.panels.heap_profiler; if (profilesPanel.visibleView && profilesPanel.visibleView.profile && - profilesPanel.visibleView._profileHeader.title === title) + profilesPanel.visibleView._profileHeader.title === title) { callback(profilesPanel.visibleView); - else + } else { HeapProfilerTestRunner._waitUntilProfileViewIsShownCallback = {title: title, callback: callback}; + } }; @@ -719,8 +744,9 @@ }; HeapProfilerTestRunner.startSamplingHeapProfiler = async function() { - if (!UI.context.flavor(SDK.HeapProfilerModel)) + if (!UI.context.flavor(SDK.HeapProfilerModel)) { await new Promise(resolve => UI.context.addFlavorChangeListener(SDK.HeapProfilerModel, resolve)); + } Profiler.SamplingHeapProfileType.instance._startRecordingProfile(); };
diff --git a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker.js b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker.js index ea60e79..1a3552b 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker.js +++ b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker.js
@@ -3,8 +3,9 @@ // found in the LICENSE file. // Release build has Runtime.js bundled. -if (!self.Runtime) +if (!self.Runtime) { self.importScripts('Runtime.js'); +} // Due to a lack of ESM within workers the functionality required by the // worker is duplicated here from Common. When ESM lands in Workers, this code @@ -29,8 +30,9 @@ * @return {*} */ function deserializeUIString(serializedMessage) { - if (!serializedMessage) + if (!serializedMessage) { return {}; + } return JSON.parse(serializedMessage); } @@ -49,8 +51,9 @@ * @return {string} */ self.ls = function(strings, vararg) { - if (typeof strings === 'string') + if (typeof strings === 'string') { return strings; + } let substitutionString = _substitutionStrings.get(strings); if (!substitutionString) { substitutionString = strings.join('%s');
diff --git a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/AllocationProfile.js b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/AllocationProfile.js index dcb9c9c..b58b2930 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/AllocationProfile.js +++ b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/AllocationProfile.js
@@ -96,8 +96,9 @@ functionInfo.addTraceTopNode(result); const rawChildren = rawNodeArray[nodeOffset + childrenOffset]; - for (let i = 0; i < rawChildren.length; i += nodeFieldCount) + for (let i = 0; i < rawChildren.length; i += nodeFieldCount) { result.children.push(traverseNode(rawChildren, i, result)); + } return result; } @@ -109,14 +110,16 @@ * @return {!Array.<!HeapSnapshotModel.SerializedAllocationNode>} */ serializeTraceTops() { - if (this._traceTops) + if (this._traceTops) { return this._traceTops; + } const result = this._traceTops = []; const functionInfos = this._functionInfos; for (let i = 0; i < functionInfos.length; i++) { const info = functionInfos[i]; - if (info.totalCount === 0) + if (info.totalCount === 0) { continue; + } const nodeId = this._nextNodeId++; const isRoot = i === 0; result.push(this._serializeNode( @@ -143,8 +146,9 @@ const branchingCallers = []; const callers = node.callers(); - for (let i = 0; i < callers.length; i++) + for (let i = 0; i < callers.length; i++) { branchingCallers.push(this._serializeCaller(callers[i])); + } return new HeapSnapshotModel.AllocationNodeCallers(nodesWithSingleCaller, branchingCallers); } @@ -324,8 +328,9 @@ * @param {!HeapSnapshotWorker.TopDownAllocationNode} node */ addTraceTopNode(node) { - if (node.allocationCount === 0) + if (node.allocationCount === 0) { return; + } this._traceTops.push(node); this.totalCount += node.allocationCount; this.totalSize += node.allocationSize; @@ -337,10 +342,12 @@ * @return {?HeapSnapshotWorker.BottomUpAllocationNode} */ bottomUpRoot() { - if (!this._traceTops.length) + if (!this._traceTops.length) { return null; - if (!this._bottomUpTree) + } + if (!this._bottomUpTree) { this._buildAllocationTraceTree(); + } return this._bottomUpTree; } @@ -362,8 +369,9 @@ bottomUpNode.liveSize += liveSize; bottomUpNode.traceTopIds.push(traceId); node = node.parent; - if (node === null) + if (node === null) { break; + } bottomUpNode = bottomUpNode.addCaller(node); }
diff --git a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js index 8ba5a2b3..3b59ae28 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js +++ b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshot.js
@@ -332,8 +332,9 @@ * @param {number} retainerIndex */ setRetainerIndex(retainerIndex) { - if (retainerIndex === this._retainerIndex) + if (retainerIndex === this._retainerIndex) { return; + } this._retainerIndex = retainerIndex; this._globalEdgeIndex = this._snapshot._retainingEdges[retainerIndex]; this._retainingNodeIndex = this._snapshot._retainingNodes[retainerIndex]; @@ -349,14 +350,16 @@ } _node() { - if (!this._nodeInstance) + if (!this._nodeInstance) { this._nodeInstance = this._snapshot.createNode(this._retainingNodeIndex); + } return this._nodeInstance; } _edge() { - if (!this._edgeInstance) + if (!this._edgeInstance) { this._edgeInstance = this._snapshot.createEdge(this._globalEdgeIndex); + } return this._edgeInstance; } @@ -736,8 +739,9 @@ } _skipFilteredItems() { - while (this._iterator.hasNext() && !this._filter(this._iterator.item())) + while (this._iterator.hasNext() && !this._filter(this._iterator.item())) { this._iterator.next(); + } } }; @@ -774,8 +778,9 @@ */ reportProblem(error) { // May be undefined in tests. - if (this._dispatcher) + if (this._dispatcher) { this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot, error); + } } /** @@ -783,8 +788,9 @@ */ _sendUpdateEvent(serializedText) { // May be undefined in tests. - if (this._dispatcher) + if (this._dispatcher) { this._dispatcher.sendEvent(HeapSnapshotModel.HeapSnapshotProgressEvent.Update, serializedText); + } } }; @@ -803,8 +809,9 @@ * @param {string} error */ addError(error) { - if (this._errors.length > 100) + if (this._errors.length > 100) { return; + } this._errors.push(error); } @@ -844,8 +851,9 @@ this._noDistance = -5; this._rootNodeIndex = 0; - if (profile.snapshot.root_index) + if (profile.snapshot.root_index) { this._rootNodeIndex = profile.snapshot.root_index; + } this._snapshotDiffs = {}; this._aggregatesForDiff = null; @@ -949,8 +957,9 @@ node.nodeIndex = nodeIndex; const traceNodeId = node.traceNodeId(); let stats = liveObjects[traceNodeId]; - if (!stats) + if (!stats) { liveObjects[traceNodeId] = stats = {count: 0, size: 0, ids: []}; + } stats.count++; stats.size += node.selfSize(); stats.ids.push(node.id()); @@ -991,8 +1000,9 @@ for (let toNodeFieldIndex = edgeToNodeOffset, l = containmentEdges.length; toNodeFieldIndex < l; toNodeFieldIndex += edgeFieldsCount) { const toNodeIndex = containmentEdges[toNodeFieldIndex]; - if (toNodeIndex % nodeFieldCount) + if (toNodeIndex % nodeFieldCount) { throw new Error('Invalid toNodeIndex ' + toNodeIndex); + } ++firstRetainerIndex[toNodeIndex / nodeFieldCount]; } for (let i = 0, firstUnusedRetainerSlot = 0; i < nodeCount; i++) { @@ -1010,8 +1020,9 @@ const srcNodeIndex = srcNodeOrdinal * nodeFieldCount; for (let edgeIndex = firstEdgeIndex; edgeIndex < nextNodeFirstEdgeIndex; edgeIndex += edgeFieldsCount) { const toNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; - if (toNodeIndex % nodeFieldCount) + if (toNodeIndex % nodeFieldCount) { throw new Error('Invalid toNodeIndex ' + toNodeIndex); + } const firstRetainerSlotIndex = firstRetainerIndex[toNodeIndex / nodeFieldCount]; const nextUnusedRetainerSlotIndex = firstRetainerSlotIndex + (--retainingNodes[firstRetainerSlotIndex]); retainingNodes[nextUnusedRetainerSlotIndex] = srcNodeIndex; @@ -1076,8 +1087,9 @@ * @return {number} */ _getDominatedIndex(nodeIndex) { - if (nodeIndex % this._nodeFieldCount) + if (nodeIndex % this._nodeFieldCount) { throw new Error('Invalid nodeIndex: ' + nodeIndex); + } return this._firstDominatedNodeIndex[nodeIndex / this._nodeFieldCount]; } @@ -1109,23 +1121,26 @@ const query = searchConfig.query; function filterString(matchedStringIndexes, string, index) { - if (string.indexOf(query) !== -1) + if (string.indexOf(query) !== -1) { matchedStringIndexes.add(index); + } return matchedStringIndexes; } const regexp = searchConfig.isRegex ? new RegExp(query) : createPlainTextSearchRegex(query, 'i'); function filterRegexp(matchedStringIndexes, string, index) { - if (regexp.test(string)) + if (regexp.test(string)) { matchedStringIndexes.add(index); + } return matchedStringIndexes; } const stringFilter = (searchConfig.isRegex || !searchConfig.caseSensitive) ? filterRegexp : filterString; const stringIndexes = this.strings.reduce(stringFilter, new Set()); - if (!stringIndexes.size) + if (!stringIndexes.size) { return []; + } const filter = this._createFilter(nodeFilter); const nodeIds = []; @@ -1138,10 +1153,12 @@ for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { node.nodeIndex = nodeIndex; - if (filter && !filter(node)) + if (filter && !filter(node)) { continue; - if (stringIndexes.has(nodes[nodeIndex + nodeNameOffset])) + } + if (stringIndexes.has(nodes[nodeIndex + nodeNameOffset])) { nodeIds.push(nodes[nodeIndex + nodeIdOffset]); + } } return nodeIds; } @@ -1179,11 +1196,13 @@ */ _createAllocationStackFilter(bottomUpAllocationNodeId) { const traceIds = this._allocationProfile.traceIds(bottomUpAllocationNodeId); - if (!traceIds.length) + if (!traceIds.length) { return undefined; + } const set = {}; - for (let i = 0; i < traceIds.length; i++) + for (let i = 0; i < traceIds.length; i++) { set[traceIds[i]] = true; + } /** * @param {!HeapSnapshotWorker.HeapSnapshotNode} node * @return {boolean} @@ -1206,14 +1225,16 @@ const aggregates = this._buildAggregates(filter); this._calculateClassesRetainedSize(aggregates.aggregatesByClassIndex, filter); aggregatesByClassName = aggregates.aggregatesByClassName; - if (key) + if (key) { this._aggregates[key] = aggregatesByClassName; + } } if (sortedIndexes && (!key || !this._aggregatesSortedFlags[key])) { this._sortAggregateIndexes(aggregatesByClassName); - if (key) + if (key) { this._aggregatesSortedFlags[key] = sortedIndexes; + } } return aggregatesByClassName; } @@ -1240,8 +1261,9 @@ allocationStack(nodeIndex) { const node = this.createNode(nodeIndex); const allocationNodeId = node.traceNodeId(); - if (!allocationNodeId) + if (!allocationNodeId) { return null; + } return this._allocationProfile.serializeAllocationStack(allocationNodeId); } @@ -1249,8 +1271,9 @@ * @return {!Object.<string, !HeapSnapshotModel.AggregateForDiff>} */ aggregatesForDiff() { - if (this._aggregatesForDiff) + if (this._aggregatesForDiff) { return this._aggregatesForDiff; + } const aggregatesByClassName = this.aggregates(true, 'allObjects'); this._aggregatesForDiff = {}; @@ -1288,8 +1311,9 @@ const nodeCount = this.nodeCount; const distances = this._nodeDistances; const noDistance = this._noDistance; - for (let i = 0; i < nodeCount; ++i) + for (let i = 0; i < nodeCount; ++i) { distances[i] = noDistance; + } const nodesToVisit = new Uint32Array(this.nodeCount); let nodesToVisitLength = 0; @@ -1341,15 +1365,18 @@ node.nodeIndex = nodeIndex; for (let edgeIndex = firstEdgeIndex; edgeIndex < edgesEnd; edgeIndex += edgeFieldsCount) { const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (edgeType === edgeWeakType) + if (edgeType === edgeWeakType) { continue; + } const childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; const childNodeOrdinal = childNodeIndex / nodeFieldCount; - if (distances[childNodeOrdinal] !== noDistance) + if (distances[childNodeOrdinal] !== noDistance) { continue; + } edge.edgeIndex = edgeIndex; - if (filter && !filter(node, edge)) + if (filter && !filter(node, edge)) { continue; + } distances[childNodeOrdinal] = distance; nodesToVisit[nodesToVisitLength++] = childNodeIndex; } @@ -1380,11 +1407,13 @@ for (let nodeIndex = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { node.nodeIndex = nodeIndex; - if (filter && !filter(node)) + if (filter && !filter(node)) { continue; + } const selfSize = nodes[nodeIndex + selfSizeOffset]; - if (!selfSize && nodes[nodeIndex + nodeTypeOffset] !== nodeNativeType) + if (!selfSize && nodes[nodeIndex + nodeTypeOffset] !== nodeNativeType) { continue; + } const classIndex = node.classIndex(); const nodeOrdinal = nodeIndex / nodeFieldCount; const distance = nodeDistances[nodeOrdinal]; @@ -1456,8 +1485,9 @@ classes.push(classIndex); } } - for (let i = dominatedIndexFrom; i < dominatedIndexTo; i++) + for (let i = dominatedIndexFrom; i < dominatedIndexTo; i++) { list.push(dominatedNodes[i]); + } const l = list.length; while (sizes[sizes.length - 1] === l) { @@ -1535,18 +1565,21 @@ if (edgeIndex < edgesEnd) { stackCurrentEdge[stackTop] += edgeFieldsCount; const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (!this._isEssentialEdge(nodeOrdinal * nodeFieldCount, edgeType)) + if (!this._isEssentialEdge(nodeOrdinal * nodeFieldCount, edgeType)) { continue; + } const childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; const childNodeOrdinal = childNodeIndex / nodeFieldCount; - if (visited[childNodeOrdinal]) + if (visited[childNodeOrdinal]) { continue; + } const nodeFlag = !flags || (flags[nodeOrdinal] & flag); const childNodeFlag = !flags || (flags[childNodeOrdinal] & flag); // We are skipping the edges from non-page-owned nodes to page-owned nodes. // Otherwise the dominators for the objects that also were retained by debugger would be affected. - if (nodeOrdinal !== rootNodeOrdinal && childNodeFlag && !nodeFlag) + if (nodeOrdinal !== rootNodeOrdinal && childNodeFlag && !nodeFlag) { continue; + } ++stackTop; stackNodes[stackTop] = childNodeOrdinal; stackCurrentEdge[stackTop] = firstEdgeIndexes[childNodeOrdinal]; @@ -1559,8 +1592,9 @@ } } - if (postOrderIndex === nodeCount || iteration > 1) + if (postOrderIndex === nodeCount || iteration > 1) { break; + } const errors = new HeapSnapshotWorker.HeapSnapshotProblemReport( `Heap snapshot: ${ nodeCount - postOrderIndex @@ -1573,8 +1607,9 @@ stackNodes[0] = rootNodeOrdinal; stackCurrentEdge[0] = firstEdgeIndexes[rootNodeOrdinal + 1]; // no need to reiterate its edges for (let i = 0; i < nodeCount; ++i) { - if (visited[i] || !this._hasOnlyWeakRetainers(i)) + if (visited[i] || !this._hasOnlyWeakRetainers(i)) { continue; + } // Add all nodes that have only weak retainers to traverse their subgraphs. stackNodes[++stackTop] = i; @@ -1583,8 +1618,9 @@ dumpNode.nodeIndex = i * nodeFieldCount; const retainers = []; - for (let it = dumpNode.retainers(); it.hasNext(); it.next()) + for (let it = dumpNode.retainers(); it.hasNext(); it.next()) { retainers.push(`${it.item().node().name()}@${it.item().node().id()}.${it.item().name()}`); + } errors.addError(`${dumpNode.name()} @${dumpNode.id()} weak retainers: ${retainers.join(', ')}`); } console.warn(errors.toString()); @@ -1599,8 +1635,9 @@ // visited after all orphan nodes and their subgraphs. --postOrderIndex; for (let i = 0; i < nodeCount; ++i) { - if (visited[i]) + if (visited[i]) { continue; + } dumpNode.nodeIndex = i * nodeFieldCount; errors.addError(dumpNode.name() + ' @' + dumpNode.id()); // Fix it by giving the node a postorder index anyway. @@ -1633,8 +1670,9 @@ for (let retainerIndex = beginRetainerIndex; retainerIndex < endRetainerIndex; ++retainerIndex) { const retainerEdgeIndex = retainingEdges[retainerIndex]; const retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; - if (retainerEdgeType !== edgeWeakType && retainerEdgeType !== edgeShortcutType) + if (retainerEdgeType !== edgeWeakType && retainerEdgeType !== edgeShortcutType) { return false; + } } return true; } @@ -1666,8 +1704,9 @@ const rootPostOrderedIndex = nodesCount - 1; const noEntry = nodesCount; const dominators = new Uint32Array(nodesCount); - for (let i = 0; i < rootPostOrderedIndex; ++i) + for (let i = 0; i < rootPostOrderedIndex; ++i) { dominators[i] = noEntry; + } dominators[rootPostOrderedIndex] = rootPostOrderedIndex; // The affected array is used to mark entries which dominators @@ -1680,8 +1719,9 @@ const endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (let edgeIndex = firstEdgeIndexes[nodeOrdinal]; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (!this._isEssentialEdge(this._rootNodeIndex, edgeType)) + if (!this._isEssentialEdge(this._rootNodeIndex, edgeType)) { continue; + } const childNodeOrdinal = containmentEdges[edgeIndex + edgeToNodeOffset] / nodeFieldCount; affected[nodeOrdinal2PostOrderIndex[childNodeOrdinal]] = 1; } @@ -1691,13 +1731,15 @@ while (changed) { changed = false; for (let postOrderIndex = rootPostOrderedIndex - 1; postOrderIndex >= 0; --postOrderIndex) { - if (affected[postOrderIndex] === 0) + if (affected[postOrderIndex] === 0) { continue; + } affected[postOrderIndex] = 0; // If dominator of the entry has already been set to root, // then it can't propagate any further. - if (dominators[postOrderIndex] === rootPostOrderedIndex) + if (dominators[postOrderIndex] === rootPostOrderedIndex) { continue; + } nodeOrdinal = postOrderIndex2NodeOrdinal[postOrderIndex]; const nodeFlag = !flags || (flags[nodeOrdinal] & flag); let newDominatorIndex = noEntry; @@ -1708,36 +1750,42 @@ const retainerEdgeIndex = retainingEdges[retainerIndex]; const retainerEdgeType = containmentEdges[retainerEdgeIndex + edgeTypeOffset]; const retainerNodeIndex = retainingNodes[retainerIndex]; - if (!this._isEssentialEdge(retainerNodeIndex, retainerEdgeType)) + if (!this._isEssentialEdge(retainerNodeIndex, retainerEdgeType)) { continue; + } orphanNode = false; const retainerNodeOrdinal = retainerNodeIndex / nodeFieldCount; const retainerNodeFlag = !flags || (flags[retainerNodeOrdinal] & flag); // We are skipping the edges from non-page-owned nodes to page-owned nodes. // Otherwise the dominators for the objects that also were retained by debugger would be affected. - if (retainerNodeIndex !== rootNodeIndex && nodeFlag && !retainerNodeFlag) + if (retainerNodeIndex !== rootNodeIndex && nodeFlag && !retainerNodeFlag) { continue; + } let retanerPostOrderIndex = nodeOrdinal2PostOrderIndex[retainerNodeOrdinal]; if (dominators[retanerPostOrderIndex] !== noEntry) { if (newDominatorIndex === noEntry) { newDominatorIndex = retanerPostOrderIndex; } else { while (retanerPostOrderIndex !== newDominatorIndex) { - while (retanerPostOrderIndex < newDominatorIndex) + while (retanerPostOrderIndex < newDominatorIndex) { retanerPostOrderIndex = dominators[retanerPostOrderIndex]; - while (newDominatorIndex < retanerPostOrderIndex) + } + while (newDominatorIndex < retanerPostOrderIndex) { newDominatorIndex = dominators[newDominatorIndex]; + } } } // If idom has already reached the root, it doesn't make sense // to check other retainers. - if (newDominatorIndex === rootPostOrderedIndex) + if (newDominatorIndex === rootPostOrderedIndex) { break; + } } } // Make root dominator of orphans. - if (orphanNode) + if (orphanNode) { newDominatorIndex = rootPostOrderedIndex; + } if (newDominatorIndex !== noEntry && dominators[postOrderIndex] !== newDominatorIndex) { dominators[postOrderIndex] = newDominatorIndex; changed = true; @@ -1772,8 +1820,9 @@ const dominatorsTree = this._dominatorsTree; const retainedSizes = this._retainedSizes; - for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) + for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; ++nodeOrdinal) { retainedSizes[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset]; + } // Propagate retained sizes for each node excluding root. for (let postOrderIndex = 0; postOrderIndex < nodeCount - 1; ++postOrderIndex) { @@ -1801,14 +1850,16 @@ let fromNodeOrdinal = 0; let toNodeOrdinal = this.nodeCount; const rootNodeOrdinal = this._rootNodeIndex / nodeFieldCount; - if (rootNodeOrdinal === fromNodeOrdinal) + if (rootNodeOrdinal === fromNodeOrdinal) { fromNodeOrdinal = 1; - else if (rootNodeOrdinal === toNodeOrdinal - 1) + } else if (rootNodeOrdinal === toNodeOrdinal - 1) { toNodeOrdinal = toNodeOrdinal - 1; - else + } else { throw new Error('Root node is expected to be either first or last'); - for (let nodeOrdinal = fromNodeOrdinal; nodeOrdinal < toNodeOrdinal; ++nodeOrdinal) + } + for (let nodeOrdinal = fromNodeOrdinal; nodeOrdinal < toNodeOrdinal; ++nodeOrdinal) { ++indexArray[dominatorsTree[nodeOrdinal]]; + } // Put in the first slot of each dominatedNodes slice the count of entries // that will be filled. let firstDominatedNodeIndex = 0; @@ -1830,8 +1881,9 @@ _buildSamples() { const samples = this._rawSamples; - if (!samples || !samples.length) + if (!samples || !samples.length) { return; + } const sampleCount = samples.length / 2; const sizeForRange = new Array(sampleCount); const timestamps = new Array(sampleCount); @@ -1854,8 +1906,9 @@ const nodeId = node.id(); // JS objects have odd ids, skip native objects. - if (nodeId % 2 === 0) + if (nodeId % 2 === 0) { continue; + } const rangeIndex = lastAssignedIds.lowerBound(nodeId); if (rangeIndex === sampleCount) { // TODO: make heap profiler not allocate while taking snapshot @@ -1922,21 +1975,24 @@ */ calculateSnapshotDiff(baseSnapshotId, baseSnapshotAggregates) { let snapshotDiff = this._snapshotDiffs[baseSnapshotId]; - if (snapshotDiff) + if (snapshotDiff) { return snapshotDiff; + } snapshotDiff = {}; const aggregates = this.aggregates(true, 'allObjects'); for (const className in baseSnapshotAggregates) { const baseAggregate = baseSnapshotAggregates[className]; const diff = this._calculateDiffForClass(baseAggregate, aggregates[className]); - if (diff) + if (diff) { snapshotDiff[className] = diff; + } } const emptyBaseAggregate = new HeapSnapshotModel.AggregateForDiff(); for (const className in aggregates) { - if (className in baseSnapshotAggregates) + if (className in baseSnapshotAggregates) { continue; + } snapshotDiff[className] = this._calculateDiffForClass(emptyBaseAggregate, aggregates[className]); } @@ -1996,15 +2052,17 @@ } diff.countDelta = diff.addedCount - diff.removedCount; diff.sizeDelta = diff.addedSize - diff.removedSize; - if (!diff.addedCount && !diff.removedCount) + if (!diff.addedCount && !diff.removedCount) { return null; + } return diff; } _nodeForSnapshotObjectId(snapshotObjectId) { for (let it = this._allNodes(); it.hasNext(); it.next()) { - if (it.node.id() === snapshotObjectId) + if (it.node.id() === snapshotObjectId) { return it.node; + } } return null; } @@ -2015,8 +2073,9 @@ */ nodeClassName(snapshotObjectId) { const node = this._nodeForSnapshotObjectId(snapshotObjectId); - if (node) + if (node) { return node.className(); + } return null; } @@ -2027,8 +2086,9 @@ idsOfObjectsWithName(name) { const ids = []; for (let it = this._allNodes(); it.hasNext(); it.next()) { - if (it.item().name() === name) + if (it.item().name() === name) { ids.push(it.item().id()); + } } return ids; } @@ -2120,10 +2180,12 @@ for (let nodeIndex = this._nodeIdOffset; nodeIndex < nodesLength; nodeIndex += nodeFieldCount) { const nextId = nodes[nodeIndex]; // JS objects have odd ids, skip native objects. - if (nextId % 2 === 0) + if (nextId % 2 === 0) { continue; - if (id < nextId) + } + if (id < nextId) { id = nextId; + } } return id; } @@ -2199,11 +2261,13 @@ } _createIterationOrder() { - if (this._iterationOrder) + if (this._iterationOrder) { return; + } this._iterationOrder = []; - for (let iterator = this._iterator; iterator.hasNext(); iterator.next()) + for (let iterator = this._iterator; iterator.hasNext(); iterator.next()) { this._iterationOrder.push(iterator.item().itemIndex()); + } } /** @@ -2220,18 +2284,22 @@ */ serializeItemsRange(begin, end) { this._createIterationOrder(); - if (begin > end) + if (begin > end) { throw new Error('Start position > end position: ' + begin + ' > ' + end); - if (end > this._iterationOrder.length) + } + if (end > this._iterationOrder.length) { end = this._iterationOrder.length; + } if (this._sortedPrefixLength < end && begin < this._iterationOrder.length - this._sortedSuffixLength) { this.sort( this._currentComparator, this._sortedPrefixLength, this._iterationOrder.length - 1 - this._sortedSuffixLength, begin, end - 1); - if (begin <= this._sortedPrefixLength) + if (begin <= this._sortedPrefixLength) { this._sortedPrefixLength = end; - if (end >= this._iterationOrder.length - this._sortedSuffixLength) + } + if (end >= this._iterationOrder.length - this._sortedSuffixLength) { this._sortedSuffixLength = this._iterationOrder.length - begin; + } } let position = begin; const count = end - begin; @@ -2291,10 +2359,12 @@ function compareEdgeFieldName(ascending, indexA, indexB) { edgeA.edgeIndex = indexA; edgeB.edgeIndex = indexB; - if (edgeB.name() === '__proto__') + if (edgeB.name() === '__proto__') { return -1; - if (edgeA.name() === '__proto__') + } + if (edgeA.name() === '__proto__') { return 1; + } const result = edgeA.hasStringName() === edgeB.hasStringName() ? (edgeA.name() < edgeB.name() ? -1 : (edgeA.name() > edgeB.name() ? 1 : 0)) : (edgeA.hasStringName() ? -1 : 1); @@ -2316,37 +2386,44 @@ function compareEdgeAndNode(indexA, indexB) { let result = compareEdgeFieldName(ascending1, indexA, indexB); - if (result === 0) + if (result === 0) { result = compareNodeField(fieldName2, ascending2, indexA, indexB); - if (result === 0) + } + if (result === 0) { return indexA - indexB; + } return result; } function compareNodeAndEdge(indexA, indexB) { let result = compareNodeField(fieldName1, ascending1, indexA, indexB); - if (result === 0) + if (result === 0) { result = compareEdgeFieldName(ascending2, indexA, indexB); - if (result === 0) + } + if (result === 0) { return indexA - indexB; + } return result; } function compareNodeAndNode(indexA, indexB) { let result = compareNodeField(fieldName1, ascending1, indexA, indexB); - if (result === 0) + if (result === 0) { result = compareNodeField(fieldName2, ascending2, indexA, indexB); - if (result === 0) + } + if (result === 0) { return indexA - indexB; + } return result; } - if (fieldName1 === '!edgeName') + if (fieldName1 === '!edgeName') { this._iterationOrder.sortRange(compareEdgeAndNode, leftBound, rightBound, windowLeft, windowRight); - else if (fieldName2 === '!edgeName') + } else if (fieldName2 === '!edgeName') { this._iterationOrder.sortRange(compareNodeAndEdge, leftBound, rightBound, windowLeft, windowRight); - else + } else { this._iterationOrder.sortRange(compareNodeAndNode, leftBound, rightBound, windowLeft, windowRight); + } } }; @@ -2375,17 +2452,20 @@ let i = 0; for (; i < this._iterationOrder.length; i++) { node.nodeIndex = this._iterationOrder[i]; - if (node.id() === snapshotObjectId) + if (node.id() === snapshotObjectId) { break; + } } - if (i === this._iterationOrder.length) + if (i === this._iterationOrder.length) { return -1; + } const targetNodeIndex = this._iterationOrder[i]; let smallerCount = 0; const compare = this._buildCompareFunction(this._currentComparator); for (let i = 0; i < this._iterationOrder.length; i++) { - if (compare(this._iterationOrder[i], targetNodeIndex) < 0) + if (compare(this._iterationOrder[i], targetNodeIndex) < 0) { ++smallerCount; + } } return smallerCount; } @@ -2421,8 +2501,9 @@ nodeA.nodeIndex = indexA; nodeB.nodeIndex = indexB; let result = sortByNodeField(fieldAccessor1, ascending1); - if (result === 0) + if (result === 0) { result = sortByNodeField(fieldAccessor2, ascending2); + } return result || indexA - indexB; } @@ -2529,8 +2610,9 @@ * @return {boolean} */ function filter(node, edge) { - if (node.isHidden()) + if (node.isHidden()) { return edge.name() !== 'sloppy_function_map' || node.rawName() !== 'system / NativeContext'; + } if (node.isArray()) { // DescriptorArrays are fixed arrays used to hold instance descriptors. // The format of the these objects is: @@ -2545,8 +2627,9 @@ // links may not be valid for all the maps. We just skip // all the descriptor links when calculating distances. // For more details see http://crbug.com/413608 - if (node.rawName() !== '(map descriptors)') + if (node.rawName() !== '(map descriptors)') { return true; + } const index = edge.name(); return index < 2 || (index % 3) !== 1; } @@ -2591,11 +2674,13 @@ const node = this.rootNode(); for (let nodeIndex = 0, ordinal = 0; nodeIndex < nodesLength; nodeIndex += nodeFieldCount, ordinal++) { const nodeType = nodes[nodeIndex + nodeTypeOffset]; - if (nodeType !== nodeNativeType) + if (nodeType !== nodeNativeType) { continue; + } node.nodeIndex = nodeIndex; - if (node.name().startsWith('Detached ')) + if (node.name().startsWith('Detached ')) { this._flags[ordinal] |= flag; + } } } @@ -2619,25 +2704,30 @@ const list = []; for (let iter = this.rootNode().edges(); iter.hasNext(); iter.next()) { - if (iter.edge.node().isUserRoot()) + if (iter.edge.node().isUserRoot()) { list.push(iter.edge.node().nodeIndex / nodeFieldCount); + } } while (list.length) { const nodeOrdinal = list.pop(); - if (flags[nodeOrdinal] & flag) + if (flags[nodeOrdinal] & flag) { continue; + } flags[nodeOrdinal] |= flag; const beginEdgeIndex = firstEdgeIndexes[nodeOrdinal]; const endEdgeIndex = firstEdgeIndexes[nodeOrdinal + 1]; for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; const childNodeOrdinal = childNodeIndex / nodeFieldCount; - if (flags[childNodeOrdinal] & flag) + if (flags[childNodeOrdinal] & flag) { continue; + } const type = containmentEdges[edgeIndex + edgeTypeOffset]; - if (type === hiddenEdgeType || type === invisibleEdgeType || type === internalEdgeType || type === weakEdgeType) + if (type === hiddenEdgeType || type === invisibleEdgeType || type === internalEdgeType || + type === weakEdgeType) { continue; + } list.push(childNodeOrdinal); } } @@ -2671,8 +2761,9 @@ const nodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; if (edgeType === edgeElementType) { node.nodeIndex = nodeIndex; - if (!node.isDocumentDOMTreesRoot()) + if (!node.isDocumentDOMTreesRoot()) { continue; + } } else if (edgeType !== edgeShortcutType) { continue; } @@ -2689,11 +2780,13 @@ for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const childNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; const childNodeOrdinal = childNodeIndex / nodeFieldCount; - if (flags[childNodeOrdinal] & pageObjectFlag) + if (flags[childNodeOrdinal] & pageObjectFlag) { continue; + } const type = containmentEdges[edgeIndex + edgeTypeOffset]; - if (type === edgeWeakType) + if (type === edgeWeakType) { continue; + } nodesToVisit[nodesToVisitLength++] = childNodeOrdinal; flags[childNodeOrdinal] |= pageObjectFlag; } @@ -2729,14 +2822,15 @@ } const nodeType = nodes[nodeIndex + nodeTypeOffset]; node.nodeIndex = nodeIndex; - if (nodeType === nodeNativeType) + if (nodeType === nodeNativeType) { sizeNative += nodeSize; - else if (nodeType === nodeCodeType) + } else if (nodeType === nodeCodeType) { sizeCode += nodeSize; - else if (nodeType === nodeConsStringType || nodeType === nodeSlicedStringType || node.type() === 'string') + } else if (nodeType === nodeConsStringType || nodeType === nodeSlicedStringType || node.type() === 'string') { sizeStrings += nodeSize; - else if (node.name() === 'Array') + } else if (node.name() === 'Array') { sizeJSArrays += this._calculateArraySize(node); + } } this._statistics = new HeapSnapshotModel.Statistics(); this._statistics.total = this.totalSize; @@ -2765,15 +2859,18 @@ const edgeInternalType = this._edgeInternalType; for (let edgeIndex = beginEdgeIndex; edgeIndex < endEdgeIndex; edgeIndex += edgeFieldsCount) { const edgeType = containmentEdges[edgeIndex + edgeTypeOffset]; - if (edgeType !== edgeInternalType) + if (edgeType !== edgeInternalType) { continue; + } const edgeName = strings[containmentEdges[edgeIndex + edgeNameOffset]]; - if (edgeName !== 'elements') + if (edgeName !== 'elements') { continue; + } const elementsNodeIndex = containmentEdges[edgeIndex + edgeToNodeOffset]; node.nodeIndex = elementsNodeIndex; - if (node.retainersCount() === 1) + if (node.retainersCount() === 1) { size += node.selfSize(); + } break; } return size; @@ -2869,10 +2966,11 @@ const edgeType = edges[edgeIndex + edgeTypeOffset]; if (edgeType === edgeInternalType) { const edgeName = strings[edges[edgeIndex + edgeNameOffset]]; - if (edgeName === 'first') + if (edgeName === 'first') { firstNodeIndex = edges[edgeIndex + edgeToNodeOffset]; - else if (edgeName === 'second') + } else if (edgeName === 'second') { secondNodeIndex = edges[edgeIndex + edgeToNodeOffset]; + } } } nodesStack.push(secondNodeIndex); @@ -2908,8 +3006,9 @@ const snapshot = this._snapshot; const nodes = snapshot.nodes; const type = nodes[this.nodeIndex + snapshot._nodeTypeOffset]; - if (type === snapshot._nodeObjectType || type === snapshot._nodeNativeType) + if (type === snapshot._nodeObjectType || type === snapshot._nodeNativeType) { return nodes[this.nodeIndex + snapshot._nodeNameOffset]; + } return -1 - type; } @@ -2964,10 +3063,12 @@ serialize() { const result = super.serialize(); const flags = this._snapshot._flagsOfNode(this); - if (flags & this._snapshot._nodeFlags.canBeQueried) + if (flags & this._snapshot._nodeFlags.canBeQueried) { result.canBeQueried = true; - if (flags & this._snapshot._nodeFlags.detachedDOMTreeNode) + } + if (flags & this._snapshot._nodeFlags.detachedDOMTreeNode) { result.detachedDOMTreeNode = true; + } return result; } }; @@ -2998,8 +3099,9 @@ * @return {boolean} */ hasStringName() { - if (!this.isShortcut()) + if (!this.isShortcut()) { return this._hasStringName(); + } return isNaN(parseInt(this._name(), 10)); } @@ -3051,8 +3153,9 @@ */ name() { const name = this._name(); - if (!this.isShortcut()) + if (!this.isShortcut()) { return String(name); + } const numName = parseInt(name, 10); return String(isNaN(numName) ? name : numName); } @@ -3073,10 +3176,11 @@ case 'property': return name.indexOf(' ') === -1 ? '.' + name : '["' + name + '"]'; case 'shortcut': - if (typeof name === 'string') + if (typeof name === 'string') { return name.indexOf(' ') === -1 ? '.' + name : '["' + name + '"]'; - else + } else { return '[' + name + ']'; + } case 'internal': case 'hidden': case 'invisible': @@ -3177,6 +3281,7 @@ (function disableLoggingForTest() { // Runtime doesn't exist because this file is loaded as a one-off // file in some inspector-protocol tests. - if (self.Runtime && Runtime.queryParam('test')) + if (self.Runtime && Runtime.queryParam('test')) { console.warn = () => undefined; + } })();
diff --git a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js index 84bc429..249710ad 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js +++ b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotLoader.js
@@ -55,8 +55,9 @@ close() { this._done = true; - if (this._dataCallback) + if (this._dataCallback) { this._dataCallback(''); + } } /** @@ -94,8 +95,9 @@ const startIndex = index; while (index < length) { const code = this._json.charCodeAt(index); - if (char0 > code || code > char9) + if (char0 > code || code > char9) { break; + } nextNumber *= 10; nextNumber += (code - char0); ++index; @@ -111,8 +113,9 @@ _parseStringsArray() { this._progress.updateStatus(ls`Parsing strings\u2026`); const closingBracketIndex = this._json.lastIndexOf(']'); - if (closingBracketIndex === -1) + if (closingBracketIndex === -1) { throw new Error('Incomplete JSON'); + } this._json = this._json.slice(0, closingBracketIndex + 1); this._snapshot.strings = JSON.parse(this._json); } @@ -122,8 +125,9 @@ */ write(chunk) { this._buffer += chunk; - if (!this._dataCallback) + if (!this._dataCallback) { return; + } this._dataCallback(this._buffer); this._dataCallback = null; this._buffer = ''; @@ -144,8 +148,9 @@ async _findToken(token, startIndex) { while (true) { const pos = this._json.indexOf(token, startIndex || 0); - if (pos !== -1) + if (pos !== -1) { return pos; + } startIndex = this._json.length - token.length + 1; this._json += await this._fetchChunk(); } @@ -175,8 +180,9 @@ async _parseInput() { const snapshotToken = '"snapshot"'; const snapshotTokenIndex = await this._findToken(snapshotToken); - if (snapshotTokenIndex === -1) + if (snapshotTokenIndex === -1) { throw new Error('Snapshot token not found'); + } this._progress.updateStatus(ls`Loading snapshot info\u2026`); const json = this._json.slice(snapshotTokenIndex + snapshotToken.length + 1); @@ -186,8 +192,9 @@ this._snapshot.snapshot = /** @type {!HeapSnapshotWorker.HeapSnapshotHeader} */ (JSON.parse(metaJSON)); }); this._jsonTokenizer.write(json); - while (this._jsonTokenizer) + while (this._jsonTokenizer) { this._jsonTokenizer.write(await this._fetchChunk()); + } this._snapshot.nodes = await this._parseArray( '"nodes"', ls`Loading nodes\u2026 %d%%`, @@ -211,20 +218,23 @@ this._json = this._json.slice(closeBracketIndex + 1); } - if (this._snapshot.snapshot.meta.sample_fields) + if (this._snapshot.snapshot.meta.sample_fields) { this._snapshot.samples = await this._parseArray('"samples"', ls`Loading samples\u2026`); + } - if (this._snapshot.snapshot.meta['location_fields']) + if (this._snapshot.snapshot.meta['location_fields']) { this._snapshot.locations = await this._parseArray('"locations"', ls`Loading locations\u2026`); - else + } else { this._snapshot.locations = []; + } this._progress.updateStatus(ls`Loading strings\u2026`); const stringsTokenIndex = await this._findToken('"strings"'); const bracketIndex = await this._findToken('[', stringsTokenIndex); this._json = this._json.slice(bracketIndex); - while (!this._done) + while (!this._done) { this._json += await this._fetchChunk(); + } this._parseStringsArray(); } };
diff --git a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.js b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.js index 2eb6186..f2d3379 100644 --- a/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.js +++ b/third_party/blink/renderer/devtools/front_end/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.js
@@ -41,8 +41,9 @@ _findFunction(name) { const path = name.split('.'); let result = this._global; - for (let i = 0; i < path.length; ++i) + for (let i = 0; i < path.length; ++i) { result = result[path[i]]; + } return result; } @@ -75,8 +76,9 @@ case 'factory': { const object = this._objects[data.objectId]; const result = object[data.methodName].apply(object, data.methodArguments); - if (result) + if (result) { this._objects[data.newObjectId] = result; + } response.result = !!result; break; } @@ -96,8 +98,9 @@ } catch (e) { response.error = e.toString(); response.errorCallStack = e.stack; - if (data.methodName) + if (data.methodName) { response.errorMethodName = data.methodName; + } } this._postMessage(response); }
diff --git a/third_party/blink/renderer/devtools/front_end/help/Help.js b/third_party/blink/renderer/devtools/front_end/help/Help.js index 0153f10..5c31963b 100644 --- a/third_party/blink/renderer/devtools/front_end/help/Help.js +++ b/third_party/blink/renderer/devtools/front_end/help/Help.js
@@ -29,10 +29,12 @@ Help._releaseNoteVersionSetting.set(latestVersion); return; } - if (!showReleaseNote) + if (!showReleaseNote) { return; - if (lastSeenVersion >= latestVersion) + } + if (lastSeenVersion >= latestVersion) { return; + } Help._releaseNoteVersionSetting.set(latestVersion); UI.viewManager.showView(Help.releaseNoteViewId, true); }; @@ -60,8 +62,9 @@ * @override */ async run() { - if (!Host.isUnderTest()) + if (!Host.isUnderTest()) { Help._showReleaseNoteIfNeeded(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/host/InspectorFrontendHost.js b/third_party/blink/renderer/devtools/front_end/host/InspectorFrontendHost.js index 6249a30..0fff65c 100644 --- a/third_party/blink/renderer/devtools/front_end/host/InspectorFrontendHost.js +++ b/third_party/blink/renderer/devtools/front_end/host/InspectorFrontendHost.js
@@ -42,8 +42,9 @@ function stopEventPropagation(event) { // Let browser handle Ctrl+/Ctrl- shortcuts in hosted mode. const zoomModifier = Host.isMac() ? event.metaKey : event.ctrlKey; - if (zoomModifier && (event.keyCode === 187 || event.keyCode === 189)) + if (zoomModifier && (event.keyCode === 187 || event.keyCode === 189)) { event.stopPropagation(); + } } document.addEventListener('keydown', stopEventPropagation, true); /** @@ -63,11 +64,13 @@ */ platform() { let match = navigator.userAgent.match(/Windows NT/); - if (match) + if (match) { return 'windows'; + } match = navigator.userAgent.match(/Mac OS X/); - if (match) + if (match) { return 'mac'; + } return 'linux'; } @@ -137,8 +140,9 @@ * @suppressGlobalPropertiesCheck */ copyText(text) { - if (text === undefined || text === null) + if (text === undefined || text === null) { return; + } if (navigator.clipboard) { navigator.clipboard.writeText(text); } else if (document.queryCommandSupported('copy')) { @@ -297,8 +301,9 @@ */ getPreferences(callback) { const prefs = {}; - for (const name in window.localStorage) + for (const name in window.localStorage) { prefs[name] = window.localStorage[name]; + } callback(prefs); } @@ -504,8 +509,9 @@ !!Runtime.queryParam('debugFrontend') || (window['InspectorTest'] && window['InspectorTest']['debugTest']); const descriptors = Host.InspectorFrontendAPIImpl.EventDescriptors; - for (let i = 0; i < descriptors.length; ++i) + for (let i = 0; i < descriptors.length; ++i) { this[descriptors[i][1]] = this._dispatch.bind(this, descriptors[i][0], descriptors[i][2], descriptors[i][3]); + } } /** @@ -516,10 +522,11 @@ _dispatch(name, signature, runOnceLoaded) { const params = Array.prototype.slice.call(arguments, 3); - if (this._debugFrontend) + if (this._debugFrontend) { setImmediate(innerDispatch); - else + } else { innerDispatch(); + } function innerDispatch() { // Single argument methods get dispatched with the param. @@ -532,8 +539,9 @@ return; } const data = {}; - for (let i = 0; i < signature.length; ++i) + for (let i = 0; i < signature.length; ++i) { data[signature[i]] = params[i]; + } try { InspectorFrontendHost.events.dispatchEventToListeners(name, data); } catch (e) { @@ -606,8 +614,9 @@ proto = Host.InspectorFrontendHostStub.prototype; for (const name of Object.getOwnPropertyNames(proto)) { const stub = proto[name]; - if (typeof stub !== 'function' || InspectorFrontendHost[name]) + if (typeof stub !== 'function' || InspectorFrontendHost[name]) { continue; + } console.error( 'Incompatible embedder: method InspectorFrontendHost.' + name + ' is missing. Using stub instead.'); @@ -631,10 +640,12 @@ */ Host.isUnderTest = function(prefs) { // Integration tests rely on test queryParam. - if (Runtime.queryParam('test')) + if (Runtime.queryParam('test')) { return true; + } // Browser tests rely on prefs. - if (prefs) + if (prefs) { return prefs['isUnderTest'] === 'true'; + } return Common.settings && Common.settings.createSetting('isUnderTest', false).get(); };
diff --git a/third_party/blink/renderer/devtools/front_end/host/Platform.js b/third_party/blink/renderer/devtools/front_end/host/Platform.js index c6fa64f..463cc66c 100644 --- a/third_party/blink/renderer/devtools/front_end/host/Platform.js +++ b/third_party/blink/renderer/devtools/front_end/host/Platform.js
@@ -29,8 +29,9 @@ * @return {string} */ Host.platform = function() { - if (!Host._platform) + if (!Host._platform) { Host._platform = InspectorFrontendHost.platform(); + } return Host._platform; }; @@ -38,8 +39,9 @@ * @return {boolean} */ Host.isMac = function() { - if (typeof Host._isMac === 'undefined') + if (typeof Host._isMac === 'undefined') { Host._isMac = Host.platform() === 'mac'; + } return Host._isMac; }; @@ -48,8 +50,9 @@ * @return {boolean} */ Host.isWin = function() { - if (typeof Host._isWin === 'undefined') + if (typeof Host._isWin === 'undefined') { Host._isWin = Host.platform() === 'windows'; + } return Host._isWin; }; @@ -58,8 +61,9 @@ * @return {boolean} */ Host.isCustomDevtoolsFrontend = function() { - if (typeof Host._isCustomDevtoolsFronend === 'undefined') + if (typeof Host._isCustomDevtoolsFronend === 'undefined') { Host._isCustomDevtoolsFronend = window.location.toString().startsWith('devtools://devtools/custom/'); + } return Host._isCustomDevtoolsFronend; }; @@ -67,8 +71,9 @@ * @return {string} */ Host.fontFamily = function() { - if (Host._fontFamily) + if (Host._fontFamily) { return Host._fontFamily; + } switch (Host.platform()) { case 'linux': Host._fontFamily = 'Roboto, Ubuntu, Arial, sans-serif';
diff --git a/third_party/blink/renderer/devtools/front_end/host/ResourceLoader.js b/third_party/blink/renderer/devtools/front_end/host/ResourceLoader.js index c382ec0..512ec2b 100644 --- a/third_party/blink/renderer/devtools/front_end/host/ResourceLoader.js +++ b/third_party/blink/renderer/devtools/front_end/host/ResourceLoader.js
@@ -66,8 +66,9 @@ const rawHeaders = []; if (headers) { - for (const key in headers) + for (const key in headers) { rawHeaders.push(key + ': ' + headers[key]); + } } InspectorFrontendHost.loadNetworkResource(url, rawHeaders.join('\r\n'), streamId, finishedCallback); @@ -75,8 +76,9 @@ * @param {!InspectorFrontendHostAPI.LoadNetworkResourceResult} response */ function finishedCallback(response) { - if (callback) + if (callback) { callback(response.statusCode, response.headers || {}); + } Host.ResourceLoader._discardOutputStream(streamId); }
diff --git a/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js b/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js index e788ff7e..55a5d8d 100644 --- a/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js +++ b/third_party/blink/renderer/devtools/front_end/host/UserMetrics.js
@@ -64,8 +64,9 @@ * @suppressGlobalPropertiesCheck */ panelLoaded(panelName, histogramName) { - if (this._firedLaunchHistogram || panelName !== this._launchPanelName) + if (this._firedLaunchHistogram || panelName !== this._launchPanelName) { return; + } this._firedLaunchHistogram = true; // Use rAF and setTimeout to ensure the marker is fired after layout and rendering. @@ -76,8 +77,9 @@ performance.mark(histogramName); // If the user has switched panel before we finished loading, ignore the histogram, // since the launch timings will have been affected and are no longer valid. - if (this._panelChangedSinceLaunch) + if (this._panelChangedSinceLaunch) { return; + } // This fires the event for the appropriate launch histogram. // The duration is measured as the time elapsed since the time origin of the document. InspectorFrontendHost.recordPerformanceHistogram(histogramName, performance.now());
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/BezierEditor.js b/third_party/blink/renderer/devtools/front_end/inline_editor/BezierEditor.js index 05f0663..671bd11 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/BezierEditor.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/BezierEditor.js
@@ -47,8 +47,9 @@ * @param {?UI.Geometry.CubicBezier} bezier */ setBezier(bezier) { - if (!bezier) + if (!bezier) { return; + } this._bezier = bezier; this._updateUI(); } @@ -173,8 +174,9 @@ } _unselectPresets() { - for (const category of this._presetCategories) + for (const category of this._presetCategories) { category.icon.classList.remove('bezier-preset-selected'); + } delete this._selectedCategory; this._header.classList.remove('bezier-header-active'); } @@ -184,8 +186,9 @@ * @param {!Event=} event */ _presetCategorySelected(category, event) { - if (this._selectedCategory === category) + if (this._selectedCategory === category) { return; + } this._unselectPresets(); this._header.classList.add('bezier-header-active'); this._selectedCategory = category; @@ -193,8 +196,9 @@ this.setBezier(UI.Geometry.CubicBezier.parse(category.presets[category.presetIndex].value)); this._onchange(); this._startPreviewAnimation(); - if (event) + if (event) { event.consume(true); + } } /** @@ -202,8 +206,9 @@ * @param {!Event} event */ _presetModifyClicked(intensify, event) { - if (!this._selectedCategory) + if (!this._selectedCategory) { return; + } const length = this._selectedCategory.presets.length; this._selectedCategory.presetIndex = (this._selectedCategory.presetIndex + (intensify ? 1 : -1) + length) % length; @@ -214,8 +219,9 @@ } _startPreviewAnimation() { - if (this._previewAnimation) + if (this._previewAnimation) { this._previewAnimation.cancel(); + } const animationDuration = 1600; const numberOnionSlices = 20;
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/BezierUI.js b/third_party/blink/renderer/devtools/front_end/inline_editor/BezierUI.js index f5c88ca6..28e2a08 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/BezierUI.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/BezierUI.js
@@ -93,8 +93,9 @@ * @param {!Element} svg */ drawCurve(bezier, svg) { - if (!bezier) + if (!bezier) { return; + } const width = this.curveWidth(); const height = this.curveHeight(); svg.setAttribute('width', this.width); @@ -102,8 +103,9 @@ svg.removeChildren(); const group = svg.createSVGChild('g'); - if (this.linearLine) + if (this.linearLine) { this._drawLine(group, 'linear-line', 0, height, width, 0); + } const curve = group.createSVGChild('path', 'bezier-path'); const curvePoints = [
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowEditor.js b/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowEditor.js index 07ef71f..9f2bf8b 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowEditor.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowEditor.js
@@ -155,8 +155,9 @@ */ _onButtonClick(event) { const insetClicked = (event.currentTarget === this._insetButton); - if (insetClicked && this._model.inset() || !insetClicked && !this._model.inset()) + if (insetClicked && this._model.inset() || !insetClicked && !this._model.inset()) { return; + } this._model.setInset(insetClicked); this._updateButtons(); this.dispatchEventToListeners(InlineEditor.CSSShadowEditor.Events.ShadowChanged, this._model); @@ -167,13 +168,16 @@ */ _handleValueModification(event) { const modifiedValue = UI.createReplacementString(event.currentTarget.value, event, customNumberHandler); - if (!modifiedValue) + if (!modifiedValue) { return; + } const length = InlineEditor.CSSLength.parse(modifiedValue); - if (!length) + if (!length) { return; - if (event.currentTarget === this._blurInput && length.amount < 0) + } + if (event.currentTarget === this._blurInput && length.amount < 0) { length.amount = 0; + } event.currentTarget.value = length.asCSSText(); event.currentTarget.selectionStart = 0; event.currentTarget.selectionEnd = event.currentTarget.value.length; @@ -187,8 +191,9 @@ * @return {string} */ function customNumberHandler(prefix, number, suffix) { - if (!suffix.length) + if (!suffix.length) { suffix = InlineEditor.CSSShadowEditor.defaultUnit; + } return prefix + number + suffix; } } @@ -200,8 +205,9 @@ this._changedElement = event.currentTarget; this._changedElement.classList.remove('invalid'); const length = InlineEditor.CSSLength.parse(event.currentTarget.value); - if (!length || event.currentTarget === this._blurInput && length.amount < 0) + if (!length || event.currentTarget === this._blurInput && length.amount < 0) { return; + } if (event.currentTarget === this._xInput) { this._model.setOffsetX(length); this._updateCanvas(false); @@ -219,12 +225,14 @@ } _onTextBlur() { - if (!this._changedElement) + if (!this._changedElement) { return; + } let length = !this._changedElement.value.trim() ? InlineEditor.CSSLength.zero() : InlineEditor.CSSLength.parse(this._changedElement.value); - if (!length) + if (!length) { length = InlineEditor.CSSLength.parse(this._changedElement.value + InlineEditor.CSSShadowEditor.defaultUnit); + } if (!length) { this._changedElement.classList.add('invalid'); this._changedElement = null; @@ -239,8 +247,9 @@ this._yInput.value = length.asCSSText(); this._updateCanvas(false); } else if (this._changedElement === this._blurInput) { - if (length.amount < 0) + if (length.amount < 0) { length = InlineEditor.CSSLength.zero(); + } this._model.setBlurRadius(length); this._blurInput.value = length.asCSSText(); this._blurSlider.value = length.amount; @@ -283,8 +292,9 @@ this._xySlider.totalOffsetTop() + this._halfCanvasSize); const clickedPoint = new UI.Geometry.Point(event.x - this._canvasOrigin.x, event.y - this._canvasOrigin.y); const thumbPoint = this._sliderThumbPosition(); - if (clickedPoint.distanceTo(thumbPoint) >= InlineEditor.CSSShadowEditor.sliderThumbRadius) + if (clickedPoint.distanceTo(thumbPoint) >= InlineEditor.CSSShadowEditor.sliderThumbRadius) { this._dragMove(event); + } return true; } @@ -293,8 +303,9 @@ */ _dragMove(event) { let point = new UI.Geometry.Point(event.x - this._canvasOrigin.x, event.y - this._canvasOrigin.y); - if (event.shiftKey) + if (event.shiftKey) { point = this._snapToClosestDirection(point); + } const constrainedPoint = this._constrainPoint(point, this._innerCanvasSize); const newX = Math.round((constrainedPoint.x / this._innerCanvasSize) * InlineEditor.CSSShadowEditor.maxRange); const newY = Math.round((constrainedPoint.y / this._innerCanvasSize) * InlineEditor.CSSShadowEditor.maxRange); @@ -332,25 +343,28 @@ _onCanvasArrowKey(event) { let shiftX = 0; let shiftY = 0; - if (event.key === 'ArrowRight') + if (event.key === 'ArrowRight') { shiftX = 1; - else if (event.key === 'ArrowLeft') + } else if (event.key === 'ArrowLeft') { shiftX = -1; - else if (event.key === 'ArrowUp') + } else if (event.key === 'ArrowUp') { shiftY = -1; - else if (event.key === 'ArrowDown') + } else if (event.key === 'ArrowDown') { shiftY = 1; + } - if (!shiftX && !shiftY) + if (!shiftX && !shiftY) { return; + } event.consume(true); if (shiftX) { const offsetX = this._model.offsetX(); const newAmount = Number.constrain( offsetX.amount + shiftX, -InlineEditor.CSSShadowEditor.maxRange, InlineEditor.CSSShadowEditor.maxRange); - if (newAmount === offsetX.amount) + if (newAmount === offsetX.amount) { return; + } this._model.setOffsetX( new InlineEditor.CSSLength(newAmount, offsetX.unit || InlineEditor.CSSShadowEditor.defaultUnit)); this._xInput.value = this._model.offsetX().asCSSText(); @@ -360,8 +374,9 @@ const offsetY = this._model.offsetY(); const newAmount = Number.constrain( offsetY.amount + shiftY, -InlineEditor.CSSShadowEditor.maxRange, InlineEditor.CSSShadowEditor.maxRange); - if (newAmount === offsetY.amount) + if (newAmount === offsetY.amount) { return; + } this._model.setOffsetY( new InlineEditor.CSSLength(newAmount, offsetY.unit || InlineEditor.CSSShadowEditor.defaultUnit)); this._yInput.value = this._model.offsetY().asCSSText(); @@ -377,8 +392,9 @@ * @return {!UI.Geometry.Point} */ _constrainPoint(point, max) { - if (Math.abs(point.x) <= max && Math.abs(point.y) <= max) + if (Math.abs(point.x) <= max && Math.abs(point.y) <= max) { return new UI.Geometry.Point(point.x, point.y); + } return point.scale(max / Math.max(Math.abs(point.x), Math.abs(point.y))); }
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowModel.js b/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowModel.js index bebe2d1..1b504aa 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowModel.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/CSSShadowModel.js
@@ -65,13 +65,15 @@ const result = results[j]; if (result.regexIndex === -1) { // Don't allow anything other than inset, color, length values, and whitespace. - if (/\S/.test(result.value)) + if (/\S/.test(result.value)) { return []; + } // All parts must be separated by whitespace. nextPartAllowed = true; } else { - if (!nextPartAllowed) + if (!nextPartAllowed) { return []; + } nextPartAllowed = false; if (result.regexIndex === 0) { @@ -79,14 +81,16 @@ shadow._format.push(InlineEditor.CSSShadowModel._Part.Inset); } else if (result.regexIndex === 1) { const color = Common.Color.parse(result.value); - if (!color) + if (!color) { return []; + } shadow._color = color; shadow._format.push(InlineEditor.CSSShadowModel._Part.Color); } else if (result.regexIndex === 2) { const length = InlineEditor.CSSLength.parse(result.value); - if (!length) + if (!length) { return []; + } const previousPart = shadow._format.length > 0 ? shadow._format[shadow._format.length - 1] : ''; if (previousPart === InlineEditor.CSSShadowModel._Part.OffsetX) { shadow._offsetY = length; @@ -109,8 +113,9 @@ invalidCount(shadow, InlineEditor.CSSShadowModel._Part.Color, 0, 1) || invalidCount(shadow, InlineEditor.CSSShadowModel._Part.BlurRadius, 0, 1) || invalidCount(shadow, InlineEditor.CSSShadowModel._Part.Inset, 0, isBoxShadow ? 1 : 0) || - invalidCount(shadow, InlineEditor.CSSShadowModel._Part.SpreadRadius, 0, isBoxShadow ? 1 : 0)) + invalidCount(shadow, InlineEditor.CSSShadowModel._Part.SpreadRadius, 0, isBoxShadow ? 1 : 0)) { return []; + } shadows.push(shadow); } return shadows; @@ -125,8 +130,9 @@ function invalidCount(shadow, part, min, max) { let count = 0; for (let i = 0; i < shadow._format.length; i++) { - if (shadow._format[i] === part) + if (shadow._format[i] === part) { count++; + } } return count < min || count > max; } @@ -137,8 +143,9 @@ */ setInset(inset) { this._inset = inset; - if (this._format.indexOf(InlineEditor.CSSShadowModel._Part.Inset) === -1) + if (this._format.indexOf(InlineEditor.CSSShadowModel._Part.Inset) === -1) { this._format.unshift(InlineEditor.CSSShadowModel._Part.Inset); + } } /** @@ -183,8 +190,9 @@ */ setColor(color) { this._color = color; - if (this._format.indexOf(InlineEditor.CSSShadowModel._Part.Color) === -1) + if (this._format.indexOf(InlineEditor.CSSShadowModel._Part.Color) === -1) { this._format.push(InlineEditor.CSSShadowModel._Part.Color); + } } /** @@ -243,18 +251,19 @@ const parts = []; for (let i = 0; i < this._format.length; i++) { const part = this._format[i]; - if (part === InlineEditor.CSSShadowModel._Part.Inset && this._inset) + if (part === InlineEditor.CSSShadowModel._Part.Inset && this._inset) { parts.push('inset'); - else if (part === InlineEditor.CSSShadowModel._Part.OffsetX) + } else if (part === InlineEditor.CSSShadowModel._Part.OffsetX) { parts.push(this._offsetX.asCSSText()); - else if (part === InlineEditor.CSSShadowModel._Part.OffsetY) + } else if (part === InlineEditor.CSSShadowModel._Part.OffsetY) { parts.push(this._offsetY.asCSSText()); - else if (part === InlineEditor.CSSShadowModel._Part.BlurRadius) + } else if (part === InlineEditor.CSSShadowModel._Part.BlurRadius) { parts.push(this._blurRadius.asCSSText()); - else if (part === InlineEditor.CSSShadowModel._Part.SpreadRadius) + } else if (part === InlineEditor.CSSShadowModel._Part.SpreadRadius) { parts.push(this._spreadRadius.asCSSText()); - else if (part === InlineEditor.CSSShadowModel._Part.Color) + } else if (part === InlineEditor.CSSShadowModel._Part.Color) { parts.push(this._color.asString(this._color.format())); + } } return parts.join(' '); } @@ -293,10 +302,12 @@ static parse(text) { const lengthRegex = new RegExp('^(?:' + InlineEditor.CSSLength.Regex.source + ')$', 'i'); const match = text.match(lengthRegex); - if (!match) + if (!match) { return null; - if (match.length > 2 && match[2]) + } + if (match.length > 2 && match[2]) { return new InlineEditor.CSSLength(parseFloat(match[1]), match[2]); + } return InlineEditor.CSSLength.zero(); }
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/ColorSwatch.js b/third_party/blink/renderer/devtools/front_end/inline_editor/ColorSwatch.js index 2dfc68ab..3abcb32 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/ColorSwatch.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/ColorSwatch.js
@@ -57,8 +57,9 @@ case cf.HSL: case cf.HSLA: - if (color.nickname()) + if (color.nickname()) { return cf.Nickname; + } return color.detectHEXFormat(); case cf.ShortHEX: @@ -148,8 +149,9 @@ * @param {!Event} event */ _handleClick(event) { - if (!event.shiftKey) + if (!event.shiftKey) { return; + } event.target.parentNode.parentNode.host.toggleNextFormat(); event.consume(true); } @@ -253,8 +255,9 @@ for (let i = 0; i < results.length; i++) { const result = results[i]; if (result.regexIndex === 1) { - if (!this._colorSwatch) + if (!this._colorSwatch) { this._colorSwatch = InlineEditor.ColorSwatch.create(); + } this._colorSwatch.setColor(model.color()); this._contentElement.appendChild(this._colorSwatch); } else {
diff --git a/third_party/blink/renderer/devtools/front_end/inline_editor/SwatchPopoverHelper.js b/third_party/blink/renderer/devtools/front_end/inline_editor/SwatchPopoverHelper.js index 6884864..f508e7fc 100644 --- a/third_party/blink/renderer/devtools/front_end/inline_editor/SwatchPopoverHelper.js +++ b/third_party/blink/renderer/devtools/front_end/inline_editor/SwatchPopoverHelper.js
@@ -23,8 +23,9 @@ * @param {!Event} event */ _onFocusOut(event) { - if (!event.relatedTarget || event.relatedTarget.isSelfOrDescendant(this._view.contentElement)) + if (!event.relatedTarget || event.relatedTarget.isSelfOrDescendant(this._view.contentElement)) { return; + } this._hideProxy(); } @@ -42,8 +43,9 @@ */ show(view, anchorElement, hiddenCallback) { if (this._popover.isShowing()) { - if (this._anchorElement === anchorElement) + if (this._anchorElement === anchorElement) { return; + } // Reopen the picker for another anchor element. this.hide(true); @@ -69,16 +71,18 @@ this._popover.setContentAnchorBox(this._anchorElement.boxInWindow()); this._popover.show(this._anchorElement.ownerDocument); this._view.contentElement.addEventListener('focusout', this._boundFocusOut, false); - if (!this._focusRestorer) + if (!this._focusRestorer) { this._focusRestorer = new UI.WidgetFocusRestorer(this._view); + } } /** * @param {boolean=} commitEdit */ hide(commitEdit) { - if (this._isHidden) + if (this._isHidden) { return; + } const document = this._popover.element.ownerDocument; this._isHidden = true; this._popover.hide(); @@ -86,8 +90,9 @@ document.removeEventListener('mousedown', this._hideProxy, false); document.defaultView.removeEventListener('resize', this._hideProxy, false); - if (this._hiddenCallback) + if (this._hiddenCallback) { this._hiddenCallback.call(null, !!commitEdit); + } this._focusRestorer.restore(); delete this._anchorElement;
diff --git a/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js b/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js index 079b4e5..19146a8f 100644 --- a/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js +++ b/third_party/blink/renderer/devtools/front_end/inspector_main/InspectorMain.js
@@ -20,14 +20,16 @@ // Only resume target during the first connection, // subsequent connections are due to connection hand-over, // there is no need to pause in debugger. - if (!firstCall) + if (!firstCall) { return; + } firstCall = false; if (waitForDebuggerInPage) { const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel.isReadyToPause()) + if (!debuggerModel.isReadyToPause()) { await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause); + } debuggerModel.pause(); } @@ -110,8 +112,9 @@ _update(targetInfos) { const hasNode = !!targetInfos.find(target => target.type === 'node' && !target.attached); this._element.classList.toggle('inactive', !hasNode); - if (hasNode) + if (hasNode) { this._button.setVisible(true); + } } /** @@ -166,8 +169,9 @@ * @param {!SDK.Target} target */ _updateTarget(target) { - if (target.type() !== SDK.Target.Type.Frame || target.parentTarget()) + if (target.type() !== SDK.Target.Type.Frame || target.parentTarget()) { return; + } target.pageAgent().setAdBlockingEnabled(this._adBlockEnabledSetting.get()); target.emulationAgent().setFocusEmulationEnabled(this._emulatePageFocusSetting.get()); } @@ -177,8 +181,9 @@ } _update() { - for (const target of SDK.targetManager.targets()) + for (const target of SDK.targetManager.targets()) { this._updateTarget(target); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js b/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js index f8253a4..21b84ae 100644 --- a/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js +++ b/third_party/blink/renderer/devtools/front_end/inspector_main/RenderingOptions.js
@@ -65,8 +65,9 @@ const mediaSetting = Common.moduleSetting('emulatedCSSMedia'); const selectSubtitle = ls`Forces media type for testing print and screen styles`; const mediaSelect = UI.SettingsUI.createControlForSetting(mediaSetting, selectSubtitle); - if (mediaSelect) + if (mediaSelect) { this.contentElement.appendChild(mediaSelect); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/javascript_metadata/JavaScriptMetadata.js b/third_party/blink/renderer/devtools/front_end/javascript_metadata/JavaScriptMetadata.js index 4002240..bcfef88 100644 --- a/third_party/blink/renderer/devtools/front_end/javascript_metadata/JavaScriptMetadata.js +++ b/third_party/blink/renderer/devtools/front_end/javascript_metadata/JavaScriptMetadata.js
@@ -18,12 +18,14 @@ if (!nativeFunction.receiver) { this._uniqueFunctions.set(nativeFunction.name, nativeFunction.signatures); } else if (nativeFunction.static) { - if (!this._staticMethods.has(nativeFunction.receiver)) + if (!this._staticMethods.has(nativeFunction.receiver)) { this._staticMethods.set(nativeFunction.receiver, new Map()); + } this._staticMethods.get(nativeFunction.receiver).set(nativeFunction.name, nativeFunction.signatures); } else { - if (!this._instanceMethods.has(nativeFunction.receiver)) + if (!this._instanceMethods.has(nativeFunction.receiver)) { this._instanceMethods.set(nativeFunction.receiver, new Map()); + } this._instanceMethods.get(nativeFunction.receiver).set(nativeFunction.name, nativeFunction.signatures); } } @@ -45,8 +47,9 @@ * @return {?Array<!Array<string>>} */ signaturesForInstanceMethod(name, receiverClassName) { - if (!this._instanceMethods.has(receiverClassName)) + if (!this._instanceMethods.has(receiverClassName)) { return null; + } return this._instanceMethods.get(receiverClassName).get(name) || null; } @@ -57,8 +60,9 @@ * @return {?Array<!Array<string>>} */ signaturesForStaticMethod(name, receiverConstructorName) { - if (!this._staticMethods.has(receiverConstructorName)) + if (!this._staticMethods.has(receiverConstructorName)) { return null; + } return this._staticMethods.get(receiverConstructorName).get(name) || null; } };
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerDetailsView.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerDetailsView.js index 8daae62..e2cd8b7 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerDetailsView.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerDetailsView.js
@@ -57,8 +57,9 @@ */ selectObject(selection) { this._selection = selection; - if (this.isShowing()) + if (this.isShowing()) { this.update(); + } } /** @@ -81,14 +82,16 @@ * @param {!Event} event */ _onScrollRectClicked(index, event) { - if (event.which !== 1) + if (event.which !== 1) { return; + } this._layerViewHost.selectObject(new LayerViewer.LayerView.ScrollRectSelection(this._selection.layer(), index)); } _onPaintProfilerButtonClicked() { - if (this._selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot || this._selection.layer()) + if (this._selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot || this._selection.layer()) { this.dispatchEventToListeners(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested, this._selection); + } } /** @@ -96,11 +99,13 @@ * @param {number} index */ _createScrollRectElement(scrollRect, index) { - if (index) + if (index) { this._scrollRectsCell.createTextChild(', '); + } const element = this._scrollRectsCell.createChild('span', 'scroll-rect'); - if (this._selection.scrollRectIndex === index) + if (this._selection.scrollRectIndex === index) { element.classList.add('active'); + } element.textContent = Common.UIString( '%s %d × %d (at %d, %d)', LayerViewer.LayerDetailsView._slowScrollRectNames.get(scrollRect.type), scrollRect.rect.x, scrollRect.rect.y, scrollRect.rect.width, scrollRect.rect.height); @@ -113,8 +118,9 @@ * @return {string} */ _formatStickyAncestorLayer(title, layer) { - if (!layer) + if (!layer) { return ''; + } const node = layer.nodeForSelfOrAncestor(); const name = node ? node.simpleSelector() : Common.UIString('<unnamed>'); @@ -126,8 +132,9 @@ * @param {?SDK.Layer} layer */ _createStickyAncestorChild(title, layer) { - if (!layer) + if (!layer) { return; + } this._stickyPositionConstraintCell.createTextChild(', '); const child = this._stickyPositionConstraintCell.createChild('span'); @@ -139,8 +146,9 @@ */ _populateStickyPositionConstraintCell(constraint) { this._stickyPositionConstraintCell.removeChildren(); - if (!constraint) + if (!constraint) { return; + } const stickyBoxRect = constraint.stickyBoxRect(); const stickyBoxRectElement = this._stickyPositionConstraintCell.createChild('span'); @@ -224,8 +232,9 @@ for (let i = 0; i < compositingReasons.length; ++i) { let text = LayerViewer.LayerDetailsView.CompositingReasonDetail[compositingReasons[i]] || compositingReasons[i]; // If the text is more than one word but does not terminate with period, add the period. - if (/\s.*[^.]$/.test(text)) + if (/\s.*[^.]$/.test(text)) { text += '.'; + } list.createChild('li').textContent = text; } }
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerTreeOutline.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerTreeOutline.js index 94c19cc..5d88ddf 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerTreeOutline.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerTreeOutline.js
@@ -63,10 +63,11 @@ this.hoverObject(null); const layer = selection && selection.layer(); const node = layer && layer[LayerViewer.LayerTreeElement._symbol]; - if (node) + if (node) { node.revealAndSelect(true); - else if (this._treeOutline.selectedTreeElement) + } else if (this._treeOutline.selectedTreeElement) { this._treeOutline.selectedTreeElement.deselect(); + } } /** @@ -76,12 +77,15 @@ hoverObject(selection) { const layer = selection && selection.layer(); const node = layer && layer[LayerViewer.LayerTreeElement._symbol]; - if (node === this._lastHoveredNode) + if (node === this._lastHoveredNode) { return; - if (this._lastHoveredNode) + } + if (this._lastHoveredNode) { this._lastHoveredNode.setHovered(false); - if (node) + } + if (node) { node.setHovered(true); + } this._lastHoveredNode = node; } @@ -99,10 +103,12 @@ const seenLayers = new Map(); let root = null; if (this._layerTree) { - if (!showInternalLayers) + if (!showInternalLayers) { root = this._layerTree.contentRoot(); - if (!root) + } + if (!root) { root = this._layerTree.root(); + } } /** @@ -110,16 +116,19 @@ * @this {LayerViewer.LayerTreeOutline} */ function updateLayer(layer) { - if (!layer.drawsContent() && !showInternalLayers) + if (!layer.drawsContent() && !showInternalLayers) { return; - if (seenLayers.get(layer)) + } + if (seenLayers.get(layer)) { console.assert(false, 'Duplicate layer: ' + layer.id()); + } seenLayers.set(layer, true); let node = layer[LayerViewer.LayerTreeElement._symbol]; let parentLayer = layer.parent(); // Skip till nearest visible ancestor. - while (parentLayer && parentLayer !== root && !parentLayer.drawsContent() && !showInternalLayers) + while (parentLayer && parentLayer !== root && !parentLayer.drawsContent() && !showInternalLayers) { parentLayer = parentLayer.parent(); + } const parent = layer === root ? this._treeOutline.rootElement() : parentLayer[LayerViewer.LayerTreeElement._symbol]; if (!parent) { @@ -130,22 +139,26 @@ node = new LayerViewer.LayerTreeElement(this, layer); parent.appendChild(node); // Expand all new non-content layers to expose content layers better. - if (!layer.drawsContent()) + if (!layer.drawsContent()) { node.expand(); + } } else { if (node.parent !== parent) { const oldSelection = this._treeOutline.selectedTreeElement; - if (node.parent) + if (node.parent) { node.parent.removeChild(node); + } parent.appendChild(node); - if (oldSelection !== this._treeOutline.selectedTreeElement) + if (oldSelection !== this._treeOutline.selectedTreeElement) { oldSelection.select(); + } } node._update(); } } - if (root) + if (root) { this._layerTree.forEachLayer(updateLayer.bind(this), root); + } // Cleanup layers that don't exist anymore from tree. const rootElement = this._treeOutline.rootElement(); for (let node = rootElement.firstChild(); node && !node.root;) { @@ -154,15 +167,17 @@ } else { const nextNode = node.nextSibling || node.parent; node.parent.removeChild(node); - if (node === this._lastHoveredNode) + if (node === this._lastHoveredNode) { this._lastHoveredNode = null; + } node = nextNode; } } if (!this._treeOutline.selectedTreeElement) { const elementToSelect = this._layerTree.contentRoot() || this._layerTree.root(); - if (elementToSelect) + if (elementToSelect) { elementToSelect[LayerViewer.LayerTreeElement._symbol].revealAndSelect(true); + } } } @@ -171,8 +186,9 @@ */ _onMouseMove(event) { const node = this._treeOutline.treeElementFromEvent(event); - if (node === this._lastHoveredNode) + if (node === this._lastHoveredNode) { return; + } this._layerViewHost.hoverObject(this._selectionForNode(node)); }
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerViewHost.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerViewHost.js index 6aa3ee7..f92b464 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerViewHost.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/LayerViewHost.js
@@ -182,37 +182,44 @@ setLayerTree(layerTree) { this._target = layerTree.target(); const selectedLayer = this._selectedObject && this._selectedObject.layer(); - if (selectedLayer && (!layerTree || !layerTree.layerById(selectedLayer.id()))) + if (selectedLayer && (!layerTree || !layerTree.layerById(selectedLayer.id()))) { this.selectObject(null); + } const hoveredLayer = this._hoveredObject && this._hoveredObject.layer(); - if (hoveredLayer && (!layerTree || !layerTree.layerById(hoveredLayer.id()))) + if (hoveredLayer && (!layerTree || !layerTree.layerById(hoveredLayer.id()))) { this.hoverObject(null); - for (const view of this._views) + } + for (const view of this._views) { view.setLayerTree(layerTree); + } } /** * @param {?LayerViewer.LayerView.Selection} selection */ hoverObject(selection) { - if (LayerViewer.LayerView.Selection.isEqual(this._hoveredObject, selection)) + if (LayerViewer.LayerView.Selection.isEqual(this._hoveredObject, selection)) { return; + } this._hoveredObject = selection; const layer = selection && selection.layer(); this._toggleNodeHighlight(layer ? layer.nodeForSelfOrAncestor() : null); - for (const view of this._views) + for (const view of this._views) { view.hoverObject(selection); + } } /** * @param {?LayerViewer.LayerView.Selection} selection */ selectObject(selection) { - if (LayerViewer.LayerView.Selection.isEqual(this._selectedObject, selection)) + if (LayerViewer.LayerView.Selection.isEqual(this._selectedObject, selection)) { return; + } this._selectedObject = selection; - for (const view of this._views) + for (const view of this._views) { view.selectObject(selection); + } } /** @@ -231,8 +238,9 @@ Common.UIString('Show internal layers'), this._toggleShowInternalLayers.bind(this), this._showInternalLayersSetting.get()); const node = selection && selection.layer() && selection.layer().nodeForSelfOrAncestor(); - if (node) + if (node) { contextMenu.appendApplicableItems(node); + } contextMenu.show(); }
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/Layers3DView.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/Layers3DView.js index b6747f9f..b68f022 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/Layers3DView.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/Layers3DView.js
@@ -80,8 +80,9 @@ this._layerTree = layerTree; this._layerTexture = null; delete this._oldTextureScale; - if (this._showPaints()) + if (this._showPaints()) { this._textureManager.setLayerTree(layerTree); + } this._update(); } @@ -122,8 +123,9 @@ */ wasShown() { this._textureManager.resume(); - if (!this._needsUpdate) + if (!this._needsUpdate) { return; + } this._resizeCanvas(); this._update(); } @@ -173,8 +175,9 @@ } if (selection.layer()) { const promise = selection.layer().snapshots()[0]; - if (promise) + if (promise) { return promise; + } } return /** @type {!Promise<?SDK.SnapshotWithRect>} */ (Promise.resolve(null)); } @@ -185,8 +188,9 @@ */ _initGL(canvas) { const gl = canvas.getContext('webgl'); - if (!gl) + if (!gl) { return null; + } gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.enable(gl.BLEND); gl.clearColor(0.0, 0.0, 0.0, 0.0); @@ -264,8 +268,9 @@ .translate(-baseWidth / 2, -baseHeight / 2, 0); let bounds; - for (let i = 0; i < this._rects.length; ++i) + for (let i = 0; i < this._rects.length; ++i) { bounds = UI.Geometry.boundsForTransformedPoints(scaleAndRotationMatrix, this._rects[i].vertices, bounds); + } this._transformController.clampOffsets( (paddingX - bounds.maxX) / window.devicePixelRatio, @@ -324,11 +329,13 @@ * @return {?WebGLRenderingContext} */ _initGLIfNecessary() { - if (this._gl) + if (this._gl) { return this._gl; + } this._gl = this._initGL(this._canvasElement); - if (!this._gl) + if (!this._gl) { return null; + } this._initShaders(); this._initWhiteTexture(); this._initChromeTextures(); @@ -348,8 +355,9 @@ this._visibleLayers = new Set(); while (queue.length > 0) { const layer = queue.shift(); - if (showInternalLayers || layer.drawsContent()) + if (showInternalLayers || layer.drawsContent()) { this._visibleLayers.add(layer); + } const children = layer.children(); for (let i = 0; i < children.length; ++i) { this._depthByLayerId[children[i].id()] = ++depth; @@ -392,8 +400,9 @@ * @param {!SDK.Layer} layer */ _calculateLayerRect(layer) { - if (!this._visibleLayers.has(layer)) + if (!this._visibleLayers.has(layer)) { return; + } const selection = new LayerViewer.LayerView.LayerSelection(layer); const rect = new LayerViewer.Layers3DView.Rectangle(selection); rect.setVertices(layer.quad(), this._depthForLayer(layer)); @@ -448,8 +457,9 @@ const tiles = this._textureManager.tilesForLayer(layer); for (let i = 0; i < tiles.length; ++i) { const tile = tiles[i]; - if (!tile.texture) + if (!tile.texture) { continue; + } const selection = new LayerViewer.LayerView.SnapshotSelection(layer, {rect: tile.rect, snapshot: tile.snapshot}); const rect = new LayerViewer.Layers3DView.Rectangle(selection); rect.calculateVerticesFromRect(layer, tile.rect, this._depthForLayer(layer) + 1); @@ -463,8 +473,9 @@ this._dimensionsForAutoscale = {width: 0, height: 0}; this._layerTree.forEachLayer(this._calculateLayerRect.bind(this)); - if (this._showSlowScrollRectsSetting.get()) + if (this._showSlowScrollRectsSetting.get()) { this._layerTree.forEachLayer(this._calculateLayerScrollRects.bind(this)); + } if (this._layerTexture && this._visibleLayers.has(this._layerTexture.layer)) { const layer = this._layerTexture.layer; @@ -485,8 +496,9 @@ _makeColorsArray(color) { let colors = []; const normalizedColor = [color[0] / 255, color[1] / 255, color[2] / 255, color[3]]; - for (let i = 0; i < 4; i++) + for (let i = 0; i < 4; i++) { colors = colors.concat(normalizedColor); + } return colors; } @@ -540,8 +552,9 @@ _drawViewportAndChrome() { const viewport = this._layerTree.viewportSize(); - if (!viewport) + if (!viewport) { return; + } const drawChrome = !Common.moduleSetting('frameViewerHideChromeWindow').get() && this._chromeTextures.length >= 3 && this._chromeTextures.indexOf(undefined) < 0; @@ -552,8 +565,9 @@ this._drawRectangle( vertices, drawChrome ? this._gl.LINE_STRIP : this._gl.LINE_LOOP, LayerViewer.Layers3DView.ViewportBorderColor); - if (!drawChrome) + if (!drawChrome) { return; + } const borderAdjustment = LayerViewer.Layers3DView.ViewportBorderWidth / 2; const viewportWidth = this._layerTree.viewportSize().width + 2 * borderAdjustment; @@ -565,8 +579,9 @@ for (let i = 0; i < this._chromeTextures.length; ++i) { const width = i === LayerViewer.Layers3DView.ChromeTexture.Middle ? middleFragmentWidth : this._chromeTextures[i].image.naturalWidth; - if (width < 0 || x + width > viewportWidth) + if (width < 0 || x + width > viewportWidth) { break; + } vertices = [x, y, z, x + width, y, z, x + width, y + chromeHeight, z, x, y + chromeHeight, z]; this._drawTexture(vertices, /** @type {!WebGLTexture} */ (this._chromeTextures[i])); x += width; @@ -578,13 +593,15 @@ */ _drawViewRect(rect) { const vertices = rect.vertices; - if (rect.texture) + if (rect.texture) { this._drawTexture(vertices, rect.texture, rect.fillColor || undefined); - else if (rect.fillColor) + } else if (rect.fillColor) { this._drawRectangle(vertices, this._gl.TRIANGLE_FAN, rect.fillColor); + } this._gl.lineWidth(rect.lineWidth); - if (rect.borderColor) + if (rect.borderColor) { this._drawRectangle(vertices, this._gl.LINE_LOOP, rect.borderColor); + } } _update() { @@ -634,8 +651,9 @@ * @return {?LayerViewer.LayerView.Selection} */ _selectionFromEventPoint(event) { - if (!this._layerTree) + if (!this._layerTree) { return null; + } let closestIntersectionPoint = Infinity; let closestObject = null; const projectionMatrix = @@ -647,8 +665,9 @@ * @param {!LayerViewer.Layers3DView.Rectangle} rect */ function checkIntersection(rect) { - if (!rect.relatedObject) + if (!rect.relatedObject) { return; + } const t = rect.intersectWithLine(projectionMatrix, x0, y0); if (t < closestIntersectionPoint) { closestIntersectionPoint = t; @@ -707,8 +726,9 @@ * @param {!Event} event */ _onMouseMove(event) { - if (event.which) + if (event.which) { return; + } this._layerViewHost.hoverObject(this._selectionFromEventPoint(event)); } @@ -726,8 +746,9 @@ _onMouseUp(event) { const maxDistanceInPixels = 6; if (this._mouseDownX && Math.abs(event.clientX - this._mouseDownX) < maxDistanceInPixels && - Math.abs(event.clientY - this._mouseDownY) < maxDistanceInPixels) + Math.abs(event.clientY - this._mouseDownY) < maxDistanceInPixels) { this._layerViewHost.selectObject(this._selectionFromEventPoint(event)); + } delete this._mouseDownX; delete this._mouseDownY; } @@ -737,8 +758,9 @@ */ _onDoubleClick(event) { const selection = this._selectionFromEventPoint(event); - if (selection && (selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot || selection.layer())) + if (selection && (selection.type() === LayerViewer.LayerView.Selection.Type.Snapshot || selection.layer())) { this.dispatchEventToListeners(LayerViewer.Layers3DView.Events.PaintProfilerRequested, selection); + } event.stopPropagation(); } @@ -870,8 +892,9 @@ } reset() { - if (this._tilesByLayer) + if (this._tilesByLayer) { this.setLayerTree(null); + } /** @type {!Map<!SDK.Layer, !Array<!LayerViewer.LayerTextureManager.Tile>>} */ this._tilesByLayer = new Map(); @@ -884,8 +907,9 @@ */ setContext(glContext) { this._gl = glContext; - if (this._scale) + if (this._scale) { this._updateTextures(); + } } suspend() { @@ -894,8 +918,9 @@ resume() { this._active = true; - if (this._queue.length) + if (this._queue.length) { this._update(); + } } /** @@ -906,8 +931,9 @@ const oldLayers = Array.from(this._tilesByLayer.keys()); if (layerTree) { layerTree.forEachLayer(layer => { - if (!layer.drawsContent()) + if (!layer.drawsContent()) { return; + } newLayers.add(layer); if (!this._tilesByLayer.has(layer)) { this._tilesByLayer.set(layer, []); @@ -915,11 +941,13 @@ } }); } - if (!oldLayers.length) + if (!oldLayers.length) { this.forceUpdate(); + } for (const layer of oldLayers) { - if (newLayers.has(layer)) + if (newLayers.has(layer)) { continue; + } this._tilesByLayer.get(layer).forEach(tile => tile.dispose()); this._tilesByLayer.delete(layer); } @@ -944,10 +972,12 @@ } } this._tilesByLayer.set(layer, reusedTiles.concat(newTiles)); - for (const tile of oldSnapshotsToTiles.values()) + for (const tile of oldSnapshotsToTiles.values()) { tile.dispose(); - if (!this._gl || !this._scale) + } + if (!this._gl || !this._scale) { return Promise.resolve(); + } return Promise.all(newTiles.map(tile => tile.update(this._gl, this._scale))).then(this._textureUpdatedCallback); } @@ -955,8 +985,9 @@ * @param {number} scale */ setScale(scale) { - if (this._scale && this._scale >= scale) + if (this._scale && this._scale >= scale) { return; + } this._scale = scale; this._updateTextures(); } @@ -973,10 +1004,12 @@ * @param {!SDK.Layer} layer */ layerNeedsUpdate(layer) { - if (this._queue.indexOf(layer) < 0) + if (this._queue.indexOf(layer) < 0) { this._queue.push(layer); - if (this._active) + } + if (this._active) { this._throttler.schedule(this._update.bind(this)); + } } forceUpdate() { @@ -990,10 +1023,12 @@ */ _update() { const layer = this._queue.shift(); - if (!layer) + if (!layer) { return Promise.resolve(); - if (this._queue.length) + } + if (this._queue.length) { this._throttler.schedule(this._update.bind(this)); + } return this._updateLayer(layer); } @@ -1007,16 +1042,19 @@ } _updateTextures() { - if (!this._gl) + if (!this._gl) { return; - if (!this._scale) + } + if (!this._scale) { return; + } for (const tiles of this._tilesByLayer.values()) { for (const tile of tiles) { const promise = tile.updateScale(this._gl, this._scale); - if (promise) + if (promise) { promise.then(this._textureUpdatedCallback); + } } } } @@ -1129,8 +1167,9 @@ for (i = 0; i < tVects.length; ++i) { const product = UI.Geometry.scalarProduct(normal, UI.Geometry.crossProduct(tVects[i], tVects[(i + 1) % tVects.length])); - if (product < 0) + if (product < 0) { return undefined; + } } return t; } @@ -1166,8 +1205,9 @@ * @return {?Promise} */ updateScale(glContext, scale) { - if (this.texture && this.scale >= scale) + if (this.texture && this.scale >= scale) { return null; + } return this.update(glContext, scale); }
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/PaintProfilerView.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/PaintProfilerView.js index 9d8c6105..62e7a269 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/PaintProfilerView.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/PaintProfilerView.js
@@ -68,8 +68,9 @@ * @return {!Object.<string, !LayerViewer.PaintProfilerCategory>} */ static categories() { - if (LayerViewer.PaintProfilerView._categories) + if (LayerViewer.PaintProfilerView._categories) { return LayerViewer.PaintProfilerView._categories; + } LayerViewer.PaintProfilerView._categories = { shapes: new LayerViewer.PaintProfilerCategory('shapes', Common.UIString('Shapes'), 'rgb(255, 161, 129)'), bitmap: new LayerViewer.PaintProfilerCategory('bitmap', Common.UIString('Bitmap'), 'rgb(136, 196, 255)'), @@ -83,8 +84,9 @@ * @return {!Object.<string, !LayerViewer.PaintProfilerCategory>} */ static _initLogItemCategories() { - if (LayerViewer.PaintProfilerView._logItemCategoriesMap) + if (LayerViewer.PaintProfilerView._logItemCategoriesMap) { return LayerViewer.PaintProfilerView._logItemCategoriesMap; + } const categories = LayerViewer.PaintProfilerView.categories(); @@ -161,8 +163,9 @@ async setSnapshotAndLog(snapshot, log, clipRect) { this._reset(); this._snapshot = snapshot; - if (this._snapshot) + if (this._snapshot) { this._snapshot.addReference(); + } this._log = log; this._logCategories = this._log.map(LayerViewer.PaintProfilerView._categoryForLogItem); @@ -191,16 +194,18 @@ const needsUpdate = scale > this._scale; const predictiveGrowthFactor = 2; this._pendingScale = Math.min(1, scale * predictiveGrowthFactor); - if (needsUpdate && this._snapshot) + if (needsUpdate && this._snapshot) { this._updateImage(); + } } _update() { this._canvas.width = this._canvasContainer.clientWidth * window.devicePixelRatio; this._canvas.height = this._canvasContainer.clientHeight * window.devicePixelRatio; this._samplesPerBar = 0; - if (!this._profiles || !this._profiles.length) + if (!this._profiles || !this._profiles.length) { return; + } const maxBars = Math.floor((this._canvas.width - 2 * this._barPaddingWidth) / this._outerBarWidth); const sampleCount = this._log.length; @@ -223,14 +228,16 @@ // Normalize by total number of samples accumulated. const factor = this._profiles.length * (i - lastBarIndex); lastBarTime /= factor; - for (categoryName in heightByCategory) + for (categoryName in heightByCategory) { heightByCategory[categoryName] /= factor; + } barTimes.push(lastBarTime); barHeightByCategory.push(heightByCategory); - if (lastBarTime > maxBarTime) + if (lastBarTime > maxBarTime) { maxBarTime = lastBarTime; + } lastBarTime = 0; heightByCategory = {}; lastBarIndex = i; @@ -240,8 +247,9 @@ const paddingHeight = 4 * window.devicePixelRatio; const scale = (this._canvas.height - paddingHeight - this._minBarHeight) / maxBarTime; for (let i = 0; i < barTimes.length; ++i) { - for (const categoryName in barHeightByCategory[i]) + for (const categoryName in barHeightByCategory[i]) { barHeightByCategory[i][categoryName] *= (barTimes[i] * scale + this._minBarHeight) / barTimes[i]; + } this._renderBar(i, barHeightByCategory[i]); } } @@ -255,8 +263,9 @@ let currentHeight = 0; const x = this._barPaddingWidth + index * this._outerBarWidth; for (const categoryName in categories) { - if (!heightByCategory[categoryName]) + if (!heightByCategory[categoryName]) { continue; + } currentHeight += heightByCategory[categoryName]; const y = this._canvas.height - currentHeight; this._context.fillStyle = categories[categoryName].color; @@ -267,15 +276,17 @@ _onWindowChanged() { this.dispatchEventToListeners(LayerViewer.PaintProfilerView.Events.WindowChanged); this._updatePieChart(); - if (this._updateImageTimer) + if (this._updateImageTimer) { return; + } this._updateImageTimer = setTimeout(this._updateImage.bind(this), 100); } _updatePieChart() { const window = this.selectionWindow(); - if (!this._profiles || !this._profiles.length || !window) + if (!this._profiles || !this._profiles.length || !window) { return; + } let totalTime = 0; const timeByCategory = {}; for (let i = window.left; i < window.right; ++i) { @@ -289,8 +300,9 @@ } } this._pieChart.setTotal(totalTime / this._profiles.length); - for (const color in timeByCategory) + for (const color in timeByCategory) { this._pieChart.addSlice(timeByCategory[color] / this._profiles.length, color); + } } /** @@ -305,8 +317,9 @@ * @return {?{left: number, right: number}} */ selectionWindow() { - if (!this._log) + if (!this._log) { return null; + } const screenLeft = this._selectionWindow.windowLeft * this._canvas.width; const screenRight = this._selectionWindow.windowRight * this._canvas.width; @@ -329,16 +342,18 @@ } const scale = this._pendingScale; this._snapshot.replay(scale, left, right).then(image => { - if (!image) + if (!image) { return; + } this._scale = scale; this._showImageCallback(image); }); } _reset() { - if (this._snapshot) + if (this._snapshot) { this._snapshot.release(); + } this._snapshot = null; this._profiles = null; this._selectionWindow.reset(); @@ -410,18 +425,21 @@ const root = this._treeOutline.rootElement(); for (;;) { const child = root.firstChild(); - if (!child || child._logItem.commandIndex >= this._selectionWindow.left) + if (!child || child._logItem.commandIndex >= this._selectionWindow.left) { break; + } root.removeChildAtIndex(0); } for (;;) { const child = root.lastChild(); - if (!child || child._logItem.commandIndex < this._selectionWindow.right) + if (!child || child._logItem.commandIndex < this._selectionWindow.right) { break; + } root.removeChildAtIndex(root.children().length - 1); } - for (let i = this._selectionWindow.left, right = this._selectionWindow.right; i < right; ++i) + for (let i = this._selectionWindow.left, right = this._selectionWindow.right; i < right; ++i) { this._appendLogItem(this._log[i]); + } return Promise.resolve(); } }; @@ -453,8 +471,9 @@ * @returns {!Promise} */ async onpopulate() { - for (const param in this._logItem.params) + for (const param in this._logItem.params) { LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(this, param, this._logItem.params[param]); + } } /** @@ -463,16 +482,19 @@ * @return {string} */ _paramToString(param, name) { - if (typeof param !== 'object') + if (typeof param !== 'object') { return typeof param === 'string' && param.length > 100 ? name : JSON.stringify(param); + } let str = ''; let keyCount = 0; for (const key in param) { if (++keyCount > 4 || typeof param[key] === 'object' || - (typeof param[key] === 'string' && param[key].length > 100)) + (typeof param[key] === 'string' && param[key].length > 100)) { return name; - if (str) + } + if (str) { str += ', '; + } str += param[key]; } return str; @@ -485,8 +507,9 @@ _paramsToString(params) { let str = ''; for (const key in params) { - if (str) + if (str) { str += ', '; + } str += this._paramToString(params[key], key); } return str; @@ -520,8 +543,9 @@ const treeElement = new LayerViewer.LogPropertyTreeElement({name: name, value: value}); element.appendChild(treeElement); if (value && typeof value === 'object') { - for (const property in value) + for (const property in value) { LayerViewer.LogPropertyTreeElement._appendLogPropertyItem(treeElement, property, value[property]); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/layer_viewer/TransformController.js b/third_party/blink/renderer/devtools/front_end/layer_viewer/TransformController.js index a63494b..8a04f6b7 100644 --- a/third_party/blink/renderer/devtools/front_end/layer_viewer/TransformController.js +++ b/third_party/blink/renderer/devtools/front_end/layer_viewer/TransformController.js
@@ -16,8 +16,9 @@ super(); this._shortcuts = {}; this.element = element; - if (this.element.tabIndex < 0) + if (this.element.tabIndex < 0) { this.element.tabIndex = 0; + } this._registerShortcuts(); UI.installDragHandle( element, this._onDragStart.bind(this), this._onDrag.bind(this), this._onDragEnd.bind(this), 'move', null); @@ -67,18 +68,21 @@ const shortcutKey = UI.KeyboardShortcut.makeKeyFromEventIgnoringModifiers(event); const handler = this._shortcuts[shortcutKey]; - if (handler && handler(event)) + if (handler && handler(event)) { event.consume(); + } } _onKeyUp(event) { - if (event.keyCode === UI.KeyboardShortcut.Keys.Shift.code) + if (event.keyCode === UI.KeyboardShortcut.Keys.Shift.code) { this._toggleMode(); + } } _addShortcuts(keys, handler) { - for (let i = 0; i < keys.length; ++i) + for (let i = 0; i < keys.length; ++i) { this._shortcuts[keys[i].key] = handler; + } } _registerShortcuts() { @@ -121,16 +125,18 @@ * @param {!LayerViewer.TransformController.Modes} mode */ _setMode(mode) { - if (this._mode === mode) + if (this._mode === mode) { return; + } this._mode = mode; this._updateModeButtons(); this.element.focus(); } _updateModeButtons() { - for (const mode in this._modeButtons) + for (const mode in this._modeButtons) { this._modeButtons[mode].setToggled(mode === this._mode); + } } /** @@ -139,8 +145,9 @@ resetAndNotify(event) { this._reset(); this._postChangeEvent(); - if (event) + if (event) { event.preventDefault(); + } this.element.focus(); }
diff --git a/third_party/blink/renderer/devtools/front_end/layers/LayerPaintProfilerView.js b/third_party/blink/renderer/devtools/front_end/layers/LayerPaintProfilerView.js index 629ff48..23409eb 100644 --- a/third_party/blink/renderer/devtools/front_end/layers/LayerPaintProfilerView.js +++ b/third_party/blink/renderer/devtools/front_end/layers/LayerPaintProfilerView.js
@@ -36,8 +36,9 @@ function setSnapshotAndLog(snapshot, log) { this._logTreeView.setCommandLog(log || []); this._paintProfilerView.setSnapshotAndLog(snapshot, log || [], null); - if (snapshot) + if (snapshot) { snapshot.release(); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/layers/LayerTreeModel.js b/third_party/blink/renderer/devtools/front_end/layers/LayerTreeModel.js index db9d6e1..2efd118 100644 --- a/third_party/blink/renderer/devtools/front_end/layers/LayerTreeModel.js +++ b/third_party/blink/renderer/devtools/front_end/layers/LayerTreeModel.js
@@ -48,23 +48,26 @@ } disable() { - if (!this._enabled) + if (!this._enabled) { return; + } this._enabled = false; this._layerTreeAgent.disable(); } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._enabled = true; this._forceEnable(); } _forceEnable() { this._lastPaintRectByLayerId = {}; - if (!this._layerTree) + if (!this._layerTree) { this._layerTree = new Layers.AgentLayerTree(this); + } this._layerTreeAgent.enable(); } @@ -79,8 +82,9 @@ * @param {?Array.<!Protocol.LayerTree.Layer>} layers */ async _layerTreeChanged(layers) { - if (!this._enabled) + if (!this._enabled) { return; + } this._throttler.schedule(this._innerSetLayers.bind(this, layers)); } @@ -95,8 +99,9 @@ for (const layerId in this._lastPaintRectByLayerId) { const lastPaintRect = this._lastPaintRectByLayerId[layerId]; const layer = layerTree.layerById(layerId); - if (layer) + if (layer) { layer._lastPaintRect = lastPaintRect; + } } this._lastPaintRectByLayerId = {}; @@ -108,8 +113,9 @@ * @param {!Protocol.DOM.Rect} clipRect */ _layerPainted(layerId, clipRect) { - if (!this._enabled) + if (!this._enabled) { return; + } const layerTree = /** @type {!Layers.AgentLayerTree} */ (this._layerTree); const layer = layerTree.layerById(layerId); if (!layer) { @@ -122,8 +128,9 @@ _onMainFrameNavigated() { this._layerTree = null; - if (this._enabled) + if (this._enabled) { this._forceEnable(); + } } }; @@ -159,8 +166,9 @@ const idsToResolve = new Set(); for (let i = 0; i < payload.length; ++i) { const backendNodeId = payload[i].backendNodeId; - if (!backendNodeId || this.backendNodeIdToNode().has(backendNodeId)) + if (!backendNodeId || this.backendNodeIdToNode().has(backendNodeId)) { continue; + } idsToResolve.add(backendNodeId); } await this.resolveBackendNodeIds(idsToResolve); @@ -174,33 +182,39 @@ this.setRoot(null); this.setContentRoot(null); // Payload will be null when not in the composited mode. - if (!layers) + if (!layers) { return; + } let root; const oldLayersById = this._layersById; this._layersById = {}; for (let i = 0; i < layers.length; ++i) { const layerId = layers[i].layerId; let layer = oldLayersById[layerId]; - if (layer) + if (layer) { layer._reset(layers[i]); - else + } else { layer = new Layers.AgentLayer(this._layerTreeModel, layers[i]); + } this._layersById[layerId] = layer; const backendNodeId = layers[i].backendNodeId; - if (backendNodeId) + if (backendNodeId) { layer._setNode(this.backendNodeIdToNode().get(backendNodeId)); - if (!this.contentRoot() && layer.drawsContent()) + } + if (!this.contentRoot() && layer.drawsContent()) { this.setContentRoot(layer); + } const parentId = layer.parentId(); if (parentId) { const parent = this._layersById[parentId]; - if (!parent) + if (!parent) { console.assert(parent, 'missing parent ' + parentId + ' for layer ' + layerId); + } parent.addChild(layer); } else { - if (root) + if (root) { console.assert(false, 'Multiple root layers'); + } root = layer; } } @@ -270,8 +284,9 @@ * @param {!SDK.Layer} child */ addChild(child) { - if (child._parent) + if (child._parent) { console.assert(false, 'Child already has a parent'); + } this._children.push(child); child._parent = this; } @@ -297,8 +312,9 @@ */ nodeForSelfOrAncestor() { for (let layer = this; layer; layer = layer._parent) { - if (layer._node) + if (layer._node) { return layer._node; + } } return null; } @@ -438,8 +454,9 @@ */ snapshots() { const promise = this._layerTreeModel._paintProfilerModel.makeSnapshot(this.id()).then(snapshot => { - if (!snapshot) + if (!snapshot) { return null; + } return {rect: {x: 0, y: 0, width: this.width(), height: this.height()}, snapshot: snapshot}; }); return [promise];
diff --git a/third_party/blink/renderer/devtools/front_end/layers/LayersPanel.js b/third_party/blink/renderer/devtools/front_end/layers/LayersPanel.js index 413c0e0..c40ea5c 100644 --- a/third_party/blink/renderer/devtools/front_end/layers/LayersPanel.js +++ b/third_party/blink/renderer/devtools/front_end/layers/LayersPanel.js
@@ -79,16 +79,18 @@ */ wasShown() { super.wasShown(); - if (this._model) + if (this._model) { this._model.enable(); + } } /** * @override */ willHide() { - if (this._model) + if (this._model) { this._model.disable(); + } super.willHide(); } @@ -97,15 +99,18 @@ * @param {!SDK.Target} target */ targetAdded(target) { - if (this._model) + if (this._model) { return; + } this._model = target.model(Layers.LayerTreeModel); - if (!this._model) + if (!this._model) { return; + } this._model.addEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged, this._onLayerTreeUpdated, this); this._model.addEventListener(Layers.LayerTreeModel.Events.LayerPainted, this._onLayerPainted, this); - if (this.isShowing()) + if (this.isShowing()) { this._model.enable(); + } } /** @@ -113,8 +118,9 @@ * @param {!SDK.Target} target */ targetRemoved(target) { - if (!this._model || this._model.target() !== target) + if (!this._model || this._model.target() !== target) { return; + } this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerTreeChanged, this._onLayerTreeUpdated, this); this._model.removeEventListener(Layers.LayerTreeModel.Events.LayerPainted, this._onLayerPainted, this); this._model.disable(); @@ -129,8 +135,9 @@ * @return {!Promise<*>} */ _update() { - if (this._model) + if (this._model) { this._layerViewHost.setLayerTree(this._model.layerTree()); + } return Promise.resolve(); } @@ -138,11 +145,13 @@ * @param {!Common.Event} event */ _onLayerPainted(event) { - if (!this._model) + if (!this._model) { return; + } const layer = /** @type {!SDK.Layer} */ (event.data); - if (this._layerViewHost.selection() && this._layerViewHost.selection().layer() === layer) + if (this._layerViewHost.selection() && this._layerViewHost.selection().layer() === layer) { this._layerDetailsView.update(); + } this._layers3DView.updateLayerSnapshot(layer); } @@ -152,8 +161,9 @@ _onPaintProfileRequested(event) { const selection = /** @type {!LayerViewer.LayerView.Selection} */ (event.data); this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect => { - if (!snapshotWithRect) + if (!snapshotWithRect) { return; + } this._layerBeingProfiled = selection.layer(); if (!this._tabbedPane.hasTab(Layers.LayersPanel.DetailsViewTabs.Profiler)) { this._tabbedPane.appendTab( @@ -169,8 +179,9 @@ * @param {!Common.Event} event */ _onTabClosed(event) { - if (event.data.tabId !== Layers.LayersPanel.DetailsViewTabs.Profiler || !this._layerBeingProfiled) + if (event.data.tabId !== Layers.LayersPanel.DetailsViewTabs.Profiler || !this._layerBeingProfiled) { return; + } this._paintProfilerView.reset(); this._layers3DView.showImageForLayer(this._layerBeingProfiled, undefined); this._layerBeingProfiled = null;
diff --git a/third_party/blink/renderer/devtools/front_end/layers_test_runner/LayersTestRunner.js b/third_party/blink/renderer/devtools/front_end/layers_test_runner/LayersTestRunner.js index 20e51c3d..31d6039 100644 --- a/third_party/blink/renderer/devtools/front_end/layers_test_runner/LayersTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/layers_test_runner/LayersTestRunner.js
@@ -8,8 +8,9 @@ */ LayersTestRunner.layerTreeModel = function() { - if (!LayersTestRunner._layerTreeModel) + if (!LayersTestRunner._layerTreeModel) { LayersTestRunner._layerTreeModel = TestRunner.mainTarget.model(Layers.LayerTreeModel); + } return LayersTestRunner._layerTreeModel; }; @@ -20,18 +21,21 @@ const height = layer.height(); const width = layer.width(); - if (height <= 200 && width <= 200) + if (height <= 200 && width <= 200) { label += ' ' + height + 'x' + width; + } - if (typeof layer.__extraData !== 'undefined') + if (typeof layer.__extraData !== 'undefined') { label += ' (' + layer.__extraData + ')'; + } return label; }; LayersTestRunner.dumpLayerTree = function(prefix, root) { - if (!prefix) + if (!prefix) { prefix = ''; + } if (!root) { root = LayersTestRunner.layerTreeModel().layerTree().contentRoot(); @@ -48,17 +52,21 @@ }; LayersTestRunner.dumpLayers3DView = function(prefix, root) { - if (!prefix) + if (!prefix) { prefix = ''; + } - if (!root) + if (!root) { root = UI.panels.layers._layers3DView._rotatingContainerElement; + } - if (root.__layer) + if (root.__layer) { TestRunner.addResult(prefix + LayersTestRunner.labelForLayer(root.__layer)); + } - for (let element = root.firstElementChild; element; element = element.nextSibling) + for (let element = root.firstElementChild; element; element = element.nextSibling) { LayersTestRunner.dumpLayers3DView(prefix + ' ', element); + } }; LayersTestRunner.evaluateAndWaitForTreeChange = async function(expression) { @@ -72,11 +80,13 @@ function testLayer(layer) { const node = layer.node(); - if (!node) + if (!node) { return false; + } - if (!node || node.getAttribute('id') !== nodeIdAttribute) + if (!node || node.getAttribute('id') !== nodeIdAttribute) { return false; + } result = layer; return true; @@ -84,8 +94,9 @@ LayersTestRunner.layerTreeModel().layerTree().forEachLayer(testLayer); - if (!result) + if (!result) { TestRunner.addResult('ERROR: No layer for ' + nodeIdAttribute); + } return result; }; @@ -134,10 +145,12 @@ LayersTestRunner.dumpSelectedStyles = function(message, element) { const classes = []; - if (element.classList.contains('selected')) + if (element.classList.contains('selected')) { classes.push('selected'); - if (element.classList.contains('hovered')) + } + if (element.classList.contains('hovered')) { classes.push('hovered'); + } TestRunner.addResult(message + ': ' + classes.join(', ')); };
diff --git a/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js b/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js index 30e04f1..1854747 100644 --- a/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js +++ b/third_party/blink/renderer/devtools/front_end/main/ExecutionContextSelector.js
@@ -40,8 +40,9 @@ */ function deferred() { // We always want the second context for the service worker targets. - if (!this._context.flavor(SDK.Target)) + if (!this._context.flavor(SDK.Target)) { this._context.setFlavor(SDK.Target, runtimeModel.target()); + } } } @@ -51,12 +52,14 @@ */ modelRemoved(runtimeModel) { const currentExecutionContext = this._context.flavor(SDK.ExecutionContext); - if (currentExecutionContext && currentExecutionContext.runtimeModel === runtimeModel) + if (currentExecutionContext && currentExecutionContext.runtimeModel === runtimeModel) { this._currentExecutionContextGone(); + } const models = this._targetManager.models(SDK.RuntimeModel); - if (this._context.flavor(SDK.Target) === runtimeModel.target() && models.length) + if (this._context.flavor(SDK.Target) === runtimeModel.target() && models.length) { this._context.setFlavor(SDK.Target, models[0].target()); + } } /** @@ -66,8 +69,9 @@ const newContext = /** @type {?SDK.ExecutionContext} */ (event.data); if (newContext) { this._context.setFlavor(SDK.Target, newContext.target()); - if (!this._ignoreContextChanged) + if (!this._ignoreContextChanged) { this._lastSelectedContextId = this._contextPersistentId(newContext); + } } } @@ -86,22 +90,26 @@ const newTarget = /** @type {?SDK.Target} */ (event.data); const currentContext = this._context.flavor(SDK.ExecutionContext); - if (!newTarget || (currentContext && currentContext.target() === newTarget)) + if (!newTarget || (currentContext && currentContext.target() === newTarget)) { return; + } const runtimeModel = newTarget.model(SDK.RuntimeModel); const executionContexts = runtimeModel ? runtimeModel.executionContexts() : []; - if (!executionContexts.length) + if (!executionContexts.length) { return; + } let newContext = null; for (let i = 0; i < executionContexts.length && !newContext; ++i) { - if (this._shouldSwitchToContext(executionContexts[i])) + if (this._shouldSwitchToContext(executionContexts[i])) { newContext = executionContexts[i]; + } } for (let i = 0; i < executionContexts.length && !newContext; ++i) { - if (this._isDefaultContext(executionContexts[i])) + if (this._isDefaultContext(executionContexts[i])) { newContext = executionContexts[i]; + } } this._ignoreContextChanged = true; this._context.setFlavor(SDK.ExecutionContext, newContext || executionContexts[0]); @@ -113,10 +121,12 @@ * @return {boolean} */ _shouldSwitchToContext(executionContext) { - if (this._lastSelectedContextId && this._lastSelectedContextId === this._contextPersistentId(executionContext)) + if (this._lastSelectedContextId && this._lastSelectedContextId === this._contextPersistentId(executionContext)) { return true; - if (!this._lastSelectedContextId && this._isDefaultContext(executionContext)) + } + if (!this._lastSelectedContextId && this._isDefaultContext(executionContext)) { return true; + } return false; } @@ -125,14 +135,17 @@ * @return {boolean} */ _isDefaultContext(executionContext) { - if (!executionContext.isDefault || !executionContext.frameId) + if (!executionContext.isDefault || !executionContext.frameId) { return false; - if (executionContext.target().parentTarget()) + } + if (executionContext.target().parentTarget()) { return false; + } const resourceTreeModel = executionContext.target().model(SDK.ResourceTreeModel); const frame = resourceTreeModel && resourceTreeModel.frameForId(executionContext.frameId); - if (frame && frame.isTopFrame()) + if (frame && frame.isTopFrame()) { return true; + } return false; } @@ -148,8 +161,9 @@ */ _onExecutionContextDestroyed(event) { const executionContext = /** @type {!SDK.ExecutionContext}*/ (event.data); - if (this._context.flavor(SDK.ExecutionContext) === executionContext) + if (this._context.flavor(SDK.ExecutionContext) === executionContext) { this._currentExecutionContextGone(); + } } /** @@ -159,8 +173,9 @@ const runtimeModel = /** @type {!SDK.RuntimeModel} */ (event.data); const executionContexts = runtimeModel.executionContexts(); for (let i = 0; i < executionContexts.length; i++) { - if (this._switchContextIfNecessary(executionContexts[i])) + if (this._switchContextIfNecessary(executionContexts[i])) { break; + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/main/Main.js b/third_party/blink/renderer/devtools/front_end/main/Main.js index 043cf09..d0e24d3 100644 --- a/third_party/blink/renderer/devtools/front_end/main/Main.js +++ b/third_party/blink/renderer/devtools/front_end/main/Main.js
@@ -44,8 +44,9 @@ * @param {string} label */ static time(label) { - if (Host.isUnderTest()) + if (Host.isUnderTest()) { return; + } console.time(label); } @@ -53,8 +54,9 @@ * @param {string} label */ static timeEnd(label) { - if (Host.isUnderTest()) + if (Host.isUnderTest()) { return; + } console.timeEnd(label); } @@ -71,8 +73,9 @@ */ _gotPreferences(prefs) { console.timeStamp('Main._gotPreferences'); - if (Host.isUnderTest(prefs)) + if (Host.isUnderTest(prefs)) { self.runtime.useTestBase(); + } this._createSettings(prefs); this._createAppUI(); } @@ -84,10 +87,11 @@ _createSettings(prefs) { this._initializeExperiments(); let storagePrefix = ''; - if (Host.isCustomDevtoolsFrontend()) + if (Host.isCustomDevtoolsFrontend()) { storagePrefix = '__custom__'; - else if (!Runtime.queryParam('can_dock') && !!Runtime.queryParam('debugFrontend') && !Host.isUnderTest()) + } else if (!Runtime.queryParam('can_dock') && !!Runtime.queryParam('debugFrontend') && !Host.isUnderTest()) { storagePrefix = '__bundled__'; + } let localStorage; if (!Host.isUnderTest() && window.localStorage) { @@ -100,8 +104,9 @@ prefs, InspectorFrontendHost.setPreference, InspectorFrontendHost.removePreference, InspectorFrontendHost.clearPreferences, storagePrefix); Common.settings = new Common.Settings(globalStorage, localStorage); - if (!Host.isUnderTest()) + if (!Host.isUnderTest()) { new Common.VersionController().updateVersion(); + } } _initializeExperiments() { @@ -139,8 +144,9 @@ Runtime.experiments.cleanUpStaleExperiments(); const enabledExperiments = Runtime.queryParam('enabledExperiments'); - if (enabledExperiments) + if (enabledExperiments) { Runtime.experiments.setServerEnabledExperiments(enabledExperiments.split(';')); + } Runtime.experiments.setDefaultExperiments([ 'backgroundServices', 'backgroundServicesNotifications', @@ -148,8 +154,9 @@ 'backgroundServicesPaymentHandler', ]); - if (Host.isUnderTest() && Runtime.queryParam('test').includes('live-line-level-heap-profile.js')) + if (Host.isUnderTest() && Runtime.queryParam('test').includes('live-line-level-heap-profile.js')) { Runtime.experiments.enableForTest('liveHeapProfile'); + } } /** @@ -249,8 +256,9 @@ const extensions = self.runtime.extensions(Common.QueryParamHandler); for (const extension of extensions) { const value = Runtime.queryParam(extension.descriptor()['name']); - if (value !== null) + if (value !== null) { extension.instance().then(handleQueryParam.bind(null, value)); + } } /** @@ -270,8 +278,9 @@ Main.Main.time('Main._initializeTarget'); const instances = await Promise.all(self.runtime.extensions('early-initialization').map(extension => extension.instance())); - for (const instance of instances) + for (const instance of instances) { await /** @type {!Common.Runnable} */ (instance).run(); + } // Used for browser tests. InspectorFrontendHost.readyForTest(); // Asynchronously run the extensions. @@ -295,8 +304,9 @@ * @param {!Common.Event} event */ async function changeListener(event) { - if (!event.data) + if (!event.data) { return; + } Common.settings.moduleSetting(setting).removeChangeListener(changeListener); (/** @type {!Common.Runnable} */ (await extension.instance())).run(); } @@ -331,8 +341,9 @@ */ function messageAdded(event) { const message = /** @type {!Common.Console.Message} */ (event.data); - if (message.show) + if (message.show) { Common.console.show(); + } } } @@ -394,8 +405,9 @@ const inspectElementModeShortcuts = UI.shortcutRegistry.shortcutDescriptorsForAction('elements.toggle-element-search'); - if (inspectElementModeShortcuts.length) + if (inspectElementModeShortcuts.length) { section.addKey(inspectElementModeShortcuts[0], Common.UIString('Select node to inspect')); + } const openResourceShortcut = UI.KeyboardShortcut.makeDescriptor('p', UI.KeyboardShortcut.Modifiers.CtrlOrMeta); section.addKey(openResourceShortcut, Common.UIString('Go to source')); @@ -410,8 +422,9 @@ } _postDocumentKeyDown(event) { - if (!event.handled) + if (!event.handled) { UI.shortcutRegistry.handleShortcut(event); + } } /** @@ -422,15 +435,18 @@ eventCopy['original'] = event; const document = event.target && event.target.ownerDocument; const target = document ? document.deepActiveElement() : null; - if (target) + if (target) { target.dispatchEvent(eventCopy); - if (eventCopy.handled) + } + if (eventCopy.handled) { event.preventDefault(); + } } _contextMenuEventFired(event) { - if (event.handled || event.target.classList.contains('popup-glasspane')) + if (event.handled || event.target.classList.contains('popup-glasspane')) { event.preventDefault(); + } } /** @@ -463,8 +479,9 @@ * @return {boolean} */ handleAction(context, actionId) { - if (InspectorFrontendHost.isHostedMode()) + if (InspectorFrontendHost.isHostedMode()) { return false; + } switch (actionId) { case 'main.zoom-in': @@ -496,8 +513,9 @@ handleAction(context, actionId) { const searchableView = UI.SearchableView.fromElement(document.deepActiveElement()) || UI.inspectorView.currentPanelDeprecated().searchableView(); - if (!searchableView) + if (!searchableView) { return false; + } switch (actionId) { case 'main.search-in-panel.find': return searchableView.handleFindShortcut(); @@ -543,8 +561,9 @@ 'Placement of DevTools relative to the page. (%s to restore last position)', toggleDockSideShorcuts[0].name); dockItemElement.appendChild(titleElement); const dockItemToolbar = new UI.Toolbar('', dockItemElement); - if (Host.isMac() && !UI.themeSupport.hasTheme()) + if (Host.isMac() && !UI.themeSupport.hasTheme()) { dockItemToolbar.makeBlueOnHover(); + } const undock = new UI.ToolbarToggle(Common.UIString('Undock into separate window'), 'largeicon-undock'); const bottom = new UI.ToolbarToggle(Common.UIString('Dock to bottom'), 'largeicon-dock-to-bottom'); const right = new UI.ToolbarToggle(Common.UIString('Dock to right'), 'largeicon-dock-to-right'); @@ -571,12 +590,13 @@ dockItemToolbar.appendToolbarItem(right); dockItemElement.addEventListener('keydown', event => { let dir = 0; - if (event.key === 'ArrowLeft') + if (event.key === 'ArrowLeft') { dir = -1; - else if (event.key === 'ArrowRight') + } else if (event.key === 'ArrowRight') { dir = 1; - else + } else { return; + } const buttons = [undock, left, bottom, right]; let index = buttons.findIndex(button => button.element.hasFocus()); @@ -597,8 +617,9 @@ } if (Components.dockController.dockSide() === Components.DockController.State.Undocked && - SDK.targetManager.mainTarget() && SDK.targetManager.mainTarget().type() === SDK.Target.Type.Frame) + SDK.targetManager.mainTarget() && SDK.targetManager.mainTarget().type() === SDK.Target.Type.Frame) { contextMenu.defaultSection().appendAction('inspector_main.focus-debuggee', Common.UIString('Focus debuggee')); + } contextMenu.defaultSection().appendAction( 'main.toggle-drawer', @@ -609,10 +630,12 @@ const extensions = self.runtime.extensions('view', undefined, true); for (const extension of extensions) { const descriptor = extension.descriptor(); - if (descriptor['persistence'] !== 'closeable') + if (descriptor['persistence'] !== 'closeable') { continue; - if (descriptor['location'] !== 'drawer-view' && descriptor['location'] !== 'panel') + } + if (descriptor['location'] !== 'drawer-view' && descriptor['location'] !== 'panel') { continue; + } moreTools.defaultSection().appendItem( extension.title(), UI.viewManager.showView.bind(UI.viewManager, descriptor['id'])); } @@ -652,8 +675,9 @@ Main.sendOverProtocol = function(method, params) { return new Promise((resolve, reject) => { Protocol.test.sendRawMessage(method, params, (err, ...results) => { - if (err) + if (err) { return reject(err); + } return resolve(results); }); });
diff --git a/third_party/blink/renderer/devtools/front_end/mobile_throttling/NetworkPanelIndicator.js b/third_party/blink/renderer/devtools/front_end/mobile_throttling/NetworkPanelIndicator.js index 34654cc2..f261b933 100644 --- a/third_party/blink/renderer/devtools/front_end/mobile_throttling/NetworkPanelIndicator.js +++ b/third_party/blink/renderer/devtools/front_end/mobile_throttling/NetworkPanelIndicator.js
@@ -5,8 +5,9 @@ MobileThrottling.NetworkPanelIndicator = class { constructor() { // TODO: we should not access network from other modules. - if (!UI.inspectorView.hasPanel('network')) + if (!UI.inspectorView.hasPanel('network')) { return; + } const manager = SDK.multitargetNetworkManager; manager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged, updateVisibility); manager.addEventListener(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged, updateVisibility);
diff --git a/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingManager.js b/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingManager.js index e5559cf..a8bf847 100644 --- a/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingManager.js +++ b/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingManager.js
@@ -66,18 +66,20 @@ } function optionSelected() { - if (selectElement.selectedIndex === selectElement.options.length - 1) + if (selectElement.selectedIndex === selectElement.options.length - 1) { selector.revealAndUpdate(); - else + } else { selector.optionSelected(options[selectElement.selectedIndex]); + } } /** * @param {number} index */ function select(index) { - if (selectElement.selectedIndex !== index) + if (selectElement.selectedIndex !== index) { selectElement.selectedIndex = index; + } } } @@ -95,10 +97,11 @@ * @this {!MobileThrottling.ThrottlingManager} */ function forceOffline() { - if (checkbox.checked()) + if (checkbox.checked()) { SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); - else + } else { SDK.multitargetNetworkManager.setNetworkConditions(this._lastNetworkThrottlingConditions); + } } function networkConditionsChanged() { @@ -131,11 +134,13 @@ function appendItems(contextMenu) { for (let index = 0; index < options.length; ++index) { const conditions = options[index]; - if (!conditions) + if (!conditions) { continue; + } if (conditions.title === MobileThrottling.CustomConditions.title && - conditions.description === MobileThrottling.CustomConditions.description) + conditions.description === MobileThrottling.CustomConditions.description) { continue; + } contextMenu.defaultSection().appendCheckboxItem( Common.UIString(conditions.title), selector.optionSelected.bind(selector, /** @type {!MobileThrottling.Conditions} */ (conditions)), @@ -150,8 +155,9 @@ function populate(groups) { options = []; for (const group of groups) { - for (const conditions of group.items) + for (const conditions of group.items) { options.push(conditions); + } options.push(null); } return options; @@ -179,8 +185,9 @@ */ setCPUThrottlingRate(rate) { this._cpuThrottlingRate = rate; - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate); + } let icon = null; if (this._cpuThrottlingRate !== MobileThrottling.CPUThrottlingRates.NoThrottling) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled); @@ -188,8 +195,9 @@ icon.title = Common.UIString('CPU throttling is enabled'); } const index = this._cpuThrottlingRates.indexOf(this._cpuThrottlingRate); - for (const control of this._cpuThrottlingControls) + for (const control of this._cpuThrottlingControls) { control.setSelectedIndex(index); + } UI.inspectorView.setPanelIcon('timeline', icon); this.dispatchEventToListeners(MobileThrottling.ThrottlingManager.Events.RateChanged, this._cpuThrottlingRate); } @@ -199,8 +207,9 @@ * @param {!SDK.EmulationModel} emulationModel */ modelAdded(emulationModel) { - if (this._cpuThrottlingRate !== MobileThrottling.CPUThrottlingRates.NoThrottling) + if (this._cpuThrottlingRate !== MobileThrottling.CPUThrottlingRates.NoThrottling) { emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate); + } } /** @@ -224,8 +233,9 @@ const title = rate === 1 ? Common.UIString('No throttling') : Common.UIString('%d\xD7 slowdown', rate); const option = control.createOption(title); control.addOption(option); - if (currentRate === rate) + if (currentRate === rate) { control.setSelectedIndex(i); + } } return control; }
diff --git a/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js b/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js index 4c61600..ef1cc0f 100644 --- a/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js
@@ -41,8 +41,9 @@ this._list.clear(); const conditions = this._customSetting.get(); - for (let i = 0; i < conditions.length; ++i) + for (let i = 0; i < conditions.length; ++i) { this._list.appendItem(conditions[i], true); + } this._list.appendSeparator(); } @@ -102,8 +103,9 @@ conditions.latency = latency ? parseInt(latency, 10) : 0; const list = this._customSetting.get(); - if (isNew) + if (isNew) { list.push(conditions); + } this._customSetting.set(list); } @@ -126,8 +128,9 @@ * @return {!UI.ListWidget.Editor} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -208,13 +211,16 @@ * @return {string} */ MobileThrottling.throughputText = function(throughput, plainText) { - if (throughput < 0) + if (throughput < 0) { return ''; + } const throughputInKbps = throughput / (1024 / 8); const delimiter = plainText ? '' : ' '; - if (throughputInKbps < 1024) + if (throughputInKbps < 1024) { return Common.UIString('%d%skb/s', throughputInKbps, delimiter); - if (throughputInKbps < 1024 * 10) + } + if (throughputInKbps < 1024 * 10) { return Common.UIString('%.1f%sMb/s', throughputInKbps / 1024, delimiter); + } return Common.UIString('%d%sMb/s', (throughputInKbps / 1024) | 0, delimiter); };
diff --git a/third_party/blink/renderer/devtools/front_end/network/BinaryResourceView.js b/third_party/blink/renderer/devtools/front_end/network/BinaryResourceView.js index cfb20db..80ae440 100644 --- a/third_party/blink/renderer/devtools/front_end/network/BinaryResourceView.js +++ b/third_party/blink/renderer/devtools/front_end/network/BinaryResourceView.js
@@ -98,21 +98,25 @@ * @override */ wasShown() { - if (!this._empty) + if (!this._empty) { this._updateView(); + } } _updateView() { const newViewObject = this._getCurrentViewObject(); - if (!newViewObject) + if (!newViewObject) { return; + } const newView = newViewObject.getView(); - if (newView === this._lastView) + if (newView === this._lastView) { return; + } - if (this._lastView) + if (this._lastView) { this._lastView.detach(); + } this._lastView = newView; newView.show(this.element, this._toolbar.element); @@ -121,8 +125,9 @@ _binaryViewTypeChanged() { const newViewType = this._binaryViewTypeCombobox.selectedOption().value; - if (this._binaryViewTypeSetting.get() === newViewType) + if (this._binaryViewTypeSetting.get() === newViewType) { return; + } this._binaryViewTypeSetting.set(newViewType); this._updateView(); } @@ -132,8 +137,9 @@ * @param {string} submenuItemText */ addCopyToContextMenu(contextMenu, submenuItemText) { - if (this._empty) + if (this._empty) { return; + } const copyMenu = contextMenu.clipboardSection().appendSubMenuItem(submenuItemText); const footerSection = copyMenu.footerSection(); @@ -169,8 +175,9 @@ * @return {!UI.Widget} */ getView() { - if (!this._view) + if (!this._view) { this._view = this._createViewFn(); + } return this._view; } };
diff --git a/third_party/blink/renderer/devtools/front_end/network/BlockedURLsPane.js b/third_party/blink/renderer/devtools/front_end/network/BlockedURLsPane.js index 2ec93c9..587568e4 100644 --- a/third_party/blink/renderer/devtools/front_end/network/BlockedURLsPane.js +++ b/third_party/blink/renderer/devtools/front_end/network/BlockedURLsPane.js
@@ -57,8 +57,9 @@ } static reset() { - if (Network.BlockedURLsPane._instance) + if (Network.BlockedURLsPane._instance) { Network.BlockedURLsPane._instance.reset(); + } } _addButtonClicked() { @@ -133,10 +134,11 @@ commitEdit(item, editor, isNew) { const url = editor.control('url').value; const patterns = this._manager.blockedPatterns(); - if (isNew) + if (isNew) { patterns.push({enabled: true, url: url}); - else + } else { patterns.splice(patterns.indexOf(item), 1, {enabled: true, url: url}); + } this._manager.setBlockedPatterns(patterns); } @@ -145,8 +147,9 @@ * @return {!UI.ListWidget.Editor<!SDK.NetworkManager.BlockedPattern>} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); const content = editor.contentElement(); @@ -175,8 +178,9 @@ this._list.element.classList.toggle('blocking-disabled', !enabled && !!this._manager.blockedPatterns().length); this._enabledCheckbox.setChecked(enabled); this._list.clear(); - for (const pattern of this._manager.blockedPatterns()) + for (const pattern of this._manager.blockedPatterns()) { this._list.appendItem(pattern, true); + } return Promise.resolve(); } @@ -185,13 +189,15 @@ * @return {number} */ _blockedRequestsCount(url) { - if (!url) + if (!url) { return 0; + } let result = 0; for (const blockedUrl of this._blockedCountForUrl.keys()) { - if (this._matches(url, blockedUrl)) + if (this._matches(url, blockedUrl)) { result += this._blockedCountForUrl.get(blockedUrl); + } } return result; } @@ -206,11 +212,13 @@ const parts = pattern.split('*'); for (let index = 0; index < parts.length; index++) { const part = parts[index]; - if (!part.length) + if (!part.length) { continue; + } pos = url.indexOf(part, pos); - if (pos === -1) + if (pos === -1) { return false; + } pos += part.length; } return true;
diff --git a/third_party/blink/renderer/devtools/front_end/network/EventSourceMessagesView.js b/third_party/blink/renderer/devtools/front_end/network/EventSourceMessagesView.js index 626519b..3555418 100644 --- a/third_party/blink/renderer/devtools/front_end/network/EventSourceMessagesView.js +++ b/third_party/blink/renderer/devtools/front_end/network/EventSourceMessagesView.js
@@ -38,8 +38,9 @@ wasShown() { this._dataGrid.rootNode().removeChildren(); const messages = this._request.eventSourceMessages(); - for (let i = 0; i < messages.length; ++i) + for (let i = 0; i < messages.length; ++i) { this._dataGrid.insertChild(new Network.EventSourceMessageNode(messages[i])); + } this._request.addEventListener(SDK.NetworkRequest.Events.EventSourceMessageAdded, this._messageAdded, this); } @@ -61,11 +62,13 @@ _sortItems() { const sortColumnId = this._dataGrid.sortColumnId(); - if (!sortColumnId) + if (!sortColumnId) { return; + } const comparator = Network.EventSourceMessageNode.Comparators[sortColumnId]; - if (!comparator) + if (!comparator) { return; + } this._dataGrid.sortNodes(comparator, !this._dataGrid.isSortOrderAscending()); } };
diff --git a/third_party/blink/renderer/devtools/front_end/network/HARWriter.js b/third_party/blink/renderer/devtools/front_end/network/HARWriter.js index b7f20e8..a932827 100644 --- a/third_party/blink/renderer/devtools/front_end/network/HARWriter.js +++ b/third_party/blink/renderer/devtools/front_end/network/HARWriter.js
@@ -39,8 +39,9 @@ const compositeProgress = new Common.CompositeProgress(progress); const content = await Network.HARWriter._harStringForRequests(requests, compositeProgress); - if (progress.isCanceled()) + if (progress.isCanceled()) { return Promise.resolve(); + } return Network.HARWriter._writeToStream(stream, compositeProgress, content); } @@ -64,8 +65,9 @@ await Promise.all(promises); progress.done(); - if (progress.isCanceled()) + if (progress.isCanceled()) { return ''; + } return JSON.stringify({log: harLog}, null, Network.HARWriter._jsonIndent); function isValidCharacter(code_point) { @@ -77,8 +79,9 @@ function needsEncoding(content) { for (let i = 0; i < content.length; i++) { - if (!isValidCharacter(content.charCodeAt(i))) + if (!isValidCharacter(content.charCodeAt(i))) { return true; + } } return false; } @@ -98,8 +101,9 @@ } entry.response.content.text = content; } - if (encoded) + if (encoded) { entry.response.content.encoding = 'base64'; + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkConfigView.js b/third_party/blink/renderer/devtools/front_end/network/NetworkConfigView.js index 2fe4ecd..dc02670 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkConfigView.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkConfigView.js
@@ -73,8 +73,9 @@ } } - if (!selectionRestored) + if (!selectionRestored) { userAgentSelectElement.selectedIndex = 0; + } } function applyOtherUserAgent() { @@ -95,8 +96,9 @@ */ _createSection(title, className) { const section = this.contentElement.createChild('section', 'network-config-group'); - if (className) + if (className) { section.classList.add(className); + } section.createChild('div', 'network-config-title').textContent = title; return section.createChild('div', 'network-config-fields'); } @@ -125,8 +127,9 @@ const customUserAgentSetting = Common.settings.createSetting('customUserAgent', ''); customUserAgentSetting.addChangeListener(() => { - if (autoCheckbox.checked) + if (autoCheckbox.checked) { return; + } SDK.multitargetNetworkManager.setCustomUserAgentOverride(customUserAgentSetting.get()); }); const customUserAgentSelectBox = section.createChild('div', 'network-config-ua-custom');
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkDataGridNode.js b/third_party/blink/renderer/devtools/front_end/network/NetworkDataGridNode.js index 37c9cf9..c6143af 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkDataGridNode.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkDataGridNode.js
@@ -49,8 +49,9 @@ * @return {!Network.NetworkNode._SupportedBackgroundColors} */ static _themedBackgroundColors() { - if (Network.NetworkNode._themedBackgroundColorsCache) + if (Network.NetworkNode._themedBackgroundColorsCache) { return Network.NetworkNode._themedBackgroundColorsCache; + } const themedColors = {}; for (const name in Network.NetworkNode._backgroundColors) { const color = Common.Color.fromRGBA(Network.NetworkNode._backgroundColors[name]); @@ -92,25 +93,31 @@ */ backgroundColor() { const bgColors = Network.NetworkNode._themedBackgroundColors(); - if (this.selected) + if (this.selected) { return /** @type {string} */ (bgColors.Selected.asString(Common.Color.Format.HEX)); + } let color = this.isStriped() ? bgColors.Stripe : bgColors.Default; - if (this.isNavigationRequest()) + if (this.isNavigationRequest()) { color = color.blendWith(bgColors.Navigation); - if (this.hovered()) + } + if (this.hovered()) { color = color.blendWith(bgColors.Hovered); - if (this.isOnInitiatorPath()) + } + if (this.isOnInitiatorPath()) { color = color.blendWith(bgColors.InitiatorPath); - if (this.isOnInitiatedPath()) + } + if (this.isOnInitiatedPath()) { color = color.blendWith(bgColors.InitiatedPath); + } return /** @type {string} */ (color.asString(Common.Color.Format.HEX)); } _updateBackgroundColor() { const element = this.existingElement(); - if (!element) + if (!element) { return; + } element.style.backgroundColor = this.backgroundColor(); this._parentView.stylesChanged(); } @@ -158,12 +165,14 @@ * @param {boolean} showInitiatorChain */ setHovered(hovered, showInitiatorChain) { - if (this._isHovered === hovered && this._showingInitiatorChain === showInitiatorChain) + if (this._isHovered === hovered && this._showingInitiatorChain === showInitiatorChain) { return; + } if (this._isHovered !== hovered) { this._isHovered = hovered; - if (this.attached()) + if (this.attached()) { this.element().classList.toggle('hover', hovered); + } } if (this._showingInitiatorChain !== showInitiatorChain) { this._showingInitiatorChain = showInitiatorChain; @@ -220,8 +229,9 @@ * @return {?SDK.NetworkRequest} */ requestOrFirstKnownChildRequest() { - if (this._requestOrFirstKnownChildRequest) + if (this._requestOrFirstKnownChildRequest) { return this._requestOrFirstKnownChildRequest; + } let request = this.request(); if (request || !this.hasChildren()) { this._requestOrFirstKnownChildRequest = request; @@ -232,8 +242,9 @@ const flatChildren = this.flatChildren(); for (let i = 0; i < flatChildren.length; i++) { request = flatChildren[i].request(); - if (!firstChildRequest || (request && request.issueTime() < firstChildRequest.issueTime())) + if (!firstChildRequest || (request && request.issueTime() < firstChildRequest.issueTime())) { firstChildRequest = request; + } } this._requestOrFirstKnownChildRequest = firstChildRequest; return this._requestOrFirstKnownChildRequest; @@ -307,8 +318,9 @@ if (aName === bName) { const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (aRequest && bRequest) + if (aRequest && bRequest) { return aRequest.indentityCompare(bRequest); + } return aRequest ? -1 : 1; } return aName < bName ? -1 : 1; @@ -323,14 +335,17 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aRemoteAddress = aRequest.remoteAddress(); const bRemoteAddress = bRequest.remoteAddress(); - if (aRemoteAddress > bRemoteAddress) + if (aRemoteAddress > bRemoteAddress) { return 1; - if (bRemoteAddress > aRemoteAddress) + } + if (bRemoteAddress > aRemoteAddress) { return -1; + } return aRequest.indentityCompare(bRequest); } @@ -343,8 +358,9 @@ static ProductComparator(productRegistry, a, b) { const aRequest = a.request(); const bRequest = b.request(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aName = productRegistry.nameForUrl(aRequest.parsedURL) || ''; const bName = productRegistry.nameForUrl(bRequest.parsedURL) || ''; return aName.localeCompare(bName) || aRequest.indentityCompare(bRequest); @@ -359,12 +375,15 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; - if (bRequest.cached() && !aRequest.cached()) + } + if (bRequest.cached() && !aRequest.cached()) { return 1; - if (aRequest.cached() && !bRequest.cached()) + } + if (aRequest.cached() && !bRequest.cached()) { return -1; + } return (aRequest.transferSize - bRequest.transferSize) || (aRequest.resourceSize - bRequest.resourceSize) || aRequest.indentityCompare(bRequest); } @@ -378,15 +397,18 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aSimpleType = a.displayType(); const bSimpleType = b.displayType(); - if (aSimpleType > bSimpleType) + if (aSimpleType > bSimpleType) { return 1; - if (bSimpleType > aSimpleType) + } + if (bSimpleType > aSimpleType) { return -1; + } return aRequest.indentityCompare(bRequest); } @@ -399,10 +421,12 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; - if (!a._initiatorCell || !b._initiatorCell) + } + if (!a._initiatorCell || !b._initiatorCell) { return !a._initiatorCell ? -1 : 1; + } const aText = a._linkifiedInitiatorAnchor ? a._linkifiedInitiatorAnchor.textContent : a._initiatorCell.title; const bText = b._linkifiedInitiatorAnchor ? b._linkifiedInitiatorAnchor.textContent : b._initiatorCell.title; return aText.localeCompare(bText); @@ -417,8 +441,9 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aScore = aRequest.requestCookies ? aRequest.requestCookies.length : 0; const bScore = bRequest.requestCookies ? bRequest.requestCookies.length : 0; return (aScore - bScore) || aRequest.indentityCompare(bRequest); @@ -434,8 +459,9 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aScore = aRequest.responseCookies ? aRequest.responseCookies.length : 0; const bScore = bRequest.responseCookies ? bRequest.responseCookies.length : 0; return (aScore - bScore) || aRequest.indentityCompare(bRequest); @@ -450,8 +476,9 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aPriority = aRequest.priority(); let aScore = aPriority ? PerfUI.networkPriorityWeight(aPriority) : 0; aScore = aScore || 0; @@ -471,12 +498,14 @@ static RequestPropertyComparator(propertyName, a, b) { const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aValue = aRequest[propertyName]; const bValue = bRequest[propertyName]; - if (aValue === bValue) + if (aValue === bValue) { return aRequest.indentityCompare(bRequest); + } return aValue > bValue ? 1 : -1; } @@ -490,8 +519,9 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aValue = String(aRequest.responseHeaderValue(propertyName) || ''); const bValue = String(bRequest.responseHeaderValue(propertyName) || ''); return aValue.localeCompare(bValue) || aRequest.indentityCompare(bRequest); @@ -507,16 +537,18 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aValue = (aRequest.responseHeaderValue(propertyName) !== undefined) ? parseFloat(aRequest.responseHeaderValue(propertyName)) : -Infinity; const bValue = (bRequest.responseHeaderValue(propertyName) !== undefined) ? parseFloat(bRequest.responseHeaderValue(propertyName)) : -Infinity; - if (aValue === bValue) + if (aValue === bValue) { return aRequest.indentityCompare(bRequest); + } return aValue > bValue ? 1 : -1; } @@ -530,14 +562,16 @@ // TODO(allada) Handle this properly for group nodes. const aRequest = a.requestOrFirstKnownChildRequest(); const bRequest = b.requestOrFirstKnownChildRequest(); - if (!aRequest || !bRequest) + if (!aRequest || !bRequest) { return !aRequest ? -1 : 1; + } const aHeader = aRequest.responseHeaderValue(propertyName); const bHeader = bRequest.responseHeaderValue(propertyName); const aValue = aHeader ? new Date(aHeader).getTime() : -Infinity; const bValue = bHeader ? new Date(bHeader).getTime() : -Infinity; - if (aValue === bValue) + if (aValue === bValue) { return aRequest.indentityCompare(bRequest); + } return aValue > bValue ? 1 : -1; } @@ -549,19 +583,23 @@ const initiatorGraph = SDK.networkLog.initiatorGraphForRequest(this._request); for (const request of initiatorGraph.initiators) { - if (request === this._request) + if (request === this._request) { continue; + } const node = this.parentView().nodeForRequest(request); - if (!node) + if (!node) { continue; + } node._setIsOnInitiatorPath(showInitiatorChain); } for (const request of initiatorGraph.initiated) { - if (request === this._request) + if (request === this._request) { continue; + } const node = this.parentView().nodeForRequest(request); - if (!node) + if (!node) { continue; + } node._setIsOnInitiatedPath(showInitiatorChain); } } @@ -570,8 +608,9 @@ * @param {boolean} isOnInitiatorPath */ _setIsOnInitiatorPath(isOnInitiatorPath) { - if (this._isOnInitiatorPath === isOnInitiatorPath || !this.attached()) + if (this._isOnInitiatorPath === isOnInitiatorPath || !this.attached()) { return; + } this._isOnInitiatorPath = isOnInitiatorPath; this._updateBackgroundColor(); } @@ -588,8 +627,9 @@ * @param {boolean} isOnInitiatedPath */ _setIsOnInitiatedPath(isOnInitiatedPath) { - if (this._isOnInitiatedPath === isOnInitiatedPath || !this.attached()) + if (this._isOnInitiatedPath === isOnInitiatedPath || !this.attached()) { return; + } this._isOnInitiatedPath = isOnInitiatedPath; this._updateBackgroundColor(); } @@ -610,8 +650,9 @@ const resourceType = this._request.resourceType(); let simpleType = resourceType.name(); - if (resourceType === Common.resourceTypes.Other || resourceType === Common.resourceTypes.Image) + if (resourceType === Common.resourceTypes.Other || resourceType === Common.resourceTypes.Image) { simpleType = mimeType.replace(/^(application|image)\//, ''); + } return simpleType; } @@ -762,14 +803,16 @@ * @return {!Array.<!Object>} */ highlightMatchedSubstring(regexp) { - if (!regexp) + if (!regexp) { return []; + } // Ensure element is created. this.element(); const domChanges = []; const matchInfo = this._nameCell.textContent.match(regexp); - if (matchInfo) + if (matchInfo) { UI.highlightSearchResult(this._nameCell, matchInfo.index, matchInfo[0].length, domChanges); + } return domChanges; } @@ -889,8 +932,9 @@ const initiator = SDK.networkLog.initiatorInfoForRequest(request); const timing = request.timing; - if (timing && timing.pushStart) + if (timing && timing.pushStart) { cell.appendChild(createTextNode(Common.UIString('Push / '))); + } switch (initiator.type) { case SDK.NetworkRequest.InitiatorType.Parser: cell.title = initiator.url + ':' + (initiator.lineNumber + 1);
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkFrameGrouper.js b/third_party/blink/renderer/devtools/front_end/network/NetworkFrameGrouper.js index 0e39df6..8fd5132 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkFrameGrouper.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkFrameGrouper.js
@@ -22,11 +22,13 @@ */ groupNodeForRequest(request) { const frame = SDK.ResourceTreeModel.frameForRequest(request); - if (!frame || frame.isTopFrame()) + if (!frame || frame.isTopFrame()) { return null; + } let groupNode = this._activeGroups.get(frame); - if (groupNode) + if (groupNode) { return groupNode; + } groupNode = new Network.FrameGroupNode(this._parentView, frame); this._activeGroups.set(frame, groupNode); return groupNode;
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js b/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js index d2bf0da..e42eaade 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkItemView.js
@@ -119,16 +119,19 @@ * @param {string=} tabId */ _selectTab(tabId) { - if (!tabId) + if (!tabId) { tabId = this._resourceViewTabSetting.get(); + } - if (!this.selectTab(tabId)) + if (!this.selectTab(tabId)) { this.selectTab('headers'); + } } _tabSelected(event) { - if (!event.data.isUserGesture) + if (!event.data.isUserGesture) { return; + } this._resourceViewTabSetting.set(event.data.tabId); } @@ -145,8 +148,9 @@ */ async revealResponseBody(line) { this._selectTab(Network.NetworkItemView.Tabs.Response); - if (this._responseView && typeof line === 'number') + if (this._responseView && typeof line === 'number') { await this._responseView.revealLine(/** @type {number} */ (line)); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js b/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js index 1470d0a..8aa0b86a 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkLogView.js
@@ -194,8 +194,9 @@ * @return {boolean} */ static _requestPathFilter(regex, request) { - if (!regex) + if (!regex) { return false; + } return regex.test(request.path() + '/' + request.name()); } @@ -313,14 +314,15 @@ * @return {boolean} */ static _requestMixedContentFilter(value, request) { - if (value === Network.NetworkLogView.MixedContentFilterValues.Displayed) + if (value === Network.NetworkLogView.MixedContentFilterValues.Displayed) { return request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable; - else if (value === Network.NetworkLogView.MixedContentFilterValues.Blocked) + } else if (value === Network.NetworkLogView.MixedContentFilterValues.Blocked) { return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && request.wasBlocked(); - else if (value === Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) + } else if (value === Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) { return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && !request.wasBlocked(); - else if (value === Network.NetworkLogView.MixedContentFilterValues.All) + } else if (value === Network.NetworkLogView.MixedContentFilterValues.All) { return request.mixedContentType !== Protocol.Security.MixedContentType.None; + } return false; } @@ -342,8 +344,9 @@ static _requestSetCookieDomainFilter(value, request) { const cookies = request.responseCookies; for (let i = 0, l = cookies ? cookies.length : 0; i < l; ++i) { - if (cookies[i].domain() === value) + if (cookies[i].domain() === value) { return true; + } } return false; } @@ -356,8 +359,9 @@ static _requestSetCookieNameFilter(value, request) { const cookies = request.responseCookies; for (let i = 0, l = cookies ? cookies.length : 0; i < l; ++i) { - if (cookies[i].name() === value) + if (cookies[i].name() === value) { return true; + } } return false; } @@ -370,8 +374,9 @@ static _requestSetCookieValueFilter(value, request) { const cookies = request.responseCookies; for (let i = 0, l = cookies ? cookies.length : 0; i < l; ++i) { - if (cookies[i].value() === value) + if (cookies[i].value() === value) { return true; + } } return false; } @@ -409,10 +414,12 @@ * @return {boolean} */ static _requestTimeFilter(windowStart, windowEnd, request) { - if (request.issueTime() > windowEnd) + if (request.issueTime() > windowEnd) { return false; - if (request.endTime !== -1 && request.endTime < windowStart) + } + if (request.endTime !== -1 && request.endTime < windowStart) { return false; + } return true; } @@ -436,10 +443,11 @@ static async _copyResponse(request) { const contentData = await request.contentData(); let content = contentData.content || ''; - if (!request.contentType().isTextType()) + if (!request.contentType().isTextType()) { content = Common.ContentProvider.contentAsDataURL(content, request.mimeType, contentData.encoded); - else if (contentData.encoded) + } else if (contentData.encoded) { content = window.atob(content); + } InspectorFrontendHost.copyText(content); } @@ -448,11 +456,13 @@ */ _handleDrop(dataTransfer) { const items = dataTransfer.items; - if (!items.length) + if (!items.length) { return; + } const entry = items[0].webkitGetAsEntry(); - if (entry.isDirectory) + if (entry.isDirectory) { return; + } entry.file(this.onLoadFromFile.bind(this)); } @@ -490,8 +500,9 @@ * @param {?string} groupKey */ _setGrouping(groupKey) { - if (this._activeGroupLookup) + if (this._activeGroupLookup) { this._activeGroupLookup.reset(); + } const groupLookup = groupKey ? this._groupLookups.get(groupKey) || null : null; this._activeGroupLookup = groupLookup; this._invalidateAllItems(); @@ -533,8 +544,9 @@ */ modelAdded(networkManager) { // TODO(allada) Remove dependency on networkManager and instead use NetworkLog and PageLoad for needed data. - if (networkManager.target().parentTarget()) + if (networkManager.target().parentTarget()) { return; + } const resourceTreeModel = networkManager.target().model(SDK.ResourceTreeModel); if (resourceTreeModel) { resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, this._loadEventFired, this); @@ -574,8 +586,9 @@ } clearSelection() { - if (this._dataGrid.selectedNode) + if (this._dataGrid.selectedNode) { this._dataGrid.selectedNode.deselect(); + } } _resetSuggestionBuilder() { @@ -639,8 +652,9 @@ } _hideRecordingHint() { - if (this._recordingHint) + if (this._recordingHint) { this._recordingHint.remove(); + } this._recordingHint = null; } @@ -650,7 +664,9 @@ */ elementsToRestoreScrollPositionsFor() { if (!this._dataGrid) // Not initialized yet. + { return []; + } return [this._dataGrid.scrollContainer]; } @@ -661,8 +677,9 @@ _setupDataGrid() { this._dataGrid.setRowContextMenuCallback((contextMenu, node) => { const request = node.request(); - if (request) + if (request) { this.handleContextMenuForRequest(contextMenu, request); + } }); this._dataGrid.setStickToBottom(true); this._dataGrid.setName('networkLog'); @@ -695,19 +712,22 @@ * @param {boolean=} highlightInitiatorChain */ _setHoveredNode(node, highlightInitiatorChain) { - if (this._hoveredNode) + if (this._hoveredNode) { this._hoveredNode.setHovered(false, false); + } this._hoveredNode = node; - if (this._hoveredNode) + if (this._hoveredNode) { this._hoveredNode.setHovered(true, !!highlightInitiatorChain); + } } /** * @param {!Event} event */ _dataGridMouseDown(event) { - if (!this._dataGrid.selectedNode && event.button) + if (!this._dataGrid.selectedNode && event.button) { event.consume(); + } } _updateSummaryBar() { @@ -724,8 +744,9 @@ let nodeCount = 0; for (const request of SDK.networkLog.requests()) { const node = request[Network.NetworkLogView._networkNodeSymbol]; - if (!node) + if (!node) { continue; + } nodeCount++; const requestTransferSize = request.transferSize; transferSize += requestTransferSize; @@ -740,10 +761,12 @@ // TODO(allada) inspectedURL should be stored in PageLoad used instead of target so HAR requests can have an // inspected url. if (networkManager && request.url() === networkManager.target().inspectedURL() && - request.resourceType() === Common.resourceTypes.Document && !networkManager.target().parentTarget()) + request.resourceType() === Common.resourceTypes.Document && !networkManager.target().parentTarget()) { baseTime = request.startTime; - if (request.endTime > maxTime) + } + if (request.endTime > maxTime) { maxTime = request.endTime; + } } if (!nodeCount) { @@ -800,13 +823,15 @@ } scheduleRefresh() { - if (this._needsRefresh) + if (this._needsRefresh) { return; + } this._needsRefresh = true; - if (this.isShowing() && !this._refreshRequestId) + if (this.isShowing() && !this._refreshRequestId) { this._refreshRequestId = this.element.window().requestAnimationFrame(this._refresh.bind(this)); + } } /** @@ -828,8 +853,9 @@ } _refreshIfNeeded() { - if (this._needsRefresh) + if (this._needsRefresh) { this._refresh(); + } } /** @@ -837,10 +863,11 @@ */ _invalidateAllItems(deferUpdate) { this._staleRequests = new Set(SDK.networkLog.requests()); - if (deferUpdate) + if (deferUpdate) { this.scheduleRefresh(); - else + } else { this._refresh(); + } } /** @@ -861,8 +888,9 @@ * @param {!Network.NetworkTimeCalculator} x */ setCalculator(x) { - if (!x || this._calculator === x) + if (!x || this._calculator === x) { return; + } if (this._calculator !== x) { this._calculator = x; @@ -870,10 +898,11 @@ } this._calculator.reset(); - if (this._calculator.startAtZero) + if (this._calculator.startAtZero) { this._columns.hideEventDividers(); - else + } else { this._columns.showEventDividers(); + } this._invalidateAllItems(); } @@ -882,8 +911,9 @@ * @param {!Common.Event} event */ _loadEventFired(event) { - if (!this._recording) + if (!this._recording) { return; + } const time = /** @type {number} */ (event.data.loadTime); if (time) { @@ -896,8 +926,9 @@ * @param {!Common.Event} event */ _domContentLoadedEventFired(event) { - if (!this._recording) + if (!this._recording) { return; + } const data = /** @type {number} */ (event.data); if (data) { this._mainRequestDOMContentLoadedTime = data; @@ -967,24 +998,28 @@ const request = this._staleRequests.firstValue(); this._staleRequests.delete(request); let node = request[Network.NetworkLogView._networkNodeSymbol]; - if (!node) + if (!node) { node = this._createNodeForRequest(request); + } staleNodes.add(node); } for (const node of staleNodes) { const isFilteredOut = !this._applyFilter(node); - if (isFilteredOut && node === this._hoveredNode) + if (isFilteredOut && node === this._hoveredNode) { this._setHoveredNode(null); + } - if (!isFilteredOut) + if (!isFilteredOut) { nodesToRefresh.push(node); + } const request = node.request(); this._timeCalculator.updateBoundaries(request); this._durationCalculator.updateBoundaries(request); const newParent = this._parentNodeForInsert(node); - if (node[Network.NetworkLogView._isFilteredOutSymbol] === isFilteredOut && node.parent === newParent) + if (node[Network.NetworkLogView._isFilteredOutSymbol] === isFilteredOut && node.parent === newParent) { continue; + } node[Network.NetworkLogView._isFilteredOutSymbol] = isFilteredOut; const removeFromParent = node.parent && (isFilteredOut || node.parent !== newParent); if (removeFromParent) { @@ -997,8 +1032,9 @@ } } - if (!newParent || isFilteredOut) + if (!newParent || isFilteredOut) { continue; + } if (!newParent.dataGrid && !nodesToInsert.has(newParent)) { nodesToInsert.set(newParent, this._dataGrid.rootNode()); @@ -1007,16 +1043,19 @@ nodesToInsert.set(node, newParent); } - for (const node of nodesToInsert.keys()) + for (const node of nodesToInsert.keys()) { nodesToInsert.get(node).appendChild(node); + } - for (const node of nodesToRefresh) + for (const node of nodesToRefresh) { node.refresh(); + } this._updateSummaryBar(); - if (nodesToInsert.size) + if (nodesToInsert.size) { this._columns.sortByCurrentColumn(); + } this._dataGrid.updateInstantly(); this._didRefreshForTest(); @@ -1030,12 +1069,14 @@ * @return {?Network.NetworkNode} */ _parentNodeForInsert(node) { - if (!this._activeGroupLookup) + if (!this._activeGroupLookup) { return this._dataGrid.rootNode(); + } const groupNode = this._activeGroupLookup.groupNodeForRequest(node.request()); - if (!groupNode) + if (!groupNode) { return this._dataGrid.rootNode(); + } return groupNode; } @@ -1052,8 +1093,9 @@ this.linkifier.reset(); this.badgePool.reset(); - if (this._activeGroupLookup) + if (this._activeGroupLookup) { this._activeGroupLookup.reset(); + } this._staleRequests.clear(); this._resetSuggestionBuilder(); @@ -1083,8 +1125,9 @@ request[Network.NetworkLogView._networkNodeSymbol] = node; node[Network.NetworkLogView._isFilteredOutSymbol] = true; - for (let redirect = request.redirectSource(); redirect; redirect = redirect.redirectSource()) + for (let redirect = request.redirectSource(); redirect; redirect = redirect.redirectSource()) { this._refreshRequest(redirect); + } return node; } @@ -1131,8 +1174,9 @@ } const responseHeaders = request.responseHeaders; - for (let i = 0, l = responseHeaders.length; i < l; ++i) + for (let i = 0, l = responseHeaders.length; i < l; ++i) { this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.HasResponseHeader, responseHeaders[i].name); + } const cookies = request.responseCookies; for (let i = 0, l = cookies ? cookies.length : 0; i < l; ++i) { const cookie = cookies[i]; @@ -1332,8 +1376,9 @@ const filename = parsedURL ? parsedURL.host : 'network-log'; const stream = new Bindings.FileOutputStream(); - if (!await stream.open(filename + '.har')) + if (!await stream.open(filename + '.har')) { return; + } const progressIndicator = new UI.ProgressIndicator(); this._progressBarContainer.appendChild(progressIndicator.element); @@ -1343,19 +1388,22 @@ } _clearBrowserCache() { - if (confirm(Common.UIString('Are you sure you want to clear browser cache?'))) + if (confirm(Common.UIString('Are you sure you want to clear browser cache?'))) { SDK.multitargetNetworkManager.clearBrowserCache(); + } } _clearBrowserCookies() { - if (confirm(Common.UIString('Are you sure you want to clear browser cookies?'))) + if (confirm(Common.UIString('Are you sure you want to clear browser cookies?'))) { SDK.multitargetNetworkManager.clearBrowserCookies(); + } } _removeAllHighlights() { this.removeAllNodeHighlights(); - for (let i = 0; i < this._highlightedSubstringChanges.length; ++i) + for (let i = 0; i < this._highlightedSubstringChanges.length; ++i) { UI.revertDomChanges(this._highlightedSubstringChanges[i]); + } this._highlightedSubstringChanges = []; } @@ -1365,18 +1413,23 @@ */ _applyFilter(node) { const request = node.request(); - if (this._timeFilter && !this._timeFilter(request)) + if (this._timeFilter && !this._timeFilter(request)) { return false; + } const categoryName = request.resourceType().category().title; - if (!this._resourceCategoryFilterUI.accept(categoryName)) + if (!this._resourceCategoryFilterUI.accept(categoryName)) { return false; - if (this._dataURLFilterUI.checked() && (request.parsedURL.isDataURL() || request.parsedURL.isBlobURL())) + } + if (this._dataURLFilterUI.checked() && (request.parsedURL.isDataURL() || request.parsedURL.isBlobURL())) { return false; - if (request.statusText === 'Service Worker Fallback Required') + } + if (request.statusText === 'Service Worker Fallback Required') { return false; + } for (let i = 0; i < this._filters.length; ++i) { - if (!this._filters[i](request)) + if (!this._filters[i](request)) { return false; + } } return true; } @@ -1418,14 +1471,18 @@ return Network.NetworkLogView._requestResponseHeaderFilter.bind(null, value); case Network.NetworkLogView.FilterType.Is: - if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.Running) + if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.Running) { return Network.NetworkLogView._runningRequestFilter; - if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.FromCache) + } + if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.FromCache) { return Network.NetworkLogView._fromCacheRequestFilter; - if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.ServiceWorkerIntercepted) + } + if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.ServiceWorkerIntercepted) { return Network.NetworkLogView._interceptedByServiceWorkerFilter; - if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.ServiceWorkerInitiated) + } + if (value.toLowerCase() === Network.NetworkLogView.IsFilterType.ServiceWorkerInitiated) { return Network.NetworkLogView._initiatedByServiceWorkerFilter; + } break; case Network.NetworkLogView.FilterType.LargerThan: @@ -1476,8 +1533,9 @@ value = value.substring(0, value.length - 1); } const quantity = Number(value); - if (isNaN(quantity)) + if (isNaN(quantity)) { return null; + } return Network.NetworkLogView._requestSizeLargerThanFilter.bind(null, quantity * multiplier); } @@ -1493,8 +1551,9 @@ _reveal(request) { this.removeAllNodeHighlights(); const node = request[Network.NetworkLogView._networkNodeSymbol]; - if (!node || !node.dataGrid) + if (!node || !node.dataGrid) { return null; + } node.reveal(); return node; } @@ -1504,8 +1563,9 @@ */ revealAndHighlightRequest(request) { const node = this._reveal(request); - if (node) + if (node) { this._highlightNode(node); + } } /** @@ -1514,8 +1574,9 @@ selectRequest(request) { this.setTextFilterValue(''); const node = this._reveal(request); - if (node) + if (node) { node.select(); + } } removeAllNodeHighlights() { @@ -1587,15 +1648,17 @@ const headerData = requestHeaders.reduce((result, header) => { const name = header.name; - if (!ignoredHeaders[name.toLowerCase()] && !name.includes(':')) + if (!ignoredHeaders[name.toLowerCase()] && !name.includes(':')) { result.append(name, header.value); + } return result; }, new Headers()); const headers = {}; - for (const headerArray of headerData) + for (const headerArray of headerData) { headers[headerArray[0]] = headerArray[1]; + } const credentials = request.requestCookies || requestHeaders.some(({name}) => credentialHeaders[name.toLowerCase()]) ? 'include' : @@ -1695,8 +1758,9 @@ let hexString = code.toString(16); // Zero pad to four digits to comply with ANSI-C Quoting: // http://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html - while (hexString.length < 4) + while (hexString.length < 4) { hexString = '0' + hexString; + } return '\\u' + hexString; } @@ -1747,16 +1811,18 @@ for (let i = 0; i < requestHeaders.length; i++) { const header = requestHeaders[i]; const name = header.name.replace(/^:/, ''); // Translate SPDY v3 headers to HTTP headers. - if (name.toLowerCase() in ignoredHeaders) + if (name.toLowerCase() in ignoredHeaders) { continue; + } command.push('-H'); command.push(escapeString(name + ': ' + header.value)); } command = command.concat(data); command.push('--compressed'); - if (request.securityState() === Protocol.Security.SecurityState.Insecure) + if (request.securityState() === Protocol.Security.SecurityState.Insecure) { command.push('--insecure'); + } return command.join(' '); } @@ -1768,10 +1834,11 @@ async _generateAllCurlCommand(requests, platform) { const nonBlobRequests = this._filterOutBlobRequests(requests); const commands = await Promise.all(nonBlobRequests.map(request => this._generateCurlCommand(request, platform))); - if (platform === 'win') + if (platform === 'win') { return commands.join(' &\r\n'); - else + } else { return commands.join(' ;\n'); + } } /** @@ -1804,8 +1871,9 @@ const headerNameValuePairs = []; for (const header of requestHeaders) { const name = header.name.replace(/^:/, ''); // Translate h2 headers to HTTP headers. - if (ignoredHeaders.has(name.toLowerCase())) + if (ignoredHeaders.has(name.toLowerCase())) { continue; + } headerNameValuePairs.push(escapeString(name) + '=' + escapeString(header.value)); } if (headerNameValuePairs.length) { @@ -1823,10 +1891,11 @@ if (formData) { command.push('-Body'); const body = escapeString(formData); - if (/[^\x20-\x7E]/.test(formData)) + if (/[^\x20-\x7E]/.test(formData)) { command.push('([System.Text.Encoding]::UTF8.GetBytes(' + body + '))'); - else + } else { command.push(body); + } } return command.join(' '); @@ -1846,8 +1915,9 @@ * @return {string} */ static getDCLEventColor() { - if (UI.themeSupport.themeName() === 'dark') + if (UI.themeSupport.themeName() === 'dark') { return '#03A9F4'; + } return '#0867CB'; }
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js b/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js index daefa7c..383ce86 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkLogViewColumns.js
@@ -70,8 +70,9 @@ } reset() { - if (this._popoverHelper) + if (this._popoverHelper) { this._popoverHelper.hidePopover(); + } this._eventDividers.clear(); } @@ -85,8 +86,9 @@ const columnConfig = /** @type {!Network.NetworkLogViewColumns.Descriptor} */ ( Object.assign({}, defaultColumnConfig, currentConfigColumn)); columnConfig.id = columnConfig.id; - if (columnConfig.subtitle) + if (columnConfig.subtitle) { columnConfig.titleDOMFragment = this._makeHeaderFragment(columnConfig.title, columnConfig.subtitle); + } this._columns.push(columnConfig); } this._loadCustomColumnsAndSettings(); @@ -99,8 +101,9 @@ this._dataGrid = new DataGrid.SortableDataGrid(this._columns.map(Network.NetworkLogViewColumns._convertToDataGridDescriptor)); this._dataGrid.element.addEventListener('mousedown', event => { - if (!this._dataGrid.selectedNode && event.button) + if (!this._dataGrid.selectedNode && event.button) { event.consume(); + } }, true); this._dataGridScroller = this._dataGrid.scrollContainer; @@ -150,11 +153,13 @@ */ function handleContextMenu(event) { const node = this._waterfallColumn.getNodeFromPoint(event.offsetX, event.offsetY); - if (!node) + if (!node) { return; + } const request = node.request(); - if (!request) + if (!request) { return; + } const contextMenu = new UI.ContextMenu(event); this._networkLogView.handleContextMenuForRequest(contextMenu, request); contextMenu.show(); @@ -166,8 +171,9 @@ * @param {!Event} event */ _onMouseWheel(shouldConsume, event) { - if (shouldConsume) + if (shouldConsume) { event.consume(true); + } const hasRecentWheel = Date.now() - this._lastWheelTime < 80; this._activeScroller.scrollBy({top: -event.wheelDeltaY, behavior: hasRecentWheel ? 'instant' : 'smooth'}); this._syncScrollers(); @@ -175,8 +181,9 @@ } _syncScrollers() { - if (!this._waterfallColumn.isShowing()) + if (!this._waterfallColumn.isShowing()) { return; + } this._waterfallScrollerContent.style.height = this._dataGridScroller.scrollHeight + 'px'; this._updateScrollerWidthIfNeeded(); this._dataGridScroller.scrollTop = this._waterfallScroller.scrollTop; @@ -272,10 +279,11 @@ this._networkLogView.removeAllNodeHighlights(); this._waterfallRequestsAreStale = true; if (columnId === 'waterfall') { - if (this._dataGrid.sortOrder() === DataGrid.DataGrid.Order.Ascending) + if (this._dataGrid.sortOrder() === DataGrid.DataGrid.Order.Ascending) { this._waterfallColumnSortIcon.setIconType('smallicon-triangle-up'); - else + } else { this._waterfallColumnSortIcon.setIconType('smallicon-triangle-down'); + } const sortFunction = Network.NetworkRequestNode.RequestPropertyComparator.bind(null, this._activeWaterfallSortId); this._dataGrid.sortNodes(sortFunction, !this._dataGrid.isSortOrderAscending()); @@ -285,8 +293,9 @@ this._waterfallColumnSortIcon.setIconType(''); const columnConfig = this._columns.find(columnConfig => columnConfig.id === columnId); - if (!columnConfig || !columnConfig.sortingFunction) + if (!columnConfig || !columnConfig.sortingFunction) { return; + } this._dataGrid.sortNodes(columnConfig.sortingFunction, !this._dataGrid.isSortOrderAscending()); this._dataGridSortedForTest(); @@ -296,12 +305,14 @@ } _updateColumns() { - if (!this._dataGrid) + if (!this._dataGrid) { return; + } const visibleColumns = /** @type {!Object.<string, boolean>} */ ({}); if (this._gridMode) { - for (const columnConfig of this._columns) + for (const columnConfig of this._columns) { visibleColumns[columnConfig.id] = columnConfig.visible; + } } else { visibleColumns.name = true; } @@ -312,13 +323,15 @@ * @param {boolean} gridMode */ switchViewMode(gridMode) { - if (this._gridMode === gridMode) + if (this._gridMode === gridMode) { return; + } this._gridMode = gridMode; if (gridMode) { - if (this._dataGrid.selectedNode) + if (this._dataGrid.selectedNode) { this._dataGrid.selectedNode.selected = false; + } this._splitWidget.showBoth(); this._activeScroller = this._waterfallScroller; this._waterfallScroller.scrollTop = this._dataGridScroller.scrollTop; @@ -346,8 +359,9 @@ _saveColumnsSettings() { const saveableSettings = {}; - for (const columnConfig of this._columns) + for (const columnConfig of this._columns) { saveableSettings[columnConfig.id] = {visible: columnConfig.visible, title: columnConfig.title}; + } this._persistantSettings.set(saveableSettings); } @@ -358,12 +372,15 @@ for (const columnId of columnIds) { const setting = savedSettings[columnId]; let columnConfig = this._columns.find(columnConfig => columnConfig.id === columnId); - if (!columnConfig) + if (!columnConfig) { columnConfig = this._addCustomHeader(setting.title, columnId); - if (columnConfig.hideable && typeof setting.visible === 'boolean') + } + if (columnConfig.hideable && typeof setting.visible === 'boolean') { columnConfig.visible = !!setting.visible; - if (typeof setting.title === 'string') + } + if (typeof setting.title === 'string') { columnConfig.title = setting.title; + } } } @@ -428,8 +445,9 @@ function setWaterfallMode(sortId) { let calculator = this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Time); const waterfallSortIds = Network.NetworkLogViewColumns.WaterfallSortIds; - if (sortId === waterfallSortIds.Duration || sortId === waterfallSortIds.Latency) + if (sortId === waterfallSortIds.Duration || sortId === waterfallSortIds.Latency) { calculator = this._calculatorsMap.get(Network.NetworkLogViewColumns._calculatorTypes.Duration); + } this._networkLogView.setCalculator(calculator); this._activeWaterfallSortId = sortId; @@ -441,8 +459,9 @@ _manageCustomHeaderDialog() { const customHeaders = []; for (const columnConfig of this._columns) { - if (columnConfig.isResponseHeader) + if (columnConfig.isResponseHeader) { customHeaders.push({title: columnConfig.title, editable: columnConfig.isCustomHeader}); + } } const manageCustomHeaders = new Network.NetworkManageCustomHeadersView( customHeaders, headerTitle => !!this._addCustomHeader(headerTitle), this._changeCustomHeader.bind(this), @@ -460,8 +479,9 @@ _removeCustomHeader(headerId) { headerId = headerId.toLowerCase(); const index = this._columns.findIndex(columnConfig => columnConfig.id === headerId); - if (index === -1) + if (index === -1) { return false; + } this._columns.splice(index, 1); this._dataGrid.removeColumn(headerId); this._saveColumnsSettings(); @@ -476,14 +496,17 @@ * @return {?Network.NetworkLogViewColumns.Descriptor} */ _addCustomHeader(headerTitle, headerId, index) { - if (!headerId) + if (!headerId) { headerId = headerTitle.toLowerCase(); - if (index === undefined) + } + if (index === undefined) { index = this._columns.length - 1; + } const currentColumnConfig = this._columns.find(columnConfig => columnConfig.id === headerId); - if (currentColumnConfig) + if (currentColumnConfig) { return null; + } const columnConfig = /** @type {!Network.NetworkLogViewColumns.Descriptor} */ ( Object.assign({}, Network.NetworkLogViewColumns._defaultColumnConfig, { @@ -495,8 +518,9 @@ sortingFunction: Network.NetworkRequestNode.ResponseHeaderStringComparator.bind(null, headerId) })); this._columns.splice(index, 0, columnConfig); - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.addColumn(Network.NetworkLogViewColumns._convertToDataGridDescriptor(columnConfig), index); + } this._saveColumnsSettings(); this._updateColumns(); return columnConfig; @@ -509,15 +533,17 @@ * @return {boolean} */ _changeCustomHeader(oldHeaderId, newHeaderTitle, newHeaderId) { - if (!newHeaderId) + if (!newHeaderId) { newHeaderId = newHeaderTitle.toLowerCase(); + } oldHeaderId = oldHeaderId.toLowerCase(); const oldIndex = this._columns.findIndex(columnConfig => columnConfig.id === oldHeaderId); const oldColumnConfig = this._columns[oldIndex]; const currentColumnConfig = this._columns.find(columnConfig => columnConfig.id === newHeaderId); - if (!oldColumnConfig || (currentColumnConfig && oldHeaderId !== newHeaderId)) + if (!oldColumnConfig || (currentColumnConfig && oldHeaderId !== newHeaderId)) { return false; + } this._removeCustomHeader(oldHeaderId); this._addCustomHeader(newHeaderTitle, newHeaderId, oldIndex); @@ -529,19 +555,23 @@ * @return {?UI.PopoverRequest} */ _getPopoverRequest(event) { - if (!this._gridMode) + if (!this._gridMode) { return null; + } const hoveredNode = this._networkLogView.hoveredNode(); - if (!hoveredNode) + if (!hoveredNode) { return null; + } const anchor = event.target.enclosingNodeOrSelfWithClass('network-script-initiated'); - if (!anchor) + if (!anchor) { return null; + } const request = hoveredNode.request(); const initiator = request ? request.initiator() : null; - if (!initiator || !initiator.stack) + if (!initiator || !initiator.stack) { return null; + } return { box: anchor.boxInWindow(), show: popover => {
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkManageCustomHeadersView.js b/third_party/blink/renderer/devtools/front_end/network/NetworkManageCustomHeadersView.js index 811684f..3965abc 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkManageCustomHeadersView.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkManageCustomHeadersView.js
@@ -93,15 +93,18 @@ commitEdit(item, editor, isNew) { const headerId = editor.control('header').value.trim(); let success; - if (isNew) + if (isNew) { success = this._addHeaderColumnCallback(headerId); - else + } else { success = this._changeHeaderColumnCallback(item.header, headerId); + } - if (success && !isNew) + if (success && !isNew) { this._columnConfigs.delete(item.header.toLowerCase()); - if (success) + } + if (success) { this._columnConfigs.set(headerId.toLowerCase(), {title: headerId, editable: true}); + } this._headersUpdated(); } @@ -121,8 +124,9 @@ * @return {!UI.ListWidget.Editor} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -147,8 +151,9 @@ function validateHeader(item, index, input) { let valid = true; const headerId = editor.control('header').value.trim().toLowerCase(); - if (this._columnConfigs.has(headerId) && item.header !== headerId) + if (this._columnConfigs.has(headerId) && item.header !== headerId) { valid = false; + } return {valid}; } }
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js b/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js index bcefb83..a06ec9f 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkOverview.js
@@ -49,8 +49,9 @@ */ _loadEventFired(event) { const time = /** @type {number} */ (event.data.loadTime); - if (time) + if (time) { this._loadEvents.push(time * 1000); + } this.scheduleUpdate(); } @@ -59,8 +60,9 @@ */ _domContentLoadedEventFired(event) { const data = /** @type {number} */ (event.data); - if (data) + if (data) { this._domContentLoadedEvents.push(data * 1000); + } this.scheduleUpdate(); } @@ -69,10 +71,12 @@ * @return {number} */ _bandId(connectionId) { - if (!connectionId || connectionId === '0') + if (!connectionId || connectionId === '0') { return -1; - if (this._bandMap.has(connectionId)) + } + if (this._bandMap.has(connectionId)) { return /** @type {number} */ (this._bandMap.get(connectionId)); + } const result = this._nextBand++; this._bandMap.set(connectionId, result); return result; @@ -141,8 +145,9 @@ * @protected */ scheduleUpdate() { - if (this._updateScheduled || !this.isShowing()) + if (this._updateScheduled || !this.isShowing()) { return; + } this._updateScheduled = true; this.element.window().requestAnimationFrame(this.update.bind(this)); } @@ -158,8 +163,9 @@ const newBoundary = new Network.NetworkTimeBoundary(calculator.minimumBoundary(), calculator.maximumBoundary()); if (!this._lastBoundary || !newBoundary.equals(this._lastBoundary)) { const span = calculator.boundarySpan(); - while (this._span < span) + while (this._span < span) { this._span *= 1.25; + } calculator.setBounds(calculator.minimumBoundary(), calculator.minimumBoundary() + this._span); this._lastBoundary = new Network.NetworkTimeBoundary(calculator.minimumBoundary(), calculator.maximumBoundary()); @@ -175,8 +181,9 @@ */ function drawLines(type, strokeStyle) { const lines = linesByType[type]; - if (!lines) + if (!lines) { return; + } const n = lines.length; context.beginPath(); context.strokeStyle = strokeStyle; @@ -184,8 +191,9 @@ const y = lines[i++] * Network.NetworkOverview._bandHeight + paddingTop; const startTime = lines[i++]; let endTime = lines[i++]; - if (endTime === Number.MAX_VALUE) + if (endTime === Number.MAX_VALUE) { endTime = calculator.maximumBoundary(); + } context.moveTo(calculator.computePosition(startTime), y); context.lineTo(calculator.computePosition(endTime) + 1, y); } @@ -217,8 +225,9 @@ Network.RequestTimingView.calculateRequestTimeRanges(request, this.calculator().minimumBoundary()); for (let j = 0; j < timeRanges.length; ++j) { const type = timeRanges[j].name; - if (band !== -1 || type === Network.RequestTimeRangeNames.Total) + if (band !== -1 || type === Network.RequestTimeRangeNames.Total) { addLine(type, y, timeRanges[j].start * 1000, timeRanges[j].end * 1000); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js b/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js index bca2026..b00401c 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkPanel.js
@@ -98,8 +98,9 @@ tabbedPane.setMinimumSize(100, 25); tabbedPane.element.classList.add('network-tabbed-pane'); tabbedPane.element.addEventListener('keydown', event => { - if (event.key !== 'Escape') + if (event.key !== 'Escape') { return; + } splitWidget.hideSidebar(); event.consume(); }); @@ -160,8 +161,9 @@ static revealAndFilter(filters) { const panel = Network.NetworkPanel._instance(); let filterString = ''; - for (const filter of filters) + for (const filter of filters) { filterString += `${filter.filterType}:${filter.filterValue} `; + } panel._networkLogView.setTextFilterValue(filterString); UI.viewManager.showView('network'); } @@ -204,10 +206,11 @@ updateSidebarToggle(); splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, updateSidebarToggle); searchToggle.addEventListener(UI.ToolbarButton.Events.Click, () => { - if (splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) + if (splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) { splitWidget.showBoth(); - else + } else { splitWidget.hideSidebar(); + } }); this._panelToolbar.appendToolbarItem(searchToggle); this._panelToolbar.appendSeparator(); @@ -267,8 +270,9 @@ } _toggleRecording() { - if (!this._preserveLogSetting.get() && !this._toggleRecordAction.toggled()) + if (!this._preserveLogSetting.get() && !this._toggleRecordAction.toggled()) { SDK.networkLog.reset(); + } this._toggleRecord(!this._toggleRecordAction.toggled()); } @@ -278,8 +282,9 @@ _toggleRecord(toggled) { this._toggleRecordAction.setToggled(toggled); this._networkLogView.setRecording(toggled); - if (!toggled && this._filmStripRecorder) + if (!toggled && this._filmStripRecorder) { this._filmStripRecorder.stopRecording(this._filmStripAvailable.bind(this)); + } // TODO(einbinder) This should be moved to a setting/action that NetworkLog owns but NetworkPanel controls, but // always be present in the command menu. SDK.networkLog.setIsRecording(toggled); @@ -289,8 +294,9 @@ * @param {?SDK.FilmStripModel} filmStripModel */ _filmStripAvailable(filmStripModel) { - if (!filmStripModel) + if (!filmStripModel) { return; + } const calculator = this._networkLogView.timeCalculator(); this._filmStripView.setModel(filmStripModel, calculator.minimumBoundary() * 1000, calculator.boundarySpan() * 1000); this._networkOverview.setFilmStripModel(filmStripModel); @@ -313,8 +319,9 @@ this._calculator.reset(); this._overviewPane.reset(); } - if (this._filmStripView) + if (this._filmStripView) { this._resetFilmStripView(); + } } /** @@ -326,8 +333,9 @@ clearTimeout(this._pendingStopTimer); delete this._pendingStopTimer; } - if (this.isShowing() && this._filmStripRecorder) + if (this.isShowing() && this._filmStripRecorder) { this._filmStripRecorder.startRecording(); + } } /** @@ -351,10 +359,11 @@ _toggleShowOverview() { const toggled = this._networkLogShowOverviewSetting.get(); - if (toggled) + if (toggled) { this._overviewPane.show(this._overviewPlaceholderElement); - else + } else { this._overviewPane.detach(); + } this.doResize(); } @@ -420,8 +429,9 @@ */ revealAndHighlightRequest(request) { this._showRequest(null); - if (request) + if (request) { this._networkLogView.revealAndHighlightRequest(request); + } } /** @@ -498,28 +508,33 @@ contextMenu.revealSection().appendItem(Common.UIString('Reveal in Network panel'), reveal.bind(this, request)); } - if (event.target.isSelfOrDescendant(this.element)) + if (event.target.isSelfOrDescendant(this.element)) { return; + } if (target instanceof SDK.Resource) { const resource = /** @type {!SDK.Resource} */ (target); - if (resource.request) + if (resource.request) { appendRevealItem.call(this, resource.request); + } return; } if (target instanceof Workspace.UISourceCode) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (target); const resource = Bindings.resourceForURL(uiSourceCode.url()); - if (resource && resource.request) + if (resource && resource.request) { appendRevealItem.call(this, resource.request); + } return; } - if (!(target instanceof SDK.NetworkRequest)) + if (!(target instanceof SDK.NetworkRequest)) { return; + } const request = /** @type {!SDK.NetworkRequest} */ (target); - if (this._networkItemView && this._networkItemView.isShowing() && this._networkItemView.request() === request) + if (this._networkItemView && this._networkItemView.isShowing() && this._networkItemView.request() === request) { return; + } appendRevealItem.call(this, request); } @@ -567,8 +582,9 @@ * @return {?UI.ViewLocation} */ resolveLocation(locationName) { - if (locationName === 'network-sidebar') + if (locationName === 'network-sidebar') { return this._sidebarLocation; + } return null; } }; @@ -602,8 +618,9 @@ * @return {!Promise} */ reveal(request) { - if (!(request instanceof SDK.NetworkRequest)) + if (!(request instanceof SDK.NetworkRequest)) { return Promise.reject(new Error('Internal error: not a network request')); + } const panel = Network.NetworkPanel._instance(); return UI.viewManager.showView('network').then(panel.revealAndHighlightRequest.bind(panel, request)); } @@ -636,22 +653,25 @@ * @param {!Array.<!SDK.TracingManager.EventPayload>} events */ traceEventsCollected(events) { - if (this._tracingModel) + if (this._tracingModel) { this._tracingModel.addEvents(events); + } } /** * @override */ tracingComplete() { - if (!this._tracingModel || !this._tracingManager) + if (!this._tracingModel || !this._tracingManager) { return; + } this._tracingModel.tracingComplete(); this._tracingManager = null; this._callback(new SDK.FilmStripModel(this._tracingModel, this._timeCalculator.minimumBoundary() * 1000)); this._callback = null; - if (this._resourceTreeModel) + if (this._resourceTreeModel) { this._resourceTreeModel.resumeReload(); + } this._resourceTreeModel = null; } @@ -672,13 +692,15 @@ this._filmStripView.reset(); this._filmStripView.setStatusText(Common.UIString('Recording frames...')); const tracingManagers = SDK.targetManager.models(SDK.TracingManager); - if (this._tracingManager || !tracingManagers.length) + if (this._tracingManager || !tracingManagers.length) { return; + } this._tracingManager = tracingManagers[0]; this._resourceTreeModel = this._tracingManager.target().model(SDK.ResourceTreeModel); - if (this._tracingModel) + if (this._tracingModel) { this._tracingModel.dispose(); + } this._tracingModel = new SDK.TracingModel(new Bindings.TempFileBackingStorage()); this._tracingManager.start(this, '-*,disabled-by-default-devtools.screenshot', ''); @@ -696,12 +718,14 @@ * @param {function(?SDK.FilmStripModel)} callback */ stopRecording(callback) { - if (!this._tracingManager) + if (!this._tracingManager) { return; + } this._tracingManager.stop(); - if (this._resourceTreeModel) + if (this._resourceTreeModel) { this._resourceTreeModel.suspendReload(); + } this._callback = callback; this._filmStripView.setStatusText(Common.UIString('Fetching frames...')); } @@ -725,15 +749,17 @@ panel._toggleRecording(); return true; case 'network.hide-request-details': - if (!panel._networkItemView) + if (!panel._networkItemView) { return false; + } panel._showRequest(null); return true; case 'network.search': const selection = UI.inspectorView.element.window().getSelection(); let queryCandidate = ''; - if (selection.rangeCount) + if (selection.rangeCount) { queryCandidate = selection.toString().replace(/\r?\n.*/, ''); + } Network.SearchNetworkView.openSearch(queryCandidate); return true; } @@ -753,14 +779,18 @@ async reveal(match) { const location = /** @type {!Network.UIRequestLocation} */ (match); const view = await Network.NetworkPanel._instance().selectRequest(location.request); - if (!view) + if (!view) { return; - if (location.searchMatch) + } + if (location.searchMatch) { await view.revealResponseBody(location.searchMatch.lineNumber); - if (location.requestHeader) + } + if (location.requestHeader) { view.revealRequestHeader(location.requestHeader.name); - if (location.responseHeader) + } + if (location.responseHeader) { view.revealResponseHeader(location.responseHeader.name); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkSearchScope.js b/third_party/blink/renderer/devtools/front_end/network/NetworkSearchScope.js index 57afb465..fc0e3cc 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkSearchScope.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkSearchScope.js
@@ -36,8 +36,9 @@ return; } for (const result of results.sort((r1, r2) => r1.label().localeCompare(r2.label()))) { - if (result.matchesCount() > 0) + if (result.matchesCount() > 0) { searchResultCallback(result); + } } progress.done(); searchFinishedCallback(true); @@ -55,21 +56,26 @@ bodyMatches = await request.searchInContent(searchConfig.query(), !searchConfig.ignoreCase(), searchConfig.isRegex()); } - if (progress.isCanceled()) + if (progress.isCanceled()) { return null; + } const locations = []; - if (stringMatchesQuery(request.url())) + if (stringMatchesQuery(request.url())) { locations.push(Network.UIRequestLocation.urlMatch(request)); + } for (const header of request.requestHeaders()) { - if (headerMatchesQuery(header)) + if (headerMatchesQuery(header)) { locations.push(Network.UIRequestLocation.requestHeaderMatch(request, header)); + } } for (const header of request.responseHeaders) { - if (headerMatchesQuery(header)) + if (headerMatchesQuery(header)) { locations.push(Network.UIRequestLocation.responseHeaderMatch(request, header)); + } } - for (const match of bodyMatches) + for (const match of bodyMatches) { locations.push(Network.UIRequestLocation.bodyMatch(request, match)); + } progress.worked(); return new Network.NetworkSearchResult(request, locations); @@ -91,8 +97,9 @@ let pos = 0; for (const regExp of regExps) { const match = string.substr(pos).match(regExp); - if (!match) + if (!match) { return false; + } pos += match.index + match[0].length; } return true; @@ -189,8 +196,9 @@ */ description() { const parsedUrl = this._request.parsedURL; - if (!parsedUrl) + if (!parsedUrl) { return this._request.url(); + } return parsedUrl.urlWithoutScheme(); } @@ -201,11 +209,13 @@ */ matchLineContent(index) { const location = this._locations[index]; - if (location.isUrlMatch) + if (location.isUrlMatch) { return this._request.url(); + } const header = location.requestHeader || location.responseHeader; - if (header) + if (header) { return header.value; + } return location.searchMatch.lineContent; } @@ -225,11 +235,13 @@ */ matchLabel(index) { const location = this._locations[index]; - if (location.isUrlMatch) + if (location.isUrlMatch) { return Common.UIString('URL'); + } const header = location.requestHeader || location.responseHeader; - if (header) + if (header) { return `${header.name}:`; + } return location.searchMatch.lineNumber + 1; } };
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkTimeCalculator.js b/third_party/blink/renderer/devtools/front_end/network/NetworkTimeCalculator.js index d1b2898..1286982 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkTimeCalculator.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkTimeCalculator.js
@@ -164,20 +164,23 @@ let start; let middle; let end; - if (request.startTime !== -1) + if (request.startTime !== -1) { start = ((request.startTime - this.minimumBoundary()) / this.boundarySpan()) * 100; - else + } else { start = 0; + } - if (request.responseReceivedTime !== -1) + if (request.responseReceivedTime !== -1) { middle = ((request.responseReceivedTime - this.minimumBoundary()) / this.boundarySpan()) * 100; - else + } else { middle = (this.startAtZero ? start : 100); + } - if (request.endTime !== -1) + if (request.endTime !== -1) { end = ((request.endTime - this.minimumBoundary()) / this.boundarySpan()) * 100; - else + } else { end = (this.startAtZero ? middle : 100); + } if (this.startAtZero) { end -= start; @@ -196,8 +199,9 @@ // This function computes a percentage in terms of the total loading time // of a specific event. If startAtZero is set, then this is useless, and we // want to return 0. - if (eventTime !== -1 && !this.startAtZero) + if (eventTime !== -1 && !this.startAtZero) { return ((eventTime - this.minimumBoundary()) / this.boundarySpan()) * 100; + } return 0; } @@ -227,8 +231,9 @@ * @param {number} eventTime */ updateBoundariesForEventTime(eventTime) { - if (eventTime === -1 || this.startAtZero) + if (eventTime === -1 || this.startAtZero) { return; + } if (this._maximumBoundary === undefined || eventTime > this._maximumBoundary) { this._maximumBoundary = eventTime; @@ -242,14 +247,16 @@ */ computeBarGraphLabels(request) { let rightLabel = ''; - if (request.responseReceivedTime !== -1 && request.endTime !== -1) + if (request.responseReceivedTime !== -1 && request.endTime !== -1) { rightLabel = Number.secondsToString(request.endTime - request.responseReceivedTime); + } const hasLatency = request.latency > 0; const leftLabel = hasLatency ? Number.secondsToString(request.latency) : rightLabel; - if (request.timing) + if (request.timing) { return {left: leftLabel, right: rightLabel}; + } let tooltip; if (hasLatency && rightLabel) { @@ -261,10 +268,11 @@ tooltip = Network.NetworkTimeCalculator._downloadFormat.format(rightLabel); } - if (request.fetchedViaServiceWorker) + if (request.fetchedViaServiceWorker) { tooltip = Network.NetworkTimeCalculator._fromServiceWorkerFormat.format(tooltip); - else if (request.cached()) + } else if (request.cached()) { tooltip = Network.NetworkTimeCalculator._fromCacheFormat.format(tooltip); + } return {left: leftLabel, right: rightLabel, tooltip: tooltip}; } @@ -275,12 +283,15 @@ const lowerBound = this._lowerBound(request); const upperBound = this._upperBound(request); let changed = false; - if (lowerBound !== -1 || this.startAtZero) + if (lowerBound !== -1 || this.startAtZero) { changed = this._extendBoundariesToIncludeTimestamp(this.startAtZero ? 0 : lowerBound); - if (upperBound !== -1) + } + if (upperBound !== -1) { changed = this._extendBoundariesToIncludeTimestamp(upperBound) || changed; - if (changed) + } + if (changed) { this._boundaryChanged(); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/network/NetworkWaterfallColumn.js b/third_party/blink/renderer/devtools/front_end/network/NetworkWaterfallColumn.js index aea813d..6cef179 100644 --- a/third_party/blink/renderer/devtools/front_end/network/NetworkWaterfallColumn.js +++ b/third_party/blink/renderer/devtools/front_end/network/NetworkWaterfallColumn.js
@@ -119,8 +119,9 @@ for (const resourceType of Object.values(Common.resourceTypes)) { let color = baseResourceTypeColors.get(resourceType.name()); - if (!color) + if (!color) { color = baseResourceTypeColors.get('other'); + } const borderColor = toBorderColor(color); waitingStyleMap.set(resourceType, {fillStyle: toWaitingColor(color), lineWidth: 1, borderColor: borderColor}); @@ -185,11 +186,13 @@ * @return {?UI.PopoverRequest} */ _getPopoverRequest(event) { - if (!this._hoveredNode) + if (!this._hoveredNode) { return null; + } const request = this._hoveredNode.request(); - if (!request) + if (!request) { return null; + } const useTimingBars = !Common.moduleSetting('networkColorCodeResourceTypes').get() && !this._calculator.startAtZero; let range; let start; @@ -211,15 +214,17 @@ end = end - halfWidth + 25; } - if (event.clientX < this._canvasPosition.left + start || event.clientX > this._canvasPosition.left + end) + if (event.clientX < this._canvasPosition.left + start || event.clientX > this._canvasPosition.left + end) { return null; + } const rowIndex = this._nodes.findIndex(node => node.hovered()); const barHeight = this._getBarHeight(range.name); const y = this._headerHeight + (this._rowHeight * rowIndex - this._scrollTop) + ((this._rowHeight - barHeight) / 2); - if (event.clientY < this._canvasPosition.top + y || event.clientY > this._canvasPosition.top + y + barHeight) + if (event.clientY < this._canvasPosition.top + y || event.clientY > this._canvasPosition.top + y + barHeight) { return null; + } const anchorBox = this.element.boxInWindow(); anchorBox.x += start; @@ -243,11 +248,13 @@ * @param {boolean} highlightInitiatorChain */ _setHoveredNode(node, highlightInitiatorChain) { - if (this._hoveredNode) + if (this._hoveredNode) { this._hoveredNode.setHovered(false, false); + } this._hoveredNode = node; - if (this._hoveredNode) + if (this._hoveredNode) { this._hoveredNode.setHovered(true, highlightInitiatorChain); + } } /** @@ -290,14 +297,16 @@ * @return {?Network.NetworkNode} */ getNodeFromPoint(x, y) { - if (y <= this._headerHeight) + if (y <= this._headerHeight) { return null; + } return this._nodes[Math.floor((this._scrollTop + y - this._headerHeight) / this._rowHeight)]; } scheduleDraw() { - if (this._updateRequestID) + if (this._updateRequestID) { return; + } this._updateRequestID = this.element.window().requestAnimationFrame(() => this.update()); } @@ -315,8 +324,9 @@ this._nodes = nodes; this._calculateCanvasSize(); } - if (eventDividers !== undefined) + if (eventDividers !== undefined) { this._eventDividers = eventDividers; + } if (this._updateRequestID) { this.element.window().cancelAnimationFrame(this._updateRequestID); delete this._updateRequestID; @@ -385,22 +395,25 @@ const node = nodes[i]; this._decorateRow(context, node, rowOffset - this._scrollTop); let drawNodes = []; - if (node.hasChildren() && !node.expanded) + if (node.hasChildren() && !node.expanded) { drawNodes = /** @type {!Array<!Network.NetworkNode>} */ (node.flatChildren()); + } drawNodes.push(node); for (const drawNode of drawNodes) { - if (useTimingBars) + if (useTimingBars) { this._buildTimingBarLayers(drawNode, rowOffset - this._scrollTop); - else + } else { this._buildSimplifiedBarLayers(context, drawNode, rowOffset - this._scrollTop); + } } } this._drawLayers(context); context.save(); context.fillStyle = UI.themeSupport.patchColorText('#888', UI.ThemeSupport.ColorUsage.Foreground); - for (const textData of this._textLayers) + for (const textData of this._textLayers) { context.fillText(textData.text, textData.x, textData.y); + } context.restore(); this._drawEventDividers(context); @@ -500,8 +513,9 @@ */ _buildSimplifiedBarLayers(context, node, y) { const request = node.request(); - if (!request) + if (!request) { return; + } const borderWidth = 1; const borderOffset = borderWidth % 2 === 0 ? 0 : 0.5; @@ -579,13 +593,15 @@ */ _buildTimingBarLayers(node, y) { const request = node.request(); - if (!request) + if (!request) { return; + } const ranges = Network.RequestTimingView.calculateRequestTimeRanges(request, 0); for (const range of ranges) { if (range.name === Network.RequestTimeRangeNames.Total || range.name === Network.RequestTimeRangeNames.Sending || - range.end - range.start === 0) + range.end - range.start === 0) { continue; + } const style = this._styleForTimeRangeName.get(range.name); const path = this._pathForStyle.get(style);
diff --git a/third_party/blink/renderer/devtools/front_end/network/RequestCookiesView.js b/third_party/blink/renderer/devtools/front_end/network/RequestCookiesView.js index 46ce536..826a654 100644 --- a/third_party/blink/renderer/devtools/front_end/network/RequestCookiesView.js +++ b/third_party/blink/renderer/devtools/front_end/network/RequestCookiesView.js
@@ -100,8 +100,9 @@ if (this._detailedRequestCookies) { requestCookies = requestCookies.map(cookie => { for (const detailedCookie of (this._detailedRequestCookies || [])) { - if (detailedCookie.name() === cookie.name() && detailedCookie.value() === cookie.value()) + if (detailedCookie.name() === cookie.name() && detailedCookie.value() === cookie.value()) { return detailedCookie; + } } return cookie; }); @@ -180,8 +181,9 @@ } _refreshRequestCookiesView() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const {requestCookies, requestCookieToBlockedReasons} = this._getRequestCookies(); const {responseCookies, responseCookieToBlockedReasons, malformedResponseCookies} = this._getResponseCookies(); @@ -263,8 +265,9 @@ } _cookiesUpdated() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } if (this._gotCookies()) { this._refreshRequestCookiesView();
diff --git a/third_party/blink/renderer/devtools/front_end/network/RequestHeadersView.js b/third_party/blink/renderer/devtools/front_end/network/RequestHeadersView.js index cf12a6d..5c07f20 100644 --- a/third_party/blink/renderer/devtools/front_end/network/RequestHeadersView.js +++ b/third_party/blink/renderer/devtools/front_end/network/RequestHeadersView.js
@@ -137,12 +137,14 @@ } } const div = createElementWithClass('div', className); - if (value === '') + if (value === '') { div.classList.add('empty-value'); - if (errorDecoding) + } + if (errorDecoding) { div.createChild('span', 'header-decode-error').textContent = Common.UIString('(unable to decode value)'); - else + } else { div.textContent = value; + } return div; } @@ -165,8 +167,9 @@ this._requestPayloadCategory.hidden = true; const formData = await this._request.requestFormData(); - if (!formData) + if (!formData) { return; + } const formParameters = await this._request.formParameters(); if (formParameters) { @@ -199,8 +202,9 @@ sourceTreeElement.selectable = false; treeElement.removeChildren(); treeElement.appendChild(sourceTreeElement); - if (!trim) + if (!trim) { return; + } const showMoreButton = createElementWithClass('button', 'request-headers-show-more-button'); showMoreButton.textContent = Common.UIString('Show more'); @@ -337,10 +341,11 @@ }); const headersText = this._request.requestHeadersText(); - if (this._showRequestHeadersText && headersText) + if (this._showRequestHeadersText && headersText) { this._refreshHeadersText(Common.UIString('Request Headers'), headers.length, headersText, treeElement); - else + } else { this._refreshHeaders(Common.UIString('Request Headers'), headers, treeElement, headersText === undefined); + } if (headersText) { const toggleButton = this._createHeadersToggleButton(this._showRequestHeadersText); @@ -386,12 +391,13 @@ const statusCodeImage = statusCodeFragment.createChild('span', 'resource-status-image', 'dt-icon-label'); statusCodeImage.title = this._request.statusCode + ' ' + this._request.statusText; - if (this._request.statusCode < 300 || this._request.statusCode === 304) + if (this._request.statusCode < 300 || this._request.statusCode === 304) { statusCodeImage.type = 'smallicon-green-ball'; - else if (this._request.statusCode < 400) + } else if (this._request.statusCode < 400) { statusCodeImage.type = 'smallicon-orange-ball'; - else + } else { statusCodeImage.type = 'smallicon-red-ball'; + } requestMethodElement.title = this._formatHeader(ls`Request Method`, this._request.requestMethod); @@ -479,8 +485,9 @@ let titleText = ''; for (const blockedReason of matchingBlockedReasons) { - if (titleText) + if (titleText) { titleText += '\n'; + } titleText += SDK.NetworkRequest.setCookieBlockedReasonToUiString(blockedReason); } icon.title = titleText; @@ -506,16 +513,18 @@ const remoteAddress = this._request.remoteAddress(); const treeElement = this._remoteAddressItem; treeElement.hidden = !remoteAddress; - if (remoteAddress) + if (remoteAddress) { treeElement.title = this._formatHeader(Common.UIString('Remote Address'), remoteAddress); + } } _refreshReferrerPolicy() { const referrerPolicy = this._request.referrerPolicy(); const treeElement = this._referrerPolicyItem; treeElement.hidden = !referrerPolicy; - if (referrerPolicy) + if (referrerPolicy) { treeElement.title = this._formatHeader(Common.UIString('Referrer Policy'), referrerPolicy); + } } /** @@ -556,8 +565,9 @@ } _clearHighlight() { - if (this._highlightedElement) + if (this._highlightedElement) { this._highlightedElement.listItemElement.classList.remove('header-highlight'); + } this._highlightedElement = null; } @@ -569,8 +579,9 @@ _revealAndHighlight(category, name) { this._clearHighlight(); for (const element of category.children()) { - if (element[Network.RequestHeadersView._headerNameSymbol] !== name) + if (element[Network.RequestHeadersView._headerNameSymbol] !== name) { continue; + } this._highlightedElement = element; element.reveal(); element.listItemElement.classList.add('header-highlight');
diff --git a/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js b/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js index d63c7f8..631f9d7c 100644 --- a/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js +++ b/third_party/blink/renderer/devtools/front_end/network/RequestPreviewView.js
@@ -43,11 +43,13 @@ */ async showPreview() { const view = await super.showPreview(); - if (!(view instanceof UI.SimpleView)) + if (!(view instanceof UI.SimpleView)) { return view; + } const toolbar = new UI.Toolbar('network-item-preview-toolbar', this.element); - for (const item of view.syncToolbarItems()) + for (const item of view.syncToolbarItems()) { toolbar.appendToolbarItem(item); + } return view; } @@ -56,20 +58,23 @@ */ async _htmlPreview() { const contentData = await this.request.contentData(); - if (contentData.error) + if (contentData.error) { return new UI.EmptyWidget(Common.UIString('Failed to load response data')); + } const whitelist = new Set(['text/html', 'text/plain', 'application/xhtml+xml']); - if (!whitelist.has(this.request.mimeType)) + if (!whitelist.has(this.request.mimeType)) { return null; + } const content = contentData.encoded ? window.atob(/** @type {string} */ (contentData.content)) : /** @type {string} */ (contentData.content); // http://crbug.com/767393 - DevTools should recognize JSON regardless of the content type const jsonView = await SourceFrame.JSONView.createView(content); - if (jsonView) + if (jsonView) { return jsonView; + } const dataURL = Common.ContentProvider.contentAsDataURL( contentData.content, this.request.mimeType, contentData.encoded, this.request.charset()); @@ -82,16 +87,19 @@ * @return {!Promise<!UI.Widget>} */ async createPreview() { - if (this.request.signedExchangeInfo()) + if (this.request.signedExchangeInfo()) { return new Network.SignedExchangeInfoView(this.request); + } const htmlErrorPreview = await this._htmlPreview(); - if (htmlErrorPreview) + if (htmlErrorPreview) { return htmlErrorPreview; + } const provided = await SourceFrame.PreviewFactory.createPreview(this.request, this.request.mimeType); - if (provided) + if (provided) { return provided; + } return new UI.EmptyWidget(Common.UIString('Preview not available')); }
diff --git a/third_party/blink/renderer/devtools/front_end/network/RequestResponseView.js b/third_party/blink/renderer/devtools/front_end/network/RequestResponseView.js index 7160865..6e5ac3c 100644 --- a/third_party/blink/renderer/devtools/front_end/network/RequestResponseView.js +++ b/third_party/blink/renderer/devtools/front_end/network/RequestResponseView.js
@@ -49,16 +49,21 @@ static _hasTextContent(request, contentData) { const mimeType = request.mimeType || ''; let resourceType = Common.ResourceType.fromMimeType(mimeType); - if (resourceType === Common.resourceTypes.Other) + if (resourceType === Common.resourceTypes.Other) { resourceType = request.contentType(); - if (resourceType === Common.resourceTypes.Image) + } + if (resourceType === Common.resourceTypes.Image) { return mimeType.startsWith('image/svg'); - if (resourceType.isTextType()) + } + if (resourceType.isTextType()) { return true; - if (contentData.error) + } + if (contentData.error) { return false; - if (resourceType === Common.resourceTypes.Other) + } + if (resourceType === Common.resourceTypes.Other) { return !!contentData.content && !contentData.encoded; + } return false; } @@ -69,8 +74,9 @@ */ static async sourceViewForRequest(request) { let sourceView = request[Network.RequestResponseView._sourceViewSymbol]; - if (sourceView !== undefined) + if (sourceView !== undefined) { return sourceView; + } const contentData = await request.contentData(); if (!Network.RequestResponseView._hasTextContent(request, contentData)) { @@ -96,8 +102,9 @@ * @return {!Promise<!UI.Widget>} */ _doShowPreview() { - if (!this._contentViewPromise) + if (!this._contentViewPromise) { this._contentViewPromise = this.showPreview(); + } return this._contentViewPromise; } @@ -118,10 +125,12 @@ async createPreview() { const contentData = await this.request.contentData(); const sourceView = await Network.RequestResponseView.sourceViewForRequest(this.request); - if ((!contentData.content || !sourceView) && !contentData.error) + if ((!contentData.content || !sourceView) && !contentData.error) { return new UI.EmptyWidget(Common.UIString('This request has no response data available.')); - if (contentData.content && sourceView) + } + if (contentData.content && sourceView) { return sourceView; + } return new UI.EmptyWidget(Common.UIString('Failed to load response data')); } @@ -130,8 +139,9 @@ */ async revealLine(line) { const view = await this._doShowPreview(); - if (view instanceof SourceFrame.ResourceSourceFrame.SearchableContainer) + if (view instanceof SourceFrame.ResourceSourceFrame.SearchableContainer) { view.revealPosition(line); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/network/RequestTimingView.js b/third_party/blink/renderer/devtools/front_end/network/RequestTimingView.js index 2623fbf..8b7a8d26 100644 --- a/third_party/blink/renderer/devtools/front_end/network/RequestTimingView.js +++ b/third_party/blink/renderer/devtools/front_end/network/RequestTimingView.js
@@ -96,8 +96,9 @@ * @param {number} end */ function addRange(name, start, end) { - if (start < Number.MAX_VALUE && start <= end) + if (start < Number.MAX_VALUE && start <= end) { result.push({name: name, start: start, end: end}); + } } /** @@ -106,8 +107,9 @@ */ function firstPositive(numbers) { for (let i = 0; i < numbers.length; ++i) { - if (numbers[i] > 0) + if (numbers[i] > 0) { return numbers[i]; + } } return undefined; } @@ -118,8 +120,9 @@ * @param {number} end */ function addOffsetRange(name, start, end) { - if (start >= 0 && end >= 0) + if (start >= 0 && end >= 0) { addRange(name, startTime + (start / 1000), startTime + (end / 1000)); + } } const timing = request.timing; @@ -142,11 +145,13 @@ const pushEnd = timing.pushEnd || endTime; // Only show the part of push that happened after the navigation/reload. // Pushes that happened on the same connection before we started main request will not be shown. - if (pushEnd > navigationStart) + if (pushEnd > navigationStart) { addRange(Network.RequestTimeRangeNames.Push, Math.max(timing.pushStart, navigationStart), pushEnd); + } } - if (issueTime < startTime) + if (issueTime < startTime) { addRange(Network.RequestTimeRangeNames.Queueing, issueTime, startTime); + } const responseReceived = (request.responseReceivedTime - startTime) * 1000; if (request.fetchedViaServiceWorker) { @@ -229,14 +234,17 @@ if (rangeName === Network.RequestTimeRangeNames.Push) { createHeader(Common.UIString('Server Push')); } else if (rangeName === Network.RequestTimeRangeNames.Queueing) { - if (!queueingHeader) + if (!queueingHeader) { queueingHeader = createHeader(ls`Resource Scheduling`); + } } else if (Network.RequestTimingView.ConnectionSetupRangeNames.has(rangeName)) { - if (!connectionHeader) + if (!connectionHeader) { connectionHeader = createHeader(Common.UIString('Connection Start')); + } } else { - if (!dataHeader) + if (!dataHeader) { dataHeader = createHeader(Common.UIString('Request/Response')); + } } const left = (scale * (range.start - startTime)); @@ -271,8 +279,9 @@ footer.createChild('td').createTextChild(Number.secondsToString(totalDuration, true)); const serverTimings = request.serverTimings; - if (!serverTimings) + if (!serverTimings) { return tableElement; + } const lastTimingRightEdge = right === undefined ? 100 : right; @@ -306,16 +315,18 @@ metric.title = description; const row = tr.createChild('td').createChild('div', 'network-timing-row'); - if (serverTiming.value === null) + if (serverTiming.value === null) { return; + } const left = scale * (endTime - startTime - (serverTiming.value / 1000)); if (left >= 0) { // don't chart values too big or too small const bar = row.createChild('span', 'network-timing-bar server-timing'); bar.style.left = left + '%'; bar.style.right = right + '%'; bar.textContent = '\u200B'; // Important for 0-time items to have 0 width. - if (!isTotal) + if (!isTotal) { bar.style.backgroundColor = colorGenerator.colorForID(serverTiming.metric); + } } const label = tr.createChild('td').createChild('div', 'network-timing-bar-title'); label.textContent = Number.millisToString(serverTiming.value, true); @@ -356,8 +367,9 @@ } _refresh() { - if (this._tableElement) + if (this._tableElement) { this._tableElement.remove(); + } this._tableElement = Network.RequestTimingView.createTimingTable(this._request, this._calculator); this._tableElement.classList.add('resource-timing-table');
diff --git a/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js b/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js index 4474597..c78ff602 100644 --- a/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js +++ b/third_party/blink/renderer/devtools/front_end/network/ResourceWebSocketFrameView.js
@@ -116,8 +116,9 @@ */ static opCodeDescription(opCode, mask) { const localizedDescription = Network.ResourceWebSocketFrameView.opCodeDescriptions[opCode] || ''; - if (mask) + if (mask) { return ls`${localizedDescription} (Opcode ${opCode}, mask)`; + } return ls`${localizedDescription} (Opcode ${opCode})`; } @@ -141,8 +142,9 @@ */ _frameAdded(event) { const frame = /** @type {!SDK.NetworkRequest.WebSocketFrame} */ (event.data); - if (!this._frameFilter(frame)) + if (!this._frameFilter(frame)) { return; + } this._dataGrid.insertChild(new Network.ResourceWebSocketFrameNode(this._request.url(), frame)); } @@ -151,8 +153,9 @@ * @return {boolean} */ _frameFilter(frame) { - if (this._filterType && frame.type !== this._filterType) + if (this._filterType && frame.type !== this._filterType) { return false; + } return !this._filterRegex || this._filterRegex.test(frame.text); } @@ -331,11 +334,13 @@ * @return {?Network.BinaryResourceView} */ binaryView() { - if (this._isTextFrame || this._frame.type === SDK.NetworkRequest.WebSocketFrameType.Error) + if (this._isTextFrame || this._frame.type === SDK.NetworkRequest.WebSocketFrameType.Error) { return null; + } - if (!this._binaryView) + if (!this._binaryView) { this._binaryView = new Network.BinaryResourceView(this._dataText, /* url */ '', Common.resourceTypes.WebSocket); + } return this._binaryView; } };
diff --git a/third_party/blink/renderer/devtools/front_end/network_test_runner/NetworkTestRunner.js b/third_party/blink/renderer/devtools/front_end/network_test_runner/NetworkTestRunner.js index ccacb53..48c07eff 100644 --- a/third_party/blink/renderer/devtools/front_end/network_test_runner/NetworkTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/network_test_runner/NetworkTestRunner.js
@@ -8,8 +8,9 @@ */ NetworkTestRunner.waitForRequestResponse = function(request) { - if (request.responseReceivedTime !== -1) + if (request.responseReceivedTime !== -1) { return Promise.resolve(request); + } return TestRunner.waitForEvent( SDK.NetworkManager.Events.RequestUpdated, TestRunner.networkManager, @@ -20,8 +21,9 @@ const networkLogView = UI.panels.network._networkLogView; const node = networkLogView.nodeForRequest(request); - if (node) + if (node) { return Promise.resolve(node); + } console.assert(networkLogView._staleRequests.has(request)); @@ -34,8 +36,9 @@ NetworkTestRunner.waitForWebsocketFrameReceived = function(wsRequest, message) { for (const frame of wsRequest.frames()) { - if (checkFrame(frame)) + if (checkFrame(frame)) { return Promise.resolve(frame); + } } return TestRunner.waitForEvent(SDK.NetworkRequest.Events.WebsocketFrameAdded, wsRequest, checkFrame); @@ -66,8 +69,9 @@ TestRunner.addResult('resources count = ' + requests.length); - for (i = 0; i < requests.length; i++) + for (i = 0; i < requests.length; i++) { TestRunner.addResult(requests[i].url()); + } }; NetworkTestRunner.dumpNetworkRequestsWithSignedExchangeInfo = function() { @@ -81,8 +85,9 @@ if (request.signedExchangeInfo().header) { const header = request.signedExchangeInfo().header; TestRunner.addResult(` Request URL: ${header.requestUrl}`); - for (const signature of header.signatures) + for (const signature of header.signatures) { TestRunner.addResult(` Certificate URL: ${signature.certUrl}`); + } } if (request.signedExchangeInfo().securityDetails) { const securityDetails = request.signedExchangeInfo().securityDetails; @@ -90,8 +95,9 @@ TestRunner.addResult(` Certificate Issuer: ${securityDetails.issuer}`); } if (request.signedExchangeInfo().errors) { - for (const errorMessage of request.signedExchangeInfo().errors) + for (const errorMessage of request.signedExchangeInfo().errors) { TestRunner.addResult(` Error: ${JSON.stringify(errorMessage)}`); + } } } } @@ -138,8 +144,9 @@ function innerCallback(msg) { if (msg.messageText.indexOf('XHR loaded') !== -1) { - if (callback) + if (callback) { callback(); + } } else { ConsoleTestRunner.addConsoleSniffer(innerCallback); }
diff --git a/third_party/blink/renderer/devtools/front_end/node_main/NodeConnectionsPanel.js b/third_party/blink/renderer/devtools/front_end/node_main/NodeConnectionsPanel.js index 25e7259..76ecfc4 100644 --- a/third_party/blink/renderer/devtools/front_end/node_main/NodeConnectionsPanel.js +++ b/third_party/blink/renderer/devtools/front_end/node_main/NodeConnectionsPanel.js
@@ -135,8 +135,9 @@ */ commitEdit(rule, editor, isNew) { rule.address = editor.control('address').value.trim(); - if (isNew) + if (isNew) { this._networkDiscoveryConfig.push(rule); + } this._update(); } @@ -155,8 +156,9 @@ * @return {!UI.ListWidget.Editor<!Adb.PortForwardingRule>} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -174,8 +176,9 @@ */ function addressValidator(rule, index, input) { const match = input.value.trim().match(/^([a-zA-Z0-9\.\-_]+):(\d+)$/); - if (!match) + if (!match) { return {valid: false}; + } const port = parseInt(match[2], 10); return {valid: port <= 65535}; }
diff --git a/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js b/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js index 10afb889..16de289 100644 --- a/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js +++ b/third_party/blink/renderer/devtools/front_end/node_main/NodeMain.js
@@ -53,8 +53,9 @@ for (const address of config.networkDiscoveryConfig) { const parts = address.split(':'); const port = parseInt(parts[1], 10); - if (parts[0] && port) + if (parts[0] && port) { locations.push({host: parts[0], port: port}); + } } this._targetAgent.setRemoteLocations(locations); } @@ -66,8 +67,9 @@ InspectorFrontendHost.events.removeEventListener( Host.InspectorFrontendHostAPI.Events.DevicesDiscoveryConfigChanged, this._devicesDiscoveryConfigChanged, this); - for (const sessionId of this._childTargets.keys()) + for (const sessionId of this._childTargets.keys()) { this.detachedFromTarget(sessionId, undefined); + } } /** @@ -75,8 +77,9 @@ * @param {!Protocol.Target.TargetInfo} targetInfo */ targetCreated(targetInfo) { - if (targetInfo.type === 'node' && !targetInfo.attached) + if (targetInfo.type === 'node' && !targetInfo.attached) { this._targetAgent.attachToTarget(targetInfo.targetId, false /* flatten */); + } } /** @@ -129,8 +132,9 @@ receivedMessageFromTarget(sessionId, message, childTargetId) { const connection = this._childConnections.get(sessionId); const onMessage = connection ? connection._onMessage : null; - if (onMessage) + if (onMessage) { onMessage.call(null, message); + } } }; @@ -178,8 +182,9 @@ * @return {!Promise} */ disconnect() { - if (this._onDisconnect) + if (this._onDisconnect) { this._onDisconnect.call(null, 'force disconnect'); + } this._onDisconnect = null; this._onMessage = null; return this._targetAgent.detachFromTarget(this._sessionId);
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js b/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js index 6a561df7..fbf8f333 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/CustomPreviewComponent.js
@@ -50,8 +50,9 @@ * @return {!Node} */ _renderJSONMLTag(jsonML) { - if (!Array.isArray(jsonML)) + if (!Array.isArray(jsonML)) { return createTextNode(jsonML + ''); + } const array = /** @type {!Array.<*>} */ (jsonML); return array[0] === 'object' ? this._layoutObjectTag(array) : this._renderElement(array); @@ -73,8 +74,9 @@ const attributes = object.shift(); for (const key in attributes) { const value = attributes[key]; - if ((key !== 'style') || (typeof value !== 'string')) + if ((key !== 'style') || (typeof value !== 'string')) { continue; + } element.setAttribute(key, value); } @@ -93,8 +95,9 @@ const attributes = objectTag.shift(); const remoteObject = this._object.runtimeModel().createRemoteObject( /** @type {!Protocol.Runtime.RemoteObject} */ (attributes)); - if (remoteObject.customPreview()) + if (remoteObject.customPreview()) { return (new ObjectUI.CustomPreviewSection(remoteObject)).element(); + } const sectionElement = ObjectUI.ObjectPropertiesSection.defaultObjectPresentation(remoteObject); sectionElement.classList.toggle('custom-expandable-section-standard-section', remoteObject.hasChildren); @@ -106,8 +109,9 @@ * @param {!Array.<*>} jsonMLTags */ _appendJsonMLTags(parentElement, jsonMLTags) { - for (let i = 0; i < jsonMLTags.length; ++i) + for (let i = 0; i < jsonMLTags.length; ++i) { parentElement.appendChild(this._renderJSONMLTag(jsonMLTags[i])); + } } /** @@ -115,20 +119,22 @@ */ _onClick(event) { event.consume(true); - if (this._cachedContent) + if (this._cachedContent) { this._toggleExpand(); - else + } else { this._loadBody(); + } } _toggleExpand() { this._expanded = !this._expanded; this._header.classList.toggle('expanded', this._expanded); this._cachedContent.classList.toggle('hidden', !this._expanded); - if (this._expanded) + if (this._expanded) { this._expandIcon.setIconType('smallicon-triangle-down'); - else + } else { this._expandIcon.setIconType('smallicon-triangle-right'); + } } _loadBody() { @@ -147,26 +153,30 @@ * @throws {string} error message */ function substituteObjectTagsInCustomPreview(jsonMLObject) { - if (!jsonMLObject || (typeof jsonMLObject !== 'object') || (typeof jsonMLObject.splice !== 'function')) + if (!jsonMLObject || (typeof jsonMLObject !== 'object') || (typeof jsonMLObject.splice !== 'function')) { return; + } const obj = jsonMLObject.length; - if (!(typeof obj === 'number' && obj >>> 0 === obj && (obj > 0 || 1 / obj > 0))) + if (!(typeof obj === 'number' && obj >>> 0 === obj && (obj > 0 || 1 / obj > 0))) { return; + } let startIndex = 1; if (jsonMLObject[0] === 'object') { const attributes = jsonMLObject[1]; const originObject = attributes['object']; const config = attributes['config']; - if (typeof originObject === 'undefined') + if (typeof originObject === 'undefined') { throw 'Illegal format: obligatory attribute "object" isn\'t specified'; + } jsonMLObject[1] = bindRemoteObject(originObject, config); startIndex = 2; } - for (let i = startIndex; i < jsonMLObject.length; ++i) + for (let i = startIndex; i < jsonMLObject.length; ++i) { substituteObjectTagsInCustomPreview(jsonMLObject[i]); + } } try { @@ -183,8 +193,9 @@ if (customPreview.bindRemoteObjectFunctionId && customPreview.formatterObjectId) { // Support for V8 version < 7.3. const args = [{objectId: customPreview.bindRemoteObjectFunctionId}, {objectId: customPreview.formatterObjectId}]; - if (customPreview.configObjectId) + if (customPreview.configObjectId) { args.push({objectId: customPreview.configObjectId}); + } this._object.callFunctionJSON(load, args).then(onBodyLoaded.bind(this)); } else if (customPreview.bodyGetterId) { this._object.callFunctionJSON(bodyGetter => bodyGetter(), [{objectId: customPreview.bodyGetterId}]) @@ -196,8 +207,9 @@ * @this {ObjectUI.CustomPreviewSection} */ function onBodyLoaded(bodyJsonML) { - if (!bodyJsonML) + if (!bodyJsonML) { return; + } this._cachedContent = this._renderJSONMLTag(bodyJsonML); this._sectionElement.appendChild(this._cachedContent); @@ -224,8 +236,9 @@ expandIfPossible() { if ((this._object.customPreview().hasBody || this._object.customPreview().bodyGetterId) && - this._customPreviewSection) + this._customPreviewSection) { this._customPreviewSection._loadBody(); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptAutocomplete.js b/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptAutocomplete.js index b5c644e..7d11587f 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptAutocomplete.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptAutocomplete.js
@@ -38,11 +38,13 @@ */ async argumentsHint(fullText) { const functionCall = await Formatter.formatterWorkerPool().findLastFunctionCall(fullText); - if (!functionCall) + if (!functionCall) { return null; + } const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return null; + } const result = await executionContext.evaluate( { expression: functionCall.baseExpression, @@ -76,8 +78,9 @@ return (result && !result.exceptionDetails && result.object) ? result.object : null; }, functionCall.functionName); executionContext.runtimeModel.releaseObjectGroup('argumentsHint'); - if (!args.length || (args.length === 1 && !args[0].length)) + if (!args.length || (args.length === 1 && !args[0].length)) { return null; + } return {args, argumentIndex: functionCall.argumentIndex}; } @@ -89,8 +92,9 @@ */ async _argumentsForFunction(functionObject, receiverObjGetter, parsedFunctionName) { const description = functionObject.description; - if (!description.endsWith('{ [native code] }')) + if (!description.endsWith('{ [native code] }')) { return [await Formatter.formatterWorkerPool().argumentsList(description)]; + } // Check if this is a bound function. if (description === 'function () { [native code] }') { @@ -106,10 +110,11 @@ const clippedArgs = []; for (const signature of originalSignatures) { const restIndex = signature.slice(0, boundArgsLength).findIndex(arg => arg.startsWith('...')); - if (restIndex !== -1) + if (restIndex !== -1) { clippedArgs.push(signature.slice(restIndex)); - else + } else { clippedArgs.push(signature.slice(boundArgsLength)); + } } return clippedArgs; } @@ -117,22 +122,26 @@ const javaScriptMetadata = await self.runtime.extension(Common.JavaScriptMetadata).instance(); const name = /^function ([^(]*)\(/.exec(description)[1] || parsedFunctionName; - if (!name) + if (!name) { return []; + } const uniqueSignatures = javaScriptMetadata.signaturesForNativeFunction(name); - if (uniqueSignatures) + if (uniqueSignatures) { return uniqueSignatures; + } const receiverObj = await receiverObjGetter(); const className = receiverObj.className; - if (javaScriptMetadata.signaturesForInstanceMethod(name, className)) + if (javaScriptMetadata.signaturesForInstanceMethod(name, className)) { return javaScriptMetadata.signaturesForInstanceMethod(name, className); + } // Check for static methods on a constructor. if (receiverObj.type === 'function' && receiverObj.description.endsWith('{ [native code] }')) { const receiverName = /^function ([^(]*)\(/.exec(receiverObj.description)[1]; const staticSignatures = javaScriptMetadata.signaturesForStaticMethod(name, receiverName); - if (staticSignatures) + if (staticSignatures) { return staticSignatures; + } } @@ -153,16 +162,18 @@ protoNames = await receiverObj.callFunctionJSON(function() { const result = []; for (let object = this; object; object = Object.getPrototypeOf(object)) { - if (typeof object === 'object' && object.constructor && object.constructor.name) + if (typeof object === 'object' && object.constructor && object.constructor.name) { result[result.length] = object.constructor.name; + } } return result; }, []); } for (const proto of protoNames) { const instanceSignatures = javaScriptMetadata.signaturesForInstanceMethod(name, proto); - if (instanceSignatures) + if (instanceSignatures) { return instanceSignatures; + } } return []; } @@ -175,12 +186,14 @@ async _mapCompletions(text, query) { const mapMatch = text.match(/\.\s*(get|set|delete)\s*\(\s*$/); const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext || !mapMatch) + if (!executionContext || !mapMatch) { return []; + } const expression = await Formatter.formatterWorkerPool().findLastExpression(text.substring(0, mapMatch.index)); - if (!expression) + if (!expression) { return []; + } const result = await executionContext.evaluate( { @@ -194,13 +207,15 @@ timeout: expression.possibleSideEffects ? 500 : undefined }, /* userGesture */ false, /* awaitPromise */ false); - if (result.error || !!result.exceptionDetails || result.object.subtype !== 'map') + if (result.error || !!result.exceptionDetails || result.object.subtype !== 'map') { return []; + } const properties = await result.object.getOwnProperties(false); const internalProperties = properties.internalProperties || []; const entriesProperty = internalProperties.find(property => property.name === '[[Entries]]'); - if (!entriesProperty) + if (!entriesProperty) { return []; + } const keysObj = await entriesProperty.value.callFunctionJSON(getEntries); executionContext.runtimeModel.releaseObjectGroup('mapCompletion'); return gotKeys(Object.keys(keysObj)); @@ -213,8 +228,9 @@ function getEntries() { const result = {__proto__: null}; for (let i = 0; i < this.length; i++) { - if (typeof this[i].key === 'string') + if (typeof this[i].key === 'string') { result[this[i].key] = true; + } } return result; } @@ -229,37 +245,43 @@ const caseSensitiveAnywhere = []; const caseInsensitiveAnywhere = []; let quoteChar = '"'; - if (query.startsWith('\'')) + if (query.startsWith('\'')) { quoteChar = '\''; + } let endChar = ')'; - if (mapMatch[0].indexOf('set') !== -1) + if (mapMatch[0].indexOf('set') !== -1) { endChar = ', '; + } const sorter = rawKeys.length < 1000 ? String.naturalOrderComparator : undefined; const keys = rawKeys.sort(sorter).map(key => quoteChar + key + quoteChar); for (const key of keys) { - if (key.length < query.length) + if (key.length < query.length) { continue; - if (query.length && key.toLowerCase().indexOf(query.toLowerCase()) === -1) + } + if (query.length && key.toLowerCase().indexOf(query.toLowerCase()) === -1) { continue; + } // Substitute actual newlines with newline characters. @see crbug.com/498421 const title = key.split('\n').join('\\n'); const text = title + endChar; - if (key.startsWith(query)) + if (key.startsWith(query)) { caseSensitivePrefix.push({text: text, title: title, priority: 4}); - else if (key.toLowerCase().startsWith(query.toLowerCase())) + } else if (key.toLowerCase().startsWith(query.toLowerCase())) { caseInsensitivePrefix.push({text: text, title: title, priority: 3}); - else if (key.indexOf(query) !== -1) + } else if (key.indexOf(query) !== -1) { caseSensitiveAnywhere.push({text: text, title: title, priority: 2}); - else + } else { caseInsensitiveAnywhere.push({text: text, title: title, priority: 1}); + } } const suggestions = caseSensitivePrefix.concat(caseInsensitivePrefix, caseSensitiveAnywhere, caseInsensitiveAnywhere); - if (suggestions.length) + if (suggestions.length) { suggestions[0].subtitle = Common.UIString('Keys'); + } return suggestions; } } @@ -272,14 +294,17 @@ */ async _completionsForExpression(fullText, query, force) { const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return []; + } let expression; - if (fullText.endsWith('.') || fullText.endsWith('[')) + if (fullText.endsWith('.') || fullText.endsWith('[')) { expression = await Formatter.formatterWorkerPool().findLastExpression(fullText.substring(0, fullText.length - 1)); + } if (!expression) { - if (fullText.endsWith('.')) + if (fullText.endsWith('.')) { return []; + } expression = {baseExpression: '', possibleSideEffects: false}; } const needsNoSideEffects = expression.possibleSideEffects; @@ -290,12 +315,14 @@ const bracketNotation = !!expressionString && fullText.endsWith('['); // User is entering float value, do not suggest anything. - if ((expressionString && !isNaN(expressionString)) || (!expressionString && query && !isNaN(query))) + if ((expressionString && !isNaN(expressionString)) || (!expressionString && query && !isNaN(query))) { return []; + } - if (!query && !expressionString && !force) + if (!query && !expressionString && !force) { return []; + } const selectedFrame = executionContext.debuggerModel.selectedCallFrame(); let completionGroups; const TEN_SECONDS = 10000; @@ -332,8 +359,9 @@ * @return {!Promise<!Array<!ObjectUI.JavaScriptAutocomplete.CompletionGroup>>} */ async function completionsOnGlobal(result) { - if (result.error || !!result.exceptionDetails || !result.object) + if (result.error || !!result.exceptionDetails || !result.object) { return []; + } let object = result.object; while (object && object.type === 'object' && object.subtype === 'proxy') { @@ -342,8 +370,9 @@ const target = internalProperties.find(property => property.name === '[[Target]]'); object = target ? target.value : null; } - if (!object) + if (!object) { return []; + } let completions = []; if (object.type === 'object' || object.type === 'function') { completions = @@ -362,23 +391,26 @@ }, /* userGesture */ false, /* awaitPromise */ false); - if (evaluateResult.object && !evaluateResult.exceptionDetails) + if (evaluateResult.object && !evaluateResult.exceptionDetails) { completions = /** @type {!Iterable} */ (evaluateResult.object.value) || []; + } } executionContext.runtimeModel.releaseObjectGroup('completion'); if (!expressionString) { const globalNames = await executionContext.globalLexicalScopeNames(); // Merge lexical scope names with first completion group on global object: let a and let b should be in the same group. - if (completions.length) + if (completions.length) { completions[0].items = completions[0].items.concat(globalNames); - else + } else { completions.push({items: globalNames.sort(), title: Common.UIString('Lexical scope variables')}); + } } for (const group of completions) { - for (let i = 0; i < group.items.length; i++) + for (let i = 0; i < group.items.length; i++) { group.items[i] = group.items[i].replace(/\n/g, '\\n'); + } group.items.sort(group.items.length < 1000 ? this._itemComparator : undefined); } @@ -393,29 +425,33 @@ */ function getCompletions(type) { let object; - if (type === 'string') + if (type === 'string') { object = new String(''); - else if (type === 'number') + } else if (type === 'number') { object = new Number(0); + } // Object-wrapped BigInts cannot be constructed via `new BigInt`. - else if (type === 'bigint') + else if (type === 'bigint') { object = Object(BigInt(0)); - else if (type === 'boolean') + } else if (type === 'boolean') { object = new Boolean(false); - else + } else { object = this; + } const result = []; try { for (let o = object; o; o = Object.getPrototypeOf(o)) { - if ((type === 'array' || type === 'typedarray') && o === object && o.length > 9999) + if ((type === 'array' || type === 'typedarray') && o === object && o.length > 9999) { continue; + } const group = {items: [], __proto__: null}; try { if (typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, 'constructor') && o.constructor && - o.constructor.name) + o.constructor.name) { group.title = o.constructor.name; + } } catch (ee) { // we could break upon cross origin check. } @@ -424,8 +460,9 @@ const isArray = Array.isArray(o); for (let i = 0; i < names.length && group.items.length < 10000; ++i) { // Skip array elements indexes. - if (isArray && /^[0-9]/.test(names[i])) + if (isArray && /^[0-9]/.test(names[i])) { continue; + } group.items[group.items.length] = names[i]; } } @@ -450,8 +487,9 @@ } const fullScopes = await Promise.all(groupPromises); executionContext.runtimeModel.releaseObjectGroup('completion'); - for (const scope of fullScopes) + for (const scope of fullScopes) { result.push({title: scope.name, items: scope.properties.map(property => property.name).sort()}); + } return result; } } @@ -465,8 +503,9 @@ * @return {!UI.SuggestBox.Suggestions} */ _receivedPropertyNames(propertyGroups, dotNotation, bracketNotation, expressionString, query) { - if (!propertyGroups) + if (!propertyGroups) { return []; + } const includeCommandLineAPI = (!dotNotation && !bracketNotation); if (includeCommandLineAPI) { const commandLineAPI = [ @@ -542,32 +581,38 @@ for (let i = 0; i < group.items.length; i++) { let property = group.items[i]; // Assume that all non-ASCII characters are letters and thus can be used as part of identifier. - if (!bracketNotation && !regex.test(property)) + if (!bracketNotation && !regex.test(property)) { continue; + } if (bracketNotation) { - if (!/^[0-9]+$/.test(property)) + if (!/^[0-9]+$/.test(property)) { property = quoteUsed + property.escapeCharacters(quoteUsed + '\\') + quoteUsed; + } property += ']'; } - if (allProperties.has(property)) + if (allProperties.has(property)) { continue; + } - if (property.length < query.length) + if (property.length < query.length) { continue; + } const lowerCaseProperty = property.toLowerCase(); - if (query.length && lowerCaseProperty.indexOf(lowerCaseQuery) === -1) + if (query.length && lowerCaseProperty.indexOf(lowerCaseQuery) === -1) { continue; + } allProperties.add(property); - if (property.startsWith(query)) + if (property.startsWith(query)) { caseSensitivePrefix.push({text: property, priority: property === query ? 5 : 4}); - else if (lowerCaseProperty.startsWith(lowerCaseQuery)) + } else if (lowerCaseProperty.startsWith(lowerCaseQuery)) { caseInsensitivePrefix.push({text: property, priority: 3}); - else if (property.indexOf(query) !== -1) + } else if (property.indexOf(query) !== -1) { caseSensitiveAnywhere.push({text: property, priority: 2}); - else + } else { caseInsensitiveAnywhere.push({text: property, priority: 1}); + } } const structuredGroup = caseSensitivePrefix.concat(caseInsensitivePrefix, caseSensitiveAnywhere, caseInsensitiveAnywhere); @@ -577,8 +622,9 @@ } result = result.concat(structuredGroup); result.forEach(item => { - if (item.text.endsWith(']')) + if (item.text.endsWith(']')) { item.title = item.text.substring(0, item.text.length - 1); + } }); } return result; @@ -592,10 +638,12 @@ _itemComparator(a, b) { const aStartsWithUnderscore = a.startsWith('_'); const bStartsWithUnderscore = b.startsWith('_'); - if (aStartsWithUnderscore && !bStartsWithUnderscore) + if (aStartsWithUnderscore && !bStartsWithUnderscore) { return 1; - if (bStartsWithUnderscore && !aStartsWithUnderscore) + } + if (bStartsWithUnderscore && !aStartsWithUnderscore) { return -1; + } return String.naturalOrderComparator(a, b); } @@ -605,12 +653,14 @@ */ static async isExpressionComplete(expression) { const currentExecutionContext = UI.context.flavor(SDK.ExecutionContext); - if (!currentExecutionContext) + if (!currentExecutionContext) { return true; + } const result = await currentExecutionContext.runtimeModel.compileScript(expression, '', false, currentExecutionContext.id); - if (!result.exceptionDetails) + if (!result.exceptionDetails) { return true; + } const description = result.exceptionDetails.exception.description; return !description.startsWith('SyntaxError: Unexpected end of input') && !description.startsWith('SyntaxError: Unterminated template literal'); @@ -650,14 +700,16 @@ */ _substituteRange(lineNumber, columnNumber) { const token = this._editor.tokenAtTextPosition(lineNumber, columnNumber); - if (token && token.type === 'js-string') + if (token && token.type === 'js-string') { return new TextUtils.TextRange(lineNumber, token.startColumn, lineNumber, columnNumber); + } const lineText = this._editor.line(lineNumber); let index; for (index = columnNumber - 1; index >= 0; index--) { - if (' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index)) !== -1) + if (' =:[({;,!+-*/&|^<>.\t\r\n'.indexOf(lineText.charAt(index)) !== -1) { break; + } } return new TextUtils.TextRange(lineNumber, index + 1, lineNumber, columnNumber); } @@ -675,19 +727,23 @@ if (token) { const excludedTokens = new Set(['js-comment', 'js-string-2', 'js-def']); const trimmedBefore = before.trim(); - if (!trimmedBefore.endsWith('[') && !trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/)) + if (!trimmedBefore.endsWith('[') && !trimmedBefore.match(/\.\s*(get|set|delete)\s*\(\s*$/)) { excludedTokens.add('js-string'); - if (!trimmedBefore.endsWith('.')) + } + if (!trimmedBefore.endsWith('.')) { excludedTokens.add('js-property'); - if (excludedTokens.has(token.type)) + } + if (excludedTokens.has(token.type)) { return []; + } } const queryAndAfter = this._editor.line(queryRange.startLine).substring(queryRange.startColumn); const words = await ObjectUI.javaScriptAutocomplete.completionsForTextInCurrentContext(before, query, force); if (!force && queryAndAfter && queryAndAfter !== query && - words.some(word => queryAndAfter.startsWith(word.text) && query.length !== word.text.length)) + words.some(word => queryAndAfter.startsWith(word.text) && query.length !== word.text.length)) { return []; + } return words; } @@ -699,19 +755,22 @@ async _tooltipCallback(lineNumber, columnNumber) { const before = this._editor.text(new TextUtils.TextRange(0, 0, lineNumber, columnNumber)); const result = await ObjectUI.javaScriptAutocomplete.argumentsHint(before); - if (!result) + if (!result) { return null; + } const argumentIndex = result.argumentIndex; const tooltip = createElement('div'); for (const args of result.args) { const argumentsElement = createElement('span'); for (let i = 0; i < args.length; i++) { - if (i === argumentIndex || (i < argumentIndex && args[i].startsWith('...'))) + if (i === argumentIndex || (i < argumentIndex && args[i].startsWith('...'))) { argumentsElement.appendChild(UI.html`<b>${args[i]}</b>`); - else + } else { argumentsElement.createTextChild(args[i]); - if (i < args.length - 1) + } + if (i < args.length - 1) { argumentsElement.createTextChild(', '); + } } tooltip.appendChild(UI.html`<div class='source-code'>\u0192(${argumentsElement})</div>`); }
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptREPL.js b/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptREPL.js index 60adc898..dbe394c 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptREPL.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/JavaScriptREPL.js
@@ -9,8 +9,9 @@ */ static wrapObjectLiteral(code) { // Only parenthesize what appears to be an object literal. - if (!(/^\s*\{/.test(code) && /\}\s*$/.test(code))) + if (!(/^\s*\{/.test(code) && /\}\s*$/.test(code))) { return code; + } const parse = (async () => 0).constructor; try { @@ -53,8 +54,9 @@ static async evaluateAndBuildPreview(text, throwOnSideEffect, timeout, allowErrors, objectGroup) { const executionContext = UI.context.flavor(SDK.ExecutionContext); const isTextLong = text.length > ObjectUI.JavaScriptREPL._MaxLengthForEvaluation; - if (!text || !executionContext || (throwOnSideEffect && isTextLong)) + if (!text || !executionContext || (throwOnSideEffect && isTextLong)) { return {preview: createDocumentFragment(), result: null}; + } const wrappedResult = await ObjectUI.JavaScriptREPL.preprocessExpression(text); const options = { @@ -63,7 +65,8 @@ includeCommandLineAPI: true, throwOnSideEffect: throwOnSideEffect, timeout: timeout, - objectGroup: objectGroup + objectGroup: objectGroup, + disableBreaks: true }; const result = await executionContext.evaluate( options, false /* userGesture */, wrappedResult.preprocessed /* awaitPromise */); @@ -78,13 +81,15 @@ */ static _buildEvaluationPreview(result, allowErrors) { const fragment = createDocumentFragment(); - if (result.error) + if (result.error) { return fragment; + } if (result.exceptionDetails && result.exceptionDetails.exception && result.exceptionDetails.exception.description) { const exception = result.exceptionDetails.exception.description; - if (exception.startsWith('TypeError: ') || allowErrors) + if (exception.startsWith('TypeError: ') || allowErrors) { fragment.createChild('span').textContent = result.exceptionDetails.text + ' ' + exception; + } return fragment; }
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPopoverHelper.js b/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPopoverHelper.js index 29c68f1..18a69cf 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPopoverHelper.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPopoverHelper.js
@@ -39,10 +39,12 @@ } dispose() { - if (this._resultHighlightedAsDOM) + if (this._resultHighlightedAsDOM) { SDK.OverlayModel.hideDOMNodeHighlight(); - if (this._linkifier) + } + if (this._linkifier) { this._linkifier.dispose(); + } } /** @@ -89,10 +91,11 @@ const valueElement = popoverContentElement.createChild('span', 'monospace object-value-' + result.type); valueElement.style.whiteSpace = 'pre'; - if (result.type === 'string') + if (result.type === 'string') { valueElement.createTextChildren(`"${description}"`); - else if (result.type !== 'function') + } else if (result.type !== 'function') { valueElement.textContent = description; + } if (result.type !== 'function') { popover.contentElement.appendChild(popoverContentElement); @@ -101,8 +104,9 @@ ObjectUI.ObjectPropertiesSection.formatObjectAsFunction(result, valueElement, true); const response = await result.debuggerModel().functionDetailsPromise(result); - if (!response) + if (!response) { return null; + } const container = createElementWithClass('div', 'object-popover-container'); const title = container.createChild('div', 'function-popover-title source-code');
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js b/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js index 432ef65..b77eb97 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/ObjectPropertiesSection.js
@@ -41,8 +41,9 @@ super(); this._object = object; this._editable = true; - if (!showOverflow) + if (!showOverflow) { this.hideOverflow(); + } this.setFocusable(true); this.setShowSelectionOnKeyboardFocus(true); this._objectTreeElement = new ObjectUI.ObjectPropertiesSection.RootElement( @@ -55,8 +56,9 @@ this.titleElement = title; this.element.appendChild(title); } - if (!this.titleElement.hasAttribute('tabIndex')) + if (!this.titleElement.hasAttribute('tabIndex')) { this.titleElement.tabIndex = -1; + } this.element._section = this; this.registerRequiredCSS('object_ui/objectValue.css'); @@ -76,15 +78,18 @@ const shadowRoot = UI.createShadowRootWithCoreStyles(componentRoot, 'object_ui/objectValue.css'); shadowRoot.appendChild( ObjectUI.ObjectPropertiesSection.createValueElement(object, false /* wasThrown */, true /* showPreview */)); - if (!object.hasChildren) + if (!object.hasChildren) { return componentRoot; + } const objectPropertiesSection = new ObjectUI.ObjectPropertiesSection(object, componentRoot, linkifier); objectPropertiesSection.editable = false; - if (skipProto) + if (skipProto) { objectPropertiesSection.skipProto(); - if (readOnly) + } + if (readOnly) { objectPropertiesSection.setEditable(false); + } return objectPropertiesSection.element; } @@ -97,26 +102,36 @@ static CompareProperties(propertyA, propertyB) { const a = propertyA.name; const b = propertyB.name; - if (a === '__proto__') + if (a === '__proto__') { return 1; - if (b === '__proto__') + } + if (b === '__proto__') { return -1; - if (!propertyA.enumerable && propertyB.enumerable) + } + if (!propertyA.enumerable && propertyB.enumerable) { return 1; - if (!propertyB.enumerable && propertyA.enumerable) + } + if (!propertyB.enumerable && propertyA.enumerable) { return -1; - if (a.startsWith('_') && !b.startsWith('_')) + } + if (a.startsWith('_') && !b.startsWith('_')) { return 1; - if (b.startsWith('_') && !a.startsWith('_')) + } + if (b.startsWith('_') && !a.startsWith('_')) { return -1; - if (propertyA.symbol && !propertyB.symbol) + } + if (propertyA.symbol && !propertyB.symbol) { return 1; - if (propertyB.symbol && !propertyA.symbol) + } + if (propertyB.symbol && !propertyA.symbol) { return -1; - if (propertyA.private && !propertyB.private) + } + if (propertyA.private && !propertyB.private) { return 1; - if (propertyB.private && !propertyA.private) + } + if (propertyB.private && !propertyA.private) { return -1; + } return String.naturalOrderComparator(a, b); } @@ -126,10 +141,12 @@ * @return {!Element} */ static createNameElement(name, isPrivate) { - if (name === null) + if (name === null) { return UI.html`<span class="name"></span>`; - if (/^\s|\s$|^$|\n/.test(name)) + } + if (/^\s|\s$|^$|\n/.test(name)) { return UI.html`<span class="name">"${name.replace(/\n/g, '\u21B5')}"</span>`; + } if (isPrivate) { return UI.html`<span class="name"> <span class="private-property-hash">${name[0]}</span>${name.substring(1)} @@ -167,8 +184,9 @@ textAfterPrefix = text.substring('class'.length); const classNameMatch = /^[^{\s]+/.exec(textAfterPrefix.trim()); let className = defaultName; - if (classNameMatch) + if (classNameMatch) { className = classNameMatch[0].trim() || defaultName; + } addElements('class', textAfterPrefix, className); } else if (asyncMatch) { textAfterPrefix = text.substring(asyncMatch[1].length); @@ -185,10 +203,11 @@ } else if (isArrow) { const maxArrowFunctionCharacterLength = 60; let abbreviation = text; - if (defaultName) + if (defaultName) { abbreviation = defaultName + '()'; - else if (text.length > maxArrowFunctionCharacterLength) + } else if (text.length > maxArrowFunctionCharacterLength) { abbreviation = text.substring(0, firstArrowIndex + 2) + ' {\u2026}'; + } addElements('', text, abbreviation); } else { addElements('\u0192', text, nameAndArguments(text)); @@ -218,12 +237,14 @@ */ function addElements(prefix, body, abbreviation) { const maxFunctionBodyLength = 200; - if (prefix.length) + if (prefix.length) { valueElement.createChild('span', 'object-value-function-prefix').textContent = prefix + ' '; - if (includePreview) + } + if (includePreview) { valueElement.createTextChild(body.trim().trimEndWithMaxLength(maxFunctionBodyLength)); - else + } else { valueElement.createTextChild(abbreviation.replace(/\n/g, ' ')); + } } } @@ -260,8 +281,9 @@ if (type === 'object' && subtype === 'internal#location') { const rawLocation = value.debuggerModel().createRawLocationByScriptId( value.value.scriptId, value.value.lineNumber, value.value.columnNumber); - if (rawLocation && linkifier) + if (rawLocation && linkifier) { return linkifier.linkifyRawLocation(rawLocation, ''); + } valueElement = createUnknownInternalLocationElement(); } else if (type === 'string' && typeof description === 'string') { valueElement = createStringElement(); @@ -272,7 +294,9 @@ } else if (type === 'number' && description && description.indexOf('e') !== -1) { valueElement = createNumberWithExponentElement(); if (parentElement) // FIXME: do it in the caller. + { parentElement.classList.add('hbox'); + } } else { valueElement = createElementWithClass('span', 'object-value-' + (subtype || type)); valueElement.title = description || ''; @@ -311,10 +335,11 @@ const valueElement = createElementWithClass('span', 'object-value-string'); const text = description.replace(/\n/g, '\u21B5'); valueElement.createChild('span', 'object-value-string-quote').textContent = '"'; - if (description.length > ObjectUI.ObjectPropertiesSection._maxRenderableStringLength) + if (description.length > ObjectUI.ObjectPropertiesSection._maxRenderableStringLength) { valueElement.appendChild(UI.createExpandableText(text, 50)); - else + } else { valueElement.createTextChild(text); + } valueElement.createChild('span', 'object-value-string-quote').textContent = '"'; valueElement.title = description || ''; return valueElement; @@ -370,8 +395,9 @@ // The includePreview flag is false for formats such as console.dir(). let defaultName = includePreview ? '' : 'anonymous'; - if (response && response.functionName) + if (response && response.functionName) { defaultName = response.functionName; + } const valueElement = ObjectUI.ObjectPropertiesSection.valueElementForFunctionDescription( func.description, includePreview, defaultName); element.appendChild(valueElement); @@ -384,8 +410,9 @@ * @return {boolean} */ static _isDisplayableProperty(property, parentProperty) { - if (!parentProperty || !parentProperty.synthetic) + if (!parentProperty || !parentProperty.synthetic) { return true; + } const name = property.name; const useless = (parentProperty.name === '[[Entries]]' && (name === 'length' || name === '__proto__')); return !useless; @@ -474,16 +501,18 @@ * @override */ onexpand() { - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.element.classList.add('expanded'); + } } /** * @override */ oncollapse() { - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.element.classList.remove('expanded'); + } } /** @@ -546,19 +575,22 @@ } let allProperties; - if (flattenProtoChain) + if (flattenProtoChain) { allProperties = await value.getAllProperties(false /* accessorPropertiesOnly */, true /* generatePreview */); - else + } else { allProperties = await SDK.RemoteObject.loadFromObjectPerProto(value, true /* generatePreview */); + } const properties = allProperties.properties; const internalProperties = allProperties.internalProperties; treeElement.removeChildren(); - if (!properties) + if (!properties) { return; + } extraProperties = extraProperties || []; - for (let i = 0; i < extraProperties.length; ++i) + for (let i = 0; i < extraProperties.length; ++i) { properties.push(extraProperties[i]); + } ObjectUI.ObjectPropertyTreeElement.populateWithProperties( treeElement, properties, internalProperties, skipProto, targetValue || value, linkifier, emptyPlaceholder); @@ -597,8 +629,9 @@ for (let i = 0; i < properties.length; ++i) { const property = properties[i]; property.parentObject = value; - if (!ObjectUI.ObjectPropertiesSection._isDisplayableProperty(property, treeNode.property)) + if (!ObjectUI.ObjectPropertiesSection._isDisplayableProperty(property, treeNode.property)) { continue; + } if (property.name === '__proto__' && !property.isAccessorProperty()) { protoProperty = property; continue; @@ -615,19 +648,23 @@ tailProperties.push(setterProperty); } const canShowProperty = property.getter || !property.isAccessorProperty(); - if (canShowProperty && property.name !== '__proto__') + if (canShowProperty && property.name !== '__proto__') { treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(property, linkifier)); + } } - for (let i = 0; i < tailProperties.length; ++i) + for (let i = 0; i < tailProperties.length; ++i) { treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(tailProperties[i], linkifier)); - if (!skipProto && protoProperty) + } + if (!skipProto && protoProperty) { treeNode.appendChild(new ObjectUI.ObjectPropertyTreeElement(protoProperty, linkifier)); + } for (const property of internalProperties) { property.parentObject = value; const treeElement = new ObjectUI.ObjectPropertyTreeElement(property, linkifier); - if (property.name === '[[Entries]]') + if (property.name === '[[Entries]]') { continue; + } treeNode.appendChild(treeElement); } @@ -639,8 +676,9 @@ * @param {?string=} emptyPlaceholder */ static _appendEmptyPlaceholderIfNeeded(treeNode, emptyPlaceholder) { - if (treeNode.childCount()) + if (treeNode.childCount()) { return; + } const title = createElementWithClass('div', 'gray-info-message'); title.textContent = emptyPlaceholder || Common.UIString('No properties'); const infoElement = new UI.TreeElement(title); @@ -657,8 +695,9 @@ const rootElement = createElement('span'); const element = rootElement.createChild('span'); element.textContent = Common.UIString('(...)'); - if (!object) + if (!object) { return rootElement; + } element.classList.add('object-value-calculate-value-button'); element.title = Common.UIString('Invoke property getter'); element.addEventListener('click', onInvokeGetterClick, false); @@ -676,8 +715,9 @@ function invokeGetter(arrayStr) { let result = this; const properties = JSON.parse(arrayStr); - for (let i = 0, n = properties.length; i < n; ++i) + for (let i = 0, n = properties.length; i < n; ++i) { result = result[properties[i]]; + } return result; } @@ -691,14 +731,16 @@ */ setSearchRegex(regex, additionalCssClassName) { let cssClasses = UI.highlightedSearchResultClassName; - if (additionalCssClassName) + if (additionalCssClassName) { cssClasses += ' ' + additionalCssClassName; + } this.revertHighlightChanges(); this._applySearch(regex, this.nameElement, cssClasses); const valueType = this.property.value.type; - if (valueType !== 'object') + if (valueType !== 'object') { this._applySearch(regex, this.valueElement, cssClasses); + } return !!this._highlightChanges.length; } @@ -717,8 +759,9 @@ ranges.push(new TextUtils.SourceRange(match.index, match[0].length)); match = regex.exec(content); } - if (ranges.length) + if (ranges.length) { UI.highlightRangesWithStyleClass(element, ranges, cssClassName, this._highlightChanges); + } } revertHighlightChanges() { @@ -746,8 +789,9 @@ ondblclick(event) { const inEditableElement = event.target.isSelfOrDescendant(this.valueElement) || (this.expandedValueElement && event.target.isSelfOrDescendant(this.expandedValueElement)); - if (!this.property.value.customPreview() && inEditableElement && (this.property.writable || this.property.setter)) + if (!this.property.value.customPreview() && inEditableElement && (this.property.writable || this.property.setter)) { this._startEditing(); + } return false; } @@ -777,12 +821,14 @@ * @param {boolean} value */ _showExpandedValueElement(value) { - if (!this.expandedValueElement) + if (!this.expandedValueElement) { return; - if (value) + } + if (value) { this._rowContainer.replaceChild(this.expandedValueElement, this.valueElement); - else + } else { this._rowContainer.replaceChild(this.valueElement, this.expandedValueElement); + } } /** @@ -792,14 +838,16 @@ _createExpandedValueElement(value) { const needsAlternateValue = value.hasChildren && !value.customPreview() && value.subtype !== 'node' && value.type !== 'function' && (value.type !== 'object' || value.preview); - if (!needsAlternateValue) + if (!needsAlternateValue) { return null; + } const valueElement = createElementWithClass('span', 'value'); - if (value.description === 'Object') + if (value.description === 'Object') { valueElement.textContent = ''; - else + } else { valueElement.setTextContentTruncatedIfNeeded(value.description || ''); + } valueElement.classList.add('object-value-' + (value.subtype || value.type)); valueElement.title = value.description || ''; return valueElement; @@ -807,10 +855,12 @@ update() { this.nameElement = ObjectUI.ObjectPropertiesSection.createNameElement(this.property.name, this.property.private); - if (!this.property.enumerable) + if (!this.property.enumerable) { this.nameElement.classList.add('object-properties-section-dimmed'); - if (this.property.synthetic) + } + if (this.property.synthetic) { this.nameElement.classList.add('synthetic-property'); + } this._updatePropertyPath(); @@ -831,20 +881,23 @@ } const valueText = this.valueElement.textContent; - if (this.property.value && valueText && !this.property.wasThrown) + if (this.property.value && valueText && !this.property.wasThrown) { this.expandedValueElement = this._createExpandedValueElement(this.property.value); + } this.listItemElement.removeChildren(); - if (isInternalEntries) + if (isInternalEntries) { this._rowContainer = UI.html`<span class='name-and-value'>${this.nameElement}</span>`; - else + } else { this._rowContainer = UI.html`<span class='name-and-value'>${this.nameElement}: ${this.valueElement}</span>`; + } this.listItemElement.appendChild(this._rowContainer); } _updatePropertyPath() { - if (this.nameElement.title) + if (this.nameElement.title) { return; + } const name = this.property.name; @@ -859,12 +912,13 @@ const parentPath = (this.parent.nameElement && !this.parent.property.synthetic) ? this.parent.nameElement.title : ''; - if (this.property.private || useDotNotation.test(name)) + if (this.property.private || useDotNotation.test(name)) { this.nameElement.title = parentPath ? `${parentPath}.${name}` : name; - else if (isInteger.test(name)) + } else if (isInteger.test(name)) { this.nameElement.title = parentPath + '[' + name + ']'; - else + } else { this.nameElement.title = parentPath + '["' + JSON.stringify(name) + '"]'; + } } /** @@ -873,10 +927,12 @@ _contextMenuFired(event) { const contextMenu = new UI.ContextMenu(event); contextMenu.appendApplicableItems(this); - if (this.property.symbol) + if (this.property.symbol) { contextMenu.appendApplicableItems(this.property.symbol); - if (this.property.value) + } + if (this.property.value) { contextMenu.appendApplicableItems(this.property.value); + } if (!this.property.synthetic && this.nameElement && this.nameElement.title) { const copyPathHandler = InspectorFrontendHost.copyText.bind(InspectorFrontendHost, this.nameElement.title); contextMenu.clipboardSection().appendItem(ls`Copy property path`, copyPathHandler); @@ -889,14 +945,16 @@ } _startEditing() { - if (this._prompt || !this.treeOutline._editable || this._readOnly) + if (this._prompt || !this.treeOutline._editable || this._readOnly) { return; + } this._editableDiv = this._rowContainer.createChild('span', 'editable-div'); let text = this.property.value.description; - if (this.property.value.type === 'string' && typeof text === 'string') + if (this.property.value.type === 'string' && typeof text === 'string') { text = '"' + text + '"'; + } this._editableDiv.setTextContentTruncatedIfNeeded(text, Common.UIString('<string is too large to edit>')); const originalContent = this._editableDiv.textContent; @@ -970,8 +1028,9 @@ if (this.property.synthetic) { let invalidate = false; - if (expression) + if (expression) { invalidate = await this.property.setSyntheticValue(expression); + } if (invalidate) { const parent = this.parent; parent.invalidateChildren(); @@ -1005,8 +1064,9 @@ * @param {!SDK.CallFunctionResult} result */ _onInvokeGetterClick(result) { - if (!result.object) + if (!result.object) { return; + } this.property.value = result.object; this.property.wasThrown = result.wasThrown; @@ -1104,16 +1164,18 @@ function* arrayIndexes(object) { if (toIndex - fromIndex < sparseIterationThreshold) { for (let i = fromIndex; i <= toIndex; ++i) { - if (i in object) + if (i in object) { yield i; + } } } else { ownPropertyNames = ownPropertyNames || Object.getOwnPropertyNames(object); for (let i = 0; i < ownPropertyNames.length; ++i) { const name = ownPropertyNames[i]; const index = name >>> 0; - if (('' + index) === name && fromIndex <= index && index <= toIndex) + if (('' + index) === name && fromIndex <= index && index <= toIndex) { yield index; + } } } } @@ -1127,18 +1189,20 @@ } let bucketSize = count; - if (count <= bucketThreshold) + if (count <= bucketThreshold) { bucketSize = count; - else + } else { bucketSize = Math.pow(bucketThreshold, Math.ceil(Math.log(count) / Math.log(bucketThreshold)) - 1); + } const ranges = []; if (consecutiveRange) { for (let i = fromIndex; i <= toIndex; i += bucketSize) { const groupStart = i; let groupEnd = groupStart + bucketSize - 1; - if (groupEnd > toIndex) + if (groupEnd > toIndex) { groupEnd = toIndex; + } ranges.push([groupStart, groupEnd, groupEnd - groupStart + 1]); } } else { @@ -1146,8 +1210,9 @@ let groupStart = -1; let groupEnd = 0; for (const i of arrayIndexes(this)) { - if (groupStart === -1) + if (groupStart === -1) { groupStart = i; + } groupEnd = i; if (++count === bucketSize) { ranges.push([groupStart, groupEnd, count]); @@ -1155,16 +1220,18 @@ groupStart = -1; } } - if (count > 0) + if (count > 0) { ranges.push([groupStart, groupEnd, count]); + } } return {ranges: ranges, skipGetOwnPropertyNames: skipGetOwnPropertyNames}; } async function callback(result) { - if (!result) + if (!result) { return; + } const ranges = /** @type {!Array.<!Array.<number>>} */ (result.ranges); if (ranges.length === 1) { await ObjectUI.ArrayGroupingTreeElement._populateAsFragment( @@ -1202,15 +1269,17 @@ const result = await object.callFunction( buildArrayFragment, [{value: fromIndex}, {value: toIndex}, {value: ObjectUI.ArrayGroupingTreeElement._sparseIterationThreshold}]); - if (!result.object || result.wasThrown) + if (!result.object || result.wasThrown) { return; + } const arrayFragment = result.object; const allProperties = await arrayFragment.getAllProperties(false /* accessorPropertiesOnly */, true /* generatePreview */); arrayFragment.release(); const properties = allProperties.properties; - if (!properties) + if (!properties) { return; + } properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties); for (let i = 0; i < properties.length; ++i) { properties[i].parentObject = this._object; @@ -1230,16 +1299,18 @@ const result = Object.create(null); if (toIndex - fromIndex < sparseIterationThreshold) { for (let i = fromIndex; i <= toIndex; ++i) { - if (i in this) + if (i in this) { result[i] = this[i]; + } } } else { const ownPropertyNames = Object.getOwnPropertyNames(this); for (let i = 0; i < ownPropertyNames.length; ++i) { const name = ownPropertyNames[i]; const index = name >>> 0; - if (String(index) === name && fromIndex <= index && index <= toIndex) + if (String(index) === name && fromIndex <= index && index <= toIndex) { result[index] = this[index]; + } } } return result; @@ -1256,18 +1327,21 @@ */ static async _populateNonIndexProperties(treeNode, object, skipGetOwnPropertyNames, linkifier) { const result = await object.callFunction(buildObjectFragment, [{value: skipGetOwnPropertyNames}]); - if (!result.object || result.wasThrown) + if (!result.object || result.wasThrown) { return; + } const allProperties = await result.object.getOwnProperties(true /* generatePreview */); result.object.release(); - if (!allProperties.properties) + if (!allProperties.properties) { return; + } const properties = allProperties.properties; properties.sort(ObjectUI.ObjectPropertiesSection.CompareProperties); for (const property of properties) { property.parentObject = this._object; - if (!ObjectUI.ObjectPropertiesSection._isDisplayableProperty(property, treeNode.property)) + if (!ObjectUI.ObjectPropertiesSection._isDisplayableProperty(property, treeNode.property)) { continue; + } const childTreeElement = new ObjectUI.ObjectPropertyTreeElement(property, linkifier); childTreeElement._readOnly = true; treeNode.appendChild(childTreeElement); @@ -1280,17 +1354,20 @@ */ function buildObjectFragment(skipGetOwnPropertyNames) { const result = {__proto__: this.__proto__}; - if (skipGetOwnPropertyNames) + if (skipGetOwnPropertyNames) { return result; + } const names = Object.getOwnPropertyNames(this); for (let i = 0; i < names.length; ++i) { const name = names[i]; // Array index check according to the ES5-15.4. - if (String(name >>> 0) === name && name >>> 0 !== 0xffffffff) + if (String(name >>> 0) === name && name >>> 0 !== 0xffffffff) { continue; + } const descriptor = Object.getOwnPropertyDescriptor(this, name); - if (descriptor) + if (descriptor) { Object.defineProperty(result, name, descriptor); + } } return result; } @@ -1353,8 +1430,9 @@ section.addEventListener(UI.TreeOutline.Events.ElementCollapsed, this._elementCollapsed, this); section[ObjectUI.ObjectPropertiesSectionExpandController._treeOutlineId] = id; - if (this._expandedProperties.has(id)) + if (this._expandedProperties.has(id)) { section.expand(); + } } /** @@ -1362,8 +1440,9 @@ */ stopWatchSectionsWithId(id) { for (const property of this._expandedProperties) { - if (property.startsWith(id + ':')) + if (property.startsWith(id + ':')) { this._expandedProperties.delete(property); + } } } @@ -1372,8 +1451,9 @@ */ _elementAttached(event) { const element = /** @type {!UI.TreeElement} */ (event.data); - if (element.isExpandable() && this._expandedProperties.has(this._propertyPath(element))) + if (element.isExpandable() && this._expandedProperties.has(this._propertyPath(element))) { element.expand(); + } } /** @@ -1398,8 +1478,9 @@ */ _propertyPath(treeElement) { const cachedPropertyPath = treeElement[ObjectUI.ObjectPropertiesSectionExpandController._cachedPathSymbol]; - if (cachedPropertyPath) + if (cachedPropertyPath) { return cachedPropertyPath; + } let current = treeElement; const rootElement = treeElement.treeOutline.objectTreeElement(); @@ -1408,10 +1489,11 @@ while (current !== rootElement) { let currentName = ''; - if (current.property) + if (current.property) { currentName = current.property.name; - else + } else { currentName = typeof current.title === 'string' ? current.title : current.title.textContent; + } result = currentName + (result ? '.' + result : ''); current = current.parent; @@ -1437,13 +1519,15 @@ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>} */ render(object, options) { - if (!(object instanceof SDK.RemoteObject)) + if (!(object instanceof SDK.RemoteObject)) { return Promise.reject(new Error('Can\'t render ' + object)); + } options = options || {}; const title = options.title; const section = new ObjectUI.ObjectPropertiesSection(object, title); - if (!title) + if (!title) { section.titleLessMode(); + } section.editable = !!options.editable; return Promise.resolve( /** @type {?{node: !Node, tree: ?UI.TreeOutline}} */ ({node: section.element, tree: section}));
diff --git a/third_party/blink/renderer/devtools/front_end/object_ui/RemoteObjectPreviewFormatter.js b/third_party/blink/renderer/devtools/front_end/object_ui/RemoteObjectPreviewFormatter.js index 6467c4b..65172c85 100644 --- a/third_party/blink/renderer/devtools/front_end/object_ui/RemoteObjectPreviewFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/object_ui/RemoteObjectPreviewFormatter.js
@@ -20,15 +20,17 @@ function sortValue(property) { // TODO(einbinder) expose whether preview properties are actually internal. const internalName = ObjectUI.RemoteObjectPreviewFormatter._internalName; - if (property.name === internalName.PromiseStatus) + if (property.name === internalName.PromiseStatus) { return 1; - else if (property.name === internalName.PromiseValue) + } else if (property.name === internalName.PromiseValue) { return 2; - else if (property.name === internalName.GeneratorStatus || property.name === internalName.PrimitiveValue) + } else if (property.name === internalName.GeneratorStatus || property.name === internalName.PrimitiveValue) { return 3; + } // TODO(einbinder) expose whether preview properties are actually private. - else if (property.type !== 'function' && !property.name.startsWith('#')) + else if (property.type !== 'function' && !property.name.startsWith('#')) { return 4; + } return 5; } } @@ -57,18 +59,20 @@ const hideDescription = description === 'Object'; text = hideDescription ? '' : description; } - if (text.length > 0) + if (text.length > 0) { parentElement.createChild('span', 'object-description').textContent = text + '\xA0'; + } } const propertiesElement = parentElement.createChild('span', 'object-properties-preview'); propertiesElement.createTextChild(isArrayOrTypedArray ? '[' : '{'); - if (preview.entries) + if (preview.entries) { this._appendEntriesPreview(propertiesElement, preview); - else if (isArrayOrTypedArray) + } else if (isArrayOrTypedArray) { this._appendArrayPropertiesPreview(propertiesElement, preview); - else + } else { this._appendObjectPropertiesPreview(propertiesElement, preview); + } if (preview.overflow) { const ellipsisText = propertiesElement.textContent.length > 1 ? ',\xA0\u2026' : '\u2026'; propertiesElement.createChild('span').textContent = ellipsisText; @@ -82,8 +86,9 @@ */ _abbreviateFullQualifiedClassName(description) { const abbreviatedDescription = description.split('.'); - for (let i = 0; i < abbreviatedDescription.length - 1; ++i) + for (let i = 0; i < abbreviatedDescription.length - 1; ++i) { abbreviatedDescription[i] = abbreviatedDescription[i].trimMiddle(3); + } return abbreviatedDescription.join('.'); } @@ -96,8 +101,9 @@ const properties = preview.properties.filter(p => p.type !== 'accessor') .sort(ObjectUI.RemoteObjectPreviewFormatter._objectPropertyComparator); for (let i = 0; i < properties.length; ++i) { - if (i > 0) + if (i > 0) { parentElement.createTextChild(', '); + } const property = properties[i]; const name = property.name; @@ -149,8 +155,9 @@ */ function toArrayIndex(name) { const index = name >>> 0; - if (String(index) === name && index < arrayLength) + if (String(index) === name && index < arrayLength) { return index; + } return -1; } @@ -159,8 +166,9 @@ let lastNonEmptyArrayIndex = -1; let elementsAdded = false; for (let i = 0; i < indexProperties.length; ++i) { - if (elementsAdded) + if (elementsAdded) { parentElement.createTextChild(', '); + } const property = indexProperties[i]; const index = toArrayIndex(property.name); @@ -178,14 +186,16 @@ } if (canShowGaps && arrayLength - lastNonEmptyArrayIndex > 1) { - if (elementsAdded) + if (elementsAdded) { parentElement.createTextChild(', '); + } appendUndefined(arrayLength); } for (let i = 0; i < otherProperties.length; ++i) { - if (elementsAdded) + if (elementsAdded) { parentElement.createTextChild(', '); + } const property = otherProperties[i]; parentElement.appendChild(this._renderDisplayName(property.name)); @@ -211,8 +221,9 @@ */ _appendEntriesPreview(parentElement, preview) { for (let i = 0; i < preview.entries.length; ++i) { - if (i > 0) + if (i > 0) { parentElement.createTextChild(', '); + } const entry = preview.entries[i]; if (entry.key) { @@ -276,8 +287,9 @@ if (type === 'object' && !subtype) { let preview = this._abbreviateFullQualifiedClassName(description); - if (preview === 'Object') + if (preview === 'Object') { preview = '{\u2026}'; + } span.textContent = preview; span.title = description; return span; @@ -303,8 +315,10 @@ ObjectUI.RemoteObjectPreviewFormatter.createSpansForNodeTitle = function(container, nodeTitle) { const match = nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/); container.createChild('span', 'webkit-html-tag-name').textContent = match[1]; - if (match[2]) + if (match[2]) { container.createChild('span', 'webkit-html-attribute-value').textContent = match[2]; - if (match[3]) + } + if (match[3]) { container.createChild('span', 'webkit-html-attribute-name').textContent = match[3]; + } };
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/ChartViewport.js b/third_party/blink/renderer/devtools/front_end/perf_ui/ChartViewport.js index b1ad8cb..12c774e 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/ChartViewport.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/ChartViewport.js
@@ -100,8 +100,9 @@ _updateScrollBar() { const showScroll = this._alwaysShowVerticalScroll || this._totalHeight > this._offsetHeight; - if (this._vScrollElement.classList.contains('hidden') !== showScroll) + if (this._vScrollElement.classList.contains('hidden') !== showScroll) { return; + } this._vScrollElement.classList.toggle('hidden', !showScroll); this._updateContentElementSize(); } @@ -136,8 +137,9 @@ _updateContentElementSize() { let offsetWidth = this._vScrollElement.offsetLeft; - if (!offsetWidth) + if (!offsetWidth) { offsetWidth = this.contentElement.offsetWidth; + } this._offsetWidth = offsetWidth; this._offsetHeight = this.contentElement.offsetHeight; this._delegate.setSize(this._offsetWidth, this._offsetHeight); @@ -150,8 +152,9 @@ this._totalHeight = totalHeight; this._vScrollContent.style.height = totalHeight + 'px'; this._updateScrollBar(); - if (this._scrollTop + this._offsetHeight <= totalHeight) + if (this._scrollTop + this._offsetHeight <= totalHeight) { return; + } this._scrollTop = Math.max(0, totalHeight - this._offsetHeight); this._vScrollElement.scrollTop = this._scrollTop; } @@ -162,10 +165,11 @@ */ setScrollOffset(offset, height) { height = height || 0; - if (this._vScrollElement.scrollTop > offset) + if (this._vScrollElement.scrollTop > offset) { this._vScrollElement.scrollTop = offset; - else if (this._vScrollElement.scrollTop < offset - this._offsetHeight + height) + } else if (this._vScrollElement.scrollTop < offset - this._offsetHeight + height) { this._vScrollElement.scrollTop = offset - this._offsetHeight + height; + } } /** @@ -209,8 +213,9 @@ * @return {boolean} */ _startDragging(event) { - if (event.shiftKey) + if (event.shiftKey) { return false; + } this._isDragging = true; this._dragStartPointX = event.pageX; this._dragStartPointY = event.pageY; @@ -239,8 +244,9 @@ * @return {boolean} */ _startRangeSelection(event) { - if (!event.shiftKey || !this._rangeSelectionEnabled) + if (!event.shiftKey || !this._rangeSelectionEnabled) { return false; + } this._isDragging = true; this._selectionOffsetShiftX = event.offsetX - event.pageX; this._selectionOffsetShiftY = event.offsetY - event.pageY; @@ -269,8 +275,9 @@ * @param {number} endTime */ setRangeSelection(startTime, endTime) { - if (!this._rangeSelectionEnabled) + if (!this._rangeSelectionEnabled) { return; + } this._rangeSelectionStart = Math.min(startTime, endTime); this._rangeSelectionEnd = Math.max(startTime, endTime); this._updateRangeSelectionOverlay(); @@ -282,8 +289,9 @@ */ onClick(event) { const time = this.pixelToTime(event.offsetX); - if (this._rangeSelectionStart !== null && time >= this._rangeSelectionStart && time <= this._rangeSelectionEnd) + if (this._rangeSelectionStart !== null && time >= this._rangeSelectionStart && time <= this._rangeSelectionEnd) { return; + } this.hideRangeSelection(); } @@ -385,8 +393,9 @@ * @param {!Event} e */ _handleZoomPanKeys(e) { - if (!UI.KeyboardShortcut.hasNoModifiers(e)) + if (!UI.KeyboardShortcut.hasNoModifiers(e)) { return; + } const zoomFactor = e.shiftKey ? 0.8 : 0.3; const panOffset = e.shiftKey ? 320 : 160; switch (e.code) { @@ -446,14 +455,16 @@ bounds.left = Math.max(bounds.left - bounds.right + maxBound, this._minimumBoundary); bounds.right = maxBound; } - if (bounds.right - bounds.left < PerfUI.FlameChart.MinimalTimeWindowMs) + if (bounds.right - bounds.left < PerfUI.FlameChart.MinimalTimeWindowMs) { return; + } this._delegate.windowChanged(bounds.left, bounds.right, animate); } scheduleUpdate() { - if (this._updateTimerId || this._cancelWindowTimesAnimation) + if (this._updateTimerId || this._cancelWindowTimesAnimation) { return; + } this._updateTimerId = this.element.window().requestAnimationFrame(() => { this._updateTimerId = 0; this._update(); @@ -471,8 +482,9 @@ * @param {boolean=} animate */ setWindowTimes(startTime, endTime, animate) { - if (startTime === this._targetLeftTime && endTime === this._targetRightTime) + if (startTime === this._targetLeftTime && endTime === this._targetRightTime) { return; + } if (!animate || this._visibleLeftTime === 0 || this._visibleRightTime === Infinity || (startTime === 0 && endTime === Infinity) || (startTime === Infinity && endTime === Infinity)) { // Skip animation, move instantly.
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/FilmStripView.js b/third_party/blink/renderer/devtools/front_end/perf_ui/FilmStripView.js index f7e63d8..ce967da9 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/FilmStripView.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/FilmStripView.js
@@ -19,8 +19,9 @@ * @param {?string} data */ static _setImageData(imageElement, data) { - if (data) + if (data) { imageElement.src = 'data:image/jpg;base64,' + data; + } } /** @@ -100,11 +101,13 @@ } update() { - if (!this._model) + if (!this._model) { return; + } const frames = this._model.frames(); - if (!frames.length) + if (!frames.length) { return; + } if (this._mode === PerfUI.FilmStripView.Modes.FrameBased) { Promise.all(frames.map(this.createFrameElement.bind(this))).then(appendElements.bind(this)); @@ -122,8 +125,9 @@ */ function continueWhenFrameImageLoaded(element0) { const frameWidth = Math.ceil(UI.measurePreferredSize(element0, this.contentElement).width); - if (!frameWidth) + if (!frameWidth) { return; + } const promises = []; for (let pos = frameWidth; pos < width; pos += frameWidth) { @@ -147,8 +151,9 @@ */ function appendElements(elements) { this.contentElement.removeChildren(); - for (let i = 0; i < elements.length; ++i) + for (let i = 0; i < elements.length; ++i) { this.contentElement.appendChild(elements[i]); + } } } @@ -156,8 +161,9 @@ * @override */ onResize() { - if (this._mode === PerfUI.FilmStripView.Modes.FrameBased) + if (this._mode === PerfUI.FilmStripView.Modes.FrameBased) { return; + } this.update(); } @@ -254,17 +260,19 @@ _keyDown(event) { switch (event.key) { case 'ArrowLeft': - if (Host.isMac() && event.metaKey) + if (Host.isMac() && event.metaKey) { this._onFirstFrame(); - else + } else { this._onPrevFrame(); + } break; case 'ArrowRight': - if (Host.isMac() && event.metaKey) + if (Host.isMac() && event.metaKey) { this._onLastFrame(); - else + } else { this._onNextFrame(); + } break; case 'Home': @@ -278,14 +286,16 @@ } _onPrevFrame() { - if (this._index > 0) + if (this._index > 0) { --this._index; + } this._render(); } _onNextFrame() { - if (this._index < this._frames.length - 1) + if (this._index < this._frames.length - 1) { ++this._index; + } this._render(); }
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js b/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js index 5b443406..3e3f6736 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/FlameChart.js
@@ -194,10 +194,12 @@ * @param {number} entryIndex */ highlightEntry(entryIndex) { - if (this._highlightedEntryIndex === entryIndex) + if (this._highlightedEntryIndex === entryIndex) { return; - if (!this._dataProvider.entryColor(entryIndex)) + } + if (!this._dataProvider.entryColor(entryIndex)) { return; + } this._highlightedEntryIndex = entryIndex; this._updateElementPosition(this._highlightElement, this._highlightedEntryIndex); this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntryHighlighted, entryIndex); @@ -286,11 +288,13 @@ * @return {?PerfUI.FlameChart.TimelineData} */ _timelineData() { - if (!this._dataProvider) + if (!this._dataProvider) { return null; + } const timelineData = this._dataProvider.timelineData(); - if (timelineData !== this._rawTimelineData || timelineData.entryStartTimes.length !== this._rawTimelineDataLength) + if (timelineData !== this._rawTimelineData || timelineData.entryStartTimes.length !== this._rawTimelineDataLength) { this._processTimelineData(timelineData); + } return this._rawTimelineData; } @@ -299,8 +303,9 @@ */ _revealEntry(entryIndex) { const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return; + } const timeLeft = this._chartViewport.windowLeftTime(); const timeRight = this._chartViewport.windowRightTime(); const entryStartTime = timelineData.entryStartTimes[entryIndex]; @@ -339,10 +344,12 @@ _onMouseMove(event) { this._lastMouseOffsetX = event.offsetX; this._lastMouseOffsetY = event.offsetY; - if (!this._enabled()) + if (!this._enabled()) { return; - if (this._chartViewport.isDragging()) + } + if (this._chartViewport.isDragging()) { return; + } if (this._coordinatesToGroupIndex(event.offsetX, event.offsetY, true /* headerOnly */) >= 0) { this.hideHighlight(); this._viewportElement.style.cursor = 'pointer'; @@ -357,14 +364,16 @@ this.hideHighlight(); const group = this._coordinatesToGroupIndex(this._lastMouseOffsetX, this._lastMouseOffsetY, false /* headerOnly */); - if (group >= 0 && this._rawTimelineData.groups[group].selectable) + if (group >= 0 && this._rawTimelineData.groups[group].selectable) { this._viewportElement.style.cursor = 'pointer'; - else + } else { this._viewportElement.style.cursor = 'default'; + } return; } - if (this._chartViewport.isDragging()) + if (this._chartViewport.isDragging()) { return; + } this._updatePopover(entryIndex); this._viewportElement.style.cursor = this._dataProvider.canJumpToEntry(entryIndex) ? 'pointer' : 'default'; this.highlightEntry(entryIndex); @@ -408,8 +417,9 @@ const dy = quadrant & 1 ? -offsetY - infoHeight : offsetY; x = Number.constrain(mouseX + dx, 0, parentWidth - infoWidth); y = Number.constrain(mouseY + dy, 0, parentHeight - infoHeight); - if (x >= mouseX || mouseX >= x + infoWidth || y >= mouseY || mouseY >= y + infoHeight) + if (x >= mouseX || mouseX >= x + infoWidth || y >= mouseY || mouseY >= y + infoHeight) { break; + } } this._entryInfo.style.left = x + 'px'; this._entryInfo.style.top = y + 'px'; @@ -424,8 +434,9 @@ // So if there was drag (mouse move) in the middle of that events // we skip the click. Otherwise we jump to the sources. const /** @const */ clickThreshold = 5; - if (this._maxDragOffset > clickThreshold) + if (this._maxDragOffset > clickThreshold) { return; + } this._selectGroup(this._coordinatesToGroupIndex(event.offsetX, event.offsetY, false /* headerOnly */)); this._toggleGroupExpand(this._coordinatesToGroupIndex(event.offsetX, event.offsetY, true /* headerOnly */)); @@ -444,8 +455,9 @@ * @param {number} groupIndex */ _selectGroup(groupIndex) { - if (groupIndex < 0 || this._selectedGroup === groupIndex) + if (groupIndex < 0 || this._selectedGroup === groupIndex) { return; + } const groups = this._rawTimelineData.groups; this._keyboardFocusedGroup = groupIndex; if (!groups[groupIndex].selectable) { @@ -485,8 +497,9 @@ * @param {number} groupIndex */ _toggleGroupExpand(groupIndex) { - if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) + if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) { return; + } this._expandGroup(groupIndex, !this._rawTimelineData.groups[groupIndex].expanded /* setExpanded */); } @@ -497,16 +510,18 @@ * @param {boolean=} propagatedExpand */ _expandGroup(groupIndex, setExpanded = true, propagatedExpand = false) { - if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) + if (groupIndex < 0 || !this._isGroupCollapsible(groupIndex)) { return; + } const groups = this._rawTimelineData.groups; const group = groups[groupIndex]; group.expanded = setExpanded; this._groupExpansionState[group.name] = group.expanded; - if (this._groupExpansionSetting) + if (this._groupExpansionSetting) { this._groupExpansionSetting.set(this._groupExpansionState); + } this._updateLevelPositions(); this._updateHighlight(); @@ -514,8 +529,9 @@ const timelineData = this._timelineData(); const level = timelineData.entryLevels[this._selectedEntryIndex]; if (this._selectedEntryIndex >= 0 && level >= group.startLevel && - (groupIndex >= groups.length - 1 || groups[groupIndex + 1].startLevel > level)) + (groupIndex >= groups.length - 1 || groups[groupIndex + 1].startLevel > level)) { this._selectedEntryIndex = -1; + } } this._updateHeight(); @@ -534,14 +550,16 @@ * @param {!Event} e */ _onKeyDown(e) { - if (!UI.KeyboardShortcut.hasNoModifiers(e) || !this._timelineData()) + if (!UI.KeyboardShortcut.hasNoModifiers(e) || !this._timelineData()) { return; + } const eventHandled = this._handleSelectionNavigation(e); // Handle keyboard navigation in groups - if (!eventHandled && this._rawTimelineData && this._rawTimelineData.groups) + if (!eventHandled && this._rawTimelineData && this._rawTimelineData.groups) { this._handleKeyboardGroupNavigation(e); + } } /** @@ -571,11 +589,13 @@ handled = entrySelected; } - if (handled && !entrySelected) + if (handled && !entrySelected) { this._deselectAllEntries(); + } - if (handled) + if (handled) { e.consume(true); + } } /** @@ -584,23 +604,26 @@ _selectFirstEntryInCurrentGroup() { const allGroups = this._rawTimelineData.groups; - if (this._keyboardFocusedGroup < 0) + if (this._keyboardFocusedGroup < 0) { return false; + } const group = allGroups[this._keyboardFocusedGroup]; const startLevelInGroup = group.startLevel; // Return if no levels in this group - if (startLevelInGroup < 0) + if (startLevelInGroup < 0) { return false; + } // Make sure this is the innermost nested group with this startLevel // This is because a parent group also contains levels of all its child groups // So check if the next group has the same level, if it does, user should // go to that child group to select this entry if (this._keyboardFocusedGroup < allGroups.length - 1 && - allGroups[this._keyboardFocusedGroup + 1].startLevel === startLevelInGroup) + allGroups[this._keyboardFocusedGroup + 1].startLevel === startLevelInGroup) { return false; + } // Get first (default) entry in startLevel of selected group @@ -615,8 +638,9 @@ * @return {boolean} */ _selectPreviousGroup() { - if (this._keyboardFocusedGroup <= 0) + if (this._keyboardFocusedGroup <= 0) { return false; + } const groupIndexToSelect = this._getGroupIndexToSelect(-1 /* offset */); this._selectGroup(groupIndexToSelect); @@ -627,8 +651,9 @@ * @return {boolean} */ _selectNextGroup() { - if (this._keyboardFocusedGroup >= this._rawTimelineData.groups.length - 1) + if (this._keyboardFocusedGroup >= this._rawTimelineData.groups.length - 1) { return false; + } const groupIndexToSelect = this._getGroupIndexToSelect(1 /* offset */); this._selectGroup(groupIndexToSelect); @@ -657,8 +682,9 @@ _selectFirstChild() { const allGroups = this._rawTimelineData.groups; - if (this._keyboardFocusedGroup < 0 || this._keyboardFocusedGroup >= allGroups.length - 1) + if (this._keyboardFocusedGroup < 0 || this._keyboardFocusedGroup >= allGroups.length - 1) { return; + } const groupIndexToSelect = this._keyboardFocusedGroup + 1; if (allGroups[groupIndexToSelect].style.nestingLevel > allGroups[this._keyboardFocusedGroup].style.nestingLevel) { @@ -672,11 +698,13 @@ * @return {boolean} */ _handleSelectionNavigation(e) { - if (this._selectedEntryIndex === -1) + if (this._selectedEntryIndex === -1) { return false; + } const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return false; + } /** * @param {number} time @@ -707,8 +735,9 @@ let indexOnLevel = levelIndexes.lowerBound(this._selectedEntryIndex); indexOnLevel += e.keyCode === keys.Left.code ? -1 : 1; e.consume(true); - if (indexOnLevel >= 0 && indexOnLevel < levelIndexes.length) + if (indexOnLevel >= 0 && indexOnLevel < levelIndexes.length) { this.dispatchEventToListeners(PerfUI.FlameChart.Events.EntrySelected, levelIndexes[indexOnLevel]); + } return true; } if (e.keyCode === keys.Up.code || e.keyCode === keys.Down.code) { @@ -727,8 +756,9 @@ ++indexOnLevel; if (indexOnLevel >= levelIndexes.length || !entriesIntersect(this._selectedEntryIndex, levelIndexes[indexOnLevel])) { - if (e.code === 'ArrowDown') + if (e.code === 'ArrowDown') { return false; + } // Stay in the current group and give focus to the parent group instead of entries this._deselectAllEntries(); @@ -749,32 +779,39 @@ * @return {number} */ _coordinatesToEntryIndex(x, y) { - if (x < 0 || y < 0) + if (x < 0 || y < 0) { return -1; + } const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return -1; + } y += this._chartViewport.scrollOffset(); const cursorLevel = this._visibleLevelOffsets.upperBound(y) - 1; - if (cursorLevel < 0 || !this._visibleLevels[cursorLevel]) + if (cursorLevel < 0 || !this._visibleLevels[cursorLevel]) { return -1; + } const offsetFromLevel = y - this._visibleLevelOffsets[cursorLevel]; - if (offsetFromLevel > this._levelHeight(cursorLevel)) + if (offsetFromLevel > this._levelHeight(cursorLevel)) { return -1; + } // Check markers first. for (const [index, pos] of this._markerPositions) { - if (timelineData.entryLevels[index] !== cursorLevel) + if (timelineData.entryLevels[index] !== cursorLevel) { continue; - if (pos.x <= x && x < pos.x + pos.width) + } + if (pos.x <= x && x < pos.x + pos.width) { return /** @type {number} */ (index); + } } // Check regular entries. const entryStartTimes = timelineData.entryStartTimes; const entriesOnLevel = this._timelineLevels[cursorLevel]; - if (!entriesOnLevel || !entriesOnLevel.length) + if (!entriesOnLevel || !entriesOnLevel.length) { return -1; + } const cursorTime = this._chartViewport.pixelToTime(x); const indexOnLevel = Math.max( @@ -786,8 +823,9 @@ * @return {boolean} */ function checkEntryHit(entryIndex) { - if (entryIndex === undefined) + if (entryIndex === undefined) { return false; + } const startTime = entryStartTimes[entryIndex]; const duration = timelineData.entryTotalTimes[entryIndex]; const startX = this._chartViewport.timeToPosition(startTime); @@ -797,11 +835,13 @@ } let entryIndex = entriesOnLevel[indexOnLevel]; - if (checkEntryHit.call(this, entryIndex)) + if (checkEntryHit.call(this, entryIndex)) { return entryIndex; + } entryIndex = entriesOnLevel[indexOnLevel + 1]; - if (checkEntryHit.call(this, entryIndex)) + if (checkEntryHit.call(this, entryIndex)) { return entryIndex; + } return -1; } @@ -812,26 +852,31 @@ * @return {number} */ _coordinatesToGroupIndex(x, y, headerOnly) { - if (x < 0 || y < 0) + if (x < 0 || y < 0) { return -1; + } y += this._chartViewport.scrollOffset(); const groups = this._rawTimelineData.groups || []; const group = this._groupOffsets.upperBound(y) - 1; - if (group < 0 || group >= groups.length) + if (group < 0 || group >= groups.length) { return -1; + } const height = headerOnly ? groups[group].style.height : this._groupOffsets[group + 1] - this._groupOffsets[group]; - if (y - this._groupOffsets[group] >= height) + if (y - this._groupOffsets[group] >= height) { return -1; - if (!headerOnly) + } + if (!headerOnly) { return group; + } const context = /** @type {!CanvasRenderingContext2D} */ (this._canvas.getContext('2d')); context.save(); context.font = groups[group].style.font; const right = this._headerLeftPadding + this._labelWidthForGroup(context, groups[group]); context.restore(); - if (x > right) + if (x > right) { return -1; + } return group; } @@ -842,8 +887,9 @@ */ _markerIndexAtPosition(x) { const markers = this._timelineData().markers; - if (!markers) + if (!markers) { return -1; + } const /** @const */ accurracyOffsetPx = 4; const time = this._chartViewport.pixelToTime(x); const leftTime = this._chartViewport.pixelToTime(x - accurracyOffsetPx); @@ -872,8 +918,9 @@ _draw() { const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return; + } const width = this._offsetWidth; const height = this._offsetHeight; @@ -904,10 +951,12 @@ /** @type {!Map<string, !Array<number>>} */ const colorBuckets = new Map(); for (let level = minVisibleBarLevel; level < this._dataProvider.maxStackDepth(); ++level) { - if (this._levelToOffset(level) > top + height) + if (this._levelToOffset(level) > top + height) { break; - if (!this._visibleLevels[level]) + } + if (!this._visibleLevels[level]) { continue; + } // Entries are ordered by start time within a level, so find the last visible entry. const levelIndexes = this._timelineLevels[level]; @@ -923,20 +972,24 @@ markerIndices.push(entryIndex); continue; } - if (duration >= minTextWidthDuration || this._forceDecorationCache[entryIndex]) + if (duration >= minTextWidthDuration || this._forceDecorationCache[entryIndex]) { titleIndices.push(entryIndex); + } const entryStartTime = entryStartTimes[entryIndex]; const entryOffsetRight = entryStartTime + duration; - if (entryOffsetRight <= this._chartViewport.windowLeftTime()) + if (entryOffsetRight <= this._chartViewport.windowLeftTime()) { break; - if (this._useWebGL) + } + if (this._useWebGL) { continue; + } const barX = this._timeToPositionClipped(entryStartTime); // Check if the entry entirely fits into an already drawn pixel, we can just skip drawing it. - if (barX >= lastDrawOffset) + if (barX >= lastDrawOffset) { continue; + } lastDrawOffset = barX; const color = this._entryColorsCache[entryIndex]; @@ -966,8 +1019,9 @@ for (let i = 0; i < indexes.length; ++i) { const entryIndex = indexes[i]; const duration = entryTotalTimes[entryIndex]; - if (isNaN(duration)) + if (isNaN(duration)) { continue; + } const entryStartTime = entryStartTimes[entryIndex]; const barX = this._timeToPositionClipped(entryStartTime); const barLevel = entryLevels[entryIndex]; @@ -990,12 +1044,14 @@ for (let m = markerIndices.length - 1; m >= 0; --m) { const entryIndex = markerIndices[m]; const title = this._dataProvider.entryTitle(entryIndex); - if (!title) + if (!title) { continue; + } const entryStartTime = entryStartTimes[entryIndex]; const level = entryLevels[entryIndex]; - if (lastMarkerLevel !== level) + if (lastMarkerLevel !== level) { lastMarkerX = -Infinity; + } const x = Math.max(this._chartViewport.timeToPosition(entryStartTime), lastMarkerX); const y = this._levelToOffset(level); const h = this._levelHeight(level); @@ -1028,10 +1084,12 @@ const unclippedBarX = this._chartViewport.timeToPosition(entryStartTime); const barHeight = this._levelHeight(barLevel); if (this._dataProvider.decorateEntry( - entryIndex, context, text, barX, barY, barWidth, barHeight, unclippedBarX, timeToPixel)) + entryIndex, context, text, barX, barY, barWidth, barHeight, unclippedBarX, timeToPixel)) { continue; - if (!text || !text.length) + } + if (!text || !text.length) { continue; + } context.fillStyle = this._dataProvider.textColor(entryIndex); context.fillText(text, barX + textPadding, barY + barHeight - this._textBaseline); } @@ -1095,8 +1153,9 @@ const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); - if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { return shader; + } console.error('Shader compile error: ' + gl.getShaderInfoLog(shader)); gl.deleteShader(shader); return null; @@ -1133,12 +1192,14 @@ _setupGLGeometry() { const gl = /** @type {?WebGLRenderingContext} */ (this._canvasGL.getContext('webgl')); - if (!gl) + if (!gl) { return; + } const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return; + } const entryTotalTimes = timelineData.entryTotalTimes; const entryStartTimes = timelineData.entryStartTimes; @@ -1156,36 +1217,43 @@ const collapsedOverviewLevels = new Array(this._visibleLevels.length); const groups = this._rawTimelineData.groups || []; this._forEachGroup((offset, index, group) => { - if (group.style.useFirstLineForOverview || !this._isGroupCollapsible(index) || group.expanded) + if (group.style.useFirstLineForOverview || !this._isGroupCollapsible(index) || group.expanded) { return; + } let nextGroup = index + 1; - while (nextGroup < groups.length && groups[nextGroup].style.nestingLevel > group.style.nestingLevel) + while (nextGroup < groups.length && groups[nextGroup].style.nestingLevel > group.style.nestingLevel) { ++nextGroup; + } const endLevel = nextGroup < groups.length ? groups[nextGroup].startLevel : this._dataProvider.maxStackDepth(); - for (let i = group.startLevel; i < endLevel; ++i) + for (let i = group.startLevel; i < endLevel; ++i) { collapsedOverviewLevels[i] = offset; + } }); for (let i = 0; i < entryTotalTimes.length; ++i) { const level = entryLevels[i]; const collapsedGroupOffset = collapsedOverviewLevels[level]; - if (!this._visibleLevels[level] && !collapsedGroupOffset) + if (!this._visibleLevels[level] && !collapsedGroupOffset) { continue; + } const color = this._entryColorsCache[i]; - if (!color) + if (!color) { continue; + } let colorIndex = parsedColorCache.get(color); if (colorIndex === undefined) { const rgba = Common.Color.parse(color).canonicalRGBA(); rgba[3] = Math.round(rgba[3] * 255); colorIndex = colors.length / 4; colors.push(...rgba); - if (colorIndex === 256) + if (colorIndex === 256) { colorArray = new Uint16Array(colorArray); + } parsedColorCache.set(color, colorIndex); } - for (let j = 0; j < verticesPerBar; ++j) + for (let j = 0; j < verticesPerBar; ++j) { colorArray[vertex + j] = colorIndex; + } const vpos = vertex * 2; const x0 = entryStartTimes[i] - this._minimumBoundary; @@ -1223,8 +1291,9 @@ const colorIndexType = useShortForColors ? gl.UNSIGNED_SHORT : gl.UNSIGNED_BYTE; if (useShortForColors) { const factor = (1 << 16) / width; - for (let i = 0; i < vertex; ++i) + for (let i = 0; i < vertex; ++i) { colorArray[i] *= factor; + } } const pixels = new Uint8Array(width * 4); @@ -1242,11 +1311,13 @@ _drawGL() { const gl = /** @type {?WebGLRenderingContext} */ (this._canvasGL.getContext('webgl')); - if (!gl) + if (!gl) { return; + } const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return; + } if (!this._prevTimelineData || timelineData.entryTotalTimes !== this._prevTimelineData.entryTotalTimes) { this._prevTimelineData = timelineData; @@ -1255,8 +1326,9 @@ gl.viewport(0, 0, this._canvasGL.width, this._canvasGL.height); - if (!this._vertexCount) + if (!this._vertexCount) { return; + } const viewportScale = [2.0 / this.boundarySpan(), -2.0 * window.devicePixelRatio / this._canvasGL.height]; const viewportShift = [this.minimumBoundary() - this.zeroTime(), this._chartViewport.scrollOffset()]; @@ -1275,8 +1347,9 @@ const top = this._chartViewport.scrollOffset(); const ratio = window.devicePixelRatio; const groups = this._rawTimelineData.groups || []; - if (!groups.length) + if (!groups.length) { return; + } const groupOffsets = this._groupOffsets; const lastGroupOffset = Array.prototype.peekLast.call(groupOffsets); @@ -1291,26 +1364,30 @@ context.fillStyle = UI.themeSupport.patchColorText('#fff', colorUsage.Background); this._forEachGroupInViewport((offset, index, group) => { const paddingHeight = group.style.padding; - if (paddingHeight < 5) + if (paddingHeight < 5) { return; + } context.fillRect(0, offset - paddingHeight + 2, width, paddingHeight - 4); }); - if (groups.length && lastGroupOffset < top + height) + if (groups.length && lastGroupOffset < top + height) { context.fillRect(0, lastGroupOffset + 2, width, top + height - lastGroupOffset); + } context.strokeStyle = UI.themeSupport.patchColorText('#eee', colorUsage.Background); context.beginPath(); this._forEachGroupInViewport((offset, index, group, isFirst) => { - if (isFirst || group.style.padding < 4) + if (isFirst || group.style.padding < 4) { return; + } hLine(offset - 2.5); }); hLine(lastGroupOffset + 1.5); context.stroke(); this._forEachGroupInViewport((offset, index, group) => { - if (group.style.useFirstLineForOverview) + if (group.style.useFirstLineForOverview) { return; + } if (!this._isGroupCollapsible(index) || group.expanded) { if (!group.style.shareHeaderLine && this._isGroupFocused(index)) { context.fillStyle = group.style.backgroundColor; @@ -1318,11 +1395,13 @@ } return; } - if (this._useWebGL) + if (this._useWebGL) { return; + } let nextGroup = index + 1; - while (nextGroup < groups.length && groups[nextGroup].style.nestingLevel > group.style.nestingLevel) + while (nextGroup < groups.length && groups[nextGroup].style.nestingLevel > group.style.nestingLevel) { nextGroup++; + } const endLevel = nextGroup < groups.length ? groups[nextGroup].startLevel : this._dataProvider.maxStackDepth(); this._drawCollapsedOverviewForGroup(group, offset, endLevel); }); @@ -1332,10 +1411,11 @@ context.font = group.style.font; if (this._isGroupCollapsible(index) && !group.expanded || group.style.shareHeaderLine) { const width = this._labelWidthForGroup(context, group) + 2; - if (this._isGroupFocused(index)) + if (this._isGroupFocused(index)) { context.fillStyle = this._selectedGroupBackroundColor; - else + } else { context.fillStyle = Common.Color.parse(group.style.backgroundColor).setAlpha(0.8).asString(null); + } context.fillRect( this._headerLeftPadding - this._headerLabelXPadding, offset + this._headerLabelYPadding, width, @@ -1408,8 +1488,9 @@ */ _forEachGroup(callback) { const groups = this._rawTimelineData.groups || []; - if (!groups.length) + if (!groups.length) { return; + } const groupOffsets = this._groupOffsets; /** @type !Array<{nestingLevel: number, visible: boolean}> */ const groupStack = [{nestingLevel: -1, visible: true}]; @@ -1425,8 +1506,9 @@ const thisGroupVisible = parentGroupVisible && (!this._isGroupCollapsible(i) || group.expanded); groupStack.push({nestingLevel: group.style.nestingLevel, visible: thisGroupVisible}); const nextOffset = i === groups.length - 1 ? groupOffsets[i + 1] + group.style.padding : groupOffsets[i + 1]; - if (!parentGroupVisible) + if (!parentGroupVisible) { continue; + } callback(groupTop, i, group, firstGroup, nextOffset - groupTop); } } @@ -1437,10 +1519,12 @@ _forEachGroupInViewport(callback) { const top = this._chartViewport.scrollOffset(); this._forEachGroup((groupTop, index, group, firstGroup, height) => { - if (groupTop - group.style.padding > top + this._offsetHeight) + if (groupTop - group.style.padding > top + this._offsetHeight) { return; - if (groupTop + height < top) + } + if (groupTop + height < top) { return; + } callback(groupTop, index, group, firstGroup, height); }); } @@ -1481,10 +1565,12 @@ const entryStartTime = entryStartTimes[entryIndex]; const barX = this._timeToPositionClipped(entryStartTime); const entryEndTime = entryStartTime + entryTotalTimes[entryIndex]; - if (isNaN(entryEndTime) || barX >= lastDrawOffset) + if (isNaN(entryEndTime) || barX >= lastDrawOffset) { continue; - if (entryEndTime <= timeWindowLeft) + } + if (entryEndTime <= timeWindowLeft) { break; + } lastDrawOffset = barX; const color = this._entryColorsCache[entryIndex]; const endBarX = this._timeToPositionClipped(entryEndTime); @@ -1547,8 +1633,9 @@ context.lineWidth = 0.5; for (let i = 0; i < endIndex; ++i) { - if (!td.flowEndTimes[i] || td.flowEndTimes[i] < this._chartViewport.windowLeftTime()) + if (!td.flowEndTimes[i] || td.flowEndTimes[i] < this._chartViewport.windowLeftTime()) { continue; + } const startX = this._chartViewport.timeToPosition(td.flowStartTimes[i]); const endX = this._chartViewport.timeToPosition(td.flowEndTimes[i]); const startLevel = td.flowStartLevels[i]; @@ -1609,8 +1696,9 @@ const height = PerfUI.FlameChart.HeaderHeight - 1; for (let i = left; i < markers.length; i++) { const timestamp = markers[i].startTime(); - if (timestamp > rightBoundary) + if (timestamp > rightBoundary) { break; + } markers[i].draw(context, this._chartViewport.timeToPosition(timestamp), height, timeToPixel); } context.restore(); @@ -1618,11 +1706,13 @@ _updateMarkerHighlight() { const element = this._markerHighlighElement; - if (element.parentElement) + if (element.parentElement) { element.remove(); + } const markerIndex = this._highlightedMarkerIndex; - if (markerIndex === -1) + if (markerIndex === -1) { return; + } const marker = this._timelineData().markers[markerIndex]; const barX = this._timeToPositionClipped(marker.startTime()); element.title = marker.title(); @@ -1661,8 +1751,9 @@ } const entryCounters = new Uint32Array(this._dataProvider.maxStackDepth() + 1); - for (let i = 0; i < timelineData.entryLevels.length; ++i) + for (let i = 0; i < timelineData.entryLevels.length; ++i) { ++entryCounters[timelineData.entryLevels[i]]; + } const levelIndexes = new Array(entryCounters.length); for (let i = 0; i < levelIndexes.length; ++i) { levelIndexes[i] = new Uint32Array(entryCounters[i]); @@ -1677,8 +1768,9 @@ const groups = this._rawTimelineData.groups || []; for (let i = 0; i < groups.length; ++i) { const expanded = this._groupExpansionState[groups[i].name]; - if (expanded !== undefined) + if (expanded !== undefined) { groups[i].expanded = expanded; + } } this._updateLevelPositions(); this._updateHeight(); @@ -1719,14 +1811,17 @@ parentGroupIsVisible = groupStack.peekLast().visible; visible = thisGroupIsVisible && parentGroupIsVisible; groupStack.push({nestingLevel: style.nestingLevel, visible: visible}); - if (parentGroupIsVisible) + if (parentGroupIsVisible) { currentOffset += nextLevel ? 0 : style.padding; + } this._groupOffsets[groupIndex] = currentOffset; - if (parentGroupIsVisible && !style.shareHeaderLine) + if (parentGroupIsVisible && !style.shareHeaderLine) { currentOffset += style.height; + } } - if (level >= levelCount) + if (level >= levelCount) { continue; + } const isFirstOnLevel = groupIndex >= 0 && level === groups[groupIndex].startLevel; const thisLevelIsVisible = parentGroupIsVisible && (visible || isFirstOnLevel && groups[groupIndex].style.useFirstLineForOverview); @@ -1743,14 +1838,17 @@ this._visibleLevels[level] = thisLevelIsVisible; this._visibleLevelOffsets[level] = currentOffset; this._visibleLevelHeights[level] = height; - if (thisLevelIsVisible || (parentGroupIsVisible && style && style.shareHeaderLine && isFirstOnLevel)) + if (thisLevelIsVisible || (parentGroupIsVisible && style && style.shareHeaderLine && isFirstOnLevel)) { currentOffset += this._visibleLevelHeights[level]; + } } - if (groupIndex >= 0) + if (groupIndex >= 0) { this._groupOffsets[groupIndex + 1] = currentOffset; + } this._visibleLevelOffsets[level] = currentOffset; - if (this._useWebGL) + if (this._useWebGL) { this._setupGLGeometry(); + } } /** @@ -1759,14 +1857,17 @@ _isGroupCollapsible(index) { const groups = this._rawTimelineData.groups || []; const style = groups[index].style; - if (!style.shareHeaderLine || !style.collapsible) + if (!style.shareHeaderLine || !style.collapsible) { return !!style.collapsible; + } const isLastGroup = index + 1 >= groups.length; - if (!isLastGroup && groups[index + 1].style.nestingLevel > style.nestingLevel) + if (!isLastGroup && groups[index + 1].style.nestingLevel > style.nestingLevel) { return true; + } const nextGroupLevel = isLastGroup ? this._dataProvider.maxStackDepth() : groups[index + 1].startLevel; - if (nextGroupLevel !== groups[index].startLevel + 1) + if (nextGroupLevel !== groups[index].startLevel + 1) { return true; + } // For groups that only have one line and share header line, pretend these are not collapsible // unless the itemsHeight does not match the headerHeight return style.height !== style.itemsHeight; @@ -1776,10 +1877,12 @@ * @param {number} entryIndex */ setSelectedEntry(entryIndex) { - if (this._selectedEntryIndex === entryIndex) + if (this._selectedEntryIndex === entryIndex) { return; - if (entryIndex !== -1) + } + if (entryIndex !== -1) { this._chartViewport.hideRangeSelection(); + } this._selectedEntryIndex = entryIndex; this._revealEntry(entryIndex); this._updateElementPosition(this._selectedElement, this._selectedEntryIndex); @@ -1792,8 +1895,9 @@ _updateElementPosition(element, entryIndex) { const elementMinWidthPx = 2; element.classList.add('hidden'); - if (entryIndex === -1) + if (entryIndex === -1) { return; + } const timelineData = this._timelineData(); const startTime = timelineData.entryStartTimes[entryIndex]; const duration = timelineData.entryTotalTimes[entryIndex]; @@ -1812,8 +1916,9 @@ barX = this._chartViewport.timeToPosition(startTime); barWidth = duration * this._chartViewport.timeToPixel(); } - if (barX + barWidth <= 0 || barX >= this._offsetWidth) + if (barX + barWidth <= 0 || barX >= this._offsetWidth) { return; + } const barCenter = barX + barWidth / 2; barWidth = Math.max(barWidth, elementMinWidthPx); barX = barCenter - barWidth / 2; @@ -1875,14 +1980,16 @@ * @override */ update() { - if (!this._timelineData()) + if (!this._timelineData()) { return; + } this._resetCanvas(); this._updateHeight(); this._updateBoundaries(); this._draw(); - if (!this._chartViewport.isDragging()) + if (!this._chartViewport.isDragging()) { this._updateHighlight(); + } } reset() {
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/GCActionDelegate.js b/third_party/blink/renderer/devtools/front_end/perf_ui/GCActionDelegate.js index a443d0c9..5d879e8 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/GCActionDelegate.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/GCActionDelegate.js
@@ -13,8 +13,9 @@ * @return {boolean} */ handleAction(context, actionId) { - for (const heapProfilerModel of SDK.targetManager.models(SDK.HeapProfilerModel)) + for (const heapProfilerModel of SDK.targetManager.models(SDK.HeapProfilerModel)) { heapProfilerModel.collectGarbage(); + } return true; } };
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/LineLevelProfile.js b/third_party/blink/renderer/devtools/front_end/perf_ui/LineLevelProfile.js index 5611239..e2f85c3b 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/LineLevelProfile.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/LineLevelProfile.js
@@ -25,8 +25,9 @@ for (let i = 0; i < nodes.length; ++i) { const node = nodes[i]; nodesToGo.push(node); - if (!node.url || !node.positionTicks) + if (!node.url || !node.positionTicks) { continue; + } for (let j = 0; j < node.positionTicks.length; ++j) { const lineInfo = node.positionTicks[j]; const line = lineInfo.line; @@ -49,12 +50,14 @@ const target = profile.target(); for (let i = 1; i < profile.samples.length; ++i) { const line = profile.lines[i]; - if (!line) + if (!line) { continue; + } const node = profile.nodeByIndex(i); const scriptIdOrUrl = node.scriptId || node.url; - if (!scriptIdOrUrl) + if (!scriptIdOrUrl) { continue; + } const time = profile.timestamps[i] - profile.timestamps[i - 1]; this._helper.addLineData(target, scriptIdOrUrl, line, time); } @@ -85,11 +88,13 @@ */ function processNode(node) { node.children.forEach(processNode); - if (!node.selfSize) + if (!node.selfSize) { return; + } const script = Number(node.callFrame.scriptId) || node.callFrame.url; - if (!script) + if (!script) { return; + } const line = node.callFrame.lineNumber + 1; helper.addLineData(target, script, line, node.selfSize); } @@ -135,8 +140,9 @@ } scheduleUpdate() { - if (this._updateTimer) + if (this._updateTimer) { return; + } this._updateTimer = setTimeout(() => { this._updateTimer = null; this._doUpdate(); @@ -158,8 +164,9 @@ const uiSourceCode = !debuggerModel && typeof scriptIdOrUrl === 'string' ? Workspace.workspace.uiSourceCodeForURL(scriptIdOrUrl) : null; - if (!debuggerModel && !uiSourceCode) + if (!debuggerModel && !uiSourceCode) { continue; + } for (const lineToData of lineToDataMap) { const line = /** @type {number} */ (lineToData[0]) - 1; const data = /** @type {number} */ (lineToData[1]); @@ -170,8 +177,9 @@ const rawLocation = typeof scriptIdOrUrl === 'string' ? debuggerModel.createRawLocationByURL(scriptIdOrUrl, line, 0) : debuggerModel.createRawLocationByScriptId(String(scriptIdOrUrl), line, 0); - if (rawLocation) + if (rawLocation) { new PerfUI.LineLevelProfile.Presentation(rawLocation, this._type, data, this._locationPool); + } } } } @@ -196,11 +204,13 @@ * @param {!Bindings.LiveLocation} liveLocation */ updateLocation(liveLocation) { - if (this._uiLocation) + if (this._uiLocation) { this._uiLocation.uiSourceCode.removeDecorationsForType(this._type); + } this._uiLocation = liveLocation.uiLocation(); - if (this._uiLocation) + if (this._uiLocation) { this._uiLocation.uiSourceCode.addLineDecoration(this._uiLocation.lineNumber, this._type, this._time); + } } }; @@ -218,8 +228,9 @@ const gutterType = `CodeMirror-gutter-${type}`; const decorations = uiSourceCode.decorationsForType(type); textEditor.uninstallGutter(gutterType); - if (!decorations || !decorations.size) + if (!decorations || !decorations.size) { return; + } textEditor.installGutter(gutterType, false); for (const decoration of decorations) { const value = /** @type {number} */ (decoration.data());
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/LiveHeapProfile.js b/third_party/blink/renderer/devtools/front_end/perf_ui/LiveHeapProfile.js index 7150085..36f6553 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/LiveHeapProfile.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/LiveHeapProfile.js
@@ -13,8 +13,9 @@ this._loadEventCallback = () => {}; this._setting = Common.settings.moduleSetting('memoryLiveHeapProfile'); this._setting.addChangeListener(event => event.data ? this._startProfiling() : this._stopProfiling()); - if (this._setting.get()) + if (this._setting.get()) { this._startProfiling(); + } } /** @@ -40,8 +41,9 @@ } async _startProfiling() { - if (this._running) + if (this._running) { return; + } this._running = true; const sessionId = this._sessionId; SDK.targetManager.observeModels(SDK.HeapProfilerModel, this); @@ -51,13 +53,15 @@ do { const models = SDK.targetManager.models(SDK.HeapProfilerModel); const profiles = await Promise.all(models.map(model => model.getSamplingProfile())); - if (sessionId !== this._sessionId) + if (sessionId !== this._sessionId) { break; + } const lineLevelProfile = self.runtime.sharedInstance(PerfUI.LineLevelProfile.Memory); lineLevelProfile.reset(); for (let i = 0; i < profiles.length; ++i) { - if (profiles[i]) + if (profiles[i]) { lineLevelProfile.appendHeapProfile(profiles[i], models[i].target()); + } } await Promise.race([ new Promise(r => setTimeout(r, Host.isUnderTest() ? 10 : 5000)), new Promise(r => this._loadEventCallback = r) @@ -67,14 +71,16 @@ SDK.targetManager.unobserveModels(SDK.HeapProfilerModel, this); SDK.targetManager.removeModelListener( SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._loadEventFired, this); - for (const model of SDK.targetManager.models(SDK.HeapProfilerModel)) + for (const model of SDK.targetManager.models(SDK.HeapProfilerModel)) { model.stopSampling(); + } self.runtime.sharedInstance(PerfUI.LineLevelProfile.Memory).reset(); } _stopProfiling() { - if (!this._running) + if (!this._running) { return; + } this._running = 0; this._sessionId++; }
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/NetworkPriorities.js b/third_party/blink/renderer/devtools/front_end/perf_ui/NetworkPriorities.js index 16b3862f..e9c54f32 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/NetworkPriorities.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/NetworkPriorities.js
@@ -27,8 +27,9 @@ * @return {!Map<!Protocol.Network.ResourcePriority, string>} */ PerfUI._priorityUILabelMap = function() { - if (PerfUI._priorityUILabelMapInstance) + if (PerfUI._priorityUILabelMapInstance) { return PerfUI._priorityUILabelMapInstance; + } /** @type {!Map<!Protocol.Network.ResourcePriority, string>} */ const map = new Map();
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/OverviewGrid.js b/third_party/blink/renderer/devtools/front_end/perf_ui/OverviewGrid.js index ca98103a..d59e668d 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/OverviewGrid.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/OverviewGrid.js
@@ -202,8 +202,9 @@ * @param {!Event} event */ _resizerElementStartDragging(event) { - if (!this._enabled) + if (!this._enabled) { return false; + } this._resizerParentOffsetLeft = event.pageX - event.offsetX - event.target.offsetLeft; event.stopPropagation(); return true; @@ -230,8 +231,9 @@ * @return {boolean} */ _startWindowSelectorDragging(event) { - if (!this._enabled) + if (!this._enabled) { return false; + } this._offsetLeft = this._parentElement.totalOffsetLeft(); const position = event.x - this._offsetLeft; this._overviewWindowSelector = new PerfUI.OverviewGrid.WindowSelector(this._parentElement, position); @@ -254,16 +256,18 @@ delete this._overviewWindowSelector; const clickThreshold = 3; if (window.end - window.start < clickThreshold) { - if (this._clickHandler && this._clickHandler.call(null, event)) + if (this._clickHandler && this._clickHandler.call(null, event)) { return; + } const middle = window.end; window.start = Math.max(0, middle - PerfUI.OverviewGrid.MinSelectableSize / 2); window.end = Math.min(this._parentElement.clientWidth, middle + PerfUI.OverviewGrid.MinSelectableSize / 2); } else if (window.end - window.start < PerfUI.OverviewGrid.MinSelectableSize) { - if (this._parentElement.clientWidth - window.end > PerfUI.OverviewGrid.MinSelectableSize) + if (this._parentElement.clientWidth - window.end > PerfUI.OverviewGrid.MinSelectableSize) { window.end = window.start + PerfUI.OverviewGrid.MinSelectableSize; - else + } else { window.start = window.end - PerfUI.OverviewGrid.MinSelectableSize; + } } this._setWindowPosition(window.start, window.end); } @@ -286,11 +290,13 @@ _windowDragging(event) { event.preventDefault(); let delta = (event.pageX - this._dragStartPoint) / this._parentElement.clientWidth; - if (this._dragStartLeft + delta < 0) + if (this._dragStartLeft + delta < 0) { delta = -this._dragStartLeft; + } - if (this._dragStartRight + delta > 1) + if (this._dragStartRight + delta > 1) { delta = 1 - this._dragStartRight; + } this._setWindow(this._dragStartLeft + delta, this._dragStartRight + delta); } @@ -300,10 +306,11 @@ */ _resizeWindowLeft(start) { // Glue to edge. - if (start < 10) + if (start < 10) { start = 0; - else if (start > this._rightResizeElement.offsetLeft - 4) + } else if (start > this._rightResizeElement.offsetLeft - 4) { start = this._rightResizeElement.offsetLeft - 4; + } this._setWindowPosition(start, null); } @@ -312,10 +319,11 @@ */ _resizeWindowRight(end) { // Glue to edge. - if (end > this._parentElement.clientWidth - 10) + if (end > this._parentElement.clientWidth - 10) { end = this._parentElement.clientWidth; - else if (end < this._leftResizeElement.offsetLeft + PerfUI.OverviewGrid.MinSelectableSize) + } else if (end < this._leftResizeElement.offsetLeft + PerfUI.OverviewGrid.MinSelectableSize) { end = this._leftResizeElement.offsetLeft + PerfUI.OverviewGrid.MinSelectableSize; + } this._setWindowPosition(null, end); } @@ -369,8 +377,9 @@ * @param {!Event} event */ _onMouseWheel(event) { - if (!this._enabled) + if (!this._enabled) { return; + } if (typeof event.wheelDeltaY === 'number' && event.wheelDeltaY) { const zoomFactor = 1.1; const mouseWheelZoomSpeed = 1 / 120; @@ -383,11 +392,13 @@ const windowLeft = this._leftResizeElement.offsetLeft + PerfUI.OverviewGrid.ResizerOffset; const windowRight = this._rightResizeElement.offsetLeft + PerfUI.OverviewGrid.ResizerOffset; - if (windowLeft - offset < 0) + if (windowLeft - offset < 0) { offset = windowLeft; + } - if (windowRight - offset > this._parentElement.clientWidth) + if (windowRight - offset > this._parentElement.clientWidth) { offset = windowRight - this._parentElement.clientWidth; + } this._setWindowPosition(windowLeft - offset, windowRight - offset);
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/PieChart.js b/third_party/blink/renderer/devtools/front_end/perf_ui/PieChart.js index b629b2d..ad1a9b2 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/PieChart.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/PieChart.js
@@ -65,8 +65,9 @@ this._formatter = formatter; this._slices = []; this._lastAngle = -Math.PI / 2; - if (showLegend) + if (showLegend) { this._legend = root.createChild('div', 'pie-chart-legend'); + } this._setSize(size); } @@ -74,16 +75,18 @@ * @param {number} totalValue */ setTotal(totalValue) { - for (let i = 0; i < this._slices.length; ++i) + for (let i = 0; i < this._slices.length; ++i) { this._slices[i].remove(); + } this._slices = []; this._totalValue = totalValue; this._lastAngle = -Math.PI / 2; let totalString; - if (totalValue) + if (totalValue) { totalString = this._formatter ? this._formatter(totalValue) : totalValue; - else + } else { totalString = ''; + } this._totalElement.textContent = totalString; if (this._legend) { this._legend.removeChildren(); @@ -108,8 +111,9 @@ */ addSlice(value, color, name) { let sliceAngle = value / this._totalValue * 2 * Math.PI; - if (!isFinite(sliceAngle)) + if (!isFinite(sliceAngle)) { return; + } sliceAngle = Math.min(sliceAngle, 2 * Math.PI * 0.9999); const path = this._createSVGChild(this._group, 'path'); const x1 = Math.cos(this._lastAngle); @@ -127,8 +131,9 @@ `M${x1},${y1} A1,1,0,${largeArc},1,${x2},${y2} L${x3},${y3} A${r2},${r2},0,${largeArc},0,${x4},${y4} Z`); path.setAttribute('fill', color); this._slices.push(path); - if (this._legend) + if (this._legend) { this._addLegendItem(path, value, name, color); + } } /** @@ -153,17 +158,19 @@ const node = this._legend.ownerDocument.createElement('div'); node.className = 'pie-chart-legend-row'; // make sure total always appears at the bottom - if (this._legend.childElementCount) + if (this._legend.childElementCount) { this._legend.insertBefore(node, this._legend.lastElementChild); - else + } else { this._legend.appendChild(node); + } const sizeDiv = node.createChild('div', 'pie-chart-size'); const swatchDiv = node.createChild('div', 'pie-chart-swatch'); const nameDiv = node.createChild('div', 'pie-chart-name'); - if (color) + if (color) { swatchDiv.style.backgroundColor = color; - else + } else { swatchDiv.classList.add('pie-chart-empty-swatch'); + } nameDiv.textContent = name; const size = this._formatter ? this._formatter(value) : value; sizeDiv.textContent = size;
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineGrid.js b/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineGrid.js index af644ce..113e9e01 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineGrid.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineGrid.js
@@ -65,10 +65,12 @@ const logGridSliceTime = Math.ceil(Math.log(gridSliceTime) / Math.LN10); gridSliceTime = Math.pow(10, logGridSliceTime); - if (gridSliceTime * pixelsPerTime >= 5 * minGridSlicePx) + if (gridSliceTime * pixelsPerTime >= 5 * minGridSlicePx) { gridSliceTime = gridSliceTime / 5; - if (gridSliceTime * pixelsPerTime >= 2 * minGridSlicePx) + } + if (gridSliceTime * pixelsPerTime >= 2 * minGridSlicePx) { gridSliceTime = gridSliceTime / 2; + } const firstDividerTime = Math.ceil((calculator.minimumBoundary() - calculator.zeroTime()) / gridSliceTime) * gridSliceTime + @@ -79,14 +81,16 @@ lastDividerTime += minGridSlicePx / pixelsPerTime; dividersCount = Math.ceil((lastDividerTime - firstDividerTime) / gridSliceTime); - if (!gridSliceTime) + if (!gridSliceTime) { dividersCount = 0; + } const offsets = []; for (let i = 0; i < dividersCount; ++i) { const time = firstDividerTime + gridSliceTime * i; - if (calculator.computePosition(time) < freeZoneAtLeft) + if (calculator.computePosition(time) < freeZoneAtLeft) { continue; + } offsets.push({position: Math.floor(calculator.computePosition(time)), time: time}); } @@ -141,8 +145,9 @@ const text = formatTimeFunction(offsetInfo.time); const textWidth = context.measureText(text).width; const textPosition = offsetInfo.position - textWidth - paddingRight; - if (!freeZoneAtLeft || freeZoneAtLeft < textPosition) + if (!freeZoneAtLeft || freeZoneAtLeft < textPosition) { context.fillText(text, textPosition, paddingTop); + } } context.restore(); } @@ -229,8 +234,9 @@ */ addEventDividers(dividers) { this._gridHeaderElement.removeChild(this._eventDividersElement); - for (const divider of dividers) + for (const divider of dividers) { this._eventDividersElement.appendChild(divider); + } this._gridHeaderElement.appendChild(this._eventDividersElement); }
diff --git a/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineOverviewPane.js b/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineOverviewPane.js index a7325bf..397e4d5 100644 --- a/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineOverviewPane.js +++ b/third_party/blink/renderer/devtools/front_end/perf_ui/TimelineOverviewPane.js
@@ -65,8 +65,9 @@ * @param {!Event} event */ _onMouseMove(event) { - if (!this._cursorEnabled) + if (!this._cursorEnabled) { return; + } this._cursorPosition = event.offsetX + event.target.offsetLeft; this._cursorElement.style.left = this._cursorPosition + 'px'; this._cursorElement.style.visibility = 'visible'; @@ -110,8 +111,9 @@ */ onResize() { const width = this.element.offsetWidth; - if (width === this._lastWidth) + if (width === this._lastWidth) { return; + } this._lastWidth = width; this.scheduleUpdate(); } @@ -120,8 +122,9 @@ * @param {!Array.<!PerfUI.TimelineOverview>} overviewControls */ setOverviewControls(overviewControls) { - for (let i = 0; i < this._overviewControls.length; ++i) + for (let i = 0; i < this._overviewControls.length; ++i) { this._overviewControls[i].dispose(); + } for (let i = 0; i < overviewControls.length; ++i) { overviewControls[i].setCalculator(this._overviewCalculator); @@ -154,11 +157,13 @@ } _update() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } this._overviewCalculator.setDisplayWidth(this._overviewGrid.clientWidth()); - for (let i = 0; i < this._overviewControls.length; ++i) + for (let i = 0; i < this._overviewControls.length; ++i) { this._overviewControls[i].update(); + } this._overviewGrid.updateDividers(this._overviewCalculator); this._updateMarkers(); this._updateWindow(); @@ -177,8 +182,9 @@ const marker = this._markers.get(time); const position = Math.round(this._overviewCalculator.computePosition(time)); // Limit the number of markers to one per pixel. - if (filteredMarkers.has(position)) + if (filteredMarkers.has(position)) { continue; + } filteredMarkers.set(position, marker); marker.style.left = position + 'px'; } @@ -195,8 +201,9 @@ this._cursorEnabled = false; this._hideCursor(); this._markers = new Map(); - for (const control of this._overviewControls) + for (const control of this._overviewControls) { control.reset(); + } this._overviewInfo.hide(); this.scheduleUpdate(); } @@ -213,11 +220,13 @@ * @param {!Common.Event} event */ _onWindowChanged(event) { - if (this._muteOnWindowChanged) + if (this._muteOnWindowChanged) { return; + } // Always use first control as a time converter. - if (!this._overviewControls.length) + if (!this._overviewControls.length) { return; + } const absoluteMin = this._overviewCalculator.minimumBoundary(); const timeSpan = this._overviewCalculator.maximumBoundary() - absoluteMin; @@ -235,8 +244,9 @@ * @param {number} endTime */ setWindowTimes(startTime, endTime) { - if (startTime === this._windowStartTime && endTime === this._windowEndTime) + if (startTime === this._windowStartTime && endTime === this._windowEndTime) { return; + } this._windowStartTime = startTime; this._windowEndTime = endTime; this._updateWindow(); @@ -245,8 +255,9 @@ } _updateWindow() { - if (!this._overviewControls.length) + if (!this._overviewControls.length) { return; + } const absoluteMin = this._overviewCalculator.minimumBoundary(); const timeSpan = this._overviewCalculator.maximumBoundary() - absoluteMin; const haveRecords = absoluteMin > 0; @@ -466,8 +477,9 @@ } resetCanvas() { - if (this.element.clientWidth) + if (this.element.clientWidth) { this.setCanvasSize(this.element.clientWidth, this.element.clientHeight); + } } /** @@ -502,13 +514,15 @@ async setContent(contentPromise) { this._visible = true; const content = await contentPromise; - if (!this._visible) + if (!this._visible) { return; + } this._element.removeChildren(); this._element.appendChild(content); this._glassPane.setContentAnchorBox(this._anchorElement.boxInWindow()); - if (!this._glassPane.isShowing()) + if (!this._glassPane.isShowing()) { this._glassPane.show(/** @type {!Document} */ (this._anchorElement.ownerDocument)); + } } hide() {
diff --git a/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js b/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js index 500e189..735e855d 100644 --- a/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js +++ b/third_party/blink/renderer/devtools/front_end/performance_monitor/PerformanceMonitor.js
@@ -39,8 +39,9 @@ * @override */ wasShown() { - if (!this._model) + if (!this._model) { return; + } SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); this._model.enable(); this._suspendStateChanged(); @@ -50,8 +51,9 @@ * @override */ willHide() { - if (!this._model) + if (!this._model) { return; + } SDK.targetManager.removeEventListener( SDK.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); this._stopPolling(); @@ -63,11 +65,13 @@ * @param {!SDK.PerformanceMetricsModel} model */ modelAdded(model) { - if (this._model) + if (this._model) { return; + } this._model = model; - if (this.isShowing()) + if (this.isShowing()) { this.wasShown(); + } } /** @@ -75,19 +79,22 @@ * @param {!SDK.PerformanceMetricsModel} model */ modelRemoved(model) { - if (this._model !== model) + if (this._model !== model) { return; - if (this.isShowing()) + } + if (this.isShowing()) { this.willHide(); + } this._model = null; } _suspendStateChanged() { const suspended = SDK.targetManager.allTargetsSuspended(); - if (suspended) + if (suspended) { this._stopPolling(); - else + } else { this._startPolling(); + } this.contentElement.classList.toggle('suspended', suspended); } @@ -121,7 +128,9 @@ // Multiply by 2 as the pollInterval has some jitter and to have some extra samples if window is resized. const maxCount = Math.ceil(millisPerWidth / this._pollIntervalMs * 2); if (this._metricsBuffer.length > maxCount * 2) // Multiply by 2 to have a hysteresis. + { this._metricsBuffer.splice(0, this._metricsBuffer.length - maxCount); + } this._controlPane.updateMetrics(metrics); } @@ -133,8 +142,9 @@ ctx.save(); ctx.translate(0, this._scaleHeight); // Reserve space for the scale bar. for (const chartInfo of this._controlPane.charts()) { - if (!this._controlPane.isActive(chartInfo.metrics[0].name)) + if (!this._controlPane.isActive(chartInfo.metrics[0].name)) { continue; + } this._drawChart(ctx, chartInfo, this._graphHeight); ctx.translate(0, this._graphHeight); } @@ -154,13 +164,15 @@ const currentTime = Date.now() / 1000; for (let sec = Math.ceil(currentTime);; --sec) { const x = this._width - ((currentTime - sec) * 1000 - this._pollIntervalMs) * this._pixelsPerMs; - if (x < -50) + if (x < -50) { break; + } ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, this._height); - if (sec >= 0 && sec % labelDistanceSeconds === 0) + if (sec >= 0 && sec % labelDistanceSeconds === 0) { ctx.fillText(new Date(sec * 1000).toLocaleTimeString(), x + 4, 12); + } ctx.strokeStyle = sec % labelDistanceSeconds ? lightGray : this._gridColor; ctx.stroke(); } @@ -212,8 +224,9 @@ * @return {number} */ _calcMax(chartInfo) { - if (chartInfo.max) + if (chartInfo.max) { return chartInfo.max; + } const width = this._width; const startTime = performance.now() - this._pollIntervalMs - width / this._pixelsPerMs; let max = -Infinity; @@ -222,12 +235,14 @@ const metrics = this._metricsBuffer[i]; const value = metrics.metrics.get(metricInfo.name); max = Math.max(max, value); - if (metrics.timestamp < startTime) + if (metrics.timestamp < startTime) { break; + } } } - if (!this._metricsBuffer.length) + if (!this._metricsBuffer.length) { return 10; + } const base10 = Math.pow(10, Math.floor(Math.log10(max))); max = Math.ceil(max / base10 / 2) * base10 * 2; @@ -246,8 +261,9 @@ _drawVerticalGrid(ctx, height, max, info) { let base = Math.pow(10, Math.floor(Math.log10(max))); const firstDigit = Math.floor(max / base); - if (firstDigit !== 1 && firstDigit % 2 === 1) + if (firstDigit !== 1 && firstDigit % 2 === 1) { base *= 2; + } let scaleValue = Math.floor(max / base) * base; const span = max; @@ -293,8 +309,9 @@ const path = new Path2D(); const topPadding = 18; const visibleHeight = height - topPadding; - if (visibleHeight < 1) + if (visibleHeight < 1) { return path; + } const span = scaleMax; const metricName = metricInfo.name; const pixelsPerMs = this._pixelsPerMs; @@ -332,8 +349,9 @@ } lastX = x; lastY = y; - if (timestamp < startTime) + if (timestamp < startTime) { break; + } } return path; @@ -359,8 +377,9 @@ _recalcChartHeight() { let height = this._scaleHeight; for (const chartInfo of this._controlPane.charts()) { - if (this._controlPane.isActive(chartInfo.metrics[0].name)) + if (this._controlPane.isActive(chartInfo.metrics[0].name)) { height += this._graphHeight; + } } this._height = Math.ceil(height * window.devicePixelRatio); this._canvas.height = this._height; @@ -436,8 +455,9 @@ {title: Common.UIString('Style recalcs / sec'), metrics: [{name: 'RecalcStyleCount', color: 'deeppink'}]} ]; for (const info of this._chartsInfo) { - for (const metric of info.metrics) + for (const metric of info.metrics) { metric.color = UI.themeSupport.patchColorText(metric.color, UI.ThemeSupport.ColorUsage.Foreground); + } } /** @type {!Map<string, !PerformanceMonitor.PerformanceMonitor.MetricIndicator>} */ @@ -456,10 +476,11 @@ * @param {boolean} active */ _onToggle(chartName, active) { - if (active) + if (active) { this._enabledCharts.add(chartName); - else + } else { this._enabledCharts.delete(chartName); + } this._enabledChartsSetting.set(Array.from(this._enabledCharts)); this.dispatchEventToListeners(PerformanceMonitor.PerformanceMonitor.ControlPane.Events.MetricChanged); } @@ -484,8 +505,9 @@ */ updateMetrics(metrics) { for (const name of this._indicators.keys()) { - if (metrics.has(name)) + if (metrics.has(name)) { this._indicators.get(name).setValue(metrics.get(name)); + } } } }; @@ -564,8 +586,9 @@ */ _handleKeypress(event) { const keyboardEvent = /** @type {!KeyboardEvent} */ (event); - if (keyboardEvent.key === ' ' || keyboardEvent.key === 'Enter') + if (keyboardEvent.key === ' ' || keyboardEvent.key === 'Enter') { this._toggleIndicator(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/performance_test_runner/TimelineTestRunner.js b/third_party/blink/renderer/devtools/front_end/performance_test_runner/TimelineTestRunner.js index 1a96801..bc57d280b 100644 --- a/third_party/blink/renderer/devtools/front_end/performance_test_runner/TimelineTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/performance_test_runner/TimelineTestRunner.js
@@ -57,8 +57,9 @@ }; TestRunner.formatters.formatAsInvalidationCause = function(cause) { - if (!cause) + if (!cause) { return '<undefined>'; + } let stackTrace; @@ -85,8 +86,9 @@ let categories = '-*,disabled-by-default-devtools.timeline*,devtools.timeline,blink.user_timing,' + SDK.TracingModel.LegacyTopLevelEventCategory; - if (additionalCategories) + if (additionalCategories) { categories += ',' + additionalCategories; + } const timelinePanel = UI.panels.timeline; const timelineController = PerformanceTestRunner.createTimelineController(); @@ -174,15 +176,17 @@ PerformanceTestRunner.printTimelineRecords = function(name) { for (const event of PerformanceTestRunner.timelineModel().inspectedTargetEvents()) { - if (event.name === name) + if (event.name === name) { PerformanceTestRunner.printTraceEventProperties(event); + } } }; PerformanceTestRunner.printTimelineRecordsWithDetails = function(name) { for (const event of PerformanceTestRunner.timelineModel().inspectedTargetEvents()) { - if (name === event.name) + if (name === event.name) { PerformanceTestRunner.printTraceEventPropertiesWithDetails(event); + } } }; @@ -199,19 +203,22 @@ PerformanceTestRunner.walkTimelineEventTreeUnderNode = function(callback, root, level) { const event = root.event; - if (event) + if (event) { callback(event, level, root); + } - for (const child of root.children().values()) + for (const child of root.children().values()) { PerformanceTestRunner.walkTimelineEventTreeUnderNode(callback, child, (level || 0) + 1); + } }; PerformanceTestRunner.printTimestampRecords = function(typeName) { const dividers = PerformanceTestRunner.timelineModel().timeMarkerEvents(); for (const event of dividers) { - if (event.name === typeName) + if (event.name === typeName) { PerformanceTestRunner.printTraceEventProperties(event); + } } }; @@ -219,13 +226,15 @@ const eventStack = []; for (const event of events) { - while (eventStack.length && eventStack.peekLast().endTime <= event.startTime) + while (eventStack.length && eventStack.peekLast().endTime <= event.startTime) { eventStack.pop(); + } callback(event, eventStack); - if (event.endTime) + if (event.endTime) { eventStack.push(event); + } } }; @@ -244,8 +253,9 @@ }; for (const field in object) { - if (object[field] === null || object[field] === undefined) + if (object[field] === null || object[field] === undefined) { delete object[field]; + } } TestRunner.addObject(object, PerformanceTestRunner.timelinePropertyFormatters); @@ -257,15 +267,17 @@ event, SDK.targetManager.mainTarget(), new Components.Linkifier()); TestRunner.addResult(`Text details for ${event.name}: ${details}`); - if (TimelineModel.TimelineData.forEvent(event).warning) + if (TimelineModel.TimelineData.forEvent(event).warning) { TestRunner.addResult(`${event.name} has a warning`); + } }; PerformanceTestRunner.mainTrack = function() { let mainTrack; for (const track of PerformanceTestRunner.timelineModel().tracks()) { - if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) + if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) { mainTrack = track; + } } return mainTrack; }; @@ -282,8 +294,9 @@ const endTime = events[parentIndex].endTime; for (let i = parentIndex + 1; i < events.length && (!events[i].endTime || events[i].endTime <= endTime); ++i) { - if (events[i].name === name) + if (events[i].name === name) { return events[i]; + } } return null; @@ -299,15 +312,17 @@ const result = {}; for (const key in object) { - if (fieldsToDump.indexOf(key) < 0) + if (fieldsToDump.indexOf(key) < 0) { continue; + } let value = object[key]; - if (typeof value === 'number') + if (typeof value === 'number') { value = Number(value.toFixed(7)); - else if (typeof value === 'object' && value) + } else if (typeof value === 'object' && value) { value = formatFields(value); + } result[key] = value; } @@ -332,14 +347,16 @@ const stackDepth = provider.maxStackDepth(); const entriesByLevel = new Multimap(); - for (let i = 0; i < timelineData.entryLevels.length; ++i) + for (let i = 0; i < timelineData.entryLevels.length; ++i) { entriesByLevel.set(timelineData.entryLevels[i], i); + } for (let groupIndex = 0; groupIndex < timelineData.groups.length; ++groupIndex) { const group = timelineData.groups[groupIndex]; - if (includeGroupsSet && !includeGroupsSet.has(group.name)) + if (includeGroupsSet && !includeGroupsSet.has(group.name)) { continue; + } const maxLevel = (groupIndex + 1 < timelineData.groups.length ? timelineData.groups[groupIndex + 1].startLevel : stackDepth);
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js b/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js index 0251661..6fef8c2 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/Automapping.js
@@ -46,10 +46,12 @@ Workspace.Workspace.Events.ProjectRemoved, event => this._onProjectRemoved(/** @type {!Workspace.Project} */ (event.data)), this); - for (const fileSystem of workspace.projects()) + for (const fileSystem of workspace.projects()) { this._onProjectAdded(fileSystem); - for (const uiSourceCode of workspace.uiSourceCodes()) + } + for (const uiSourceCode of workspace.uiSourceCodes()) { this._onUISourceCodeAdded(uiSourceCode); + } } /** @@ -61,8 +63,9 @@ } scheduleRemap() { - for (const status of this._statuses.valuesArray()) + for (const status of this._statuses.valuesArray()) { this._clearNetworkStatus(status.network); + } this._scheduleSweep(); } @@ -76,8 +79,9 @@ function sweepUnmapped() { const networkProjects = this._workspace.projectsForType(Workspace.projectTypes.Network); for (const networkProject of networkProjects) { - for (const uiSourceCode of networkProject.uiSourceCodes()) + for (const uiSourceCode of networkProject.uiSourceCodes()) { this._computeNetworkStatus(uiSourceCode); + } } this._onSweepHappenedForTest(); return Promise.resolve(); @@ -91,13 +95,16 @@ * @param {!Workspace.Project} project */ _onProjectRemoved(project) { - for (const uiSourceCode of project.uiSourceCodes()) + for (const uiSourceCode of project.uiSourceCodes()) { this._onUISourceCodeRemoved(uiSourceCode); - if (project.type() !== Workspace.projectTypes.FileSystem) + } + if (project.type() !== Workspace.projectTypes.FileSystem) { return; + } const fileSystem = /** @type {!Persistence.FileSystemWorkspaceBinding.FileSystem} */ (project); - for (const gitFolder of fileSystem.initialGitFolders()) + for (const gitFolder of fileSystem.initialGitFolders()) { this._projectFoldersIndex.removeFolder(gitFolder); + } this._projectFoldersIndex.removeFolder(fileSystem.fileSystemPath()); this.scheduleRemap(); } @@ -106,11 +113,13 @@ * @param {!Workspace.Project} project */ _onProjectAdded(project) { - if (project.type() !== Workspace.projectTypes.FileSystem) + if (project.type() !== Workspace.projectTypes.FileSystem) { return; + } const fileSystem = /** @type {!Persistence.FileSystemWorkspaceBinding.FileSystem} */ (project); - for (const gitFolder of fileSystem.initialGitFolders()) + for (const gitFolder of fileSystem.initialGitFolders()) { this._projectFoldersIndex.addFolder(gitFolder); + } this._projectFoldersIndex.addFolder(fileSystem.fileSystemPath()); project.uiSourceCodes().forEach(this._onUISourceCodeAdded.bind(this)); this.scheduleRemap(); @@ -122,8 +131,9 @@ _onUISourceCodeAdded(uiSourceCode) { const project = uiSourceCode.project(); if (project.type() === Workspace.projectTypes.FileSystem) { - if (!Persistence.FileSystemWorkspaceBinding.fileSystemSupportsAutomapping(project)) + if (!Persistence.FileSystemWorkspaceBinding.fileSystemSupportsAutomapping(project)) { return; + } this._filesIndex.addPath(uiSourceCode.url()); this._fileSystemUISourceCodes.set(uiSourceCode.url(), uiSourceCode); this._scheduleSweep(); @@ -140,8 +150,9 @@ this._filesIndex.removePath(uiSourceCode.url()); this._fileSystemUISourceCodes.delete(uiSourceCode.url()); const status = uiSourceCode[this._statusSymbol]; - if (status) + if (status) { this._clearNetworkStatus(status.network); + } } else if (uiSourceCode.project().type() === Workspace.projectTypes.Network) { this._clearNetworkStatus(uiSourceCode); } @@ -153,14 +164,16 @@ _onUISourceCodeRenamed(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data.uiSourceCode); const oldURL = /** @type {string} */ (event.data.oldURL); - if (uiSourceCode.project().type() !== Workspace.projectTypes.FileSystem) + if (uiSourceCode.project().type() !== Workspace.projectTypes.FileSystem) { return; + } this._filesIndex.removePath(oldURL); this._fileSystemUISourceCodes.delete(oldURL); const status = uiSourceCode[this._statusSymbol]; - if (status) + if (status) { this._clearNetworkStatus(status.network); + } this._filesIndex.addPath(uiSourceCode.url()); this._fileSystemUISourceCodes.set(uiSourceCode.url(), uiSourceCode); @@ -171,12 +184,15 @@ * @param {!Workspace.UISourceCode} networkSourceCode */ _computeNetworkStatus(networkSourceCode) { - if (networkSourceCode[this._processingPromiseSymbol] || networkSourceCode[this._statusSymbol]) + if (networkSourceCode[this._processingPromiseSymbol] || networkSourceCode[this._statusSymbol]) { return; - if (this._interceptors.some(interceptor => interceptor(networkSourceCode))) + } + if (this._interceptors.some(interceptor => interceptor(networkSourceCode))) { return; - if (networkSourceCode.url().startsWith('wasm://')) + } + if (networkSourceCode.url().startsWith('wasm://')) { return; + } const createBindingPromise = this._createBinding(networkSourceCode).then(validateStatus.bind(this)).then(onStatus.bind(this)); networkSourceCode[this._processingPromiseSymbol] = createBindingPromise; @@ -187,12 +203,15 @@ * @this {Persistence.Automapping} */ async function validateStatus(status) { - if (!status) + if (!status) { return null; - if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) + } + if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) { return null; - if (status.network.contentType().isFromSourceMap() || !status.fileSystem.contentType().isTextType()) + } + if (status.network.contentType().isFromSourceMap() || !status.fileSystem.contentType().isTextType()) { return status; + } // At the time binding comes, there are multiple user scenarios: // 1. Both network and fileSystem files are **not** dirty. @@ -211,8 +230,9 @@ // We consider this to be un-realistic scenario and in this case just fail gracefully. // // To support usecase (3), we need to validate against original network content. - if (status.fileSystem.isDirty() && (status.network.isDirty() || status.network.hasCommits())) + if (status.fileSystem.isDirty() && (status.network.isDirty() || status.network.hasCommits())) { return null; + } const contents = await Promise.all([ status.fileSystem.requestContent(), @@ -220,11 +240,13 @@ ]); const fileSystemContent = contents[0]; const networkContent = contents[1]; - if (fileSystemContent === null || networkContent === null) + if (fileSystemContent === null || networkContent === null) { return null; + } - if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) + if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) { return null; + } const target = Bindings.NetworkProject.targetForUISourceCode(status.network); let isValid = false; @@ -248,16 +270,18 @@ * @this {Persistence.Automapping} */ function onStatus(status) { - if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) + if (networkSourceCode[this._processingPromiseSymbol] !== createBindingPromise) { return; + } networkSourceCode[this._processingPromiseSymbol] = null; if (!status) { this._onBindingFailedForTest(); return; } // TODO(lushnikov): remove this check once there's a single uiSourceCode per url. @see crbug.com/670180 - if (status.network[this._statusSymbol] || status.fileSystem[this._statusSymbol]) + if (status.network[this._statusSymbol] || status.fileSystem[this._statusSymbol]) { return; + } this._statuses.add(status); status.network[this._statusSymbol] = status; @@ -265,8 +289,9 @@ if (status.exactMatch) { const projectFolder = this._projectFoldersIndex.closestParentFolder(status.fileSystem.url()); const newFolderAdded = projectFolder ? this._activeFoldersIndex.addFolder(projectFolder) : false; - if (newFolderAdded) + if (newFolderAdded) { this._scheduleSweep(); + } } this._onStatusAdded.call(null, status); } @@ -290,16 +315,18 @@ return; } const status = networkSourceCode[this._statusSymbol]; - if (!status) + if (!status) { return; + } this._statuses.delete(status); status.network[this._statusSymbol] = null; status.fileSystem[this._statusSymbol] = null; if (status.exactMatch) { const projectFolder = this._projectFoldersIndex.closestParentFolder(status.fileSystem.url()); - if (projectFolder) + if (projectFolder) { this._activeFoldersIndex.removeFolder(projectFolder); + } } this._onStatusRemoved.call(null, status); } @@ -318,16 +345,19 @@ } let networkPath = Common.ParsedURL.extractPath(networkSourceCode.url()); - if (networkPath === null) + if (networkPath === null) { return Promise.resolve(/** @type {?Persistence.AutomappingStatus} */ (null)); + } - if (networkPath.endsWith('/')) + if (networkPath.endsWith('/')) { networkPath += 'index.html'; + } const urlDecodedNetworkPath = decodeURI(networkPath); const similarFiles = this._filesIndex.similarFiles(urlDecodedNetworkPath).map(path => this._fileSystemUISourceCodes.get(path)); - if (!similarFiles.length) + if (!similarFiles.length) { return Promise.resolve(/** @type {?Persistence.AutomappingStatus} */ (null)); + } return this._pullMetadatas(similarFiles.concat(networkSourceCode)).then(onMetadatas.bind(this)); @@ -339,17 +369,20 @@ const networkMetadata = networkSourceCode[this._metadataSymbol]; if (!networkMetadata || (!networkMetadata.modificationTime && typeof networkMetadata.contentSize !== 'number')) { // If networkSourceCode does not have metadata, try to match against active folders. - if (activeFiles.length !== 1) + if (activeFiles.length !== 1) { return null; + } return new Persistence.AutomappingStatus(networkSourceCode, activeFiles[0], false); } // Try to find exact matches, prioritizing active folders. let exactMatches = this._filterWithMetadata(activeFiles, networkMetadata); - if (!exactMatches.length) + if (!exactMatches.length) { exactMatches = this._filterWithMetadata(similarFiles, networkMetadata); - if (exactMatches.length !== 1) + } + if (exactMatches.length !== 1) { return null; + } return new Persistence.AutomappingStatus(networkSourceCode, exactMatches[0], true); } } @@ -372,8 +405,9 @@ _filterWithMetadata(files, networkMetadata) { return files.filter(file => { const fileMetadata = file[this._metadataSymbol]; - if (!fileMetadata) + if (!fileMetadata) { return false; + } // Allow a second of difference due to network timestamps lack of precision. const timeMatches = !networkMetadata.modificationTime || Math.abs(networkMetadata.modificationTime - fileMetadata.modificationTime) < 1000; @@ -418,8 +452,9 @@ similarFiles(networkPath) { const encodedPath = this._encoder.encode(networkPath); const longestCommonPrefix = this._reversedIndex.longestPrefix(encodedPath.reverse(), false); - if (!longestCommonPrefix) + if (!longestCommonPrefix) { return []; + } return this._reversedIndex.words(longestCommonPrefix) .map(encodedPath => this._encoder.decode(encodedPath.reverse())); } @@ -444,8 +479,9 @@ * @return {boolean} */ addFolder(path) { - if (path.endsWith('/')) + if (path.endsWith('/')) { path = path.substring(0, path.length - 1); + } const encodedPath = this._encoder.encode(path); this._index.add(encodedPath); const count = this._folderCount.get(encodedPath) || 0; @@ -458,12 +494,14 @@ * @return {boolean} */ removeFolder(path) { - if (path.endsWith('/')) + if (path.endsWith('/')) { path = path.substring(0, path.length - 1); + } const encodedPath = this._encoder.encode(path); const count = this._folderCount.get(encodedPath) || 0; - if (!count) + if (!count) { return false; + } if (count > 1) { this._folderCount.set(encodedPath, count - 1); return false;
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/EditFileSystemView.js b/third_party/blink/renderer/devtools/front_end/persistence/EditFileSystemView.js index fa3163a..329f21a 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/EditFileSystemView.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/EditFileSystemView.js
@@ -68,8 +68,9 @@ } _update() { - if (this._muteUpdate) + if (this._muteUpdate) { return; + } this._excludedFoldersList.clear(); this._excludedFolders = []; @@ -143,8 +144,9 @@ * @return {!UI.ListWidget.Editor} */ _createExcludedFolderEditor() { - if (this._excludedFolderEditor) + if (this._excludedFolderEditor) { return this._excludedFolderEditor; + } const editor = new UI.ListWidget.Editor(); this._excludedFolderEditor = editor; @@ -169,14 +171,16 @@ function pathPrefixValidator(item, index, input) { const prefix = this._normalizePrefix(input.value.trim()); - if (!prefix) + if (!prefix) { return {valid: false, errorMessage: ls`Enter a path`}; + } const configurableCount = Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().size; for (let i = 0; i < configurableCount; ++i) { - if (i !== index && this._excludedFolders[i] === prefix) + if (i !== index && this._excludedFolders[i] === prefix) { return {valid: false, errorMessage: ls`Enter a unique path`}; + } } return {valid: true}; } @@ -187,8 +191,9 @@ * @return {string} */ _normalizePrefix(prefix) { - if (!prefix) + if (!prefix) { return ''; + } return prefix + (prefix[prefix.length - 1] === '/' ? '' : '/'); } };
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/FileSystemWorkspaceBinding.js b/third_party/blink/renderer/devtools/front_end/persistence/FileSystemWorkspaceBinding.js index a84c3f2..fdcb551 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/FileSystemWorkspaceBinding.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/FileSystemWorkspaceBinding.js
@@ -129,8 +129,9 @@ * @param {!Array<!Persistence.IsolatedFileSystem>} fileSystems */ _onFileSystemsLoaded(fileSystems) { - for (const fileSystem of fileSystems) + for (const fileSystem of fileSystems) { this._addFileSystem(fileSystem); + } } /** @@ -166,22 +167,25 @@ const paths = /** @type {!Persistence.IsolatedFileSystemManager.FilesChangedData} */ (event.data); for (const fileSystemPath of paths.changed.keysArray()) { const fileSystem = this._boundFileSystems.get(fileSystemPath); - if (!fileSystem) + if (!fileSystem) { continue; + } paths.changed.get(fileSystemPath).forEach(path => fileSystem._fileChanged(path)); } for (const fileSystemPath of paths.added.keysArray()) { const fileSystem = this._boundFileSystems.get(fileSystemPath); - if (!fileSystem) + if (!fileSystem) { continue; + } paths.added.get(fileSystemPath).forEach(path => fileSystem._fileChanged(path)); } for (const fileSystemPath of paths.removed.keysArray()) { const fileSystem = this._boundFileSystems.get(fileSystemPath); - if (!fileSystem) + if (!fileSystem) { continue; + } paths.removed.get(fileSystemPath).forEach(path => fileSystem.removeUISourceCode(path)); } } @@ -270,8 +274,9 @@ * @return {!Promise<?Workspace.UISourceCodeMetadata>} */ requestMetadata(uiSourceCode) { - if (uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]) + if (uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]) { return uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata]; + } const relativePath = this._filePathForUISourceCode(uiSourceCode); const promise = this._fileSystem.getMetadata(relativePath).then(onMetadata); uiSourceCode[Persistence.FileSystemWorkspaceBinding._metadata] = promise; @@ -282,8 +287,9 @@ * @return {?Workspace.UISourceCodeMetadata} */ function onMetadata(metadata) { - if (!metadata) + if (!metadata) { return null; + } return new Workspace.UISourceCodeMetadata(metadata.modificationTime, metadata.size); } } @@ -414,8 +420,9 @@ async findFilesMatchingSearchRequest(searchConfig, filesMathingFileQuery, progress) { let result = filesMathingFileQuery; const queriesToRun = searchConfig.queries().slice(); - if (!queriesToRun.length) + if (!queriesToRun.length) { queriesToRun.push(''); + } progress.setTotalWork(queriesToRun.length); for (const query of queriesToRun) { @@ -447,10 +454,12 @@ */ function reportFileChunk(from) { const to = Math.min(from + chunkSize, filePaths.length); - for (let i = from; i < to; ++i) + for (let i = from; i < to; ++i) { this._addFile(filePaths[i]); - if (to < filePaths.length) + } + if (to < filePaths.length) { setTimeout(reportFileChunk.bind(this, to), 100); + } } } @@ -460,17 +469,20 @@ */ excludeFolder(url) { let relativeFolder = url.substring(this._fileSystemBaseURL.length); - if (!relativeFolder.startsWith('/')) + if (!relativeFolder.startsWith('/')) { relativeFolder = '/' + relativeFolder; - if (!relativeFolder.endsWith('/')) + } + if (!relativeFolder.endsWith('/')) { relativeFolder += '/'; + } this._fileSystem.addExcludedFolder(relativeFolder); const uiSourceCodes = this.uiSourceCodes().slice(); for (let i = 0; i < uiSourceCodes.length; ++i) { const uiSourceCode = uiSourceCodes[i]; - if (uiSourceCode.url().startsWith(url)) + if (uiSourceCode.url().startsWith(url)) { this.removeUISourceCode(uiSourceCode.url()); + } } } @@ -503,8 +515,9 @@ const guardFileName = this._fileSystemPath + path + (!path.endsWith('/') ? '/' : '') + name; this._creatingFilesGuard.add(guardFileName); const filePath = await this._fileSystem.createFile(path, name); - if (!filePath) + if (!filePath) { return null; + } const uiSourceCode = this._addFile(filePath); uiSourceCode.setContent(content, !!isBase64); this._creatingFilesGuard.delete(guardFileName); @@ -518,8 +531,9 @@ deleteFile(uiSourceCode) { const relativePath = this._filePathForUISourceCode(uiSourceCode); this._fileSystem.deleteFile(relativePath).then(success => { - if (success) + if (success) { this.removeUISourceCode(uiSourceCode.url()); + } }); } @@ -546,8 +560,9 @@ */ _fileChanged(path) { // Ignore files that are being created but do not have content yet. - if (this._creatingFilesGuard.has(path)) + if (this._creatingFilesGuard.has(path)) { return; + } const uiSourceCode = this.uiSourceCodeForURL(path); if (!uiSourceCode) { const contentType = this._fileSystem.contentType(path);
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystem.js b/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystem.js index 0bd71813..6efb09a 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystem.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystem.js
@@ -68,8 +68,9 @@ */ static create(manager, path, embedderPath, type, name, rootURL) { const domFileSystem = InspectorFrontendHost.isolatedFileSystem(name, rootURL); - if (!domFileSystem) + if (!domFileSystem) { return Promise.resolve(/** @type {?Persistence.IsolatedFileSystem} */ (null)); + } const fileSystem = new Persistence.IsolatedFileSystem(manager, path, embedderPath, domFileSystem, type); return fileSystem._initializeFilePaths() @@ -168,8 +169,9 @@ for (let i = 0; i < entries.length; ++i) { const entry = entries[i]; if (!entry.isDirectory) { - if (this.isFileExcluded(entry.fullPath)) + if (this.isFileExcluded(entry.fullPath)) { continue; + } this._initialFilePaths.add(entry.fullPath.substr(1)); } else { if (entry.fullPath.endsWith('/.git')) { @@ -186,8 +188,9 @@ this._requestEntries(entry.fullPath, boundInnerCallback); } } - if ((--pendingRequests === 0)) + if ((--pendingRequests === 0)) { fulfill(); + } } } @@ -199,15 +202,17 @@ // Fast-path. If parent directory already exists we return it immidiatly. let dirEntry = await new Promise( resolve => this._domFileSystem.root.getDirectory(folderPath, undefined, resolve, () => resolve(null))); - if (dirEntry) + if (dirEntry) { return dirEntry; + } const paths = folderPath.split('/'); let activePath = ''; for (const path of paths) { activePath = activePath + '/' + path; dirEntry = await this._innerCreateFolderIfNeeded(activePath); - if (!dirEntry) + if (!dirEntry) { return null; + } } return dirEntry; } @@ -234,11 +239,13 @@ */ async createFile(path, name) { const dirEntry = await this._createFoldersIfNotExist(path); - if (!dirEntry) + if (!dirEntry) { return null; + } const fileEntry = await this._serializedFileOperation(path, createFileCandidate.bind(this, name || 'NewFile')); - if (!fileEntry) + if (!fileEntry) { return null; + } return fileEntry.fullPath.substr(1); /** @@ -345,10 +352,11 @@ const extension = Common.ParsedURL.extractExtension(path); const encoded = Persistence.IsolatedFileSystem.BinaryExtensions.has(extension); const readPromise = new Promise(x => reader.onloadend = x); - if (encoded) + if (encoded) { reader.readAsBinaryString(blob); - else + } else { reader.readAsText(blob); + } await readPromise; if (reader.error) { console.error('Can\'t read file: ' + path + ': ' + reader.error); @@ -405,10 +413,11 @@ fileWriter.onerror = errorHandler.bind(this); fileWriter.onwriteend = fileWritten; let blob; - if (isBase64) - blob = await(await fetch(`data:application/octet-stream;base64,${content}`)).blob(); - else + if (isBase64) { + blob = await (await fetch(`data:application/octet-stream;base64,${content}`)).blob(); + } else { blob = new Blob([content], {type: 'text/plain'}); + } fileWriter.write(blob); function fileWritten() { @@ -595,8 +604,9 @@ * @return {boolean} */ isFileExcluded(folderPath) { - if (this._excludedFolders.has(folderPath)) + if (this._excludedFolders.has(folderPath)) { return true; + } const regex = this._manager.workspaceFolderExcludePatternSetting().asRegExp(); return !!(regex && regex.test(folderPath)); } @@ -665,14 +675,18 @@ */ contentType(path) { const extension = Common.ParsedURL.extractExtension(path); - if (Persistence.IsolatedFileSystem._styleSheetExtensions.has(extension)) + if (Persistence.IsolatedFileSystem._styleSheetExtensions.has(extension)) { return Common.resourceTypes.Stylesheet; - if (Persistence.IsolatedFileSystem._documentExtensions.has(extension)) + } + if (Persistence.IsolatedFileSystem._documentExtensions.has(extension)) { return Common.resourceTypes.Document; - if (Persistence.IsolatedFileSystem.ImageExtensions.has(extension)) + } + if (Persistence.IsolatedFileSystem.ImageExtensions.has(extension)) { return Common.resourceTypes.Image; - if (Persistence.IsolatedFileSystem._scriptExtensions.has(extension)) + } + if (Persistence.IsolatedFileSystem._scriptExtensions.has(extension)) { return Common.resourceTypes.Script; + } return Persistence.IsolatedFileSystem.BinaryExtensions.has(extension) ? Common.resourceTypes.Other : Common.resourceTypes.Document; }
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystemManager.js b/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystemManager.js index 2c3604bd..f08840a 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystemManager.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/IsolatedFileSystemManager.js
@@ -82,8 +82,9 @@ function onFileSystemsLoaded(event) { const fileSystems = /** @type {!Array.<!Persistence.IsolatedFileSystemManager.FileSystem>} */ (event.data); const promises = []; - for (let i = 0; i < fileSystems.length; ++i) + for (let i = 0; i < fileSystems.length; ++i) { promises.push(this._innerAddFileSystem(fileSystems[i], false)); + } Promise.all(promises).then(onFileSystemsAdded); } @@ -137,11 +138,13 @@ * @this {Persistence.IsolatedFileSystemManager} */ function storeFileSystem(fileSystem) { - if (!fileSystem) + if (!fileSystem) { return null; + } this._fileSystems.set(fileSystemURL, fileSystem); - if (dispatchEvent) + if (dispatchEvent) { this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemAdded, fileSystem); + } return fileSystem; } } @@ -163,8 +166,9 @@ let fileSystem = /** @type {?Persistence.IsolatedFileSystemManager.FileSystem} */ (event.data['fileSystem']); if (errorMessage) { Common.console.error(Common.UIString('Unable to add filesystem: %s', errorMessage)); - if (!this._fileSystemRequestResolve) + if (!this._fileSystemRequestResolve) { return; + } this._fileSystemRequestResolve.call(null, null); this._fileSystemRequestResolve = null; } else if (fileSystem) { @@ -183,8 +187,9 @@ const embedderPath = /** @type {string} */ (event.data); const fileSystemPath = Common.ParsedURL.platformPathToURL(embedderPath); const isolatedFileSystem = this._fileSystems.get(fileSystemPath); - if (!isolatedFileSystem) + if (!isolatedFileSystem) { return; + } this._fileSystems.delete(fileSystemPath); isolatedFileSystem.fileSystemRemoved(); this.dispatchEventToListeners(Persistence.IsolatedFileSystemManager.Events.FileSystemRemoved, isolatedFileSystem); @@ -212,11 +217,13 @@ for (const embedderPath of embedderPaths) { const filePath = Common.ParsedURL.platformPathToURL(embedderPath); for (const fileSystemPath of this._fileSystems.keys()) { - if (this._fileSystems.get(fileSystemPath).isFileExcluded(embedderPath)) + if (this._fileSystems.get(fileSystemPath).isFileExcluded(embedderPath)) { continue; + } const pathPrefix = fileSystemPath.endsWith('/') ? fileSystemPath : fileSystemPath + '/'; - if (!filePath.startsWith(pathPrefix)) + if (!filePath.startsWith(pathPrefix)) { continue; + } paths.set(fileSystemPath, filePath); } } @@ -251,12 +258,13 @@ ]; const defaultLinuxExcludedFolders = ['/.*~$']; let defaultExcludedFolders = defaultCommonExcludedFolders; - if (Host.isWin()) + if (Host.isWin()) { defaultExcludedFolders = defaultExcludedFolders.concat(defaultWinExcludedFolders); - else if (Host.isMac()) + } else if (Host.isMac()) { defaultExcludedFolders = defaultExcludedFolders.concat(defaultMacExcludedFolders); - else + } else { defaultExcludedFolders = defaultExcludedFolders.concat(defaultLinuxExcludedFolders); + } const defaultExcludedFoldersPattern = defaultExcludedFolders.join('|'); this._workspaceFolderExcludePatternSetting = Common.settings.createRegExpSetting( 'workspaceFolderExcludePattern', defaultExcludedFoldersPattern, Host.isWin() ? 'i' : ''); @@ -297,8 +305,9 @@ const totalWork = /** @type {number} */ (event.data['totalWork']); const progress = this._progresses.get(requestId); - if (!progress) + if (!progress) { return; + } progress.setTotalWork(totalWork); } @@ -310,8 +319,9 @@ const worked = /** @type {number} */ (event.data['worked']); const progress = this._progresses.get(requestId); - if (!progress) + if (!progress) { return; + } progress.worked(worked); if (progress.isCanceled()) { InspectorFrontendHost.stopIndexing(requestId); @@ -326,8 +336,9 @@ const requestId = /** @type {number} */ (event.data['requestId']); const progress = this._progresses.get(requestId); - if (!progress) + if (!progress) { return; + } progress.done(); this._progresses.delete(requestId); } @@ -340,8 +351,9 @@ const files = /** @type {!Array.<string>} */ (event.data['files']); const callback = this._callbacks.get(requestId); - if (!callback) + if (!callback) { return; + } callback.call(null, files); this._callbacks.delete(requestId); }
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/NetworkPersistenceManager.js b/third_party/blink/renderer/devtools/front_end/persistence/NetworkPersistenceManager.js index 23d10fb..a1f591c 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/NetworkPersistenceManager.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/NetworkPersistenceManager.js
@@ -64,15 +64,17 @@ * @return {?Promise<?string>} */ originalContentForUISourceCode(uiSourceCode) { - if (!uiSourceCode[this._bindingSymbol]) + if (!uiSourceCode[this._bindingSymbol]) { return null; + } const fileSystemUISourceCode = uiSourceCode[this._bindingSymbol].fileSystem; return fileSystemUISourceCode[this._originalResponseContentPromiseSymbol] || null; } _enabledChanged() { - if (this._enabled === this._enabledSetting.get()) + if (this._enabled === this._enabledSetting.get()) { return; + } this._enabled = this._enabledSetting.get(); if (this._enabled) { this._eventDescriptors = [ @@ -104,14 +106,16 @@ _updateActiveProject() { const wasActive = this._active; this._active = !!(this._enabledSetting.get() && SDK.targetManager.mainTarget() && this._project); - if (this._active === wasActive) + if (this._active === wasActive) { return; + } if (this._active) { this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this)); const networkProjects = this._workspace.projectsForType(Workspace.projectTypes.Network); - for (const networkProject of networkProjects) + for (const networkProject of networkProjects) { networkProject.uiSourceCodes().forEach(this._networkUISourceCodeAdded.bind(this)); + } } else if (this._project) { this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this)); this._networkUISourceCodeForEncodedPath.clear(); @@ -124,11 +128,13 @@ * @return {string} */ _encodedPathFromUrl(url) { - if (!this._active) + if (!this._active) { return ''; + } let urlPath = Common.ParsedURL.urlWithoutHash(url.replace(/^https?:\/\//, '')); - if (urlPath.endsWith('/') && urlPath.indexOf('?') === -1) + if (urlPath.endsWith('/') && urlPath.indexOf('?') === -1) { urlPath = urlPath + 'index.html'; + } let encodedPathParts = encodeUrlPathToLocalPathParts(urlPath); const projectPath = Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id()); const encodedPath = encodedPathParts.join('/'); @@ -150,17 +156,20 @@ function encodeUrlPathToLocalPathParts(urlPath) { const encodedParts = []; for (const pathPart of fileNamePartsFromUrlPath(urlPath)) { - if (!pathPart) + if (!pathPart) { continue; + } // encodeURI() escapes all the unsafe filename characters except /:?* let encodedName = encodeURI(pathPart).replace(/[\/:\?\*]/g, match => '%' + match[0].charCodeAt(0).toString(16)); // Windows does not allow a small set of filenames. - if (Persistence.NetworkPersistenceManager._reservedFileNames.has(encodedName.toLowerCase())) + if (Persistence.NetworkPersistenceManager._reservedFileNames.has(encodedName.toLowerCase())) { encodedName = encodedName.split('').map(char => '%' + char.charCodeAt(0).toString(16)).join(''); + } // Windows does not allow the file to end in a space or dot (space should already be encoded). const lastChar = encodedName.charAt(encodedName.length - 1); - if (lastChar === '.') + if (lastChar === '.') { encodedName = encodedName.substr(0, encodedName.length - 1) + '%2e'; + } encodedParts.push(encodedName); } return encodedParts; @@ -173,10 +182,12 @@ function fileNamePartsFromUrlPath(urlPath) { urlPath = Common.ParsedURL.urlWithoutHash(urlPath); const queryIndex = urlPath.indexOf('?'); - if (queryIndex === -1) + if (queryIndex === -1) { return urlPath.split('/'); - if (queryIndex === 0) + } + if (queryIndex === 0) { return [urlPath]; + } const endSection = urlPath.substr(queryIndex); const parts = urlPath.substr(0, urlPath.length - endSection.length).split('/'); parts[parts.length - 1] += endSection; @@ -202,8 +213,9 @@ */ _unbind(uiSourceCode) { const binding = uiSourceCode[this._bindingSymbol]; - if (!binding) + if (!binding) { return; + } delete binding.network[this._bindingSymbol]; delete binding.fileSystem[this._bindingSymbol]; Persistence.persistence.removeBinding(binding); @@ -214,10 +226,12 @@ * @param {!Workspace.UISourceCode} fileSystemUISourceCode */ async _bind(networkUISourceCode, fileSystemUISourceCode) { - if (networkUISourceCode[this._bindingSymbol]) + if (networkUISourceCode[this._bindingSymbol]) { this._unbind(networkUISourceCode); - if (fileSystemUISourceCode[this._bindingSymbol]) + } + if (fileSystemUISourceCode[this._bindingSymbol]) { this._unbind(fileSystemUISourceCode); + } const binding = new Persistence.PersistenceBinding(networkUISourceCode, fileSystemUISourceCode); networkUISourceCode[this._bindingSymbol] = binding; fileSystemUISourceCode[this._bindingSymbol] = binding; @@ -247,8 +261,9 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ async saveUISourceCodeForOverrides(uiSourceCode) { - if (!this.canSaveUISourceCodeForOverrides(uiSourceCode)) + if (!this.canSaveUISourceCodeForOverrides(uiSourceCode)) { return; + } uiSourceCode[this._savingSymbol] = true; let encodedPath = this._encodedPathFromUrl(uiSourceCode.url()); const content = await uiSourceCode.requestContent(); @@ -274,10 +289,12 @@ */ _patternForFileSystemUISourceCode(uiSourceCode) { const relativePathParts = Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode); - if (relativePathParts.length < 2) + if (relativePathParts.length < 2) { return ''; - if (relativePathParts[1] === 'longurls' && relativePathParts.length !== 2) + } + if (relativePathParts[1] === 'longurls' && relativePathParts.length !== 2) { return 'http?://' + relativePathParts[0] + '/*'; + } return 'http?://' + this._decodeLocalPathToUrlPath(relativePathParts.join('/')); } @@ -301,15 +318,17 @@ */ _networkUISourceCodeAdded(uiSourceCode) { if (uiSourceCode.project().type() !== Workspace.projectTypes.Network || - !this._canHandleNetworkUISourceCode(uiSourceCode)) + !this._canHandleNetworkUISourceCode(uiSourceCode)) { return; + } const url = Common.ParsedURL.urlWithoutHash(uiSourceCode.url()); this._networkUISourceCodeForEncodedPath.set(this._encodedPathFromUrl(url), uiSourceCode); const fileSystemUISourceCode = this._project.uiSourceCodeForURL(this._project.fileSystemPath() + '/' + this._encodedPathFromUrl(url)); - if (!fileSystemUISourceCode) + if (!fileSystemUISourceCode) { return; + } this._bind(uiSourceCode, fileSystemUISourceCode); } @@ -317,14 +336,16 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _filesystemUISourceCodeAdded(uiSourceCode) { - if (!this._active || uiSourceCode.project() !== this._project) + if (!this._active || uiSourceCode.project() !== this._project) { return; + } this._updateInterceptionPatterns(); const relativePath = Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode); const networkUISourceCode = this._networkUISourceCodeForEncodedPath.get(relativePath.join('/')); - if (networkUISourceCode) + if (networkUISourceCode) { this._bind(networkUISourceCode, uiSourceCode); + } } _updateInterceptionPatterns() { @@ -335,15 +356,17 @@ * @return {!Promise} */ function innerUpdateInterceptionPatterns() { - if (!this._active) + if (!this._active) { return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns([], this._interceptionHandlerBound); + } const patterns = new Set(); const indexFileName = 'index.html'; for (const uiSourceCode of this._project.uiSourceCodes()) { const pattern = this._patternForFileSystemUISourceCode(uiSourceCode); patterns.add(pattern); - if (pattern.endsWith('/' + indexFileName)) + if (pattern.endsWith('/' + indexFileName)) { patterns.add(pattern.substr(0, pattern.length - indexFileName.length)); + } } return SDK.multitargetNetworkManager.setInterceptionHandlerForPatterns( @@ -366,8 +389,9 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _networkUISourceCodeRemoved(uiSourceCode) { - if (uiSourceCode.project().type() !== Workspace.projectTypes.Network) + if (uiSourceCode.project().type() !== Workspace.projectTypes.Network) { return; + } this._unbind(uiSourceCode); this._networkUISourceCodeForEncodedPath.delete(this._encodedPathFromUrl(uiSourceCode.url())); } @@ -376,24 +400,28 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _filesystemUISourceCodeRemoved(uiSourceCode) { - if (uiSourceCode.project() !== this._project) + if (uiSourceCode.project() !== this._project) { return; + } this._updateInterceptionPatterns(); delete uiSourceCode[this._originalResponseContentPromiseSymbol]; this._unbind(uiSourceCode); } _setProject(project) { - if (project === this._project) + if (project === this._project) { return; + } - if (this._project) + if (this._project) { this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeRemoved.bind(this)); + } this._project = project; - if (this._project) + if (this._project) { this._project.uiSourceCodes().forEach(this._filesystemUISourceCodeAdded.bind(this)); + } this._updateActiveProject(); this.dispatchEventToListeners(Persistence.NetworkPersistenceManager.Events.ProjectChanged, this._project); @@ -404,13 +432,16 @@ */ _onProjectAdded(project) { if (project.type() !== Workspace.projectTypes.FileSystem || - Persistence.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides') + Persistence.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides') { return; + } const fileSystemPath = Persistence.FileSystemWorkspaceBinding.fileSystemPath(project.id()); - if (!fileSystemPath) + if (!fileSystemPath) { return; - if (this._project) + } + if (this._project) { this._project.remove(); + } this._setProject(project); } @@ -419,8 +450,9 @@ * @param {!Workspace.Project} project */ _onProjectRemoved(project) { - if (project !== this._project) + if (project !== this._project) { return; + } this._setProject(null); } @@ -430,12 +462,14 @@ */ async _interceptionHandler(interceptedRequest) { const method = interceptedRequest.request.method; - if (!this._active || (method !== 'GET' && method !== 'POST')) + if (!this._active || (method !== 'GET' && method !== 'POST')) { return; + } const path = this._project.fileSystemPath() + '/' + this._encodedPathFromUrl(interceptedRequest.request.url); const fileSystemUISourceCode = this._project.uiSourceCodeForURL(path); - if (!fileSystemUISourceCode) + if (!fileSystemUISourceCode) { return; + } let mimeType = ''; if (interceptedRequest.responseHeaders) { @@ -446,16 +480,18 @@ if (!mimeType) { const expectedResourceType = Common.resourceTypes[interceptedRequest.resourceType] || Common.resourceTypes.Other; mimeType = fileSystemUISourceCode.mimeType(); - if (Common.ResourceType.fromMimeType(mimeType) !== expectedResourceType) + if (Common.ResourceType.fromMimeType(mimeType) !== expectedResourceType) { mimeType = expectedResourceType.canonicalMimeType(); + } } const project = /** @type {!Persistence.FileSystemWorkspaceBinding.FileSystem} */ (fileSystemUISourceCode.project()); fileSystemUISourceCode[this._originalResponseContentPromiseSymbol] = interceptedRequest.responseBody().then(response => { - if (response.error || response.content === null) + if (response.error || response.content === null) { return null; + } return response.encoded ? atob(response.content) : response.content; });
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js b/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js index a115455..cc35a397 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/Persistence.js
@@ -107,8 +107,9 @@ * @param {!Persistence.PersistenceBinding} binding */ _innerRemoveBinding(binding) { - if (binding.network[Persistence.Persistence._binding] !== binding) + if (binding.network[Persistence.Persistence._binding] !== binding) { return; + } console.assert( binding.network[Persistence.Persistence._binding] === binding.fileSystem[Persistence.Persistence._binding], 'ERROR: inconsistent binding for networkURL ' + binding.network.url()); @@ -163,8 +164,9 @@ */ _syncWorkingCopy(uiSourceCode) { const binding = uiSourceCode[Persistence.Persistence._binding]; - if (!binding || binding[Persistence.Persistence._muteWorkingCopy]) + if (!binding || binding[Persistence.Persistence._muteWorkingCopy]) { return; + } const other = binding.network === uiSourceCode ? binding.fileSystem : binding.network; if (!uiSourceCode.isDirty()) { binding[Persistence.Persistence._muteWorkingCopy] = true; @@ -214,8 +216,9 @@ */ syncContent(uiSourceCode, newContent, encoded) { const binding = uiSourceCode[Persistence.Persistence._binding]; - if (!binding || binding[Persistence.Persistence._muteCommit]) + if (!binding || binding[Persistence.Persistence._muteCommit]) { return; + } const other = binding.network === uiSourceCode ? binding.fileSystem : binding.network; const target = Bindings.NetworkProject.targetForUISourceCode(binding.network); if (target.type() === SDK.Target.Type.Node) { @@ -252,14 +255,17 @@ newContent = newContent.substring( Persistence.Persistence._NodePrefix.length, newContent.length - Persistence.Persistence._NodeSuffix.length); } - if (currentContent.startsWith(Persistence.Persistence._NodeShebang)) + if (currentContent.startsWith(Persistence.Persistence._NodeShebang)) { newContent = Persistence.Persistence._NodeShebang + newContent; + } } else { - if (newContent.startsWith(Persistence.Persistence._NodeShebang)) + if (newContent.startsWith(Persistence.Persistence._NodeShebang)) { newContent = newContent.substring(Persistence.Persistence._NodeShebang.length); + } if (currentContent.startsWith(Persistence.Persistence._NodePrefix) && - currentContent.endsWith(Persistence.Persistence._NodeSuffix)) + currentContent.endsWith(Persistence.Persistence._NodeSuffix)) { newContent = Persistence.Persistence._NodePrefix + newContent + Persistence.Persistence._NodeSuffix; + } } return newContent; } @@ -286,12 +292,15 @@ * @return {boolean} */ hasUnsavedCommittedChanges(uiSourceCode) { - if (this._workspace.hasResourceContentTrackingExtensions()) + if (this._workspace.hasResourceContentTrackingExtensions()) { return false; - if (uiSourceCode.project().canSetFileContent()) + } + if (uiSourceCode.project().canSetFileContent()) { return false; - if (uiSourceCode[Persistence.Persistence._binding]) + } + if (uiSourceCode[Persistence.Persistence._binding]) { return false; + } return !!uiSourceCode.hasCommits(); } @@ -323,11 +332,13 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _notifyBindingEvent(uiSourceCode) { - if (!this._subscribedBindingEventListeners.has(uiSourceCode)) + if (!this._subscribedBindingEventListeners.has(uiSourceCode)) { return; + } const listeners = Array.from(this._subscribedBindingEventListeners.get(uiSourceCode)); - for (const listener of listeners) + for (const listener of listeners) { listener.call(null); + } } /** @@ -368,10 +379,11 @@ for (const token of filePath.split('/')) { relative += token + '/'; const count = this._filePathPrefixesToBindingCount.get(relative); - if (count === 1) + if (count === 1) { this._filePathPrefixesToBindingCount.delete(relative); - else + } else { this._filePathPrefixesToBindingCount.set(relative, count - 1); + } } } @@ -380,8 +392,9 @@ * @return {boolean} */ filePathHasBindings(filePath) { - if (!filePath.endsWith('/')) + if (!filePath.endsWith('/')) { filePath += '/'; + } return this._filePathPrefixesToBindingCount.has(filePath); } };
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js b/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js index 53ebe75..a286f5e 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/PersistenceActions.js
@@ -18,18 +18,21 @@ appendApplicableItems(event, contextMenu, target) { const contentProvider = /** @type {!Common.ContentProvider} */ (target); async function saveAs() { - if (contentProvider instanceof Workspace.UISourceCode) + if (contentProvider instanceof Workspace.UISourceCode) { /** @type {!Workspace.UISourceCode} */ (contentProvider).commitWorkingCopy(); + } let content = await contentProvider.requestContent(); - if (await contentProvider.contentEncoded()) + if (await contentProvider.contentEncoded()) { content = window.atob(content); + } const url = contentProvider.contentURL(); Workspace.fileManager.save(url, /** @type {string} */ (content), true); Workspace.fileManager.close(url); } - if (contentProvider.contentType().isDocumentOrScriptOrStyleSheet()) + if (contentProvider.contentType().isDocumentOrScriptOrStyleSheet()) { contextMenu.saveSection().appendItem(Common.UIString('Save as...'), saveAs); + } // Retrieve uiSourceCode by URL to pick network resources everywhere. const uiSourceCode = Workspace.workspace.uiSourceCodeForURL(contentProvider.contentURL());
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/PersistenceUtils.js b/third_party/blink/renderer/devtools/front_end/persistence/PersistenceUtils.js index ec923cf..d99ae30 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/PersistenceUtils.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/PersistenceUtils.js
@@ -9,12 +9,15 @@ */ static tooltipForUISourceCode(uiSourceCode) { const binding = Persistence.persistence.binding(uiSourceCode); - if (!binding) + if (!binding) { return ''; - if (uiSourceCode === binding.network) + } + if (uiSourceCode === binding.network) { return Persistence.FileSystemWorkspaceBinding.tooltipForUISourceCode(binding.fileSystem); - if (binding.network.contentType().isFromSourceMap()) + } + if (binding.network.contentType().isFromSourceMap()) { return Common.UIString('Linked to source map: %s', binding.network.url().trimMiddle(150)); + } return Common.UIString('Linked to %s', binding.network.url().trimMiddle(150)); } @@ -25,18 +28,21 @@ static iconForUISourceCode(uiSourceCode) { const binding = Persistence.persistence.binding(uiSourceCode); if (binding) { - if (!binding.fileSystem.url().startsWith('file://')) + if (!binding.fileSystem.url().startsWith('file://')) { return null; + } const icon = UI.Icon.create('mediumicon-file-sync'); icon.title = Persistence.PersistenceUtils.tooltipForUISourceCode(binding.network); // TODO(allada) This will not work properly with dark theme. - if (Persistence.networkPersistenceManager.project() === binding.fileSystem.project()) + if (Persistence.networkPersistenceManager.project() === binding.fileSystem.project()) { icon.style.filter = 'hue-rotate(160deg)'; + } return icon; } if (uiSourceCode.project().type() !== Workspace.projectTypes.FileSystem || - !uiSourceCode.url().startsWith('file://')) + !uiSourceCode.url().startsWith('file://')) { return null; + } const icon = UI.Icon.create('mediumicon-file'); icon.title = Persistence.PersistenceUtils.tooltipForUISourceCode(uiSourceCode);
diff --git a/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js b/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js index f0e40db..75b0a8f 100644 --- a/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/persistence/WorkspaceSettingsTab.js
@@ -40,8 +40,9 @@ this._mappingViewByPath = new Map(); const fileSystems = Persistence.isolatedFileSystemManager.fileSystems(); - for (let i = 0; i < fileSystems.length; ++i) + for (let i = 0; i < fileSystems.length; ++i) { this._addItem(fileSystems[i]); + } } /** @@ -82,12 +83,14 @@ */ _addItem(fileSystem) { // Support managing only instances of IsolatedFileSystem. - if (!(fileSystem instanceof Persistence.IsolatedFileSystem)) + if (!(fileSystem instanceof Persistence.IsolatedFileSystem)) { return; + } const networkPersistenceProject = Persistence.networkPersistenceManager.project(); if (networkPersistenceProject && - Persistence.isolatedFileSystemManager.fileSystem(networkPersistenceProject.fileSystemPath()) === fileSystem) + Persistence.isolatedFileSystemManager.fileSystem(networkPersistenceProject.fileSystemPath()) === fileSystem) { return; + } const element = this._renderFileSystem(fileSystem); this._elementByPath.set(fileSystem.path(), element);
diff --git a/third_party/blink/renderer/devtools/front_end/platform/utilities.js b/third_party/blink/renderer/devtools/front_end/platform/utilities.js index 31973aa..2d832eb 100644 --- a/third_party/blink/renderer/devtools/front_end/platform/utilities.js +++ b/third_party/blink/renderer/devtools/front_end/platform/utilities.js
@@ -95,13 +95,15 @@ } } - if (!foundChar) + if (!foundChar) { return String(this); + } let result = ''; for (let i = 0; i < this.length; ++i) { - if (chars.indexOf(this.charAt(i)) !== -1) + if (chars.indexOf(this.charAt(i)) !== -1) { result += '\\'; + } result += this.charAt(i); } @@ -131,10 +133,12 @@ let regexString = ''; for (let i = 0; i < query.length; ++i) { let c = query.charAt(i); - if (toEscape.indexOf(c) !== -1) + if (toEscape.indexOf(c) !== -1) { c = '\\' + c; - if (i) + } + if (i) { regexString += '[^\\0' + c + ']*'; + } regexString += c; } return new RegExp(regexString, 'i'); @@ -148,19 +152,22 @@ if (!String._invalidCharactersRegExp) { // Escape orphan surrogates and invalid characters. let invalidCharacters = ''; - for (let i = 0xfffe; i <= 0x10ffff; i += 0x10000) + for (let i = 0xfffe; i <= 0x10ffff; i += 0x10000) { invalidCharacters += String.fromCodePoint(i, i + 1); + } String._invalidCharactersRegExp = new RegExp(`[${invalidCharacters}\uD800-\uDFFF\uFDD0-\uFDEF]`, 'gu'); } let result = ''; let lastPos = 0; while (true) { const match = String._invalidCharactersRegExp.exec(text); - if (!match) + if (!match) { break; + } result += text.substring(lastPos, match.index) + '\\u' + text.charCodeAt(match.index).toString(16); - if (match.index + 1 < String._invalidCharactersRegExp.lastIndex) + if (match.index + 1 < String._invalidCharactersRegExp.lastIndex) { result += '\\u' + text.charCodeAt(match.index + 1).toString(16); + } lastPos = String._invalidCharactersRegExp.lastIndex; } return result + text.substring(lastPos); @@ -201,16 +208,18 @@ * @return {string} */ String.prototype.trimMiddle = function(maxLength) { - if (this.length <= maxLength) + if (this.length <= maxLength) { return String(this); + } let leftHalf = maxLength >> 1; let rightHalf = maxLength - leftHalf - 1; if (this.codePointAt(this.length - rightHalf - 1) >= 0x10000) { --rightHalf; ++leftHalf; } - if (leftHalf > 0 && this.codePointAt(leftHalf - 1) >= 0x10000) + if (leftHalf > 0 && this.codePointAt(leftHalf - 1) >= 0x10000) { --leftHalf; + } return this.substr(0, leftHalf) + '\u2026' + this.substr(this.length - rightHalf, rightHalf); }; @@ -219,8 +228,9 @@ * @return {string} */ String.prototype.trimEndWithMaxLength = function(maxLength) { - if (this.length <= maxLength) + if (this.length <= maxLength) { return String(this); + } return this.substr(0, maxLength - 1) + '\u2026'; }; @@ -231,8 +241,9 @@ String.prototype.trimURL = function(baseURLDomain) { let result = this.replace(/^(https|http|file):\/\//i, ''); if (baseURLDomain) { - if (result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) + if (result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) { result = result.substr(baseURLDomain.length); + } } return result; }; @@ -249,10 +260,12 @@ * @return {number} */ String.prototype.compareTo = function(other) { - if (this > other) + if (this > other) { return 1; - if (this < other) + } + if (this < other) { return -1; + } return 0; }; @@ -261,8 +274,9 @@ */ String.prototype.removeURLFragment = function() { let fragmentIndex = this.indexOf('#'); - if (fragmentIndex === -1) + if (fragmentIndex === -1) { fragmentIndex = this.length; + } return this.substring(0, fragmentIndex); }; @@ -271,8 +285,9 @@ * @return {number} */ String.hashCode = function(string) { - if (!string) + if (!string) { return 0; + } // Hash algorithm for substrings is described in "Über die Komplexität der Multiplikation in // eingeschränkten Branchingprogrammmodellen" by Woelfe. // http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000 @@ -315,8 +330,9 @@ const data = encoder.encode(this.toString()); const n = data.length; let encoded = ''; - if (n === 0) + if (n === 0) { return encoded; + } let shift; let v = 0; for (let i = 0; i < n; i++) { @@ -328,10 +344,11 @@ v = 0; } } - if (shift === 0) + if (shift === 0) { encoded += String.fromCharCode(encodeBits(v >>> 18 & 63), encodeBits(v >>> 12 & 63), 61, 61); - else if (shift === 1) + } else if (shift === 1) { encoded += String.fromCharCode(encodeBits(v >>> 18 & 63), encodeBits(v >>> 12 & 63), encodeBits(v >>> 6 & 63), 61); + } return encoded; }; @@ -345,31 +362,38 @@ let chunka, chunkb, anum, bnum; while (1) { if (a) { - if (!b) + if (!b) { return 1; + } } else { - if (b) + if (b) { return -1; - else + } else { return 0; + } } chunka = a.match(chunk)[0]; chunkb = b.match(chunk)[0]; anum = !isNaN(chunka); bnum = !isNaN(chunkb); - if (anum && !bnum) + if (anum && !bnum) { return -1; - if (bnum && !anum) + } + if (bnum && !anum) { return 1; + } if (anum && bnum) { const diff = chunka - chunkb; - if (diff) + if (diff) { return diff; + } if (chunka.length !== chunkb.length) { - if (! + chunka && ! + chunkb) // chunks are strings of all 0s (special case) + if (!+chunka && !+chunkb) // chunks are strings of all 0s (special case) + { return chunka.length - chunkb.length; - else + } else { return chunkb.length - chunka.length; + } } } else if (chunka !== chunkb) { return (chunka < chunkb) ? -1 : 1; @@ -387,8 +411,9 @@ String.caseInsensetiveComparator = function(a, b) { a = a.toUpperCase(); b = b.toUpperCase(); - if (a === b) + if (a === b) { return 0; + } return a > b ? 1 : -1; }; @@ -399,10 +424,11 @@ * @return {number} */ Number.constrain = function(num, min, max) { - if (num < min) + if (num < min) { num = min; - else if (num > max) + } else if (num > max) { num = max; + } return num; }; @@ -412,10 +438,11 @@ * @return {number} */ Number.gcd = function(a, b) { - if (b === 0) + if (b === 0) { return a; - else + } else { return Number.gcd(b, a % b); + } }; /** @@ -423,8 +450,9 @@ * @return {string} */ Number.toFixedIfFloating = function(value) { - if (!value || isNaN(value)) + if (!value || isNaN(value)) { return value; + } const number = Number(value); return number % 1 ? number.toFixed(3) : String(number); }; @@ -461,15 +489,17 @@ */ value: function(value, firstOnly) { let index = this.indexOf(value); - if (index === -1) + if (index === -1) { return false; + } if (firstOnly) { this.splice(index, 1); return true; } for (let i = index + 1, n = this.length; i < n; ++i) { - if (this[i] !== value) + if (this[i] !== value) { this[index++] = this[i]; + } } this.length = index; return true; @@ -483,8 +513,9 @@ * @template T */ value: function(array) { - for (let i = 0; i < array.length; ++i) + for (let i = 0; i < array.length; ++i) { this.push(array[i]); + } } }); @@ -497,8 +528,9 @@ */ value: function(index) { const result = []; - for (let i = index; i < index + this.length; ++i) + for (let i = index; i < index + this.length; ++i) { result.push(this[i % this.length]); + } return result; } }); @@ -565,19 +597,23 @@ */ value: function(comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight) { function quickSortRange(array, comparator, left, right, sortWindowLeft, sortWindowRight) { - if (right <= left) + if (right <= left) { return; + } const pivotIndex = Math.floor(Math.random() * (right - left)) + left; const pivotNewIndex = array.partition(comparator, left, right, pivotIndex); - if (sortWindowLeft < pivotNewIndex) + if (sortWindowLeft < pivotNewIndex) { quickSortRange(array, comparator, left, pivotNewIndex - 1, sortWindowLeft, sortWindowRight); - if (pivotNewIndex < sortWindowRight) + } + if (pivotNewIndex < sortWindowRight) { quickSortRange(array, comparator, pivotNewIndex + 1, right, sortWindowLeft, sortWindowRight); + } } - if (leftBound === 0 && rightBound === (this.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound) + if (leftBound === 0 && rightBound === (this.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound) { this.sort(comparator); - else + } else { quickSortRange(this, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight); + } return this; } }; @@ -611,10 +647,11 @@ let r = right !== undefined ? right : this.length; while (l < r) { const m = (l + r) >> 1; - if (comparator(object, this[m]) > 0) + if (comparator(object, this[m]) > 0) { l = m + 1; - else + } else { r = m; + } } return r; } @@ -646,10 +683,11 @@ let r = right !== undefined ? right : this.length; while (l < r) { const m = (l + r) >> 1; - if (comparator(object, this[m]) >= 0) + if (comparator(object, this[m]) >= 0) { l = m + 1; - else + } else { r = m; + } } return r; } @@ -688,8 +726,9 @@ */ value: function(field) { const result = new Array(this.length); - for (let i = 0; i < this.length; ++i) + for (let i = 0; i < this.length; ++i) { result[i] = this[i][field]; + } return result; } }); @@ -720,18 +759,23 @@ let j = 0; while (i < array1.length && j < array2.length) { const compareValue = comparator(array1[i], array2[j]); - if (mergeNotIntersect || !compareValue) + if (mergeNotIntersect || !compareValue) { result.push(compareValue <= 0 ? array1[i] : array2[j]); - if (compareValue <= 0) + } + if (compareValue <= 0) { i++; - if (compareValue >= 0) + } + if (compareValue >= 0) { j++; + } } if (mergeNotIntersect) { - while (i < array1.length) + while (i < array1.length) { result.push(array1[i++]); - while (j < array2.length) + } + while (j < array2.length) { result.push(array2[j++]); + } } return result; } @@ -781,12 +825,14 @@ const tokens = []; function addStringToken(str) { - if (!str) + if (!str) { return; - if (tokens.length && tokens[tokens.length - 1].type === 'string') + } + if (tokens.length && tokens[tokens.length - 1].type === 'string') { tokens[tokens.length - 1].value += str; - else + } else { tokens.push({type: 'string', value: str}); + } } function addSpecifierToken(specifier, precision, substitutionIndex) { @@ -800,11 +846,13 @@ ['darkGray', 'lightRed', 'lightGreen', 'lightYellow', 'lightBlue', 'lightMagenta', 'lightCyan', 'white', '']; const colors = {color: colorCodes, colorLight: colorCodesLight, bgColor: colorCodes, bgColorLight: colorCodesLight}; const type = types[Math.floor(code / 10)]; - if (!type) + if (!type) { return; + } const color = colors[type][code % 10]; - if (!color) + if (!color) { return; + } tokens.push({ type: 'specifier', specifier: 'c', @@ -818,16 +866,18 @@ new RegExp(`%%|%(?:(\\d+)\\$)?(?:\\.(\\d*))?([${Object.keys(formatters).join('')}])|\\u001b\\[(\\d+)m`, 'g'); for (let match = re.exec(format); !!match; match = re.exec(format)) { const matchStart = match.index; - if (matchStart > textStart) + if (matchStart > textStart) { addStringToken(format.substring(textStart, matchStart)); + } if (match[0] === '%%') { addStringToken('%'); } else if (match[0].startsWith('%')) { // eslint-disable-next-line no-unused-vars const [_, substitionString, precisionString, specifierString] = match; - if (substitionString && Number(substitionString) > 0) + if (substitionString && Number(substitionString) > 0) { substitutionIndex = Number(substitionString) - 1; + } const precision = precisionString ? Number(precisionString) : -1; addSpecifierToken(specifierString, precision, substitutionIndex); ++substitutionIndex; @@ -853,8 +903,9 @@ * @return {number} */ f: function(substitution, token) { - if (substitution && token.precision > -1) + if (substitution && token.precision > -1) { substitution = substitution.toFixed(token.precision); + } return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0); }, @@ -892,8 +943,9 @@ * @template T, Q */ String.format = function(format, substitutions, formatters, initialValue, append, tokenizedFormat) { - if (!format || ((!substitutions || !substitutions.length) && format.search(/\u001b\[(\d+)m/) === -1)) + if (!format || ((!substitutions || !substitutions.length) && format.search(/\u001b\[(\d+)m/) === -1)) { return {formattedResult: append(initialValue, format), unusedSubstitutions: substitutions}; + } function prettyFunctionName() { return 'String.format("' + format + '", "' + Array.prototype.join.call(substitutions, '", "') + '")'; @@ -934,8 +986,9 @@ continue; } - if (!token.value) + if (!token.value) { usedSubstitutionIndexes[token.substitutionIndex] = true; + } if (!(token.specifier in formatters)) { // Encountered an unsupported format character, treat as a string. @@ -949,8 +1002,9 @@ const unusedSubstitutions = []; for (let i = 0; i < substitutions.length; ++i) { - if (i in usedSubstitutionIndexes) + if (i in usedSubstitutionIndexes) { continue; + } unusedSubstitutions.push(substitutions[i]); } @@ -975,8 +1029,9 @@ } } - if (!regexObject) + if (!regexObject) { regexObject = self.createPlainTextSearchRegex(query, regexFlags); + } return regexObject; }; @@ -992,8 +1047,9 @@ let regex = ''; for (let i = 0; i < query.length; ++i) { const c = query.charAt(i); - if (regexSpecialCharacters.indexOf(c) !== -1) + if (regexSpecialCharacters.indexOf(c) !== -1) { regex += '\\'; + } regex += c; } return new RegExp(regex, flags || ''); @@ -1009,8 +1065,9 @@ let result = 0; let match; while (text && (match = regex.exec(text))) { - if (match[0].length > 0) + if (match[0].length > 0) { ++result; + } text = text.substring(match.index + 1); } return result; @@ -1048,8 +1105,9 @@ * @template T */ Set.prototype.firstValue = function() { - if (!this.size) + if (!this.size) { return null; + } return this.values().next().value; }; @@ -1058,8 +1116,9 @@ * @template T */ Set.prototype.addAll = function(iterable) { - for (const e of iterable) + for (const e of iterable) { this.add(e); + } }; /** @@ -1069,8 +1128,9 @@ */ Set.prototype.containsAll = function(iterable) { for (const e of iterable) { - if (!this.has(e)) + if (!this.has(e)) { return false; + } } return true; }; @@ -1157,8 +1217,9 @@ */ hasValue: function(key, value) { const set = this._map.get(key); - if (!set) + if (!set) { return false; + } return set.has(value); }, @@ -1176,11 +1237,13 @@ */ delete: function(key, value) { const values = this.get(key); - if (!values) + if (!values) { return false; + } const result = values.delete(value); - if (!values.size) + if (!values.size) { this._map.delete(key); + } return result; }, @@ -1204,8 +1267,9 @@ valuesArray: function() { const result = []; const keys = this.keysArray(); - for (let i = 0; i < keys.length; ++i) + for (let i = 0; i < keys.length; ++i) { result.pushAll(this.get(keys[i]).valuesArray()); + } return result; }, @@ -1223,8 +1287,9 @@ function load(successCallback, failureCallback) { function onReadyStateChanged() { - if (xhr.readyState !== XMLHttpRequest.DONE) + if (xhr.readyState !== XMLHttpRequest.DONE) { return; + } if (xhr.status !== 200) { xhr.onreadystatechange = null; failureCallback(new Error(xhr.status)); @@ -1340,10 +1405,11 @@ callback(); } - if (document.readyState === 'complete' || document.readyState === 'interactive') + if (document.readyState === 'complete' || document.readyState === 'interactive') { callback(); - else + } else { self.addEventListener('DOMContentLoaded', windowLoaded, false); + } }; const _singletonSymbol = Symbol('singleton'); @@ -1354,8 +1420,9 @@ * @return {!T} */ self.singleton = function(constructorFunction) { - if (_singletonSymbol in constructorFunction) + if (_singletonSymbol in constructorFunction) { return constructorFunction[_singletonSymbol]; + } const instance = new constructorFunction(); constructorFunction[_singletonSymbol] = instance; return instance; @@ -1366,12 +1433,15 @@ * @return {number} */ self.base64ToSize = function(content) { - if (!content) + if (!content) { return 0; + } let size = content.length * 3 / 4; - if (content[content.length - 1] === '=') + if (content[content.length - 1] === '=') { size--; - if (content.length > 1 && content[content.length - 2] === '=') + } + if (content.length > 1 && content[content.length - 2] === '=') { size--; + } return size; };
diff --git a/third_party/blink/renderer/devtools/front_end/product_registry/BadgePool.js b/third_party/blink/renderer/devtools/front_end/product_registry/BadgePool.js index c5c06a9b..58e2ced 100644 --- a/third_party/blink/renderer/devtools/front_end/product_registry/BadgePool.js +++ b/third_party/blink/renderer/devtools/front_end/product_registry/BadgePool.js
@@ -13,8 +13,9 @@ if (!forceShow) { this._setting = Common.settings.moduleSetting('product_registry.badges-visible'); this._setting.addChangeListener(this._settingUpdated.bind(this)); - if (this._setting.get()) + if (this._setting.get()) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.ShowedThirdPartyBadges); + } } } @@ -74,8 +75,9 @@ const entry = registry.entryForUrl(parsedUrl); if (!entry) { frame.findCreationCallFrame(callFrame => { - if (!callFrame.url) + if (!callFrame.url) { return false; + } parsedUrl = new Common.ParsedURL(callFrame.url); return !!registry.entryForUrl(parsedUrl); }); @@ -95,15 +97,17 @@ const parsedUrl = await this._badgeElements.get(badgeElement)(); const registry = await ProductRegistry.instance(); const entryName = parsedUrl && registry.nameForUrl(parsedUrl); - if (!entryName) + if (!entryName) { return; + } const tokens = entryName.replace(/[a-z]*/g, '').split(' '); let label; - if (tokens.length > 1) + if (tokens.length > 1) { label = tokens[0][0] + tokens[1][0]; - else + } else { label = entryName; + } const iconElement = badgeElement.createChild('span', 'product-registry-badge monospace'); iconElement.setAttribute('data-initial', label.substring(0, 2).toUpperCase()); @@ -115,8 +119,9 @@ } _settingUpdated() { - for (const badgeElement of this._badgeElements.keys()) + for (const badgeElement of this._badgeElements.keys()) { this._renderBadge(badgeElement); + } } /** @@ -139,8 +144,9 @@ * @param {!Element} badgeElement */ async _showPopup(badgeElement) { - if (!this._badgeElements.has(badgeElement)) + if (!this._badgeElements.has(badgeElement)) { return; + } const registry = await ProductRegistry.instance(); const parsedUrl = await this._badgeElements.get(badgeElement)();
diff --git a/third_party/blink/renderer/devtools/front_end/product_registry/ProductRegistry.js b/third_party/blink/renderer/devtools/front_end/product_registry/ProductRegistry.js index dd0183c..92128a7 100644 --- a/third_party/blink/renderer/devtools/front_end/product_registry/ProductRegistry.js +++ b/third_party/blink/renderer/devtools/front_end/product_registry/ProductRegistry.js
@@ -6,8 +6,9 @@ */ ProductRegistry.instance = function() { const extension = self.runtime.extension(ProductRegistry.Registry); - if (extension) + if (extension) { return extension.instance(); + } // TODO(tvanderlippe): Remove type-cast once Closure compiler is updated to latest version. return Promise.resolve(/** @type {!ProductRegistry.Registry} */ (self.singleton(ProductRegistry.RegistryStub))); };
diff --git a/third_party/blink/renderer/devtools/front_end/product_registry_impl/ProductRegistryImpl.js b/third_party/blink/renderer/devtools/front_end/product_registry_impl/ProductRegistryImpl.js index fb3f4939..0a8d28b7 100644 --- a/third_party/blink/renderer/devtools/front_end/product_registry_impl/ProductRegistryImpl.js +++ b/third_party/blink/renderer/devtools/front_end/product_registry_impl/ProductRegistryImpl.js
@@ -16,8 +16,9 @@ */ nameForUrl(parsedUrl) { const entry = this.entryForUrl(parsedUrl); - if (entry) + if (entry) { return entry.name; + } return null; } @@ -27,8 +28,9 @@ * @return {?ProductRegistry.Registry.ProductEntry} */ entryForUrl(parsedUrl) { - if (parsedUrl.isDataURL() || !parsedUrl.isValid) + if (parsedUrl.isDataURL() || !parsedUrl.isValid) { return null; + } // TODO(allada) This should be expanded to allow paths as as well as domain to find a product. const productsByDomainHash = ProductRegistryImpl._productsByDomainHash; // Remove leading www. if it is the only subdomain. @@ -43,21 +45,25 @@ const prefixes = productsByDomainHash.get(ProductRegistryImpl._hashForDomain(subDomain)); previousIndex = index; index = nextIndex; - if (!prefixes) + if (!prefixes) { continue; + } // Exact match domains are always highest priority. - if ('' in prefixes && domain === subDomain) + if ('' in prefixes && domain === subDomain) { return prefixes['']; + } if (previousSubdomain) { for (const prefix in prefixes) { const domainPrefix = previousSubdomain.substr(0, prefix.length); - if (domainPrefix === prefix && prefix !== '') + if (domainPrefix === prefix && prefix !== '') { return prefixes[prefix]; + } } } // Process wildcard subdomain if no better match found. - if (prefixes && '*' in prefixes) + if (prefixes && '*' in prefixes) { return prefixes['*']; + } } return null; } @@ -69,8 +75,9 @@ */ typeForUrl(parsedUrl) { const entry = this.entryForUrl(parsedUrl); - if (entry) + if (entry) { return entry.type; + } return null; } };
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/BottomUpProfileDataGrid.js b/third_party/blink/renderer/devtools/front_end/profiler/BottomUpProfileDataGrid.js index 66e697c7..28a3c5a 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/BottomUpProfileDataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/BottomUpProfileDataGrid.js
@@ -60,8 +60,9 @@ child.self += focusNode.self; - if (!totalAccountedFor) + if (!totalAccountedFor) { child.total += focusNode.total; + } } else { // If not, add it as a true ancestor. // In heavy mode, we take our visual identity from ancestor node... @@ -111,21 +112,24 @@ * @param {string} aCallUID */ _exclude(aCallUID) { - if (this._remainingNodeInfos) + if (this._remainingNodeInfos) { this.populate(); + } this.save(); const children = this.children; let index = this.children.length; - while (index--) + while (index--) { children[index]._exclude(aCallUID); + } const child = this.childrenByCallUID.get(aCallUID); - if (child) + if (child) { this.merge(child, true); + } } /** @@ -134,8 +138,9 @@ restore() { super.restore(); - if (!this.children.length) + if (!this.children.length) { this.setHasChildren(this._willHaveChildren(this.profileNode)); + } } /** @@ -193,8 +198,9 @@ for (let index = 0; index < count; ++index) { const profileNode = profileNodes[index]; - if (!profileNode.UID) + if (!profileNode.UID) { profileNode.UID = ++profileNodeUIDs; + } if (profileNode.parent) { // The total time of this ancestor is accounted for if we're in any form of recursive cycle. @@ -241,8 +247,9 @@ * @param {!Profiler.ProfileDataGridNode} profileDataGridNode */ focus(profileDataGridNode) { - if (!profileDataGridNode) + if (!profileDataGridNode) { return; + } this.save(); @@ -255,8 +262,9 @@ focusNode = currentNode; currentNode = currentNode.parent; - if (currentNode instanceof Profiler.ProfileDataGridNode) + if (currentNode instanceof Profiler.ProfileDataGridNode) { currentNode._keepOnlyChild(focusNode); + } } this.children = [focusNode]; @@ -267,8 +275,9 @@ * @param {!Profiler.ProfileDataGridNode} profileDataGridNode */ exclude(profileDataGridNode) { - if (!profileDataGridNode) + if (!profileDataGridNode) { return; + } this.save(); @@ -277,17 +286,20 @@ // If we have a top level node that is excluded, get rid of it completely (not keeping children), // since bottom up data relies entirely on the root node. - if (excludedTopLevelChild) + if (excludedTopLevelChild) { this.children.remove(excludedTopLevelChild); + } const children = this.children; const count = children.length; - for (let index = 0; index < count; ++index) + for (let index = 0; index < count; ++index) { children[index]._exclude(excludedCallUID); + } - if (this.lastComparator) + if (this.lastComparator) { this.sort(this.lastComparator, true); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileFlameChart.js b/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileFlameChart.js index b628265..3d24520d 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileFlameChart.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileFlameChart.js
@@ -269,14 +269,16 @@ this._searchResults = []; const entriesCount = this._dataProvider._entryNodes.length; for (let index = 0; index < entriesCount; ++index) { - if (this._dataProvider.entryTitle(index).match(matcher)) + if (this._dataProvider.entryTitle(index).match(matcher)) { this._searchResults.push(index); + } } if (this._searchResults.length) { this._searchResultIndex = this._searchResults.indexOf(selectedEntryIndex); - if (this._searchResultIndex === -1) + if (this._searchResultIndex === -1) { this._searchResultIndex = jumpBackwards ? this._searchResults.length - 1 : 0; + } this._mainPane.setSelectedEntry(this._searchResults[this._searchResultIndex]); } else { this.searchCanceled(); @@ -484,16 +486,18 @@ } _scheduleUpdate() { - if (this._updateTimerId) + if (this._updateTimerId) { return; + } this._updateTimerId = this.element.window().requestAnimationFrame(this.update.bind(this)); } update() { this._updateTimerId = 0; const timelineData = this._timelineData(); - if (!timelineData) + if (!timelineData) { return; + } this._resetCanvas( this._overviewContainer.clientWidth, this._overviewContainer.clientHeight - PerfUI.FlameChart.HeaderHeight); this._overviewCalculator._updateBoundaries(this); @@ -548,8 +552,9 @@ const start = Math.floor((entryStartTimes[entryIndex] - minimumBoundary) * scaleFactor); const finish = Math.floor((entryStartTimes[entryIndex] - minimumBoundary + entryTotalTimes[entryIndex]) * scaleFactor); - for (let x = start; x <= finish; ++x) + for (let x = start; x <= finish; ++x) { drawData[x] = Math.max(drawData[x], entryLevels[entryIndex] + 1); + } } return drawData; }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js b/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js index 2df9fb9..9feb28cb 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/CPUProfileView.js
@@ -161,8 +161,9 @@ _startRecordingProfile() { const cpuProfilerModel = UI.context.flavor(SDK.CPUProfilerModel); - if (this.profileBeingRecorded() || !cpuProfilerModel) + if (this.profileBeingRecorded() || !cpuProfilerModel) { return; + } const profile = new Profiler.CPUProfileHeader(cpuProfilerModel, this); this.setProfileBeingRecorded(profile); SDK.targetManager.suspendAllTargets(); @@ -175,8 +176,9 @@ async _stopRecordingProfile() { this._recording = false; - if (!this.profileBeingRecorded() || !this.profileBeingRecorded()._cpuProfilerModel) + if (!this.profileBeingRecorded() || !this.profileBeingRecorded()._cpuProfilerModel) { return; + } const profile = await this.profileBeingRecorded()._cpuProfilerModel.stopRecording(); const recordedProfile = this.profileBeingRecorded(); @@ -379,8 +381,9 @@ prepareHighlightedEntryInfo(entryIndex) { const timelineData = this._timelineData; const node = this._entryNodes[entryIndex]; - if (!node) + if (!node) { return null; + } const entryInfo = []; /** @@ -395,10 +398,12 @@ * @return {string} */ function millisecondsToString(ms) { - if (ms === 0) + if (ms === 0) { return '0'; - if (ms < 1000) + } + if (ms < 1000) { return Common.UIString('%.1f\xa0ms', ms); + } return Number.secondsToString(ms / 1000, true); } const name = UI.beautifyFunctionName(node.functionName); @@ -410,13 +415,15 @@ const linkifier = new Components.Linkifier(); const link = linkifier.maybeLinkifyConsoleCallFrame( this._cpuProfilerModel && this._cpuProfilerModel.target(), node.callFrame); - if (link) + if (link) { pushEntryInfoRow(ls`URL`, link.textContent); + } linkifier.dispose(); pushEntryInfoRow(ls`Aggregated self time`, Number.secondsToString(node.self / 1000, true)); pushEntryInfoRow(ls`Aggregated total time`, Number.secondsToString(node.total / 1000, true)); - if (node.deoptReason) + if (node.deoptReason) { pushEntryInfoRow(ls`Not optimized`, node.deoptReason); + } return Profiler.ProfileView.buildPopoverTable(entryInfo); }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js index 3ea629a..61e0a088 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapProfileView.js
@@ -21,8 +21,9 @@ const isNativeProfile = this._profileType.id === Profiler.SamplingNativeHeapProfileType.TypeId || this._profileType.id === Profiler.SamplingNativeHeapSnapshotType.TypeId; - if (isNativeProfile) + if (isNativeProfile) { views.push(Profiler.ProfileView.ViewTypes.Text); + } this.initialize(new Profiler.HeapProfileView.NodeFormatter(this), views); const profile = new Profiler.SamplingHeapProfileModel(profileHeader._profile || profileHeader.protocolProfile()); @@ -104,8 +105,9 @@ } this._max.push(this._sizes.peekLast()); - if (this._timestamps.peekLast() - this._timestamps[0] > this._totalTime) + if (this._timestamps.peekLast() - this._timestamps[0] > this._totalTime) { this._totalTime *= 2; + } const samples = /** @type {!Profiler.HeapTimelineOverview.Samples} */ ({ sizes: this._sizes, @@ -158,8 +160,9 @@ const modules = this.profile().modules.map( m => Object.assign({address: BigInt(m.baseAddress), endAddress: BigInt(m.baseAddress) + BigInt(m.size)}, m)); modules.sort((m1, m2) => m1.address > m2.address ? 1 : m1.address < m2.address ? -1 : 0); - for (const child of sortedChildren) + for (const child of sortedChildren) { printTree(' ', child !== sortedChildren.peekLast(), child); + } text += '\nBinary Images:\n'; for (const module of modules) { @@ -186,27 +189,31 @@ if (addressText) { const address = BigInt(addressText); const pos = modules.upperBound(address, (address, module) => address - module.address); - if (pos > 0 && address < modules[pos - 1].endAddress) + if (pos > 0 && address < modules[pos - 1].endAddress) { module = modules[pos - 1]; + } } const functionName = (addressText ? node.functionName.substr(addressText.length + 1) : node.functionName) || '???'; text += `${padding}${Math.round(node.total / 1024)} ${functionName} `; if (module) { const fileName = /[^/\\]*$/.exec(module.name); - if (fileName) + if (fileName) { text += `(in ${fileName}) `; + } const offset = BigInt(addressText) - module.address; text += `load address ${module.baseAddress} + 0x${offset.toString(16)} `; } - if (addressText) + if (addressText) { text += `[${addressText}]`; + } text += '\n'; const guideChar = drawGuide ? guides[padding.length / 2 % guides.length] : ' '; const nextPadding = padding + guideChar + ' '; const sortedChildren = node.children.sort((a, b) => b.total - a.total); - for (const child of sortedChildren) + for (const child of sortedChildren) { printTree(nextPadding, child !== sortedChildren.peekLast(), child); + } } } }; @@ -260,17 +267,19 @@ * @return {boolean} */ buttonClicked() { - if (this._recording) + if (this._recording) { this._stopRecordingProfile(); - else + } else { this._startRecordingProfile(); + } return this._recording; } _startRecordingProfile() { const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel); - if (this.profileBeingRecorded() || !heapProfilerModel) + if (this.profileBeingRecorded() || !heapProfilerModel) { return; + } const profileHeader = new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this); this.setProfileBeingRecorded(profileHeader); this.addProfile(profileHeader); @@ -286,8 +295,9 @@ async _stopRecordingProfile() { this._recording = false; - if (!this.profileBeingRecorded() || !this.profileBeingRecorded().heapProfilerModel()) + if (!this.profileBeingRecorded() || !this.profileBeingRecorded().heapProfilerModel()) { return; + } this.profileBeingRecorded().updateStatus(ls`Stopping\u2026`); const profile = await this._stopSampling(); @@ -370,8 +380,9 @@ */ _startSampling() { this.profileBeingRecorded().heapProfilerModel().startSampling(); - if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline')) + if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline')) { this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs); + } } /** @@ -387,8 +398,9 @@ async _updateStats() { const profile = await this.profileBeingRecorded().heapProfilerModel().getSamplingProfile(); - if (!this._updateTimer) + if (!this._updateTimer) { return; + } this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.StatsUpdate, profile); this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs); } @@ -490,11 +502,13 @@ * @return {!Promise} */ async _takeSnapshot() { - if (this.profileBeingRecorded()) + if (this.profileBeingRecorded()) { return; + } const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel); - if (!heapProfilerModel) + if (!heapProfilerModel) { return; + } const profile = new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this, ls`Snapshot ${this.nextProfileUid()}`); @@ -639,8 +653,9 @@ minOrdinal = minOrdinal || 0; maxOrdinal = maxOrdinal || Infinity; for (const sample of profile.samples) { - if (sample.ordinal < minOrdinal || sample.ordinal > maxOrdinal) + if (sample.ordinal < minOrdinal || sample.ordinal > maxOrdinal) { continue; + } const size = nodeIdToSizeMap.get(sample.nodeId) || 0; nodeIdToSizeMap.set(sample.nodeId, size + sample.size); } @@ -661,8 +676,9 @@ const targetNode = targetNodeStack.pop(); targetNode.children = sourceNode.children.map(child => { const targetChild = new Profiler.SamplingHeapProfileNode(child); - if (nodeIdToSizeMap) + if (nodeIdToSizeMap) { targetChild.self = nodeIdToSizeMap.get(child.id) || 0; + } return targetChild; }); sourceNodeStack.pushAll(sourceNode.children); @@ -821,8 +837,9 @@ */ prepareHighlightedEntryInfo(entryIndex) { const node = this._entryNodes[entryIndex]; - if (!node) + if (!node) { return null; + } const entryInfo = []; /** * @param {string} title @@ -837,8 +854,9 @@ const linkifier = new Components.Linkifier(); const link = linkifier.maybeLinkifyConsoleCallFrame( this._heapProfilerModel ? this._heapProfilerModel.target() : null, node.callFrame); - if (link) + if (link) { pushEntryInfoRow(ls`URL`, link.textContent); + } linkifier.dispose(); return Profiler.ProfileView.buildPopoverTable(entryInfo); }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapProfilerPanel.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapProfilerPanel.js index 0951dd56..284f885 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapProfilerPanel.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapProfilerPanel.js
@@ -26,24 +26,29 @@ * @param {!Object} target */ appendApplicableItems(event, contextMenu, target) { - if (!(target instanceof SDK.RemoteObject)) + if (!(target instanceof SDK.RemoteObject)) { return; + } - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const object = /** @type {!SDK.RemoteObject} */ (target); - if (!object.objectId) + if (!object.objectId) { return; + } const objectId = /** @type {string} */ (object.objectId); const heapProfiles = Profiler.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles(); - if (!heapProfiles.length) + if (!heapProfiles.length) { return; + } const heapProfilerModel = object.runtimeModel().heapProfilerModel(); - if (!heapProfilerModel) + if (!heapProfilerModel) { return; + } /** * @param {string} viewName @@ -51,8 +56,9 @@ */ function revealInView(viewName) { heapProfilerModel.snapshotObjectIdForObjectId(objectId).then(result => { - if (this.isShowing() && result) + if (this.isShowing() && result) { this.showObject(result, viewName); + } }); }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotDataGrids.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotDataGrids.js index fef1ec31..519d9ea 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotDataGrids.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotDataGrids.js
@@ -46,8 +46,9 @@ ]; for (const info of tooltips) { const headerCell = this.headerTableHeader(info[0]); - if (headerCell) + if (headerCell) { headerCell.setAttribute('title', info[1]); + } } /** @@ -102,8 +103,9 @@ _disposeAllNodes() { const children = this.topLevelNodes(); - for (let i = 0, l = children.length; i < l; ++i) + for (let i = 0, l = children.length; i < l; ++i) { children[i].dispose(); + } } /** @@ -114,8 +116,9 @@ this._nameFilter.addEventListener(UI.ToolbarInput.Event.TextChanged, this._onNameFilterChanged, this); this.updateVisibleNodes(true); } - if (this._populatedAndSorted) + if (this._populatedAndSorted) { this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown, this); + } } _sortingComplete() { @@ -128,8 +131,9 @@ * @override */ willHide() { - if (this._nameFilter) + if (this._nameFilter) { this._nameFilter.removeEventListener(UI.ToolbarInput.Event.TextChanged, this._onNameFilterChanged, this); + } this._clearCurrentHighlight(); } @@ -174,8 +178,9 @@ } _clearCurrentHighlight() { - if (!this._highlightedNode) + if (!this._highlightedNode) { return; + } this._highlightedNode.element().classList.remove('highlighted-row'); this._highlightedNode = null; } @@ -191,8 +196,9 @@ sortingChanged() { const sortAscending = this.isSortOrderAscending(); const sortColumnId = this.sortColumnId(); - if (this._lastSortColumnId === sortColumnId && this._lastSortAscending === sortAscending) + if (this._lastSortColumnId === sortColumnId && this._lastSortAscending === sortAscending) { return; + } this._lastSortColumnId = sortColumnId; this._lastSortAscending = sortAscending; const sortFields = this._sortFields(sortColumnId, sortAscending); @@ -201,15 +207,18 @@ let field1 = nodeA[sortFields[0]]; let field2 = nodeB[sortFields[0]]; let result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); - if (!sortFields[1]) + if (!sortFields[1]) { result = -result; - if (result !== 0) + } + if (result !== 0) { return result; + } field1 = nodeA[sortFields[2]]; field2 = nodeB[sortFields[2]]; result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); - if (!sortFields[3]) + if (!sortFields[3]) { result = -result; + } return result; } this._performSorting(SortByTwoFields); @@ -223,8 +232,9 @@ for (let i = 0, l = children.length; i < l; ++i) { const child = children[i]; this.appendChildAfterSorting(child); - if (child.expanded) + if (child.expanded) { child.sort(); + } } this.recursiveSortingLeave(); } @@ -240,10 +250,12 @@ } recursiveSortingLeave() { - if (!this._recursiveSortingDepth) + if (!this._recursiveSortingDepth) { return; - if (--this._recursiveSortingDepth) + } + if (--this._recursiveSortingDepth) { return; + } this.updateVisibleNodes(true); this.dispatchEventToListeners(Profiler.HeapSnapshotSortableDataGrid.Events.SortingComplete); } @@ -338,8 +350,9 @@ scrollBottom = Math.max(0, scrollBottom - guardZoneHeight); let viewPortHeight = scrollHeight - scrollTop - scrollBottom; // Do nothing if populated nodes still fit the viewport. - if (!force && scrollTop >= this._topPaddingHeight && scrollBottom >= this._bottomPaddingHeight) + if (!force && scrollTop >= this._topPaddingHeight && scrollBottom >= this._bottomPaddingHeight) { return; + } const hysteresisHeight = 500; scrollTop -= hysteresisHeight; viewPortHeight += 2 * hysteresisHeight; @@ -355,10 +368,11 @@ if (selectedNode) { // Keep selection even if the node is not in the current viewport. - if (selectedNode.parent) + if (selectedNode.parent) { selectedNode.select(true); - else + } else { this.selectedNode = selectedNode; + } } } @@ -369,8 +383,9 @@ * @return {number} */ _addVisibleNodes(parentNode, topBound, bottomBound) { - if (!parentNode.expanded) + if (!parentNode.expanded) { return 0; + } const children = this.allChildren(parentNode); let topPadding = 0; @@ -380,11 +395,13 @@ let i = 0; for (; i < children.length; ++i) { const child = children[i]; - if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) + if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) { continue; + } const newTop = topPadding + this._nodeHeight(child); - if (newTop > topBound) + if (newTop > topBound) { break; + } topPadding = newTop; } @@ -392,8 +409,9 @@ let position = topPadding; for (; i < children.length && position < bottomBound; ++i) { const child = children[i]; - if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) + if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) { continue; + } const hasChildren = child.hasChildren(); child.removeChildren(); child.setHasChildren(hasChildren); @@ -406,8 +424,9 @@ let bottomPadding = 0; for (; i < children.length; ++i) { const child = children[i]; - if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) + if (nameFilterValue && child.filteredOut && child.filteredOut(nameFilterValue)) { continue; + } bottomPadding += this._nodeHeight(child); } @@ -422,11 +441,13 @@ */ _nodeHeight(node) { let result = node.nodeSelfHeight(); - if (!node.expanded) + if (!node.expanded) { return result; + } const children = this.allChildren(node); - for (let i = 0; i < children.length; i++) + for (let i = 0; i < children.length; i++) { result += this._nodeHeight(children[i]); + } return result; } @@ -439,8 +460,9 @@ const node = /** @type {!Profiler.HeapSnapshotGridNode} */ (pathToReveal.peekLast()); const scrollTop = this.scrollContainer.scrollTop; const scrollBottom = scrollTop + this.scrollContainer.offsetHeight; - if (height >= scrollTop && height < scrollBottom) + if (height >= scrollTop && height < scrollBottom) { return Promise.resolve(node); + } const scrollGap = 40; this.scrollContainer.scrollTop = Math.max(0, height - scrollGap); @@ -449,8 +471,9 @@ this._scrollToResolveCallback = resolve.bind(null, node); // Still resolve the promise if it does not scroll for some reason. this.scrollContainer.window().requestAnimationFrame(() => { - if (!this._scrollToResolveCallback) + if (!this._scrollToResolveCallback) { return; + } this._scrollToResolveCallback(); this._scrollToResolveCallback = null; }); @@ -605,8 +628,9 @@ */ sortingChanged() { const rootNode = this.rootNode(); - if (rootNode.hasChildren()) + if (rootNode.hasChildren()) { rootNode.sort(); + } } }; @@ -722,12 +746,14 @@ } const className = await this.snapshot.nodeClassName(parseInt(id, 10)); - if (!className) + if (!className) { return null; + } const parent = this.topLevelNodes().find(classNode => classNode._name === className); - if (!parent) + if (!parent) { return null; + } const nodes = await parent.populateNodeBySnapshotObjectId(parseInt(id, 10)); return nodes.length ? this.revealTreeNode(nodes) : null; @@ -744,8 +770,9 @@ */ setDataSource(snapshot) { this.snapshot = snapshot; - if (this._profileIndex === -1) + if (this._profileIndex === -1) { this._populateChildren(); + } if (this._objectIdToSelect) { this.revealObjectByHeapSnapshotId(this._objectIdToSelect); @@ -804,8 +831,9 @@ this._nextRequestedFilter = this._filterInProgress.equals(nodeFilter) ? null : nodeFilter; return; } - if (this._lastFilter && this._lastFilter.equals(nodeFilter)) + if (this._lastFilter && this._lastFilter.equals(nodeFilter)) { return; + } this._filterInProgress = nodeFilter; const aggregates = await this.snapshot.aggregatesWithFilter(nodeFilter); @@ -956,8 +984,9 @@ this.removeTopLevelNodes(); const root = this.rootNode(); const tops = this._topNodes; - for (const top of tops) + for (const top of tops) { this.appendNode(root, new Profiler.AllocationGridNode(this, top)); + } this.updateVisibleNodes(true); } @@ -982,10 +1011,12 @@ * @return {number} */ function compare(a, b) { - if (a[fieldName] > b[fieldName]) + if (a[fieldName] > b[fieldName]) { return compareResult; - if (a[fieldName] < b[fieldName]) + } + if (a[fieldName] < b[fieldName]) { return -compareResult; + } return 0; } return compare;
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotGridNodes.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotGridNodes.js index 6806d55..c1d46a1e 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotGridNodes.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotGridNodes.js
@@ -89,8 +89,9 @@ * @return {!Profiler.HeapSnapshotGridNode.ChildrenProvider} */ _provider() { - if (!this._providerObject) + if (!this._providerObject) { this._providerObject = this.createProvider(); + } return this._providerObject; } @@ -101,8 +102,9 @@ */ createCell(columnId) { const cell = super.createCell(columnId); - if (this._searchMatched) + if (this._searchMatched) { cell.classList.add('highlight'); + } return cell; } @@ -123,11 +125,13 @@ } dispose() { - if (this._providerObject) + if (this._providerObject) { this._providerObject.dispose(); + } for (let node = this.children[0]; node; node = node.traverseNextNode(true, this, true)) { - if (node.dispose) + if (node.dispose) { node.dispose(); + } } } @@ -215,8 +219,9 @@ * @override */ populate() { - if (this._populated) + if (this._populated) { return; + } this._populated = true; this._provider().sortAndRewind(this.comparator()).then(() => this._populateChildren()); } @@ -249,8 +254,9 @@ * @this {Profiler.HeapSnapshotGridNode} */ function serializeNextChunk() { - if (firstNotSerializedPosition >= toPosition) + if (firstNotSerializedPosition >= toPosition) { return; + } const end = Math.min(firstNotSerializedPosition + this._dataGrid.defaultPopulateCount(), toPosition); this._provider().serializeItemsRange(firstNotSerializedPosition, end).then(childrenRetrieved.bind(this)); firstNotSerializedPosition = end; @@ -295,10 +301,12 @@ insertShowMoreButton.call(this, 0, itemsRange.startPosition, insertionIndex++); } this._retrievedChildrenRanges.push({from: itemsRange.startPosition, to: itemsRange.endPosition}); - for (let i = 0, l = items.length; i < l; ++i) + for (let i = 0, l = items.length; i < l; ++i) { insertRetrievedChild.call(this, items[i], insertionIndex++); - if (itemsRange.endPosition < itemsRange.totalLength) + } + if (itemsRange.endPosition < itemsRange.totalLength) { insertShowMoreButton.call(this, itemsRange.endPosition, itemsRange.totalLength, insertionIndex++); + } } else { let rangeIndex = 0; let found = false; @@ -311,8 +319,9 @@ } insertionIndex += range.to - range.from; // Skip the button if there is one. - if (range.to < itemsRange.totalLength) + if (range.to < itemsRange.totalLength) { insertionIndex += 1; + } ++rangeIndex; } @@ -322,8 +331,9 @@ insertShowMoreButton.call( this, itemsRange.startPosition, found ? range.from : itemsRange.totalLength, insertionIndex); range = {from: itemsRange.startPosition, to: itemsRange.startPosition}; - if (!found) + if (!found) { rangeIndex = this._retrievedChildrenRanges.length; + } this._retrievedChildrenRanges.splice(rangeIndex, 0, range); } else { insertionIndex += itemPosition - range.from; @@ -342,8 +352,9 @@ // We're at the position before button: ...<?node>x<button> const nextRange = this._retrievedChildrenRanges[rangeIndex + 1]; let newEndOfRange = nextRange ? nextRange.from : itemsRange.totalLength; - if (newEndOfRange > itemsRange.endPosition) + if (newEndOfRange > itemsRange.endPosition) { newEndOfRange = itemsRange.endPosition; + } while (itemPosition < newEndOfRange) { insertRetrievedChild.call(this, items[itemIndex++], insertionIndex++); ++itemPosition; @@ -358,10 +369,11 @@ } else { range.to = newEndOfRange; // Remove or update next button. - if (newEndOfRange === itemsRange.totalLength) + if (newEndOfRange === itemsRange.totalLength) { this.removeChildByIndex(insertionIndex); - else + } else { this.allChildren()[insertionIndex].setStartPosition(itemsRange.endPosition); + } } } } @@ -373,8 +385,9 @@ return; } - if (this.expanded) + if (this.expanded) { this._dataGrid.updateVisibleNodes(true); + } afterPopulate(); this.dispatchEventToListeners(Profiler.HeapSnapshotGridNode.Events.PopulateComplete); } @@ -385,10 +398,12 @@ const children = this.allChildren(); for (let i = 0, l = children.length; i < l; ++i) { const child = children[i]; - if (!child.expanded) + if (!child.expanded) { continue; - if (!this._savedChildren) + } + if (!this._savedChildren) { this._savedChildren = {}; + } this._savedChildren[this._childHashForNode(child)] = child; } } @@ -407,8 +422,9 @@ await this._populateChildren(0, instanceCount); for (const child of this.allChildren()) { - if (child.expanded) + if (child.expanded) { child.sort(); + } } this._dataGrid.recursiveSortingLeave(); } @@ -463,8 +479,9 @@ constructor(dataGrid, node) { super(dataGrid, false); // node is null for DataGrid root nodes. - if (!node) + if (!node) { return; + } this._name = node.name; this._type = node.type; this._distance = node.distance; @@ -480,8 +497,9 @@ } else if (node.canBeQueried) { this._reachableFromWindow = true; } - if (node.detachedDOMTreeNode) + if (node.detachedDOMTreeNode) { this.detachedDOMTreeNode = true; + } const snapshot = dataGrid.snapshot; const shallowSizePercent = this._shallowSize / snapshot.totalSize * 100.0; @@ -510,8 +528,9 @@ */ createCell(columnId) { const cell = columnId !== 'object' ? this._createValueCell(columnId) : this._createObjectCell(); - if (this._searchMatched) + if (this._searchMatched) { cell.classList.add('highlight'); + } return cell; } @@ -570,12 +589,14 @@ div.appendChild(UI.html `<span class="heap-object-tag" title="${ls`User object reachable from window`}">🗖</span>`); } - if (this.detachedDOMTreeNode) + if (this.detachedDOMTreeNode) { div.appendChild(UI.html`<span class="heap-object-tag" title="${ls`Detached from DOM tree`}">✀</span>`); + } this._appendSourceLocation(div); const cell = fragment.element(); - if (this.depth) + if (this.depth) { cell.style.setProperty('padding-left', (this.depth * this.dataGrid.indentWidth) + 'px'); + } cell.heapSnapshotNode = this; return cell; } @@ -593,10 +614,11 @@ const linkContainer = UI.html`<span class="heap-object-source-link" />`; div.appendChild(linkContainer); const link = await this._dataGrid.dataDisplayDelegate().linkifyObject(this.snapshotNodeIndex); - if (link) + if (link) { linkContainer.appendChild(link); - else + } else { linkContainer.remove(); + } } /** @@ -608,10 +630,11 @@ async queryObjectContent(heapProfilerModel, objectGroupName) { const runtimeModel = heapProfilerModel.runtimeModel(); let result; - if (this._type === 'string') + if (this._type === 'string') { result = runtimeModel.createRemoteObjectFromPrimitiveValue(this._name); - else + } else { result = await heapProfilerModel.objectForSnapshotObjectId(String(this.snapshotNodeId), objectGroupName); + } return result || runtimeModel.createRemoteObjectFromPrimitiveValue(ls`Preview is not available`); } @@ -628,12 +651,14 @@ shortenWindowURL(fullName, hasObjectId) { const startPos = fullName.indexOf('/'); const endPos = hasObjectId ? fullName.indexOf('@') : fullName.length; - if (startPos === -1 || endPos === -1) + if (startPos === -1 || endPos === -1) { return fullName; + } const fullURL = fullName.substring(startPos + 1, endPos).trimLeft(); let url = fullURL.trimURL(); - if (url.length > 40) + if (url.length > 40) { url = url.trimMiddle(40); + } return fullName.substr(0, startPos + 2) + url + fullName.substr(endPos); } }; @@ -657,8 +682,9 @@ this._parentObjectNode = parentObjectNode; this._cycledWithAncestorGridNode = this._findAncestorWithSameSnapshotNodeId(); - if (!this._cycledWithAncestorGridNode) + if (!this._cycledWithAncestorGridNode) { this.updateHasChildren(); + } const data = this.data; data['count'] = ''; @@ -689,8 +715,9 @@ _findAncestorWithSameSnapshotNodeId() { let ancestor = this._parentObjectNode; while (ancestor) { - if (ancestor.snapshotNodeId === this.snapshotNodeId) + if (ancestor.snapshotNodeId === this.snapshotNodeId) { return ancestor; + } ancestor = ancestor._parentObjectNode; } return null; @@ -757,8 +784,9 @@ name = `[${name}]`; break; } - if (this._cycledWithAncestorGridNode) + if (this._cycledWithAncestorGridNode) { div.classList.add('cycled-ancessor-node'); + } div.prepend(UI.html`<span class="${nameClass}">${name}</span> <span class="grayed">${this._edgeNodeSeparator()}</span>`); } @@ -1008,10 +1036,12 @@ */ createCell(columnId) { const cell = columnId === 'object' ? super.createCell(columnId) : this._createValueCell(columnId); - if (columnId === 'object' && this._count > 1) + if (columnId === 'object' && this._count > 1) { cell.appendChild(UI.html`<span class="objects-count">×${this._count}</span>`); - if (this._searchMatched) + } + if (this._searchMatched) { cell.classList.add('highlight'); + } return cell; } @@ -1110,8 +1140,9 @@ if (beginPosition < this._addedCount) { itemsRange = await this._addedNodesProvider.serializeItemsRange(beginPosition, endPosition); - for (const item of itemsRange.items) + for (const item of itemsRange.items) { item.isAddedNotRemoved = true; + } if (itemsRange.endPosition >= endPosition) { itemsRange.totalLength = this._addedCount + this._removedCount; @@ -1126,10 +1157,12 @@ beginPosition - this._addedCount, endPosition - this._addedCount); } - if (!addedItems.items.length) + if (!addedItems.items.length) { addedItems.startPosition = this._addedCount + itemsRange.startPosition; - for (const item of itemsRange.items) + } + for (const item of itemsRange.items) { item.isAddedNotRemoved = false; + } addedItems.items.pushAll(itemsRange.items); addedItems.endPosition = this._addedCount + itemsRange.endPosition; addedItems.totalLength = this._addedCount + this._removedCount; @@ -1195,8 +1228,9 @@ */ createCell(columnId) { const cell = super.createCell(columnId); - if (columnId !== 'object') + if (columnId !== 'object') { cell.classList.add('numeric-column'); + } return cell; } @@ -1205,10 +1239,11 @@ * @return {!Profiler.HeapSnapshotInstanceNode} */ _createChildNode(item) { - if (item.isAddedNotRemoved) + if (item.isAddedNotRemoved) { return new Profiler.HeapSnapshotInstanceNode(this._dataGrid, this._dataGrid.snapshot, item, false); - else + } else { return new Profiler.HeapSnapshotInstanceNode(this._dataGrid, this._dataGrid.baseSnapshot, item, true); + } } /** @@ -1254,12 +1289,14 @@ } _signForDelta(delta) { - if (delta === 0) + if (delta === 0) { return ''; - if (delta > 0) + } + if (delta > 0) { return '+'; - else - return '\u2212'; // Math minus sign, same width as plus. + } else { + return '\u2212'; + } // Math minus sign, same width as plus. } }; @@ -1288,8 +1325,9 @@ * @override */ populate() { - if (this._populated) + if (this._populated) { return; + } this._doPopulate(); } @@ -1306,14 +1344,16 @@ dataGrid.appendNode(parentNode, child); parentNode = child; parentNode._populated = true; - if (this.expanded) + if (this.expanded) { parentNode.expand(); + } } const callersBranch = callers.branchingCallers; callersBranch.sort(this._dataGrid._createComparator()); - for (const caller of callersBranch) + for (const caller of callersBranch) { dataGrid.appendNode(parentNode, new Profiler.AllocationGridNode(dataGrid, caller)); + } dataGrid.updateVisibleNodes(true); } @@ -1322,8 +1362,9 @@ */ expand() { super.expand(); - if (this.children.length === 1) + if (this.children.length === 1) { this.children[0].expand(); + } } /** @@ -1332,8 +1373,9 @@ * @return {!Element} */ createCell(columnId) { - if (columnId !== 'name') + if (columnId !== 'name') { return this._createValueCell(columnId); + } const cell = super.createCell(columnId); const allocationNode = this._allocationNode;
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotProxy.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotProxy.js index d675782..06a6627 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotProxy.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotProxy.js
@@ -67,8 +67,9 @@ dispose() { this._worker.terminate(); - if (this._interval) + if (this._interval) { clearInterval(this._interval); + } } disposeObject(objectId) { @@ -133,8 +134,9 @@ callMethod(callback, objectId, methodName) { const callId = this._nextCallId++; const methodArguments = Array.prototype.slice.call(arguments, 3); - if (callback) + if (callback) { this._callbacks.set(callId, callback); + } this._postMessage({ callId: callId, disposition: 'method', @@ -145,21 +147,24 @@ } startCheckingForLongRunningCalls() { - if (this._interval) + if (this._interval) { return; + } this._checkLongRunningCalls(); this._interval = setInterval(this._checkLongRunningCalls.bind(this), 300); } _checkLongRunningCalls() { for (const callId of this._previousCallbacks) { - if (!this._callbacks.has(callId)) + if (!this._callbacks.has(callId)) { this._previousCallbacks.delete(callId); + } } const hasLongRunningCalls = !!this._previousCallbacks.size; this.dispatchEventToListeners(Profiler.HeapSnapshotWorkerProxy.Events.Wait, hasLongRunningCalls); - for (const callId of this._callbacks.keysArray()) + for (const callId of this._callbacks.keysArray()) { this._previousCallbacks.add(callId); + } } /** @@ -168,8 +173,9 @@ _messageReceived(event) { const data = event.data; if (data.eventName) { - if (this._eventHandler) + if (this._eventHandler) { this._eventHandler(data.eventName, data.data); + } return; } if (data.error) { @@ -181,8 +187,9 @@ this._callbacks.delete(data.callId); return; } - if (!this._callbacks.has(data.callId)) + if (!this._callbacks.has(data.callId)) { return; + } const callback = this._callbacks.get(data.callId); this._callbacks.delete(data.callId); callback(data.result);
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js index 03f523e..3e1a347 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapSnapshotView.js
@@ -50,8 +50,9 @@ profileType.addEventListener(Profiler.ProfileType.Events.RemoveProfileHeader, this._onProfileHeaderRemoved, this); const isHeapTimeline = profileType.id === Profiler.TrackingHeapSnapshotProfileType.TypeId; - if (isHeapTimeline) + if (isHeapTimeline) { this._createOverview(); + } this._parentDataDisplayDelegate = dataDisplayDelegate; @@ -126,11 +127,13 @@ this._perspectives = []; this._comparisonPerspective = new Profiler.HeapSnapshotView.ComparisonPerspective(); this._perspectives.push(new Profiler.HeapSnapshotView.SummaryPerspective()); - if (profile.profileType() !== Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType) + if (profile.profileType() !== Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType) { this._perspectives.push(this._comparisonPerspective); + } this._perspectives.push(new Profiler.HeapSnapshotView.ContainmentPerspective()); - if (this._allocationWidget) + if (this._allocationWidget) { this._perspectives.push(new Profiler.HeapSnapshotView.AllocationPerspective()); + } this._perspectives.push(new Profiler.HeapSnapshotView.StatisticsPerspective()); this._perspectiveSelect = new UI.ToolbarComboBox(this._onSelectedPerspectiveChanged.bind(this), ls`Perspective`); @@ -164,8 +167,9 @@ this._populate(); this._searchThrottler = new Common.Throttler(0); - for (const existingProfile of this._profiles()) + for (const existingProfile of this._profiles()) { existingProfile.addEventListener(Profiler.ProfileHeader.Events.ProfileTitleChanged, this._updateControls, this); + } } _createOverview() { @@ -187,8 +191,9 @@ Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate, this._onHeapStatsUpdate, this); this._profile.profileType().removeEventListener( Profiler.TrackingHeapSnapshotProfileType.TrackingStopped, this._onStopTracking, this); - if (this._trackingOverviewGrid) + if (this._trackingOverviewGrid) { this._trackingOverviewGrid.stop(); + } } /** @@ -196,8 +201,9 @@ */ _onHeapStatsUpdate(event) { const samples = event.data; - if (samples) + if (samples) { this._trackingOverviewGrid.setSamples(event.data); + } } /** @@ -222,10 +228,11 @@ * @param {string} perspectiveName */ showObject(snapshotObjectId, perspectiveName) { - if (snapshotObjectId <= this._profile.maxJSObjectId) + if (snapshotObjectId <= this._profile.maxJSObjectId) { this.selectLiveObject(perspectiveName, snapshotObjectId); - else + } else { this._parentDataDisplayDelegate.showObject(snapshotObjectId, perspectiveName); + } } /** @@ -236,16 +243,19 @@ async linkifyObject(nodeIndex) { const heapProfilerModel = this._profile.heapProfilerModel(); // heapProfilerModel is null if snapshot was loaded from file - if (!heapProfilerModel) + if (!heapProfilerModel) { return null; + } const location = await this._profile.getLocation(nodeIndex); - if (!location) + if (!location) { return null; + } const debuggerModel = heapProfilerModel.runtimeModel().debuggerModel(); const rawLocation = debuggerModel.createRawLocationByScriptId( String(location.scriptId), location.lineNumber, location.columnNumber); - if (!rawLocation) + if (!rawLocation) { return null; + } const sourceURL = rawLocation.script() && rawLocation.script().sourceURL; return sourceURL && this._linkifier ? this._linkifier.linkifyRawLocation(rawLocation, sourceURL) : null; } @@ -274,8 +284,9 @@ const list = this._profiles(); const profileIndex = list.indexOf(this._profile); this._baseSelect.setSelectedIndex(Math.max(0, profileIndex - 1)); - if (this._trackingOverviewGrid) + if (this._trackingOverviewGrid) { this._trackingOverviewGrid.updateGrid(); + } } /** @@ -300,8 +311,9 @@ const minId = event.data.minId; const maxId = event.data.maxId; this._selectedSizeText.setText(Common.UIString('Selected size: %s', Number.bytesToString(event.data.size))); - if (this._constructorsDataGrid.snapshot) + if (this._constructorsDataGrid.snapshot) { this._constructorsDataGrid.setSelectionRange(minId, maxId); + } } /** @@ -310,8 +322,9 @@ */ syncToolbarItems() { const result = [this._perspectiveSelect, this._classNameFilter]; - if (this._profile.profileType() !== Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType) + if (this._profile.profileType() !== Profiler.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType) { result.push(this._baseSelect, this._filterSelect); + } result.push(this._selectedSizeText); return result; } @@ -352,8 +365,9 @@ * @param {?Profiler.HeapSnapshotGridNode} node */ _selectRevealedNode(node) { - if (node) + if (node) { node.select(); + } } /** @@ -378,19 +392,22 @@ // Call searchCanceled since it will reset everything we need before doing a new search. this.searchCanceled(); - if (!this._currentPerspective.supportsSearch()) + if (!this._currentPerspective.supportsSearch()) { return; + } this.currentQuery = nextQuery; const query = nextQuery.query.trim(); - if (!query) + if (!query) { return; + } if (query.charAt(0) === '@') { const snapshotNodeId = parseInt(query.substring(1), 10); - if (isNaN(snapshotNodeId)) + if (isNaN(snapshotNodeId)) { return; + } const node = await this._dataGrid.revealObjectByHeapSnapshotId(String(snapshotNodeId)); this._selectRevealedNode(node); return; @@ -399,8 +416,9 @@ this._searchResults = await this._profile._snapshotProxy.search(this.currentQuery, this._dataGrid.nodeFilter()); this._searchableView.updateSearchMatchesCount(this._searchResults.length); - if (this._searchResults.length) + if (this._searchResults.length) { this._currentSearchResultIndex = nextQuery.jumpBackwards ? this._searchResults.length - 1 : 0; + } await this._jumpToSearchResult(this._currentSearchResultIndex); } @@ -408,8 +426,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchResults.length) + if (!this._searchResults.length) { return; + } this._currentSearchResultIndex = (this._currentSearchResultIndex + 1) % this._searchResults.length; this._searchThrottler.schedule(this._jumpToSearchResult.bind(this, this._currentSearchResultIndex)); } @@ -418,8 +437,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchResults.length) + if (!this._searchResults.length) { return; + } this._currentSearchResultIndex = (this._currentSearchResultIndex + this._searchResults.length - 1) % this._searchResults.length; this._searchThrottler.schedule(this._jumpToSearchResult.bind(this, this._currentSearchResultIndex)); @@ -431,15 +451,17 @@ */ async _jumpToSearchResult(searchResultIndex) { this._searchableView.updateCurrentMatchIndex(searchResultIndex); - if (searchResultIndex === -1) + if (searchResultIndex === -1) { return; + } const node = await this._dataGrid.revealObjectByHeapSnapshotId(String(this._searchResults[searchResultIndex])); this._selectRevealedNode(node); } refreshVisibleData() { - if (!this._dataGrid) + if (!this._dataGrid) { return; + } let child = this._dataGrid.rootNode().children[0]; while (child) { child.refresh(); @@ -448,17 +470,20 @@ } _changeBase() { - if (this._baseProfile === this._profiles()[this._baseSelect.selectedIndex()]) + if (this._baseProfile === this._profiles()[this._baseSelect.selectedIndex()]) { return; + } this._baseProfile = this._profiles()[this._baseSelect.selectedIndex()]; const dataGrid = /** @type {!Profiler.HeapSnapshotDiffDataGrid} */ (this._dataGrid); // Change set base data source only if main data source is already set. - if (dataGrid.snapshot) + if (dataGrid.snapshot) { this._baseProfile._loadPromise.then(dataGrid.setBaseDataSource.bind(dataGrid)); + } - if (!this.currentQuery || !this._searchResults) + if (!this.currentQuery || !this._searchResults) { return; + } // The current search needs to be performed again. First negate out previous match // count by calling the search finished callback with a negative number of matches. @@ -470,8 +495,9 @@ const profileIndex = this._filterSelect.selectedIndex() - 1; this._dataGrid.filterSelectIndexChanged(this._profiles(), profileIndex); - if (!this.currentQuery || !this._searchResults) + if (!this.currentQuery || !this._searchResults) { return; + } // The current search needs to be performed again. First negate out previous match // count by calling the search finished callback with a negative number of matches. @@ -510,8 +536,9 @@ _inspectedObjectChanged(event) { const selectedNode = /** @type {!DataGrid.DataGridNode} */ (event.data); const heapProfilerModel = this._profile.heapProfilerModel(); - if (heapProfilerModel && selectedNode instanceof Profiler.HeapSnapshotGenericObjectNode) + if (heapProfilerModel && selectedNode instanceof Profiler.HeapSnapshotGenericObjectNode) { heapProfilerModel.addInspectedHeapObject(String(selectedNode.snapshotNodeId)); + } } /** @@ -521,11 +548,13 @@ const dataSource = nodeItem && nodeItem.retainersDataSource(); if (dataSource) { this._retainmentDataGrid.setDataSource(dataSource.snapshot, dataSource.snapshotNodeIndex); - if (this._allocationStackView) + if (this._allocationStackView) { this._allocationStackView.setAllocatedObject(dataSource.snapshot, dataSource.snapshotNodeIndex); + } } else { - if (this._allocationStackView) + if (this._allocationStackView) { this._allocationStackView.clear(); + } this._retainmentDataGrid.reset(); } } @@ -536,8 +565,9 @@ */ _changePerspectiveAndWait(perspectiveTitle) { const perspectiveIndex = this._perspectives.findIndex(perspective => perspective.title() === perspectiveTitle); - if (perspectiveIndex === -1 || this._currentPerspectiveIndex === perspectiveIndex) + if (perspectiveIndex === -1 || this._currentPerspectiveIndex === perspectiveIndex) { return Promise.resolve(); + } const promise = this._perspectives[perspectiveIndex].masterGrid(this).once( Profiler.HeapSnapshotSortableDataGrid.Events.ContentShown); @@ -550,24 +580,30 @@ async _updateDataSourceAndView() { const dataGrid = this._dataGrid; - if (!dataGrid || dataGrid.snapshot) + if (!dataGrid || dataGrid.snapshot) { return; + } const snapshotProxy = await this._profile._loadPromise; - if (this._dataGrid !== dataGrid) + if (this._dataGrid !== dataGrid) { return; - if (dataGrid.snapshot !== snapshotProxy) + } + if (dataGrid.snapshot !== snapshotProxy) { dataGrid.setDataSource(snapshotProxy); - if (dataGrid !== this._diffDataGrid) + } + if (dataGrid !== this._diffDataGrid) { return; - if (!this._baseProfile) + } + if (!this._baseProfile) { this._baseProfile = this._profiles()[this._baseSelect.selectedIndex()]; + } const baseSnapshotProxy = await this._baseProfile._loadPromise; - if (this._diffDataGrid.baseSnapshot !== baseSnapshotProxy) + if (this._diffDataGrid.baseSnapshot !== baseSnapshotProxy) { this._diffDataGrid.setBaseDataSource(baseSnapshotProxy); + } } /** @@ -581,8 +617,9 @@ * @param {number} selectedIndex */ _changePerspective(selectedIndex) { - if (selectedIndex === this._currentPerspectiveIndex) + if (selectedIndex === this._currentPerspectiveIndex) { return; + } this._currentPerspectiveIndex = selectedIndex; @@ -593,13 +630,15 @@ perspective.activate(this); this.refreshVisibleData(); - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.updateWidths(); + } this._updateDataSourceAndView(); - if (!this.currentQuery || !this._searchResults) + if (!this.currentQuery || !this._searchResults) { return; + } // The current search needs to be performed again. First negate out previous match // count by calling the search finished callback with a negative number of matches. @@ -614,10 +653,11 @@ async selectLiveObject(perspectiveName, snapshotObjectId) { await this._changePerspectiveAndWait(perspectiveName); const node = await this._dataGrid.revealObjectByHeapSnapshotId(snapshotObjectId); - if (node) + if (node) { node.select(); - else + } else { Common.console.error('Cannot find corresponding heap snapshot node'); + } } /** @@ -628,16 +668,18 @@ const span = event.target.enclosingNodeOrSelfWithNodeName('span'); const row = event.target.enclosingNodeOrSelfWithNodeName('tr'); const heapProfilerModel = this._profile.heapProfilerModel(); - if (!row || !span || !heapProfilerModel) + if (!row || !span || !heapProfilerModel) { return null; + } const node = row._dataGridNode; let objectPopoverHelper; return { box: span.boxInWindow(), show: async popover => { const remoteObject = await node.queryObjectContent(heapProfilerModel, 'popover'); - if (!remoteObject) + if (!remoteObject) { return false; + } objectPopoverHelper = await ObjectUI.ObjectPopoverHelper.buildObjectPopover(remoteObject, popover); if (!objectPopoverHelper) { heapProfilerModel.runtimeModel().releaseObjectGroup('popover'); @@ -656,8 +698,9 @@ const multipleSnapshots = this._profiles().length > 1; this._perspectiveSelect.removeOptions(); this._perspectives.forEach((perspective, index) => { - if (multipleSnapshots || perspective !== this._comparisonPerspective) + if (multipleSnapshots || perspective !== this._comparisonPerspective) { this._perspectiveSelect.createOption(perspective.title(), String(index)); + } }); } @@ -666,11 +709,13 @@ const selectedIndex = this._baseSelect.selectedIndex(); this._baseSelect.removeOptions(); - for (const item of list) + for (const item of list) { this._baseSelect.createOption(item.title); + } - if (selectedIndex > -1) + if (selectedIndex > -1) { this._baseSelect.setSelectedIndex(selectedIndex); + } } _updateFilterOptions() { @@ -681,15 +726,17 @@ this._filterSelect.createOption(Common.UIString('All objects')); for (let i = 0; i < list.length; ++i) { let title; - if (!i) + if (!i) { title = Common.UIString('Objects allocated before %s', list[i].title); - else + } else { title = Common.UIString('Objects allocated between %s and %s', list[i - 1].title, list[i].title); + } this._filterSelect.createOption(title); } - if (selectedIndex > -1) + if (selectedIndex > -1) { this._filterSelect.setSelectedIndex(selectedIndex); + } } _updateControls() { @@ -765,12 +812,15 @@ heapSnapshotView._baseSelect.setVisible(false); heapSnapshotView._filterSelect.setVisible(false); heapSnapshotView._classNameFilter.setVisible(false); - if (heapSnapshotView._trackingOverviewGrid) + if (heapSnapshotView._trackingOverviewGrid) { heapSnapshotView._trackingOverviewGrid.detach(); - if (heapSnapshotView._allocationWidget) + } + if (heapSnapshotView._allocationWidget) { heapSnapshotView._allocationWidget.detach(); - if (heapSnapshotView._statisticsView) + } + if (heapSnapshotView._statisticsView) { heapSnapshotView._statisticsView.detach(); + } heapSnapshotView._splitWidget.detach(); heapSnapshotView._splitWidget.detachChildWidgets(); @@ -817,8 +867,9 @@ heapSnapshotView._splitWidget.show(heapSnapshotView._searchableView.element); heapSnapshotView._filterSelect.setVisible(true); heapSnapshotView._classNameFilter.setVisible(true); - if (!heapSnapshotView._trackingOverviewGrid) + if (!heapSnapshotView._trackingOverviewGrid) { return; + } heapSnapshotView._trackingOverviewGrid.show( heapSnapshotView._searchableView.element, heapSnapshotView._splitWidget.element); heapSnapshotView._trackingOverviewGrid.update(); @@ -942,8 +993,9 @@ heapSnapshotView._constructorsDataGrid.clear(); const selectedNode = heapSnapshotView._allocationDataGrid.selectedNode; - if (selectedNode) + if (selectedNode) { heapSnapshotView._constructorsDataGrid.setAllocationNodeId(selectedNode.allocationNodeId()); + } } /** @@ -1093,11 +1145,13 @@ } async _takeHeapSnapshot() { - if (this.profileBeingRecorded()) + if (this.profileBeingRecorded()) { return; + } const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel); - if (!heapProfilerModel) + if (!heapProfilerModel) { return; + } let profile = new Profiler.HeapProfileHeader(heapProfilerModel, this); this.setProfileBeingRecorded(profile); @@ -1117,8 +1171,9 @@ * @param {!Common.Event} event */ _addHeapSnapshotChunk(event) { - if (!this.profileBeingRecorded()) + if (!this.profileBeingRecorded()) { return; + } const chunk = /** @type {string} */ (event.data); this.profileBeingRecorded().transferChunk(chunk); } @@ -1128,12 +1183,14 @@ */ _reportHeapSnapshotProgress(event) { const profile = this.profileBeingRecorded(); - if (!profile) + if (!profile) { return; + } const data = /** @type {{done: number, total: number, finished: boolean}} */ (event.data); profile.updateStatus(Common.UIString('%.0f%%', (data.done / data.total) * 100), true); - if (data.finished) + if (data.finished) { profile._prepareToLoad(); + } } /** @@ -1142,14 +1199,16 @@ _resetProfiles(event) { const heapProfilerModel = /** @type {!SDK.HeapProfilerModel} */ (event.data); for (const profile of this.getProfiles()) { - if (profile.heapProfilerModel() === heapProfilerModel) + if (profile.heapProfilerModel() === heapProfilerModel) { this.removeProfile(profile); + } } } _snapshotReceived(profile) { - if (this.profileBeingRecorded() === profile) + if (this.profileBeingRecorded() === profile) { this.setProfileBeingRecorded(null); + } this.dispatchEventToListeners(Profiler.HeapSnapshotProfileType.SnapshotReceived, profile); } }; @@ -1192,16 +1251,18 @@ * @param {!Common.Event} event */ _heapStatsUpdate(event) { - if (!this._profileSamples) + if (!this._profileSamples) { return; + } const samples = /** @type {!Array.<number>} */ (event.data); let index; for (let i = 0; i < samples.length; i += 3) { index = samples[i]; const size = samples[i + 2]; this._profileSamples.sizes[index] = size; - if (!this._profileSamples.max[index]) + if (!this._profileSamples.max[index]) { this._profileSamples.max[index] = size; + } } } @@ -1210,8 +1271,9 @@ */ _lastSeenObjectId(event) { const profileSamples = this._profileSamples; - if (!profileSamples) + if (!profileSamples) { return; + } const data = /** @type {{lastSeenObjectId: number, timestamp: number}} */ (event.data); const currentIndex = Math.max(profileSamples.ids.length, profileSamples.max.length - 1); profileSamples.ids[currentIndex] = data.lastSeenObjectId; @@ -1220,8 +1282,9 @@ profileSamples.sizes[currentIndex] = 0; } profileSamples.timestamps[currentIndex] = data.timestamp; - if (profileSamples.totalTime < data.timestamp - profileSamples.timestamps[0]) + if (profileSamples.totalTime < data.timestamp - profileSamples.timestamps[0]) { profileSamples.totalTime *= 2; + } this.dispatchEventToListeners(Profiler.TrackingHeapSnapshotProfileType.HeapStatsUpdate, this._profileSamples); this.profileBeingRecorded().updateStatus(null, true); } @@ -1258,11 +1321,13 @@ } _startRecordingProfile() { - if (this.profileBeingRecorded()) + if (this.profileBeingRecorded()) { return; + } const heapProfilerModel = this._addNewProfile(); - if (!heapProfilerModel) + if (!heapProfilerModel) { return; + } heapProfilerModel.startTrackingHeapObjects(this._recordAllocationStacksSetting.get()); } @@ -1290,8 +1355,9 @@ */ _addNewProfile() { const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel); - if (!heapProfilerModel) + if (!heapProfilerModel) { return null; + } this.setProfileBeingRecorded(new Profiler.HeapProfileHeader(heapProfilerModel, this, undefined)); this._profileSamples = new Profiler.HeapTimelineOverview.Samples(); this.profileBeingRecorded()._profileSamples = this._profileSamples; @@ -1310,8 +1376,9 @@ await stopPromise; // ------------ ASYNC ------------ const profile = this.profileBeingRecorded(); - if (!profile) + if (!profile) { return; + } profile._finishLoad(); this._profileSamples = null; this.setProfileBeingRecorded(null); @@ -1319,10 +1386,11 @@ } _toggleRecording() { - if (this._recording) + if (this._recording) { this._stopRecordingProfile(); - else + } else { this._startRecordingProfile(); + } return this._recording; } @@ -1362,8 +1430,9 @@ this.setProfileBeingRecorded(null); super._resetProfiles(event); this._profileSamples = null; - if (wasRecording) + if (wasRecording) { this._addNewProfile(); + } } /** @@ -1451,10 +1520,12 @@ } _finishLoad() { - if (!this._wasDisposed) + if (!this._wasDisposed) { this._receiver.close(); - if (!this._bufferedWriter) + } + if (!this._bufferedWriter) { return; + } this._didWriteToTempFile(this._bufferedWriter); } @@ -1463,13 +1534,15 @@ */ _didWriteToTempFile(tempFile) { if (this._wasDisposed) { - if (tempFile) + if (tempFile) { tempFile.remove(); + } return; } this._tempFile = tempFile; - if (!tempFile) + if (!tempFile) { this._failedToCreateTempFile = true; + } if (this._onTempFileReady) { this._onTempFileReady(); this._onTempFileReady = null; @@ -1500,8 +1573,9 @@ return; } - if (HeapSnapshotModel.HeapSnapshotProgressEvent.Update !== eventName) + if (HeapSnapshotModel.HeapSnapshotProgressEvent.Update !== eventName) { return; + } const serializedMessage = /** @type {string} */ (data); const messageObject = Common.deserializeUIString(serializedMessage); this.updateStatus(ls(messageObject.messageParts, messageObject.values)); @@ -1511,15 +1585,17 @@ * @override */ dispose() { - if (this._workerProxy) + if (this._workerProxy) { this._workerProxy.dispose(); + } this.removeTempFile(); this._wasDisposed = true; } _didCompleteSnapshotTransfer() { - if (!this._snapshotProxy) + if (!this._snapshotProxy) { return; + } this.updateStatus(Number.bytesToString(this._snapshotProxy.totalSize), false); } @@ -1527,8 +1603,9 @@ * @param {string} chunk */ transferChunk(chunk) { - if (!this._bufferedWriter) + if (!this._bufferedWriter) { this._bufferedWriter = new Bindings.TempFile(); + } this._bufferedWriter.write([chunk]); ++this._totalNumberOfChunks; @@ -1536,8 +1613,9 @@ } _snapshotReceived(snapshotProxy) { - if (this._wasDisposed) + if (this._wasDisposed) { return; + } this._receiver = null; this._snapshotProxy = snapshotProxy; this.maxJSObjectId = snapshotProxy.maxJSObjectId(); @@ -1549,8 +1627,9 @@ notifySnapshotReceived() { this._fulfillLoad(this._snapshotProxy); this.profileType()._snapshotReceived(this); - if (this.canSaveToFile()) + if (this.canSaveToFile()) { this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileReceived); + } } /** @@ -1574,8 +1653,9 @@ * @this {Profiler.HeapProfileHeader} */ async function onOpen(accepted) { - if (!accepted) + if (!accepted) { return; + } if (this._failedToCreateTempFile) { Common.console.error('Failed to open temp file with heap snapshot'); fileOutputStream.close(); @@ -1583,8 +1663,9 @@ } if (this._tempFile) { const error = await this._tempFile.copyToOutputStream(fileOutputStream, this._onChunkTransferred.bind(this)); - if (error) + if (error) { Common.console.error('Failed to read heap snapshot from temp file: ' + error.message); + } this._didCompleteSnapshotTransfer(); return; } @@ -1619,8 +1700,9 @@ this._setupWorker(); const reader = new Bindings.ChunkedFileReader(file, 10000000); const success = await reader.read(/** @type {!Common.OutputStream} */ (this._receiver)); - if (!success) + if (!success) { this.updateStatus(reader.error().message); + } return success ? null : reader.error(); } }; @@ -1697,8 +1779,9 @@ const frameDiv = stackDiv.createChild('div', 'stack-frame'); const name = frameDiv.createChild('div'); name.textContent = UI.beautifyFunctionName(frame.functionName); - if (!frame.scriptId) + if (!frame.scriptId) { continue; + } const urlElement = this._linkifier.linkifyScriptLocation( this._heapProfilerModel ? this._heapProfilerModel.target() : null, String(frame.scriptId), frame.scriptName, frame.line - 1, frame.column - 1);
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js b/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js index 09f2ed55..151c47d1 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/HeapTimelineOverview.js
@@ -33,8 +33,9 @@ this._running = true; const drawFrame = () => { this.update(); - if (this._running) + if (this._running) { this.element.window().requestAnimationFrame(drawFrame); + } }; drawFrame(); } @@ -48,8 +49,9 @@ */ setSamples(samples) { this._profileSamples = samples; - if (!this._running) + if (!this._running) { this.update(); + } } /** @@ -57,8 +59,9 @@ * @param {number} height */ _drawOverviewCanvas(width, height) { - if (!this._profileSamples) + if (!this._profileSamples) { return; + } const profileSamples = this._profileSamples; const sizes = profileSamples.sizes; const topSizes = profileSamples.max; @@ -77,8 +80,9 @@ for (let i = 1; i < timestamps.length; ++i) { const x = Math.floor((timestamps[i] - startTime) * scaleFactor); if (x !== currentX) { - if (size) + if (size) { callback(currentX, size); + } size = 0; currentX = x; } @@ -128,8 +132,9 @@ // e.g. a round value 10KB is 10240 bytes. gridValue = Math.pow(1024, Math.floor(Math.log(maxGridValue) / Math.log(1024))); gridValue *= Math.pow(10, Math.floor(Math.log(maxGridValue / gridValue) / Math.LN10)); - if (gridValue * 5 <= maxGridValue) + if (gridValue * 5 <= maxGridValue) { gridValue *= 5; + } gridY = Math.round(height - gridValue * yScaleFactor - 0.5) + 0.5; context.beginPath(); context.lineWidth = 1; @@ -190,13 +195,15 @@ } _onWindowChanged() { - if (!this._updateGridTimerId) + if (!this._updateGridTimerId) { this._updateGridTimerId = setTimeout(this.updateGrid.bind(this), 10); + } } _scheduleUpdate() { - if (this._updateTimerId) + if (this._updateTimerId) { return; + } this._updateTimerId = setTimeout(this.update.bind(this), 10); } @@ -208,8 +215,9 @@ update() { this._updateTimerId = null; - if (!this.isShowing()) + if (!this.isShowing()) { return; + } this._updateBoundaries(); this._overviewCalculator._updateBoundaries(this); this._overviewGrid.updateDividers(this._overviewCalculator); @@ -220,8 +228,9 @@ this._updateGridTimerId = 0; this._updateBoundaries(); const ids = this._profileSamples.ids; - if (!ids.length) + if (!ids.length) { return; + } const timestamps = this._profileSamples.timestamps; const sizes = this._profileSamples.sizes; const startTime = timestamps[0]; @@ -231,8 +240,9 @@ const minIndex = timestamps.lowerBound(timeLeft); const maxIndex = timestamps.upperBound(timeRight); let size = 0; - for (let i = minIndex; i <= maxIndex; ++i) + for (let i = minIndex; i <= maxIndex; ++i) { size += sizes[i]; + } const minId = minIndex > 0 ? ids[minIndex - 1] : 0; const maxId = maxIndex < ids.length ? ids[maxIndex] : Infinity;
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/IsolateSelector.js b/third_party/blink/renderer/devtools/front_end/profiler/IsolateSelector.js index 8494544..04396e1d 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/IsolateSelector.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/IsolateSelector.js
@@ -59,8 +59,9 @@ const index = item.model().target() === SDK.targetManager.mainTarget() ? 0 : this._items.length; this._items.insert(index, item); this._itemByIsolate.set(isolate, item); - if (this._items.length === 1) + if (this._items.length === 1) { this._list.selectItem(item); + } this._update(); } @@ -91,12 +92,14 @@ _targetChanged(event) { const target = /** @type {!SDK.Target} */ (event.data); const model = target.model(SDK.RuntimeModel); - if (!model) + if (!model) { return; + } const isolate = SDK.isolateManager.isolateByModel(model); const item = isolate && this._itemByIsolate.get(isolate); - if (item) + if (item) { item.updateTitle(); + } } /** @@ -105,8 +108,9 @@ _heapStatsChanged(event) { const isolate = /** @type {!SDK.IsolateManager.Isolate} */ (event.data); const listItem = this._itemByIsolate.get(isolate); - if (listItem) + if (listItem) { listItem.updateStats(); + } this._updateTotal(); } @@ -128,8 +132,9 @@ static _formatTrendElement(trendValueMs, element) { const changeRateBytesPerSecond = trendValueMs * 1e3; const changeRateThresholdBytesPerSecond = 1024; - if (Math.abs(changeRateBytesPerSecond) < changeRateThresholdBytesPerSecond) + if (Math.abs(changeRateBytesPerSecond) < changeRateThresholdBytesPerSecond) { return; + } const changeRateText = Number.bytesToString(Math.abs(changeRateBytesPerSecond)); const changeText = changeRateBytesPerSecond > 0 ? ls`\u2B06${changeRateText}/s` : ls`\u2B07${changeRateText}/s`; element.classList.toggle('increasing', changeRateBytesPerSecond > 0); @@ -177,10 +182,12 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected'); - if (toElement) + } + if (toElement) { toElement.classList.add('selected'); + } const model = to && to.model(); UI.context.setFlavor(SDK.HeapProfilerModel, model && model.heapProfilerModel()); UI.context.setFlavor(SDK.CPUProfilerModel, model && model.target().model(SDK.CPUProfilerModel));
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/LiveHeapProfileView.js b/third_party/blink/renderer/devtools/front_end/profiler/LiveHeapProfileView.js index 5a360ba1..5e8f6dd 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/LiveHeapProfileView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/LiveHeapProfileView.js
@@ -68,8 +68,9 @@ dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this._sortingChanged, this); for (const info of columns) { const headerCell = dataGrid.headerTableHeader(info.id); - if (headerCell) + if (headerCell) { headerCell.setAttribute('title', info.tooltip); + } } return dataGrid; } @@ -103,8 +104,9 @@ const isolates = Array.from(SDK.isolateManager.isolates()); const profiles = await Promise.all( isolates.map(isolate => isolate.heapProfilerModel() && isolate.heapProfilerModel().getSamplingProfile())); - if (this._currentPollId !== pollId) + if (this._currentPollId !== pollId) { return; + } this._update(isolates, profiles); await new Promise(r => setTimeout(r, 3000)); } while (this._currentPollId === pollId); @@ -118,8 +120,9 @@ /** @type {!Map<string, !{size: number, isolates: !Set<!SDK.IsolateManager.Isolate>}>} */ const dataByUrl = new Map(); profiles.forEach((profile, index) => { - if (profile) + if (profile) { processNodeTree(isolates[index], '', profile.head); + } }); const rootNode = this._dataGrid.rootNode(); @@ -144,8 +147,9 @@ } for (const node of rootNode.children.slice()) { - if (!exisitingNodes.has(node)) + if (!exisitingNodes.has(node)) { node.remove(); + } this._gridNodeByUrl.delete(node); } @@ -159,8 +163,9 @@ function processNodeTree(isolate, parentUrl, node) { const url = node.callFrame.url || parentUrl || systemNodeName(node) || anonymousScriptName(node); node.children.forEach(processNodeTree.bind(null, isolate, url)); - if (!node.selfSize) + if (!node.selfSize) { return; + } let data = dataByUrl.get(url); if (!data) { data = {size: 0, isolates: new Set()}; @@ -192,25 +197,29 @@ * @param {!Event} event */ _onKeyDown(event) { - if (!isEnterKey(event)) + if (!isEnterKey(event)) { return; + } event.consume(true); this._revealSourceForSelectedNode(); } _revealSourceForSelectedNode() { const node = this._dataGrid.selectedNode; - if (!node || !node._url) + if (!node || !node._url) { return; + } const sourceCode = Workspace.workspace.uiSourceCodeForURL(node._url); - if (sourceCode) + if (sourceCode) { Common.Revealer.reveal(sourceCode); + } } _sortingChanged() { const columnId = this._dataGrid.sortColumnId(); - if (!columnId) + if (!columnId) { return; + } const sortByUrl = (a, b) => b._url.localeCompare(a._url); const sortBySize = (a, b) => b._size - a._size; const sortFunction = columnId === 'url' ? sortByUrl : sortBySize; @@ -219,10 +228,11 @@ _toggleRecording() { const enable = !this._setting.get(); - if (enable) + if (enable) { this._startRecording(false); - else + } else { this._stopRecording(); + } } /** @@ -230,14 +240,17 @@ */ _startRecording(reload) { this._setting.set(true); - if (!reload) + if (!reload) { return; + } const mainTarget = SDK.targetManager.mainTarget(); - if (!mainTarget) + if (!mainTarget) { return; + } const resourceTreeModel = /** @type {?SDK.ResourceTreeModel} */ (mainTarget.model(SDK.ResourceTreeModel)); - if (resourceTreeModel) + if (resourceTreeModel) { resourceTreeModel.reloadPage(); + } } async _stopRecording() { @@ -263,8 +276,9 @@ * @param {number} isolateCount */ updateNode(size, isolateCount) { - if (this._size === size && this._isolateCount === isolateCount) + if (this._size === size && this._isolateCount === isolateCount) { return; + } this._size = size; this._isolateCount = isolateCount; this.refresh();
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfileDataGrid.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfileDataGrid.js index 646b521..ca88d477 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfileDataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfileDataGrid.js
@@ -70,8 +70,9 @@ // If the grid node is collapsed, then don't sort children (save operation for later). // If the grid node has the same sorting as previously, then there is no point in sorting it again. if (!force && (!gridNode.expanded || gridNode.lastComparator === comparator)) { - if (gridNode.children.length) + if (gridNode.children.length) { gridNode.shouldRefreshChildren = true; + } continue; } @@ -83,8 +84,9 @@ if (childCount) { children.sort(comparator); - for (let childIndex = 0; childIndex < childCount; ++childIndex) + for (let childIndex = 0; childIndex < childCount; ++childIndex) { children[childIndex].recalculateSiblings(childIndex); + } gridNodeGroups.push(children); } @@ -100,8 +102,9 @@ static merge(container, child, shouldAbsorb) { container.self += child.self; - if (!shouldAbsorb) + if (!shouldAbsorb) { container.total += child.total; + } let children = container.children.slice(); @@ -110,8 +113,9 @@ let count = children.length; for (let index = 0; index < count; ++index) { - if (!shouldAbsorb || children[index] !== child) + if (!shouldAbsorb || children[index] !== child) { container.appendChild(children[index]); + } } children = child.children.slice(); @@ -121,10 +125,11 @@ const orphanedChild = children[index]; const existingChild = container.childrenByCallUID.get(orphanedChild.callUID); - if (existingChild) + if (existingChild) { existingChild.merge(/** @type{!Profiler.ProfileDataGridNode} */ (orphanedChild), false); - else + } else { container.appendChild(orphanedChild); + } } } @@ -132,16 +137,18 @@ * @param {!Profiler.ProfileDataGridNode|!Profiler.ProfileDataGridTree} container */ static populate(container) { - if (container._populated) + if (container._populated) { return; + } container._populated = true; container.populateChildren(); const currentComparator = container.tree.lastComparator; - if (currentComparator) + if (currentComparator) { container.sort(currentComparator, true); + } } /** @@ -172,11 +179,13 @@ cell.appendChild(warningIcon); } cell.createTextChild(this.functionName); - if (this.profileNode.scriptId === '0') + if (this.profileNode.scriptId === '0') { break; + } const urlElement = this.tree._formatter.linkifyNode(this); - if (!urlElement) + if (!urlElement) { break; + } urlElement.style.maxWidth = '75%'; cell.appendChild(urlElement); break; @@ -246,8 +255,9 @@ * @return {?Profiler.ProfileDataGridNode} */ findChild(node) { - if (!node) + if (!node) { return null; + } return this.childrenByCallUID.get(node.callUID); } @@ -276,8 +286,9 @@ // This allows us to restore them all to their original state when we revert. save() { - if (this._savedChildren) + if (this._savedChildren) { return; + } this._savedSelf = this.self; this._savedTotal = this.total; @@ -291,8 +302,9 @@ * @protected */ restore() { - if (!this._savedChildren) + if (!this._savedChildren) { return; + } this.self = this._savedSelf; this.total = this._savedTotal; @@ -350,21 +362,25 @@ if (!comparator) { if (isAscending) { comparator = function(lhs, rhs) { - if (lhs[property] < rhs[property]) + if (lhs[property] < rhs[property]) { return -1; + } - if (lhs[property] > rhs[property]) + if (lhs[property] > rhs[property]) { return 1; + } return 0; }; } else { comparator = function(lhs, rhs) { - if (lhs[property] > rhs[property]) + if (lhs[property] > rhs[property]) { return -1; + } - if (lhs[property] < rhs[property]) + if (lhs[property] < rhs[property]) { return 1; + } return 0; }; @@ -402,8 +418,9 @@ * @return {?Profiler.ProfileDataGridNode} */ findChild(node) { - if (!node) + if (!node) { return null; + } return this.childrenByCallUID.get(node.callUID); } @@ -420,16 +437,18 @@ * @protected */ save() { - if (this._savedChildren) + if (this._savedChildren) { return; + } this._savedTotal = this.total; this._savedChildren = this.children.slice(); } restore() { - if (!this._savedChildren) + if (!this._savedChildren) { return; + } this.children = this._savedChildren; this.total = this._savedTotal; @@ -437,8 +456,9 @@ const children = this.children; const count = children.length; - for (let index = 0; index < count; ++index) + for (let index = 0; index < count; ++index) { children[index].restore(); + } this._savedChildren = null; } @@ -449,8 +469,9 @@ */ _matchFunction(searchConfig) { const query = searchConfig.query.trim(); - if (!query.length) + if (!query.length) { return null; + } const greaterThan = (query.startsWith('>')); const lessThan = (query.startsWith('<')); @@ -461,17 +482,19 @@ let queryNumber = parseFloat(query); if (greaterThan || lessThan || equalTo) { - if (equalTo && (greaterThan || lessThan)) + if (equalTo && (greaterThan || lessThan)) { queryNumber = parseFloat(query.substring(2)); - else + } else { queryNumber = parseFloat(query.substring(1)); + } } const queryNumberMilliseconds = (secondsUnits ? (queryNumber * 1000) : queryNumber); // Make equalTo implicitly true if it wasn't specified there is no other operator. - if (!isNaN(queryNumber) && !(greaterThan || lessThan)) + if (!isNaN(queryNumber) && !(greaterThan || lessThan)) { equalTo = true; + } const matcher = createPlainTextSearchRegex(query, 'i'); @@ -486,47 +509,60 @@ if (percentUnits) { if (lessThan) { - if (profileDataGridNode.selfPercent < queryNumber) + if (profileDataGridNode.selfPercent < queryNumber) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent < queryNumber) + } + if (profileDataGridNode.totalPercent < queryNumber) { profileDataGridNode._searchMatchedTotalColumn = true; + } } else if (greaterThan) { - if (profileDataGridNode.selfPercent > queryNumber) + if (profileDataGridNode.selfPercent > queryNumber) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent > queryNumber) + } + if (profileDataGridNode.totalPercent > queryNumber) { profileDataGridNode._searchMatchedTotalColumn = true; + } } if (equalTo) { - if (profileDataGridNode.selfPercent === queryNumber) + if (profileDataGridNode.selfPercent === queryNumber) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.totalPercent === queryNumber) + } + if (profileDataGridNode.totalPercent === queryNumber) { profileDataGridNode._searchMatchedTotalColumn = true; + } } } else if (millisecondsUnits || secondsUnits) { if (lessThan) { - if (profileDataGridNode.self < queryNumberMilliseconds) + if (profileDataGridNode.self < queryNumberMilliseconds) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.total < queryNumberMilliseconds) + } + if (profileDataGridNode.total < queryNumberMilliseconds) { profileDataGridNode._searchMatchedTotalColumn = true; + } } else if (greaterThan) { - if (profileDataGridNode.self > queryNumberMilliseconds) + if (profileDataGridNode.self > queryNumberMilliseconds) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.total > queryNumberMilliseconds) + } + if (profileDataGridNode.total > queryNumberMilliseconds) { profileDataGridNode._searchMatchedTotalColumn = true; + } } if (equalTo) { - if (profileDataGridNode.self === queryNumberMilliseconds) + if (profileDataGridNode.self === queryNumberMilliseconds) { profileDataGridNode._searchMatchedSelfColumn = true; - if (profileDataGridNode.total === queryNumberMilliseconds) + } + if (profileDataGridNode.total === queryNumberMilliseconds) { profileDataGridNode._searchMatchedTotalColumn = true; + } } } if (profileDataGridNode.functionName.match(matcher) || - (profileDataGridNode.url && profileDataGridNode.url.match(matcher))) + (profileDataGridNode.url && profileDataGridNode.url.match(matcher))) { profileDataGridNode._searchMatchedFunctionColumn = true; + } if (profileDataGridNode._searchMatchedSelfColumn || profileDataGridNode._searchMatchedTotalColumn || profileDataGridNode._searchMatchedFunctionColumn) { @@ -548,14 +584,16 @@ performSearch(searchConfig, shouldJump, jumpBackwards) { this.searchCanceled(); const matchesQuery = this._matchFunction(searchConfig); - if (!matchesQuery) + if (!matchesQuery) { return; + } this._searchResults = []; const deepSearch = this.deepSearch; for (let current = this.children[0]; current; current = current.traverseNextNode(!deepSearch, null, !deepSearch)) { - if (matchesQuery(current)) + if (matchesQuery(current)) { this._searchResults.push({profileNode: current}); + } } this._searchResultIndex = jumpBackwards ? 0 : this._searchResults.length - 1; this._searchableView.updateSearchMatchesCount(this._searchResults.length); @@ -584,8 +622,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchResults || !this._searchResults.length) + if (!this._searchResults || !this._searchResults.length) { return; + } this._searchResultIndex = (this._searchResultIndex + 1) % this._searchResults.length; this._jumpToSearchResult(this._searchResultIndex); } @@ -594,8 +633,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchResults || !this._searchResults.length) + if (!this._searchResults || !this._searchResults.length) { return; + } this._searchResultIndex = (this._searchResultIndex - 1 + this._searchResults.length) % this._searchResults.length; this._jumpToSearchResult(this._searchResultIndex); } @@ -621,8 +661,9 @@ */ _jumpToSearchResult(index) { const searchResult = this._searchResults[index]; - if (!searchResult) + if (!searchResult) { return; + } const profileNode = searchResult.profileNode; profileNode.revealAndSelect(); this._searchableView.updateCurrentMatchIndex(index);
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfileHeader.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfileHeader.js index a63cc2d..2c27663 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfileHeader.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfileHeader.js
@@ -60,8 +60,9 @@ } removeTempFile() { - if (this._tempFile) + if (this._tempFile) { this._tempFile.remove(); + } } dispose() {
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfileLauncherView.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfileLauncherView.js index 4184522e..eaeb62de 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfileLauncherView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfileLauncherView.js
@@ -71,10 +71,11 @@ } _updateControls() { - if (this._isEnabled && this._recordButtonEnabled) + if (this._isEnabled && this._recordButtonEnabled) { this._controlButton.removeAttribute('disabled'); - else + } else { this._controlButton.setAttribute('disabled', ''); + } this._controlButton.title = this._recordButtonEnabled ? '' : UI.anotherProfilerActiveLabel(); if (this._isInstantProfile) { this._controlButton.classList.remove('running'); @@ -89,8 +90,9 @@ this._controlButton.classList.add('primary-button'); this._controlButton.textContent = Common.UIString('Start'); } - for (const item of this._typeIdToOptionElement.values()) + for (const item of this._typeIdToOptionElement.values()) { item.disabled = !!this._isProfiling; + } } profileStarted() {
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfileType.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfileType.js index 6960d35..6cbb9f4 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfileType.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfileType.js
@@ -21,8 +21,9 @@ this._profileBeingRecorded = null; this._nextProfileUid = 1; - if (!window.opener) + if (!window.opener) { window.addEventListener('unload', this._clearTempStorage.bind(this), false); + } } /** @@ -135,8 +136,9 @@ */ getProfile(uid) { for (let i = 0; i < this._profiles.length; ++i) { - if (this._profiles[i].uid === uid) + if (this._profiles[i].uid === uid) { return this._profiles[i]; + } } return null; } @@ -148,8 +150,9 @@ loadFromFile(file) { let name = file.name; const fileExtension = this.fileExtension(); - if (fileExtension && name.endsWith(fileExtension)) + if (fileExtension && name.endsWith(fileExtension)) { name = name.substr(0, name.length - fileExtension.length); + } const profile = this.createProfileLoadedFromFile(name); profile.setFromFile(); this.setProfileBeingRecorded(profile); @@ -178,15 +181,17 @@ */ removeProfile(profile) { const index = this._profiles.indexOf(profile); - if (index === -1) + if (index === -1) { return; + } this._profiles.splice(index, 1); this._disposeProfile(profile); } _clearTempStorage() { - for (let i = 0; i < this._profiles.length; ++i) + for (let i = 0; i < this._profiles.length; ++i) { this._profiles[i].removeTempFile(); + } } /** @@ -207,8 +212,9 @@ } reset() { - for (const profile of this._profiles.slice()) + for (const profile of this._profiles.slice()) { this._disposeProfile(profile); + } this._profiles = []; this._nextProfileUid = 1; }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js index 008c196..6cd4489 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfileView.js
@@ -109,18 +109,20 @@ this.viewSelectComboBox.select(option); this._changeView(); - if (this._flameChart) + if (this._flameChart) { this._flameChart.update(); + } } /** * @override */ focus() { - if (this._flameChart) + if (this._flameChart) { this._flameChart.focus(); - else + } else { super.focus(); + } } /** @@ -136,8 +138,9 @@ * @param {number} timeRight */ selectRange(timeLeft, timeRight) { - if (!this._flameChart) + if (!this._flameChart) { return; + } this._flameChart.selectRange(timeLeft, timeRight); } @@ -179,8 +182,9 @@ } refresh() { - if (!this.profileDataGridTree) + if (!this.profileDataGridTree) { return; + } const selectedProfileNode = this.dataGrid.selectedNode ? this.dataGrid.selectedNode.profileNode : null; this.dataGrid.rootNode().removeChildren(); @@ -188,11 +192,13 @@ const children = this.profileDataGridTree.children; const count = children.length; - for (let index = 0; index < count; ++index) + for (let index = 0; index < count; ++index) { this.dataGrid.rootNode().appendChild(children[index]); + } - if (selectedProfileNode) + if (selectedProfileNode) { selectedProfileNode.selected = true; + } } refreshVisibleData() { @@ -265,8 +271,9 @@ } _ensureTextViewCreated() { - if (this._textView) + if (this._textView) { return; + } this._textView = new UI.SimpleView(ls`Call tree`); this._textView.registerRequiredCSS('profiler/profilesPanel.css'); this.populateTextView(this._textView); @@ -286,8 +293,9 @@ } _ensureFlameChartCreated() { - if (this._flameChart) + if (this._flameChart) { return; + } this._dataProvider = this.createFlameChartDataProvider(); this._flameChart = new Profiler.CPUProfileFlameChart(this._searchableView, this._dataProvider); this._flameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this._onEntrySelected.bind(this)); @@ -300,24 +308,28 @@ const entryIndex = event.data; const node = this._dataProvider._entryNodes[entryIndex]; const debuggerModel = this._profileHeader._debuggerModel; - if (!node || !node.scriptId || !debuggerModel) + if (!node || !node.scriptId || !debuggerModel) { return; + } const script = debuggerModel.scriptForId(node.scriptId); - if (!script) + if (!script) { return; + } const location = /** @type {!SDK.DebuggerModel.Location} */ ( debuggerModel.createRawLocation(script, node.lineNumber, node.columnNumber)); Common.Revealer.reveal(Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location)); } _changeView() { - if (!this._profile) + if (!this._profile) { return; + } this._searchableView.closeSearch(); - if (this._visibleView) + if (this._visibleView) { this._visibleView.detach(); + } this._viewType.set(this.viewSelectComboBox.selectedOption().value); switch (this._viewType.get()) { @@ -365,8 +377,9 @@ * @param {!Common.Event} event */ _focusClicked(event) { - if (!this.dataGrid.selectedNode) + if (!this.dataGrid.selectedNode) { return; + } this.resetButton.setEnabled(true); this.profileDataGridTree.focus(this.dataGrid.selectedNode); @@ -381,8 +394,9 @@ _excludeClicked(event) { const selectedNode = this.dataGrid.selectedNode; - if (!selectedNode) + if (!selectedNode) { return; + } selectedNode.deselect(); @@ -502,11 +516,13 @@ this._fileName = this._fileName || `${this.profileType().typeName()}-${new Date().toISO8601Compact()}${this.profileType().fileExtension()}`; const accepted = await fileOutputStream.open(this._fileName); - if (!accepted || !this._tempFile) + if (!accepted || !this._tempFile) { return; + } const data = await this._tempFile.read(); - if (data) + if (data) { await fileOutputStream.write(data); + } fileOutputStream.close(); } @@ -538,8 +554,9 @@ } this._jsonifiedProfile = null; - if (this.profileType().profileBeingRecorded() === this) + if (this.profileType().profileBeingRecorded() === this) { this.profileType().setProfileBeingRecorded(null); + } return error; } @@ -551,7 +568,8 @@ this._protocolProfile = profile; this._tempFile = new Bindings.TempFile(); this._tempFile.write([JSON.stringify(profile)]); - if (this.canSaveToFile()) + if (this.canSaveToFile()) { this.dispatchEventToListeners(Profiler.ProfileHeader.Events.ProfileReceived); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js b/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js index 62ed453..b2b216e 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/ProfilesPanel.js
@@ -88,8 +88,9 @@ this._profileToView = []; this._typeIdToSidebarSection = {}; const types = this._profileTypes; - for (let i = 0; i < types.length; i++) + for (let i = 0; i < types.length; i++) { this._registerProfileType(types[i]); + } this._launcherView.restoreSelectedProfileType(); this.profilesItemTreeElement.select(); this._showLauncherView(); @@ -107,12 +108,14 @@ */ _onKeyDown(event) { let handled = false; - if (event.key === 'ArrowDown' && !event.altKey) + if (event.key === 'ArrowDown' && !event.altKey) { handled = this._sidebarTree.selectNext(); - else if (event.key === 'ArrowUp' && !event.altKey) + } else if (event.key === 'ArrowUp' && !event.altKey) { handled = this._sidebarTree.selectPrevious(); - if (handled) + } + if (handled) { event.consume(true); + } } /** @@ -124,8 +127,9 @@ } _createFileSelectorElement() { - if (this._fileSelectorElement) + if (this._fileSelectorElement) { this.element.removeChild(this._fileSelectorElement); + } this._fileSelectorElement = UI.createFileSelectorElement(this._loadFromFile.bind(this)); Profiler.ProfilesPanel._fileSelectorElement = this._fileSelectorElement; this.element.appendChild(this._fileSelectorElement); @@ -160,23 +164,26 @@ } const error = await profileType.loadFromFile(file); - if (error) + if (error) { UI.MessageDialog.show(Common.UIString('Profile loading failed: %s.', error.message)); + } } /** * @return {boolean} */ toggleRecord() { - if (!this._toggleRecordAction.enabled()) + if (!this._toggleRecordAction.enabled()) { return true; + } const type = this._selectedProfileType; const isProfiling = type.buttonClicked(); this._updateToggleRecordAction(isProfiling); if (isProfiling) { this._launcherView.profileStarted(); - if (type.hasTemporaryView()) + if (type.hasTemporaryView()) { this.showProfile(type.profileBeingRecorded()); + } } else { this._launcherView.profileFinished(); } @@ -195,12 +202,14 @@ const enable = toggled || (!SDK.targetManager.allTargetsSuspended() && hasSelectedTarget); this._toggleRecordAction.setEnabled(enable); this._toggleRecordAction.setToggled(toggled); - if (enable) + if (enable) { this._toggleRecordButton.setTitle(this._selectedProfileType ? this._selectedProfileType.buttonTooltip : ''); - else + } else { this._toggleRecordButton.setTitle(UI.anotherProfilerActiveLabel()); - if (this._selectedProfileType) + } + if (this._selectedProfileType) { this._launcherView.updateProfileType(this._selectedProfileType, enable); + } } _profileBeingRecordedRemoved() { @@ -289,8 +298,9 @@ profileType.addEventListener(Profiler.ProfileType.Events.ProfileComplete, profileComplete, this); const profiles = profileType.getProfiles(); - for (let i = 0; i < profiles.length; i++) + for (let i = 0; i < profiles.length; i++) { this._addProfileHeader(profiles[i]); + } } /** @@ -316,20 +326,23 @@ const profileType = profile.profileType(); const typeId = profileType.id; this._typeIdToSidebarSection[typeId].addProfileHeader(profile); - if (!this.visibleView || this.visibleView === this._launcherView) + if (!this.visibleView || this.visibleView === this._launcherView) { this.showProfile(profile); + } } /** * @param {!Profiler.ProfileHeader} profile */ _removeProfileHeader(profile) { - if (profile.profileType().profileBeingRecorded() === profile) + if (profile.profileType().profileBeingRecorded() === profile) { this._profileBeingRecordedRemoved(); + } const i = this._indexOfViewForProfile(profile); - if (i !== -1) + if (i !== -1) { this._profileToView.splice(i, 1); + } const typeId = profile.profileType().id; const sectionIsEmpty = this._typeIdToSidebarSection[typeId].removeProfileHeader(profile); @@ -349,12 +362,14 @@ */ showProfile(profile) { if (!profile || - (profile.profileType().profileBeingRecorded() === profile) && !profile.profileType().hasTemporaryView()) + (profile.profileType().profileBeingRecorded() === profile) && !profile.profileType().hasTemporaryView()) { return null; + } const view = this.viewForProfile(profile); - if (view === this.visibleView) + if (view === this.visibleView) { return view; + } this.closeVisibleView(); @@ -370,8 +385,9 @@ this._profileViewToolbar.removeToolbarItems(); const toolbarItems = view.syncToolbarItems(); - for (let i = 0; i < toolbarItems.length; ++i) + for (let i = 0; i < toolbarItems.length; ++i) { this._profileViewToolbar.appendToolbarItem(toolbarItems[i]); + } return view; } @@ -399,8 +415,9 @@ */ viewForProfile(profile) { const index = this._indexOfViewForProfile(profile); - if (index !== -1) + if (index !== -1) { return this._profileToView[index].view; + } const view = profile.createView(this); view.element.classList.add('profile-view'); this._profileToView.push({profile: profile, view: view}); @@ -416,8 +433,9 @@ } closeVisibleView() { - if (this.visibleView) + if (this.visibleView) { this.visibleView.detach(); + } delete this.visibleView; } @@ -484,8 +502,9 @@ const selected = firstProfileTreeElement.selected; this.removeChild(firstProfileTreeElement); group.sidebarTreeElement.appendChild(firstProfileTreeElement); - if (selected) + if (selected) { firstProfileTreeElement.revealAndSelect(); + } firstProfileTreeElement.setSmall(true); firstProfileTreeElement.setMainTitle(Common.UIString('Run %d', 1)); @@ -509,8 +528,9 @@ */ removeProfileHeader(profile) { const index = this._sidebarElementIndex(profile); - if (index === -1) + if (index === -1) { return false; + } const profileTreeElement = this._profileTreeElements[index]; this._profileTreeElements.splice(index, 1); @@ -529,14 +549,16 @@ groupElements[0].setMainTitle(profile.title); this.removeChild(group.sidebarTreeElement); } - if (groupElements.length !== 0) + if (groupElements.length !== 0) { sidebarParent = group.sidebarTreeElement; + } } sidebarParent.removeChild(profileTreeElement); profileTreeElement.dispose(); - if (this.childCount()) + if (this.childCount()) { return false; + } this.hidden = true; return true; } @@ -557,8 +579,9 @@ _sidebarElementIndex(profile) { const elements = this._profileTreeElements; for (let i = 0; i < elements.length; i++) { - if (elements[i].profile === profile) + if (elements[i].profile === profile) { return i; + } } return -1; } @@ -606,10 +629,11 @@ this._dataDisplayDelegate = dataDisplayDelegate; this.profile = profile; profile.addEventListener(Profiler.ProfileHeader.Events.UpdateStatus, this._updateStatus, this); - if (profile.canSaveToFile()) + if (profile.canSaveToFile()) { this._createSaveLink(); - else + } else { profile.addEventListener(Profiler.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this); + } } _createSaveLink() { @@ -631,8 +655,9 @@ this._subtitleElement.textContent = statusUpdate.subtitle || ''; this._titlesElement.classList.toggle('no-subtitle', !statusUpdate.subtitle); } - if (typeof statusUpdate.wait === 'boolean' && this.listItemElement) + if (typeof statusUpdate.wait === 'boolean' && this.listItemElement) { this.listItemElement.classList.toggle('wait', statusUpdate.wait); + } } /** @@ -641,8 +666,9 @@ * @return {boolean} */ ondblclick(event) { - if (!this._editing) + if (!this._editing) { this._startEditing(/** @type {!Element} */ (event.target)); + } return false; } @@ -651,8 +677,9 @@ */ _startEditing(eventTarget) { const container = eventTarget.enclosingNodeOrSelfWithClass('title'); - if (!container) + if (!container) { return; + } const config = new UI.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this)); this._editing = UI.InplaceEditor.startEditing(container, config); } @@ -697,10 +724,12 @@ * @override */ onattach() { - if (this._className) + if (this._className) { this.listItemElement.classList.add(this._className); - if (this._small) + } + if (this._small) { this.listItemElement.classList.add('small'); + } this.listItemElement.appendChildren(this._iconElement, this._titlesElement); this.listItemElement.addEventListener('contextmenu', this._handleContextMenuEvent.bind(this), true); } @@ -715,8 +744,9 @@ contextMenu.headerSection().appendItem( Common.UIString('Load\u2026'), Profiler.ProfilesPanel._fileSelectorElement.click.bind(Profiler.ProfilesPanel._fileSelectorElement)); - if (profile.canSaveToFile()) + if (profile.canSaveToFile()) { contextMenu.saveSection().appendItem(Common.UIString('Save\u2026'), profile.saveToFile.bind(profile)); + } contextMenu.footerSection().appendItem(Common.UIString('Delete'), this.ondelete.bind(this)); contextMenu.show(); } @@ -730,8 +760,9 @@ */ setSmall(small) { this._small = small; - if (this.listItemElement) + if (this.listItemElement) { this.listItemElement.classList.toggle('small', this._small); + } } /** @@ -765,8 +796,9 @@ */ onselect() { const hasChildren = this.childCount() > 0; - if (hasChildren) + if (hasChildren) { this._dataDisplayDelegate.showProfile(this.lastChild().profile); + } return hasChildren; }
diff --git a/third_party/blink/renderer/devtools/front_end/profiler/TopDownProfileDataGrid.js b/third_party/blink/renderer/devtools/front_end/profiler/TopDownProfileDataGrid.js index b073b7e..f9d0c498 100644 --- a/third_party/blink/renderer/devtools/front_end/profiler/TopDownProfileDataGrid.js +++ b/third_party/blink/renderer/devtools/front_end/profiler/TopDownProfileDataGrid.js
@@ -59,21 +59,24 @@ * @param {string} aCallUID */ static _excludeRecursively(container, aCallUID) { - if (container._remainingChildren) + if (container._remainingChildren) { container.populate(); + } container.save(); const children = container.children; let index = container.children.length; - while (index--) + while (index--) { Profiler.TopDownProfileDataGridNode._excludeRecursively(children[index], aCallUID); + } const child = container.childrenByCallUID.get(aCallUID); - if (child) + if (child) { Profiler.ProfileDataGridNode.merge(container, child, true); + } } /** @@ -105,8 +108,9 @@ * @param {!Profiler.ProfileDataGridNode} profileDataGridNode */ focus(profileDataGridNode) { - if (!profileDataGridNode) + if (!profileDataGridNode) { return; + } this.save(); profileDataGridNode.savePosition(); @@ -119,23 +123,26 @@ * @param {!Profiler.ProfileDataGridNode} profileDataGridNode */ exclude(profileDataGridNode) { - if (!profileDataGridNode) + if (!profileDataGridNode) { return; + } this.save(); Profiler.TopDownProfileDataGridNode._excludeRecursively(this, profileDataGridNode.callUID); - if (this.lastComparator) + if (this.lastComparator) { this.sort(this.lastComparator, true); + } } /** * @override */ restore() { - if (!this._savedChildren) + if (!this._savedChildren) { return; + } this.children[0].restorePosition();
diff --git a/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js b/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js index 0f870cf..81b7a8f 100644 --- a/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js +++ b/third_party/blink/renderer/devtools/front_end/protocol/InspectorBackend.js
@@ -66,8 +66,9 @@ */ _addAgentGetterMethodToProtocolTargetPrototype(domain) { let upperCaseLength = 0; - while (upperCaseLength < domain.length && domain[upperCaseLength].toLowerCase() !== domain[upperCaseLength]) + while (upperCaseLength < domain.length && domain[upperCaseLength].toLowerCase() !== domain[upperCaseLength]) { ++upperCaseLength; + } const methodName = domain.substr(0, upperCaseLength).toLowerCase() + domain.slice(upperCaseLength) + 'Agent'; @@ -108,8 +109,9 @@ * @return {!Protocol.InspectorBackend._DispatcherPrototype} */ _dispatcherPrototype(domain) { - if (!this._dispatcherPrototypes.has(domain)) + if (!this._dispatcherPrototypes.has(domain)) { this._dispatcherPrototypes.set(domain, new Protocol.InspectorBackend._DispatcherPrototype()); + } return this._dispatcherPrototypes.get(domain); } @@ -132,8 +134,9 @@ registerEnum(type, values) { const domainAndName = type.split('.'); const domain = domainAndName[0]; - if (!Protocol[domain]) + if (!Protocol[domain]) { Protocol[domain] = {}; + } Protocol[domain][domainAndName[1]] = values; this._initialized = true; @@ -169,10 +172,11 @@ clientCallback(defaultValue); return; } - if (constructor) + if (constructor) { clientCallback(new constructor(value)); - else + } else { clientCallback(value); + } } return callbackWrapper; } @@ -293,8 +297,9 @@ this._connection.setOnDisconnect(reason => { const session = this._sessions.get(''); - if (session) + if (session) { session.target.dispose(reason); + } }); } @@ -312,8 +317,9 @@ */ unregisterSession(sessionId) { const session = this._sessions.get(sessionId); - for (const callback of session.callbacks.values()) + for (const callback of session.callbacks.values()) { Protocol.SessionRouter.dispatchConnectionError(callback); + } this._sessions.delete(sessionId); } @@ -323,8 +329,9 @@ */ _getTargetBySessionId(sessionId) { const session = this._sessions.get(sessionId ? sessionId : ''); - if (!session) + if (!session) { return null; + } return session.target; } @@ -354,13 +361,16 @@ const messageId = this._nextMessageId(); messageObject.id = messageId; messageObject.method = method; - if (params) + if (params) { messageObject.params = params; - if (sessionId) + } + if (sessionId) { messageObject.sessionId = sessionId; + } - if (Protocol.test.dumpProtocol) + if (Protocol.test.dumpProtocol) { Protocol.test.dumpProtocol('frontend: ' + JSON.stringify(messageObject)); + } if (Protocol.test.onMessageSent) { const paramsObject = JSON.parse(JSON.stringify(params || {})); @@ -388,8 +398,9 @@ * @param {!Object|string} message */ _onMessage(message) { - if (Protocol.test.dumpProtocol) + if (Protocol.test.dumpProtocol) { Protocol.test.dumpProtocol('backend: ' + ((typeof message === 'string') ? message : JSON.stringify(message))); + } if (Protocol.test.onMessageReceived) { const messageObjectCopy = JSON.parse((typeof message === 'string') ? message : JSON.stringify(message)); @@ -406,8 +417,9 @@ return; } - if (session.target._needsNodeJSPatching) + if (session.target._needsNodeJSPatching) { Protocol.NodeURL.patch(messageObject); + } if (session.proxyConnection) { if (session.proxyConnection._onMessage) { @@ -430,8 +442,9 @@ callback(messageObject.error, messageObject.result); --this._pendingResponsesCount; - if (this._pendingScripts.length && !this._pendingResponsesCount) + if (this._pendingScripts.length && !this._pendingResponsesCount) { this._deprecatedRunAfterPendingDispatches(); + } } else { if (!('method' in messageObject)) { Protocol.InspectorBackend.reportProtocolError('Protocol Error: the message without method', messageObject); @@ -454,15 +467,17 @@ * @param {function()=} script */ _deprecatedRunAfterPendingDispatches(script) { - if (script) + if (script) { this._pendingScripts.push(script); + } // Execute all promises. setTimeout(() => { - if (!this._pendingResponsesCount) + if (!this._pendingResponsesCount) { this._executeAfterPendingDispatches(); - else + } else { this._deprecatedRunAfterPendingDispatches(); + } }, 0); } @@ -470,8 +485,9 @@ if (!this._pendingResponsesCount) { const scripts = this._pendingScripts; this._pendingScripts = []; - for (let id = 0; id < scripts.length; ++id) + for (let id = 0; id < scripts.length; ++id) { scripts[id](); + } } } @@ -502,14 +518,16 @@ this._needsNodeJSPatching = needsNodeJSPatching; this._sessionId = sessionId; - if ((!parentTarget && connection) || (!parentTarget && sessionId) || (connection && sessionId)) + if ((!parentTarget && connection) || (!parentTarget && sessionId) || (connection && sessionId)) { throw new Error('Either connection or sessionId (but not both) must be supplied for a child target'); - if (sessionId) + } + if (sessionId) { this._router = parentTarget._router; - else if (connection) + } else if (connection) { this._router = new Protocol.SessionRouter(connection); - else + } else { this._router = new Protocol.SessionRouter(Protocol.Connection._factory()); + } this._router.registerSession(this, this._sessionId); @@ -532,8 +550,9 @@ * @param {!Object} dispatcher */ registerDispatcher(domain, dispatcher) { - if (!this._dispatchers[domain]) + if (!this._dispatchers[domain]) { return; + } this._dispatchers[domain].addDomainDispatcher(dispatcher); } @@ -611,8 +630,9 @@ this['invoke_' + methodName] = invoke; this._replyArgs[domainAndMethod] = replyArgs; - if (hasErrorData) + if (hasErrorData) { this._hasErrorData[domainAndMethod] = true; + } } /** @@ -639,8 +659,9 @@ } const value = args.shift(); - if (optionalFlag && typeof value === 'undefined') + if (optionalFlag && typeof value === 'undefined') { continue; + } if (typeof value !== typeName) { errorCallback( @@ -677,14 +698,16 @@ errorMessage = message; } const params = this._prepareParameters(method, signature, args, onError); - if (errorMessage) + if (errorMessage) { return Promise.resolve(null); + } return new Promise(resolve => { const callback = (error, result) => { if (error && !Protocol.test.suppressRequestErrors && error.code !== Protocol.DevToolsStubErrorCode && - error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode) + error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode) { console.error('Request ' + method + ' failed. ' + JSON.stringify(error)); + } if (error) { @@ -695,10 +718,11 @@ resolve(result && args.length ? result[args[0]] : undefined); }; - if (!this._target._router) + if (!this._target._router) { Protocol.SessionRouter.dispatchConnectionError(callback); - else + } else { this._target._router.sendMessage(this._target._sessionId, this._domain, method, params, callback); + } }); } @@ -711,21 +735,25 @@ return new Promise(fulfill => { const callback = (error, result) => { if (error && !Protocol.test.suppressRequestErrors && error.code !== Protocol.DevToolsStubErrorCode && - error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode) + error.code !== Protocol._GenericError && error.code !== Protocol._ConnectionClosedErrorCode) { console.error('Request ' + method + ' failed. ' + JSON.stringify(error)); + } - if (!result) + if (!result) { result = {}; - if (error) + } + if (error) { result[Protocol.Error] = error.message; + } fulfill(result); }; - if (!this._target._router) + if (!this._target._router) { Protocol.SessionRouter.dispatchConnectionError(callback); - else + } else { this._target._router.sendMessage(this._target._sessionId, this._domain, method, request, callback); + } }); } }; @@ -758,8 +786,9 @@ * @param {!Object} messageObject */ dispatch(functionName, messageObject) { - if (!this._dispatchers.length) + if (!this._dispatchers.length) { return; + } if (!this._eventArgs[messageObject.method]) { Protocol.InspectorBackend.reportProtocolError( @@ -770,14 +799,16 @@ const params = []; if (messageObject.params) { const paramNames = this._eventArgs[messageObject.method]; - for (let i = 0; i < paramNames.length; ++i) + for (let i = 0; i < paramNames.length; ++i) { params.push(messageObject.params[paramNames[i]]); + } } for (let index = 0; index < this._dispatchers.length; ++index) { const dispatcher = this._dispatchers[index]; - if (functionName in dispatcher) + if (functionName in dispatcher) { dispatcher[functionName].apply(dispatcher, params); + } } } };
diff --git a/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js b/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js index e69d057..6e00a79 100644 --- a/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js +++ b/third_party/blink/renderer/devtools/front_end/protocol/NodeURL.js
@@ -14,14 +14,16 @@ * @param {string} path */ function process(object, path) { - if (object.url && Protocol.NodeURL._isPlatformPath(object.url, Host.isWin())) + if (object.url && Protocol.NodeURL._isPlatformPath(object.url, Host.isWin())) { object.url = Common.ParsedURL.platformPathToURL(object.url); + } for (const entry of Object.entries(object)) { const key = entry[0]; const value = entry[1]; const entryPath = path + '.' + key; - if (entryPath !== '.result.result.value' && value !== null && typeof value === 'object') + if (entryPath !== '.result.result.value' && value !== null && typeof value === 'object') { process(value, entryPath); + } } } }
diff --git a/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js b/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js index a103d36..62bb74d 100644 --- a/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js +++ b/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js
@@ -68,14 +68,17 @@ const filters = this._filterParser.parse(query); this._filter = node => { for (const {key, text, negative} of filters) { - if (!text) + if (!text) { continue; + } const data = key ? node.data[key] : node.data; - if (!data) + if (!data) { continue; + } const found = JSON.stringify(data).toLowerCase().indexOf(text.toLowerCase()) !== -1; - if (found === negative) + if (found === negative) { return false; + } } return true; }; @@ -87,8 +90,9 @@ _filterNodes() { for (const node of this._nodes) { if (this._filter(node)) { - if (!node.parent) + if (!node.parent) { this._dataGrid.insertChild(node); + } } else { node.remove(); } @@ -133,15 +137,17 @@ _updateColumnVisibility() { const visibleColumns = /** @type {!Object.<string, boolean>} */ ({}); - for (const columnConfig of this._columns) + for (const columnConfig of this._columns) { visibleColumns[columnConfig.id] = columnConfig.visible; + } this._dataGrid.setColumnsVisiblity(visibleColumns); } _sortDataGrid() { const sortColumnId = this._dataGrid.sortColumnId(); - if (!sortColumnId) + if (!sortColumnId) { return; + } let columnIsNumeric = true; switch (sortColumnId) { @@ -161,8 +167,9 @@ * @override */ wasShown() { - if (this._started) + if (this._started) { return; + } this._started = true; this._startTime = Date.now(); this._setRecording(true); @@ -186,8 +193,9 @@ * @return {string} */ _targetToString(target) { - if (!target) + if (!target) { return ''; + } return target.decorateLabel(`${target.name()} ${target === SDK.targetManager.mainTarget() ? '' : target.id()}`); } @@ -198,13 +206,15 @@ _messageRecieved(message, target) { if ('id' in message) { const node = this._nodeForId[message.id]; - if (!node) + if (!node) { return; + } node.data.response = message.result || message.error; node.hasError = !!message.error; node.refresh(); - if (this._dataGrid.selectedNode === node) + if (this._dataGrid.selectedNode === node) { this._infoWidget.render(node.data); + } return; } @@ -218,8 +228,9 @@ target: this._targetToString(sdkTarget) }); this._nodes.push(node); - if (this._filter(node)) + if (this._filter(node)) { this._dataGrid.insertChild(node); + } } /** @@ -239,8 +250,9 @@ }); this._nodeForId[message.id] = node; this._nodes.push(node); - if (this._filter(node)) + if (this._filter(node)) { this._dataGrid.insertChild(node); + } } }; @@ -316,8 +328,9 @@ this._tabbedPane.changeTabView('response', new UI.EmptyWidget(ls`No message selected`)); return; } - if (!requestEnabled) + if (!requestEnabled) { this._tabbedPane.selectTab('response'); + } this._tabbedPane.changeTabView('request', SourceFrame.JSONView.createViewSync(data.request)); this._tabbedPane.changeTabView('response', SourceFrame.JSONView.createViewSync(data.response));
diff --git a/third_party/blink/renderer/devtools/front_end/quick_open/CommandMenu.js b/third_party/blink/renderer/devtools/front_end/quick_open/CommandMenu.js index ae00a67..90edd467 100644 --- a/third_party/blink/renderer/devtools/front_end/quick_open/CommandMenu.js +++ b/third_party/blink/renderer/devtools/front_end/quick_open/CommandMenu.js
@@ -80,24 +80,28 @@ self.runtime.extensions(UI.ViewLocationResolver).forEach(extension => { const category = extension.descriptor()['category']; const name = extension.descriptor()['name']; - if (category && name) + if (category && name) { locations.set(name, category); + } }); const viewExtensions = self.runtime.extensions('view'); for (const extension of viewExtensions) { const category = locations.get(extension.descriptor()['location']); - if (category) + if (category) { this._commands.push(QuickOpen.CommandMenu.createRevealViewCommand(extension, ls(category))); + } } // Populate whitelisted settings. const settingExtensions = self.runtime.extensions('setting'); for (const extension of settingExtensions) { const options = extension.descriptor()['options']; - if (!options || !extension.descriptor()['category']) + if (!options || !extension.descriptor()['category']) { continue; - for (const pair of options) + } + for (const pair of options) { this._commands.push(QuickOpen.CommandMenu.createSettingCommand(extension, ls(pair['title']), pair['value'])); + } } } @@ -124,13 +128,15 @@ // Populate whitelisted actions. const actions = UI.actionRegistry.availableActions(); for (const action of actions) { - if (action.category()) + if (action.category()) { this._commands.push(QuickOpen.CommandMenu.createActionCommand(action)); + } } for (const command of allCommands) { - if (command.available()) + if (command.available()) { this._commands.push(command); + } } this._commands = this._commands.sort(commandComparator); @@ -182,15 +188,17 @@ let score = 0; // Score longer sequences higher. for (let i = 0; i < opcodes.length; ++i) { - if (opcodes[i][0] === Diff.Diff.Operation.Equal) + if (opcodes[i][0] === Diff.Diff.Operation.Equal) { score += opcodes[i][1].length * opcodes[i][1].length; + } } // Score panel/drawer reveals above regular actions. - if (command.category().startsWith('Panel')) + if (command.category().startsWith('Panel')) { score += 2; - else if (command.category().startsWith('Drawer')) + } else if (command.category().startsWith('Drawer')) { score += 1; + } return score; } @@ -220,8 +228,9 @@ * @param {string} promptValue */ selectItem(itemIndex, promptValue) { - if (itemIndex === null) + if (itemIndex === null) { return; + } this._commands[itemIndex].execute(); Host.userMetrics.actionTaken(Host.UserMetrics.Action.SelectCommandFromCommandMenu); }
diff --git a/third_party/blink/renderer/devtools/front_end/quick_open/FilteredListWidget.js b/third_party/blink/renderer/devtools/front_end/quick_open/FilteredListWidget.js index 5b8cd56..ca8cdc8 100644 --- a/third_party/blink/renderer/devtools/front_end/quick_open/FilteredListWidget.js +++ b/third_party/blink/renderer/devtools/front_end/quick_open/FilteredListWidget.js
@@ -61,8 +61,9 @@ * @return {boolean} */ static highlightRanges(element, query, caseInsensitive) { - if (!query) + if (!query) { return false; + } /** * @param {string} text @@ -75,10 +76,11 @@ const ranges = []; for (let i = 0; i < opcodes.length; ++i) { const opcode = opcodes[i]; - if (opcode[0] === Diff.Diff.Operation.Equal) + if (opcode[0] === Diff.Diff.Operation.Equal) { ranges.push(new TextUtils.SourceRange(offset, opcode[1].length)); - else if (opcode[0] !== Diff.Diff.Operation.Insert) + } else if (opcode[0] !== Diff.Diff.Operation.Insert) { return null; + } offset += opcode[1].length; } return ranges; @@ -86,8 +88,9 @@ const text = element.textContent; let ranges = rangesForMatch(text, query); - if (!ranges || caseInsensitive) + if (!ranges || caseInsensitive) { ranges = rangesForMatch(text.toUpperCase(), query.toUpperCase()); + } if (ranges) { UI.highlightRangesWithStyleClass(element, ranges, 'highlight'); return true; @@ -124,16 +127,19 @@ * @param {?QuickOpen.FilteredListWidget.Provider} provider */ setProvider(provider) { - if (provider === this._provider) + if (provider === this._provider) { return; + } - if (this._provider) + if (this._provider) { this._provider.detach(); + } this._clearTimers(); this._provider = provider; - if (this.isShowing()) + if (this.isShowing()) { this._attachProvider(); + } } _attachProvider() { @@ -168,8 +174,9 @@ * @override */ willHide() { - if (this._provider) + if (this._provider) { this._provider.detach(); + } this._clearTimers(); } @@ -187,21 +194,24 @@ * @param {!Event} event */ _onEnter(event) { - if (!this._provider) + if (!this._provider) { return; + } const selectedIndexInProvider = this._provider.itemCount() ? this._list.selectedItem() : null; this._selectItem(selectedIndexInProvider); - if (this._dialog) + if (this._dialog) { this._dialog.hide(); + } } /** * @param {?QuickOpen.FilteredListWidget.Provider} provider */ _itemsLoaded(provider) { - if (this._loadTimeout || provider !== this._provider) + if (this._loadTimeout || provider !== this._provider) { return; + } this._loadTimeout = setTimeout(this._updateAfterItemsLoaded.bind(this), 0); } @@ -252,8 +262,9 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected'); + } if (toElement) { toElement.classList.add('selected'); UI.ARIAUtils.alert(toElement.textContent, toElement); @@ -265,13 +276,15 @@ */ _onClick(event) { const item = this._list.itemForNode(/** @type {?Node} */ (event.target)); - if (item === null) + if (item === null) { return; + } event.consume(true); this._selectItem(item); - if (this._dialog) + if (this._dialog) { this._dialog.hide(); + } } /** @@ -297,8 +310,9 @@ break; } } - if (!completion) + if (!completion) { return false; + } this._prompt.focus(); this._prompt.setText(completion); this._prompt.setDOMSelection(userEnteredText.length, completion.length); @@ -316,8 +330,9 @@ clearTimeout(this._scoringTimer); delete this._scoringTimer; - if (this._refreshListWithCurrentResult) + if (this._refreshListWithCurrentResult) { this._refreshListWithCurrentResult(); + } } if (!this._provider) { @@ -370,13 +385,15 @@ for (i = fromIndex; i < this._provider.itemCount() && workDone < maxWorkItems; ++i) { // Filter out non-matching items quickly. - if (filterRegex && !filterRegex.test(this._provider.itemKeyAt(i))) + if (filterRegex && !filterRegex.test(this._provider.itemKeyAt(i))) { continue; + } // Score item. const score = this._provider.itemScoreAt(i, query); - if (query) + if (query) { workDone++; + } // Find its index in the scores array (earlier elements have bigger scores). if (score > minBestScore || bestScores.length < bestItemsToCollect) { @@ -400,8 +417,9 @@ // Process everything in chunks. if (i < this._provider.itemCount()) { this._scoringTimer = setTimeout(scoreItems.bind(this, i), 0); - if (window.performance.now() - scoreStartTime > 50) + if (window.performance.now() - scoreStartTime > 50) { this._progressBarElement.style.transform = 'scaleX(' + i / this._provider.itemCount() + ')'; + } return; } if (window.performance.now() - scoreStartTime > 100) { @@ -425,10 +443,12 @@ this._updateNotFoundMessage(!!filteredItems.length); const oldHeight = this._list.element.offsetHeight; this._items.replaceAll(filteredItems); - if (filteredItems.length) + if (filteredItems.length) { this._list.selectItem(filteredItems[0]); - if (this._list.element.offsetHeight !== oldHeight) + } + if (this._list.element.offsetHeight !== oldHeight) { this._list.viewportResized(); + } this._itemsFilteredForTest(); } @@ -450,10 +470,12 @@ } _queryChanged() { - if (this._queryChangedCallback) + if (this._queryChangedCallback) { this._queryChangedCallback(this._value()); - if (this._provider) + } + if (this._provider) { this._provider.queryChanged(this._cleanValue()); + } } /** @@ -481,13 +503,15 @@ handled = this._list.selectItemNextPage(false); break; } - if (handled) + if (handled) { event.consume(true); + } } _scheduleFilter() { - if (this._filterTimer) + if (this._filterTimer) { return; + } this._filterTimer = setTimeout(this._filterItems.bind(this), 0); } @@ -496,8 +520,9 @@ */ _selectItem(itemIndex) { this._promptHistory.push(this._value()); - if (this._promptHistory.length > 100) + if (this._promptHistory.length > 100) { this._promptHistory.shift(); + } this._provider.selectItem(itemIndex, this._cleanValue()); } };
diff --git a/third_party/blink/renderer/devtools/front_end/quick_open/HelpQuickOpen.js b/third_party/blink/renderer/devtools/front_end/quick_open/HelpQuickOpen.js index a8757e1..89b2d9ad 100644 --- a/third_party/blink/renderer/devtools/front_end/quick_open/HelpQuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/quick_open/HelpQuickOpen.js
@@ -13,8 +13,9 @@ * @param {!Runtime.Extension} extension */ _addProvider(extension) { - if (extension.title()) + if (extension.title()) { this._providers.push({prefix: extension.descriptor()['prefix'], title: extension.title()}); + } } /** @@ -64,8 +65,9 @@ * @param {string} promptValue */ selectItem(itemIndex, promptValue) { - if (itemIndex !== null) + if (itemIndex !== null) { QuickOpen.QuickOpen.show(this._providers[itemIndex].prefix); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/quick_open/QuickOpen.js b/third_party/blink/renderer/devtools/front_end/quick_open/QuickOpen.js index 04e78cec..742014d 100644 --- a/third_party/blink/renderer/devtools/front_end/quick_open/QuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/quick_open/QuickOpen.js
@@ -45,15 +45,17 @@ */ _queryChanged(query) { const prefix = this._prefixes.find(prefix => query.startsWith(prefix)); - if (typeof prefix !== 'string' || this._prefix === prefix) + if (typeof prefix !== 'string' || this._prefix === prefix) { return; + } this._prefix = prefix; this._filteredListWidget.setPrefix(prefix); this._filteredListWidget.setProvider(null); this._providers.get(prefix)().then(provider => { - if (this._prefix !== prefix) + if (this._prefix !== prefix) { return; + } this._filteredListWidget.setProvider(provider); this._providerLoadedForTest(provider); });
diff --git a/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js b/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js index 44d12696..ec6b0ab 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js
@@ -55,13 +55,15 @@ * @param {!SDK.Target} target */ targetAdded(target) { - if (this._target) + if (this._target) { return; + } this._target = target; this._resourceTreeModel = target.model(SDK.ResourceTreeModel); this._serviceWorkerManager = target.model(SDK.ServiceWorkerManager); - if (!this._resourceTreeModel || !this._serviceWorkerManager) + if (!this._resourceTreeModel || !this._serviceWorkerManager) { return; + } this._updateManifest(true); @@ -78,10 +80,12 @@ * @param {!SDK.Target} target */ targetRemoved(target) { - if (this._target !== target) + if (this._target !== target) { return; - if (!this._resourceTreeModel || !this._serviceWorkerManager) + } + if (!this._resourceTreeModel || !this._serviceWorkerManager) { return; + } delete this._resourceTreeModel; delete this._serviceWorkerManager; Common.EventTarget.removeEventListeners(this._registeredListeners); @@ -121,11 +125,13 @@ UI.createIconLabel(error.message, error.critical ? 'smallicon-error' : 'smallicon-warning')); } - if (!data) + if (!data) { return; + } - if (data.charCodeAt(0) === 0xFEFF) - data = data.slice(1); // Trim the BOM as per https://tools.ietf.org/html/rfc7159#section-8.1. + if (data.charCodeAt(0) === 0xFEFF) { + data = data.slice(1); + } // Trim the BOM as per https://tools.ietf.org/html/rfc7159#section-8.1. const parsedManifest = JSON.parse(data); this._nameField.textContent = stringProperty('name'); @@ -161,14 +167,16 @@ const title = (icon['sizes'] || '') + '\n' + (icon['type'] || ''); const field = this._iconsSection.appendField(title); const image = await this._loadImage(Common.ParsedURL.completeURL(url, icon['src'])); - if (image) + if (image) { field.appendChild(image); + } } this._installabilitySection.clearContent(); this._installabilitySection.element.classList.toggle('hidden', !installabilityErrors.length); - for (const error of installabilityErrors) + for (const error of installabilityErrors) { this._installabilitySection.appendRow().appendChild(UI.createIconLabel(error, 'smallicon-warning')); + } /** * @param {string} name @@ -176,8 +184,9 @@ */ function stringProperty(name) { const value = parsedManifest[name]; - if (typeof value !== 'string') + if (typeof value !== 'string') { return ''; + } return value; } }
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheItemsView.js b/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheItemsView.js index f83a6b6..7d8e72d 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheItemsView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheItemsView.js
@@ -85,8 +85,9 @@ } _maybeUpdate() { - if (!this.isShowing() || !this._viewDirty) + if (!this.isShowing() || !this._viewDirty) { return; + } this._update(); this._viewDirty = false; @@ -124,8 +125,9 @@ this._statusIcon.textContent = info.text; if (this.isShowing() && this._status === Resources.ApplicationCacheModel.IDLE && - (oldStatus === Resources.ApplicationCacheModel.UPDATEREADY || !this._resources)) + (oldStatus === Resources.ApplicationCacheModel.UPDATEREADY || !this._resources)) { this._markDirty(); + } this._maybeUpdate(); } @@ -154,8 +156,9 @@ this._emptyWidget.show(this.element); this._deleteButton.setVisible(false); - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.element.classList.add('hidden'); + } return; } // FIXME: are these variables needed anywhere else? @@ -165,8 +168,9 @@ this._size = applicationCache.size; this._resources = applicationCache.resources; - if (!this._dataGrid) + if (!this._dataGrid) { this._createDataGrid(); + } this._populateDataGrid(); this._dataGrid.autoSizeColumns(20, 80); @@ -237,16 +241,18 @@ } } - if (!nodeToSelect && this._dataGrid.rootNode().children.length) + if (!nodeToSelect && this._dataGrid.rootNode().children.length) { this._dataGrid.rootNode().children[0].selected = true; + } } /** * @param {!Common.Event} event */ _deleteButtonClicked(event) { - if (!this._dataGrid || !this._dataGrid.selectedNode) + if (!this._dataGrid || !this._dataGrid.selectedNode) { return; + } // FIXME: Delete Button semantics are not yet defined. (Delete a single, or all?) this._deleteCallback(this._dataGrid.selectedNode);
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheModel.js b/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheModel.js index 41c076e..946d0bb 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheModel.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ApplicationCacheModel.js
@@ -63,8 +63,9 @@ const frameId = frame.id; const manifestURL = await this._agent.getManifestForFrame(frameId); - if (manifestURL !== null && !manifestURL) + if (manifestURL !== null && !manifestURL) { this._frameManifestRemoved(frameId); + } } /** @@ -83,8 +84,9 @@ async _mainFrameNavigated() { const framesWithManifests = await this._agent.getFramesWithManifests(); - for (const frame of framesWithManifests || []) + for (const frame of framesWithManifests || []) { this._frameManifestUpdated(frame.frameId, frame.manifestURL, frame.status); + } } /** @@ -98,11 +100,13 @@ return; } - if (!manifestURL) + if (!manifestURL) { return; + } - if (this._manifestURLsByFrame[frameId] && manifestURL !== this._manifestURLsByFrame[frameId]) + if (this._manifestURLsByFrame[frameId] && manifestURL !== this._manifestURLsByFrame[frameId]) { this._frameManifestRemoved(frameId); + } const statusChanged = this._statuses[frameId] !== status; this._statuses[frameId] = status; @@ -112,16 +116,18 @@ this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestAdded, frameId); } - if (statusChanged) + if (statusChanged) { this.dispatchEventToListeners(Resources.ApplicationCacheModel.Events.FrameManifestStatusUpdated, frameId); + } } /** * @param {string} frameId */ _frameManifestRemoved(frameId) { - if (!this._manifestURLsByFrame[frameId]) + if (!this._manifestURLsByFrame[frameId]) { return; + } delete this._manifestURLsByFrame[frameId]; delete this._statuses[frameId];
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ApplicationPanelSidebar.js b/third_party/blink/renderer/devtools/front_end/resources/ApplicationPanelSidebar.js index 4b8bb66..46983629 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ApplicationPanelSidebar.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ApplicationPanelSidebar.js
@@ -157,8 +157,9 @@ SDK.ResourceTreeModel, SDK.ResourceTreeModel.Events.FrameNavigated, this._frameNavigated, this); const selection = this._panel.lastSelectedItemPath(); - if (!selection.length) + if (!selection.length) { manifestTreeElement.select(); + } } /** @@ -179,8 +180,9 @@ * @param {!SDK.Target} target */ targetAdded(target) { - if (this._target) + if (this._target) { return; + } this._target = target; this._databaseModel = target.model(Resources.DatabaseModel); if (this._databaseModel) { @@ -189,11 +191,13 @@ } const resourceTreeModel = target.model(SDK.ResourceTreeModel); - if (!resourceTreeModel) + if (!resourceTreeModel) { return; + } - if (resourceTreeModel.cachedResourcesLoaded()) + if (resourceTreeModel.cachedResourcesLoaded()) { this._initialize(); + } resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.CachedResourcesLoaded, this._initialize, this); resourceTreeModel.addEventListener( @@ -205,8 +209,9 @@ * @param {!SDK.Target} target */ targetRemoved(target) { - if (target !== this._target) + if (target !== this._target) { return; + } delete this._target; const resourceTreeModel = target.model(SDK.ResourceTreeModel); @@ -232,17 +237,21 @@ } _initialize() { - for (const frame of SDK.ResourceTreeModel.frames()) + for (const frame of SDK.ResourceTreeModel.frames()) { this._addCookieDocument(frame); - if (this._databaseModel) + } + if (this._databaseModel) { this._databaseModel.enable(); + } const cacheStorageModel = this._target.model(SDK.ServiceWorkerCacheModel); - if (cacheStorageModel) + if (cacheStorageModel) { cacheStorageModel.enable(); + } const resourceTreeModel = this._target.model(SDK.ResourceTreeModel); - if (resourceTreeModel) + if (resourceTreeModel) { this._populateApplicationCacheTree(resourceTreeModel); + } SDK.targetManager.observeModels(Resources.DOMStorageModel, /** @type {!SDK.SDKModelObserver} */ ({ modelAdded: model => this._domStorageModelAdded(model), modelRemoved: model => this._domStorageModelRemoved(model) @@ -259,14 +268,18 @@ if (Runtime.experiments.isEnabled('backgroundServices')) { this.backgroundFetchTreeElement._initialize(backgroundServiceModel); this.backgroundSyncTreeElement._initialize(backgroundServiceModel); - if (Runtime.experiments.isEnabled('backgroundServicesNotifications')) + if (Runtime.experiments.isEnabled('backgroundServicesNotifications')) { this.notificationsTreeElement._initialize(backgroundServiceModel); - if (Runtime.experiments.isEnabled('backgroundServicesPaymentHandler')) + } + if (Runtime.experiments.isEnabled('backgroundServicesPaymentHandler')) { this.paymentHandlerTreeElement._initialize(backgroundServiceModel); - if (Runtime.experiments.isEnabled('backgroundServicesPeriodicBackgroundSync')) + } + if (Runtime.experiments.isEnabled('backgroundServicesPeriodicBackgroundSync')) { this.periodicBackgroundSyncTreeElement._initialize(backgroundServiceModel); - if (Runtime.experiments.isEnabled('backgroundServicesPushMessaging')) + } + if (Runtime.experiments.isEnabled('backgroundServicesPushMessaging')) { this.pushMessagingTreeElement._initialize(backgroundServiceModel); + } } } @@ -308,8 +321,9 @@ } _resetAppCache() { - for (const frameId of Object.keys(this._applicationCacheFrameElements)) + for (const frameId of Object.keys(this._applicationCacheFrameElements)) { this._applicationCacheFrameManifestRemoved({data: frameId}); + } this.applicationCacheListTreeElement.setExpandable(false); } @@ -318,16 +332,20 @@ */ _treeElementAdded(event) { const selection = this._panel.lastSelectedItemPath(); - if (!selection.length) + if (!selection.length) { return; + } const element = event.data; const index = selection.indexOf(element.itemURL); - if (index < 0) + if (index < 0) { return; - for (let parent = element.parent; parent; parent = parent.parent) + } + for (let parent = element.parent; parent; parent = parent.parent) { parent.expand(); - if (index > 0) + } + if (index > 0) { element.expand(); + } element.select(); } @@ -343,12 +361,14 @@ _frameNavigated(event) { const frame = /** @type {!SDK.ResourceTreeFrame} */ (event.data); - if (frame.isTopFrame()) + if (frame.isTopFrame()) { this._reset(); + } const applicationCacheFrameTreeElement = this._applicationCacheFrameElements[frame.id]; - if (applicationCacheFrameTreeElement) + if (applicationCacheFrameTreeElement) { applicationCacheFrameTreeElement.frameNavigated(frame); + } this._addCookieDocument(frame); } @@ -367,8 +387,9 @@ */ _addCookieDocument(frame) { const parsedURL = frame.url.asParsedURL(); - if (!parsedURL || (parsedURL.scheme !== 'http' && parsedURL.scheme !== 'https' && parsedURL.scheme !== 'file')) + if (!parsedURL || (parsedURL.scheme !== 'http' && parsedURL.scheme !== 'https' && parsedURL.scheme !== 'file')) { return; + } const domain = parsedURL.securityOrigin(); if (!this._domains[domain]) { @@ -394,10 +415,11 @@ const domStorageTreeElement = new Resources.DOMStorageTreeElement(this._panel, domStorage); this._domStorageTreeElements.set(domStorage, domStorageTreeElement); - if (domStorage.isLocalStorage) + if (domStorage.isLocalStorage) { this.localStorageListTreeElement.appendChild(domStorageTreeElement); - else + } else { this.sessionStorageListTreeElement.appendChild(domStorageTreeElement); + } } /** @@ -413,13 +435,15 @@ */ _removeDOMStorage(domStorage) { const treeElement = this._domStorageTreeElements.get(domStorage); - if (!treeElement) + if (!treeElement) { return; + } const wasSelected = treeElement.selected; const parentListTreeElement = treeElement.parent; parentListTreeElement.removeChild(treeElement); - if (wasSelected) + if (wasSelected) { parentListTreeElement.select(); + } this._domStorageTreeElements.remove(domStorage); } @@ -448,8 +472,9 @@ * @param {string=} tableName */ _showDatabase(database, tableName) { - if (!database) + if (!database) { return; + } let view; if (tableName) { @@ -501,31 +526,36 @@ async _updateDatabaseTables(event) { const database = /** @type {!Resources.Database} */ (event.data); - if (!database) + if (!database) { return; + } const databasesTreeElement = this._databaseTreeElements.get(database); - if (!databasesTreeElement) + if (!databasesTreeElement) { return; + } databasesTreeElement.invalidateChildren(); const tableViews = this._databaseTableViews.get(database); - if (!tableViews) + if (!tableViews) { return; + } const tableNamesHash = {}; const panel = this._panel; const tableNames = await database.tableNames(); const tableNamesLength = tableNames.length; - for (let i = 0; i < tableNamesLength; ++i) + for (let i = 0; i < tableNamesLength; ++i) { tableNamesHash[tableNames[i]] = true; + } for (const tableName in tableViews) { if (!(tableName in tableNamesHash)) { - if (panel.visibleView === tableViews[tableName]) + if (panel.visibleView === tableViews[tableName]) { panel.showView(null); + } delete tableViews[tableName]; } } @@ -579,8 +609,9 @@ _applicationCacheFrameManifestRemoved(event) { const frameId = event.data; const frameTreeElement = this._applicationCacheFrameElements[frameId]; - if (!frameTreeElement) + if (!frameTreeElement) { return; + } const manifestURL = frameTreeElement.manifestURL; delete this._applicationCacheFrameElements[frameId]; @@ -588,8 +619,9 @@ frameTreeElement.parent.removeChild(frameTreeElement); const manifestTreeElement = this._applicationCacheManifestElements[manifestURL]; - if (manifestTreeElement.childCount()) + if (manifestTreeElement.childCount()) { return; + } delete this._applicationCacheManifestElements[manifestURL]; manifestTreeElement.parent.removeChild(manifestTreeElement); @@ -599,34 +631,40 @@ const frameId = event.data; const status = this._applicationCacheModel.frameManifestStatus(frameId); - if (this._applicationCacheViews[frameId]) + if (this._applicationCacheViews[frameId]) { this._applicationCacheViews[frameId].updateStatus(status); + } } _applicationCacheNetworkStateChanged(event) { const isNowOnline = event.data; - for (const manifestURL in this._applicationCacheViews) + for (const manifestURL in this._applicationCacheViews) { this._applicationCacheViews[manifestURL].updateNetworkState(isNowOnline); + } } showView(view) { - if (view) + if (view) { this.showResource(view.resource); + } } _onmousemove(event) { const nodeUnderMouse = event.target; - if (!nodeUnderMouse) + if (!nodeUnderMouse) { return; + } const listNode = nodeUnderMouse.enclosingNodeOrSelfWithNodeName('li'); - if (!listNode) + if (!listNode) { return; + } const element = listNode.treeElement; - if (this._previousHoveredElement === element) + if (this._previousHoveredElement === element) { return; + } if (this._previousHoveredElement) { this._previousHoveredElement.hovered = false; @@ -666,14 +704,16 @@ * @return {boolean} */ onselect(selectedByUser) { - if (!selectedByUser) + if (!selectedByUser) { return false; + } const path = []; for (let el = this; el; el = el.parent) { const url = el.itemURL; - if (!url) + if (!url) { break; + } path.push(url); } this._storagePanel.setLastSelectedItemPath(path); @@ -730,8 +770,9 @@ */ onattach() { super.onattach(); - if (this._expandedSetting.get()) + if (this._expandedSetting.get()) { this.expand(); + } } /** @@ -802,8 +843,9 @@ _initialize(model) { this._model = model; // Show the view if the model was initialized after selection. - if (this._selected && !this._view) + if (this._selected && !this._view) { this.onselect(false); + } } /** @@ -821,11 +863,13 @@ super.onselect(selectedByUser); this._selected = true; - if (!this._model) + if (!this._model) { return false; + } - if (!this._view) + if (!this._view) { this._view = new Resources.BackgroundServiceView(this._serviceName, this._model); + } this.showView(this._view); UI.context.setFlavor(Resources.BackgroundServiceView, this._view); return false; @@ -873,8 +917,9 @@ async updateChildren() { this.removeChildren(); const tableNames = await this._database.tableNames(); - for (const tableName of tableNames) + for (const tableName of tableNames) { this.appendChild(new Resources.DatabaseTableTreeElement(this._sidebar, this._database, tableName)); + } } }; @@ -934,8 +979,9 @@ this._swCacheTreeElements = []; this._swCacheModel = model; if (model) { - for (const cache of model.caches()) + for (const cache of model.caches()) { this._addCache(model, cache); + } } SDK.targetManager.addModelListener( SDK.ServiceWorkerCacheModel, SDK.ServiceWorkerCacheModel.Events.CacheAdded, this._cacheAdded, this); @@ -958,8 +1004,9 @@ } _refreshCaches() { - if (this._swCacheModel) + if (this._swCacheModel) { this._swCacheModel.refreshCacheNames(); + } } /** @@ -989,8 +1036,9 @@ const model = /** @type {!SDK.ServiceWorkerCacheModel} */ (event.data.model); const swCacheTreeElement = this._cacheTreeElement(model, cache); - if (!swCacheTreeElement) + if (!swCacheTreeElement) { return; + } this.removeChild(swCacheTreeElement); this._swCacheTreeElements.remove(swCacheTreeElement); @@ -1011,8 +1059,9 @@ break; } } - if (index !== -1) + if (index !== -1) { return this._swCacheTreeElements[i]; + } return null; } }; @@ -1061,8 +1110,9 @@ */ update(cache) { this._cache = cache; - if (this._view) + if (this._view) { this._view.update(cache); + } } /** @@ -1071,8 +1121,9 @@ */ onselect(selectedByUser) { super.onselect(selectedByUser); - if (!this._view) + if (!this._view) { this._view = new Resources.ServiceWorkerCacheView(this._model, this._cache); + } this.showView(this._view); return false; @@ -1105,8 +1156,9 @@ */ onselect(selectedByUser) { super.onselect(selectedByUser); - if (!this._view) + if (!this._view) { this._view = new Resources.ServiceWorkersView(); + } this.showView(this._view); return false; } @@ -1138,8 +1190,9 @@ */ onselect(selectedByUser) { super.onselect(selectedByUser); - if (!this._view) + if (!this._view) { this._view = new Resources.AppManifestView(); + } this.showView(this._view); return false; } @@ -1171,8 +1224,9 @@ */ onselect(selectedByUser) { super.onselect(selectedByUser); - if (!this._view) + if (!this._view) { this._view = new Resources.ClearStorageView(); + } this.showView(this._view); return false; } @@ -1206,8 +1260,9 @@ for (const indexedDBModel of SDK.targetManager.models(Resources.IndexedDBModel)) { const databases = indexedDBModel.databases(); - for (let j = 0; j < databases.length; ++j) + for (let j = 0; j < databases.length; ++j) { this._addIndexedDB(indexedDBModel, databases[j]); + } } } @@ -1216,8 +1271,9 @@ */ removeIndexedDBForModel(model) { const idbDatabaseTreeElements = this._idbDatabaseTreeElements.filter(element => element._model === model); - for (const idbDatabaseTreeElement of idbDatabaseTreeElements) + for (const idbDatabaseTreeElement of idbDatabaseTreeElements) { this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement); + } } /** @@ -1235,8 +1291,9 @@ } refreshIndexedDB() { - for (const indexedDBModel of SDK.targetManager.models(Resources.IndexedDBModel)) + for (const indexedDBModel of SDK.targetManager.models(Resources.IndexedDBModel)) { indexedDBModel.refreshDatabaseNames(); + } } /** @@ -1267,8 +1324,9 @@ const model = /** @type {!Resources.IndexedDBModel} */ (event.data.model); const idbDatabaseTreeElement = this._idbDatabaseTreeElement(model, databaseId); - if (!idbDatabaseTreeElement) + if (!idbDatabaseTreeElement) { return; + } this._removeIDBDatabaseTreeElement(idbDatabaseTreeElement); } @@ -1291,8 +1349,9 @@ const entriesUpdated = /** @type {boolean} */ (event.data.entriesUpdated); const idbDatabaseTreeElement = this._idbDatabaseTreeElement(model, database.databaseId); - if (!idbDatabaseTreeElement) + if (!idbDatabaseTreeElement) { return; + } idbDatabaseTreeElement.update(database, entriesUpdated); this._indexedDBLoadedForTest(); } @@ -1310,8 +1369,9 @@ const model = /** @type {!Resources.IndexedDBModel} */ (event.data.model); const idbDatabaseTreeElement = this._idbDatabaseTreeElement(model, databaseId); - if (!idbDatabaseTreeElement) + if (!idbDatabaseTreeElement) { return; + } idbDatabaseTreeElement.indexedDBContentUpdated(objectStoreName); } @@ -1370,8 +1430,9 @@ * @param {string} objectStoreName */ indexedDBContentUpdated(objectStoreName) { - if (this._idbObjectStoreTreeElements[objectStoreName]) + if (this._idbObjectStoreTreeElements[objectStoreName]) { this._idbObjectStoreTreeElements[objectStoreName].markNeedsRefresh(); + } } /** @@ -1394,21 +1455,24 @@ this._idbObjectStoreTreeElements[objectStore.name].update(objectStore, entriesUpdated); } for (const objectStoreName in this._idbObjectStoreTreeElements) { - if (!objectStoreNames[objectStoreName]) + if (!objectStoreNames[objectStoreName]) { this._objectStoreRemoved(objectStoreName); + } } - if (this._view) + if (this._view) { this._view.update(database); + } this._updateTooltip(); } _updateTooltip() { - if (Object.keys(this._idbObjectStoreTreeElements).length === 0) + if (Object.keys(this._idbObjectStoreTreeElements).length === 0) { this.tooltip = ls`Version: ${this._database.version} (empty)`; - else + } else { this.tooltip = ls`Version: ${this._database.version}`; + } } /** @@ -1417,8 +1481,9 @@ */ onselect(selectedByUser) { super.onselect(selectedByUser); - if (!this._view) + if (!this._view) { this._view = new Resources.IDBDatabaseView(this._model, this._database); + } this.showView(this._view); return false; @@ -1436,8 +1501,9 @@ } clear() { - for (const objectStoreName in this._idbObjectStoreTreeElements) + for (const objectStoreName in this._idbObjectStoreTreeElements) { this._objectStoreRemoved(objectStoreName); + } } }; @@ -1474,10 +1540,12 @@ } markNeedsRefresh() { - if (this._view) + if (this._view) { this._view.markNeedsRefresh(); - for (const indexName in this._idbIndexTreeElements) + } + for (const indexName in this._idbIndexTreeElements) { this._idbIndexTreeElements[indexName].markNeedsRefresh(); + } } _handleContextMenuEvent(event) { @@ -1487,10 +1555,12 @@ } _refreshObjectStore() { - if (this._view) + if (this._view) { this._view.refreshData(); - for (const indexName in this._idbIndexTreeElements) + } + for (const indexName in this._idbIndexTreeElements) { this._idbIndexTreeElements[indexName].refreshIndex(); + } } async _clearObjectStore() { @@ -1519,8 +1589,9 @@ this._idbIndexTreeElements[index.name].update(this._objectStore, index, entriesUpdated); } for (const indexName in this._idbIndexTreeElements) { - if (!indexNames[indexName]) + if (!indexNames[indexName]) { this._indexRemoved(indexName); + } } for (const indexName in this._idbIndexTreeElements) { if (!indexNames[indexName]) { @@ -1529,11 +1600,13 @@ } } - if (this.childCount()) + if (this.childCount()) { this.expand(); + } - if (this._view && entriesUpdated) + if (this._view && entriesUpdated) { this._view.update(this._objectStore, null); + } this._updateTooltip(); } @@ -1541,8 +1614,9 @@ _updateTooltip() { const keyPathString = this._objectStore.keyPathString; let tooltipString = keyPathString !== null ? ls`Key path: ${keyPathString}` : ''; - if (this._objectStore.autoIncrement) + if (this._objectStore.autoIncrement) { tooltipString += '\n' + Common.UIString('autoIncrement'); + } this.tooltip = tooltipString; } @@ -1572,10 +1646,12 @@ } clear() { - for (const indexName in this._idbIndexTreeElements) + for (const indexName in this._idbIndexTreeElements) { this._indexRemoved(indexName); - if (this._view) + } + if (this._view) { this._view.clear(); + } } }; @@ -1606,13 +1682,15 @@ } markNeedsRefresh() { - if (this._view) + if (this._view) { this._view.markNeedsRefresh(); + } } refreshIndex() { - if (this._view) + if (this._view) { this._view.refreshData(); + } } /** @@ -1624,8 +1702,9 @@ this._objectStore = objectStore; this._index = index; - if (this._view && entriesUpdated) + if (this._view && entriesUpdated) { this._view.update(this._objectStore, this._index); + } this._updateTooltip(); } @@ -1634,10 +1713,12 @@ const tooltipLines = []; const keyPathString = this._index.keyPathString; tooltipLines.push(ls`Key path: ${keyPathString}`); - if (this._index.unique) + if (this._index.unique) { tooltipLines.push(Common.UIString('unique')); - if (this._index.multiEntry) + } + if (this._index.multiEntry) { tooltipLines.push(Common.UIString('multiEntry')); + } this.tooltip = tooltipLines.join('\n'); } @@ -1657,8 +1738,9 @@ } clear() { - if (this._view) + if (this._view) { this._view.clear(); + } } }; @@ -1867,10 +1949,12 @@ * @param {?string} link */ setLink(link) { - if (link && !this._linkElement) + if (link && !this._linkElement) { this._linkElement = this._emptyWidget.appendLink(link); - if (!link && this._linkElement) + } + if (!link && this._linkElement) { this._linkElement.classList.add('hidden'); + } if (link && this._linkElement) { this._linkElement.setAttribute('href', link); this._linkElement.classList.remove('hidden');
diff --git a/third_party/blink/renderer/devtools/front_end/resources/BackgroundServiceView.js b/third_party/blink/renderer/devtools/front_end/resources/BackgroundServiceView.js index fec6f917..fe52daf5 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/BackgroundServiceView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/BackgroundServiceView.js
@@ -127,8 +127,9 @@ _refreshView() { this._clearView(); const events = this._model.getEvents(this._serviceName).filter(event => this._acceptEvent(event)); - for (const event of events) + for (const event of events) { this._addEvent(event); + } } /** @@ -161,11 +162,13 @@ */ _onRecordingStateChanged(event) { const state = /** @type {!Resources.BackgroundServiceModel.RecordingState} */ (event.data); - if (state.serviceName !== this._serviceName) + if (state.serviceName !== this._serviceName) { return; + } - if (state.isRecording === this._recordButton.toggled()) + if (state.isRecording === this._recordButton.toggled()) { return; + } this._recordButton.setToggled(state.isRecording); this._showPreview(this._selectedEventNode); @@ -176,15 +179,17 @@ */ _onEventReceived(event) { const serviceEvent = /** @type {!Protocol.BackgroundService.BackgroundServiceEvent} */ (event.data); - if (!this._acceptEvent(serviceEvent)) + if (!this._acceptEvent(serviceEvent)) { return; + } this._addEvent(serviceEvent); } _onOriginChanged() { // No need to refresh the view if we are already showing all events. - if (this._originCheckbox.checked()) + if (this._originCheckbox.checked()) { return; + } this._refreshView(); } @@ -234,8 +239,9 @@ // Try to get the scope of the Service Worker registration to be more user-friendly. const registration = this._serviceWorkerManager.registrations().get(serviceEvent.serviceWorkerRegistrationId); - if (registration) + if (registration) { swScope = registration.scopeURL.substr(registration.securityOrigin.length); + } return { id: this._dataGrid.rootNode().children.length + 1, @@ -253,11 +259,13 @@ * @return {boolean} */ _acceptEvent(event) { - if (event.service !== this._serviceName) + if (event.service !== this._serviceName) { return false; + } - if (this._originCheckbox.checked()) + if (this._originCheckbox.checked()) { return true; + } // Trim the trailing '/'. const origin = event.origin.substr(0, event.origin.length - 1); @@ -296,13 +304,15 @@ * @param {?Resources.BackgroundServiceView.EventDataNode} dataNode */ _showPreview(dataNode) { - if (this._selectedEventNode && this._selectedEventNode === dataNode) + if (this._selectedEventNode && this._selectedEventNode === dataNode) { return; + } this._selectedEventNode = dataNode; - if (this._preview) + if (this._preview) { this._preview.detach(); + } if (this._selectedEventNode) { this._preview = this._selectedEventNode.createPreview(); @@ -349,8 +359,9 @@ const stream = new Bindings.FileOutputStream(); const accepted = await stream.open(fileName); - if (!accepted) + if (!accepted) { return; + } const events = this._model.getEvents(this._serviceName).filter(event => this._acceptEvent(event)); await stream.write(JSON.stringify(events, undefined, 2));
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js b/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js index 9d07955..5966f5d42 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ClearStorageView.js
@@ -29,8 +29,9 @@ this._securityOrigin = null; this._settings = new Map(); - for (const type of Resources.ClearStorageView.AllStorageTypes) + for (const type of Resources.ClearStorageView.AllStorageTypes) { this._settings.set(type, Common.settings.createSetting('clear-storage-' + type, true)); + } const quota = this._reportView.appendSection(Common.UIString('Usage')); this._quotaRow = quota.appendSelectableRow(); @@ -84,8 +85,9 @@ * @param {!SDK.Target} target */ targetAdded(target) { - if (this._target) + if (this._target) { return; + } this._target = target; const securityOriginManager = target.model(SDK.SecurityOriginManager); this._updateOrigin( @@ -99,8 +101,9 @@ * @param {!SDK.Target} target */ targetRemoved(target) { - if (this._target !== target) + if (this._target !== target) { return; + } const securityOriginManager = target.model(SDK.SecurityOriginManager); securityOriginManager.removeEventListener( SDK.SecurityOriginManager.Events.MainSecurityOriginChanged, this._originChanged, this); @@ -132,16 +135,19 @@ } _clear() { - if (!this._securityOrigin) + if (!this._securityOrigin) { return; + } const selectedStorageTypes = []; for (const type of this._settings.keys()) { - if (this._settings.get(type).get()) + if (this._settings.get(type).get()) { selectedStorageTypes.push(type); + } } - if (this._target) + if (this._target) { Resources.ClearStorageView.clear(this._target, this._securityOrigin, selectedStorageTypes); + } this._clearButton.disabled = true; const label = this._clearButton.textContent; @@ -164,22 +170,25 @@ const hasAll = set.has(Protocol.Storage.StorageType.All); if (set.has(Protocol.Storage.StorageType.Cookies) || hasAll) { const cookieModel = target.model(SDK.CookieModel); - if (cookieModel) + if (cookieModel) { cookieModel.clear(); + } } if (set.has(Protocol.Storage.StorageType.Indexeddb) || hasAll) { for (const target of SDK.targetManager.targets()) { const indexedDBModel = target.model(Resources.IndexedDBModel); - if (indexedDBModel) + if (indexedDBModel) { indexedDBModel.clearForOrigin(securityOrigin); + } } } if (set.has(Protocol.Storage.StorageType.Local_storage) || hasAll) { const storageModel = target.model(Resources.DOMStorageModel); - if (storageModel) + if (storageModel) { storageModel.clearForOrigin(securityOrigin); + } } if (set.has(Protocol.Storage.StorageType.Websql) || hasAll) { @@ -193,14 +202,16 @@ if (set.has(Protocol.Storage.StorageType.Cache_storage) || hasAll) { const target = SDK.targetManager.mainTarget(); const model = target && target.model(SDK.ServiceWorkerCacheModel); - if (model) + if (model) { model.clearForOrigin(securityOrigin); + } } if (set.has(Protocol.Storage.StorageType.Appcache) || hasAll) { const appcacheModel = target.model(Resources.ApplicationCacheModel); - if (appcacheModel) + if (appcacheModel) { appcacheModel.reset(); + } } } @@ -209,8 +220,9 @@ * @return {!Promise<?>} */ async doUpdate() { - if (!this._securityOrigin) + if (!this._securityOrigin) { return; + } const securityOrigin = /** @type {string} */ (this._securityOrigin); const response = await this._target.storageAgent().invoke_getUsageAndQuota({origin: securityOrigin}); @@ -232,8 +244,9 @@ this._resetPieChart(response.usage); for (const usageForType of response.usageBreakdown.sort((a, b) => b.usage - a.usage)) { const value = usageForType.usage; - if (!value) + if (!value) { continue; + } const title = this._getStorageTypeName(usageForType.storageType); const color = this._pieColors.get(usageForType.storageType) || '#ccc'; this._pieChart.addSlice(value, color, title); @@ -313,14 +326,17 @@ */ _handleClear() { const target = SDK.targetManager.mainTarget(); - if (!target) + if (!target) { return false; + } const resourceTreeModel = target.model(SDK.ResourceTreeModel); - if (!resourceTreeModel) + if (!resourceTreeModel) { return false; + } const securityOrigin = resourceTreeModel.getMainSecurityOrigin(); - if (!securityOrigin) + if (!securityOrigin) { return false; + } Resources.ClearStorageView.clear(target, securityOrigin, Resources.ClearStorageView.AllStorageTypes); return true;
diff --git a/third_party/blink/renderer/devtools/front_end/resources/CookieItemsView.js b/third_party/blink/renderer/devtools/front_end/resources/CookieItemsView.js index 87f39a4..c9727b9 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/CookieItemsView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/CookieItemsView.js
@@ -95,14 +95,17 @@ * @param {?SDK.Cookie} value */ _showPreview(preview, value) { - if (this._preview && this._previewValue === value) + if (this._preview && this._previewValue === value) { return; + } - if (this._preview) + if (this._preview) { this._preview.detach(); + } - if (!preview) + if (!preview) { preview = new UI.EmptyWidget(ls`Select a cookie to preview it value`); + } this._previewValue = value; this._preview = preview; @@ -145,10 +148,12 @@ * @return {!Promise<boolean>} */ _saveCookie(newCookie, oldCookie) { - if (!this._model) + if (!this._model) { return Promise.resolve(false); - if (oldCookie && (newCookie.name() !== oldCookie.name() || newCookie.url() !== oldCookie.url())) + } + if (oldCookie && (newCookie.name() !== oldCookie.name() || newCookie.url() !== oldCookie.url())) { this._model.deleteCookie(oldCookie); + } return this._model.saveCookie(newCookie); } @@ -189,8 +194,9 @@ */ deleteSelectedItem() { const selectedCookie = this._cookiesTable.selectedCookie(); - if (selectedCookie) + if (selectedCookie) { this._model.deleteCookie(selectedCookie, () => this.refreshItems()); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/resources/DOMStorageItemsView.js b/third_party/blink/renderer/devtools/front_end/resources/DOMStorageItemsView.js index 7b054ca..6a22561 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/DOMStorageItemsView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/DOMStorageItemsView.js
@@ -91,8 +91,9 @@ } _domStorageItemsCleared() { - if (!this.isShowing() || !this._dataGrid) + if (!this.isShowing() || !this._dataGrid) { return; + } this._dataGrid.rootNode().removeChildren(); this._dataGrid.addCreationNode(false); @@ -103,8 +104,9 @@ * @param {!Common.Event} event */ _domStorageItemRemoved(event) { - if (!this.isShowing() || !this._dataGrid) + if (!this.isShowing() || !this._dataGrid) { return; + } const storageData = event.data; const rootNode = this._dataGrid.rootNode(); @@ -124,16 +126,18 @@ * @param {!Common.Event} event */ _domStorageItemAdded(event) { - if (!this.isShowing() || !this._dataGrid) + if (!this.isShowing() || !this._dataGrid) { return; + } const storageData = event.data; const rootNode = this._dataGrid.rootNode(); const children = rootNode.children; for (let i = 0; i < children.length; ++i) { - if (children[i].data.key === storageData.key) + if (children[i].data.key === storageData.key) { return; + } } const childNode = new DataGrid.DataGridNode({key: storageData.key, value: storageData.value}, false); @@ -144,18 +148,21 @@ * @param {!Common.Event} event */ _domStorageItemUpdated(event) { - if (!this.isShowing() || !this._dataGrid) + if (!this.isShowing() || !this._dataGrid) { return; + } const storageData = event.data; const childNode = this._dataGrid.rootNode().children.find(child => child.data.key === storageData.key); - if (!childNode || childNode.data.value === storageData.value) + if (!childNode || childNode.data.value === storageData.value) { return; + } childNode.data.value = storageData.value; childNode.refresh(); - if (!childNode.selected) + if (!childNode.selected) { return; + } this._previewEntry(childNode); this.setCanDeleteSelected(true); } @@ -167,8 +174,9 @@ const rootNode = this._dataGrid.rootNode(); let selectedKey = null; for (const node of rootNode.children) { - if (!node.selected) + if (!node.selected) { continue; + } selectedKey = node.data.key; break; } @@ -181,11 +189,13 @@ const node = new DataGrid.DataGridNode({key: key, value: value}, false); node.selectable = true; rootNode.appendChild(node); - if (!selectedNode || key === selectedKey) + if (!selectedNode || key === selectedKey) { selectedNode = node; + } } - if (selectedNode) + if (selectedNode) { selectedNode.selected = true; + } this._dataGrid.addCreationNode(false); this.setCanDeleteSelected(!!selectedNode); } @@ -194,8 +204,9 @@ * @override */ deleteSelectedItem() { - if (!this._dataGrid || !this._dataGrid.selectedNode) + if (!this._dataGrid || !this._dataGrid.selectedNode) { return; + } this._deleteCallback(this._dataGrid.selectedNode); } @@ -219,8 +230,9 @@ _editingCallback(editingNode, columnIdentifier, oldText, newText) { const domStorage = this._domStorage; if (columnIdentifier === 'key') { - if (typeof oldText === 'string') + if (typeof oldText === 'string') { domStorage.removeItem(oldText); + } domStorage.setItem(newText, editingNode.data.value || ''); this._removeDupes(editingNode); } else { @@ -236,17 +248,20 @@ const children = rootNode.children; for (let i = children.length - 1; i >= 0; --i) { const childNode = children[i]; - if ((childNode.data.key === masterNode.data.key) && (masterNode !== childNode)) + if ((childNode.data.key === masterNode.data.key) && (masterNode !== childNode)) { rootNode.removeChild(childNode); + } } } _deleteCallback(node) { - if (!node || node.isCreationNode) + if (!node || node.isCreationNode) { return; + } - if (this._domStorage) + if (this._domStorage) { this._domStorage.removeItem(node.data.key); + } } /** @@ -254,12 +269,15 @@ * @param {?string} value */ _showPreview(preview, value) { - if (this._preview && this._previewValue === value) + if (this._preview && this._previewValue === value) { return; - if (this._preview) + } + if (this._preview) { this._preview.detach(); - if (!preview) + } + if (!preview) { preview = new UI.EmptyWidget(Common.UIString('Select a value to preview')); + } this._previewValue = value; this._preview = preview; preview.show(this._previewPanel.contentElement); @@ -280,8 +298,9 @@ Common.StaticContentProvider.fromString(url, Common.resourceTypes.XHR, /** @type {string} */ (value)); const preview = await SourceFrame.PreviewFactory.createPreview(provider, 'text/plain'); // Selection could've changed while the preview was loaded - if (!entry.selected) + if (!entry.selected) { return; + } this._showPreview(preview, value); } };
diff --git a/third_party/blink/renderer/devtools/front_end/resources/DOMStorageModel.js b/third_party/blink/renderer/devtools/front_end/resources/DOMStorageModel.js index 176f1d1..c9a1cbfc 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/DOMStorageModel.js +++ b/third_party/blink/renderer/devtools/front_end/resources/DOMStorageModel.js
@@ -120,8 +120,9 @@ } enable() { - if (this._enabled) + if (this._enabled) { return; + } this.target().registerDOMStorageDispatcher(new Resources.DOMStorageDispatcher(this)); this._securityOriginManager.addEventListener( @@ -129,8 +130,9 @@ this._securityOriginManager.addEventListener( SDK.SecurityOriginManager.Events.SecurityOriginRemoved, this._securityOriginRemoved, this); - for (const securityOrigin of this._securityOriginManager.securityOrigins()) + for (const securityOrigin of this._securityOriginManager.securityOrigins()) { this._addOrigin(securityOrigin); + } this._agent.enable(); this._enabled = true; @@ -140,8 +142,9 @@ * @param {string} origin */ clearForOrigin(origin) { - if (!this._enabled) + if (!this._enabled) { return; + } for (const isLocal of [true, false]) { const key = this._storageKey(origin, isLocal); const storage = this._storages[key]; @@ -164,8 +167,9 @@ _addOrigin(securityOrigin) { const parsed = new Common.ParsedURL(securityOrigin); // These are "opaque" origins which are not supposed to support DOM storage. - if (!parsed.isValid || parsed.scheme === 'data' || parsed.scheme === 'about' || parsed.scheme === 'javascript') + if (!parsed.isValid || parsed.scheme === 'data' || parsed.scheme === 'about' || parsed.scheme === 'javascript') { return; + } for (const isLocal of [true, false]) { const key = this._storageKey(securityOrigin, isLocal); @@ -190,8 +194,9 @@ for (const isLocal of [true, false]) { const key = this._storageKey(securityOrigin, isLocal); const storage = this._storages[key]; - if (!storage) + if (!storage) { continue; + } delete this._storages[key]; this.dispatchEventToListeners(Resources.DOMStorageModel.Events.DOMStorageRemoved, storage); } @@ -211,8 +216,9 @@ */ _domStorageItemsCleared(storageId) { const domStorage = this.storageForId(storageId); - if (!domStorage) + if (!domStorage) { return; + } const eventData = {}; domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemsCleared, eventData); @@ -224,8 +230,9 @@ */ _domStorageItemRemoved(storageId, key) { const domStorage = this.storageForId(storageId); - if (!domStorage) + if (!domStorage) { return; + } const eventData = {key: key}; domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemRemoved, eventData); @@ -238,8 +245,9 @@ */ _domStorageItemAdded(storageId, key, value) { const domStorage = this.storageForId(storageId); - if (!domStorage) + if (!domStorage) { return; + } const eventData = {key: key, value: value}; domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemAdded, eventData); @@ -253,8 +261,9 @@ */ _domStorageItemUpdated(storageId, key, oldValue, value) { const domStorage = this.storageForId(storageId); - if (!domStorage) + if (!domStorage) { return; + } const eventData = {key: key, oldValue: oldValue, value: value}; domStorage.dispatchEventToListeners(Resources.DOMStorage.Events.DOMStorageItemUpdated, eventData); @@ -273,8 +282,9 @@ */ storages() { const result = []; - for (const id in this._storages) + for (const id in this._storages) { result.push(this._storages[id]); + } return result; } };
diff --git a/third_party/blink/renderer/devtools/front_end/resources/DatabaseModel.js b/third_party/blink/renderer/devtools/front_end/resources/DatabaseModel.js index 816abc5..cd3b1d3 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/DatabaseModel.js +++ b/third_party/blink/renderer/devtools/front_end/resources/DatabaseModel.js
@@ -106,12 +106,13 @@ return; } let message; - if (sqlError.message) + if (sqlError.message) { message = sqlError.message; - else if (sqlError.code === 2) + } else if (sqlError.code === 2) { message = Common.UIString('Database no longer has expected version.'); - else + } else { message = Common.UIString('An unexpected error %s occurred.', sqlError.code); + } onError(message); } }; @@ -132,15 +133,17 @@ } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._agent.enable(); this._enabled = true; } disable() { - if (!this._enabled) + if (!this._enabled) { return; + } this._enabled = false; this._databases = []; this._agent.disable(); @@ -152,8 +155,9 @@ */ databases() { const result = []; - for (const database of this._databases) + for (const database of this._databases) { result.push(database); + } return result; }
diff --git a/third_party/blink/renderer/devtools/front_end/resources/DatabaseQueryView.js b/third_party/blink/renderer/devtools/front_end/resources/DatabaseQueryView.js index 3921e9db..bcbc5791b 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/DatabaseQueryView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/DatabaseQueryView.js
@@ -51,8 +51,9 @@ } _messagesClicked() { - if (!this._prompt.isCaretInsidePrompt() && !this.element.hasSelection()) + if (!this._prompt.isCaretInsidePrompt() && !this.element.hasSelection()) { this._prompt.moveCaretToEndOfPrompt(); + } } /** @@ -62,8 +63,9 @@ * @return {!Promise<!UI.SuggestBox.Suggestions>} */ async completions(expression, prefix, force) { - if (!prefix) + if (!prefix) { return []; + } prefix = prefix.toLowerCase(); const tableNames = await this.database.tableNames(); @@ -74,8 +76,9 @@ } _selectStart(event) { - if (this._selectionTimeout) + if (this._selectionTimeout) { clearTimeout(this._selectionTimeout); + } this._prompt.clearAutocomplete(); @@ -84,8 +87,9 @@ */ function moveBackIfOutside() { delete this._selectionTimeout; - if (!this._prompt.isCaretInsidePrompt() && !this.element.hasSelection()) + if (!this._prompt.isCaretInsidePrompt() && !this.element.hasSelection()) { this._prompt.moveCaretToEndOfPrompt(); + } this._prompt.autoCompleteSoon(); } @@ -105,8 +109,9 @@ const query = this._prompt.textWithCurrentSuggestion(); this._prompt.clearAutocomplete(); - if (!query.length) + if (!query.length) { return; + } this._prompt.setEnabled(false); try { @@ -136,8 +141,9 @@ } this._appendViewQueryResult(trimmedQuery, view); - if (trimmedQuery.match(/^create /i) || trimmedQuery.match(/^drop table /i)) + if (trimmedQuery.match(/^create /i) || trimmedQuery.match(/^drop table /i)) { this.dispatchEventToListeners(Resources.DatabaseQueryView.Events.SchemaUpdated, this.database); + } } /** @@ -146,10 +152,11 @@ */ _appendViewQueryResult(query, view) { const resultElement = this._appendQueryResult(query); - if (view) + if (view) { view.show(resultElement); - else + } else { resultElement.remove(); + } this._promptElement.scrollIntoView(false); }
diff --git a/third_party/blink/renderer/devtools/front_end/resources/DatabaseTableView.js b/third_party/blink/renderer/devtools/front_end/resources/DatabaseTableView.js index b76d74c..056a3b6b 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/DatabaseTableView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/DatabaseTableView.js
@@ -88,8 +88,9 @@ this._dataGrid.autoSizeColumns(5); this._columnsMap = new Map(); - for (let i = 1; i < columnNames.length; ++i) + for (let i = 1; i < columnNames.length; ++i) { this._columnsMap.set(columnNames[i], String(i)); + } this._lastVisibleColumns = ''; const visibleColumnsText = this._visibleColumnsSetting.get()[this.tableName] || ''; this._visibleColumnsInput.setValue(visibleColumnsText); @@ -97,8 +98,9 @@ } _onVisibleColumnsChanged() { - if (!this._dataGrid) + if (!this._dataGrid) { return; + } const text = this._visibleColumnsInput.value(); const parts = text.split(/[\s,]+/); const matches = new Set(); @@ -113,11 +115,13 @@ } const newVisibleColumns = matches.valuesArray().sort().join(', '); if (newVisibleColumns.length === 0) { - for (const v of this._columnsMap.values()) + for (const v of this._columnsMap.values()) { columnsVisibility[v] = true; + } } - if (newVisibleColumns === this._lastVisibleColumns) + if (newVisibleColumns === this._lastVisibleColumns) { return; + } const visibleColumnsRegistry = this._visibleColumnsSetting.get(); visibleColumnsRegistry[this.tableName] = text; this._visibleColumnsSetting.set(visibleColumnsRegistry);
diff --git a/third_party/blink/renderer/devtools/front_end/resources/IndexedDBModel.js b/third_party/blink/renderer/devtools/front_end/resources/IndexedDBModel.js index 8a95859..52b4717 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/IndexedDBModel.js +++ b/third_party/blink/renderer/devtools/front_end/resources/IndexedDBModel.js
@@ -63,8 +63,9 @@ * }|undefined)} */ static keyFromIDBKey(idbKey) { - if (typeof(idbKey) === 'undefined' || idbKey === null) + if (typeof (idbKey) === 'undefined' || idbKey === null) { return undefined; + } let type; const key = {}; @@ -83,8 +84,9 @@ type = Resources.IndexedDBModel.KeyTypes.DateType; } else if (Array.isArray(idbKey)) { key.array = []; - for (let i = 0; i < idbKey.length; ++i) + for (let i = 0; i < idbKey.length; ++i) { key.array.push(Resources.IndexedDBModel.keyFromIDBKey(idbKey[i])); + } type = Resources.IndexedDBModel.KeyTypes.ArrayType; } break; @@ -133,16 +135,19 @@ * @return {?string} */ static keyPathStringFromIDBKeyPath(idbKeyPath) { - if (typeof idbKeyPath === 'string') + if (typeof idbKeyPath === 'string') { return '"' + idbKeyPath + '"'; - if (idbKeyPath instanceof Array) + } + if (idbKeyPath instanceof Array) { return '["' + idbKeyPath.join('", "') + '"]'; + } return null; } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._indexedDBAgent.enable(); this._securityOriginManager.addEventListener( @@ -150,8 +155,9 @@ this._securityOriginManager.addEventListener( SDK.SecurityOriginManager.Events.SecurityOriginRemoved, this._securityOriginRemoved, this); - for (const securityOrigin of this._securityOriginManager.securityOrigins()) + for (const securityOrigin of this._securityOriginManager.securityOrigins()) { this._addOrigin(securityOrigin); + } this._enabled = true; } @@ -160,8 +166,9 @@ * @param {string} origin */ clearForOrigin(origin) { - if (!this._enabled || !this._databaseNamesBySecurityOrigin[origin]) + if (!this._enabled || !this._databaseNamesBySecurityOrigin[origin]) { return; + } this._removeOrigin(origin); this._addOrigin(origin); @@ -171,15 +178,17 @@ * @param {!Resources.IndexedDBModel.DatabaseId} databaseId */ async deleteDatabase(databaseId) { - if (!this._enabled) + if (!this._enabled) { return; + } await this._indexedDBAgent.deleteDatabase(databaseId.securityOrigin, databaseId.name); this._loadDatabaseNames(databaseId.securityOrigin); } async refreshDatabaseNames() { - for (const securityOrigin in this._databaseNamesBySecurityOrigin) + for (const securityOrigin in this._databaseNamesBySecurityOrigin) { await this._loadDatabaseNames(securityOrigin); + } this.dispatchEventToListeners(Resources.IndexedDBModel.Events.DatabaseNamesRefreshed); } @@ -234,8 +243,9 @@ console.assert(!this._databaseNamesBySecurityOrigin[securityOrigin]); this._databaseNamesBySecurityOrigin[securityOrigin] = []; this._loadDatabaseNames(securityOrigin); - if (this._isValidSecurityOrigin(securityOrigin)) + if (this._isValidSecurityOrigin(securityOrigin)) { this._storageAgent.trackIndexedDBForOrigin(securityOrigin); + } } /** @@ -243,11 +253,13 @@ */ _removeOrigin(securityOrigin) { console.assert(this._databaseNamesBySecurityOrigin[securityOrigin]); - for (let i = 0; i < this._databaseNamesBySecurityOrigin[securityOrigin].length; ++i) + for (let i = 0; i < this._databaseNamesBySecurityOrigin[securityOrigin].length; ++i) { this._databaseRemoved(securityOrigin, this._databaseNamesBySecurityOrigin[securityOrigin][i]); + } delete this._databaseNamesBySecurityOrigin[securityOrigin]; - if (this._isValidSecurityOrigin(securityOrigin)) + if (this._isValidSecurityOrigin(securityOrigin)) { this._storageAgent.untrackIndexedDBForOrigin(securityOrigin); + } } /** @@ -270,12 +282,14 @@ this._databaseNamesBySecurityOrigin[securityOrigin] = databaseNames; for (const databaseName of oldDatabaseNames) { - if (!newDatabaseNames.has(databaseName)) + if (!newDatabaseNames.has(databaseName)) { this._databaseRemoved(securityOrigin, databaseName); + } } for (const databaseName of newDatabaseNames) { - if (!oldDatabaseNames.has(databaseName)) + if (!oldDatabaseNames.has(databaseName)) { this._databaseAdded(securityOrigin, databaseName); + } } } @@ -286,8 +300,9 @@ const result = []; for (const securityOrigin in this._databaseNamesBySecurityOrigin) { const databaseNames = this._databaseNamesBySecurityOrigin[securityOrigin]; - for (let i = 0; i < databaseNames.length; ++i) + for (let i = 0; i < databaseNames.length; ++i) { result.push(new Resources.IndexedDBModel.DatabaseId(securityOrigin, databaseNames[i])); + } } return result; } @@ -317,10 +332,12 @@ */ async _loadDatabaseNames(securityOrigin) { const databaseNames = await this._indexedDBAgent.requestDatabaseNames(securityOrigin); - if (!databaseNames) + if (!databaseNames) { return []; - if (!this._databaseNamesBySecurityOrigin[securityOrigin]) + } + if (!this._databaseNamesBySecurityOrigin[securityOrigin]) { return []; + } this._updateOriginDatabaseNames(securityOrigin, databaseNames); return databaseNames; } @@ -333,10 +350,12 @@ const databaseWithObjectStores = await this._indexedDBAgent.requestDatabase(databaseId.securityOrigin, databaseId.name); - if (!databaseWithObjectStores) + if (!databaseWithObjectStores) { return; - if (!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]) + } + if (!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]) { return; + } const databaseModel = new Resources.IndexedDBModel.Database(databaseId, databaseWithObjectStores.version); this._databases.set(databaseId, databaseModel); @@ -414,8 +433,9 @@ } const runtimeModel = this.target().model(SDK.RuntimeModel); - if (!runtimeModel || !this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]) + if (!runtimeModel || !this._databaseNamesBySecurityOrigin[databaseId.securityOrigin]) { return; + } const dataEntries = response.objectStoreDataEntries; const entries = []; for (const dataEntry of dataEntries) { @@ -451,8 +471,9 @@ */ async _refreshDatabaseList(securityOrigin) { const databaseNames = await this._loadDatabaseNames(securityOrigin); - for (const databaseName of databaseNames) + for (const databaseName of databaseNames) { this._loadDatabase(new Resources.IndexedDBModel.DatabaseId(securityOrigin, databaseName), false); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js b/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js index 02f383c..e0f5b9a 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js +++ b/third_party/blink/renderer/devtools/front_end/resources/IndexedDBViews.js
@@ -58,8 +58,9 @@ UI.createTextButton(ls`Refresh database`, () => this._refreshDatabaseButtonClicked(), ls`Refresh database`); footer.appendChild(this._refreshButton); - if (database) + if (database) { this.update(database); + } } _refreshDatabase() { @@ -89,8 +90,9 @@ async _deleteDatabase() { const ok = await UI.ConfirmDialog.show( Common.UIString('Please confirm delete of "%s" database.', this._database.databaseId.name), this.element); - if (ok) + if (ok) { this._model.deleteDatabase(this._database.databaseId); + } } }; @@ -173,15 +175,17 @@ _keyColumnHeaderFragment(prefix, keyPath) { const keyColumnHeaderFragment = createDocumentFragment(); keyColumnHeaderFragment.createTextChild(prefix); - if (keyPath === null) + if (keyPath === null) { return keyColumnHeaderFragment; + } keyColumnHeaderFragment.createTextChild(' (' + Common.UIString('Key path: ')); if (Array.isArray(keyPath)) { keyColumnHeaderFragment.createTextChild('['); for (let i = 0; i < keyPath.length; ++i) { - if (i !== 0) + if (i !== 0) { keyColumnHeaderFragment.createTextChild(', '); + } keyColumnHeaderFragment.appendChild(this._keyPathStringFragment(keyPath[i])); } keyColumnHeaderFragment.createTextChild(']'); @@ -260,8 +264,9 @@ this._objectStore = objectStore; this._index = index; - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.asWidget().detach(); + } this._dataGrid = this._createDataGrid(); this._dataGrid.asWidget().show(this.element); @@ -294,8 +299,9 @@ this._refreshButton.setEnabled(false); this._clearButton.setEnabled(!this._isIndex); - if (!force && this._lastKey === key && this._lastPageSize === pageSize && this._lastSkipCount === skipCount) + if (!force && this._lastKey === key && this._lastPageSize === pageSize && this._lastSkipCount === skipCount) { return; + } if (this._lastKey !== key || this._lastPageSize !== pageSize) { skipCount = 0; @@ -324,12 +330,14 @@ const node = new Resources.IDBDataGridNode(data); this._dataGrid.rootNode().appendChild(node); - if (data['number'] <= selected) + if (data['number'] <= selected) { selectedNode = node; + } } - if (selectedNode) + if (selectedNode) { selectedNode.select(); + } this._pageBackButton.setEnabled(!!skipCount); this._pageForwardButton.setEnabled(hasMore); this._needsRefresh.setVisible(false); @@ -353,11 +361,13 @@ * @param {?Resources.IndexedDBModel.ObjectStoreMetadata} metadata */ _updateSummaryBar(metadata) { - if (!this._summaryBarElement) + if (!this._summaryBarElement) { this._summaryBarElement = this.element.createChild('div', 'object-store-summary-bar'); + } this._summaryBarElement.removeChildren(); - if (!metadata) + if (!metadata) { return; + } const separator = '\u2002\u2758\u2002'; @@ -401,8 +411,9 @@ async _deleteButtonClicked(node) { if (!node) { node = this._dataGrid.selectedNode; - if (!node) + if (!node) { return; + } } const key = /** @type {!SDK.RemoteObject} */ (this._isIndex ? node.data.primaryKey : node.data.key); const keyValue = /** @type {!Array<?>|!Date|number|string} */ (key.value);
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ResourcesPanel.js b/third_party/blink/renderer/devtools/front_end/resources/ResourcesPanel.js index 9dd82a4b..a07c33b 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ResourcesPanel.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ResourcesPanel.js
@@ -77,8 +77,9 @@ } resetView() { - if (this.visibleView && Resources.ResourcesPanel._shouldCloseOnReset(this.visibleView)) + if (this.visibleView && Resources.ResourcesPanel._shouldCloseOnReset(this.visibleView)) { this.showView(null); + } } /** @@ -86,20 +87,24 @@ */ showView(view) { this._pendingViewPromise = null; - if (this.visibleView === view) + if (this.visibleView === view) { return; + } - if (this.visibleView) + if (this.visibleView) { this.visibleView.detach(); + } - if (view) + if (view) { view.show(this.storageViews); + } this.visibleView = view; this._storageViewToolbar.removeToolbarItems(); const toolbarItems = (view instanceof UI.SimpleView && view.syncToolbarItems()) || []; - for (let i = 0; i < toolbarItems.length; ++i) + for (let i = 0; i < toolbarItems.length; ++i) { this._storageViewToolbar.appendToolbarItem(toolbarItems[i]); + } this._storageViewToolbar.element.classList.toggle('hidden', !toolbarItems.length); } @@ -110,8 +115,9 @@ async scheduleShowView(viewPromise) { this._pendingViewPromise = viewPromise; const view = await viewPromise; - if (this._pendingViewPromise !== viewPromise) + if (this._pendingViewPromise !== viewPromise) { return null; + } this.showView(view); return view; } @@ -121,8 +127,9 @@ * @param {string|null} categoryLink */ showCategoryView(categoryName, categoryLink) { - if (!this._categoryView) + if (!this._categoryView) { this._categoryView = new Resources.StorageCategoryView(); + } this._categoryView.setText(categoryName); this._categoryView.setLink(categoryLink); this.showView(this._categoryView); @@ -132,13 +139,15 @@ * @param {!Resources.DOMStorage} domStorage */ showDOMStorage(domStorage) { - if (!domStorage) + if (!domStorage) { return; + } - if (!this._domStorageView) + if (!this._domStorageView) { this._domStorageView = new Resources.DOMStorageItemsView(domStorage); - else + } else { this._domStorageView.setStorage(domStorage); + } this.showView(this._domStorageView); } @@ -148,12 +157,14 @@ */ showCookies(cookieFrameTarget, cookieDomain) { const model = cookieFrameTarget.model(SDK.CookieModel); - if (!model) + if (!model) { return; - if (!this._cookieView) + } + if (!this._cookieView) { this._cookieView = new Resources.CookieItemsView(model, cookieDomain); - else + } else { this._cookieView.setCookiesDomain(model, cookieDomain); + } this.showView(this._cookieView); } @@ -163,11 +174,13 @@ */ clearCookies(target, cookieDomain) { const model = target.model(SDK.CookieModel); - if (!model) + if (!model) { return; + } model.clear(cookieDomain, () => { - if (this._cookieView) + if (this._cookieView) { this._cookieView.refreshItems(); + } }); } }; @@ -182,8 +195,9 @@ * @return {!Promise} */ async reveal(resource) { - if (!(resource instanceof SDK.Resource)) + if (!(resource instanceof SDK.Resource)) { return Promise.reject(new Error('Internal error: not a resource')); + } const sidebar = Resources.ResourcesPanel._instance()._sidebar; await UI.viewManager.showView('resources'); await sidebar.showResource(resource);
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ResourcesSection.js b/third_party/blink/renderer/devtools/front_end/resources/ResourcesSection.js index 40fe01a..9fcec54e 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ResourcesSection.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ResourcesSection.js
@@ -24,8 +24,9 @@ const mainTarget = SDK.targetManager.mainTarget(); const resourceTreeModel = mainTarget && mainTarget.model(SDK.ResourceTreeModel); const mainFrame = resourceTreeModel && resourceTreeModel.mainFrame; - if (mainFrame) + if (mainFrame) { this._frameAdded(mainFrame); + } } /** @@ -34,11 +35,13 @@ */ static _getParentFrame(frame) { const parentFrame = frame.parentFrame; - if (parentFrame) + if (parentFrame) { return parentFrame; + } const parentTarget = frame.resourceTreeModel().target().parentTarget(); - if (!parentTarget) + if (!parentTarget) { return null; + } return parentTarget.model(SDK.ResourceTreeModel).mainFrame; } @@ -47,14 +50,17 @@ * @return {boolean} */ _expandFrame(frame) { - if (!frame) + if (!frame) { return false; + } let treeElement = this._treeElementForFrameId.get(frame.id); - if (!treeElement && !this._expandFrame(Resources.ResourcesSection._getParentFrame(frame))) + if (!treeElement && !this._expandFrame(Resources.ResourcesSection._getParentFrame(frame))) { return false; + } treeElement = this._treeElementForFrameId.get(frame.id); - if (!treeElement) + if (!treeElement) { return false; + } treeElement.expand(); return true; } @@ -66,11 +72,13 @@ * @return {!Promise} */ async revealResource(resource, line, column) { - if (!this._expandFrame(resource.frame())) + if (!this._expandFrame(resource.frame())) { return; + } const resourceTreeElement = Resources.FrameResourceTreeElement.forResource(resource); - if (resourceTreeElement) + if (resourceTreeElement) { await resourceTreeElement.revealResource(line, column); + } } /** @@ -79,8 +87,9 @@ _frameAdded(frame) { const parentFrame = Resources.ResourcesSection._getParentFrame(frame); const parentTreeElement = parentFrame ? this._treeElementForFrameId.get(parentFrame.id) : this._treeElement; - if (!parentTreeElement) + if (!parentTreeElement) { return; + } const frameTreeElement = new Resources.FrameTreeElement(this, frame); this._treeElementForFrameId.set(frame.id, frameTreeElement); parentTreeElement.appendChild(frameTreeElement); @@ -91,12 +100,14 @@ */ _frameDetached(frame) { const frameTreeElement = this._treeElementForFrameId.get(frame.id); - if (!frameTreeElement) + if (!frameTreeElement) { return; + } this._treeElementForFrameId.remove(frame.id); - if (frameTreeElement.parent) + if (frameTreeElement.parent) { frameTreeElement.parent.removeChild(frameTreeElement); + } } /** @@ -104,8 +115,9 @@ */ _frameNavigated(frame) { const frameTreeElement = this._treeElementForFrameId.get(frame.id); - if (frameTreeElement) + if (frameTreeElement) { frameTreeElement.frameNavigated(frame); + } } /** @@ -190,11 +202,13 @@ * @param {!SDK.Resource} resource */ appendResource(resource) { - if (!this._populated) + if (!this._populated) { return; + } const statusCode = resource['statusCode']; - if (statusCode >= 301 && statusCode <= 303) + if (statusCode >= 301 && statusCode <= 303) { return; + } const resourceType = resource.resourceType(); const categoryName = resourceType.name(); @@ -224,18 +238,21 @@ * @param {!UI.TreeElement} treeElement */ appendChild(treeElement) { - if (!this._populated) + if (!this._populated) { return; + } this._insertInPresentationOrder(this, treeElement); } _insertInPresentationOrder(parentTreeElement, childTreeElement) { // Insert in the alphabetical order, first frames, then resources. Document resource goes last. function typeWeight(treeElement) { - if (treeElement instanceof Resources.StorageCategoryTreeElement) + if (treeElement instanceof Resources.StorageCategoryTreeElement) { return 2; - if (treeElement instanceof Resources.FrameTreeElement) + } + if (treeElement instanceof Resources.FrameTreeElement) { return 1; + } return 3; } @@ -244,20 +261,22 @@ const typeWeight2 = typeWeight(treeElement2); let result; - if (typeWeight1 > typeWeight2) + if (typeWeight1 > typeWeight2) { result = 1; - else if (typeWeight1 < typeWeight2) + } else if (typeWeight1 < typeWeight2) { result = -1; - else + } else { result = treeElement1.titleAsText().localeCompare(treeElement2.titleAsText()); + } return result; } const childCount = parentTreeElement.childCount(); let i; for (i = 0; i < childCount; ++i) { - if (compare(childTreeElement, parentTreeElement.childAt(i)) < 0) + if (compare(childTreeElement, parentTreeElement.childAt(i)) < 0) { break; + } } parentTreeElement.insertChild(childTreeElement, i); } @@ -268,10 +287,12 @@ */ async onpopulate() { this._populated = true; - for (const child of this._frame.childFrames) + for (const child of this._frame.childFrames) { this._section._frameAdded(child); - for (const resource of this._frame.resources()) + } + for (const resource of this._frame.resources()) { this.appendResource(resource); + } } }; @@ -311,12 +332,14 @@ * @return {!Promise<!UI.Widget>} */ _preparePreview() { - if (this._previewPromise) + if (this._previewPromise) { return this._previewPromise; + } const viewPromise = SourceFrame.PreviewFactory.createPreview(this._resource, this._resource.mimeType); this._previewPromise = viewPromise.then(view => { - if (view) + if (view) { return view; + } return new UI.EmptyWidget(this._resource.url); }); return this._previewPromise; @@ -374,8 +397,9 @@ async revealResource(line, column) { this.revealAndSelect(true); const view = await this._panel.scheduleShowView(this._preparePreview()); - if (!(view instanceof SourceFrame.ResourceSourceFrame) || typeof line !== 'number') + if (!(view instanceof SourceFrame.ResourceSourceFrame) || typeof line !== 'number') { return; + } view.revealPosition(line, column, true); } };
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js index 89fb6e9..528ee2a 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkerCacheViews.js
@@ -76,8 +76,9 @@ } _resetDataGrid() { - if (this._dataGrid) + if (this._dataGrid) { this._dataGrid.asWidget().detach(); + } this._dataGrid = this._createDataGrid(); const dataGridWidget = this._dataGrid.asWidget(); this._splitWidget.setSidebarWidget(dataGridWidget); @@ -106,12 +107,15 @@ * @param {?UI.Widget} preview */ _showPreview(preview) { - if (preview && this._preview === preview) + if (preview && this._preview === preview) { return; - if (this._preview) + } + if (this._preview) { this._preview.detach(); - if (!preview) + } + if (!preview) { preview = new UI.EmptyWidget(Common.UIString('Select a cache entry above to preview')); + } this._preview = preview; this._preview.show(this._previewPanel.element); } @@ -152,22 +156,24 @@ } _sortingChanged() { - if (!this._dataGrid) + if (!this._dataGrid) { return; + } const accending = this._dataGrid.isSortOrderAscending(); const columnId = this._dataGrid.sortColumnId(); let comparator; - if (columnId === 'name') + if (columnId === 'name') { comparator = (a, b) => a._name.localeCompare(b._name); - else if (columnId === 'contentType') + } else if (columnId === 'contentType') { comparator = (a, b) => a.data.mimeType.localeCompare(b.data.mimeType); - else if (columnId === 'contentLength') + } else if (columnId === 'contentLength') { comparator = (a, b) => a.data.resourceSize - b.data.resourceSize; - else if (columnId === 'responseTime') + } else if (columnId === 'responseTime') { comparator = (a, b) => a.data.endTime - b.data.endTime; - else if (columnId === 'responseType') + } else if (columnId === 'responseType') { comparator = (a, b) => a._responseType.localeCompare(b._responseType); + } const children = this._dataGrid.rootNode().children.slice(); this._dataGrid.rootNode().removeChildren(); @@ -200,8 +206,9 @@ async _deleteButtonClicked(node) { if (!node) { node = this._dataGrid && this._dataGrid.selectedNode; - if (!node) + if (!node) { return; + } } await this._model.deleteCacheEntry(this._cache, /** @type {string} */ (node.data.url())); node.remove(); @@ -217,15 +224,17 @@ } _updateSummaryBar() { - if (!this._summaryBarElement) + if (!this._summaryBarElement) { this._summaryBarElement = this.element.createChild('div', 'cache-storage-summary-bar'); + } this._summaryBarElement.removeChildren(); const span = this._summaryBarElement.createChild('span'); - if (this._entryPathFilter) + if (this._entryPathFilter) { span.textContent = ls`Matching entries: ${this._returnCount}`; - else + } else { span.textContent = ls`Total entries: ${this._returnCount}`; + } } /** @@ -245,8 +254,9 @@ /** @type {!Map<string, !DataGrid.DataGridNode>} */ const oldEntries = new Map(); const rootNode = this._dataGrid.rootNode(); - for (const node of rootNode.children) + for (const node of rootNode.children) { oldEntries.set(node.data.url, node); + } rootNode.removeChildren(); let selectedNode = null; for (let i = 0; i < entries.length; ++i) { @@ -260,15 +270,17 @@ node.data.number = i + this._skipCount; } rootNode.appendChild(node); - if (entry.requestURL === selected) + if (entry.requestURL === selected) { selectedNode = node; + } } this._pageBackButton.setEnabled(!!skipCount); this._pageForwardButton.setEnabled(hasMore); - if (!selectedNode) + if (!selectedNode) { this._showPreview(null); - else + } else { selectedNode.revealAndSelect(); + } this._updatedForTest(); } @@ -279,8 +291,9 @@ const pageSize = this._pageSize; let skipCount = this._skipCount; - if (!force && this._lastPageSize === pageSize && this._lastSkipCount === skipCount) + if (!force && this._lastPageSize === pageSize && this._lastSkipCount === skipCount) { return; + } this._refreshButton.setEnabled(false); if (this._lastPageSize !== pageSize) { skipCount = 0; @@ -309,8 +322,9 @@ */ _cacheContentUpdated(event) { const nameAndOrigin = event.data; - if (this._cache.securityOrigin !== nameAndOrigin.origin || this._cache.cacheName !== nameAndOrigin.cacheName) + if (this._cache.securityOrigin !== nameAndOrigin.origin || this._cache.cacheName !== nameAndOrigin.cacheName) { return; + } this._refreshThrottler.schedule(() => Promise.resolve(this._updateData(true)), true); } @@ -325,8 +339,9 @@ } // It is possible that table selection changes before the preview opens. - if (request === this._dataGrid.selectedNode.data) + if (request === this._dataGrid.selectedNode.data) { this._showPreview(preview); + } } /** @@ -352,8 +367,9 @@ request.resourceSize = (header && header.value) | 0; let resourceType = Common.ResourceType.fromMimeType(contentType); - if (!resourceType) + if (!resourceType) { resourceType = Common.ResourceType.fromURL(entry.requestURL) || Common.resourceTypes.Other; + } request.setResourceType(resourceType); request.setContentDataProvider(this._requestContent.bind(this, request)); return request; @@ -367,8 +383,9 @@ const isText = request.resourceType().isTextType(); const contentData = {error: null, content: null, encoded: !isText}; const response = await this._cache.requestCachedResponse(request.url(), request.requestHeaders()); - if (response) + if (response) { contentData.content = isText ? window.atob(response.body) : response.body; + } return contentData; } @@ -390,10 +407,11 @@ super(request); this._number = number; const parsed = new Common.ParsedURL(request.url()); - if (parsed.isValid) + if (parsed.isValid) { this._name = request.url().trimURL(parsed.domain()); - else + } else { this._name = request.url(); + } this._request = request; this._responseType = responseType; } @@ -411,12 +429,13 @@ } else if (columnId === 'name') { value = this._name; } else if (columnId === 'responseType') { - if (this._responseType === 'opaqueResponse') + if (this._responseType === 'opaqueResponse') { value = 'opaque'; - else if (this._responseType === 'opaqueRedirect') + } else if (this._responseType === 'opaqueRedirect') { value = 'opaqueredirect'; - else + } else { value = this._responseType; + } } else if (columnId === 'contentType') { value = this._request.mimeType; } else if (columnId === 'contentLength') { @@ -458,15 +477,18 @@ * @param {string=} tabId */ _selectTab(tabId) { - if (!tabId) + if (!tabId) { tabId = this._resourceViewTabSetting.get(); - if (!this._tabbedPane.selectTab(tabId)) + } + if (!this._tabbedPane.selectTab(tabId)) { this._tabbedPane.selectTab('headers'); + } } _tabSelected(event) { - if (!event.data.isUserGesture) + if (!event.data.isUserGesture) { return; + } this._resourceViewTabSetting.set(event.data.tabId); } };
diff --git a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js index 351e1d39..db9e13a 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/ServiceWorkersView.js
@@ -38,8 +38,9 @@ const filterLabel = this._otherSWFilter.createChild('label', 'service-worker-filter-label'); filterLabel.textContent = Common.UIString('Service workers from other origins'); self.onInvokeElement(this._otherSWFilter, event => { - if (event.target === this._otherSWFilter || event.target === filterLabel) + if (event.target === this._otherSWFilter || event.target === filterLabel) { this._toggleFilter(); + } }); const toolbar = new UI.Toolbar('service-worker-filter-toolbar', this._otherSWFilter); @@ -77,13 +78,15 @@ * @param {!SDK.ServiceWorkerManager} serviceWorkerManager */ modelAdded(serviceWorkerManager) { - if (this._manager) + if (this._manager) { return; + } this._manager = serviceWorkerManager; this._securityOriginManager = serviceWorkerManager.target().model(SDK.SecurityOriginManager); - for (const registration of this._manager.registrations().values()) + for (const registration of this._manager.registrations().values()) { this._updateRegistration(registration); + } this._eventListeners.set(serviceWorkerManager, [ this._manager.addEventListener( @@ -102,8 +105,9 @@ * @param {!SDK.ServiceWorkerManager} serviceWorkerManager */ modelRemoved(serviceWorkerManager) { - if (!this._manager || this._manager !== serviceWorkerManager) + if (!this._manager || this._manager !== serviceWorkerManager) { return; + } Common.EventTarget.removeEventListeners(this._eventListeners.get(serviceWorkerManager)); this._eventListeners.delete(serviceWorkerManager); @@ -126,14 +130,15 @@ const waiting = versions.get(SDK.ServiceWorkerVersion.Modes.Waiting); const redundant = versions.get(SDK.ServiceWorkerVersion.Modes.Redundant); - if (active) + if (active) { timestamp = active.scriptResponseTime; - else if (waiting) + } else if (waiting) { timestamp = waiting.scriptResponseTime; - else if (installing) + } else if (installing) { timestamp = installing.scriptResponseTime; - else if (redundant) + } else if (redundant) { timestamp = redundant.scriptResponseTime; + } return timestamp; } @@ -146,8 +151,9 @@ const expectedView = this._getReportViewForOrigin(section._registration.securityOrigin); hasOthers |= expectedView === this._otherWorkersView; hasThis |= expectedView === this._currentWorkersView; - if (section._section.parentWidget() !== expectedView) + if (section._section.parentWidget() !== expectedView) { movedSections.push(section); + } } for (const section of movedSections) { @@ -170,10 +176,11 @@ }); for (const section of this._sections.values()) { if (section._section.parentWidget() === this._currentWorkersView || - this._isRegistrationVisible(section._registration)) + this._isRegistrationVisible(section._registration)) { section._section.showWidget(); - else + } else { section._section.hideWidget(); + } } this.contentElement.classList.toggle('service-worker-has-current', !!hasThis); this._otherWorkers.classList.toggle('hidden', !hasOthers); @@ -193,21 +200,24 @@ let hasNonDeletedRegistrations = false; const securityOrigins = new Set(this._securityOriginManager.securityOrigins()); for (const registration of this._manager.registrations().values()) { - if (!securityOrigins.has(registration.securityOrigin) && !this._isRegistrationVisible(registration)) + if (!securityOrigins.has(registration.securityOrigin) && !this._isRegistrationVisible(registration)) { continue; + } if (!registration.canBeRemoved()) { hasNonDeletedRegistrations = true; break; } } - if (!hasNonDeletedRegistrations) + if (!hasNonDeletedRegistrations) { return; + } for (const registration of this._manager.registrations().values()) { const visible = securityOrigins.has(registration.securityOrigin) || this._isRegistrationVisible(registration); - if (!visible && registration.canBeRemoved()) + if (!visible && registration.canBeRemoved()) { this._removeRegistrationFromList(registration); + } } } @@ -217,10 +227,11 @@ */ _getReportViewForOrigin(origin) { if (this._securityOriginManager.securityOrigins().includes(origin) || - this._securityOriginManager.unreachableMainSecurityOrigin() === origin) + this._securityOriginManager.unreachableMainSecurityOrigin() === origin) { return this._currentWorkersView; - else + } else { return this._otherWorkersView; + } } /** @@ -237,8 +248,9 @@ /** @type {!SDK.ServiceWorkerManager} */ (this._manager), uiSection, registration); this._sections.set(registration, section); } - if (skipUpdate) + if (skipUpdate) { return; + } this._updateSectionVisibility(); section._scheduleUpdate(); } @@ -256,8 +268,9 @@ */ _removeRegistrationFromList(registration) { const section = this._sections.get(registration); - if (section) + if (section) { section._section.detach(); + } this._sections.delete(registration); this._updateSectionVisibility(); } @@ -268,8 +281,9 @@ */ _isRegistrationVisible(registration) { const filterString = this._filter.value(); - if (!filterString || !registration.scopeURL) + if (!filterString || !registration.scopeURL) { return true; + } const regex = String.filterRegex(filterString); return registration.scopeURL.match(regex); @@ -283,10 +297,11 @@ _updateCollapsedStyle() { const expanded = this._otherSWFilter.getAttribute('aria-checked') === 'true'; this._otherWorkers.classList.toggle('service-worker-filter-collapsed', !expanded); - if (expanded) + if (expanded) { this._otherWorkersView.showWidget(); - else + } else { this._otherWorkersView.hideWidget(); + } this._otherWorkersView.setHeaderVisible(false); } @@ -388,8 +403,9 @@ */ _targetForVersionId(versionId) { const version = this._manager.findVersion(versionId); - if (!version || !version.targetId) + if (!version || !version.targetId) { return null; + } return SDK.targetManager.targetById(version.targetId); } @@ -449,8 +465,9 @@ */ _update() { const fingerprint = this._registration.fingerprint(); - if (fingerprint === this._fingerprint) + if (fingerprint === this._fingerprint) { return Promise.resolve(); + } this._fingerprint = fingerprint; this._toolbar.setEnabled(!this._registration.isDeleted); @@ -477,8 +494,9 @@ if (active.isRunning() || active.isStarting()) { this._createLink(activeEntry, Common.UIString('stop'), this._stopButtonClicked.bind(this, active.id)); - if (!this._targetForVersionId(active.id)) + if (!this._targetForVersionId(active.id)) { this._createLink(activeEntry, Common.UIString('inspect'), this._inspectButtonClicked.bind(this, active.id)); + } } else if (active.isStartable()) { this._createLink(activeEntry, Common.UIString('start'), this._startButtonClicked.bind(this)); } @@ -496,8 +514,9 @@ this._createLink(waitingEntry, Common.UIString('skipWaiting'), this._skipButtonClicked.bind(this)); waitingEntry.createChild('div', 'service-worker-subtitle').textContent = Common.UIString('Received %s', new Date(waiting.scriptResponseTime * 1000).toLocaleString()); - if (!this._targetForVersionId(waiting.id) && (waiting.isRunning() || waiting.isStarting())) + if (!this._targetForVersionId(waiting.id) && (waiting.isRunning() || waiting.isStarting())) { this._createLink(waitingEntry, Common.UIString('inspect'), this._inspectButtonClicked.bind(this, waiting.id)); + } } if (installing) { const installingEntry = this._addVersion( @@ -572,8 +591,9 @@ * @param {?Protocol.Target.TargetInfo} targetInfo */ _onClientInfo(element, targetInfo) { - if (!targetInfo) + if (!targetInfo) { return; + } this._clientInfoCache.set(targetInfo.targetId, targetInfo); this._updateClientInfo(element, targetInfo); }
diff --git a/third_party/blink/renderer/devtools/front_end/resources/StorageItemsView.js b/third_party/blink/renderer/devtools/front_end/resources/StorageItemsView.js index 635cd24b..1e5fb3e 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/StorageItemsView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/StorageItemsView.js
@@ -26,9 +26,9 @@ const toolbarItems = [this._refreshButton, this._filterItem, toolbarSeparator, this._deleteAllButton, this._deleteSelectedButton]; - for (const item of toolbarItems) + for (const item of toolbarItems) { this._mainToolbar.appendToolbarItem(item); - + } } /** @@ -59,8 +59,9 @@ * @protected */ filter(items, keyFunction) { - if (!this._filterRegex) + if (!this._filterRegex) { return items; + } return items.filter(item => this._filterRegex.test(keyFunction(item))); }
diff --git a/third_party/blink/renderer/devtools/front_end/screencast/InputModel.js b/third_party/blink/renderer/devtools/front_end/screencast/InputModel.js index e4d674c..4b6b28d 100644 --- a/third_party/blink/renderer/devtools/front_end/screencast/InputModel.js +++ b/third_party/blink/renderer/devtools/front_end/screencast/InputModel.js
@@ -63,13 +63,16 @@ 'mousemove': 'mouseMoved', 'mousewheel': 'mouseWheel' }; - if (!(event.type in types) || !(event.which in buttons)) + if (!(event.type in types) || !(event.which in buttons)) { return; - if (event.type !== 'mousewheel' && buttons[event.which] === 'none') + } + if (event.type !== 'mousewheel' && buttons[event.which] === 'none') { return; + } - if (event.type === 'mousedown' || this._activeTouchOffsetTop === null) + if (event.type === 'mousedown' || this._activeTouchOffsetTop === null) { this._activeTouchOffsetTop = offsetTop; + } const x = Math.round(event.offsetX / zoom); let y = Math.round(event.offsetY / zoom); @@ -88,8 +91,9 @@ } else { this._activeTouchParams = params; } - if (event.type === 'mouseup') + if (event.type === 'mouseup') { this._activeTouchOffsetTop = null; + } this._inputAgent.invoke_emulateTouchFromMouseEvent(params); }
diff --git a/third_party/blink/renderer/devtools/front_end/screencast/ScreencastApp.js b/third_party/blink/renderer/devtools/front_end/screencast/ScreencastApp.js index c65f7feb..725641b 100644 --- a/third_party/blink/renderer/devtools/front_end/screencast/ScreencastApp.js +++ b/third_party/blink/renderer/devtools/front_end/screencast/ScreencastApp.js
@@ -20,8 +20,9 @@ * @return {!Screencast.ScreencastApp} */ static _instance() { - if (!Screencast.ScreencastApp._appInstance) + if (!Screencast.ScreencastApp._appInstance) { Screencast.ScreencastApp._appInstance = new Screencast.ScreencastApp(); + } return Screencast.ScreencastApp._appInstance; } @@ -48,8 +49,9 @@ * @param {!SDK.ScreenCaptureModel} screenCaptureModel */ modelAdded(screenCaptureModel) { - if (this._screenCaptureModel) + if (this._screenCaptureModel) { return; + } this._screenCaptureModel = screenCaptureModel; this._toggleButton.setEnabled(true); this._screencastView = new Screencast.ScreencastView(screenCaptureModel); @@ -63,8 +65,9 @@ * @param {!SDK.ScreenCaptureModel} screenCaptureModel */ modelRemoved(screenCaptureModel) { - if (this._screenCaptureModel !== screenCaptureModel) + if (this._screenCaptureModel !== screenCaptureModel) { return; + } delete this._screenCaptureModel; this._toggleButton.setEnabled(false); this._screencastView.detach(); @@ -79,14 +82,16 @@ } _onScreencastEnabledChanged() { - if (!this._rootSplitWidget) + if (!this._rootSplitWidget) { return; + } const enabled = this._enabledSetting.get() && this._screencastView; this._toggleButton.setToggled(enabled); - if (enabled) + if (enabled) { this._rootSplitWidget.showBoth(); - else + } else { this._rootSplitWidget.hideMain(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/screencast/ScreencastView.js b/third_party/blink/renderer/devtools/front_end/screencast/ScreencastView.js index 6378f85..b1639675 100644 --- a/third_party/blink/renderer/devtools/front_end/screencast/ScreencastView.js +++ b/third_party/blink/renderer/devtools/front_end/screencast/ScreencastView.js
@@ -111,10 +111,12 @@ } _startCasting() { - if (SDK.targetManager.allTargetsSuspended()) + if (SDK.targetManager.allTargetsSuspended()) { return; - if (this._isCasting) + } + if (this._isCasting) { return; + } this._isCasting = true; const maxImageDimension = 2048; @@ -130,21 +132,26 @@ 'jpeg', 80, Math.floor(Math.min(maxImageDimension, dimensions.width)), Math.floor(Math.min(maxImageDimension, dimensions.height)), undefined, this._screencastFrame.bind(this), this._screencastVisibilityChanged.bind(this)); - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.overrideEmulateTouch(true); - if (this._overlayModel) + } + if (this._overlayModel) { this._overlayModel.setHighlighter(this); + } } _stopCasting() { - if (!this._isCasting) + if (!this._isCasting) { return; + } this._isCasting = false; this._screenCaptureModel.stopScreencast(); - for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel)) { emulationModel.overrideEmulateTouch(false); - if (this._overlayModel) + } + if (this._overlayModel) { this._overlayModel.setHighlighter(null); + } } /** @@ -166,8 +173,9 @@ dimensionsCSS.height / (this._imageElement.naturalWidth * deviceSizeRatio)); this._viewportElement.classList.remove('hidden'); const bordersSize = Screencast.ScreencastView._bordersSize; - if (this._imageZoom < 1.01 / window.devicePixelRatio) + if (this._imageZoom < 1.01 / window.devicePixelRatio) { this._imageZoom = 1 / window.devicePixelRatio; + } this._screenZoom = this._imageElement.naturalWidth * this._imageZoom / metadata.deviceWidth; this._viewportElement.style.width = metadata.deviceWidth * this._screenZoom + bordersSize + 'px'; this._viewportElement.style.height = metadata.deviceHeight * this._screenZoom + bordersSize + 'px'; @@ -193,10 +201,11 @@ * @param {!Common.Event} event */ _onSuspendStateChange(event) { - if (SDK.targetManager.allTargetsSuspended()) + if (SDK.targetManager.allTargetsSuspended()) { this._stopCasting(); - else + } else { this._startCasting(); + } this._updateGlasspane(); } @@ -221,15 +230,18 @@ return; } - if (!this._pageScaleFactor || !this._domModel) + if (!this._pageScaleFactor || !this._domModel) { return; + } if (!this._inspectModeConfig || event.type === 'mousewheel') { - if (this._inputModel) + if (this._inputModel) { this._inputModel.emitTouchFromMouseEvent(event, this._screenOffsetTop, this._screenZoom); + } event.preventDefault(); - if (event.type === 'mousedown') + if (event.type === 'mousedown') { this._canvasElement.focus(); + } return; } @@ -240,8 +252,9 @@ Math.floor(position.y / this._pageScaleFactor + this._scrollOffsetY), Common.moduleSetting('showUAShadowDOM').get()); - if (!node) + if (!node) { return; + } if (event.type === 'mousemove') { this.highlightInOverlay({node}, this._inspectModeConfig); this._domModel.overlayModel().nodeHighlightRequested(node.id); @@ -266,8 +279,9 @@ return; } - if (this._inputModel) + if (this._inputModel) { this._inputModel.emitKeyEvent(event); + } event.consume(); this._canvasElement.focus(); } @@ -283,8 +297,9 @@ * @param {!Event} event */ _handleBlurEvent(event) { - if (this._inputModel) + if (this._inputModel) { this._inputModel.cancelTouch(); + } } /** @@ -327,12 +342,14 @@ async _highlightInOverlay(data, config) { const {node: n, deferredNode, object} = data; let node = n; - if (!node && deferredNode) + if (!node && deferredNode) { node = await deferredNode.resolvePromise(); + } if (!node && object) { const domModel = object.runtimeModel().target().model(SDK.DOMModel); - if (domModel) + if (domModel) { node = await domModel.pushObjectAsNodeToFrontend(object); + } } this._highlightNode = node; @@ -406,19 +423,25 @@ this._context.save(); const transparentColor = 'rgba(0, 0, 0, 0)'; const quads = []; - if (model.content && config.contentColor !== transparentColor) + if (model.content && config.contentColor !== transparentColor) { quads.push({quad: model.content, color: config.contentColor}); - if (model.padding && config.paddingColor !== transparentColor) + } + if (model.padding && config.paddingColor !== transparentColor) { quads.push({quad: model.padding, color: config.paddingColor}); - if (model.border && config.borderColor !== transparentColor) + } + if (model.border && config.borderColor !== transparentColor) { quads.push({quad: model.border, color: config.borderColor}); - if (model.margin && config.marginColor !== transparentColor) + } + if (model.margin && config.marginColor !== transparentColor) { quads.push({quad: model.margin, color: config.marginColor}); + } - for (let i = quads.length - 1; i > 0; --i) + for (let i = quads.length - 1; i > 0; --i) { this._drawOutlinedQuadWithClip(quads[i].quad, quads[i - 1].quad, quads[i].color); - if (quads.length > 0) + } + if (quads.length > 0) { this._drawOutlinedQuad(quads[0].quad, quads[0].color); + } this._context.restore(); this._drawElementTitle(); @@ -437,8 +460,9 @@ * @return {string} */ _cssColor(color) { - if (!color) + if (!color) { return 'transparent'; + } return Common.Color.fromRGBA([color.r, color.g, color.b, color.a]).asString(Common.Color.Format.RGBA) || ''; } @@ -486,8 +510,9 @@ } _drawElementTitle() { - if (!this._node) + if (!this._node) { return; + } const canvasWidth = this._canvasElement.getBoundingClientRect().width; const canvasHeight = this._canvasElement.getBoundingClientRect().height; @@ -497,8 +522,9 @@ this._nodeIdElement.textContent = this._node.getAttribute('id') ? '#' + this._node.getAttribute('id') : ''; this._nodeIdElement.textContent = this._node.getAttribute('id') ? '#' + this._node.getAttribute('id') : ''; let className = this._node.getAttribute('class'); - if (className && className.length > 50) + if (className && className.length > 50) { className = className.substring(0, 50) + '\u2026'; + } this._classNameElement.textContent = className || ''; this._nodeWidthElement.textContent = this._model.width; this._nodeHeightElement.textContent = this._model.height; @@ -515,8 +541,9 @@ let renderArrowDown = false; let boxX = Math.max(2, this._model.margin[0]); - if (boxX + titleWidth > canvasWidth) + if (boxX + titleWidth > canvasWidth) { boxX = canvasWidth - titleWidth - 2; + } let boxY; if (anchorTop > canvasHeight) { @@ -643,8 +670,9 @@ */ _navigateToHistoryEntry(offset) { const newIndex = this._historyIndex + offset; - if (newIndex < 0 || newIndex >= this._historyEntries.length) + if (newIndex < 0 || newIndex >= this._historyEntries.length) { return; + } this._resourceTreeModel.navigateToHistoryEntry(this._historyEntries[newIndex]); this._requestNavigationHistory(); } @@ -657,21 +685,25 @@ * @param {!Event} event */ _navigationUrlKeyUp(event) { - if (event.key !== 'Enter') + if (event.key !== 'Enter') { return; + } let url = this._navigationUrl.value; - if (!url) + if (!url) { return; - if (!url.match(Screencast.ScreencastView._SchemeRegex)) + } + if (!url.match(Screencast.ScreencastView._SchemeRegex)) { url = 'http://' + url; + } this._resourceTreeModel.navigate(url); this._canvasElement.focus(); } async _requestNavigationHistory() { const history = await this._resourceTreeModel.navigationHistory(); - if (!history) + if (!history) { return; + } this._historyIndex = history.currentIndex; this._historyEntries = history.entries; @@ -681,8 +713,9 @@ let url = this._historyEntries[this._historyIndex].url; const match = url.match(Screencast.ScreencastView._HttpRegex); - if (match) + if (match) { url = match[1]; + } InspectorFrontendHost.inspectedURLChanged(url); this._navigationUrl.value = url; } @@ -736,8 +769,9 @@ delete this._requestIds; this._updateProgress(1); // Display 100% progress on load, hide it in 0.5s. setTimeout(function() { - if (!this._navigationProgressVisible()) + if (!this._navigationProgressVisible()) { this._displayProgress(0); + } }.bind(this), 500); } @@ -746,22 +780,26 @@ } _onRequestStarted(event) { - if (!this._navigationProgressVisible()) + if (!this._navigationProgressVisible()) { return; + } const request = /** @type {!SDK.NetworkRequest} */ (event.data); // Ignore long-living WebSockets for the sake of progress indicator, as we won't be waiting them anyway. - if (request.type === Common.resourceTypes.WebSocket) + if (request.type === Common.resourceTypes.WebSocket) { return; + } this._requestIds[request.requestId()] = request; ++this._startedRequests; } _onRequestFinished(event) { - if (!this._navigationProgressVisible()) + if (!this._navigationProgressVisible()) { return; + } const request = /** @type {!SDK.NetworkRequest} */ (event.data); - if (!(request.requestId() in this._requestIds)) + if (!(request.requestId() in this._requestIds)) { return; + } ++this._finishedRequests; setTimeout(function() { this._updateProgress( @@ -770,10 +808,12 @@ } _updateProgress(progress) { - if (!this._navigationProgressVisible()) + if (!this._navigationProgressVisible()) { return; - if (this._maxDisplayedProgress >= progress) + } + if (this._maxDisplayedProgress >= progress) { return; + } this._maxDisplayedProgress = progress; this._displayProgress(progress); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CPUProfileDataModel.js b/third_party/blink/renderer/devtools/front_end/sdk/CPUProfileDataModel.js index 98d78b85..bf1e624 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CPUProfileDataModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CPUProfileDataModel.js
@@ -68,8 +68,9 @@ * @param {!Protocol.Profiler.Profile} profile */ _compatibilityConversionHeadToNodes(profile) { - if (!profile.head || profile.nodes) + if (!profile.head || profile.nodes) { return; + } /** @type {!Array<!Protocol.Profiler.ProfileNode>} */ const nodes = []; convertNodesTree(profile.head); @@ -91,8 +92,9 @@ * @return {?Array<number>} */ _convertTimeDeltas(profile) { - if (!profile.timeDeltas) + if (!profile.timeDeltas) { return null; + } let lastTimeUsec = profile.startTime; const timestamps = new Array(profile.timeDeltas.length); for (let i = 0; i < profile.timeDeltas.length; ++i) { @@ -112,8 +114,9 @@ * @return {boolean} */ function isNativeNode(node) { - if (node.callFrame) + if (node.callFrame) { return !!node.callFrame.url && node.callFrame.url.startsWith('native '); + } return !!node['url'] && node['url'].startsWith('native '); } @@ -121,16 +124,18 @@ * @param {!Array<!Protocol.Profiler.ProfileNode>} nodes */ function buildChildrenFromParents(nodes) { - if (nodes[0].children) + if (nodes[0].children) { return; + } nodes[0].children = []; for (let i = 1; i < nodes.length; ++i) { const node = nodes[i]; const parentNode = nodeByIdMap.get(node.parent); - if (parentNode.children) + if (parentNode.children) { parentNode.children.push(node.id); - else + } else { parentNode.children = [node.id]; + } } } @@ -139,13 +144,16 @@ * @param {!Array<number>|undefined} samples */ function buildHitCountFromSamples(nodes, samples) { - if (typeof(nodes[0].hitCount) === 'number') + if (typeof (nodes[0].hitCount) === 'number') { return; + } console.assert(samples, 'Error: Neither hitCount nor samples are present in profile.'); - for (let i = 0; i < nodes.length; ++i) + for (let i = 0; i < nodes.length; ++i) { nodes[i].hitCount = 0; - for (let i = 0; i < samples.length; ++i) + } + for (let i = 0; i < samples.length; ++i) { ++nodeByIdMap.get(samples[i]).hitCount; + } } /** @type {!Map<number, !Protocol.Profiler.ProfileNode>} */ @@ -169,8 +177,9 @@ while (sourceNodeStack.length) { let parentNode = parentNodeStack.pop(); const sourceNode = sourceNodeStack.pop(); - if (!sourceNode.children) + if (!sourceNode.children) { sourceNode.children = []; + } const targetNode = new SDK.CPUProfileNode(sourceNode, sampleTime); if (keepNatives || !isNativeNode(sourceNode)) { parentNode.children.push(targetNode); @@ -182,22 +191,25 @@ parentNodeStack.push.apply(parentNodeStack, sourceNode.children.map(() => parentNode)); sourceNodeStack.push.apply(sourceNodeStack, sourceNode.children.map(id => nodeByIdMap.get(id))); } - if (this.samples) + if (this.samples) { this.samples = this.samples.map(id => idMap.get(id)); + } return resultRoot; } _sortSamples() { const timestamps = this.timestamps; - if (!timestamps) + if (!timestamps) { return; + } const samples = this.samples; const indices = timestamps.map((x, index) => index); indices.sort((a, b) => timestamps[a] - timestamps[b]); for (let i = 0; i < timestamps.length; ++i) { let index = indices[i]; - if (index === i) + if (index === i) { continue; + } // Move items in a cycle. const savedTimestamp = timestamps[i]; const savedSample = samples[i]; @@ -222,15 +234,17 @@ const profileStartTime = this.profileStartTime; const interval = (this.profileEndTime - profileStartTime) / this.samples.length; timestamps = new Float64Array(this.samples.length + 1); - for (let i = 0; i < timestamps.length; ++i) + for (let i = 0; i < timestamps.length; ++i) { timestamps[i] = profileStartTime + i * interval; + } this.timestamps = timestamps; return; } // Convert samples from usec to msec - for (let i = 0; i < timestamps.length; ++i) + for (let i = 0; i < timestamps.length; ++i) { timestamps[i] /= 1000; + } if (this.samples.length === timestamps.length) { // Support for a legacy format where were no timeDeltas. // Add an extra timestamp used to calculate the last sample duration. @@ -257,12 +271,13 @@ const topLevelNodes = this.profileHead.children; for (let i = 0; i < topLevelNodes.length && !(this.gcNode && this.programNode && this.idleNode); i++) { const node = topLevelNodes[i]; - if (node.functionName === '(garbage collector)') + if (node.functionName === '(garbage collector)') { this.gcNode = node; - else if (node.functionName === '(program)') + } else if (node.functionName === '(program)') { this.programNode = node; - else if (node.functionName === '(idle)') + } else if (node.functionName === '(idle)') { this.idleNode = node; + } } } @@ -275,8 +290,9 @@ // with the preceeding sample. const samples = this.samples; const samplesCount = samples.length; - if (!this.programNode || samplesCount < 3) + if (!this.programNode || samplesCount < 3) { return; + } const idToNode = this._idToNode; const programNodeId = this.programNode.id; const gcNodeId = this.gcNode ? this.gcNode.id : -1; @@ -294,15 +310,17 @@ prevNodeId = nodeId; nodeId = nextNodeId; } - if (count) + if (count) { Common.console.warn(ls`DevTools: CPU profile parser is fixing ${count} missing samples.`); + } /** * @param {!SDK.ProfileNode} node * @return {!SDK.ProfileNode} */ function bottomNode(node) { - while (node.parent && node.parent.parent) + while (node.parent && node.parent.parent) { node = node.parent; + } return node; } /** @@ -321,8 +339,9 @@ * @param {number=} stopTime */ forEachFrame(openFrameCallback, closeFrameCallback, startTime, stopTime) { - if (!this.profileHead || !this.samples) + if (!this.profileHead || !this.samples) { return; + } startTime = startTime || 0; stopTime = stopTime || Infinity; @@ -341,22 +360,26 @@ // Extra slots for gc being put on top, // and one at the bottom to allow safe stackTop-1 access. const stackDepth = this.maxDepth + 3; - if (!this._stackStartTimes) + if (!this._stackStartTimes) { this._stackStartTimes = new Float64Array(stackDepth); + } const stackStartTimes = this._stackStartTimes; - if (!this._stackChildrenDuration) + if (!this._stackChildrenDuration) { this._stackChildrenDuration = new Float64Array(stackDepth); + } const stackChildrenDuration = this._stackChildrenDuration; let node; let sampleIndex; for (sampleIndex = startIndex; sampleIndex < samplesCount; sampleIndex++) { sampleTime = timestamps[sampleIndex]; - if (sampleTime >= stopTime) + if (sampleTime >= stopTime) { break; + } const id = samples[sampleIndex]; - if (id === prevId) + if (id === prevId) { continue; + } node = idToNode.get(id); let prevNode = idToNode.get(prevId);
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js index eb3e595c..3c0080b 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js
@@ -31,8 +31,9 @@ /** @type {!Map<!Protocol.DOM.NodeId, !Map<string, boolean>>} */ this._matchingSelectors = new Map(); this._keyframes = []; - if (animationsPayload) + if (animationsPayload) { this._keyframes = animationsPayload.map(rule => new SDK.CSSKeyframesRule(cssModel, rule)); + } /** @type {!Map<!SDK.CSSStyleDeclaration, ?SDK.DOMNode>} */ this._nodeForStyle = new Map(); @@ -40,8 +41,9 @@ this._inheritedStyles = new Set(); matchedPayload = cleanUserAgentPayload(matchedPayload); - for (const inheritedResult of inheritedPayload) + for (const inheritedResult of inheritedPayload) { inheritedResult.matchedCSSRules = cleanUserAgentPayload(inheritedResult.matchedCSSRules); + } this._mainDOMCascade = this._buildMainCascade(inlinePayload, attributesPayload, matchedPayload, inheritedPayload); this._pseudoDOMCascades = this._buildPseudoCascades(pseudoPayload); @@ -49,8 +51,9 @@ /** @type {!Map<!SDK.CSSStyleDeclaration, !SDK.CSSMatchedStyles.DOMInheritanceCascade>} */ this._styleToDOMCascade = new Map(); for (const domCascade of Array.from(this._pseudoDOMCascades.values()).concat(this._mainDOMCascade)) { - for (const style of domCascade.styles()) + for (const style of domCascade.styles()) { this._styleToDOMCascade.set(style, domCascade); + } } /** @@ -58,8 +61,9 @@ * @return {!Array<!Protocol.CSS.RuleMatch>} */ function cleanUserAgentPayload(payload) { - for (const ruleMatch of payload) + for (const ruleMatch of payload) { cleanUserAgentSelectors(ruleMatch); + } // Merge UA rules that are sequential and have similar selector/media. const cleanMatchedPayload = []; @@ -82,14 +86,18 @@ function mergeRule(from, to) { const shorthands = /** @type {!Map<string, string>} */ (new Map()); const properties = /** @type {!Map<string, string>} */ (new Map()); - for (const entry of to.rule.style.shorthandEntries) + for (const entry of to.rule.style.shorthandEntries) { shorthands.set(entry.name, entry.value); - for (const entry of to.rule.style.cssProperties) + } + for (const entry of to.rule.style.cssProperties) { properties.set(entry.name, entry.value); - for (const entry of from.rule.style.shorthandEntries) + } + for (const entry of from.rule.style.shorthandEntries) { shorthands.set(entry.name, entry.value); - for (const entry of from.rule.style.cssProperties) + } + for (const entry of from.rule.style.cssProperties) { properties.set(entry.name, entry.value); + } to.rule.style.shorthandEntries = shorthands.keysArray().map(name => ({name, value: shorthands.get(name)})); to.rule.style.cssProperties = properties.keysArray().map(name => ({name, value: properties.get(name)})); } @@ -99,8 +107,9 @@ * @return {?string} */ function mediaText(ruleMatch) { - if (!ruleMatch.rule.media) + if (!ruleMatch.rule.media) { return null; + } return ruleMatch.rule.media.map(media => media.text).join(', '); } @@ -109,8 +118,9 @@ */ function cleanUserAgentSelectors(ruleMatch) { const {matchingSelectors, rule} = ruleMatch; - if (rule.origin !== 'user-agent' || !matchingSelectors.length) + if (rule.origin !== 'user-agent' || !matchingSelectors.length) { return; + } rule.selectorList.selectors = rule.selectorList.selectors.filter((item, i) => matchingSelectors.includes(i)); rule.selectorList.text = rule.selectorList.selectors.map(item => item.text).join(', '); ruleMatch.matchingSelectors = matchingSelectors.map((item, i) => i); @@ -136,8 +146,9 @@ * @this {SDK.CSSMatchedStyles} */ function addAttributesStyle() { - if (!attributesPayload) + if (!attributesPayload) { return; + } const style = new SDK.CSSStyleDeclaration(this._cssModel, null, attributesPayload, SDK.CSSStyleDeclaration.Type.Attributes); this._nodeForStyle.set(style, this._node); @@ -166,8 +177,9 @@ this._addMatchingSelectors(this._node, rule, matchedPayload[i].matchingSelectors); } - if (!addedAttributesStyle) + if (!addedAttributesStyle) { addAttributesStyle.call(this); + } nodeCascades.push(new SDK.CSSMatchedStyles.NodeCascade(this, nodeStyles, false /* isInherited */)); // Walk the node structure and identify styles with inherited properties. @@ -189,10 +201,13 @@ for (let j = inheritedMatchedCSSRules.length - 1; j >= 0; --j) { const inheritedRule = new SDK.CSSStyleRule(this._cssModel, inheritedMatchedCSSRules[j].rule); this._addMatchingSelectors(parentNode, inheritedRule, inheritedMatchedCSSRules[j].matchingSelectors); - if (!this._containsInherited(inheritedRule.style)) + if (!this._containsInherited(inheritedRule.style)) { continue; - if (containsStyle(nodeStyles, inheritedRule.style) || containsStyle(this._inheritedStyles, inheritedRule.style)) + } + if (containsStyle(nodeStyles, inheritedRule.style) || + containsStyle(this._inheritedStyles, inheritedRule.style)) { continue; + } this._nodeForStyle.set(inheritedRule.style, parentNode); inheritedStyles.push(inheritedRule.style); this._inheritedStyles.add(inheritedRule.style); @@ -209,11 +224,13 @@ * @return {boolean} */ function containsStyle(styles, query) { - if (!query.styleSheetId || !query.range) + if (!query.styleSheetId || !query.range) { return false; + } for (const style of styles) { - if (query.styleSheetId === style.styleSheetId && style.range && query.range.equal(style.range)) + if (query.styleSheetId === style.styleSheetId && style.range && query.range.equal(style.range)) { return true; + } } return false; } @@ -226,8 +243,9 @@ _buildPseudoCascades(pseudoPayload) { /** @type {!Map<!Protocol.DOM.PseudoType, !SDK.CSSMatchedStyles.DOMInheritanceCascade>} */ const pseudoCascades = new Map(); - if (!pseudoPayload) + if (!pseudoPayload) { return pseudoCascades; + } for (let i = 0; i < pseudoPayload.length; ++i) { const entryPayload = pseudoPayload[i]; // PseudoElement nodes are not created unless "content" css property is set. @@ -238,8 +256,9 @@ const pseudoRule = new SDK.CSSStyleRule(this._cssModel, rules[j].rule); pseudoStyles.push(pseudoRule.style); this._nodeForStyle.set(pseudoRule.style, pseudoElement); - if (pseudoElement) + if (pseudoElement) { this._addMatchingSelectors(pseudoElement, pseudoRule, rules[j].matchingSelectors); + } } const nodeCascade = new SDK.CSSMatchedStyles.NodeCascade(this, pseudoStyles, false /* isInherited */); pseudoCascades.set(entryPayload.pseudoType, new SDK.CSSMatchedStyles.DOMInheritanceCascade([nodeCascade])); @@ -289,15 +308,18 @@ */ matchingSelectors(rule) { const node = this.nodeForStyle(rule.style); - if (!node) + if (!node) { return []; + } const map = this._matchingSelectors.get(node.id); - if (!map) + if (!map) { return []; + } const result = []; for (let i = 0; i < rule.selectors.length; ++i) { - if (map.get(rule.selectors[i].text)) + if (map.get(rule.selectors[i].text)) { result.push(i); + } } return result; } @@ -308,11 +330,13 @@ */ recomputeMatchingSelectors(rule) { const node = this.nodeForStyle(rule.style); - if (!node) + if (!node) { return Promise.resolve(); + } const promises = []; - for (const selector of rule.selectors) + for (const selector of rule.selectors) { promises.push(querySelector.call(this, node, selector.text)); + } return Promise.all(promises); /** @@ -325,13 +349,15 @@ // We assume that "matching" property does not ever change during the // MatchedStyleResult's lifetime. const map = this._matchingSelectors.get(node.id); - if ((map && map.has(selectorText)) || !ownerDocument) + if ((map && map.has(selectorText)) || !ownerDocument) { return; + } const matchingNodeIds = await this._node.domModel().querySelectorAll(ownerDocument.id, selectorText); - if (matchingNodeIds) + if (matchingNodeIds) { this._setSelectorMatches(node, selectorText, matchingNodeIds.indexOf(node.id) !== -1); + } } } @@ -366,8 +392,9 @@ mediaMatches(style) { const media = style.parentRule ? style.parentRule.media : []; for (let i = 0; media && i < media.length; ++i) { - if (!media[i].active()) + if (!media[i].active()) { return false; + } } return true; } @@ -411,8 +438,9 @@ for (let i = 0; i < properties.length; ++i) { const property = properties[i]; // Does this style contain non-overridden inherited property? - if (property.activeInStyle() && SDK.cssMetadata().isPropertyInherited(property.name)) + if (property.activeInStyle() && SDK.cssMetadata().isPropertyInherited(property.name)) { return true; + } } return false; } @@ -473,8 +501,9 @@ resetActiveProperties() { this._mainDOMCascade.reset(); - for (const domCascade of this._pseudoDOMCascades.values()) + for (const domCascade of this._pseudoDOMCascades.values()) { domCascade.reset(); + } } }; @@ -501,15 +530,18 @@ for (const style of this._styles) { const rule = style.parentRule; // Compute cascade for CSSStyleRules only. - if (rule && !(rule instanceof SDK.CSSStyleRule)) + if (rule && !(rule instanceof SDK.CSSStyleRule)) { continue; - if (rule && !this._matchedStyles.hasMatchingSelectors(rule)) + } + if (rule && !this._matchedStyles.hasMatchingSelectors(rule)) { continue; + } for (const property of style.allProperties()) { // Do not pick non-inherited properties from inherited styles. - if (this._isInherited && !SDK.cssMetadata().isPropertyInherited(property.name)) + if (this._isInherited && !SDK.cssMetadata().isPropertyInherited(property.name)) { continue; + } if (!property.activeInStyle()) { this._propertiesState.set(property, SDK.CSSMatchedStyles.PropertyState.Overloaded); @@ -523,8 +555,9 @@ continue; } - if (activeProperty) + if (activeProperty) { this._propertiesState.set(activeProperty, SDK.CSSMatchedStyles.PropertyState.Overloaded); + } this._propertiesState.set(property, SDK.CSSMatchedStyles.PropertyState.Active); this._activeProperties.set(canonicalName, property); } @@ -549,8 +582,9 @@ /** @type {!Map<!SDK.CSSStyleDeclaration, !SDK.CSSMatchedStyles.NodeCascade>} */ this._styleToNodeCascade = new Map(); for (const nodeCascade of nodeCascades) { - for (const style of nodeCascade._styles) + for (const style of nodeCascade._styles) { this._styleToNodeCascade.set(style, nodeCascade); + } } } @@ -560,8 +594,9 @@ */ availableCSSVariables(style) { const nodeCascade = this._styleToNodeCascade.get(style); - if (!nodeCascade) + if (!nodeCascade) { return []; + } this._ensureInitialized(); return Array.from(this._availableCSSVariables.get(nodeCascade).keys()); } @@ -573,8 +608,9 @@ */ computeCSSVariable(style, variableName) { const nodeCascade = this._styleToNodeCascade.get(style); - if (!nodeCascade) + if (!nodeCascade) { return null; + } this._ensureInitialized(); const availableCSSVariables = this._availableCSSVariables.get(nodeCascade); const computedCSSVariables = this._computedCSSVariables.get(nodeCascade); @@ -588,8 +624,9 @@ */ computeValue(style, value) { const nodeCascade = this._styleToNodeCascade.get(style); - if (!nodeCascade) + if (!nodeCascade) { return null; + } this._ensureInitialized(); const availableCSSVariables = this._availableCSSVariables.get(nodeCascade); const computedCSSVariables = this._computedCSSVariables.get(nodeCascade); @@ -603,10 +640,12 @@ * @return {?string} */ _innerComputeCSSVariable(availableCSSVariables, computedCSSVariables, variableName) { - if (!availableCSSVariables.has(variableName)) + if (!availableCSSVariables.has(variableName)) { return null; - if (computedCSSVariables.has(variableName)) + } + if (computedCSSVariables.has(variableName)) { return computedCSSVariables.get(variableName); + } // Set dummy value to avoid infinite recursion. computedCSSVariables.set(variableName, null); const definedValue = availableCSSVariables.get(variableName); @@ -631,16 +670,19 @@ } // process var() function const regexMatch = result.value.match(/^var\((--[a-zA-Z0-9-_]+)[,]?\s*(.*)\)$/); - if (!regexMatch) + if (!regexMatch) { return null; + } const cssVariable = regexMatch[1]; const computedValue = this._innerComputeCSSVariable(availableCSSVariables, computedCSSVariables, cssVariable); - if (computedValue === null && !regexMatch[2]) + if (computedValue === null && !regexMatch[2]) { return null; - if (computedValue === null) + } + if (computedValue === null) { tokens.push(regexMatch[2]); - else + } else { tokens.push(computedValue); + } } return tokens.map(token => token.trim()).join(' '); } @@ -669,8 +711,9 @@ } _ensureInitialized() { - if (this._initialized) + if (this._initialized) { return; + } this._initialized = true; const activeProperties = new Map(); @@ -698,21 +741,24 @@ const shorthandProperty = /** @type {!SDK.CSSProperty} */ (entry[1]); const shorthandStyle = shorthandProperty.ownerStyle; const longhands = shorthandStyle.longhandProperties(shorthandProperty.name); - if (!longhands.length) + if (!longhands.length) { continue; + } let hasActiveLonghands = false; for (const longhand of longhands) { const longhandCanonicalName = SDK.cssMetadata().canonicalPropertyName(longhand.name); const longhandActiveProperty = activeProperties.get(longhandCanonicalName); - if (!longhandActiveProperty) + if (!longhandActiveProperty) { continue; + } if (longhandActiveProperty.ownerStyle === shorthandStyle) { hasActiveLonghands = true; break; } } - if (hasActiveLonghands) + if (hasActiveLonghands) { continue; + } activeProperties.delete(canonicalName); this._propertiesState.set(shorthandProperty, SDK.CSSMatchedStyles.PropertyState.Overloaded); } @@ -724,8 +770,9 @@ for (const entry of nodeCascade._activeProperties.entries()) { const propertyName = /** @type {string} */ (entry[0]); const property = /** @type {!SDK.CSSProperty} */ (entry[1]); - if (propertyName.startsWith('--')) + if (propertyName.startsWith('--')) { accumulatedCSSVariables.set(propertyName, property.value); + } } this._availableCSSVariables.set(nodeCascade, new Map(accumulatedCSSVariables)); this._computedCSSVariables.set(nodeCascade, new Map());
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSMedia.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSMedia.js index c6f7118..bf48d89 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSMedia.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSMedia.js
@@ -11,8 +11,9 @@ constructor(payload) { this._active = payload.active; this._expressions = []; - for (let j = 0; j < payload.expressions.length; ++j) + for (let j = 0; j < payload.expressions.length; ++j) { this._expressions.push(SDK.CSSMediaQueryExpression.parsePayload(payload.expressions[j])); + } } /** @@ -128,8 +129,9 @@ */ static parseMediaArrayPayload(cssModel, payload) { const result = []; - for (let i = 0; i < payload.length; ++i) + for (let i = 0; i < payload.length; ++i) { result.push(SDK.CSSMedia.parsePayload(cssModel, payload[i])); + } return result; } @@ -145,8 +147,9 @@ this.mediaList = null; if (payload.mediaList) { this.mediaList = []; - for (let i = 0; i < payload.mediaList.length; ++i) + for (let i = 0; i < payload.mediaList.length; ++i) { this.mediaList.push(SDK.CSSMediaQuery.parsePayload(payload.mediaList[i])); + } } } @@ -154,12 +157,14 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.styleSheetId !== edit.styleSheetId || !this.range) + if (this.styleSheetId !== edit.styleSheetId || !this.range) { return; - if (edit.oldRange.equal(this.range)) + } + if (edit.oldRange.equal(this.range)) { this._reinitialize(/** @type {!Protocol.CSS.CSSMedia} */ (edit.payload)); - else + } else { this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange); + } } /** @@ -167,8 +172,9 @@ * @return {boolean} */ equal(other) { - if (!this.styleSheetId || !this.range || !other.range) + if (!this.styleSheetId || !this.range || !other.range) { return false; + } return this.styleSheetId === other.styleSheetId && this.range.equal(other.range); } @@ -176,11 +182,13 @@ * @return {boolean} */ active() { - if (!this.mediaList) + if (!this.mediaList) { return true; + } for (let i = 0; i < this.mediaList.length; ++i) { - if (this.mediaList[i].active()) + if (this.mediaList[i].active()) { return true; + } } return false; } @@ -189,11 +197,13 @@ * @return {number|undefined} */ lineNumberInSource() { - if (!this.range) + if (!this.range) { return undefined; + } const header = this.header(); - if (!header) + if (!header) { return undefined; + } return header.lineNumberInSource(this.range.startLine); } @@ -201,11 +211,13 @@ * @return {number|undefined} */ columnNumberInSource() { - if (!this.range) + if (!this.range) { return undefined; + } const header = this.header(); - if (!header) + if (!header) { return undefined; + } return header.columnNumberInSource(this.range.startLine, this.range.startColumn); } @@ -221,8 +233,9 @@ */ rawLocation() { const header = this.header(); - if (!header || this.lineNumberInSource() === undefined) + if (!header || this.lineNumberInSource() === undefined) { return null; + } const lineNumber = Number(this.lineNumberInSource()); return new SDK.CSSLocation(header, lineNumber, this.columnNumberInSource()); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSMetadata.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSMetadata.js index dab04ad..7bf29b84 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSMetadata.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSMetadata.js
@@ -50,14 +50,17 @@ for (let i = 0; i < properties.length; ++i) { const property = properties[i]; const propertyName = property.name; - if (!CSS.supports(propertyName, 'initial')) + if (!CSS.supports(propertyName, 'initial')) { continue; + } this._values.push(propertyName); - if (property.inherited) + if (property.inherited) { this._inherited.add(propertyName); - if (property.svg) + } + if (property.svg) { this._svgProperties.add(propertyName); + } const longhands = properties[i].longhands; if (longhands) { @@ -85,8 +88,9 @@ .filter(value => CSS.supports(name, value)) .sort(SDK.CSSMetadata._sortPrefixesToEnd); const presets = values.map(value => `${name}: ${value}`); - if (!this.isSVGProperty(name)) + if (!this.isSVGProperty(name)) { this._nameValuePresets.pushAll(presets); + } this._nameValuePresetsIncludingSVG.pushAll(presets); } } @@ -98,10 +102,12 @@ static _sortPrefixesToEnd(a, b) { const aIsPrefixed = a.startsWith('-webkit-'); const bIsPrefixed = b.startsWith('-webkit-'); - if (aIsPrefixed && !bIsPrefixed) + if (aIsPrefixed && !bIsPrefixed) { return 1; - if (!aIsPrefixed && bIsPrefixed) + } + if (!aIsPrefixed && bIsPrefixed) { return -1; + } return a < b ? -1 : (a > b ? 1 : 0); } @@ -169,8 +175,9 @@ */ isLengthProperty(propertyName) { propertyName = propertyName.toLowerCase(); - if (propertyName === 'line-height') + if (propertyName === 'line-height') { return false; + } return SDK.CSSMetadata._distanceProperties.has(propertyName) || propertyName.startsWith('margin') || propertyName.startsWith('padding') || propertyName.indexOf('width') !== -1 || propertyName.indexOf('height') !== -1; @@ -198,14 +205,17 @@ * @return {string} */ canonicalPropertyName(name) { - if (this.isCustomProperty(name)) + if (this.isCustomProperty(name)) { return name; + } name = name.toLowerCase(); - if (!name || name.length < 9 || name.charAt(0) !== '-') + if (!name || name.length < 9 || name.charAt(0) !== '-') { return name; + } const match = name.match(/(?:-webkit-)(.+)/); - if (!match || !this._valuesSet.has(match[1])) + if (!match || !this._valuesSet.has(match[1])) { return name; + } return match[1]; } @@ -216,8 +226,9 @@ isCSSPropertyName(propertyName) { propertyName = propertyName.toLowerCase(); if (propertyName.startsWith('-moz-') || propertyName.startsWith('-o-') || propertyName.startsWith('-webkit-') || - propertyName.startsWith('-ms-')) + propertyName.startsWith('-ms-')) { return true; + } return this._valuesSet.has(propertyName); } @@ -240,8 +251,9 @@ const entry = SDK.CSSMetadata._propertyDataMap[propertyName] || SDK.CSSMetadata._propertyDataMap[unprefixedName]; const keywords = entry && entry.values ? entry.values.slice() : []; for (const commonKeyword of ['auto', 'none']) { - if (CSS.supports(propertyName, commonKeyword)) + if (CSS.supports(propertyName, commonKeyword)) { keywords.push(commonKeyword); + } } return keywords; } @@ -256,8 +268,9 @@ acceptedKeywords.pushAll(this._specificPropertyValues(propertyName)); if (this.isColorAwareProperty(propertyName)) { acceptedKeywords.push('currentColor'); - for (const color in Common.Color.Nicknames) + for (const color in Common.Color.Nicknames) { acceptedKeywords.push(color); + } } return acceptedKeywords.sort(SDK.CSSMetadata._sortPrefixesToEnd); } @@ -278,8 +291,9 @@ getValuePreset(key, value) { const values = SDK.CSSMetadata._valuePresets.get(key); let text = values ? values.get(value) : null; - if (!text) + if (!text) { return null; + } let startColumn = text.length; let endColumn = text.length; if (text) { @@ -309,8 +323,9 @@ * @return {!SDK.CSSMetadata} */ SDK.cssMetadata = function() { - if (!SDK.CSSMetadata._instance) + if (!SDK.CSSMetadata._instance) { SDK.CSSMetadata._instance = new SDK.CSSMetadata(SDK.CSSMetadata._generatedProperties || []); + } return SDK.CSSMetadata._instance; };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js index 94051a4..be54c34 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js
@@ -48,8 +48,9 @@ SDK.ResourceTreeModel.Events.MainFrameNavigated, this._resetStyleSheets, this); } target.registerCSSDispatcher(new SDK.CSSDispatcher(this)); - if (!target.suspended()) + if (!target.suspended()) { this._enable(); + } /** @type {!Map.<string, !SDK.CSSStyleSheetHeader>} */ this._styleSheetIdToHeader = new Map(); /** @type {!Map.<string, !Object.<!Protocol.Page.FrameId, !Array.<!Protocol.CSS.StyleSheetId>>>} */ @@ -74,8 +75,9 @@ const headers = []; for (const headerId of this.styleSheetIdsForURL(sourceURL)) { const header = this.styleSheetHeaderForId(headerId); - if (header) + if (header) { headers.push(header); + } } return headers; } @@ -91,14 +93,16 @@ headers.sort(stylesheetComparator); const compareToArgLocation = (_, header) => lineNumber - header.startLine || columnNumber - header.startColumn; const endIndex = headers.upperBound(undefined, compareToArgLocation); - if (!endIndex) + if (!endIndex) { return []; + } const locations = []; const last = headers[endIndex - 1]; for (let index = endIndex - 1; index >= 0 && headers[index].startLine === last.startLine && headers[index].startColumn === last.startColumn; - --index) + --index) { locations.push(new SDK.CSSLocation(headers[index], lineNumber, columnNumber)); + } return locations; @@ -127,16 +131,19 @@ let sourceURLIndex = text.lastIndexOf('/*# sourceURL='); if (sourceURLIndex === -1) { sourceURLIndex = text.lastIndexOf('/*@ sourceURL='); - if (sourceURLIndex === -1) + if (sourceURLIndex === -1) { return text; + } } const sourceURLLineIndex = text.lastIndexOf('\n', sourceURLIndex); - if (sourceURLLineIndex === -1) + if (sourceURLLineIndex === -1) { return text; + } const sourceURLLine = text.substr(sourceURLLineIndex + 1).split('\n', 1)[0]; const sourceURLRegex = /[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/; - if (sourceURLLine.search(sourceURLRegex) === -1) + if (sourceURLLine.search(sourceURLRegex) === -1) { return text; + } return text.substr(0, sourceURLLineIndex) + text.substr(sourceURLLineIndex + sourceURLLine.length + 1); } @@ -160,8 +167,9 @@ const stylePayloads = await this._agent.setStyleTexts([{styleSheetId: styleSheetId, range: range.serializeToObject(), text: text}]); - if (!stylePayloads || stylePayloads.length !== 1) + if (!stylePayloads || stylePayloads.length !== 1) { return false; + } this._domModel.markUndoableState(!majorChange); const edit = new SDK.CSSModel.Edit(styleSheetId, range, text, stylePayloads[0]); @@ -185,8 +193,9 @@ await this._ensureOriginalStyleSheetText(styleSheetId); const selectorPayload = await this._agent.setRuleSelector(styleSheetId, range, text); - if (!selectorPayload) + if (!selectorPayload) { return false; + } this._domModel.markUndoableState(); const edit = new SDK.CSSModel.Edit(styleSheetId, range, text, selectorPayload); this._fireStyleSheetChanged(styleSheetId, edit); @@ -209,8 +218,9 @@ await this._ensureOriginalStyleSheetText(styleSheetId); const payload = await this._agent.setKeyframeKey(styleSheetId, range, text); - if (!payload) + if (!payload) { return false; + } this._domModel.markUndoableState(); const edit = new SDK.CSSModel.Edit(styleSheetId, range, text, payload); this._fireStyleSheetChanged(styleSheetId, edit); @@ -261,8 +271,9 @@ async _enable() { await this._agent.enable(); this._isEnabled = true; - if (this._isRuleUsageTrackingEnabled) + if (this._isRuleUsageTrackingEnabled) { await this.startCoverage(); + } this.dispatchEventToListeners(SDK.CSSModel.Events.ModelWasEnabled); } @@ -273,12 +284,14 @@ async matchedStylesPromise(nodeId) { const response = await this._agent.invoke_getMatchedStylesForNode({nodeId}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return null; + } const node = this._domModel.nodeForId(nodeId); - if (!node) + if (!node) { return null; + } return new SDK.CSSMatchedStyles( this, /** @type {!SDK.DOMNode} */ (node), response.inlineStyle || null, response.attributesStyle || null, @@ -308,8 +321,9 @@ */ async backgroundColorsPromise(nodeId) { const response = this._agent.invoke_getBackgroundColors({nodeId}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return null; + } return response; } @@ -333,10 +347,11 @@ * @return {number} */ function styleSheetComparator(a, b) { - if (a.sourceURL < b.sourceURL) + if (a.sourceURL < b.sourceURL) { return -1; - else if (a.sourceURL > b.sourceURL) + } else if (a.sourceURL > b.sourceURL) { return 1; + } return a.startLine - b.startLine || a.startColumn - b.startColumn; } values.sort(styleSheetComparator); @@ -351,8 +366,9 @@ async inlineStylesPromise(nodeId) { const response = await this._agent.invoke_getInlineStylesForNode({nodeId}); - if (response[Protocol.Error] || !response.inlineStyle) + if (response[Protocol.Error] || !response.inlineStyle) { return null; + } const inlineStyle = new SDK.CSSStyleDeclaration(this, null, response.inlineStyle, SDK.CSSStyleDeclaration.Type.Inline); const attributesStyle = response.attributesStyle ? @@ -370,18 +386,21 @@ forcePseudoState(node, pseudoClass, enable) { const pseudoClasses = node.marker(SDK.CSSModel.PseudoStateMarker) || []; if (enable) { - if (pseudoClasses.indexOf(pseudoClass) >= 0) + if (pseudoClasses.indexOf(pseudoClass) >= 0) { return false; + } pseudoClasses.push(pseudoClass); node.setMarker(SDK.CSSModel.PseudoStateMarker, pseudoClasses); } else { - if (pseudoClasses.indexOf(pseudoClass) < 0) + if (pseudoClasses.indexOf(pseudoClass) < 0) { return false; + } pseudoClasses.remove(pseudoClass); - if (pseudoClasses.length) + if (pseudoClasses.length) { node.setMarker(SDK.CSSModel.PseudoStateMarker, pseudoClasses); - else + } else { node.setMarker(SDK.CSSModel.PseudoStateMarker, null); + } } this._agent.forcePseudoState(node.id, pseudoClasses); @@ -411,8 +430,9 @@ await this._ensureOriginalStyleSheetText(styleSheetId); const mediaPayload = await this._agent.setMediaText(styleSheetId, range, newMediaText); - if (!mediaPayload) + if (!mediaPayload) { return false; + } this._domModel.markUndoableState(); const edit = new SDK.CSSModel.Edit(styleSheetId, range, newMediaText, mediaPayload); this._fireStyleSheetChanged(styleSheetId, edit); @@ -433,8 +453,9 @@ await this._ensureOriginalStyleSheetText(styleSheetId); const rulePayload = await this._agent.addRule(styleSheetId, ruleText, ruleLocation); - if (!rulePayload) + if (!rulePayload) { return null; + } this._domModel.markUndoableState(); const edit = new SDK.CSSModel.Edit(styleSheetId, ruleLocation, ruleText, rulePayload); this._fireStyleSheetChanged(styleSheetId, edit); @@ -452,8 +473,9 @@ const frameId = node.frameId() || (this._resourceTreeModel ? this._resourceTreeModel.mainFrame.id : ''); const headers = this._styleSheetIdToHeader.valuesArray(); const styleSheetHeader = headers.find(header => header.frameId === frameId && header.isViaInspector()); - if (styleSheetHeader) + if (styleSheetHeader) { return styleSheetHeader; + } try { const styleSheetId = await this._agent.createStyleSheet(frameId); @@ -500,8 +522,9 @@ */ _ensureOriginalStyleSheetText(styleSheetId) { const header = this.styleSheetHeaderForId(styleSheetId); - if (!header) + if (!header) { return Promise.resolve(/** @type {?string} */ (null)); + } let promise = this._originalStyleSheetText.get(header); if (!promise) { promise = this.getStyleSheetText(header.id); @@ -533,8 +556,9 @@ const styleSheetHeader = new SDK.CSSStyleSheetHeader(this, header); this._styleSheetIdToHeader.set(header.styleSheetId, styleSheetHeader); const url = styleSheetHeader.resourceURL(); - if (!this._styleSheetIdsForURL.get(url)) + if (!this._styleSheetIdsForURL.get(url)) { this._styleSheetIdsForURL.set(url, {}); + } const frameIdToStyleSheetIds = this._styleSheetIdsForURL.get(url); let styleSheetIds = frameIdToStyleSheetIds[styleSheetHeader.frameId]; if (!styleSheetIds) { @@ -552,8 +576,9 @@ _styleSheetRemoved(id) { const header = this._styleSheetIdToHeader.get(id); console.assert(header); - if (!header) + if (!header) { return; + } this._styleSheetIdToHeader.remove(id); const url = header.resourceURL(); const frameIdToStyleSheetIds = @@ -563,8 +588,9 @@ frameIdToStyleSheetIds[header.frameId].remove(id); if (!frameIdToStyleSheetIds[header.frameId].length) { delete frameIdToStyleSheetIds[header.frameId]; - if (!Object.keys(frameIdToStyleSheetIds).length) + if (!Object.keys(frameIdToStyleSheetIds).length) { this._styleSheetIdsForURL.remove(url); + } } this._originalStyleSheetText.remove(header); this._sourceMapManager.detachSourceMap(header); @@ -577,12 +603,14 @@ */ styleSheetIdsForURL(url) { const frameIdToStyleSheetIds = this._styleSheetIdsForURL.get(url); - if (!frameIdToStyleSheetIds) + if (!frameIdToStyleSheetIds) { return []; + } let result = []; - for (const frameId in frameIdToStyleSheetIds) + for (const frameId in frameIdToStyleSheetIds) { result = result.concat(frameIdToStyleSheetIds[frameId]); + } return result; } @@ -596,8 +624,9 @@ const header = /** @type {!SDK.CSSStyleSheetHeader} */ (this._styleSheetIdToHeader.get(styleSheetId)); console.assert(header); newText = SDK.CSSModel.trimSourceURL(newText); - if (header.hasSourceURL) + if (header.hasSourceURL) { newText += '\n/*# sourceURL=' + header.sourceURL + ' */'; + } await this._ensureOriginalStyleSheetText(styleSheetId); const response = await this._agent.invoke_setStyleSheetText({styleSheetId: header.id, text: newText}); @@ -606,8 +635,9 @@ this._sourceMapManager.detachSourceMap(header); header.setSourceMapURL(sourceMapURL); this._sourceMapManager.attachSourceMap(header, header.sourceURL, header.sourceMapURL); - if (sourceMapURL === null) + if (sourceMapURL === null) { return 'Error in CSS.setStyleSheetText'; + } this._domModel.markUndoableState(!majorChange); this._fireStyleSheetChanged(styleSheetId); return null; @@ -667,11 +697,13 @@ * @return {!Promise.<?SDK.CSSMatchedStyles>} */ cachedMatchedCascadeForNode(node) { - if (this._cachedMatchedCascadeNode !== node) + if (this._cachedMatchedCascadeNode !== node) { this.discardCachedMatchedCascade(); + } this._cachedMatchedCascadeNode = node; - if (!this._cachedMatchedCascadePromise) + if (!this._cachedMatchedCascadePromise) { this._cachedMatchedCascadePromise = this.matchedStylesPromise(node.id); + } return this._cachedMatchedCascadePromise; } @@ -831,8 +863,9 @@ */ computedStylePromise(nodeId) { let promise = this._nodeIdToPromise.get(nodeId); - if (promise) + if (promise) { return promise; + } promise = this._cssModel._agent.getComputedStyleForNode(nodeId).then(parsePayload.bind(this)); this._nodeIdToPromise.set(nodeId, promise); return promise; @@ -844,11 +877,13 @@ */ function parsePayload(computedPayload) { this._nodeIdToPromise.delete(nodeId); - if (!computedPayload || !computedPayload.length) + if (!computedPayload || !computedPayload.length) { return null; + } const result = new Map(); - for (const property of computedPayload) + for (const property of computedPayload) { result.set(property.name, property.value); + } return result; } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSProperty.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSProperty.js index e386ab3..737af9b 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSProperty.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSProperty.js
@@ -52,17 +52,20 @@ } _ensureRanges() { - if (this._nameRange && this._valueRange) + if (this._nameRange && this._valueRange) { return; + } const range = this.range; const text = this.text ? new TextUtils.Text(this.text) : null; - if (!range || !text) + if (!range || !text) { return; + } const nameIndex = text.value().indexOf(this.name); const valueIndex = text.value().lastIndexOf(this.value); - if (nameIndex === -1 || valueIndex === -1 || nameIndex > valueIndex) + if (nameIndex === -1 || valueIndex === -1 || nameIndex > valueIndex) { return; + } const nameSourceRange = new TextUtils.SourceRange(nameIndex, this.name.length); const valueSourceRange = new TextUtils.SourceRange(valueIndex, this.value.length); @@ -107,10 +110,12 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.ownerStyle.styleSheetId !== edit.styleSheetId) + if (this.ownerStyle.styleSheetId !== edit.styleSheetId) { return; - if (this.range) + } + if (this.range) { this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange); + } } /** @@ -121,11 +126,13 @@ } get propertyText() { - if (this.text !== undefined) + if (this.text !== undefined) { return this.text; + } - if (this.name === '') + if (this.name === '') { return ''; + } return this.name + ': ' + this.value + (this.important ? ' !important' : '') + ';'; } @@ -143,17 +150,21 @@ * @return {!Promise.<boolean>} */ async setText(propertyText, majorChange, overwrite) { - if (!this.ownerStyle) + if (!this.ownerStyle) { return Promise.reject(new Error('No ownerStyle for property')); + } - if (!this.ownerStyle.styleSheetId) + if (!this.ownerStyle.styleSheetId) { return Promise.reject(new Error('No owner style id')); + } - if (!this.range || !this.ownerStyle.range) + if (!this.range || !this.ownerStyle.range) { return Promise.reject(new Error('Style not editable')); + } - if (majorChange) + if (majorChange) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited); + } if (overwrite && propertyText === this.propertyText) { this.ownerStyle.cssModel().domModel().markUndoableState(!majorChange); @@ -181,8 +192,9 @@ */ static _formatStyle(styleText, indentation, endIndentation, tokenizerFactory) { const doubleIndent = indentation.substring(endIndentation.length) + indentation; - if (indentation) + if (indentation) { indentation = '\n' + indentation; + } let result = ''; let propertyName = ''; let propertyText; @@ -191,8 +203,9 @@ const tokenize = tokenizerFactory.createTokenizer('text/css'); tokenize('*{' + styleText + '}', processToken); - if (insideProperty) + if (insideProperty) { result += propertyText; + } result = result.substring(2, result.length - 1).trimRight(); return result + (indentation ? '\n' + endIndentation : ''); @@ -215,11 +228,13 @@ propertyText = token; } else if (token !== ';' || needsSemi) { result += token; - if (token.trim() && !(tokenType && tokenType.includes('css-comment'))) + if (token.trim() && !(tokenType && tokenType.includes('css-comment'))) { needsSemi = token !== ';'; + } } - if (token === '{' && !tokenType) + if (token === '{' && !tokenType) { needsSemi = false; + } return; } @@ -228,16 +243,19 @@ needsSemi = false; insideProperty = false; propertyName = ''; - if (token === '}') + if (token === '}') { result += '}'; + } } else { if (SDK.cssMetadata().isGridAreaDefiningProperty(propertyName)) { const rowResult = SDK.CSSMetadata.GridAreaRowRegex.exec(token); - if (rowResult && rowResult.index === 0 && !propertyText.trimRight().endsWith(']')) + if (rowResult && rowResult.index === 0 && !propertyText.trimRight().endsWith(']')) { propertyText = propertyText.trimRight() + '\n' + doubleIndent; + } } - if (!propertyName && token === ':') + if (!propertyName && token === ':') { propertyName = propertyText; + } propertyText += token; } } @@ -248,8 +266,9 @@ */ function isDisabledProperty(text) { const colon = text.indexOf(':'); - if (colon === -1) + if (colon === -1) { return false; + } const propertyName = text.substring(2, colon).trim(); return SDK.cssMetadata().isCSSPropertyName(propertyName); } @@ -261,8 +280,9 @@ */ _detectIndentation(text) { const lines = text.split('\n'); - if (lines.length < 2) + if (lines.length < 2) { return ''; + } return TextUtils.TextUtils.lineIndent(lines[1]); } @@ -282,10 +302,12 @@ * @return {!Promise.<boolean>} */ setDisabled(disabled) { - if (!this.ownerStyle) + if (!this.ownerStyle) { return Promise.resolve(false); - if (disabled === this.disabled) + } + if (disabled === this.disabled) { return Promise.resolve(true); + } const propertyText = this.text.trim(); const text = disabled ? '/* ' + propertyText + ' */' : this.text.substring(2, propertyText.length - 2).trim(); return this.setText(text, true, true);
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSRule.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSRule.js index bb866f9..17269f71 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSRule.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSRule.js
@@ -10,16 +10,18 @@ */ constructor(payload) { this.text = payload.text; - if (payload.range) + if (payload.range) { this.range = TextUtils.TextRange.fromObject(payload.range); + } } /** * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (!this.range) + if (!this.range) { return; + } this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange); } }; @@ -48,8 +50,9 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.styleSheetId !== edit.styleSheetId) + if (this.styleSheetId !== edit.styleSheetId) { return; + } this.style.rebase(edit); } @@ -57,8 +60,9 @@ * @return {string} */ resourceURL() { - if (!this.styleSheetId) + if (!this.styleSheetId) { return ''; + } const styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId); return styleSheetHeader.resourceURL(); } @@ -137,8 +141,9 @@ _reinitializeSelectors(selectorList) { /** @type {!Array.<!SDK.CSSValue>} */ this.selectors = []; - for (let i = 0; i < selectorList.selectors.length; ++i) + for (let i = 0; i < selectorList.selectors.length; ++i) { this.selectors.push(new SDK.CSSValue(selectorList.selectors[i])); + } } /** @@ -147,11 +152,13 @@ */ setSelectorText(newSelector) { const styleSheetId = this.styleSheetId; - if (!styleSheetId) + if (!styleSheetId) { throw 'No rule stylesheet id'; + } const range = this.selectorRange(); - if (!range) + if (!range) { throw 'Rule selector is not editable'; + } return this._cssModel.setSelectorText(styleSheetId, range, newSelector); } @@ -167,8 +174,9 @@ */ selectorRange() { const firstRange = this.selectors[0].range; - if (!firstRange) + if (!firstRange) { return null; + } const lastRange = this.selectors.peekLast().range; return new TextUtils.TextRange( firstRange.startLine, firstRange.startColumn, lastRange.endLine, lastRange.endColumn); @@ -180,8 +188,9 @@ */ lineNumberInSource(selectorIndex) { const selector = this.selectors[selectorIndex]; - if (!selector || !selector.range || !this.styleSheetId) + if (!selector || !selector.range || !this.styleSheetId) { return 0; + } const styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId); return styleSheetHeader.lineNumberInSource(selector.range.startLine); } @@ -192,8 +201,9 @@ */ columnNumberInSource(selectorIndex) { const selector = this.selectors[selectorIndex]; - if (!selector || !selector.range || !this.styleSheetId) + if (!selector || !selector.range || !this.styleSheetId) { return undefined; + } const styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId); console.assert(styleSheetHeader); return styleSheetHeader.columnNumberInSource(selector.range.startLine, selector.range.startColumn); @@ -204,16 +214,19 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.styleSheetId !== edit.styleSheetId) + if (this.styleSheetId !== edit.styleSheetId) { return; + } if (this.selectorRange().equal(edit.oldRange)) { this._reinitializeSelectors(/** @type {!Protocol.CSS.SelectorList} */ (edit.payload)); } else { - for (let i = 0; i < this.selectors.length; ++i) + for (let i = 0; i < this.selectors.length; ++i) { this.selectors[i].rebase(edit); + } } - for (const media of this.media) + for (const media of this.media) { media.rebase(edit); + } super.rebase(edit); } @@ -281,12 +294,14 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.styleSheetId !== edit.styleSheetId || !this._keyText.range) + if (this.styleSheetId !== edit.styleSheetId || !this._keyText.range) { return; - if (edit.oldRange.equal(this._keyText.range)) + } + if (edit.oldRange.equal(this._keyText.range)) { this._reinitializeKey(/** @type {!Protocol.CSS.Value} */ (edit.payload)); - else + } else { this._keyText.rebase(edit); + } super.rebase(edit); } @@ -297,11 +312,13 @@ */ setKeyText(newKeyText) { const styleSheetId = this.styleSheetId; - if (!styleSheetId) + if (!styleSheetId) { throw 'No rule stylesheet id'; + } const range = this._keyText.range; - if (!range) + if (!range) { throw 'Keyframe key is not editable'; + } return this._cssModel.setKeyframeKey(styleSheetId, range, newKeyText); } };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleDeclaration.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleDeclaration.js index d02bd356..a22d70c 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleDeclaration.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleDeclaration.js
@@ -35,14 +35,16 @@ * @param {!SDK.CSSModel.Edit} edit */ rebase(edit) { - if (this.styleSheetId !== edit.styleSheetId || !this.range) + if (this.styleSheetId !== edit.styleSheetId || !this.range) { return; + } if (edit.oldRange.equal(this.range)) { this._reinitialize(/** @type {!Protocol.CSS.CSSStyle} */ (edit.payload)); } else { this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange); - for (let i = 0; i < this._allProperties.length; ++i) + for (let i = 0; i < this._allProperties.length; ++i) { this._allProperties[i].rebase(edit); + } } } @@ -58,8 +60,9 @@ this._shorthandIsImportant = new Set(); for (let i = 0; i < shorthandEntries.length; ++i) { this._shorthandValues.set(shorthandEntries[i].name, shorthandEntries[i].value); - if (shorthandEntries[i].important) + if (shorthandEntries[i].important) { this._shorthandIsImportant.add(shorthandEntries[i].name); + } } this._allProperties = []; @@ -77,8 +80,9 @@ } parseUnusedText.call(this, cssText, start.line, start.column, this.range.endLine, this.range.endColumn); } else { - for (const cssProperty of payload.cssProperties) + for (const cssProperty of payload.cssProperties) { this._allProperties.push(SDK.CSSProperty.parsePayload(this, this._allProperties.length, cssProperty)); + } } this._generateSyntheticPropertiesIfNeeded(); @@ -86,8 +90,9 @@ this._activePropertyMap = new Map(); for (const property of this._allProperties) { - if (!property.activeInStyle()) + if (!property.activeInStyle()) { continue; + } this._activePropertyMap.set(property.name, property); } @@ -162,15 +167,18 @@ } _generateSyntheticPropertiesIfNeeded() { - if (this.range) + if (this.range) { return; + } - if (!this._shorthandValues.size) + if (!this._shorthandValues.size) { return; + } const propertiesSet = new Set(); - for (const property of this._allProperties) + for (const property of this._allProperties) { propertiesSet.add(property.name); + } const generatedProperties = []; // For style-based properties, generate shorthands with values when possible. @@ -178,11 +186,13 @@ // For style-based properties, try generating shorthands. const shorthands = SDK.cssMetadata().shorthands(property.name) || []; for (const shorthand of shorthands) { - if (propertiesSet.has(shorthand)) - continue; // There already is a shorthand this longhands falls under. + if (propertiesSet.has(shorthand)) { + continue; + } // There already is a shorthand this longhands falls under. const shorthandValue = this._shorthandValues.get(shorthand); - if (!shorthandValue) - continue; // Never generate synthetic shorthands when no value is available. + if (!shorthandValue) { + continue; + } // Never generate synthetic shorthands when no value is available. // Generate synthetic shorthand we have a value for. const shorthandImportance = !!this._shorthandIsImportant.has(shorthand); @@ -207,8 +217,9 @@ return !!property.range; } - if (this.range) + if (this.range) { return this._allProperties.filter(propertyHasRange); + } const leadingProperties = []; for (const property of this._allProperties) { @@ -220,8 +231,9 @@ break; } } - if (!belongToAnyShorthand) + if (!belongToAnyShorthand) { leadingProperties.push(property); + } } return leadingProperties; @@ -231,8 +243,9 @@ * @return {!Array.<!SDK.CSSProperty>} */ leadingProperties() { - if (!this._leadingProperties) + if (!this._leadingProperties) { this._leadingProperties = this._computeLeadingProperties(); + } return this._leadingProperties; } @@ -305,8 +318,9 @@ const result = []; for (let i = 0; longhands && i < longhands.length; ++i) { const property = this._activePropertyMap.get(longhands[i]); - if (property) + if (property) { result.push(property); + } } return result; } @@ -324,8 +338,9 @@ */ pastLastSourcePropertyIndex() { for (let i = this.allProperties().length - 1; i >= 0; --i) { - if (this.allProperties()[i].range) + if (this.allProperties()[i].range) { return i + 1; + } } return 0; } @@ -356,8 +371,9 @@ * @return {!Promise.<boolean>} */ setText(text, majorChange) { - if (!this.range || !this.styleSheetId) + if (!this.range || !this.styleSheetId) { return Promise.resolve(false); + } return this._cssModel.setStyleText(this.styleSheetId, this.range, text, majorChange); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleSheetHeader.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleSheetHeader.js index 8cfe057..f208dd6c 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleSheetHeader.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSStyleSheetHeader.js
@@ -23,8 +23,9 @@ this.startLine = payload.startLine; this.startColumn = payload.startColumn; this.contentLength = payload.length; - if (payload.ownerNode) + if (payload.ownerNode) { this.ownerNode = new SDK.DeferredDOMNode(cssModel.target(), payload.ownerNode); + } this.setSourceMapURL(payload.sourceMapURL); } @@ -76,8 +77,9 @@ console.assert(frame); const parsedURL = new Common.ParsedURL(frame.url); let fakeURL = 'inspector://' + parsedURL.host + parsedURL.folderPathComponents; - if (!fakeURL.endsWith('/')) + if (!fakeURL.endsWith('/')) { fakeURL += '/'; + } fakeURL += 'inspector-stylesheet'; return fakeURL; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js b/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js index a89ac32..c7b726d 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ChildTargetManager.js
@@ -63,8 +63,9 @@ * @override */ dispose() { - for (const sessionId of this._childTargets.keys()) + for (const sessionId of this._childTargets.keys()) { this.detachedFromTarget(sessionId, undefined); + } } /** @@ -112,8 +113,9 @@ * @return {!Promise<string>} */ async _getParentTargetId() { - if (!this._parentTargetId) + if (!this._parentTargetId) { this._parentTargetId = (await this._parentTarget.targetAgent().getTargetInfo()).targetId; + } return this._parentTargetId; } @@ -124,8 +126,9 @@ * @param {boolean} waitingForDebugger */ attachedToTarget(sessionId, targetInfo, waitingForDebugger) { - if (this._parentTargetId === targetInfo.targetId) + if (this._parentTargetId === targetInfo.targetId) { return; + } let targetName = ''; if (targetInfo.type === 'worker' && targetInfo.title && targetInfo.title !== targetInfo.url) { @@ -137,15 +140,17 @@ } let type = SDK.Target.Type.Browser; - if (targetInfo.type === 'iframe') + if (targetInfo.type === 'iframe') { type = SDK.Target.Type.Frame; + } // TODO(lfg): ensure proper capabilities for child pages (e.g. portals). - else if (targetInfo.type === 'page') + else if (targetInfo.type === 'page') { type = SDK.Target.Type.Frame; - else if (targetInfo.type === 'worker') + } else if (targetInfo.type === 'worker') { type = SDK.Target.Type.Worker; - else if (targetInfo.type === 'service_worker') + } else if (targetInfo.type === 'service_worker') { type = SDK.Target.Type.ServiceWorker; + } const target = this._targetManager.createTarget(targetInfo.targetId, targetName, type, this._parentTarget, sessionId);
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/Connections.js b/third_party/blink/renderer/devtools/front_end/sdk/Connections.js index a3ea04b..bc44429 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/Connections.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/Connections.js
@@ -40,16 +40,18 @@ * @param {string} message */ sendRawMessage(message) { - if (this._onMessage) + if (this._onMessage) { InspectorFrontendHost.sendMessageToBackend(message); + } } /** * @param {!Common.Event} event */ _dispatchMessage(event) { - if (this._onMessage) + if (this._onMessage) { this._onMessage.call(null, /** @type {string} */ (event.data)); + } } /** @@ -80,8 +82,9 @@ this._onDisconnect = null; this._onMessage = null; - if (onDisconnect) + if (onDisconnect) { onDisconnect.call(null, 'force disconnect'); + } return Promise.resolve(); } }; @@ -99,8 +102,9 @@ this._socket.onerror = this._onError.bind(this); this._socket.onopen = this._onOpen.bind(this); this._socket.onmessage = messageEvent => { - if (this._onMessage) + if (this._onMessage) { this._onMessage.call(null, /** @type {string} */ (messageEvent.data)); + } }; this._socket.onclose = this._onClose.bind(this); @@ -137,8 +141,9 @@ _onOpen() { this._socket.onerror = console.error; this._connected = true; - for (const message of this._messages) + for (const message of this._messages) { this._socket.send(message); + } this._messages = []; } @@ -166,10 +171,11 @@ * @param {string} message */ sendRawMessage(message) { - if (this._connected) + if (this._connected) { this._socket.send(message); - else + } else { this._messages.push(message); + } } /** @@ -180,8 +186,9 @@ let fulfill; const promise = new Promise(f => fulfill = f); this._close(() => { - if (this._onDisconnect) + if (this._onDisconnect) { this._onDisconnect.call(null, 'force disconnect'); + } fulfill(); }); return promise; @@ -231,8 +238,9 @@ code: Protocol.DevToolsStubErrorCode, data: messageObject }; - if (this._onMessage) + if (this._onMessage) { this._onMessage.call(null, {id: messageObject.id, error: error}); + } } /** @@ -240,8 +248,9 @@ * @return {!Promise} */ disconnect() { - if (this._onDisconnect) + if (this._onDisconnect) { this._onDisconnect.call(null, 'force disconnect'); + } this._onDisconnect = null; this._onMessage = null; return Promise.resolve(); @@ -294,8 +303,9 @@ * @return {!Promise} */ disconnect() { - if (this._onDisconnect) + if (this._onDisconnect) { this._onDisconnect.call(null, 'force disconnect'); + } this._onDisconnect = null; this._onMessage = null; return Promise.resolve();
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ConsoleModel.js b/third_party/blink/renderer/devtools/front_end/sdk/ConsoleModel.js index e77e21b..4b6d37e 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ConsoleModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ConsoleModel.js
@@ -110,8 +110,9 @@ */ targetRemoved(target) { const runtimeModel = target.model(SDK.RuntimeModel); - if (runtimeModel) + if (runtimeModel) { this._messageByExceptionId.delete(runtimeModel); + } Common.EventTarget.removeEventListeners(target[SDK.ConsoleModel._events] || []); } @@ -134,8 +135,9 @@ }, Common.settings.moduleSetting('consoleUserActivationEval').get(), awaitPromise); Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConsoleEvaluated); - if (result.error) + if (result.error) { return; + } await Common.console.showPromise(); this.dispatchEventToListeners( SDK.ConsoleModel.Events.CommandEvaluated, @@ -161,8 +163,10 @@ */ addMessage(msg) { msg._pageLoadSequenceNumber = this._pageLoadSequenceNumber; - if (msg.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI && msg.type === SDK.ConsoleMessage.MessageType.Clear) + if (msg.source === SDK.ConsoleMessage.MessageSource.ConsoleAPI && + msg.type === SDK.ConsoleMessage.MessageType.Clear) { this._clearIfNecessary(); + } this._messages.push(msg); const runtimeModel = msg.runtimeModel(); @@ -198,8 +202,9 @@ const exceptionId = /** @type {number} */ (event.data); const modelMap = this._messageByExceptionId.get(runtimeModel); const exceptionMessage = modelMap ? modelMap.get(exceptionId) : null; - if (!exceptionMessage) + if (!exceptionMessage) { return; + } this._errors--; exceptionMessage.level = SDK.ConsoleMessage.MessageLevel.Verbose; this.dispatchEventToListeners(SDK.ConsoleModel.Events.MessageUpdated, exceptionMessage); @@ -212,21 +217,24 @@ _consoleAPICalled(runtimeModel, event) { const call = /** @type {!SDK.RuntimeModel.ConsoleAPICall} */ (event.data); let level = SDK.ConsoleMessage.MessageLevel.Info; - if (call.type === SDK.ConsoleMessage.MessageType.Debug) + if (call.type === SDK.ConsoleMessage.MessageType.Debug) { level = SDK.ConsoleMessage.MessageLevel.Verbose; - else if (call.type === SDK.ConsoleMessage.MessageType.Error || call.type === SDK.ConsoleMessage.MessageType.Assert) + } else if ( + call.type === SDK.ConsoleMessage.MessageType.Error || call.type === SDK.ConsoleMessage.MessageType.Assert) { level = SDK.ConsoleMessage.MessageLevel.Error; - else if (call.type === SDK.ConsoleMessage.MessageType.Warning) + } else if (call.type === SDK.ConsoleMessage.MessageType.Warning) { level = SDK.ConsoleMessage.MessageLevel.Warning; - else if (call.type === SDK.ConsoleMessage.MessageType.Info || call.type === SDK.ConsoleMessage.MessageType.Log) + } else if (call.type === SDK.ConsoleMessage.MessageType.Info || call.type === SDK.ConsoleMessage.MessageType.Log) { level = SDK.ConsoleMessage.MessageLevel.Info; + } let message = ''; - if (call.args.length && call.args[0].unserializableValue) + if (call.args.length && call.args[0].unserializableValue) { message = call.args[0].unserializableValue; - else if (call.args.length && (typeof call.args[0].value !== 'object' || call.args[0].value === null)) + } else if (call.args.length && (typeof call.args[0].value !== 'object' || call.args[0].value === null)) { message = call.args[0].value + ''; - else if (call.args.length && call.args[0].description) + } else if (call.args.length && call.args[0].description) { message = call.args[0].description; + } const callFrame = call.stackTrace && call.stackTrace.callFrames.length ? call.stackTrace.callFrames[0] : null; const consoleMessage = new SDK.ConsoleMessage( runtimeModel, SDK.ConsoleMessage.MessageSource.ConsoleAPI, level, @@ -248,8 +256,9 @@ } _clearIfNecessary() { - if (!Common.moduleSetting('preserveConsoleLog').get()) + if (!Common.moduleSetting('preserveConsoleLog').get()) { this._clear(); + } ++this._pageLoadSequenceNumber; } @@ -257,8 +266,9 @@ * @param {!Common.Event} event */ _mainFrameNavigated(event) { - if (Common.moduleSetting('preserveConsoleLog').get()) + if (Common.moduleSetting('preserveConsoleLog').get()) { Common.console.log(Common.UIString('Navigated to %s', event.data.url)); + } } /** @@ -328,10 +338,12 @@ } requestClearMessages() { - for (const logModel of SDK.targetManager.models(SDK.LogModel)) + for (const logModel of SDK.targetManager.models(SDK.LogModel)) { logModel.requestClear(); - for (const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)) + } + for (const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)) { runtimeModel.discardConsoleEntries(); + } this._clear(); } @@ -394,8 +406,9 @@ this.evaluateCommandInConsole( executionContext, message, text, /* useCommandLineAPI */ false, /* awaitPromise */ false); } - if (callFunctionResult.object) + if (callFunctionResult.object) { callFunctionResult.object.release(); + } /** * @suppressReceiverCheck @@ -404,8 +417,9 @@ function saveVariable(value) { const prefix = 'temp'; let index = 1; - while ((prefix + index) in this) + while ((prefix + index) in this) { ++index; + } const name = prefix + index; this[name] = value; return name; @@ -416,8 +430,9 @@ */ function failedToSave(result) { let message = Common.UIString('Failed to save to temp variable.'); - if (result) + if (result) { message += ' ' + result.description; + } Common.console.error(message); } } @@ -476,14 +491,16 @@ this.workerId = workerId || null; if (!this.executionContextId && this._runtimeModel) { - if (this.scriptId) + if (this.scriptId) { this.executionContextId = this._runtimeModel.executionContextIdForScriptId(this.scriptId); - else if (this.stackTrace) + } else if (this.stackTrace) { this.executionContextId = this._runtimeModel.executionContextForStackTrace(this.stackTrace); + } } - if (context) + if (context) { this.context = context.match(/[^#]*/)[0]; + } } /** @@ -598,25 +615,30 @@ * @return {boolean} */ isEqual(msg) { - if (!msg) + if (!msg) { return false; + } - if (!this._isEqualStackTraces(this.stackTrace, msg.stackTrace)) + if (!this._isEqualStackTraces(this.stackTrace, msg.stackTrace)) { return false; + } if (this.parameters) { - if (!msg.parameters || this.parameters.length !== msg.parameters.length) + if (!msg.parameters || this.parameters.length !== msg.parameters.length) { return false; + } for (let i = 0; i < msg.parameters.length; ++i) { // Never treat objects as equal - their properties might change over time. Errors can be treated as equal // since they are always formatted as strings. - if (msg.parameters[i].type === 'object' && msg.parameters[i].subtype !== 'error') + if (msg.parameters[i].type === 'object' && msg.parameters[i].subtype !== 'error') { return false; + } if (this.parameters[i].type !== msg.parameters[i].type || this.parameters[i].value !== msg.parameters[i].value || - this.parameters[i].description !== msg.parameters[i].description) + this.parameters[i].description !== msg.parameters[i].description) { return false; + } } } @@ -632,19 +654,23 @@ * @return {boolean} */ _isEqualStackTraces(stackTrace1, stackTrace2) { - if (!stackTrace1 !== !stackTrace2) + if (!stackTrace1 !== !stackTrace2) { return false; - if (!stackTrace1) + } + if (!stackTrace1) { return true; + } const callFrames1 = stackTrace1.callFrames; const callFrames2 = stackTrace2.callFrames; - if (callFrames1.length !== callFrames2.length) + if (callFrames1.length !== callFrames2.length) { return false; + } for (let i = 0, n = callFrames1.length; i < n; ++i) { if (callFrames1[i].url !== callFrames2[i].url || callFrames1[i].functionName !== callFrames2[i].functionName || callFrames1[i].lineNumber !== callFrames2[i].lineNumber || - callFrames1[i].columnNumber !== callFrames2[i].columnNumber) + callFrames1[i].columnNumber !== callFrames2[i].columnNumber) { return false; + } } return this._isEqualStackTraces(stackTrace1.parent, stackTrace2.parent); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ContentProviders.js b/third_party/blink/renderer/devtools/front_end/sdk/ContentProviders.js index 45bbc89..203755f 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ContentProviders.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ContentProviders.js
@@ -103,8 +103,9 @@ */ async searchInContent(query, caseSensitive, isRegex) { const content = await this.requestContent(); - if (typeof content !== 'string') + if (typeof content !== 'string') { return []; + } return Common.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex); } };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CookieModel.js b/third_party/blink/renderer/devtools/front_end/sdk/CookieModel.js index ea23dd0..0af455c 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CookieModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CookieModel.js
@@ -17,8 +17,9 @@ */ static cookieMatchesResourceURL(cookie, resourceURL) { const url = resourceURL.asParsedURL(); - if (!url || !SDK.CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(), url.host)) + if (!url || !SDK.CookieModel.cookieDomainMatchesResourceDomain(cookie.domain(), url.host)) { return false; + } return ( url.path.startsWith(cookie.path()) && (!cookie.port() || url.port === cookie.port()) && (!cookie.secure() || url.scheme === 'https')); @@ -30,8 +31,9 @@ * @return {boolean} */ static cookieDomainMatchesResourceDomain(cookieDomain, resourceDomain) { - if (cookieDomain.charAt(0) !== '.') + if (cookieDomain.charAt(0) !== '.') { return resourceDomain === cookieDomain; + } return !!resourceDomain.match( new RegExp('^([^\\.]+\\.)*' + cookieDomain.substring(1).escapeForRegExp() + '$', 'i')); } @@ -67,11 +69,13 @@ */ saveCookie(cookie) { let domain = cookie.domain(); - if (!domain.startsWith('.')) + if (!domain.startsWith('.')) { domain = ''; + } let expires = undefined; - if (cookie.expires()) + if (cookie.expires()) { expires = Math.floor(Date.parse(cookie.expires()) / 1000); + } return this.target() .networkAgent() .setCookie( @@ -92,12 +96,14 @@ */ function populateResourceURLs(resource) { const documentURL = resource.documentURL.asParsedURL(); - if (documentURL && (!domain || documentURL.securityOrigin() === domain)) + if (documentURL && (!domain || documentURL.securityOrigin() === domain)) { resourceURLs.push(resource.url); + } } const resourceTreeModel = this.target().model(SDK.ResourceTreeModel); - if (resourceTreeModel) + if (resourceTreeModel) { resourceTreeModel.forAllResources(populateResourceURLs); + } return this.getCookies(resourceURLs); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CookieParser.js b/third_party/blink/renderer/devtools/front_end/sdk/CookieParser.js index a18fd52..dd197a6 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CookieParser.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CookieParser.js
@@ -69,14 +69,16 @@ * @return {?Array<!SDK.Cookie>} */ parseCookie(cookieHeader) { - if (!this._initialize(cookieHeader)) + if (!this._initialize(cookieHeader)) { return null; + } for (let kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) { - if (kv.key.charAt(0) === '$' && this._lastCookie) + if (kv.key.charAt(0) === '$' && this._lastCookie) { this._lastCookie.addAttribute(kv.key.slice(1), kv.value); - else if (kv.key.toLowerCase() !== '$version' && typeof kv.value === 'string') + } else if (kv.key.toLowerCase() !== '$version' && typeof kv.value === 'string') { this._addCookie(kv, SDK.Cookie.Type.Request); + } this._advanceAndCheckCookieDelimiter(); } this._flushCookie(); @@ -88,15 +90,18 @@ * @return {?Array<!SDK.Cookie>} */ parseSetCookie(setCookieHeader) { - if (!this._initialize(setCookieHeader)) + if (!this._initialize(setCookieHeader)) { return null; + } for (let kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) { - if (this._lastCookie) + if (this._lastCookie) { this._lastCookie.addAttribute(kv.key, kv.value); - else + } else { this._addCookie(kv, SDK.Cookie.Type.Response); - if (this._advanceAndCheckCookieDelimiter()) + } + if (this._advanceAndCheckCookieDelimiter()) { this._flushCookie(); + } } this._flushCookie(); return this._cookies; @@ -108,8 +113,9 @@ */ _initialize(headerValue) { this._input = headerValue; - if (typeof headerValue !== 'string') + if (typeof headerValue !== 'string') { return false; + } this._cookies = []; this._lastCookie = null; this._lastCookieLine = ''; @@ -130,8 +136,9 @@ * @return {?SDK.CookieParser.KeyValue} */ _extractKeyValue() { - if (!this._input || !this._input.length) + if (!this._input || !this._input.length) { return null; + } // Note: RFCs offer an option for quoted values that may contain commas and semicolons. // Many browsers/platforms do not support this, however (see http://webkit.org/b/16699 // and http://crbug.com/12361). The logic below matches latest versions of IE, Firefox, @@ -155,8 +162,9 @@ */ _advanceAndCheckCookieDelimiter() { const match = /^\s*[\n;]\s*/.exec(this._input); - if (!match) + if (!match) { return false; + } this._lastCookieLine += match[0]; this._input = this._input.slice(match[0].length); return match[0].match('\n') !== null; @@ -167,8 +175,9 @@ * @param {!SDK.Cookie.Type} type */ _addCookie(keyValue, type) { - if (this._lastCookie) + if (this._lastCookie) { this._lastCookie.setSize(keyValue.position - this._lastCookiePosition); + } // Mozilla bug 169091: Mozilla, IE and Chrome treat single token (w/o "=") as // specifying a value for a cookie with empty name. @@ -224,14 +233,18 @@ cookie.addAttribute('domain', protocolCookie['domain']); cookie.addAttribute('path', protocolCookie['path']); cookie.addAttribute('port', protocolCookie['port']); - if (protocolCookie['expires']) + if (protocolCookie['expires']) { cookie.addAttribute('expires', protocolCookie['expires'] * 1000); - if (protocolCookie['httpOnly']) + } + if (protocolCookie['httpOnly']) { cookie.addAttribute('httpOnly'); - if (protocolCookie['secure']) + } + if (protocolCookie['secure']) { cookie.addAttribute('secure'); - if (protocolCookie['sameSite']) + } + if (protocolCookie['sameSite']) { cookie.addAttribute('sameSite', protocolCookie['sameSite']); + } cookie.setSize(protocolCookie['size']); return cookie; } @@ -354,8 +367,9 @@ return new Date(targetDate.getTime() + 1000 * this.maxAge()); } - if (this.expires()) + if (this.expires()) { return new Date(this.expires()); + } return null; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/DOMDebuggerModel.js b/third_party/blink/renderer/devtools/front_end/sdk/DOMDebuggerModel.js index e8a5fc0..78092b3 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/DOMDebuggerModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/DOMDebuggerModel.js
@@ -17,8 +17,9 @@ /** @type {!Array<!SDK.DOMDebuggerModel.DOMBreakpoint>} */ this._domBreakpoints = []; this._domBreakpointsSetting = Common.settings.createLocalSetting('domBreakpoints', []); - if (this._domModel.existingDocument()) + if (this._domModel.existingDocument()) { this._documentUpdated(); + } } /** @@ -34,16 +35,18 @@ */ async eventListeners(remoteObject) { console.assert(remoteObject.runtimeModel() === this._runtimeModel); - if (!remoteObject.objectId) + if (!remoteObject.objectId) { return []; + } const payloads = await this._agent.getEventListeners(/** @type {string} */ (remoteObject.objectId)); const eventListeners = []; for (const payload of payloads || []) { const location = this._runtimeModel.debuggerModel().createRawLocationByScriptId( payload.scriptId, payload.lineNumber, payload.columnNumber); - if (!location) + if (!location) { continue; + } eventListeners.push(new SDK.EventListener( this, remoteObject, payload.type, payload.useCapture, payload.passive, payload.once, payload.handler ? this._runtimeModel.createRemoteObject(payload.handler) : null, @@ -110,13 +113,15 @@ * @param {boolean} enabled */ toggleDOMBreakpoint(breakpoint, enabled) { - if (enabled === breakpoint.enabled) + if (enabled === breakpoint.enabled) { return; + } breakpoint.enabled = enabled; - if (enabled) + if (enabled) { this._enableDOMBreakpoint(breakpoint); - else + } else { this._disableDOMBreakpoint(breakpoint); + } this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointToggled, breakpoint); } @@ -143,8 +148,9 @@ */ _nodeHasBreakpoints(node) { for (const breakpoint of this._domBreakpoints) { - if (breakpoint.node === node && breakpoint.enabled) + if (breakpoint.node === node && breakpoint.enabled) { return true; + } } return false; } @@ -156,8 +162,9 @@ resolveDOMBreakpointData(auxData) { const type = auxData['type']; const node = this._domModel.nodeForId(auxData['nodeId']); - if (!type || !node) + if (!type || !node) { return null; + } let targetNode = null; let insertion = false; if (type === SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified) { @@ -182,8 +189,9 @@ const currentURL = this._currentURL(); for (const breakpoint of this._domBreakpointsSetting.get()) { - if (breakpoint.url === currentURL) + if (breakpoint.url === currentURL) { this._domModel.pushNodeByPathToFrontend(breakpoint.path).then(appendBreakpoint.bind(this, breakpoint)); + } } /** @@ -193,12 +201,14 @@ */ function appendBreakpoint(breakpoint, nodeId) { const node = nodeId ? this._domModel.nodeForId(nodeId) : null; - if (!node) + if (!node) { return; + } const domBreakpoint = new SDK.DOMDebuggerModel.DOMBreakpoint(this, node, breakpoint.type, breakpoint.enabled); this._domBreakpoints.push(domBreakpoint); - if (breakpoint.enabled) + if (breakpoint.enabled) { this._enableDOMBreakpoint(domBreakpoint); + } this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointAdded, domBreakpoint); } } @@ -221,8 +231,9 @@ } } - if (!removed.length) + if (!removed.length) { return; + } this._domBreakpoints = left; this._saveDOMBreakpoints(); this.dispatchEventToListeners(SDK.DOMDebuggerModel.Events.DOMBreakpointsRemoved, removed); @@ -383,8 +394,9 @@ * @return {!Promise<undefined>} */ remove() { - if (!this.canRemove()) + if (!this.canRemove()) { return Promise.resolve(); + } if (this._origin !== SDK.EventListener.Origin.FrameworkUser) { /** @@ -396,8 +408,9 @@ */ function removeListener(type, listener, useCapture) { this.removeEventListener(type, listener, useCapture); - if (this['on' + type]) + if (this['on' + type]) { this['on' + type] = undefined; + } } return /** @type {!Promise<undefined>} */ (this._eventTarget.callFunction(removeListener, [ @@ -524,11 +537,13 @@ * @param {boolean} enabled */ setEnabled(enabled) { - if (this._enabled === enabled) + if (this._enabled === enabled) { return; + } this._enabled = enabled; - for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) + for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) { this._updateOnModel(model); + } } /** @@ -536,16 +551,18 @@ */ _updateOnModel(model) { if (this._instrumentationName) { - if (this._enabled) + if (this._enabled) { model._agent.setInstrumentationBreakpoint(this._instrumentationName); - else + } else { model._agent.removeInstrumentationBreakpoint(this._instrumentationName); + } } else { for (const eventTargetName of this._eventTargetNames) { - if (this._enabled) + if (this._enabled) { model._agent.setEventListenerBreakpoint(this._eventName, eventTargetName); - else + } else { model._agent.removeEventListenerBreakpoint(this._eventName, eventTargetName); + } } } } @@ -569,8 +586,9 @@ this._xhrBreakpointsSetting = Common.settings.createLocalSetting('xhrBreakpoints', []); /** @type {!Map<string, boolean>} */ this._xhrBreakpoints = new Map(); - for (const breakpoint of this._xhrBreakpointsSetting.get()) + for (const breakpoint of this._xhrBreakpointsSetting.get()) { this._xhrBreakpoints.set(breakpoint.url, breakpoint.enabled); + } /** @type {!Array<!SDK.DOMDebuggerModel.EventListenerBreakpoint>} */ this._eventListenerBreakpoints = []; @@ -730,14 +748,17 @@ eventTargetName = (eventTargetName || '*').toLowerCase(); let result = null; for (const breakpoint of this._eventListenerBreakpoints) { - if (instrumentationName && breakpoint._instrumentationName === instrumentationName) + if (instrumentationName && breakpoint._instrumentationName === instrumentationName) { result = breakpoint; + } if (eventName && breakpoint._eventName === eventName && - breakpoint._eventTargetNames.indexOf(eventTargetName) !== -1) + breakpoint._eventTargetNames.indexOf(eventTargetName) !== -1) { result = breakpoint; + } if (!result && eventName && breakpoint._eventName === eventName && - breakpoint._eventTargetNames.indexOf('*') !== -1) + breakpoint._eventTargetNames.indexOf('*') !== -1) { result = breakpoint; + } } return result; } @@ -761,13 +782,16 @@ errorName = errorName.replace(/^.*(0x[0-9a-f]+).*$/i, '$1'); return Common.UIString('WebGL Error Fired (%s)', errorName); } - if (id === 'instrumentation:scriptBlockedByCSP' && auxData['directiveText']) + if (id === 'instrumentation:scriptBlockedByCSP' && auxData['directiveText']) { return Common.UIString('Script blocked due to Content Security Policy directive: %s', auxData['directiveText']); + } const breakpoint = this._resolveEventListenerBreakpoint(id, auxData['targetName']); - if (!breakpoint) + if (!breakpoint) { return ''; - if (auxData['targetName']) + } + if (auxData['targetName']) { return auxData['targetName'] + '.' + breakpoint._title; + } return breakpoint._title; } @@ -788,8 +812,9 @@ _saveXHRBreakpoints() { const breakpoints = []; - for (const url of this._xhrBreakpoints.keys()) + for (const url of this._xhrBreakpoints.keys()) { breakpoints.push({url: url, enabled: this._xhrBreakpoints.get(url)}); + } this._xhrBreakpointsSetting.set(breakpoints); } @@ -800,8 +825,9 @@ addXHRBreakpoint(url, enabled) { this._xhrBreakpoints.set(url, enabled); if (enabled) { - for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) + for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) { model._agent.setXHRBreakpoint(url); + } } this._saveXHRBreakpoints(); } @@ -813,8 +839,9 @@ const enabled = this._xhrBreakpoints.get(url); this._xhrBreakpoints.delete(url); if (enabled) { - for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) + for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) { model._agent.removeXHRBreakpoint(url); + } } this._saveXHRBreakpoints(); } @@ -826,10 +853,11 @@ toggleXHRBreakpoint(url, enabled) { this._xhrBreakpoints.set(url, enabled); for (const model of SDK.targetManager.models(SDK.DOMDebuggerModel)) { - if (enabled) + if (enabled) { model._agent.setXHRBreakpoint(url); - else + } else { model._agent.removeXHRBreakpoint(url); + } } this._saveXHRBreakpoints(); } @@ -840,12 +868,14 @@ */ modelAdded(domDebuggerModel) { for (const url of this._xhrBreakpoints.keys()) { - if (this._xhrBreakpoints.get(url)) + if (this._xhrBreakpoints.get(url)) { domDebuggerModel._agent.setXHRBreakpoint(url); + } } for (const breakpoint of this._eventListenerBreakpoints) { - if (breakpoint._enabled) + if (breakpoint._enabled) { breakpoint._updateOnModel(domDebuggerModel); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js b/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js index c2e44d1..9c80dbf 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/DOMModel.js
@@ -81,8 +81,9 @@ this._attributes = []; this._attributesMap = {}; - if (payload.attributes) + if (payload.attributes) { this._setAttributesPayload(payload.attributes); + } /** @type {!Map<string, ?>} */ this._markers = new Map(); @@ -119,8 +120,9 @@ } else if ((payload.nodeName === 'IFRAME' || payload.nodeName === 'PORTAL') && payload.frameId) { const childTarget = SDK.targetManager.targetById(payload.frameId); const childModel = childTarget ? childTarget.model(SDK.DOMModel) : null; - if (childModel) + if (childModel) { this._childDocumentPromiseForTesting = childModel.requestDocument(); + } this._children = []; } @@ -130,20 +132,24 @@ this._children = []; } - if (payload.distributedNodes) + if (payload.distributedNodes) { this._setDistributedNodePayloads(payload.distributedNodes); + } - if (payload.children) + if (payload.children) { this._setChildrenPayload(payload.children); + } this._setPseudoElements(payload.pseudoElements); if (this._nodeType === Node.ELEMENT_NODE) { // HTML and BODY from internal iframes should not overwrite top-level ones. - if (this.ownerDocument && !this.ownerDocument.documentElement && this._nodeName === 'HTML') + if (this.ownerDocument && !this.ownerDocument.documentElement && this._nodeName === 'HTML') { this.ownerDocument.documentElement = this; - if (this.ownerDocument && !this.ownerDocument.body && this._nodeName === 'BODY') + } + if (this.ownerDocument && !this.ownerDocument.body && this._nodeName === 'BODY') { this.ownerDocument.body = this; + } } else if (this._nodeType === Node.DOCUMENT_TYPE_NODE) { this.publicId = payload.publicId; this.systemId = payload.systemId; @@ -165,8 +171,9 @@ * @return {!Promise<?Protocol.Runtime.StackTrace>} */ creationStackTrace() { - if (this._creationStackTrace) + if (this._creationStackTrace) { return this._creationStackTrace; + } const stackTracesPromise = this._agent.invoke_getNodeStackTraces({nodeId: this.id}); this._creationStackTrace = stackTracesPromise.then(res => res.creation); @@ -296,8 +303,9 @@ * @return {?SDK.DOMNode} */ beforePseudoElement() { - if (!this._pseudoElements) + if (!this._pseudoElements) { return null; + } return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.Before); } @@ -305,8 +313,9 @@ * @return {?SDK.DOMNode} */ afterPseudoElement() { - if (!this._pseudoElements) + if (!this._pseudoElements) { return null; + } return this._pseudoElements.get(SDK.DOMNode.PseudoElementNames.After); } @@ -344,12 +353,14 @@ * @return {?SDK.DOMNode} */ ancestorShadowRoot() { - if (!this._isInShadowTree) + if (!this._isInShadowTree) { return null; + } let current = this; - while (current && !current.isShadowRoot()) + while (current && !current.isShadowRoot()) { current = current.parentNode; + } return current; } @@ -358,8 +369,9 @@ */ ancestorUserAgentShadowRoot() { const ancestorShadowRoot = this.ancestorShadowRoot(); - if (!ancestorShadowRoot) + if (!ancestorShadowRoot) { return null; + } return ancestorShadowRoot.shadowRootType() === SDK.DOMNode.ShadowRootTypes.UserAgent ? ancestorShadowRoot : null; } @@ -382,16 +394,19 @@ */ nodeNameInCorrectCase() { const shadowRootType = this.shadowRootType(); - if (shadowRootType) + if (shadowRootType) { return '#shadow-root (' + shadowRootType + ')'; + } // If there is no local name, it's case sensitive - if (!this.localName()) + if (!this.localName()) { return this.nodeName(); + } // If the names are different lengths, there is a prefix and it's case sensitive - if (this.localName().length !== this.nodeName().length) + if (this.localName().length !== this.nodeName().length) { return this.nodeName(); + } // Return the localname, which will be case insensitive if its an html node return this.localName(); @@ -403,10 +418,12 @@ */ setNodeName(name, callback) { this._agent.invoke_setNodeName({nodeId: this.id, name}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null, this._domModel.nodeForId(response.nodeId)); + } }); } @@ -430,10 +447,12 @@ */ setNodeValue(value, callback) { this._agent.invoke_setNodeValue({nodeId: this.id, value}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null); + } }); } @@ -453,10 +472,12 @@ */ setAttribute(name, text, callback) { this._agent.invoke_setAttributesAsText({nodeId: this.id, text, name}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null); + } }); } @@ -467,10 +488,12 @@ */ setAttributeValue(name, value, callback) { this._agent.invoke_setAttributeValue({nodeId: this.id, name, value}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null); + } }); } @@ -496,12 +519,14 @@ */ async removeAttribute(name) { const response = await this._agent.invoke_removeAttribute({nodeId: this.id, name}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return; + } delete this._attributesMap[name]; const index = this._attributes.findIndex(attr => attr.name === name); - if (index !== -1) + if (index !== -1) { this._attributes.splice(index, 1); + } this._domModel.markUndoableState(); } @@ -541,10 +566,12 @@ */ setOuterHTML(html, callback) { this._agent.invoke_setOuterHTML({nodeId: this.id, outerHTML: html}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null); + } }); } @@ -553,10 +580,12 @@ */ removeNode(callback) { this._agent.invoke_removeNode({nodeId: this.id}).then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null); + } }); } @@ -565,8 +594,9 @@ */ async copyNode() { const text = await this._agent.getOuterHTML(this.id); - if (text !== null) + if (text !== null) { InspectorFrontendHost.copyText(text); + } return text; } @@ -599,13 +629,15 @@ * @return {boolean} */ isAncestor(node) { - if (!node) + if (!node) { return false; + } let currentNode = node.parentNode; while (currentNode) { - if (this === currentNode) + if (this === currentNode) { return true; + } currentNode = currentNode.parentNode; } return false; @@ -624,8 +656,9 @@ */ frameId() { let node = this.parentNode || this; - while (!node._frameOwnerFrameId && node.parentNode) + while (!node._frameOwnerFrameId && node.parentNode) { node = node.parentNode; + } return node._frameOwnerFrameId; } @@ -645,11 +678,13 @@ const value = attrs[i + 1]; this._addAttribute(name, value); - if (attributesChanged) + if (attributesChanged) { continue; + } - if (!oldAttributesMap[name] || oldAttributesMap[name].value !== value) + if (!oldAttributesMap[name] || oldAttributesMap[name].value !== value) { attributesChanged = true; + } } return attributesChanged; } @@ -683,8 +718,9 @@ } node.parentNode = null; this._subtreeMarkerCount -= node._subtreeMarkerCount; - if (node._subtreeMarkerCount) + if (node._subtreeMarkerCount) { this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged, this); + } this._renumber(); } @@ -706,8 +742,9 @@ */ _setPseudoElements(payloads) { this._pseudoElements = new Map(); - if (!payloads) + if (!payloads) { return; + } for (let i = 0; i < payloads.length; ++i) { const node = SDK.DOMNode.create(this._domModel, this.ownerDocument, this._isInShadowTree, payloads[i]); @@ -761,10 +798,11 @@ */ _setAttribute(name, value) { const attr = this._attributesMap[name]; - if (attr) + if (attr) { attr.value = value; - else + } else { this._addAttribute(name, value); + } } /** @@ -788,10 +826,12 @@ .invoke_copyTo( {nodeId: this.id, targetNodeId: targetNode.id, insertBeforeNodeId: anchorNode ? anchorNode.id : undefined}) .then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null, response.nodeId); + } }); } @@ -805,10 +845,12 @@ .invoke_moveTo( {nodeId: this.id, targetNodeId: targetNode.id, insertBeforeNodeId: anchorNode ? anchorNode.id : undefined}) .then(response => { - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._domModel.markUndoableState(); - if (callback) + } + if (callback) { callback(response[Protocol.Error] || null, this._domModel.nodeForId(response.nodeId)); + } }); } @@ -825,24 +867,29 @@ */ setMarker(name, value) { if (value === null) { - if (!this._markers.has(name)) + if (!this._markers.has(name)) { return; + } this._markers.delete(name); - for (let node = this; node; node = node.parentNode) + for (let node = this; node; node = node.parentNode) { --node._subtreeMarkerCount; - for (let node = this; node; node = node.parentNode) + } + for (let node = this; node; node = node.parentNode) { this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged, node); + } return; } if (this.parentNode && !this._markers.has(name)) { - for (let node = this; node; node = node.parentNode) + for (let node = this; node; node = node.parentNode) { ++node._subtreeMarkerCount; + } } this._markers.set(name, value); - for (let node = this; node; node = node.parentNode) + for (let node = this; node; node = node.parentNode) { this._domModel.dispatchEventToListeners(SDK.DOMModel.Events.MarkersChanged, node); + } } /** @@ -862,14 +909,18 @@ * @param {!SDK.DOMNode} node */ function traverse(node) { - if (!node._subtreeMarkerCount) + if (!node._subtreeMarkerCount) { return; - for (const marker of node._markers.keys()) + } + for (const marker of node._markers.keys()) { visitor(node, marker); - if (!node._children) + } + if (!node._children) { return; - for (const child of node._children) + } + for (const child of node._children) { traverse(child); + } } traverse(this); } @@ -879,11 +930,13 @@ * @return {?string} */ resolveURL(url) { - if (!url) + if (!url) { return url; + } for (let frameOwnerCandidate = this; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) { - if (frameOwnerCandidate.baseURL) + if (frameOwnerCandidate.baseURL) { return Common.ParsedURL.completeURL(frameOwnerCandidate.baseURL, url); + } } return null; } @@ -919,11 +972,13 @@ let node = this; while (true) { let ancestor = node.ancestorUserAgentShadowRoot(); - if (!ancestor) + if (!ancestor) { break; + } ancestor = node.ancestorShadowHost(); - if (!ancestor) + if (!ancestor) { break; + } // User agent shadow root, keep climbing up. node = ancestor; } @@ -935,19 +990,22 @@ */ enclosingElementOrSelf() { let node = this; - if (node && node.nodeType() === Node.TEXT_NODE && node.parentNode) + if (node && node.nodeType() === Node.TEXT_NODE && node.parentNode) { node = node.parentNode; + } - if (node && node.nodeType() !== Node.ELEMENT_NODE) + if (node && node.nodeType() !== Node.ELEMENT_NODE) { node = null; + } return node; } async scrollIntoView() { const node = this.enclosingElementOrSelf(); const object = await node.resolveToObject(); - if (!object) + if (!object) { return; + } object.callFunction(scrollIntoView); object.release(); node.highlightForTwoSeconds(); @@ -964,8 +1022,9 @@ async focus() { const node = this.enclosingElementOrSelf(); const object = await node.resolveToObject(); - if (!object) + if (!object) { return; + } await object.callFunction(focusInPage); object.release(); node.highlightForTwoSeconds(); @@ -985,13 +1044,16 @@ */ simpleSelector() { const lowerCaseName = this.localName() || this.nodeName().toLowerCase(); - if (this.nodeType() !== Node.ELEMENT_NODE) + if (this.nodeType() !== Node.ELEMENT_NODE) { return lowerCaseName; + } if (lowerCaseName === 'input' && this.getAttribute('type') && !this.getAttribute('id') && - !this.getAttribute('class')) + !this.getAttribute('class')) { return lowerCaseName + '[type="' + this.getAttribute('type') + '"]'; - if (this.getAttribute('id')) + } + if (this.getAttribute('id')) { return lowerCaseName + '#' + this.getAttribute('id'); + } if (this.getAttribute('class')) { return (lowerCaseName === 'div' ? '' : lowerCaseName) + '.' + this.getAttribute('class').trim().replace(/\s+/g, '.'); @@ -1122,11 +1184,13 @@ this._runtimeModel = /** @type {!SDK.RuntimeModel} */ (target.model(SDK.RuntimeModel)); - if (!target.suspended()) + if (!target.suspended()) { this._agent.enable(); + } - if (Runtime.experiments.isEnabled('captureNodeCreationStacks')) + if (Runtime.experiments.isEnabled('captureNodeCreationStacks')) { this._agent.setNodeStackTracesEnabled(true); + } } /** @@ -1151,16 +1215,18 @@ } static cancelSearch() { - for (const domModel of SDK.targetManager.models(SDK.DOMModel)) + for (const domModel of SDK.targetManager.models(SDK.DOMModel)) { domModel._cancelSearch(); + } } /** * @param {!SDK.DOMNode} node */ _scheduleMutationEvent(node) { - if (!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)) + if (!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated)) { return; + } this._lastMutationId = (this._lastMutationId || 0) + 1; Promise.resolve().then(callObserve.bind(this, node, this._lastMutationId)); @@ -1171,8 +1237,9 @@ * @param {number} mutationId */ function callObserve(node, mutationId) { - if (!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated) || this._lastMutationId !== mutationId) + if (!this.hasEventListeners(SDK.DOMModel.Events.DOMMutated) || this._lastMutationId !== mutationId) { return; + } this.dispatchEventToListeners(SDK.DOMModel.Events.DOMMutated, node); } @@ -1182,10 +1249,12 @@ * @return {!Promise<!SDK.DOMDocument>} */ requestDocument() { - if (this._document) + if (this._document) { return Promise.resolve(this._document); - if (!this._pendingDocumentRequestPromise) + } + if (!this._pendingDocumentRequestPromise) { this._pendingDocumentRequestPromise = this._requestDocument(); + } return this._pendingDocumentRequestPromise; } @@ -1196,8 +1265,9 @@ const documentPayload = await this._agent.getDocument(); delete this._pendingDocumentRequestPromise; - if (documentPayload) + if (documentPayload) { this._setDocument(documentPayload); + } if (!this._document) { console.error('No document'); return null; @@ -1207,8 +1277,9 @@ if (parentModel && !this._frameOwnerNode) { await parentModel.requestDocument(); const response = await parentModel._agent.invoke_getFrameOwner({frameId: this.target().id()}); - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._frameOwnerNode = parentModel.nodeForId(response.nodeId); + } } // Document could have been cleared by now. @@ -1260,13 +1331,15 @@ await this.requestDocument(); const backendNodeIdsArray = backendNodeIds.valuesArray(); const nodeIds = await this._agent.pushNodesByBackendIdsToFrontend(backendNodeIdsArray); - if (!nodeIds) + if (!nodeIds) { return null; + } /** @type {!Map<number, ?SDK.DOMNode>} */ const map = new Map(); for (let i = 0; i < nodeIds.length; ++i) { - if (nodeIds[i]) + if (nodeIds[i]) { map.set(backendNodeIdsArray[i], this.nodeForId(nodeIds[i])); + } } return map; } @@ -1296,8 +1369,9 @@ */ _attributeModified(nodeId, name, value) { const node = this._idToDOMNode[nodeId]; - if (!node) + if (!node) { return; + } node._setAttribute(name, value); this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified, {node: node, name: name}); @@ -1310,8 +1384,9 @@ */ _attributeRemoved(nodeId, name) { const node = this._idToDOMNode[nodeId]; - if (!node) + if (!node) { return; + } node._removeAttribute(name); this.dispatchEventToListeners(SDK.DOMModel.Events.AttrRemoved, {node: node, name: name}); this._scheduleMutationEvent(node); @@ -1322,8 +1397,9 @@ */ _inlineStyleInvalidated(nodeIds) { this._attributeLoadNodeIds.addAll(nodeIds); - if (!this._loadNodeAttributesTimeout) + if (!this._loadNodeAttributesTimeout) { this._loadNodeAttributesTimeout = setTimeout(this._loadNodeAttributes.bind(this), 20); + } } _loadNodeAttributes() { @@ -1335,8 +1411,9 @@ return; } const node = this._idToDOMNode[nodeId]; - if (!node) + if (!node) { return; + } if (node._setAttributesPayload(attributes)) { this.dispatchEventToListeners(SDK.DOMModel.Events.AttrModified, {node: node, name: 'style'}); this._scheduleMutationEvent(node); @@ -1370,8 +1447,9 @@ // if it hits backend post document update, it will contain most recent result. const documentWasRequested = this._document || this._pendingDocumentRequestPromise; this._setDocument(null); - if (this.parentModel() && documentWasRequested) + if (this.parentModel() && documentWasRequested) { this.requestDocument(); + } } /** @@ -1379,24 +1457,27 @@ */ _setDocument(payload) { this._idToDOMNode = {}; - if (payload && 'nodeId' in payload) + if (payload && 'nodeId' in payload) { this._document = new SDK.DOMDocument(this, payload); - else + } else { this._document = null; + } SDK.domModelUndoStack._dispose(this); - if (!this.parentModel()) + if (!this.parentModel()) { this.dispatchEventToListeners(SDK.DOMModel.Events.DocumentUpdated, this); + } } /** * @param {!Protocol.DOM.Node} payload */ _setDetachedRoot(payload) { - if (payload.nodeName === '#document') + if (payload.nodeName === '#document') { new SDK.DOMDocument(this, payload); - else + } else { SDK.DOMNode.create(this, null, false, payload); + } } /** @@ -1457,8 +1538,9 @@ */ _shadowRootPushed(hostId, root) { const host = this._idToDOMNode[hostId]; - if (!host) + if (!host) { return; + } const node = SDK.DOMNode.create(this, host.ownerDocument, true, root); node.parentNode = host; this._idToDOMNode[node.id] = node; @@ -1473,11 +1555,13 @@ */ _shadowRootPopped(hostId, rootId) { const host = this._idToDOMNode[hostId]; - if (!host) + if (!host) { return; + } const root = this._idToDOMNode[rootId]; - if (!root) + if (!root) { return; + } host._removeChild(root); this._unbind(root); this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved, {node: root, parent: host}); @@ -1490,8 +1574,9 @@ */ _pseudoElementAdded(parentId, pseudoElement) { const parent = this._idToDOMNode[parentId]; - if (!parent) + if (!parent) { return; + } const node = SDK.DOMNode.create(this, parent.ownerDocument, false, pseudoElement); node.parentNode = parent; this._idToDOMNode[node.id] = node; @@ -1507,11 +1592,13 @@ */ _pseudoElementRemoved(parentId, pseudoElementId) { const parent = this._idToDOMNode[parentId]; - if (!parent) + if (!parent) { return; + } const pseudoElement = this._idToDOMNode[pseudoElementId]; - if (!pseudoElement) + if (!pseudoElement) { return; + } parent._removeChild(pseudoElement); this._unbind(pseudoElement); this.dispatchEventToListeners(SDK.DOMModel.Events.NodeRemoved, {node: pseudoElement, parent: parent}); @@ -1524,8 +1611,9 @@ */ _distributedNodesUpdated(insertionPointId, distributedNodes) { const insertionPoint = this._idToDOMNode[insertionPointId]; - if (!insertionPoint) + if (!insertionPoint) { return; + } insertionPoint._setDistributedNodePayloads(distributedNodes); this.dispatchEventToListeners(SDK.DOMModel.Events.DistributedNodesChanged, insertionPoint); this._scheduleMutationEvent(insertionPoint); @@ -1536,15 +1624,19 @@ */ _unbind(node) { delete this._idToDOMNode[node.id]; - for (let i = 0; node._children && i < node._children.length; ++i) + for (let i = 0; node._children && i < node._children.length; ++i) { this._unbind(node._children[i]); - for (let i = 0; i < node._shadowRoots.length; ++i) + } + for (let i = 0; i < node._shadowRoots.length; ++i) { this._unbind(node._shadowRoots[i]); + } const pseudoElements = node.pseudoElements(); - for (const value of pseudoElements.values()) + for (const value of pseudoElements.values()) { this._unbind(value); - if (node._templateContent) + } + if (node._templateContent) { this._unbind(node._templateContent); + } } /** @@ -1554,8 +1646,9 @@ */ async performSearch(query, includeUserAgentShadowDOM) { const response = await this._agent.invoke_performSearch({query, includeUserAgentShadowDOM}); - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this._searchId = response.searchId; + } return response[Protocol.Error] ? 0 : response.resultCount; } @@ -1564,15 +1657,17 @@ * @return {!Promise<?SDK.DOMNode>} */ async searchResult(index) { - if (!this._searchId) + if (!this._searchId) { return null; + } const nodeIds = await this._agent.getSearchResults(this._searchId, index, index + 1); return nodeIds && nodeIds.length === 1 ? this.nodeForId(nodeIds[0]) : null; } _cancelSearch() { - if (!this._searchId) + if (!this._searchId) { return; + } this._agent.discardSearchResults(this._searchId); delete this._searchId; } @@ -1618,8 +1713,9 @@ */ async nodeForLocation(x, y, includeUserAgentShadowDOM) { const response = await this._agent.invoke_getNodeForLocation({x, y, includeUserAgentShadowDOM}); - if (response[Protocol.Error] || !response.nodeId) + if (response[Protocol.Error] || !response.nodeId) { return null; + } return this.nodeForId(response.nodeId); } @@ -1840,8 +1936,9 @@ } // Previous minor change is already in the stack. - if (minorChange && this._lastModelWithMinorChange === model) + if (minorChange && this._lastModelWithMinorChange === model) { return; + } this._stack = this._stack.slice(0, this._index); this._stack.push(model); @@ -1861,8 +1958,9 @@ * @return {!Promise} */ undo() { - if (this._index === 0) + if (this._index === 0) { return Promise.resolve(); + } --this._index; this._lastModelWithMinorChange = null; return this._stack[this._index]._agent.undo(); @@ -1872,8 +1970,9 @@ * @return {!Promise} */ redo() { - if (this._index >= this._stack.length) + if (this._index >= this._stack.length) { return Promise.resolve(); + } ++this._index; this._lastModelWithMinorChange = null; return this._stack[this._index - 1]._agent.redo(); @@ -1885,13 +1984,15 @@ _dispose(model) { let shift = 0; for (let i = 0; i < this._index; ++i) { - if (this._stack[i] === model) + if (this._stack[i] === model) { ++shift; + } } this._stack.remove(model); this._index -= shift; - if (this._lastModelWithMinorChange === model) + if (this._lastModelWithMinorChange === model) { this._lastModelWithMinorChange = null; + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js b/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js index 7f173189..c577767 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/DebuggerModel.js
@@ -65,8 +65,9 @@ Common.moduleSetting('disableAsyncStackTraces').addChangeListener(this._asyncStackTracesStateChanged, this); Common.moduleSetting('breakpointsActive').addChangeListener(this._breakpointsActiveChanged, this); - if (!target.suspended()) + if (!target.suspended()) { this._enableDebugger(); + } /** @type {!Map<string, string>} */ this._stringMap = new Map(); @@ -82,8 +83,9 @@ * @return {?string} */ static _sourceMapId(executionContextId, sourceURL, sourceMapURL) { - if (!sourceMapURL) + if (!sourceMapURL) { return null; + } return executionContextId + ':' + sourceURL + ':' + sourceMapURL; } @@ -112,8 +114,9 @@ * @return {!Promise} */ _enableDebugger() { - if (this._debuggerEnabled) + if (this._debuggerEnabled) { return Promise.resolve(); + } this._debuggerEnabled = true; // Set a limit for the total size of collected script sources retained by debugger. @@ -124,10 +127,12 @@ enablePromise.then(this._registerDebugger.bind(this)); this._pauseOnExceptionStateChanged(); this._asyncStackTracesStateChanged(); - if (!Common.moduleSetting('breakpointsActive').get()) + if (!Common.moduleSetting('breakpointsActive').get()) { this._breakpointsActiveChanged(); - if (SDK.DebuggerModel._scheduledPauseOnAsyncCall) + } + if (SDK.DebuggerModel._scheduledPauseOnAsyncCall) { this._pauseOnAsyncCall(SDK.DebuggerModel._scheduledPauseOnAsyncCall); + } this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerWasEnabled, this); return enablePromise; } @@ -136,8 +141,9 @@ * @param {string|null} debuggerId */ _registerDebugger(debuggerId) { - if (!debuggerId) + if (!debuggerId) { return; + } SDK.DebuggerModel._debuggerIdToModel.set(debuggerId, this); this._debuggerId = debuggerId; this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerIsReadyToPause, this); @@ -162,8 +168,9 @@ * @return {!Promise} */ _disableDebugger() { - if (!this._debuggerEnabled) + if (!this._debuggerEnabled) { return Promise.resolve(); + } this._debuggerEnabled = false; const disablePromise = this._agent.disable(); @@ -190,8 +197,9 @@ * @param {number} timeout */ skipAllPausesUntilReloadOrTimeout(timeout) { - if (this._skipAllPausesTimeout) + if (this._skipAllPausesTimeout) { clearTimeout(this._skipAllPausesTimeout); + } this._agent.setSkipAllPauses(true); // If reload happens before the timeout, the flag will be already unset and the timeout callback won't change anything. this._skipAllPausesTimeout = setTimeout(this._skipAllPauses.bind(this, false), timeout); @@ -199,12 +207,13 @@ _pauseOnExceptionStateChanged() { let state; - if (!Common.moduleSetting('pauseOnExceptionEnabled').get()) + if (!Common.moduleSetting('pauseOnExceptionEnabled').get()) { state = SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions; - else if (Common.moduleSetting('pauseOnCaughtException').get()) + } else if (Common.moduleSetting('pauseOnCaughtException').get()) { state = SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions; - else + } else { state = SDK.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions; + } this._agent.setPauseOnExceptions(state); } @@ -273,8 +282,9 @@ const scripts = this._scriptsBySourceURL.get(url) || []; for (let i = 0, l = scripts.length; i < l; ++i) { const script = scripts[i]; - if (lineNumber === script.lineOffset) + if (lineNumber === script.lineOffset) { minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset; + } } columnNumber = Math.max(columnNumber, minColumnNumber); const response = await this._agent.invoke_setBreakpointByUrl({ @@ -284,11 +294,13 @@ columnNumber: columnNumber, condition: condition }); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return {locations: [], breakpointId: null}; + } let locations = []; - if (response.locations) + if (response.locations) { locations = response.locations.map(payload => SDK.DebuggerModel.Location.fromPayload(this, payload)); + } return {locations: locations, breakpointId: response.breakpointId}; } @@ -306,13 +318,15 @@ const error = response[Protocol.Error]; if (error) { // Old V8 backend doesn't support scriptHash argument. - if (error !== 'Either url or urlRegex must be specified.') + if (error !== 'Either url or urlRegex must be specified.') { return {locations: [], breakpointId: null}; + } return this._setBreakpointBySourceId(scriptId, lineNumber, columnNumber, condition); } let locations = []; - if (response.locations) + if (response.locations) { locations = response.locations.map(payload => SDK.DebuggerModel.Location.fromPayload(this, payload)); + } return {locations: locations, breakpointId: response.breakpointId}; } @@ -327,11 +341,13 @@ // This method is required for backward compatibility with V8 before 6.3.275. const response = await this._agent.invoke_setBreakpoint( {location: {scriptId: scriptId, lineNumber: lineNumber, columnNumber: columnNumber}, condition: condition}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return {breakpointId: null, locations: []}; + } let actualLocation = []; - if (response.actualLocation) + if (response.actualLocation) { actualLocation = [SDK.DebuggerModel.Location.fromPayload(this, response.actualLocation)]; + } return {locations: actualLocation, breakpointId: response.breakpointId}; } @@ -341,8 +357,9 @@ */ async removeBreakpoint(breakpointId) { const response = await this._agent.invoke_removeBreakpoint({breakpointId}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { console.error('Failed to remove breakpoint: ' + response[Protocol.Error]); + } } /** @@ -357,8 +374,9 @@ end: endLocation ? endLocation.payload() : undefined, restrictToFunction: restrictToFunction }); - if (response[Protocol.Error] || !response.locations) + if (response[Protocol.Error] || !response.locations) { return []; + } return response.locations.map(location => SDK.DebuggerModel.BreakLocation.fromPayload(this, location)); } @@ -388,8 +406,9 @@ } _reset() { - for (const scriptWithSourceMap of this._sourceMapIdToScript.values()) + for (const scriptWithSourceMap of this._sourceMapIdToScript.values()) { this._sourceMapManager.detachSourceMap(scriptWithSourceMap); + } this._sourceMapIdToScript.clear(); this._scripts.clear(); @@ -417,8 +436,9 @@ * @return {!Array.<!SDK.Script>} */ scriptsForSourceURL(sourceURL) { - if (!sourceURL) + if (!sourceURL) { return []; + } return this._scriptsBySourceURL.get(sourceURL) || []; } @@ -429,8 +449,9 @@ scriptsForExecutionContext(executionContext) { const result = []; for (const script of this._scripts.values()) { - if (script.executionContextId === executionContext.id) + if (script.executionContextId === executionContext.id) { result.push(script); + } } return result; } @@ -495,15 +516,17 @@ this._debuggerPausedDetails = debuggerPausedDetails; if (this._debuggerPausedDetails) { if (Runtime.experiments.isEnabled('emptySourceMapAutoStepping') && this._beforePausedCallback) { - if (!this._beforePausedCallback.call(null, this._debuggerPausedDetails)) + if (!this._beforePausedCallback.call(null, this._debuggerPausedDetails)) { return false; + } } this.dispatchEventToListeners(SDK.DebuggerModel.Events.DebuggerPaused, this); } - if (debuggerPausedDetails) + if (debuggerPausedDetails) { this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]); - else + } else { this.setSelectedCallFrame(null); + } return true; } @@ -529,8 +552,9 @@ // Note: this is only to support old backends. Newer ones do not send asyncCallStackTraceId. SDK.DebuggerModel._scheduledPauseOnAsyncCall = asyncCallStackTraceId; const promises = []; - for (const model of SDK.DebuggerModel._debuggerIdToModel.values()) + for (const model of SDK.DebuggerModel._debuggerIdToModel.values()) { promises.push(model._pauseOnAsyncCall(asyncCallStackTraceId)); + } await Promise.all(promises); this.resume(); return; @@ -542,12 +566,14 @@ if (pausedDetails && this._continueToLocationCallback) { const callback = this._continueToLocationCallback; delete this._continueToLocationCallback; - if (callback(pausedDetails)) + if (callback(pausedDetails)) { return; + } } - if (!this._setDebuggerPausedDetails(pausedDetails)) + if (!this._setDebuggerPausedDetails(pausedDetails)) { this._agent.stepInto(); + } SDK.DebuggerModel._scheduledPauseOnAsyncCall = null; } @@ -579,11 +605,13 @@ scriptId, sourceURL, startLine, startColumn, endLine, endColumn, executionContextId, hash, executionContextAuxData, isLiveEdit, sourceMapURL, hasSourceURLComment, hasSyntaxError, length, originStackTrace) { - if (this._scripts.has(scriptId)) + if (this._scripts.has(scriptId)) { return this._scripts.get(scriptId); + } let isContentScript = false; - if (executionContextAuxData && ('isDefault' in executionContextAuxData)) + if (executionContextAuxData && ('isDefault' in executionContextAuxData)) { isContentScript = !executionContextAuxData['isDefault']; + } sourceURL = this._internString(sourceURL); const script = new SDK.Script( this, scriptId, sourceURL, startLine, startColumn, endLine, endColumn, executionContextId, @@ -598,8 +626,9 @@ // Consecutive script evaluations in the same execution context with the same sourceURL // and sourceMappingURL should result in source map reloading. const previousScript = this._sourceMapIdToScript.get(sourceMapId); - if (previousScript) + if (previousScript) { this._sourceMapManager.detachSourceMap(previousScript); + } this._sourceMapIdToScript.set(sourceMapId, script); this._sourceMapManager.attachSourceMap(script, script.sourceURL, script.sourceMapURL); } @@ -618,14 +647,16 @@ */ setSourceMapURL(script, newSourceMapURL) { let sourceMapId = SDK.DebuggerModel._sourceMapId(script.executionContextId, script.sourceURL, script.sourceMapURL); - if (sourceMapId && this._sourceMapIdToScript.get(sourceMapId) === script) + if (sourceMapId && this._sourceMapIdToScript.get(sourceMapId) === script) { this._sourceMapIdToScript.delete(sourceMapId); + } this._sourceMapManager.detachSourceMap(script); script.sourceMapURL = newSourceMapURL; sourceMapId = SDK.DebuggerModel._sourceMapId(script.executionContextId, script.sourceURL, script.sourceMapURL); - if (!sourceMapId) + if (!sourceMapId) { return; + } this._sourceMapIdToScript.set(sourceMapId, script); this._sourceMapManager.attachSourceMap(script, script.sourceURL, script.sourceMapURL); } @@ -649,8 +680,9 @@ */ _registerScript(script) { this._scripts.set(script.scriptId, script); - if (script.isAnonymousScript()) + if (script.isAnonymousScript()) { return; + } let scripts = this._scriptsBySourceURL.get(script.sourceURL); if (!scripts) { @@ -669,8 +701,9 @@ } _collectDiscardedScripts() { - if (this._discardableScripts.length < 1000) + if (this._discardableScripts.length < 1000) { return; + } const scriptsToDiscard = this._discardableScripts.splice(0, 100); for (const script of scriptsToDiscard) { this._unregisterScript(script); @@ -699,12 +732,15 @@ const scripts = this._scriptsBySourceURL.get(sourceURL) || []; for (let i = 0, l = scripts.length; i < l; ++i) { const script = scripts[i]; - if (!closestScript) + if (!closestScript) { closestScript = script; - if (script.lineOffset > lineNumber || (script.lineOffset === lineNumber && script.columnOffset > columnNumber)) + } + if (script.lineOffset > lineNumber || (script.lineOffset === lineNumber && script.columnOffset > columnNumber)) { continue; - if (script.endLine < lineNumber || (script.endLine === lineNumber && script.endColumn <= columnNumber)) + } + if (script.endLine < lineNumber || (script.endLine === lineNumber && script.endColumn <= columnNumber)) { continue; + } closestScript = script; break; } @@ -730,16 +766,18 @@ createRawLocationsByStackTrace(stackTrace) { const frames = []; while (stackTrace) { - for (const frame of stackTrace.callFrames) + for (const frame of stackTrace.callFrames) { frames.push(frame); + } stackTrace = stackTrace.parent; } const rawLocations = []; for (const frame of frames) { const rawLocation = this.createRawLocationByScriptId(frame.scriptId, frame.lineNumber, frame.columnNumber); - if (rawLocation) + if (rawLocation) { rawLocations.push(rawLocation); + } } return rawLocations; } @@ -762,8 +800,9 @@ * @param {?SDK.DebuggerModel.CallFrame} callFrame */ setSelectedCallFrame(callFrame) { - if (this._selectedCallFrame === callFrame) + if (this._selectedCallFrame === callFrame) { return; + } this._selectedCallFrame = callFrame; this.dispatchEventToListeners(SDK.DebuggerModel.Events.CallFrameSelected, this); } @@ -797,20 +836,23 @@ * @this {!SDK.DebuggerModel} */ function buildDetails(response) { - if (!response) + if (!response) { return null; + } let location = null; if (response.internalProperties) { for (const prop of response.internalProperties) { - if (prop.name === '[[FunctionLocation]]') + if (prop.name === '[[FunctionLocation]]') { location = prop.value; + } } } let functionName = null; if (response.properties) { for (const prop of response.properties) { - if (prop.name === 'name' && prop.value && prop.value.type === 'string') + if (prop.name === 'name' && prop.value && prop.value.type === 'string') { functionName = prop.value; + } if (prop.name === 'displayName' && prop.value && prop.value.type === 'string') { functionName = prop.value; break; @@ -836,8 +878,9 @@ async setVariableValue(scopeNumber, variableName, newValue, callFrameId) { const response = await this._agent.invoke_setVariableValue({scopeNumber, variableName, newValue, callFrameId}); const error = response[Protocol.Error]; - if (error) + if (error) { console.error(error); + } return error; } @@ -866,8 +909,9 @@ async setBlackboxPatterns(patterns) { const response = await this._agent.invoke_setBlackboxPatterns({patterns}); const error = response[Protocol.Error]; - if (error) + if (error) { console.error(error); + } return !error; } @@ -903,8 +947,9 @@ * @return {string} string */ _internString(string) { - if (!this._stringMap.has(string)) + if (!this._stringMap.has(string)) { this._stringMap.set(string, string); + } return this._stringMap.get(string); } }; @@ -1123,8 +1168,9 @@ * @param {function()=} pausedCallback */ continueToLocation(pausedCallback) { - if (pausedCallback) + if (pausedCallback) { this.debuggerModel._continueToLocationCallback = this._paused.bind(this, pausedCallback); + } this.debuggerModel._agent.continueToLocation( this.payload(), SDK.DebuggerModel.ContinueToLocationTargetCallFrames.Current); } @@ -1165,8 +1211,9 @@ */ constructor(debuggerModel, scriptId, lineNumber, columnNumber, type) { super(debuggerModel, scriptId, lineNumber, columnNumber); - if (type) + if (type) { this.type = type; + } } /** @@ -1200,11 +1247,13 @@ for (let i = 0; i < payload.scopeChain.length; ++i) { const scope = new SDK.DebuggerModel.Scope(this, i); this._scopeChain.push(scope); - if (scope.type() === Protocol.Debugger.ScopeType.Local) + if (scope.type() === Protocol.Debugger.ScopeType.Local) { this._localScope = scope; + } } - if (payload.functionLocation) + if (payload.functionLocation) { this._functionLocation = SDK.DebuggerModel.Location.fromPayload(debuggerModel, payload.functionLocation); + } this._returnValue = payload.returnValue ? this.debuggerModel._runtimeModel.createRemoteObject(payload.returnValue) : null; } @@ -1219,8 +1268,9 @@ for (let i = 0; i < callFrames.length; ++i) { const callFrame = callFrames[i]; const script = debuggerModel.scriptForId(callFrame.location.scriptId); - if (script) + if (script) { result.push(new SDK.DebuggerModel.CallFrame(debuggerModel, script, callFrame)); + } } return result; } @@ -1272,16 +1322,19 @@ * @return {!Promise<?SDK.RemoteObject>} */ async setReturnValue(expression) { - if (!this._returnValue) + if (!this._returnValue) { return null; + } const evaluateResponse = await this.debuggerModel._agent.invoke_evaluateOnCallFrame( {callFrameId: this.id, expression: expression, silent: true, objectGroup: 'backtrace'}); - if (evaluateResponse[Protocol.Error] || evaluateResponse.exceptionDetails) + if (evaluateResponse[Protocol.Error] || evaluateResponse.exceptionDetails) { return null; + } const response = await this.debuggerModel._agent.invoke_setReturnValue({newValue: evaluateResponse.result}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return null; + } this._returnValue = this.debuggerModel._runtimeModel.createRemoteObject(evaluateResponse.result); return this._returnValue; } @@ -1317,8 +1370,9 @@ const needsTerminationOptions = !!options.throwOnSideEffect || options.timeout !== undefined; if (needsTerminationOptions && (runtimeModel.hasSideEffectSupport() === false || - (runtimeModel.hasSideEffectSupport() === null && !await runtimeModel.checkSideEffectSupport()))) + (runtimeModel.hasSideEffectSupport() === null && !await runtimeModel.checkSideEffectSupport()))) { return {error: 'Side-effect checks not supported by backend.'}; + } const response = await this.debuggerModel._agent.invoke_evaluateOnCallFrame({ callFrameId: this.id, @@ -1341,8 +1395,9 @@ async restart() { const response = await this.debuggerModel._agent.invoke_restartFrame({callFrameId: this._payload.callFrameId}); - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { this.debuggerModel.stepInto(); + } } }; @@ -1434,8 +1489,9 @@ * @return {!SDK.RemoteObject} */ object() { - if (this._object) + if (this._object) { return this._object; + } const runtimeModel = this._callFrame.debuggerModel._runtimeModel; const declarativeScope = @@ -1479,8 +1535,9 @@ this.reason = reason; this.auxData = auxData; this.breakpointIds = breakpointIds; - if (asyncStackTrace) + if (asyncStackTrace) { this.asyncStackTrace = this._cleanRedundantFrames(asyncStackTrace); + } this.asyncStackTraceId = asyncStackTraceId; } @@ -1489,8 +1546,9 @@ */ exception() { if (this.reason !== SDK.DebuggerModel.BreakReason.Exception && - this.reason !== SDK.DebuggerModel.BreakReason.PromiseRejection) + this.reason !== SDK.DebuggerModel.BreakReason.PromiseRejection) { return null; + } return this.debuggerModel._runtimeModel.createRemoteObject( /** @type {!Protocol.Runtime.RemoteObject} */ (this.auxData)); } @@ -1503,12 +1561,14 @@ let stack = asyncStackTrace; let previous = null; while (stack) { - if (stack.description === 'async function' && stack.callFrames.length) + if (stack.description === 'async function' && stack.callFrames.length) { stack.callFrames.shift(); - if (previous && !stack.callFrames.length) + } + if (previous && !stack.callFrames.length) { previous.parent = stack.parent; - else + } else { previous = stack; + } stack = stack.parent; } return asyncStackTrace;
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/EmulationModel.js b/third_party/blink/renderer/devtools/front_end/sdk/EmulationModel.js index 9e788d1c..02f50a6 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/EmulationModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/EmulationModel.js
@@ -13,19 +13,22 @@ this._deviceOrientationAgent = target.deviceOrientationAgent(); this._cssModel = target.model(SDK.CSSModel); this._overlayModel = target.model(SDK.OverlayModel); - if (this._overlayModel) + if (this._overlayModel) { this._overlayModel.addEventListener(SDK.OverlayModel.Events.InspectModeWillBeToggled, this._updateTouch, this); + } const disableJavascriptSetting = Common.settings.moduleSetting('javaScriptDisabled'); disableJavascriptSetting.addChangeListener( () => this._emulationAgent.setScriptExecutionDisabled(disableJavascriptSetting.get())); - if (disableJavascriptSetting.get()) + if (disableJavascriptSetting.get()) { this._emulationAgent.setScriptExecutionDisabled(true); + } const mediaSetting = Common.moduleSetting('emulatedCSSMedia'); mediaSetting.addChangeListener(() => this._emulateCSSMedia(mediaSetting.get())); - if (mediaSetting.get()) + if (mediaSetting.get()) { this._emulateCSSMedia(mediaSetting.get()); + } this._touchEnabled = false; this._touchMobile = false; @@ -52,10 +55,11 @@ * @return {!Promise} */ emulateDevice(metrics) { - if (metrics) + if (metrics) { return this._emulationAgent.invoke_setDeviceMetricsOverride(metrics); - else + } else { return this._emulationAgent.clearDeviceMetricsOverride(); + } } /** @@ -99,8 +103,9 @@ */ _emulateCSSMedia(media) { this._emulationAgent.setEmulatedMedia(media); - if (this._cssModel) + if (this._cssModel) { this._cssModel.mediaQueryResultChanged(); + } } /** @@ -133,17 +138,21 @@ enabled: this._touchEnabled, configuration: this._touchMobile ? 'mobile' : 'desktop', }; - if (this._customTouchEnabled) + if (this._customTouchEnabled) { configuration = {enabled: true, configuration: 'mobile'}; + } - if (this._overlayModel && this._overlayModel.inspectModeEnabled()) + if (this._overlayModel && this._overlayModel.inspectModeEnabled()) { configuration = {enabled: false, configuration: 'mobile'}; + } - if (!this._touchConfiguration.enabled && !configuration.enabled) + if (!this._touchConfiguration.enabled && !configuration.enabled) { return; + } if (this._touchConfiguration.enabled && configuration.enabled && - this._touchConfiguration.configuration === configuration.configuration) + this._touchConfiguration.configuration === configuration.configuration) { return; + } this._touchConfiguration = configuration; this._emulationAgent.setTouchEmulationEnabled(configuration.enabled, 1); @@ -189,14 +198,16 @@ * @return {?SDK.EmulationModel.Geolocation} */ static parseUserInput(latitudeString, longitudeString, errorStatus) { - if (!latitudeString && !longitudeString) + if (!latitudeString && !longitudeString) { return null; + } const {valid: isLatitudeValid} = SDK.EmulationModel.Geolocation.latitudeValidator(latitudeString); const {valid: isLongitudeValid} = SDK.EmulationModel.Geolocation.longitudeValidator(longitudeString); - if (!isLatitudeValid && !isLongitudeValid) + if (!isLatitudeValid && !isLongitudeValid) { return null; + } const latitude = isLatitudeValid ? parseFloat(latitudeString) : -1; const longitude = isLongitudeValid ? parseFloat(longitudeString) : -1; @@ -260,15 +271,17 @@ * @return {?SDK.EmulationModel.DeviceOrientation} */ static parseUserInput(alphaString, betaString, gammaString) { - if (!alphaString && !betaString && !gammaString) + if (!alphaString && !betaString && !gammaString) { return null; + } const {valid: isAlphaValid} = SDK.EmulationModel.DeviceOrientation.validator(alphaString); const {valid: isBetaValid} = SDK.EmulationModel.DeviceOrientation.validator(betaString); const {valid: isGammaValid} = SDK.EmulationModel.DeviceOrientation.validator(gammaString); - if (!isAlphaValid && !isBetaValid && !isGammaValid) + if (!isAlphaValid && !isBetaValid && !isGammaValid) { return null; + } const alpha = isAlphaValid ? parseFloat(alphaString) : -1; const beta = isBetaValid ? parseFloat(betaString) : -1;
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/FilmStripModel.js b/third_party/blink/renderer/devtools/front_end/sdk/FilmStripModel.js index 71c7237..35deaea 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/FilmStripModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/FilmStripModel.js
@@ -27,20 +27,24 @@ /** @type {!Array<!SDK.FilmStripModel.Frame>} */ this._frames = []; const browserMain = SDK.TracingModel.browserMainThread(tracingModel); - if (!browserMain) + if (!browserMain) { return; + } const events = browserMain.events(); for (let i = 0; i < events.length; ++i) { const event = events[i]; - if (event.startTime < this._zeroTime) + if (event.startTime < this._zeroTime) { continue; - if (!event.hasCategory(SDK.FilmStripModel._category)) + } + if (!event.hasCategory(SDK.FilmStripModel._category)) { continue; + } if (event.name === SDK.FilmStripModel.TraceEvents.CaptureFrame) { const data = event.args['data']; - if (data) + if (data) { this._frames.push(SDK.FilmStripModel.Frame._fromEvent(this, event, this._frames.length)); + } } else if (event.name === SDK.FilmStripModel.TraceEvents.Screenshot) { this._frames.push(SDK.FilmStripModel.Frame._fromSnapshot( this, /** @type {!SDK.TracingModel.ObjectSnapshot} */ (event), this._frames.length)); @@ -140,8 +144,9 @@ * @return {!Promise<?string>} */ imageDataPromise() { - if (this._imageData || !this._snapshot) + if (this._imageData || !this._snapshot) { return Promise.resolve(this._imageData); + } return /** @type {!Promise<?string>} */ (this._snapshot.objectPromise()); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js b/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js index e0b139a..221528e 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/HARLog.js
@@ -53,8 +53,9 @@ static async build(requests) { const log = new SDK.HARLog(); const entryPromises = []; - for (const request of requests) + for (const request of requests) { entryPromises.push(SDK.HARLog.Entry.build(request)); + } const entries = await Promise.all(entryPromises); return {version: '1.2', creator: log._creator(), pages: log._buildPages(requests), entries: entries}; } @@ -75,8 +76,9 @@ for (let i = 0; i < requests.length; ++i) { const request = requests[i]; const page = SDK.NetworkLog.PageLoad.forRequest(request); - if (!page || seenIdentifiers[page.id]) + if (!page || seenIdentifiers[page.id]) { continue; + } seenIdentifiers[page.id] = true; pages.push(this._convertPage(page, request)); } @@ -107,8 +109,9 @@ */ _pageEventTime(page, time) { const startTime = page.startTime; - if (time === -1 || startTime === -1) + if (time === -1 || startTime === -1) { return -1; + } return SDK.HARLog.Entry._toMilliseconds(time - startTime); } }; @@ -140,24 +143,29 @@ const harEntry = new SDK.HARLog.Entry(request); let ipAddress = harEntry._request.remoteAddress(); const portPositionInString = ipAddress.lastIndexOf(':'); - if (portPositionInString !== -1) + if (portPositionInString !== -1) { ipAddress = ipAddress.substr(0, portPositionInString); + } const timings = harEntry._buildTimings(); let time = 0; // "ssl" is included in the connect field, so do not double count it. - for (const t of [timings.blocked, timings.dns, timings.connect, timings.send, timings.wait, timings.receive]) + for (const t of [timings.blocked, timings.dns, timings.connect, timings.send, timings.wait, timings.receive]) { time += Math.max(t, 0); + } const initiator = harEntry._request.initiator(); const exportedInitiator = {}; exportedInitiator.type = initiator.type; - if (initiator.url !== undefined) + if (initiator.url !== undefined) { exportedInitiator.url = initiator.url; - if (initiator.lineNumber !== undefined) + } + if (initiator.lineNumber !== undefined) { exportedInitiator.lineNumber = initiator.lineNumber; - if (initiator.stack) + } + if (initiator.stack) { exportedInitiator.stack = initiator.stack; + } const entry = { startedDateTime: SDK.HARLog.pseudoWallTime(harEntry._request, harEntry._request.issueTime()).toJSON(), @@ -175,20 +183,24 @@ // Chrome specific. - if (harEntry._request.cached()) + if (harEntry._request.cached()) { entry._fromCache = harEntry._request.cachedInMemory() ? 'memory' : 'disk'; + } - if (harEntry._request.connectionId !== '0') + if (harEntry._request.connectionId !== '0') { entry.connection = harEntry._request.connectionId; + } const page = SDK.NetworkLog.PageLoad.forRequest(harEntry._request); - if (page) + if (page) { entry.pageref = 'page_' + page.id; + } if (harEntry._request.resourceType() === Common.resourceTypes.WebSocket) { const messages = []; - for (const message of harEntry._request.frames()) + for (const message of harEntry._request.frames()) { messages.push({type: message.type, time: message.time, opcode: message.opCode, data: message.text}); + } entry._webSocketMessages = messages; } @@ -211,8 +223,9 @@ bodySize: await this._requestBodySize() }; const postData = await this._buildPostData(); - if (postData) + if (postData) { res.postData = postData; + } return res; } @@ -247,8 +260,9 @@ // text: this._request.content // TODO: pull out into a boolean flag, as content can be huge (and needs to be requested with an async call) }; const compression = this.responseCompression; - if (typeof compression === 'number') + if (typeof compression === 'number') { content.compression = compression; + } return content; } @@ -272,14 +286,17 @@ // "blocked" here represents both queued + blocked/stalled + proxy (ie: anything before request was started). // We pick the better of when the network request start was reported and pref timing. const blockedStart = leastNonNegative([timing.dnsStart, timing.connectStart, timing.sendStart]); - if (blockedStart !== Infinity) + if (blockedStart !== Infinity) { result.blocked += blockedStart; + } // Proxy is part of blocked but sometimes (like quic) blocked is -1 but has proxy timings. - if (timing.proxyEnd !== -1) + if (timing.proxyEnd !== -1) { result._blocked_proxy = timing.proxyEnd - timing.proxyStart; - if (result._blocked_proxy && result._blocked_proxy > result.blocked) + } + if (result._blocked_proxy && result._blocked_proxy > result.blocked) { result.blocked = result._blocked_proxy; + } const dnsStart = timing.dnsEnd >= 0 ? blockedStart : 0; const dnsEnd = timing.dnsEnd >= 0 ? timing.dnsEnd : -1; @@ -299,8 +316,9 @@ const sendEnd = timing.sendEnd >= 0 ? timing.sendEnd : 0; result.send = sendEnd - sendStart; // Quic sometimes says that sendStart is before connectionEnd (see: crbug.com/740792) - if (result.send < 0) + if (result.send < 0) { result.send = 0; + } highestTime = Math.max(sendEnd, connectEnd, sslEnd, dnsEnd, blockedStart, 0); } else if (this._request.responseReceivedTime === -1) { // Means that we don't have any more details after blocked, so attribute all to blocked. @@ -333,12 +351,14 @@ */ async _buildPostData() { const postData = await this._request.requestFormData(); - if (!postData) + if (!postData) { return null; + } const res = {mimeType: this._request.requestContentType() || '', text: postData}; const formParameters = await this._request.formParameters(); - if (formParameters) + if (formParameters) { res.params = this._buildParameters(formParameters); + } return res; } @@ -380,8 +400,9 @@ httpOnly: cookie.httpOnly(), secure: cookie.secure() }; - if (cookie.sameSite()) + if (cookie.sameSite()) { c.sameSite = cookie.sameSite(); + } return c; } @@ -390,8 +411,9 @@ */ async _requestBodySize() { const postData = await this._request.requestFormData(); - if (!postData) + if (!postData) { return 0; + } // As per the har spec, returns the length in bytes of the posted data. // TODO(jarhar): This will be wrong if the underlying encoding is not UTF-8. NetworkRequest.requestFormData is @@ -404,10 +426,12 @@ * @return {number} */ get responseBodySize() { - if (this._request.cached() || this._request.statusCode === 304) + if (this._request.cached() || this._request.statusCode === 304) { return 0; - if (!this._request.responseHeadersText) + } + if (!this._request.responseHeadersText) { return -1; + } return this._request.transferSize - this._request.responseHeadersText.length; } @@ -415,10 +439,12 @@ * @return {number|undefined} */ get responseCompression() { - if (this._request.cached() || this._request.statusCode === 304 || this._request.statusCode === 206) + if (this._request.cached() || this._request.statusCode === 304 || this._request.statusCode === 206) { return; - if (!this._request.responseHeadersText) + } + if (!this._request.responseHeadersText) { return; + } return this._request.resourceSize - this.responseBodySize; } };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js b/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js index d37fd39..22031cc 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/HeapProfilerModel.js
@@ -30,8 +30,9 @@ } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._enabled = true; this._heapProfilerAgent.enable(); @@ -41,8 +42,9 @@ * @param {number=} samplingRateInBytes */ startSampling(samplingRateInBytes) { - if (this._samplingProfilerDepth++) + if (this._samplingProfilerDepth++) { return; + } const defaultSamplingIntervalInBytes = 16384; this._heapProfilerAgent.startSampling(samplingRateInBytes || defaultSamplingIntervalInBytes); } @@ -51,10 +53,12 @@ * @return {!Promise<?Protocol.HeapProfiler.SamplingHeapProfile>} */ stopSampling() { - if (!this._samplingProfilerDepth) + if (!this._samplingProfilerDepth) { throw new Error('Sampling profiler is not running.'); - if (--this._samplingProfilerDepth) + } + if (--this._samplingProfilerDepth) { return this.getSamplingProfile(); + } return this._heapProfilerAgent.stopSampling(); } @@ -107,8 +111,9 @@ for (const sample of rawProfile.samples) { const node = sample.stack.reverse().reduce((node, name) => { let child = node.children.get(name); - if (child) + if (child) { return child; + } const namespace = /^([^:]*)::/.exec(name); child = { children: new Map(),
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/IsolateManager.js b/third_party/blink/renderer/devtools/front_end/sdk/IsolateManager.js index 992bcdb..ab3cb6d 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/IsolateManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/IsolateManager.js
@@ -24,13 +24,16 @@ * @param {!SDK.IsolateManager.Observer} observer */ observeIsolates(observer) { - if (this._observers.has(observer)) + if (this._observers.has(observer)) { throw new Error('Observer can only be registered once'); - if (!this._observers.size) + } + if (!this._observers.size) { this._poll(); + } this._observers.add(observer); - for (const isolate of this._isolates.values()) + for (const isolate of this._isolates.values()) { observer.isolateAdded(isolate); + } } /** @@ -38,8 +41,9 @@ */ unobserveIsolates(observer) { this._observers.delete(observer); - if (!this._observers.size) - ++this._pollId; // Stops the current polling loop. + if (!this._observers.size) { + ++this._pollId; + } // Stops the current polling loop. } /** @@ -72,11 +76,13 @@ } isolate._models.add(model); if (isolate._models.size === 1) { - for (const observer of this._observers) + for (const observer of this._observers) { observer.isolateAdded(isolate); + } } else { - for (const observer of this._observers) + for (const observer of this._observers) { observer.isolateChanged(isolate); + } } } @@ -87,17 +93,20 @@ modelRemoved(model) { const isolateId = this._isolateIdByModel.get(model); this._isolateIdByModel.delete(model); - if (!isolateId) + if (!isolateId) { return; + } const isolate = this._isolates.get(isolateId); isolate._models.delete(model); if (isolate._models.size) { - for (const observer of this._observers) + for (const observer of this._observers) { observer.isolateChanged(isolate); + } return; } - for (const observer of this._observers) + for (const observer of this._observers) { observer.isolateRemoved(isolate); + } this._isolates.delete(isolateId); } @@ -199,8 +208,9 @@ async _update() { const model = this.runtimeModel(); const usage = model && await model.heapUsage(); - if (!usage) + if (!usage) { return; + } this._usedHeapSize = usage.usedSize; this._memoryTrend.add(this._usedHeapSize); SDK.isolateManager.dispatchEventToListeners(SDK.IsolateManager.Events.MemoryChanged, this);
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/LayerTreeBase.js b/third_party/blink/renderer/devtools/front_end/sdk/LayerTreeBase.js index d8d45f5..31541a8 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/LayerTreeBase.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/LayerTreeBase.js
@@ -155,13 +155,15 @@ this._containingBlockRect = constraint.containingBlockRect; /** @type {?SDK.Layer} */ this._nearestLayerShiftingStickyBox = null; - if (layerTree && constraint.nearestLayerShiftingStickyBox) + if (layerTree && constraint.nearestLayerShiftingStickyBox) { this._nearestLayerShiftingStickyBox = layerTree.layerById(constraint.nearestLayerShiftingStickyBox); + } /** @type {?SDK.Layer} */ this._nearestLayerShiftingContainingBlock = null; - if (layerTree && constraint.nearestLayerShiftingContainingBlock) + if (layerTree && constraint.nearestLayerShiftingContainingBlock) { this._nearestLayerShiftingContainingBlock = layerTree.layerById(constraint.nearestLayerShiftingContainingBlock); + } } /** @@ -255,8 +257,9 @@ forEachLayer(callback, root) { if (!root) { root = this.root(); - if (!root) + if (!root) { return false; + } } return callback(root) || root.children().some(this.forEachLayer.bind(this, callback)); } @@ -274,15 +277,18 @@ * @return {!Promise} */ async resolveBackendNodeIds(requestedNodeIds) { - if (!requestedNodeIds.size || !this._domModel) + if (!requestedNodeIds.size || !this._domModel) { return; + } const nodesMap = await this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds); - if (!nodesMap) + if (!nodesMap) { return; - for (const nodeId of nodesMap.keysArray()) + } + for (const nodeId of nodesMap.keysArray()) { this._backendNodeIdToNode.set(nodeId, nodesMap.get(nodeId) || null); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/NetworkLog.js b/third_party/blink/renderer/devtools/front_end/sdk/NetworkLog.js index 64e0f1b..4d07acaf 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/NetworkLog.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/NetworkLog.js
@@ -94,8 +94,9 @@ * @param {boolean} enabled */ setIsRecording(enabled) { - if (this._isRecording === enabled) + if (this._isRecording === enabled) { return; + } this._isRecording = enabled; if (enabled) { SDK.targetManager.observeModels(SDK.NetworkManager, this); @@ -129,8 +130,9 @@ // We itterate backwards because the last item will likely be the one needed for console network request lookups. for (let i = this._requests.length - 1; i >= 0; i--) { const request = this._requests[i]; - if (requestId === request.requestId() && networkManager === SDK.NetworkManager.forRequest(request)) + if (requestId === request.requestId() && networkManager === SDK.NetworkManager.forRequest(request)) { return request; + } } return null; } @@ -142,8 +144,9 @@ */ _requestByManagerAndURL(networkManager, url) { for (const request of this._requests) { - if (url === request.url() && networkManager === SDK.NetworkManager.forRequest(request)) + if (url === request.url() && networkManager === SDK.NetworkManager.forRequest(request)) { return request; + } } return null; } @@ -168,8 +171,9 @@ */ initiatorInfoForRequest(request) { this._initializeInitiatorSymbolIfNeeded(request); - if (request[SDK.NetworkLog._initiatorDataSymbol].info) + if (request[SDK.NetworkLog._initiatorDataSymbol].info) { return request[SDK.NetworkLog._initiatorDataSymbol].info; + } let type = SDK.NetworkRequest.InitiatorType.Other; let url = ''; @@ -191,8 +195,9 @@ } else if (initiator.type === Protocol.Network.InitiatorType.Script) { for (let stack = initiator.stack; stack; stack = stack.parent) { const topFrame = stack.callFrames.length ? stack.callFrames[0] : null; - if (!topFrame) + if (!topFrame) { continue; + } type = SDK.NetworkRequest.InitiatorType.Script; url = topFrame.url || Common.UIString('<anonymous>'); lineNumber = topFrame.lineNumber; @@ -205,8 +210,9 @@ url = initiator.url; lineNumber = initiator.lineNumber || 0; } - if (initiator.stack && initiator.stack.callFrames && initiator.stack.callFrames.length) + if (initiator.stack && initiator.stack.callFrames && initiator.stack.callFrames.length) { initiatorStack = initiator.stack || null; + } } else if (initiator.type === Protocol.Network.InitiatorType.Preload) { type = SDK.NetworkRequest.InitiatorType.Preload; } else if (initiator.type === Protocol.Network.InitiatorType.SignedExchange) { @@ -236,8 +242,9 @@ const networkManager = SDK.NetworkManager.forRequest(request); for (const otherRequest of this._requests) { const otherRequestManager = SDK.NetworkManager.forRequest(request); - if (networkManager === otherRequestManager && this._initiatorChain(otherRequest).has(request)) + if (networkManager === otherRequestManager && this._initiatorChain(otherRequest).has(request)) { initiated.add(otherRequest); + } } return {initiators: this._initiatorChain(request), initiated: initiated}; } @@ -250,8 +257,9 @@ this._initializeInitiatorSymbolIfNeeded(request); let initiatorChainCache = /** @type {?Set<!SDK.NetworkRequest>} */ (request[SDK.NetworkLog._initiatorDataSymbol].chain); - if (initiatorChainCache) + if (initiatorChainCache) { return initiatorChainCache; + } initiatorChainCache = new Set(); @@ -261,8 +269,9 @@ initiatorChainCache.addAll(checkRequest[SDK.NetworkLog._initiatorDataSymbol].chain); break; } - if (initiatorChainCache.has(checkRequest)) + if (initiatorChainCache.has(checkRequest)) { break; + } initiatorChainCache.add(checkRequest); checkRequest = this._initiatorRequest(checkRequest); } while (checkRequest); @@ -276,8 +285,9 @@ */ _initiatorRequest(request) { this._initializeInitiatorSymbolIfNeeded(request); - if (request[SDK.NetworkLog._initiatorDataSymbol].request !== undefined) + if (request[SDK.NetworkLog._initiatorDataSymbol].request !== undefined) { return request[SDK.NetworkLog._initiatorDataSymbol].request; + } const url = this.initiatorInfoForRequest(request).url; const networkManager = SDK.NetworkManager.forRequest(request); request[SDK.NetworkLog._initiatorDataSymbol].request = @@ -286,8 +296,9 @@ } _willReloadPage() { - if (!Common.moduleSetting('network_log.preserve-log').get()) + if (!Common.moduleSetting('network_log.preserve-log').get()) { this.reset(); + } } /** @@ -296,8 +307,9 @@ _onMainFrameNavigated(event) { const mainFrame = /** @type {!SDK.ResourceTreeFrame} */ (event.data); const manager = mainFrame.resourceTreeModel().target().model(SDK.NetworkManager); - if (!manager || mainFrame.resourceTreeModel().target().parentTarget()) + if (!manager || mainFrame.resourceTreeModel().target().parentTarget()) { return; + } const oldRequests = this._requests; const oldManagerRequests = this._requests.filter(request => SDK.NetworkManager.forRequest(request) === manager); @@ -310,8 +322,9 @@ let currentPageLoad = null; const requestsToAdd = []; for (const request of oldManagerRequests) { - if (request.loaderId !== mainFrame.loaderId) + if (request.loaderId !== mainFrame.loaderId) { continue; + } if (!currentPageLoad) { currentPageLoad = new SDK.NetworkLog.PageLoad(request); let redirectSource = request.redirectSource(); @@ -326,14 +339,16 @@ // Preserve service worker requests from the new session. const serviceWorkerRequestsToAdd = []; for (const swRequest of oldRequests) { - if (!swRequest.initiatedByServiceWorker()) + if (!swRequest.initiatedByServiceWorker()) { continue; + } // If there is a matching request that came before this one, keep it. const keepRequest = requestsToAdd.some( request => request.url() === swRequest.url() && request.issueTime() <= swRequest.issueTime()); - if (keepRequest) + if (keepRequest) { serviceWorkerRequestsToAdd.push(swRequest); + } } requestsToAdd.push(...serviceWorkerRequestsToAdd); @@ -353,8 +368,9 @@ } } - if (currentPageLoad) + if (currentPageLoad) { this._pageLoadForManager.set(manager, currentPageLoad); + } } /** @@ -380,8 +396,9 @@ this._requestsSet.add(request); const manager = SDK.NetworkManager.forRequest(request); const pageLoad = manager ? this._pageLoadForManager.get(manager) : null; - if (pageLoad) + if (pageLoad) { pageLoad.bindRequest(request); + } this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestAdded, request); } @@ -390,8 +407,9 @@ */ _onRequestUpdated(event) { const request = /** @type {!SDK.NetworkRequest} */ (event.data); - if (!this._requestsSet.has(request)) + if (!this._requestsSet.has(request)) { return; + } this.dispatchEventToListeners(SDK.NetworkLog.Events.RequestUpdated, request); } @@ -410,8 +428,9 @@ _onDOMContentLoaded(resourceTreeModel, event) { const networkManager = resourceTreeModel.target().model(SDK.NetworkManager); const pageLoad = networkManager ? this._pageLoadForManager.get(networkManager) : null; - if (pageLoad) + if (pageLoad) { pageLoad.contentLoadTime = /** @type {number} */ (event.data); + } } /** @@ -420,8 +439,9 @@ _onLoad(event) { const networkManager = event.data.resourceTreeModel.target().model(SDK.NetworkManager); const pageLoad = networkManager ? this._pageLoadForManager.get(networkManager) : null; - if (pageLoad) + if (pageLoad) { pageLoad.loadTime = /** @type {number} */ (event.data.loadTime); + } } reset() { @@ -429,8 +449,9 @@ this._requestsSet.clear(); const managers = new Set(SDK.targetManager.models(SDK.NetworkManager)); for (const manager of this._pageLoadForManager.keys()) { - if (!managers.has(manager)) + if (!managers.has(manager)) { this._pageLoadForManager.delete(manager); + } } this.dispatchEventToListeners(SDK.NetworkLog.Events.Reset); @@ -457,11 +478,13 @@ associateConsoleMessageWithRequest(consoleMessage, requestId) { const target = consoleMessage.target(); const networkManager = target ? target.model(SDK.NetworkManager) : null; - if (!networkManager) + if (!networkManager) { return; + } const request = this.requestByManagerAndId(networkManager, requestId); - if (!request) + if (!request) { return; + } consoleMessage[SDK.NetworkLog._requestSymbol] = request; const initiator = request.initiator(); if (initiator) { @@ -501,10 +524,12 @@ async _showDataSaverWarningIfNeeded() { const manager = SDK.NetworkManager.forRequest(this.mainRequest); - if (!manager) + if (!manager) { return; - if (!this.mainRequest.finished) + } + if (!this.mainRequest.finished) { await this.mainRequest.once(SDK.NetworkRequest.Events.FinishedLoading); + } const saveDataHeader = this.mainRequest.requestHeaderValue('Save-Data'); if (!SDK.NetworkLog.PageLoad._dataSaverMessageWasShown && saveDataHeader && saveDataHeader === 'on') { const message = Common.UIString(
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js b/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js index 4d94a2f..609c194 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js
@@ -40,14 +40,16 @@ this._dispatcher = new SDK.NetworkDispatcher(this); this._networkAgent = target.networkAgent(); target.registerNetworkDispatcher(this._dispatcher); - if (Common.moduleSetting('cacheDisabled').get()) + if (Common.moduleSetting('cacheDisabled').get()) { this._networkAgent.setCacheDisabled(true); + } this._networkAgent.enable(undefined, undefined, SDK.NetworkManager.MAX_EAGER_POST_REQUEST_BODY_LENGTH); this._bypassServiceWorkerSetting = Common.settings.createSetting('bypassServiceWorker', false); - if (this._bypassServiceWorkerSetting.get()) + if (this._bypassServiceWorkerSetting.get()) { this._bypassServiceWorkerChanged(); + } this._bypassServiceWorkerSetting.addChangeListener(this._bypassServiceWorkerChanged, this); Common.moduleSetting('cacheDisabled').addChangeListener(this._cacheDisabledSettingChanged, this); @@ -75,8 +77,9 @@ */ static replayRequest(request) { const manager = request[SDK.NetworkManager._networkManagerForRequestSymbol]; - if (!manager) + if (!manager) { return; + } manager._networkAgent.replayXHR(request.requestId()); } @@ -89,8 +92,9 @@ */ static async searchInRequest(request, query, caseSensitive, isRegex) { const manager = SDK.NetworkManager.forRequest(request); - if (!manager) + if (!manager) { return []; + } const response = await manager._networkAgent.invoke_searchInResponseBody( {requestId: request.requestId(), query: query, caseSensitive: caseSensitive, isRegex: isRegex}); return response.result || []; @@ -101,13 +105,16 @@ * @return {!Promise<!SDK.NetworkRequest.ContentData>} */ static async requestContentData(request) { - if (request.resourceType() === Common.resourceTypes.WebSocket) + if (request.resourceType() === Common.resourceTypes.WebSocket) { return {error: 'Content for WebSockets is currently not supported', content: null, encoded: false}; - if (!request.finished) + } + if (!request.finished) { await request.once(SDK.NetworkRequest.Events.FinishedLoading); + } const manager = SDK.NetworkManager.forRequest(request); - if (!manager) + if (!manager) { return {error: 'No network manager for request', content: null, encoded: false}; + } const response = await manager._networkAgent.invoke_getResponseBody({requestId: request.requestId()}); const error = response[Protocol.Error] || null; return {error: error, content: error ? null : response.body, encoded: response.base64Encoded}; @@ -119,8 +126,9 @@ */ static requestPostData(request) { const manager = SDK.NetworkManager.forRequest(request); - if (manager) + if (manager) { return manager._networkAgent.getRequestPostData(request.backendRequestId()); + } console.error('No network manager for request'); return /** @type {!Promise<?string>} */ (Promise.resolve(null)); } @@ -131,8 +139,9 @@ * TODO(allada): this belongs to NetworkConditionsSelector, which should hardcode/guess it. */ static _connectionType(conditions) { - if (!conditions.download && !conditions.upload) + if (!conditions.download && !conditions.upload) { return Protocol.Network.ConnectionType.None; + } let types = SDK.NetworkManager._connectionTypes; if (!types) { SDK.NetworkManager._connectionTypes = []; @@ -145,8 +154,9 @@ types.push(['wimax', Protocol.Network.ConnectionType.Wimax]); } for (const type of types) { - if (conditions.title.toLowerCase().indexOf(type[0]) !== -1) + if (conditions.title.toLowerCase().indexOf(type[0]) !== -1) { return type[1]; + } } return Protocol.Network.ConnectionType.Other; } @@ -157,8 +167,9 @@ */ static lowercaseHeaders(headers) { const newHeaders = {}; - for (const headerName in headers) + for (const headerName in headers) { newHeaders[headerName.toLowerCase()] = headers[headerName]; + } return newHeaders; } @@ -292,8 +303,9 @@ const result = []; for (const name in headersMap) { const values = headersMap[name].split('\n'); - for (let i = 0; i < values.length; ++i) + for (let i = 0; i < values.length; ++i) { result.push({name: name, value: values[i]}); + } } return result; } @@ -316,16 +328,19 @@ * @param {!Protocol.Network.Response=} response */ _updateNetworkRequestWithResponse(networkRequest, response) { - if (response.url && networkRequest.url() !== response.url) + if (response.url && networkRequest.url() !== response.url) { networkRequest.setUrl(response.url); + } networkRequest.mimeType = response.mimeType; networkRequest.statusCode = response.status; networkRequest.statusText = response.statusText; - if (!networkRequest.hasExtraResponseInfo()) + if (!networkRequest.hasExtraResponseInfo()) { networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers); + } - if (response.encodedDataLength >= 0) + if (response.encodedDataLength >= 0) { networkRequest.setTransferSize(response.encodedDataLength); + } if (response.requestHeaders && !networkRequest.hasExtraRequestInfo()) { // TODO(http://crbug.com/1004979): Stop using response.requestHeaders and @@ -337,17 +352,21 @@ networkRequest.connectionReused = response.connectionReused; networkRequest.connectionId = String(response.connectionId); - if (response.remoteIPAddress) + if (response.remoteIPAddress) { networkRequest.setRemoteAddress(response.remoteIPAddress, response.remotePort || -1); + } - if (response.fromServiceWorker) + if (response.fromServiceWorker) { networkRequest.fetchedViaServiceWorker = true; + } - if (response.fromDiskCache) + if (response.fromDiskCache) { networkRequest.setFromDiskCache(); + } - if (response.fromPrefetchCache) + if (response.fromPrefetchCache) { networkRequest.setFromPrefetchCache(); + } networkRequest.timing = response.timing; @@ -364,8 +383,9 @@ {message: message, requestId: networkRequest.requestId(), warning: true}); } - if (response.securityDetails) + if (response.securityDetails) { networkRequest.setSecurityDetails(response.securityDetails); + } } /** @@ -379,20 +399,24 @@ // Also, if a URL like http://localhost/wiki/load.php?debug=true&lang=en produces text/css and gets reloaded, // it is 304 Not Modified and its guessed mime-type is text/php, which is wrong. // Don't check for mime-types in 304-resources. - if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304 || networkRequest.statusCode === 204) + if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304 || networkRequest.statusCode === 204) { return true; + } const resourceType = networkRequest.resourceType(); if (resourceType !== Common.resourceTypes.Stylesheet && resourceType !== Common.resourceTypes.Document && - resourceType !== Common.resourceTypes.TextTrack) + resourceType !== Common.resourceTypes.TextTrack) { return true; + } - if (!networkRequest.mimeType) - return true; // Might be not known for cached resources with null responses. + if (!networkRequest.mimeType) { + return true; + } // Might be not known for cached resources with null responses. - if (networkRequest.mimeType in SDK.NetworkManager._MIMETypes) + if (networkRequest.mimeType in SDK.NetworkManager._MIMETypes) { return resourceType.name() in SDK.NetworkManager._MIMETypes[networkRequest.mimeType]; + } return false; } @@ -405,8 +429,9 @@ */ resourceChangedPriority(requestId, newPriority, timestamp) { const networkRequest = this._inflightRequestsById[requestId]; - if (networkRequest) + if (networkRequest) { networkRequest.setPriority(newPriority); + } } /** @@ -432,8 +457,9 @@ // process and DevTools to find the matching request. if (!networkRequest) { networkRequest = this._inflightRequestsByURL[info.outerResponse.url]; - if (!networkRequest) + if (!networkRequest) { return; + } } networkRequest.setSignedExchangeInfo(info); networkRequest.setResourceType(Common.resourceTypes.SignedExchange); @@ -461,8 +487,9 @@ let networkRequest = this._inflightRequestsById[requestId]; if (networkRequest) { // FIXME: move this check to the backend. - if (!redirectResponse) + if (!redirectResponse) { return; + } // If signedExchangeReceived event has already been sent for the request, // ignores the internally generated |redirectResponse|. The // |outerResponse| of SignedExchangeInfo was set to |networkRequest| in @@ -494,8 +521,9 @@ */ requestServedFromCache(requestId) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.setFromMemoryCache(); } @@ -533,8 +561,9 @@ if ('set-cookie' in lowercaseHeaders && lowercaseHeaders['set-cookie'].length > 4096) { const values = lowercaseHeaders['set-cookie'].split('\n'); for (let i = 0; i < values.length; ++i) { - if (values[i].length <= 4096) + if (values[i].length <= 4096) { continue; + } const message = Common.UIString( 'Set-Cookie header is ignored in response from url: %s. Cookie length should be less than or equal to 4096 characters.', response.url); @@ -558,14 +587,17 @@ */ dataReceived(requestId, time, dataLength, encodedDataLength) { let networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { networkRequest = this._maybeAdoptMainResourceRequest(requestId); - if (!networkRequest) + } + if (!networkRequest) { return; + } networkRequest.resourceSize += dataLength; - if (encodedDataLength !== -1) + if (encodedDataLength !== -1) { networkRequest.increaseTransferSize(encodedDataLength); + } networkRequest.endTime = time; this._updateNetworkRequest(networkRequest); @@ -580,10 +612,12 @@ */ loadingFinished(requestId, finishTime, encodedDataLength, shouldReportCorbBlocking) { let networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { networkRequest = this._maybeAdoptMainResourceRequest(requestId); - if (!networkRequest) + } + if (!networkRequest) { return; + } this._getExtraInfoBuilder(requestId).finished(); this._finishNetworkRequest(networkRequest, finishTime, encodedDataLength, shouldReportCorbBlocking); } @@ -599,8 +633,9 @@ */ loadingFailed(requestId, time, resourceType, localizedDescription, canceled, blockedReason) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.failed = true; networkRequest.setResourceType(Common.resourceTypes[resourceType]); @@ -640,8 +675,9 @@ */ webSocketWillSendHandshakeRequest(requestId, time, wallTime, request) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.requestMethod = 'GET'; networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers)); @@ -658,17 +694,20 @@ */ webSocketHandshakeResponseReceived(requestId, time, response) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.statusCode = response.status; networkRequest.statusText = response.statusText; networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers); networkRequest.responseHeadersText = response.headersText || ''; - if (response.requestHeaders) + if (response.requestHeaders) { networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders)); - if (response.requestHeadersText) + } + if (response.requestHeadersText) { networkRequest.setRequestHeadersText(response.requestHeadersText); + } networkRequest.responseReceivedTime = time; networkRequest.protocol = 'websocket'; @@ -683,8 +722,9 @@ */ webSocketFrameReceived(requestId, time, response) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.addProtocolFrame(response, time, false); networkRequest.responseReceivedTime = time; @@ -700,8 +740,9 @@ */ webSocketFrameSent(requestId, time, response) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.addProtocolFrame(response, time, true); networkRequest.responseReceivedTime = time; @@ -717,8 +758,9 @@ */ webSocketFrameError(requestId, time, errorMessage) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.addProtocolFrameError(errorMessage, time); networkRequest.responseReceivedTime = time; @@ -733,8 +775,9 @@ */ webSocketClosed(requestId, time) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } this._finishNetworkRequest(networkRequest, time, -1); } @@ -748,8 +791,9 @@ */ eventSourceMessageReceived(requestId, time, eventName, eventId, data) { const networkRequest = this._inflightRequestsById[requestId]; - if (!networkRequest) + if (!networkRequest) { return; + } networkRequest.addEventSourceMessage(time, eventName, eventId, data); } @@ -842,8 +886,9 @@ _appendRedirect(requestId, time, redirectURL) { const originalNetworkRequest = this._inflightRequestsById[requestId]; let redirectCount = 0; - for (let redirect = originalNetworkRequest.redirectSource(); redirect; redirect = redirect.redirectSource()) + for (let redirect = originalNetworkRequest.redirectSource(); redirect; redirect = redirect.redirectSource()) { redirectCount++; + } originalNetworkRequest.markAsRedirect(redirectCount); this._finishNetworkRequest(originalNetworkRequest, time, -1); @@ -861,8 +906,9 @@ */ _maybeAdoptMainResourceRequest(requestId) { const request = SDK.multitargetNetworkManager._inflightMainResourceRequests.get(requestId); - if (!request) + if (!request) { return null; + } const oldDispatcher = SDK.NetworkManager.forRequest(request)._dispatcher; delete oldDispatcher._inflightRequestsById[requestId]; delete oldDispatcher._inflightRequestsByURL[request.url()]; @@ -880,8 +926,9 @@ this._inflightRequestsByURL[networkRequest.url()] = networkRequest; // The following relies on the fact that loaderIds and requestIds are // globally unique and that the main request has them equal. - if (networkRequest.loaderId === networkRequest.requestId()) + if (networkRequest.loaderId === networkRequest.requestId()) { SDK.multitargetNetworkManager._inflightMainResourceRequests.set(networkRequest.requestId(), networkRequest); + } this._manager.dispatchEventToListeners(SDK.NetworkManager.Events.RequestStarted, networkRequest); } @@ -1014,17 +1061,22 @@ */ modelAdded(networkManager) { const networkAgent = networkManager.target().networkAgent(); - if (this._extraHeaders) + if (this._extraHeaders) { networkAgent.setExtraHTTPHeaders(this._extraHeaders); - if (this._currentUserAgent()) + } + if (this._currentUserAgent()) { networkAgent.setUserAgentOverride(this._currentUserAgent()); - if (this._effectiveBlockedURLs.length) + } + if (this._effectiveBlockedURLs.length) { networkAgent.setBlockedURLs(this._effectiveBlockedURLs); - if (this.isIntercepting()) + } + if (this.isIntercepting()) { networkAgent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray()); + } this._agents.add(networkAgent); - if (this.isThrottling()) + if (this.isThrottling()) { this._updateNetworkConditions(networkAgent); + } } /** @@ -1034,8 +1086,9 @@ modelRemoved(networkManager) { for (const entry of this._inflightMainResourceRequests) { const manager = SDK.NetworkManager.forRequest(/** @type {!SDK.NetworkRequest} */ (entry[1])); - if (manager !== networkManager) + if (manager !== networkManager) { continue; + } this._inflightMainResourceRequests.delete(/** @type {string} */ (entry[0])); } this._agents.delete(networkManager.target().networkAgent()); @@ -1061,8 +1114,9 @@ */ setNetworkConditions(conditions) { this._networkConditions = conditions; - for (const agent of this._agents) + for (const agent of this._agents) { this._updateNetworkConditions(agent); + } this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.ConditionsChanged); } @@ -1092,8 +1146,9 @@ */ setExtraHTTPHeaders(headers) { this._extraHeaders = headers; - for (const agent of this._agents) + for (const agent of this._agents) { agent.setExtraHTTPHeaders(this._extraHeaders); + } } /** @@ -1105,19 +1160,22 @@ _updateUserAgentOverride() { const userAgent = this._currentUserAgent(); - for (const agent of this._agents) + for (const agent of this._agents) { agent.setUserAgentOverride(userAgent); + } } /** * @param {string} userAgent */ setUserAgentOverride(userAgent) { - if (this._userAgentOverride === userAgent) + if (this._userAgentOverride === userAgent) { return; + } this._userAgentOverride = userAgent; - if (!this._customUserAgent) + if (!this._customUserAgent) { this._updateUserAgentOverride(); + } this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.UserAgentChanged); } @@ -1171,8 +1229,9 @@ * @param {boolean} enabled */ setBlockingEnabled(enabled) { - if (this._blockingEnabledSetting.get() === enabled) + if (this._blockingEnabledSetting.get() === enabled) { return; + } this._blockingEnabledSetting.set(enabled); this._updateBlockedPatterns(); this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.BlockedPatternsChanged); @@ -1182,16 +1241,19 @@ const urls = []; if (this._blockingEnabledSetting.get()) { for (const pattern of this._blockedPatternsSetting.get()) { - if (pattern.enabled) + if (pattern.enabled) { urls.push(pattern.url); + } } } - if (!urls.length && !this._effectiveBlockedURLs.length) + if (!urls.length && !this._effectiveBlockedURLs.length) { return; + } this._effectiveBlockedURLs = urls; - for (const agent of this._agents) + for (const agent of this._agents) { agent.setBlockedURLs(this._effectiveBlockedURLs); + } } /** @@ -1209,8 +1271,9 @@ setInterceptionHandlerForPatterns(patterns, requestInterceptor) { // Note: requestInterceptors may recieve interception requests for patterns they did not subscribe to. this._urlsForRequestInterceptor.deleteAll(requestInterceptor); - for (const newPattern of patterns) + for (const newPattern of patterns) { this._urlsForRequestInterceptor.set(requestInterceptor, newPattern); + } return this._updateInterceptionPatternsOnNextTick(); } @@ -1219,8 +1282,9 @@ */ _updateInterceptionPatternsOnNextTick() { // This is used so we can register and unregister patterns in loops without sending lots of protocol messages. - if (!this._updatingInterceptionPatternsPromise) + if (!this._updatingInterceptionPatternsPromise) { this._updatingInterceptionPatternsPromise = Promise.resolve().then(this._updateInterceptionPatterns.bind(this)); + } return this._updatingInterceptionPatternsPromise; } @@ -1228,12 +1292,14 @@ * @return {!Promise} */ _updateInterceptionPatterns() { - if (!Common.moduleSetting('cacheDisabled').get()) + if (!Common.moduleSetting('cacheDisabled').get()) { Common.moduleSetting('cacheDisabled').set(true); + } this._updatingInterceptionPatternsPromise = null; const promises = /** @type {!Array<!Promise>} */ ([]); - for (const agent of this._agents) + for (const agent of this._agents) { promises.push(agent.setRequestInterception(this._urlsForRequestInterceptor.valuesArray())); + } this.dispatchEventToListeners(SDK.MultitargetNetworkManager.Events.InterceptorsChanged); return Promise.all(promises); } @@ -1244,21 +1310,25 @@ async _requestIntercepted(interceptedRequest) { for (const requestInterceptor of this._urlsForRequestInterceptor.keysArray()) { await requestInterceptor(interceptedRequest); - if (interceptedRequest.hasResponded()) + if (interceptedRequest.hasResponded()) { return; + } } - if (!interceptedRequest.hasResponded()) + if (!interceptedRequest.hasResponded()) { interceptedRequest.continueRequestWithoutChange(); + } } clearBrowserCache() { - for (const agent of this._agents) + for (const agent of this._agents) { agent.clearBrowserCache(); + } } clearBrowserCookies() { - for (const agent of this._agents) + for (const agent of this._agents) { agent.clearBrowserCookies(); + } } /** @@ -1278,11 +1348,13 @@ const headers = {}; const currentUserAgent = this._currentUserAgent(); - if (currentUserAgent) + if (currentUserAgent) { headers['User-Agent'] = currentUserAgent; + } - if (Common.moduleSetting('cacheDisabled').get()) + if (Common.moduleSetting('cacheDisabled').get()) { headers['Cache-Control'] = 'no-cache'; + } Host.ResourceLoader.load(url, headers, callback); } @@ -1461,8 +1533,9 @@ */ _sync(index) { const req = this._requests[index]; - if (!req) + if (!req) { return; + } const requestExtraInfo = this._requestExtraInfos[index]; if (requestExtraInfo) { @@ -1480,13 +1553,15 @@ } _deleteIfComplete() { - if (!this._finished) + if (!this._finished) { return; + } if (this._hasExtraInfo) { // if we haven't gotten the last responseExtraInfo event, we have to wait for it. - if (!this._requests.peekLast().hasExtraResponseInfo()) + if (!this._requests.peekLast().hasExtraResponseInfo()) { return; + } } this._deleteCallback();
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js b/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js index bde14a34..1ba954cb 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/NetworkRequest.js
@@ -131,10 +131,12 @@ indentityCompare(other) { const thisId = this.requestId(); const thatId = other.requestId(); - if (thisId > thatId) + if (thisId > thatId) { return 1; - if (thisId < thatId) + } + if (thisId < thatId) { return -1; + } return 0; } @@ -170,8 +172,9 @@ * @param {string} x */ setUrl(x) { - if (this._url === x) + if (this._url === x) { return; + } this._url = x; this._parsedURL = new Common.ParsedURL(x); @@ -327,8 +330,9 @@ } else { // Prefer endTime since it might be from the network stack. this._endTime = x; - if (this._responseReceivedTime > x) + if (this._responseReceivedTime > x) { this._responseReceivedTime = x; + } } this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged, this); } @@ -337,8 +341,9 @@ * @return {number} */ get duration() { - if (this._endTime === -1 || this._startTime === -1) + if (this._endTime === -1 || this._startTime === -1) { return -1; + } return this._endTime - this._startTime; } @@ -346,8 +351,9 @@ * @return {number} */ get latency() { - if (this._responseReceivedTime === -1 || this._startTime === -1) + if (this._responseReceivedTime === -1 || this._startTime === -1) { return -1; + } return this._responseReceivedTime - this._startTime; } @@ -397,13 +403,15 @@ * @param {boolean} x */ set finished(x) { - if (this._finished === x) + if (this._finished === x) { return; + } this._finished = x; - if (x) + if (x) { this.dispatchEventToListeners(SDK.NetworkRequest.Events.FinishedLoading, this); + } } /** @@ -511,8 +519,9 @@ */ initiatedByServiceWorker() { const networkManager = SDK.NetworkManager.forRequest(this); - if (!networkManager) + if (!networkManager) { return false; + } return networkManager.target().type() === SDK.Target.Type.ServiceWorker; } @@ -527,16 +536,19 @@ * @param {!Protocol.Network.ResourceTiming|undefined} timingInfo */ set timing(timingInfo) { - if (!timingInfo || this._fromMemoryCache) + if (!timingInfo || this._fromMemoryCache) { return; + } // Take startTime and responseReceivedTime from timing data for better accuracy. // Timing's requestTime is a baseline in seconds, rest of the numbers there are ticks in millis. this._startTime = timingInfo.requestTime; const headersReceivedTime = timingInfo.requestTime + timingInfo.receiveHeadersEnd / 1000.0; - if ((this._responseReceivedTime || -1) < 0 || this._responseReceivedTime > headersReceivedTime) + if ((this._responseReceivedTime || -1) < 0 || this._responseReceivedTime > headersReceivedTime) { this._responseReceivedTime = headersReceivedTime; - if (this._startTime > this._responseReceivedTime) + } + if (this._startTime > this._responseReceivedTime) { this._responseReceivedTime = this._startTime; + } this._timing = timingInfo; this.dispatchEventToListeners(SDK.NetworkRequest.Events.TimingChanged, this); @@ -567,8 +579,9 @@ * @return {string} */ name() { - if (this._name) + if (this._name) { return this._name; + } this._parseNameAndPathFromURL(); return this._name; } @@ -577,8 +590,9 @@ * @return {string} */ path() { - if (this._path) + if (this._path) { return this._path; + } this._parseNameAndPathFromURL(); return this._path; } @@ -620,8 +634,9 @@ get folder() { let path = this._parsedURL.path; const indexOfQuery = path.indexOf('?'); - if (indexOfQuery !== -1) + if (indexOfQuery !== -1) { path = path.substring(0, indexOfQuery); + } const lastSlashIndex = path.lastIndexOf('/'); return lastSlashIndex !== -1 ? path.substring(0, lastSlashIndex) : ''; } @@ -720,8 +735,9 @@ * @return {string|undefined} */ requestHeaderValue(headerName) { - if (this._requestHeaderValues[headerName]) + if (this._requestHeaderValues[headerName]) { return this._requestHeaderValues[headerName]; + } this._requestHeaderValues[headerName] = this._computeHeaderValue(this.requestHeaders(), headerName); return this._requestHeaderValues[headerName]; } @@ -730,8 +746,9 @@ * @return {?Array.<!SDK.Cookie>} */ get requestCookies() { - if (!this._requestCookies) + if (!this._requestCookies) { this._requestCookies = SDK.CookieParser.parseCookie(this.requestHeaderValue('Cookie')); + } return this._requestCookies; } @@ -739,8 +756,9 @@ * @return {!Promise<?string>} */ requestFormData() { - if (!this._requestFormDataPromise) + if (!this._requestFormDataPromise) { this._requestFormDataPromise = SDK.NetworkManager.requestPostData(this); + } return this._requestFormDataPromise; } @@ -758,8 +776,9 @@ */ _filteredProtocolName() { const protocol = this.protocol.toLowerCase(); - if (protocol === 'h2') + if (protocol === 'h2') { return 'http/2.0'; + } return protocol.replace(/^http\/2(\.0)?\+/, 'http/2.0+'); } @@ -770,8 +789,9 @@ const headersText = this.requestHeadersText(); if (!headersText) { const version = this.requestHeaderValue('version') || this.requestHeaderValue(':version'); - if (version) + if (version) { return version; + } return this._filteredProtocolName(); } const firstLine = headersText.split(/\r\n/)[0]; @@ -819,8 +839,9 @@ * @return {!Array.<!SDK.NetworkRequest.NameValue>} */ get sortedResponseHeaders() { - if (this._sortedResponseHeaders !== undefined) + if (this._sortedResponseHeaders !== undefined) { return this._sortedResponseHeaders; + } this._sortedResponseHeaders = this.responseHeaders.slice(); this._sortedResponseHeaders.sort(function(a, b) { @@ -834,8 +855,9 @@ * @return {string|undefined} */ responseHeaderValue(headerName) { - if (headerName in this._responseHeaderValues) + if (headerName in this._responseHeaderValues) { return this._responseHeaderValues[headerName]; + } this._responseHeaderValues[headerName] = this._computeHeaderValue(this.responseHeaders, headerName); return this._responseHeaderValues[headerName]; } @@ -844,8 +866,9 @@ * @return {!Array.<!SDK.Cookie>} */ get responseCookies() { - if (!this._responseCookies) + if (!this._responseCookies) { this._responseCookies = SDK.CookieParser.parseSetCookie(this.responseHeaderValue('Set-Cookie')); + } return this._responseCookies; } @@ -860,8 +883,9 @@ * @return {?Array.<!SDK.ServerTiming>} */ get serverTimings() { - if (typeof this._serverTimings === 'undefined') + if (typeof this._serverTimings === 'undefined') { this._serverTimings = SDK.ServerTiming.parseHeaders(this.responseHeaders); + } return this._serverTimings; } @@ -869,8 +893,9 @@ * @return {?string} */ queryString() { - if (this._queryString !== undefined) + if (this._queryString !== undefined) { return this._queryString; + } let queryString = null; const url = this.url(); @@ -878,8 +903,9 @@ if (questionMarkPosition !== -1) { queryString = url.substring(questionMarkPosition + 1); const hashSignPosition = queryString.indexOf('#'); - if (hashSignPosition !== -1) + if (hashSignPosition !== -1) { queryString = queryString.substring(0, hashSignPosition); + } } this._queryString = queryString; return this._queryString; @@ -889,11 +915,13 @@ * @return {?Array.<!SDK.NetworkRequest.NameValue>} */ get queryParameters() { - if (this._parsedQueryParameters) + if (this._parsedQueryParameters) { return this._parsedQueryParameters; + } const queryString = this.queryString(); - if (!queryString) + if (!queryString) { return null; + } this._parsedQueryParameters = this._parseParameters(queryString); return this._parsedQueryParameters; } @@ -904,14 +932,16 @@ async _parseFormParameters() { const requestContentType = this.requestContentType(); - if (!requestContentType) + if (!requestContentType) { return null; + } // Handling application/x-www-form-urlencoded request bodies. if (requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) { const formData = await this.requestFormData(); - if (!formData) + if (!formData) { return null; + } return this._parseParameters(formData); } @@ -919,16 +949,19 @@ // Handling multipart/form-data request bodies. const multipartDetails = requestContentType.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/); - if (!multipartDetails) + if (!multipartDetails) { return null; + } const boundary = multipartDetails[1]; - if (!boundary) + if (!boundary) { return null; + } const formData = await this.requestFormData(); - if (!formData) + if (!formData) { return null; + } return this._parseMultipartFormDataParameters(formData, boundary); } @@ -937,8 +970,9 @@ * @return {!Promise<?Array<!SDK.NetworkRequest.NameValue>>} */ formParameters() { - if (!this._formParametersPromise) + if (!this._formParametersPromise) { this._formParametersPromise = this._parseFormParameters(); + } return this._formParametersPromise; } @@ -949,8 +983,9 @@ const headersText = this._responseHeadersText; if (!headersText) { const version = this.responseHeaderValue('version') || this.responseHeaderValue(':version'); - if (version) + if (version) { return version; + } return this._filteredProtocolName(); } const firstLine = headersText.split(/\r\n/)[0]; @@ -965,10 +1000,11 @@ _parseParameters(queryString) { function parseNameValue(pair) { const position = pair.indexOf('='); - if (position === -1) + if (position === -1) { return {name: pair, value: ''}; - else + } else { return {name: pair.substring(0, position), value: pair.substring(position + 1)}; + } } return queryString.split('&').map(parseNameValue); } @@ -1015,8 +1051,9 @@ function parseMultipartField(result, field) { const [match, name, filename, contentType, value] = field.match(keyValuePattern) || []; - if (!match) + if (!match) { return result; + } const processedValue = (filename || contentType) ? ls`(binary)` : value; result.push({name, value: processedValue}); @@ -1035,14 +1072,17 @@ const values = []; for (let i = 0; i < headers.length; ++i) { - if (headers[i].name.toLowerCase() === headerName) + if (headers[i].name.toLowerCase() === headerName) { values.push(headers[i].value); + } } - if (!values.length) + if (!values.length) { return undefined; + } // Set-Cookie values should be separated by '\n', not comma, otherwise cookies could not be parsed. - if (headerName === 'set-cookie') + if (headerName === 'set-cookie') { return values.join('\n'); + } return values.join(', '); } @@ -1050,12 +1090,14 @@ * @return {!Promise<!SDK.NetworkRequest.ContentData>} */ contentData() { - if (this._contentData) + if (this._contentData) { return this._contentData; - if (this._contentDataProvider) + } + if (this._contentDataProvider) { this._contentData = this._contentDataProvider(); - else + } else { this._contentData = SDK.NetworkManager.requestContentData(this); + } return this._contentData; } @@ -1107,15 +1149,18 @@ * @return {!Promise<!Array<!Common.ContentProvider.SearchMatch>>} */ async searchInContent(query, caseSensitive, isRegex) { - if (!this._contentDataProvider) + if (!this._contentDataProvider) { return SDK.NetworkManager.searchInRequest(this, query, caseSensitive, isRegex); + } const contentData = await this.contentData(); let content = contentData.content; - if (!content) + if (!content) { return []; - if (contentData.encoded) + } + if (contentData.encoded) { content = window.atob(content); + } return Common.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex); } @@ -1190,11 +1235,13 @@ let imageSrc = Common.ContentProvider.contentAsDataURL(content, this._mimeType, encoded); if (imageSrc === null && !this._failed) { const cacheControl = this.responseHeaderValue('cache-control') || ''; - if (!cacheControl.includes('no-cache')) + if (!cacheControl.includes('no-cache')) { imageSrc = this._url; + } } - if (imageSrc !== null) + if (imageSrc !== null) { image.src = imageSrc; + } } /** @@ -1288,15 +1335,17 @@ */ charset() { const contentTypeHeader = this.responseHeaderValue('content-type'); - if (!contentTypeHeader) + if (!contentTypeHeader) { return null; + } const responseCharsets = contentTypeHeader.replace(/ /g, '') .split(';') .filter(parameter => parameter.toLowerCase().startsWith('charset=')) .map(parameter => parameter.slice('charset='.length)); - if (responseCharsets.length) + if (responseCharsets.length) { return responseCharsets[0]; + } return null; } @@ -1339,12 +1388,14 @@ // Generate request headers text from raw headers in extra request info because // Network.requestWillBeSentExtraInfo doesn't include headers text. let requestHeadersText = `${this.requestMethod} ${this.parsedURL.path}`; - if (this.parsedURL.queryParams) + if (this.parsedURL.queryParams) { requestHeadersText += `?${this.parsedURL.queryParams}`; + } requestHeadersText += ` HTTP/1.1\r\n`; - for (const {name, value} of this.requestHeaders()) + for (const {name, value} of this.requestHeaders()) { requestHeadersText += `${name}: ${value}\r\n`; + } this.setRequestHeadersText(requestHeadersText); } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js b/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js index f40c104..27c52b90 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/OverlayModel.js
@@ -54,13 +54,15 @@ */ static highlightObjectAsDOMNode(object) { const domModel = object.runtimeModel().target().model(SDK.DOMModel); - if (domModel) + if (domModel) { domModel.overlayModel().highlightInOverlay({object}); + } } static hideDOMNodeHighlight() { - for (const overlayModel of SDK.targetManager.models(SDK.OverlayModel)) + for (const overlayModel of SDK.targetManager.models(SDK.OverlayModel)) { overlayModel._delayedHideHighlight(0); + } } static async muteHighlight() { @@ -92,22 +94,30 @@ () => this._overlayAgent.setShowHitTestBorders(this._showHitTestBordersSetting.get())) ]; - if (this._showPaintRectsSetting.get()) + if (this._showPaintRectsSetting.get()) { this._overlayAgent.setShowPaintRects(true); - if (this._showLayoutShiftRegionsSetting.get()) + } + if (this._showLayoutShiftRegionsSetting.get()) { this._overlayAgent.setShowLayoutShiftRegions(true); - if (this._showAdHighlightsSetting.get()) + } + if (this._showAdHighlightsSetting.get()) { this._overlayAgent.setShowAdHighlights(true); - if (this._showDebugBordersSetting.get()) + } + if (this._showDebugBordersSetting.get()) { this._overlayAgent.setShowDebugBorders(true); - if (this._showFPSCounterSetting.get()) + } + if (this._showFPSCounterSetting.get()) { this._overlayAgent.setShowFPSCounter(true); - if (this._showScrollBottleneckRectsSetting.get()) + } + if (this._showScrollBottleneckRectsSetting.get()) { this._overlayAgent.setShowScrollBottleneckRects(true); - if (this._showHitTestBordersSetting.get()) + } + if (this._showHitTestBordersSetting.get()) { this._overlayAgent.setShowHitTestBorders(true); - if (this._debuggerModel.isPaused()) + } + if (this._debuggerModel.isPaused()) { this._updatePausedInDebuggerMessage(); + } return this._overlayAgent.setShowViewportSizeOnResize(this._showViewportSizeOnResize); } @@ -134,8 +144,9 @@ */ setShowViewportSizeOnResize(show) { this._showViewportSizeOnResize = show; - if (this.target().suspended()) + if (this.target().suspended()) { return; + } this._overlayAgent.setShowViewportSizeOnResize(show); } @@ -143,8 +154,9 @@ * @return {!Promise} */ _updatePausedInDebuggerMessage() { - if (this.target().suspended()) + if (this.target().suspended()) { return Promise.resolve(); + } const message = this._debuggerModel.isPaused() && !Common.moduleSetting('disablePausedStateOverlay').get() ? Common.UIString('Paused in debugger') : undefined; @@ -188,8 +200,9 @@ this._hideHighlightTimeout = null; } const highlightConfig = this._buildHighlightConfig(mode); - if (typeof showInfo !== 'undefined') + if (typeof showInfo !== 'undefined') { highlightConfig.showInfo = showInfo; + } this._highlighter.highlightInOverlay(data, highlightConfig); } @@ -205,8 +218,9 @@ * @param {number} delay */ _delayedHideHighlight(delay) { - if (this._hideHighlightTimeout === null) + if (this._hideHighlightTimeout === null) { this._hideHighlightTimeout = setTimeout(() => this.highlightInOverlay({}), delay); + } } /** @@ -229,17 +243,21 @@ const showRulers = Common.moduleSetting('showMetricsRulers').get(); const highlightConfig = {showInfo: mode === 'all', showRulers: showRulers, showStyles, showExtensionLines: showRulers}; - if (mode === 'all' || mode === 'content') + if (mode === 'all' || mode === 'content') { highlightConfig.contentColor = Common.Color.PageHighlight.Content.toProtocolRGBA(); + } - if (mode === 'all' || mode === 'padding') + if (mode === 'all' || mode === 'padding') { highlightConfig.paddingColor = Common.Color.PageHighlight.Padding.toProtocolRGBA(); + } - if (mode === 'all' || mode === 'border') + if (mode === 'all' || mode === 'border') { highlightConfig.borderColor = Common.Color.PageHighlight.Border.toProtocolRGBA(); + } - if (mode === 'all' || mode === 'margin') + if (mode === 'all' || mode === 'margin') { highlightConfig.marginColor = Common.Color.PageHighlight.Margin.toProtocolRGBA(); + } if (mode === 'all') { highlightConfig.eventTargetColor = Common.Color.PageHighlight.EventTarget.toProtocolRGBA(); @@ -247,8 +265,9 @@ highlightConfig.shapeMarginColor = Common.Color.PageHighlight.ShapeMargin.toProtocolRGBA(); } - if (mode === 'all') + if (mode === 'all') { highlightConfig.cssGridColor = Common.Color.PageHighlight.CssGrid.toProtocolRGBA(); + } return highlightConfig; } @@ -259,8 +278,9 @@ */ nodeHighlightRequested(nodeId) { const node = this._domModel.nodeForId(nodeId); - if (node) + if (node) { this.dispatchEventToListeners(SDK.OverlayModel.Events.HighlightNodeRequested, node); + } } /** @@ -278,8 +298,9 @@ const deferredNode = new SDK.DeferredDOMNode(this.target(), backendNodeId); if (SDK.OverlayModel._inspectNodeHandler) { deferredNode.resolvePromise().then(node => { - if (node) + if (node) { SDK.OverlayModel._inspectNodeHandler(node); + } }); } else { Common.Revealer.reveal(deferredNode); @@ -366,10 +387,11 @@ const nodeId = node ? node.id : undefined; const backendNodeId = deferredNode ? deferredNode.backendNodeId() : undefined; const objectId = object ? object.objectId : undefined; - if (nodeId || backendNodeId || objectId) + if (nodeId || backendNodeId || objectId) { this._model._overlayAgent.highlightNode(config, nodeId, backendNodeId, objectId, selectorList); - else + } else { this._model._overlayAgent.hideHighlight(); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/PaintProfiler.js b/third_party/blink/renderer/devtools/front_end/sdk/PaintProfiler.js index 61e3208..33cfd7cb 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/PaintProfiler.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/PaintProfiler.js
@@ -85,8 +85,9 @@ release() { console.assert(this._refCount > 0, 'release is already called on the object'); - if (!--this._refCount) + if (!--this._refCount) { this._paintProfilerModel._layerTreeAgent.releaseSnapshot(this._id); + } } addReference() {
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ProfileTreeModel.js b/third_party/blink/renderer/devtools/front_end/sdk/ProfileTreeModel.js index 4f646b2..856b44a 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ProfileTreeModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ProfileTreeModel.js
@@ -91,16 +91,18 @@ while (nodesToTraverse.length) { const parent = nodesToTraverse.pop(); const depth = parent.depth + 1; - if (depth > this.maxDepth) + if (depth > this.maxDepth) { this.maxDepth = depth; + } const children = parent.children; const length = children.length; for (let i = 0; i < length; ++i) { const child = children[i]; child.depth = depth; child.parent = parent; - if (child.children.length) + if (child.children.length) { nodesToTraverse.push(child); + } } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/RemoteObject.js b/third_party/blink/renderer/devtools/front_end/sdk/RemoteObject.js index b44adf8e0..bbd9834 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/RemoteObject.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/RemoteObject.js
@@ -55,12 +55,14 @@ * @return {string} */ static type(remoteObject) { - if (remoteObject === null) + if (remoteObject === null) { return 'null'; + } const type = typeof remoteObject; - if (type !== 'object' && type !== 'function') + if (type !== 'object' && type !== 'function') { return type; + } return remoteObject.type; } @@ -79,8 +81,9 @@ * @return {number} */ static arrayLength(object) { - if (object.subtype !== 'array' && object.subtype !== 'typedarray') + if (object.subtype !== 'array' && object.subtype !== 'typedarray') { return 0; + } // Array lengths in V8-generated descriptions switched from square brackets to parentheses. // Both formats are checked in case the front end is dealing with an old version of V8. const parenMatches = object.description.match(SDK.RemoteObject._descriptionLengthParenRegex); @@ -96,15 +99,18 @@ const type = typeof object; if (type === 'number') { const description = String(object); - if (object === 0 && 1 / object < 0) + if (object === 0 && 1 / object < 0) { return SDK.RemoteObject.UnserializableNumber.Negative0; + } if (description === SDK.RemoteObject.UnserializableNumber.NaN || description === SDK.RemoteObject.UnserializableNumber.Infinity || - description === SDK.RemoteObject.UnserializableNumber.NegativeInfinity) + description === SDK.RemoteObject.UnserializableNumber.NegativeInfinity) { return description; + } } - if (type === 'bigint') + if (type === 'bigint') { return object + 'n'; + } return null; } @@ -114,34 +120,41 @@ */ static toCallArgument(object) { const type = typeof object; - if (type === 'undefined') + if (type === 'undefined') { return {}; + } const unserializableDescription = SDK.RemoteObject.unserializableDescription(object); if (type === 'number') { - if (unserializableDescription !== null) + if (unserializableDescription !== null) { return {unserializableValue: unserializableDescription}; + } return {value: object}; } - if (type === 'bigint') + if (type === 'bigint') { return {unserializableValue: /** @type {!Protocol.Runtime.UnserializableValue} */ (unserializableDescription)}; - if (type === 'string' || type === 'boolean') + } + if (type === 'string' || type === 'boolean') { return {value: object}; + } - if (!object) + if (!object) { return {value: null}; + } // The unserializableValue is a function on SDK.RemoteObject's and a simple property on // Protocol.Runtime.RemoteObject's. if (object instanceof SDK.RemoteObject) { const unserializableValue = object.unserializableValue(); - if (unserializableValue !== undefined) + if (unserializableValue !== undefined) { return {unserializableValue: unserializableValue}; + } } else if (object.unserializableValue !== undefined) { return {unserializableValue: object.unserializableValue}; } - if (typeof object.objectId !== 'undefined') + if (typeof object.objectId !== 'undefined') { return {objectId: object.objectId}; + } return {value: object.value}; } @@ -159,25 +172,29 @@ const accessorProperties = result[0].properties; const ownProperties = result[1].properties; const internalProperties = result[1].internalProperties; - if (!ownProperties || !accessorProperties) + if (!ownProperties || !accessorProperties) { return /** @type {!SDK.GetPropertiesResult} */ ({properties: null, internalProperties: null}); + } const propertiesMap = new Map(); const propertySymbols = []; for (let i = 0; i < accessorProperties.length; i++) { const property = accessorProperties[i]; - if (property.symbol) + if (property.symbol) { propertySymbols.push(property); - else + } else { propertiesMap.set(property.name, property); + } } for (let i = 0; i < ownProperties.length; i++) { const property = ownProperties[i]; - if (property.isAccessorProperty()) + if (property.isAccessorProperty()) { continue; - if (property.symbol) + } + if (property.symbol) { propertySymbols.push(property); - else + } else { propertiesMap.set(property.name, property); + } } return { properties: propertiesMap.valuesArray().concat(propertySymbols), @@ -358,22 +375,25 @@ this._preview = preview; } else { this._description = description; - if (!this.description && unserializableValue) + if (!this.description && unserializableValue) { this._description = unserializableValue; - if (!this._description && (typeof value !== 'object' || value === null)) + } + if (!this._description && (typeof value !== 'object' || value === null)) { this._description = value + ''; + } this._hasChildren = false; if (typeof unserializableValue === 'string') { this._unserializableValue = unserializableValue; if (unserializableValue === SDK.RemoteObject.UnserializableNumber.Infinity || unserializableValue === SDK.RemoteObject.UnserializableNumber.NegativeInfinity || unserializableValue === SDK.RemoteObject.UnserializableNumber.Negative0 || - unserializableValue === SDK.RemoteObject.UnserializableNumber.NaN) + unserializableValue === SDK.RemoteObject.UnserializableNumber.NaN) { this._value = Number(unserializableValue); - else if (type === 'bigint' && unserializableValue.endsWith('n')) + } else if (type === 'bigint' && unserializableValue.endsWith('n')) { this._value = BigInt(unserializableValue.substring(0, unserializableValue.length - 1)); - else + } else { this._value = unserializableValue; + } } else { this._value = value; @@ -489,13 +509,15 @@ * @return {!Promise<!SDK.GetPropertiesResult>} */ async doGetProperties(ownProperties, accessorPropertiesOnly, generatePreview) { - if (!this._objectId) + if (!this._objectId) { return /** @type {!SDK.GetPropertiesResult} */ ({properties: null, internalProperties: null}); + } const response = await this._runtimeAgent.invoke_getProperties( {objectId: this._objectId, ownProperties, accessorPropertiesOnly, generatePreview}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return /** @type {!SDK.GetPropertiesResult} */ ({properties: null, internalProperties: null}); + } if (response.exceptionDetails) { this._runtimeModel.exceptionThrown(Date.now(), response.exceptionDetails); return /** @type {!SDK.GetPropertiesResult} */ ({properties: null, internalProperties: null}); @@ -510,10 +532,12 @@ !!property.wasThrown, propertySymbol); if (typeof property.value === 'undefined') { - if (property.get && property.get.type !== 'undefined') + if (property.get && property.get.type !== 'undefined') { remoteProperty.getter = this._runtimeModel.createRemoteObject(property.get); - if (property.set && property.set.type !== 'undefined') + } + if (property.set && property.set.type !== 'undefined') { remoteProperty.setter = this._runtimeModel.createRemoteObject(property.set); + } } result.push(remoteProperty); } @@ -526,10 +550,12 @@ const internalPropertiesResult = []; for (const property of internalProperties) { - if (!property.value) + if (!property.value) { continue; - if (property.name === '[[StableObjectId]]') + } + if (property.name === '[[StableObjectId]]') { continue; + } const propertyValue = this._runtimeModel.createRemoteObject(property.value); internalPropertiesResult.push(new SDK.RemoteObjectProperty( property.name, propertyValue, true, false, undefined, undefined, undefined, true)); @@ -544,8 +570,9 @@ * @return {!Promise<string|undefined>} */ async setPropertyValue(name, value) { - if (!this._objectId) + if (!this._objectId) { return `Can't set a property of non-object.`; + } const response = await this._runtimeAgent.invoke_evaluate({expression: value, silent: true}); if (response[Protocol.Error] || response.exceptionDetails) { @@ -554,13 +581,15 @@ /** @type {string} */ (response.result.value)); } - if (typeof name === 'string') + if (typeof name === 'string') { name = SDK.RemoteObject.toCallArgument(name); + } const resultPromise = this.doSetObjectPropertyValue(response.result, name); - if (response.result.objectId) + if (response.result.objectId) { this._runtimeAgent.releaseObject(response.result.objectId); + } return resultPromise; } @@ -590,18 +619,21 @@ * @return {!Promise<string|undefined>} */ async deleteProperty(name) { - if (!this._objectId) + if (!this._objectId) { return `Can't delete a property of non-object.`; + } const deletePropertyFunction = 'function(a) { delete this[a]; return !(a in this); }'; const response = await this._runtimeAgent.invoke_callFunctionOn( {objectId: this._objectId, functionDeclaration: deletePropertyFunction, arguments: [name], silent: true}); - if (response[Protocol.Error] || response.exceptionDetails) + if (response[Protocol.Error] || response.exceptionDetails) { return response[Protocol.Error] || response.result.description; + } - if (!response.result.value) + if (!response.result.value) { return 'Failed to delete property.'; + } } /** @@ -613,8 +645,9 @@ async callFunction(functionDeclaration, args) { const response = await this._runtimeAgent.invoke_callFunctionOn( {objectId: this._objectId, functionDeclaration: functionDeclaration.toString(), arguments: args, silent: true}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return {object: null, wasThrown: false}; + } // TODO: release exceptionDetails object return {object: this._runtimeModel.createRemoteObject(response.result), wasThrown: !!response.exceptionDetails}; } @@ -641,8 +674,9 @@ * @override */ release() { - if (!this._objectId) + if (!this._objectId) { return; + } this._runtimeAgent.releaseObject(this._objectId); } @@ -706,8 +740,9 @@ * @return {!Promise<!SDK.GetPropertiesResult>} */ async doGetProperties(ownProperties, accessorPropertiesOnly, generatePreview) { - if (accessorPropertiesOnly) + if (accessorPropertiesOnly) { return /** @type {!SDK.GetPropertiesResult} */ ({properties: [], internalProperties: []}); + } if (this._savedScopeProperties) { // No need to reload scope variables, as the remote object never @@ -721,8 +756,9 @@ if (this._scopeRef && Array.isArray(allProperties.properties)) { this._savedScopeProperties = allProperties.properties.slice(); if (!this._scopeRef.callFrameId) { - for (const property of this._savedScopeProperties) + for (const property of this._savedScopeProperties) { property.writable = false; + } } } return allProperties; @@ -738,12 +774,14 @@ const name = /** @type {string} */ (argumentName.value); const error = await this.debuggerModel().setVariableValue( this._scopeRef.number, name, SDK.RemoteObject.toCallArgument(result), this._scopeRef.callFrameId); - if (error) + if (error) { return error; + } if (this._savedScopeProperties) { for (const property of this._savedScopeProperties) { - if (property.name === name) + if (property.name === name) { property.value = this._runtimeModel.createRemoteObject(result); + } } } } @@ -778,18 +816,21 @@ */ constructor(name, value, enumerable, writable, isOwn, wasThrown, symbol, synthetic, syntheticSetter, isPrivate) { this.name = name; - if (value !== null) + if (value !== null) { this.value = value; + } this.enumerable = typeof enumerable !== 'undefined' ? enumerable : true; const isNonSyntheticOrSyntheticWritable = !synthetic || !!syntheticSetter; this.writable = typeof writable !== 'undefined' ? writable : isNonSyntheticOrSyntheticWritable; this.isOwn = !!isOwn; this.wasThrown = !!wasThrown; - if (symbol) + if (symbol) { this.symbol = symbol; + } this.synthetic = !!synthetic; - if (syntheticSetter) + if (syntheticSetter) { this.syntheticSetter = syntheticSetter; + } this.private = !!isPrivate; } @@ -798,11 +839,13 @@ * @return {!Promise<boolean>} */ async setSyntheticValue(expression) { - if (!this.syntheticSetter) + if (!this.syntheticSetter) { return false; + } const result = await this.syntheticSetter(expression); - if (result) + if (result) { this.value = result; + } return !!result; } @@ -863,8 +906,9 @@ * @return {string} */ get description() { - if (this._cachedDescription) + if (this._cachedDescription) { return this._cachedDescription; + } /** * @param {!SDK.RemoteObjectProperty} property @@ -882,8 +926,9 @@ */ function formatObjectItem(property) { let name = property.name; - if (/^\s|\s$|^$|\n/.test(name)) + if (/^\s|\s$|^$|\n/.test(name)) { name = '"' + name.replace(/\n/g, '\u21B5') + '"'; + } return name + ': ' + this._formatValue(property.value); } @@ -913,11 +958,13 @@ * @return {string} */ _formatValue(value) { - if (!value) + if (!value) { return 'undefined'; + } const description = value.description || ''; - if (value.type === 'string') + if (value.type === 'string') { return '"' + description.replace(/\n/g, '\u21B5') + '"'; + } return description; } @@ -938,8 +985,9 @@ buffer += ',\u2026'; break; } - if (i) + if (i) { buffer += ', '; + } buffer += itemDescription; } buffer += suffix; @@ -959,14 +1007,17 @@ * @return {string|undefined} */ get subtype() { - if (this._value === null) + if (this._value === null) { return 'null'; + } - if (Array.isArray(this._value)) + if (Array.isArray(this._value)) { return 'array'; + } - if (this._value instanceof Date) + if (this._value instanceof Date) { return 'date'; + } return undefined; } @@ -976,8 +1027,9 @@ * @return {boolean} */ get hasChildren() { - if ((typeof this._value !== 'object') || (this._value === null)) + if ((typeof this._value !== 'object') || (this._value === null)) { return false; + } return !!Object.keys(/** @type {!Object} */ (this._value)).length; } @@ -1010,8 +1062,9 @@ * @return {!Array.<!SDK.RemoteObjectProperty>} */ _children() { - if (!this.hasChildren) + if (!this.hasChildren) { return []; + } const value = /** @type {!Object} */ (this._value); /** @@ -1020,12 +1073,14 @@ */ function buildProperty(propName) { let propValue = value[propName]; - if (!(propValue instanceof SDK.RemoteObject)) + if (!(propValue instanceof SDK.RemoteObject)) { propValue = SDK.RemoteObject.fromLocalObject(propValue); + } return new SDK.RemoteObjectProperty(propName, propValue); } - if (!this._cachedChildren) + if (!this._cachedChildren) { this._cachedChildren = Object.keys(value).map(buildProperty); + } return this._cachedChildren; } @@ -1094,8 +1149,9 @@ * @return {!SDK.RemoteArray} */ static objectAsArray(object) { - if (!object || object.type !== 'object' || (object.subtype !== 'array' && object.subtype !== 'typedarray')) + if (!object || object.type !== 'object' || (object.subtype !== 'array' && object.subtype !== 'typedarray')) { throw new Error('Object is empty or not an array'); + } return new SDK.RemoteArray(object); } @@ -1104,19 +1160,22 @@ * @return {!Promise<!SDK.RemoteArray>} */ static createFromRemoteObjects(objects) { - if (!objects.length) + if (!objects.length) { throw new Error('Input array is empty'); + } const objectArguments = []; - for (let i = 0; i < objects.length; ++i) + for (let i = 0; i < objects.length; ++i) { objectArguments.push(SDK.RemoteObject.toCallArgument(objects[i])); + } return objects[0].callFunction(createArray, objectArguments).then(returnRemoteArray); /** * @return {!Array<*>} */ function createArray() { - if (arguments.length > 1) + if (arguments.length > 1) { return new Array(arguments); + } return [arguments[0]]; } @@ -1125,8 +1184,9 @@ * @return {!SDK.RemoteArray} */ function returnRemoteArray(result) { - if (result.wasThrown || !result.object) + if (result.wasThrown || !result.object) { throw new Error('Call function throws exceptions or returns empty value'); + } return SDK.RemoteArray.objectAsArray(result.object); } } @@ -1136,8 +1196,9 @@ * @return {!Promise<!SDK.RemoteObject>} */ at(index) { - if (index < 0 || index > this._object.arrayLength()) + if (index < 0 || index > this._object.arrayLength()) { throw new Error('Out of range'); + } return this._object.callFunction(at, [SDK.RemoteObject.toCallArgument(index)]).then(assertCallFunctionResult); /** @@ -1155,8 +1216,9 @@ * @return {!SDK.RemoteObject} */ function assertCallFunctionResult(result) { - if (result.wasThrown || !result.object) + if (result.wasThrown || !result.object) { throw new Error('Exception in callFunction or result value is empty'); + } return result.object; } } @@ -1175,8 +1237,9 @@ */ map(func) { const promises = []; - for (let i = 0; i < this.length(); ++i) + for (let i = 0; i < this.length(); ++i) { promises.push(this.at(i).then(func)); + } return Promise.all(promises); } @@ -1202,8 +1265,9 @@ * @return {!SDK.RemoteFunction} */ static objectAsFunction(object) { - if (!object || object.type !== 'function') + if (!object || object.type !== 'function') { throw new Error('Object is empty or not a function'); + } return new SDK.RemoteFunction(object); } @@ -1219,12 +1283,14 @@ * @this {SDK.RemoteFunction} */ function targetFunction(ownProperties) { - if (!ownProperties.internalProperties) + if (!ownProperties.internalProperties) { return this._object; + } const internalProperties = ownProperties.internalProperties; for (const property of internalProperties) { - if (property.name === '[[TargetFunction]]') + if (property.name === '[[TargetFunction]]') { return property.value; + } } return this._object; } @@ -1253,8 +1319,9 @@ * @return {?SDK.DebuggerModel.FunctionDetails} */ function releaseTargetFunction(targetFunction, functionDetails) { - if (targetFunction) + if (targetFunction) { targetFunction.release(); + } return functionDetails; } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/Resource.js b/third_party/blink/renderer/devtools/front_end/sdk/Resource.js index 50fd5a45..095c6b1 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/Resource.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/Resource.js
@@ -59,16 +59,18 @@ /** @type {?string} */ this._content; /** @type {boolean} */ this._contentEncoded; this._pendingContentCallbacks = []; - if (this._request && !this._request.finished) + if (this._request && !this._request.finished) { this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._requestFinished, this); + } } /** * @return {?Date} */ lastModified() { - if (this._lastModified || !this._request) + if (this._lastModified || !this._request) { return this._lastModified; + } const lastModifiedHeader = this._request.responseLastModified(); const date = lastModifiedHeader ? new Date(lastModifiedHeader) : null; this._lastModified = date && date.isValid() ? date : null; @@ -79,8 +81,9 @@ * @return {?number} */ contentSize() { - if (typeof this._contentSize === 'number' || !this._request) + if (typeof this._contentSize === 'number' || !this._request) { return this._contentSize; + } return this._request.resourceSize; } @@ -172,8 +175,9 @@ * @return {!Common.ResourceType} */ contentType() { - if (this.resourceType() === Common.resourceTypes.Document && this.mimeType.indexOf('javascript') !== -1) + if (this.resourceType() === Common.resourceTypes.Document && this.mimeType.indexOf('javascript') !== -1) { return Common.resourceTypes.Script; + } return this.resourceType(); } @@ -191,14 +195,16 @@ * @return {!Promise<string>} */ requestContent() { - if (typeof this._content !== 'undefined') + if (typeof this._content !== 'undefined') { return Promise.resolve(/** @type {string} */ (this._content)); + } let callback; const promise = new Promise(fulfill => callback = fulfill); this._pendingContentCallbacks.push(callback); - if (!this._request || this._request.finished) + if (!this._request || this._request.finished) { this._innerRequestContent(); + } return promise; } @@ -217,10 +223,12 @@ * @return {!Promise<!Array<!Common.ContentProvider.SearchMatch>>} */ async searchInContent(query, caseSensitive, isRegex) { - if (!this.frameId) + if (!this.frameId) { return []; - if (this.request) + } + if (this.request) { return this.request.searchInContent(query, caseSensitive, isRegex); + } const result = await this._resourceTreeModel.target().pageAgent().searchInResource( this.frameId, this.url, query, caseSensitive, isRegex); return result || []; @@ -237,13 +245,15 @@ _requestFinished() { this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._requestFinished, this); - if (this._pendingContentCallbacks.length) + if (this._pendingContentCallbacks.length) { this._innerRequestContent(); + } } async _innerRequestContent() { - if (this._contentRequested) + if (this._contentRequested) { return; + } this._contentRequested = true; if (this.request) { @@ -257,11 +267,13 @@ this._contentEncoded = response.base64Encoded; } - if (this._content === null) + if (this._content === null) { this._contentEncoded = false; + } - for (const callback of this._pendingContentCallbacks.splice(0)) + for (const callback of this._pendingContentCallbacks.splice(0)) { callback(this._content); + } delete this._contentRequested; } @@ -269,10 +281,12 @@ * @return {boolean} */ hasTextContent() { - if (this._type.isTextType()) + if (this._type.isTextType()) { return true; - if (this._type === Common.resourceTypes.Other) + } + if (this._type === Common.resourceTypes.Other) { return !!this._content && !this._contentEncoded; + } return false; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ResourceTreeModel.js b/third_party/blink/renderer/devtools/front_end/sdk/ResourceTreeModel.js index 915594c..2ae93013 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ResourceTreeModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ResourceTreeModel.js
@@ -66,8 +66,9 @@ static frameForRequest(request) { const networkManager = SDK.NetworkManager.forRequest(request); const resourceTreeModel = networkManager ? networkManager.target().model(SDK.ResourceTreeModel) : null; - if (!resourceTreeModel) + if (!resourceTreeModel) { return null; + } return resourceTreeModel.frameForId(request.frameId); } @@ -76,8 +77,9 @@ */ static frames() { let result = []; - for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) + for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { result = result.concat(resourceTreeModel._frames.valuesArray()); + } return result; } @@ -89,8 +91,9 @@ for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { const mainFrame = resourceTreeModel.mainFrame; const result = mainFrame ? mainFrame.resourceForURL(url) : null; - if (result) + if (result) { return result; + } } return null; } @@ -101,8 +104,9 @@ */ static reloadAllPages(bypassCache, scriptToEvaluateOnLoad) { for (const resourceTreeModel of SDK.targetManager.models(SDK.ResourceTreeModel)) { - if (!resourceTreeModel.target().parentTarget()) + if (!resourceTreeModel.target().parentTarget()) { resourceTreeModel.reloadPage(bypassCache, scriptToEvaluateOnLoad); + } } } @@ -151,8 +155,9 @@ */ _addFrame(frame, aboutToNavigate) { this._frames.set(frame.id, frame); - if (frame.isMainFrame()) + if (frame.isMainFrame()) { this.mainFrame = frame; + } this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameAdded, frame); this._updateSecurityOrigins(); } @@ -166,14 +171,17 @@ _frameAttached(frameId, parentFrameId, stackTrace) { const parentFrame = parentFrameId ? (this._frames.get(parentFrameId) || null) : null; // Do nothing unless cached resource tree is processed - it will overwrite everything. - if (!this._cachedResourcesProcessed && parentFrame) + if (!this._cachedResourcesProcessed && parentFrame) { return null; - if (this._frames.has(frameId)) + } + if (this._frames.has(frameId)) { return null; + } const frame = new SDK.ResourceTreeFrame(this, parentFrame, frameId, null, stackTrace || null); - if (parentFrameId && !parentFrame) + if (parentFrameId && !parentFrame) { frame._crossTargetParentFrameId = parentFrameId; + } if (frame.isMainFrame() && this.mainFrame) { // Navigation to the new backend process. this._frameDetached(this.mainFrame.id); @@ -188,8 +196,9 @@ _frameNavigated(framePayload) { const parentFrame = framePayload.parentId ? (this._frames.get(framePayload.parentId) || null) : null; // Do nothing unless cached resource tree is processed - it will overwrite everything. - if (!this._cachedResourcesProcessed && parentFrame) + if (!this._cachedResourcesProcessed && parentFrame) { return; + } let frame = this._frames.get(framePayload.id); if (!frame) { // Simulate missed "frameAttached" for a main frame navigation to the new backend process. @@ -201,16 +210,19 @@ frame._navigate(framePayload); this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameNavigated, frame); - if (frame.isMainFrame()) + if (frame.isMainFrame()) { this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.MainFrameNavigated, frame); + } // Fill frame with retained resources (the ones loaded using new loader). const resources = frame.resources(); - for (let i = 0; i < resources.length; ++i) + for (let i = 0; i < resources.length; ++i) { this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.ResourceAdded, resources[i]); + } - if (frame.isMainFrame()) + if (frame.isMainFrame()) { this.target().setInspectedURL(frame.url); + } this._updateSecurityOrigins(); } @@ -219,17 +231,20 @@ */ _frameDetached(frameId) { // Do nothing unless cached resource tree is processed - it will overwrite everything. - if (!this._cachedResourcesProcessed) + if (!this._cachedResourcesProcessed) { return; + } const frame = this._frames.get(frameId); - if (!frame) + if (!frame) { return; + } - if (frame.parentFrame) + if (frame.parentFrame) { frame.parentFrame._removeChildFrame(frame); - else + } else { frame._remove(); + } this._updateSecurityOrigins(); } @@ -237,33 +252,39 @@ * @param {!Common.Event} event */ _onRequestFinished(event) { - if (!this._cachedResourcesProcessed) + if (!this._cachedResourcesProcessed) { return; + } const request = /** @type {!SDK.NetworkRequest} */ (event.data); - if (request.failed || request.resourceType() === Common.resourceTypes.XHR) + if (request.failed || request.resourceType() === Common.resourceTypes.XHR) { return; + } const frame = this._frames.get(request.frameId); - if (frame) + if (frame) { frame._addRequest(request); + } } /** * @param {!Common.Event} event */ _onRequestUpdateDropped(event) { - if (!this._cachedResourcesProcessed) + if (!this._cachedResourcesProcessed) { return; + } const frameId = event.data.frameId; const frame = this._frames.get(frameId); - if (!frame) + if (!frame) { return; + } const url = event.data.url; - if (frame._resourcesMap[url]) + if (frame._resourcesMap[url]) { return; + } const resource = new SDK.Resource( this, null, url, frame.url, frameId, event.data.loaderId, Common.resourceTypes[event.data.resourceType], @@ -284,8 +305,9 @@ * @return {boolean} */ forAllResources(callback) { - if (this.mainFrame) + if (this.mainFrame) { return this.mainFrame._callForFrameResources(callback); + } return false; } @@ -312,12 +334,14 @@ _addFramesRecursively(parentFrame, frameTreePayload) { const framePayload = frameTreePayload.frame; const frame = new SDK.ResourceTreeFrame(this, parentFrame, framePayload.id, framePayload, null); - if (!parentFrame && framePayload.parentId) + if (!parentFrame && framePayload.parentId) { frame._crossTargetParentFrameId = framePayload.parentId; + } this._addFrame(frame); - for (let i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i) + for (let i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i) { this._addFramesRecursively(frame, frameTreePayload.childFrames[i]); + } for (let i = 0; i < frameTreePayload.resources.length; ++i) { const subresource = frameTreePayload.resources[i]; @@ -356,8 +380,9 @@ resumeReload() { this._reloadSuspensionCount--; console.assert(this._reloadSuspensionCount >= 0, 'Unbalanced call to ResourceTreeModel.resumeReload()'); - if (!this._reloadSuspensionCount && this._pendingReloadOptions) + if (!this._reloadSuspensionCount && this._pendingReloadOptions) { this.reloadPage.apply(this, this._pendingReloadOptions); + } } /** @@ -366,8 +391,9 @@ */ reloadPage(bypassCache, scriptToEvaluateOnLoad) { // Only dispatch PageReloadRequested upon first reload request to simplify client logic. - if (!this._pendingReloadOptions) + if (!this._pendingReloadOptions) { this.dispatchEventToListeners(SDK.ResourceTreeModel.Events.PageReloadRequested, this); + } if (this._reloadSuspensionCount) { this._pendingReloadOptions = [bypassCache, scriptToEvaluateOnLoad]; return; @@ -390,8 +416,9 @@ */ async navigationHistory() { const response = await this._agent.invoke_getNavigationHistory({}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return null; + } return {currentIndex: response.currentIndex, entries: response.entries}; } @@ -407,8 +434,9 @@ */ async fetchAppManifest() { const response = await this._agent.invoke_getAppManifest({}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return {url: response.url, data: null, errors: []}; + } return {url: response.url, data: response.data || null, errors: response.errors}; } @@ -440,8 +468,9 @@ return parents.reverse(); } - if (a.target() !== b.target()) + if (a.target() !== b.target()) { return SDK.ExecutionContext.comparator(a, b); + } const framesA = a.frameId ? framePath(this.frameForId(a.frameId)) : []; const framesB = b.frameId ? framePath(this.frameForId(b.frameId)) : []; @@ -454,14 +483,17 @@ break; } } - if (!frameA && frameB) + if (!frameA && frameB) { return -1; + } - if (!frameB && frameA) + if (!frameB && frameA) { return 1; + } - if (frameA && frameB) + if (frameA && frameB) { return frameA.id.localeCompare(frameB.id); + } return SDK.ExecutionContext.comparator(a, b); } @@ -477,8 +509,9 @@ let unreachableMainSecurityOrigin = null; for (const frame of this._frames.values()) { const origin = frame.securityOrigin; - if (!origin) + if (!origin) { continue; + } securityOrigins.add(origin); if (frame.isMainFrame()) { @@ -584,8 +617,9 @@ */ this._resourcesMap = {}; - if (this._parentFrame) + if (this._parentFrame) { this._parentFrame._childFrames.push(this); + } } @@ -602,8 +636,9 @@ const mainResource = this._resourcesMap[this._url]; this._resourcesMap = {}; this._removeChildFrames(); - if (mainResource && mainResource.loaderId === this._loaderId) + if (mainResource && mainResource.loaderId === this._loaderId) { this.addResource(mainResource); + } } /** @@ -673,13 +708,16 @@ * @return {?SDK.ResourceTreeFrame} */ crossTargetParentFrame() { - if (!this._crossTargetParentFrameId) + if (!this._crossTargetParentFrameId) { return null; - if (!this._model.target().parentTarget()) + } + if (!this._model.target().parentTarget()) { return null; + } const parentModel = this._model.target().parentTarget().model(SDK.ResourceTreeModel); - if (!parentModel) + if (!parentModel) { return null; + } // Note that parent model has already processed cached resources: // - when parent target was created, we issued getResourceTree call; // - strictly after we issued setAutoAttach call; @@ -697,8 +735,9 @@ let stackTrace = this._creationStackTrace; while (stackTrace) { const foundEntry = stackTrace.callFrames.find(searchFn); - if (foundEntry) + if (foundEntry) { return foundEntry; + } stackTrace = this.parent; } return null; @@ -733,8 +772,9 @@ _removeChildFrames() { const frames = this._childFrames; this._childFrames = []; - for (let i = 0; i < frames.length; ++i) + for (let i = 0; i < frames.length; ++i) { frames[i]._remove(); + } } _remove() { @@ -776,8 +816,9 @@ */ resources() { const result = []; - for (const url in this._resourcesMap) + for (const url in this._resourcesMap) { result.push(this._resourcesMap[url]); + } return result; } @@ -787,10 +828,12 @@ */ resourceForURL(url) { let resource = this._resourcesMap[url] || null; - if (resource) + if (resource) { return resource; - for (let i = 0; !resource && i < this._childFrames.length; ++i) + } + for (let i = 0; !resource && i < this._childFrames.length; ++i) { resource = this._childFrames[i].resourceForURL(url); + } return resource; } @@ -800,13 +843,15 @@ */ _callForFrameResources(callback) { for (const url in this._resourcesMap) { - if (callback(this._resourcesMap[url])) + if (callback(this._resourcesMap[url])) { return true; + } } for (let i = 0; i < this._childFrames.length; ++i) { - if (this._childFrames[i]._callForFrameResources(callback)) + if (this._childFrames[i]._callForFrameResources(callback)) { return true; + } } return false; } @@ -815,12 +860,14 @@ * @return {string} */ displayName() { - if (this.isTopFrame()) + if (this.isTopFrame()) { return Common.UIString('top'); + } const subtitle = new Common.ParsedURL(this._url).displayName; if (subtitle) { - if (!this._name) + if (!this._name) { return subtitle; + } return this._name + ' (' + subtitle + ')'; } return Common.UIString('<iframe>'); @@ -954,8 +1001,9 @@ * @param {string=} prompt */ javascriptDialogOpening(url, message, dialogType, hasBrowserHandler, prompt) { - if (!hasBrowserHandler) + if (!hasBrowserHandler) { this._resourceTreeModel._agent.handleJavaScriptDialog(false); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js b/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js index acda0f17..fec74fb 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/RuntimeModel.js
@@ -47,8 +47,9 @@ /** @type {?boolean} */ this._hasSideEffectSupport = null; - if (Common.moduleSetting('customFormatters').get()) + if (Common.moduleSetting('customFormatters').get()) { this._agent.setCustomObjectFormatterEnabled(true); + } Common.moduleSetting('customFormatters').addChangeListener(this._customFormattersStateChanged.bind(this)); } @@ -104,8 +105,9 @@ */ defaultExecutionContext() { for (const context of this.executionContexts()) { - if (context.isDefault) + if (context.isDefault) { return context; + } } return null; } @@ -134,8 +136,9 @@ */ _executionContextDestroyed(executionContextId) { const executionContext = this._executionContextById.get(executionContextId); - if (!executionContext) + if (!executionContext) { return; + } this.debuggerModel().executionContextDestroyed(executionContext); this._executionContextById.delete(executionContextId); this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed, executionContext); @@ -149,8 +152,9 @@ this.debuggerModel().globalObjectCleared(); const contexts = this.executionContexts(); this._executionContextById.clear(); - for (let i = 0; i < contexts.length; ++i) + for (let i = 0; i < contexts.length; ++i) { this.dispatchEventToListeners(SDK.RuntimeModel.Events.ExecutionContextDestroyed, contexts[i]); + } } /** @@ -183,10 +187,12 @@ const type = typeof value; let unserializableValue = undefined; const unserializableDescription = SDK.RemoteObject.unserializableDescription(value); - if (unserializableDescription !== null) + if (unserializableDescription !== null) { unserializableValue = /** @type {!Protocol.Runtime.UnserializableValue} */ (unserializableDescription); - if (typeof unserializableValue !== 'undefined') + } + if (typeof unserializableValue !== 'undefined') { value = undefined; + } return new SDK.RemoteObjectImpl(this, undefined, type, undefined, value, unserializableValue); } @@ -214,8 +220,9 @@ * @param {!SDK.RuntimeModel.EvaluationResult} result */ releaseEvaluationResult(result) { - if (result.object) + if (result.object) { result.object.release(); + } if (result.exceptionDetails && result.exceptionDetails.exception) { const exception = result.exceptionDetails.exception; const exceptionObject = this.createRemoteObject({type: exception.type, objectId: exception.objectId}); @@ -295,8 +302,9 @@ * @return {!Promise<!SDK.RuntimeModel.QueryObjectResult>} */ async queryObjects(prototype) { - if (!prototype.objectId) + if (!prototype.objectId) { return {error: 'Prototype should be an Object.'}; + } const response = await this._agent.invoke_queryObjects( {prototypeObjectId: /** @type {string} */ (prototype.objectId), objectGroup: 'console'}); const error = response[Protocol.Error]; @@ -354,8 +362,9 @@ */ function didGetDetails(response) { object.release(); - if (!response || !response.location) + if (!response || !response.location) { return; + } Common.Revealer.reveal(response.location); } object.release(); @@ -378,10 +387,12 @@ * @suppressReceiverCheck */ function toStringForClipboard(subtype) { - if (subtype === 'node') + if (subtype === 'node') { return this.outerHTML; - if (subtype && typeof this === 'undefined') + } + if (subtype && typeof this === 'undefined') { return subtype + ''; + } try { return JSON.stringify(this, null, ' '); } catch (e) { @@ -411,8 +422,9 @@ let text = exceptionDetails.text; if (exceptionDetails.exception && exceptionDetails.exception.description) { let description = exceptionDetails.exception.description; - if (description.indexOf('\n') !== -1) + if (description.indexOf('\n') !== -1) { description = description.substring(0, description.indexOf('\n')); + } text += ' ' + description; } return text; @@ -468,10 +480,12 @@ * @return {number} */ executionContextForStackTrace(stackTrace) { - while (stackTrace && !stackTrace.callFrames.length) + while (stackTrace && !stackTrace.callFrames.length) { stackTrace = stackTrace.parent; - if (!stackTrace || !stackTrace.callFrames.length) + } + if (!stackTrace || !stackTrace.callFrames.length) { return 0; + } return this.executionContextIdForScriptId(stackTrace.callFrames[0].scriptId); } @@ -487,8 +501,9 @@ */ async checkSideEffectSupport() { const testContext = this.executionContexts().peekLast(); - if (!testContext) + if (!testContext) { return false; + } // Check for a positive throwOnSideEffect response without triggering side effects. const response = await this._agent.invoke_evaluate({ expression: String.escapeInvalidUnicodeCharacters(SDK.RuntimeModel._sideEffectTestExpression), @@ -550,7 +565,8 @@ * returnByValue: (boolean|undefined), * generatePreview: (boolean|undefined), * throwOnSideEffect: (boolean|undefined), - * timeout: (number|undefined) + * timeout: (number|undefined), + * disableBreaks: (boolean|undefined) * }} */ SDK.RuntimeModel.EvaluationOptions; @@ -698,14 +714,18 @@ * @return {number} */ function targetWeight(target) { - if (!target.parentTarget()) + if (!target.parentTarget()) { return 5; - if (target.type() === SDK.Target.Type.Frame) + } + if (target.type() === SDK.Target.Type.Frame) { return 4; - if (target.type() === SDK.Target.Type.ServiceWorker) + } + if (target.type() === SDK.Target.Type.ServiceWorker) { return 3; - if (target.type() === SDK.Target.Type.Worker) + } + if (target.type() === SDK.Target.Type.Worker) { return 2; + } return 1; } @@ -734,24 +754,29 @@ break; } } - if (!targetA && targetB) + if (!targetA && targetB) { return -1; + } - if (!targetB && targetA) + if (!targetB && targetA) { return 1; + } if (targetA && targetB) { const weightDiff = targetWeight(targetA) - targetWeight(targetB); - if (weightDiff) + if (weightDiff) { return -weightDiff; + } return targetA.id().localeCompare(targetB.id()); } // Main world context should always go first. - if (a.isDefault) + if (a.isDefault) { return -1; - if (b.isDefault) + } + if (b.isDefault) { return +1; + } return a.name.localeCompare(b.name); } @@ -763,21 +788,25 @@ */ evaluate(options, userGesture, awaitPromise) { // FIXME: It will be moved to separate ExecutionContext. - if (this.debuggerModel.selectedCallFrame()) + if (this.debuggerModel.selectedCallFrame()) { return this.debuggerModel.evaluateOnSelectedCallFrame(options); + } // Assume backends either support both throwOnSideEffect and timeout options or neither. const needsTerminationOptions = !!options.throwOnSideEffect || options.timeout !== undefined; - if (!needsTerminationOptions || this.runtimeModel.hasSideEffectSupport()) + if (!needsTerminationOptions || this.runtimeModel.hasSideEffectSupport()) { return this._evaluateGlobal(options, userGesture, awaitPromise); + } /** @type {!SDK.RuntimeModel.EvaluationResult} */ const unsupportedError = {error: 'Side-effect checks not supported by backend.'}; - if (this.runtimeModel.hasSideEffectSupport() === false) + if (this.runtimeModel.hasSideEffectSupport() === false) { return Promise.resolve(unsupportedError); + } return this.runtimeModel.checkSideEffectSupport().then(() => { - if (this.runtimeModel.hasSideEffectSupport()) + if (this.runtimeModel.hasSideEffectSupport()) { return this._evaluateGlobal(options, userGesture, awaitPromise); + } return Promise.resolve(unsupportedError); }); } @@ -823,7 +852,8 @@ userGesture: userGesture, awaitPromise: awaitPromise, throwOnSideEffect: options.throwOnSideEffect, - timeout: options.timeout + timeout: options.timeout, + disableBreaks: options.disableBreaks }); const error = response[Protocol.Error];
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ScreenCaptureModel.js b/third_party/blink/renderer/devtools/front_end/sdk/ScreenCaptureModel.js index 6c2fecd..00fe7ce 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ScreenCaptureModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ScreenCaptureModel.js
@@ -58,8 +58,9 @@ */ async fetchLayoutMetrics() { const response = await this._agent.invoke_getLayoutMetrics({}); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { return null; + } return { viewportX: response.visualViewport.pageX, viewportY: response.visualViewport.pageY, @@ -77,8 +78,9 @@ */ screencastFrame(data, metadata, sessionId) { this._agent.screencastFrameAck(sessionId); - if (this._onScreencastFrame) + if (this._onScreencastFrame) { this._onScreencastFrame.call(null, data, metadata); + } } /** @@ -86,8 +88,9 @@ * @param {boolean} visible */ screencastVisibilityChanged(visible) { - if (this._onScreencastVisibilityChanged) + if (this._onScreencastVisibilityChanged) { this._onScreencastVisibilityChanged.call(null, visible); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/Script.js b/third_party/blink/renderer/devtools/front_end/sdk/Script.js index e646e172..fb33db5 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/Script.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/Script.js
@@ -76,15 +76,18 @@ let sourceURLIndex = source.lastIndexOf('//# sourceURL='); if (sourceURLIndex === -1) { sourceURLIndex = source.lastIndexOf('//@ sourceURL='); - if (sourceURLIndex === -1) + if (sourceURLIndex === -1) { return source; + } } const sourceURLLineIndex = source.lastIndexOf('\n', sourceURLIndex); - if (sourceURLLineIndex === -1) + if (sourceURLLineIndex === -1) { return source; + } const sourceURLLine = source.substr(sourceURLLineIndex + 1).split('\n', 1)[0]; - if (sourceURLLine.search(SDK.Script.sourceURLRegex) === -1) + if (sourceURLLine.search(SDK.Script.sourceURLRegex) === -1) { return source; + } return source.substr(0, sourceURLLineIndex) + source.substr(sourceURLLineIndex + sourceURLLine.length + 1); } @@ -138,17 +141,21 @@ * @return {!Promise<string>} */ async requestContent() { - if (this._source) + if (this._source) { return this._source; - if (!this.scriptId) + } + if (!this.scriptId) { return ''; + } const source = await this.debuggerModel.target().debuggerAgent().getScriptSource(this.scriptId); - if (source && this.hasSourceURL) + if (source && this.hasSourceURL) { this._source = SDK.Script._trimSourceURLComment(source); - else + } else { this._source = source || ''; - if (this._originalSource === null) + } + if (this._originalSource === null) { this._originalSource = this._source; + } return this._source; } @@ -172,8 +179,9 @@ * @return {!Promise<!Array<!Common.ContentProvider.SearchMatch>>} */ async searchInContent(query, caseSensitive, isRegex) { - if (!this.scriptId) + if (!this.scriptId) { return []; + } const matches = await this.debuggerModel.target().debuggerAgent().searchInContent(this.scriptId, query, caseSensitive, isRegex); @@ -185,8 +193,9 @@ * @return {string} */ _appendSourceURLCommentIfNeeded(source) { - if (!this.hasSourceURL) + if (!this.hasSourceURL) { return source; + } return source + '\n //# sourceURL=' + this.sourceURL; } @@ -212,8 +221,9 @@ const response = await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource( {scriptId: this.scriptId, scriptSource: newSource}); - if (!response[Protocol.Error] && !response.exceptionDetails) + if (!response[Protocol.Error] && !response.exceptionDetails) { this._source = newSource; + } const needsStepIn = !!response.stackChanged; callback(
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/SecurityOriginManager.js b/third_party/blink/renderer/devtools/front_end/sdk/SecurityOriginManager.js index f4727f1..62c35c1 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/SecurityOriginManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/SecurityOriginManager.js
@@ -30,13 +30,15 @@ this._securityOrigins = securityOrigins; for (const origin of oldOrigins) { - if (!this._securityOrigins.has(origin)) + if (!this._securityOrigins.has(origin)) { this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginRemoved, origin); + } } for (const origin of this._securityOrigins) { - if (!oldOrigins.has(origin)) + if (!oldOrigins.has(origin)) { this.dispatchEventToListeners(SDK.SecurityOriginManager.Events.SecurityOriginAdded, origin); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ServerTiming.js b/third_party/blink/renderer/devtools/front_end/sdk/ServerTiming.js index 8a8a12f..6174660 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ServerTiming.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ServerTiming.js
@@ -22,8 +22,9 @@ */ static parseHeaders(headers) { const rawServerTimingHeaders = headers.filter(item => item.name.toLowerCase() === 'server-timing'); - if (!rawServerTimingHeaders.length) + if (!rawServerTimingHeaders.length) { return null; + } const serverTimings = rawServerTimingHeaders.reduce((memo, header) => { const timing = this.createFromHeaderValue(header.value); @@ -48,8 +49,9 @@ function consumeDelimiter(char) { console.assert(char.length === 1); trimLeadingWhiteSpace(); - if (valueString.charAt(0) !== char) + if (valueString.charAt(0) !== char) { return false; + } valueString = valueString.substring(1); return true; @@ -57,16 +59,18 @@ function consumeToken() { // https://tools.ietf.org/html/rfc7230#appendix-B const result = /^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(valueString); - if (!result) + if (!result) { return null; + } valueString = result[2]; return result[1]; } function consumeTokenOrQuotedString() { trimLeadingWhiteSpace(); - if (valueString.charAt(0) === '"') + if (valueString.charAt(0) === '"') { return consumeQuotedString(); + } return consumeToken(); } @@ -97,8 +101,9 @@ } function consumeExtraneous() { const result = /([,;].*)/.exec(valueString); - if (result) + if (result) { valueString = result[1]; + } } const result = []; @@ -106,13 +111,15 @@ while ((name = consumeToken()) !== null) { const entry = {name}; - if (valueString.charAt(0) === '=') + if (valueString.charAt(0) === '=') { this.showWarning(ls`Deprecated syntax found. Please use: <name>;dur=<duration>;desc=<description>`); + } while (consumeDelimiter(';')) { let paramName; - if ((paramName = consumeToken()) === null) + if ((paramName = consumeToken()) === null) { continue; + } paramName = paramName.toLowerCase(); const parseParameter = this.getParserForParameter(paramName); @@ -130,8 +137,9 @@ continue; } - if (paramValue === null) + if (paramValue === null) { this.showWarning(ls`No value found for parameter \"${paramName}\".`); + } parseParameter.call(this, entry, paramValue); } else { @@ -141,12 +149,14 @@ } result.push(entry); - if (!consumeDelimiter(',')) + if (!consumeDelimiter(',')) { break; + } } - if (valueString.length) + if (valueString.length) { this.showWarning(ls`Extraneous trailing characters.`); + } return result; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerCacheModel.js b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerCacheModel.js index e2fa197..b1e9d67b 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerCacheModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerCacheModel.js
@@ -30,16 +30,18 @@ } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._securityOriginManager.addEventListener( SDK.SecurityOriginManager.Events.SecurityOriginAdded, this._securityOriginAdded, this); this._securityOriginManager.addEventListener( SDK.SecurityOriginManager.Events.SecurityOriginRemoved, this._securityOriginRemoved, this); - for (const securityOrigin of this._securityOriginManager.securityOrigins()) + for (const securityOrigin of this._securityOriginManager.securityOrigins()) { this._addOrigin(securityOrigin); + } this._enabled = true; } @@ -52,12 +54,14 @@ } refreshCacheNames() { - for (const cache of this._caches.values()) + for (const cache of this._caches.values()) { this._cacheRemoved(cache); + } this._caches.clear(); const securityOrigins = this._securityOriginManager.securityOrigins(); - for (const securityOrigin of securityOrigins) + for (const securityOrigin of securityOrigins) { this._loadCacheNames(securityOrigin); + } } /** @@ -80,8 +84,9 @@ */ async deleteCacheEntry(cache, request) { const response = await this._cacheAgent.invoke_deleteEntry({cacheId: cache.cacheId, request}); - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { return; + } Common.console.error(Common.UIString( 'ServiceWorkerCacheAgent error deleting cache entry %s in cache: %s', cache.toString(), response[Protocol.Error])); @@ -103,8 +108,9 @@ */ caches() { const caches = new Array(); - for (const cache of this._caches.values()) + for (const cache of this._caches.values()) { caches.push(cache); + } return caches; } @@ -112,8 +118,9 @@ * @override */ dispose() { - for (const cache of this._caches.values()) + for (const cache of this._caches.values()) { this._cacheRemoved(cache); + } this._caches.clear(); if (this._enabled) { this._securityOriginManager.removeEventListener( @@ -125,8 +132,9 @@ _addOrigin(securityOrigin) { this._loadCacheNames(securityOrigin); - if (this._isValidSecurityOrigin(securityOrigin)) + if (this._isValidSecurityOrigin(securityOrigin)) { this._storageAgent.trackCacheStorageForOrigin(securityOrigin); + } } /** @@ -140,8 +148,9 @@ this._cacheRemoved(cache); } } - if (this._isValidSecurityOrigin(securityOrigin)) + if (this._isValidSecurityOrigin(securityOrigin)) { this._storageAgent.untrackCacheStorageForOrigin(securityOrigin); + } } /** @@ -158,8 +167,9 @@ */ async _loadCacheNames(securityOrigin) { const caches = await this._cacheAgent.requestCacheNames(securityOrigin); - if (!caches) + if (!caches) { return; + } this._updateCacheNames(securityOrigin, caches); } @@ -190,8 +200,9 @@ const cache = new SDK.ServiceWorkerCacheModel.Cache(this, cacheJson.securityOrigin, cacheJson.cacheName, cacheJson.cacheId); updatingCachesIds.add(cache.cacheId); - if (this._caches.has(cache.cacheId)) + if (this._caches.has(cache.cacheId)) { continue; + } newCaches.set(cache.cacheId, cache); this._caches.set(cache.cacheId, cache); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js index 649be99..993862b 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/ServiceWorkerManager.js
@@ -44,22 +44,25 @@ this._registrations = new Map(); this.enable(); this._forceUpdateSetting = Common.settings.createSetting('serviceWorkerUpdateOnReload', false); - if (this._forceUpdateSetting.get()) + if (this._forceUpdateSetting.get()) { this._forceUpdateSettingChanged(); + } this._forceUpdateSetting.addChangeListener(this._forceUpdateSettingChanged, this); new SDK.ServiceWorkerContextNamer(target, this); } enable() { - if (this._enabled) + if (this._enabled) { return; + } this._enabled = true; this._agent.enable(); } disable() { - if (!this._enabled) + if (!this._enabled) { return; + } this._enabled = false; this._registrations.clear(); this._agent.disable(); @@ -78,8 +81,9 @@ */ hasRegistrationForURLs(urls) { for (const registration of this._registrations.values()) { - if (urls.filter(url => url && url.startsWith(registration.scopeURL)).length === urls.length) + if (urls.filter(url => url && url.startsWith(registration.scopeURL)).length === urls.length) { return true; + } } return false; } @@ -91,8 +95,9 @@ findVersion(versionId) { for (const registration of this.registrations().values()) { const version = registration.versions.get(versionId); - if (version) + if (version) { return version; + } } return null; } @@ -102,16 +107,18 @@ */ deleteRegistration(registrationId) { const registration = this._registrations.get(registrationId); - if (!registration) + if (!registration) { return; + } if (registration._isRedundant()) { this._registrations.delete(registrationId); this.dispatchEventToListeners(SDK.ServiceWorkerManager.Events.RegistrationDeleted, registration); return; } registration._deleting = true; - for (const version of registration.versions.values()) + for (const version of registration.versions.values()) { this.stopWorker(version.id); + } this._unregister(registration.scopeURL); } @@ -120,8 +127,9 @@ */ updateRegistration(registrationId) { const registration = this._registrations.get(registrationId); - if (!registration) + if (!registration) { return; + } this._agent.updateRegistration(registration.scopeURL); } @@ -131,8 +139,9 @@ */ deliverPushMessage(registrationId, data) { const registration = this._registrations.get(registrationId); - if (!registration) + if (!registration) { return; + } const origin = Common.ParsedURL.extractOrigin(registration.scopeURL); this._agent.deliverPushMessage(origin, registrationId, data); } @@ -144,8 +153,9 @@ */ dispatchSyncEvent(registrationId, tag, lastChance) { const registration = this._registrations.get(registrationId); - if (!registration) + if (!registration) { return; + } const origin = Common.ParsedURL.extractOrigin(registration.scopeURL); this._agent.dispatchSyncEvent(origin, registrationId, tag, lastChance); } @@ -156,8 +166,9 @@ */ dispatchPeriodicSyncEvent(registrationId, tag) { const registration = this._registrations.get(registrationId); - if (!registration) + if (!registration) { return; + } const origin = Common.ParsedURL.extractOrigin(registration.scopeURL); this._agent.dispatchPeriodicSyncEvent(origin, registrationId, tag); } @@ -228,8 +239,9 @@ const registrations = new Set(); for (const payload of versions) { const registration = this._registrations.get(payload.registrationId); - if (!registration) + if (!registration) { continue; + } registration._updateVersion(payload); registrations.add(registration); } @@ -248,8 +260,9 @@ */ _workerErrorReported(payload) { const registration = this._registrations.get(payload.registrationId); - if (!registration) + if (!registration) { return; + } registration.errors.push(payload); this.dispatchEventToListeners( SDK.ServiceWorkerManager.Events.RegistrationErrorAdded, {registration: registration, error: payload}); @@ -339,8 +352,9 @@ this.scriptLastModified = payload.scriptLastModified; this.scriptResponseTime = payload.scriptResponseTime; this.controlledClients = []; - for (let i = 0; i < payload.controlledClients.length; ++i) + for (let i = 0; i < payload.controlledClients.length; ++i) { this.controlledClients.push(payload.controlledClients[i]); + } this.targetId = payload.targetId || null; } @@ -433,12 +447,13 @@ * @return {string} */ mode() { - if (this.isNew() || this.isInstalling()) + if (this.isNew() || this.isInstalling()) { return SDK.ServiceWorkerVersion.Modes.Installing; - else if (this.isInstalled()) + } else if (this.isInstalled()) { return SDK.ServiceWorkerVersion.Modes.Waiting; - else if (this.isActivating() || this.isActivated()) + } else if (this.isActivating() || this.isActivated()) { return SDK.ServiceWorkerVersion.Modes.Active; + } return SDK.ServiceWorkerVersion.Modes.Redundant; } }; @@ -505,8 +520,9 @@ versionsByMode() { /** @type {!Map<string, !SDK.ServiceWorkerVersion>} */ const result = new Map(); - for (const version of this.versions.values()) + for (const version of this.versions.values()) { result.set(version.mode(), version); + } return result; } @@ -531,8 +547,9 @@ */ _isRedundant() { for (const version of this.versions.values()) { - if (!version.isStoppedAndRedundant()) + if (!version.isStoppedAndRedundant()) { return false; + } } return true; } @@ -588,8 +605,9 @@ for (const registration of registrations) { const versions = registration.versions.valuesArray(); for (const version of versions) { - if (version.targetId) + if (version.targetId) { this._versionByTargetId.set(version.targetId, version); + } } } this._updateAllContextLabels(); @@ -601,8 +619,9 @@ _executionContextCreated(event) { const executionContext = /** @type {!SDK.ExecutionContext} */ (event.data); const serviceWorkerTargetId = this._serviceWorkerTargetId(executionContext.target()); - if (!serviceWorkerTargetId) + if (!serviceWorkerTargetId) { return; + } this._updateContextLabel(executionContext, this._versionByTargetId.get(serviceWorkerTargetId) || null); } @@ -611,21 +630,24 @@ * @return {?string} */ _serviceWorkerTargetId(target) { - if (target.parentTarget() !== this._target || target.type() !== SDK.Target.Type.ServiceWorker) + if (target.parentTarget() !== this._target || target.type() !== SDK.Target.Type.ServiceWorker) { return null; + } return target.id(); } _updateAllContextLabels() { for (const target of SDK.targetManager.targets()) { const serviceWorkerTargetId = this._serviceWorkerTargetId(target); - if (!serviceWorkerTargetId) + if (!serviceWorkerTargetId) { continue; + } const version = this._versionByTargetId.get(serviceWorkerTargetId) || null; const runtimeModel = target.model(SDK.RuntimeModel); const executionContexts = runtimeModel ? runtimeModel.executionContexts() : []; - for (const context of executionContexts) + for (const context of executionContexts) { this._updateContextLabel(context, version); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js b/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js index 56e691d..35a3caa21 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js
@@ -90,8 +90,9 @@ * @return {number} */ static compare(entry1, entry2) { - if (entry1.lineNumber !== entry2.lineNumber) + if (entry1.lineNumber !== entry2.lineNumber) { return entry1.lineNumber - entry2.lineNumber; + } return entry1.columnNumber - entry2.columnNumber; } }; @@ -170,8 +171,9 @@ if (!SDK.TextSourceMap._base64Map) { const base64Digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; SDK.TextSourceMap._base64Map = {}; - for (let i = 0; i < base64Digits.length; ++i) + for (let i = 0; i < base64Digits.length; ++i) { SDK.TextSourceMap._base64Map[base64Digits.charAt(i)] = i; + } } this._json = payload; @@ -185,8 +187,9 @@ this._sourceInfos = new Map(); if (this._json.sections) { const sectionWithURL = !!this._json.sections.find(section => !!section.url); - if (sectionWithURL) + if (sectionWithURL) { Common.console.warn(`SourceMap "${sourceMappingURL}" contains unsupported "URL" field in one of its sections.`); + } } this._eachSection(this._parseSources.bind(this)); } @@ -214,8 +217,9 @@ return; } - if (content.slice(0, 3) === ')]}') + if (content.slice(0, 3) === ')]}') { content = content.substring(content.indexOf('\n')); + } try { const payload = /** @type {!SDK.SourceMapV3} */ (JSON.parse(content)); callback(new SDK.TextSourceMap(compiledURL, sourceMapURL, payload)); @@ -259,8 +263,9 @@ */ sourceContentProvider(sourceURL, contentType) { const info = this._sourceInfos.get(sourceURL); - if (info.content) + if (info.content) { return Common.StaticContentProvider.fromString(sourceURL, contentType, info.content); + } return new SDK.CompilerSourceMappingContentProvider(sourceURL, contentType); } @@ -270,8 +275,9 @@ * @return {?string} */ embeddedContentByURL(sourceURL) { - if (!this._sourceInfos.has(sourceURL)) + if (!this._sourceInfos.has(sourceURL)) { return null; + } return this._sourceInfos.get(sourceURL).content; } @@ -298,11 +304,13 @@ const mappings = this._reversedMappings(sourceURL); const first = mappings.lowerBound(lineNumber, lineComparator); const last = mappings.upperBound(lineNumber, lineComparator); - if (first >= mappings.length || mappings[first].sourceLineNumber !== lineNumber) + if (first >= mappings.length || mappings[first].sourceLineNumber !== lineNumber) { return null; + } const columnMappings = mappings.slice(first, last); - if (!columnMappings.length) + if (!columnMappings.length) { return null; + } const index = columnMappings.lowerBound(columnNumber, (columnNumber, mapping) => columnNumber - mapping.sourceColumnNumber); return index >= columnMappings.length ? columnMappings[columnMappings.length - 1] : columnMappings[index]; @@ -329,8 +337,9 @@ undefined, (unused, entry) => lineNumber - entry.sourceLineNumber || columnNumber - entry.sourceColumnNumber); let startIndex = endIndex; while (startIndex > 0 && mappings[startIndex - 1].sourceLineNumber === mappings[endIndex - 1].sourceLineNumber && - mappings[startIndex - 1].sourceColumnNumber === mappings[endIndex - 1].sourceColumnNumber) + mappings[startIndex - 1].sourceColumnNumber === mappings[endIndex - 1].sourceColumnNumber) { --startIndex; + } return mappings.slice(startIndex, endIndex); } @@ -352,12 +361,14 @@ * @return {!Array.<!SDK.SourceMapEntry>} */ _reversedMappings(sourceURL) { - if (!this._sourceInfos.has(sourceURL)) + if (!this._sourceInfos.has(sourceURL)) { return []; + } const mappings = this.mappings(); const info = this._sourceInfos.get(sourceURL); - if (info.reverseMappings === null) + if (info.reverseMappings === null) { info.reverseMappings = mappings.filter(mapping => mapping.sourceURL === sourceURL).sort(sourceMappingComparator); + } return info.reverseMappings; @@ -367,13 +378,16 @@ * @return {number} */ function sourceMappingComparator(a, b) { - if (a.sourceLineNumber !== b.sourceLineNumber) + if (a.sourceLineNumber !== b.sourceLineNumber) { return a.sourceLineNumber - b.sourceLineNumber; - if (a.sourceColumnNumber !== b.sourceColumnNumber) + } + if (a.sourceColumnNumber !== b.sourceColumnNumber) { return a.sourceColumnNumber - b.sourceColumnNumber; + } - if (a.lineNumber !== b.lineNumber) + if (a.lineNumber !== b.lineNumber) { return a.lineNumber - b.lineNumber; + } return a.columnNumber - b.columnNumber; } @@ -387,8 +401,9 @@ callback(this._json, 0, 0); return; } - for (const section of this._json.sections) + for (const section of this._json.sections) { callback(section.map, section.offset.line, section.offset.column); + } } /** @@ -397,14 +412,16 @@ _parseSources(sourceMap) { const sourcesList = []; let sourceRoot = sourceMap.sourceRoot || ''; - if (sourceRoot && !sourceRoot.endsWith('/')) + if (sourceRoot && !sourceRoot.endsWith('/')) { sourceRoot += '/'; + } for (let i = 0; i < sourceMap.sources.length; ++i) { const href = sourceRoot + sourceMap.sources[i]; let url = Common.ParsedURL.completeURL(this._baseURL, href) || href; const source = sourceMap.sourcesContent && sourceMap.sourcesContent[i]; - if (url === this._compiledURL && source) + if (url === this._compiledURL && source) { url += Common.UIString('? [sm]'); + } this._sourceInfos.set(url, new SDK.TextSourceMap.SourceInfo(source, null)); sourcesList.push(url); } @@ -435,8 +452,9 @@ columnNumber = 0; stringCharIterator.next(); } - if (!stringCharIterator.hasNext()) + if (!stringCharIterator.hasNext()) { break; + } } columnNumber += this._decodeVLQ(stringCharIterator); @@ -509,8 +527,9 @@ * @return {number} */ function comparator(position, mapping) { - if (position.lineNumber !== mapping.sourceLineNumber) + if (position.lineNumber !== mapping.sourceLineNumber) { return position.lineNumber - mapping.sourceLineNumber; + } return position.columnNumber - mapping.sourceColumnNumber; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/SourceMapManager.js b/third_party/blink/renderer/devtools/front_end/sdk/SourceMapManager.js index 6024d21..2afcd35 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/SourceMapManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/SourceMapManager.js
@@ -36,8 +36,9 @@ * @param {boolean} isEnabled */ setEnabled(isEnabled) { - if (isEnabled === this._isEnabled) + if (isEnabled === this._isEnabled) { return; + } this._isEnabled = isEnabled; const clients = Array.from(this._resolvedSourceMapURL.keys()); for (const client of clients) { @@ -52,8 +53,9 @@ * @param {!Common.Event} event */ _inspectedURLChanged(event) { - if (event.data !== this._target) + if (event.data !== this._target) { return; + } const clients = Array.from(this._resolvedSourceMapURL.keys()); for (const client of clients) { @@ -82,8 +84,9 @@ * @return {!Array<!T>} */ clientsForSourceMap(sourceMap) { - if (this._sourceMapURLToClients.has(sourceMap.url())) + if (this._sourceMapURLToClients.has(sourceMap.url())) { return this._sourceMapURLToClients.get(sourceMap.url()).valuesArray(); + } return this._sourceMapURLToLoadingClients.get(sourceMap.url()).valuesArray(); } @@ -118,20 +121,23 @@ * @param {?string} sourceMapURL */ attachSourceMap(client, sourceURL, sourceMapURL) { - if (!sourceMapURL) + if (!sourceMapURL) { return; + } console.assert(!this._resolvedSourceMapURL.has(client), 'SourceMap is already attached to client'); const resolvedURLs = this._resolveRelativeURLs(sourceURL, sourceMapURL); - if (!resolvedURLs.sourceURL || !resolvedURLs.sourceMapURL) + if (!resolvedURLs.sourceURL || !resolvedURLs.sourceMapURL) { return; + } this._relativeSourceURL.set(client, sourceURL); this._relativeSourceMapURL.set(client, sourceMapURL); this._resolvedSourceMapURL.set(client, resolvedURLs.sourceMapURL); sourceURL = resolvedURLs.sourceURL; sourceMapURL = resolvedURLs.sourceMapURL; - if (!this._isEnabled) + if (!this._isEnabled) { return; + } this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapWillAttach, client); @@ -154,16 +160,19 @@ this._sourceMapLoadedForTest(); const clients = this._sourceMapURLToLoadingClients.get(sourceMapURL); this._sourceMapURLToLoadingClients.deleteAll(sourceMapURL); - if (!clients.size) + if (!clients.size) { return; + } if (!sourceMap) { - for (const client of clients) + for (const client of clients) { this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach, client); + } return; } this._sourceMapByURL.set(sourceMapURL, sourceMap); - for (const client of clients) + for (const client of clients) { attach.call(this, sourceMapURL, client); + } } /** @@ -188,17 +197,20 @@ this._relativeSourceMapURL.delete(client); this._resolvedSourceMapURL.delete(client); - if (!sourceMapURL) + if (!sourceMapURL) { return; + } if (!this._sourceMapURLToClients.hasValue(sourceMapURL, client)) { - if (this._sourceMapURLToLoadingClients.delete(sourceMapURL, client)) + if (this._sourceMapURLToLoadingClients.delete(sourceMapURL, client)) { this.dispatchEventToListeners(SDK.SourceMapManager.Events.SourceMapFailedToAttach, client); + } return; } this._sourceMapURLToClients.delete(sourceMapURL, client); const sourceMap = this._sourceMapByURL.get(sourceMapURL); - if (!this._sourceMapURLToClients.has(sourceMapURL)) + if (!this._sourceMapURLToClients.has(sourceMapURL)) { this._sourceMapByURL.delete(sourceMapURL); + } this.dispatchEventToListeners( SDK.SourceMapManager.Events.SourceMapDetached, {client: client, sourceMap: sourceMap}); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/Target.js b/third_party/blink/renderer/devtools/front_end/sdk/Target.js index a9f47b7..61c186ca 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/Target.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/Target.js
@@ -42,8 +42,9 @@ case SDK.Target.Type.ServiceWorker: this._capabilitiesMask = SDK.Target.Capability.JS | SDK.Target.Capability.Log | SDK.Target.Capability.Network | SDK.Target.Capability.Target | SDK.Target.Capability.Inspector; - if (!parentTarget) + if (!parentTarget) { this._capabilitiesMask |= SDK.Target.Capability.Browser; + } break; case SDK.Target.Type.Worker: this._capabilitiesMask = SDK.Target.Capability.JS | SDK.Target.Capability.Log | SDK.Target.Capability.Network | @@ -70,8 +71,9 @@ const registered = Array.from(SDK.SDKModel._registeredModels.keys()); for (const modelClass of registered) { const info = SDK.SDKModel._registeredModels.get(modelClass); - if (info.autostart || required.has(modelClass)) + if (info.autostart || required.has(modelClass)) { this.model(modelClass); + } } this._creatingModels = false; } @@ -145,8 +147,9 @@ dispose(reason) { super.dispose(reason); this._targetManager.removeTarget(this); - for (const model of this._modelByConstructor.valuesArray()) + for (const model of this._modelByConstructor.valuesArray()) { model.dispose(); + } } /** @@ -157,13 +160,15 @@ model(modelClass) { if (!this._modelByConstructor.get(modelClass)) { const info = SDK.SDKModel._registeredModels.get(modelClass); - if (info === undefined) + if (info === undefined) { throw 'Model class is not registered @' + new Error().stack; + } if ((this._capabilitiesMask & info.capabilities) === info.capabilities) { const model = new modelClass(this); this._modelByConstructor.set(modelClass, model); - if (!this._creatingModels) + if (!this._creatingModels) { this._targetManager.modelAdded(this, modelClass, model); + } } } return this._modelByConstructor.get(modelClass) || null; @@ -190,11 +195,13 @@ this._inspectedURL = inspectedURL; const parsedURL = inspectedURL.asParsedURL(); this._inspectedURLName = parsedURL ? parsedURL.lastPathComponentWithFragment() : '#' + this._id; - if (!this.parentTarget()) + if (!this.parentTarget()) { InspectorFrontendHost.inspectedURLChanged(inspectedURL || ''); + } this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.InspectedURLChanged, this); - if (!this._name) + if (!this._name) { this._targetManager.dispatchEventToListeners(SDK.TargetManager.Events.NameChanged, this); + } } /** @@ -202,8 +209,9 @@ * @return {!Promise} */ async suspend(reason) { - if (this._isSuspended) + if (this._isSuspended) { return Promise.resolve(); + } this._isSuspended = true; await Promise.all(Array.from(this.models().values(), m => m.preSuspendModel(reason))); @@ -214,8 +222,9 @@ * @return {!Promise} */ async resume() { - if (!this._isSuspended) + if (!this._isSuspended) { return Promise.resolve(); + } this._isSuspended = false; await Promise.all(Array.from(this.models().values(), m => m.resumeModel())); @@ -328,8 +337,9 @@ * @param {boolean} autostart */ SDK.SDKModel.register = function(modelClass, capabilities, autostart) { - if (!SDK.SDKModel._registeredModels) + if (!SDK.SDKModel._registeredModels) { SDK.SDKModel._registeredModels = new Map(); + } SDK.SDKModel._registeredModels.set(modelClass, {capabilities: capabilities, autostart: autostart}); };
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js b/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js index 81cef967..766cb48 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/TargetManager.js
@@ -23,8 +23,9 @@ * @return {!Promise} */ suspendAllTargets(reason) { - if (this._isSuspended) + if (this._isSuspended) { return Promise.resolve(); + } this._isSuspended = true; this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged); return Promise.all(this._targets.map(target => target.suspend(reason))); @@ -34,8 +35,9 @@ * @return {!Promise} */ resumeAllTargets() { - if (!this._isSuspended) + if (!this._isSuspended) { return Promise.resolve(); + } this._isSuspended = false; this.dispatchEventToListeners(SDK.TargetManager.Events.SuspendStateChanged); return Promise.all(this._targets.map(target => target.resume())); @@ -57,8 +59,9 @@ const result = []; for (let i = 0; i < this._targets.length; ++i) { const model = this._targets[i].model(modelClass); - if (model) + if (model) { result.push(model); + } } return result; } @@ -78,8 +81,9 @@ observeModels(modelClass, observer) { const models = this.models(modelClass); this._modelObservers.set(modelClass, observer); - for (const model of models) + for (const model of models) { observer.modelAdded(model); + } } /** @@ -97,8 +101,9 @@ * @param {!SDK.SDKModel} model */ modelAdded(target, modelClass, model) { - for (const observer of this._modelObservers.get(modelClass).valuesArray()) + for (const observer of this._modelObservers.get(modelClass).valuesArray()) { observer.modelAdded(model); + } } /** @@ -107,8 +112,9 @@ * @param {!SDK.SDKModel} model */ _modelRemoved(target, modelClass, model) { - for (const observer of this._modelObservers.get(modelClass).valuesArray()) + for (const observer of this._modelObservers.get(modelClass).valuesArray()) { observer.modelRemoved(model); + } } /** @@ -120,8 +126,9 @@ addModelListener(modelClass, eventType, listener, thisObject) { for (let i = 0; i < this._targets.length; ++i) { const model = this._targets[i].model(modelClass); - if (model) + if (model) { model.addEventListener(eventType, listener, thisObject); + } } this._modelListeners.set(eventType, {modelClass: modelClass, thisObject: thisObject, listener: listener}); } @@ -133,18 +140,21 @@ * @param {!Object=} thisObject */ removeModelListener(modelClass, eventType, listener, thisObject) { - if (!this._modelListeners.has(eventType)) + if (!this._modelListeners.has(eventType)) { return; + } for (let i = 0; i < this._targets.length; ++i) { const model = this._targets[i].model(modelClass); - if (model) + if (model) { model.removeEventListener(eventType, listener, thisObject); + } } for (const info of this._modelListeners.get(eventType)) { - if (info.modelClass === modelClass && info.listener === listener && info.thisObject === thisObject) + if (info.modelClass === modelClass && info.listener === listener && info.thisObject === thisObject) { this._modelListeners.delete(eventType, info); + } } } @@ -152,10 +162,12 @@ * @param {!SDK.TargetManager.Observer} targetObserver */ observeTargets(targetObserver) { - if (this._observers.indexOf(targetObserver) !== -1) + if (this._observers.indexOf(targetObserver) !== -1) { throw new Error('Observer can only be registered once'); - for (const target of this._targets) + } + for (const target of this._targets) { targetObserver.targetAdded(target); + } this._observers.push(targetObserver); } @@ -179,23 +191,27 @@ createTarget(id, name, type, parentTarget, sessionId, waitForDebuggerInPage, connection) { const target = new SDK.Target(this, id, name, type, parentTarget, sessionId || '', this._isSuspended, connection || null); - if (waitForDebuggerInPage) + if (waitForDebuggerInPage) { target.pageAgent().waitForDebugger(); + } target.createModels(new Set(this._modelObservers.keysArray())); this._targets.push(target); const copy = this._observers.slice(0); - for (const observer of copy) + for (const observer of copy) { observer.targetAdded(target); + } - for (const modelClass of target.models().keys()) + for (const modelClass of target.models().keys()) { this.modelAdded(target, modelClass, target.models().get(modelClass)); + } for (const key of this._modelListeners.keysArray()) { for (const info of this._modelListeners.get(key)) { const model = target.model(info.modelClass); - if (model) + if (model) { model.addEventListener(key, info.listener, info.thisObject); + } } } @@ -206,22 +222,26 @@ * @param {!SDK.Target} target */ removeTarget(target) { - if (!this._targets.includes(target)) + if (!this._targets.includes(target)) { return; + } this._targets.remove(target); - for (const modelClass of target.models().keys()) + for (const modelClass of target.models().keys()) { this._modelRemoved(target, modelClass, target.models().get(modelClass)); + } const copy = this._observers.slice(0); - for (const observer of copy) + for (const observer of copy) { observer.targetRemoved(target); + } for (const key of this._modelListeners.keysArray()) { for (const info of this._modelListeners.get(key)) { const model = target.model(info.modelClass); - if (model) + if (model) { model.removeEventListener(key, info.listener, info.thisObject); + } } } } @@ -240,8 +260,9 @@ targetById(id) { // TODO(dgozman): add a map id -> target. for (let i = 0; i < this._targets.length; ++i) { - if (this._targets[i].id() === id) + if (this._targets[i].id() === id) { return this._targets[i]; + } } return null; }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/TracingManager.js b/third_party/blink/renderer/devtools/front_end/sdk/TracingManager.js index d324dc2..b87a5d05 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/TracingManager.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/TracingManager.js
@@ -63,8 +63,9 @@ return; } - if (this._eventsRetrieved > this._eventBufferSize) + if (this._eventsRetrieved > this._eventBufferSize) { this._eventsRetrieved = this._eventBufferSize; + } this._activeClient.eventsRetrievalProgress(this._eventsRetrieved / this._eventBufferSize); } @@ -83,8 +84,9 @@ * @return {!Promise<!Object>} */ async start(client, categoryFilter, options) { - if (this._activeClient) + if (this._activeClient) { throw new Error('Tracing is already started'); + } const bufferUsageReportingIntervalMs = 500; this._activeClient = client; const args = { @@ -94,16 +96,19 @@ transferMode: SDK.TracingManager.TransferMode.ReportEvents }; const response = await this._tracingAgent.invoke_start(args); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { this._activeClient = null; + } return response; } stop() { - if (!this._activeClient) + if (!this._activeClient) { throw new Error('Tracing is not started'); - if (this._finishing) + } + if (this._finishing) { throw new Error('Tracing is already being stopped'); + } this._finishing = true; this._tracingAgent.end(); }
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/TracingModel.js b/third_party/blink/renderer/devtools/front_end/sdk/TracingModel.js index 276dd21..a72f2e0 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/TracingModel.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/TracingModel.js
@@ -80,8 +80,9 @@ */ static _extractId(payload) { const scope = payload.scope || ''; - if (typeof payload.id2 === 'undefined') + if (typeof payload.id2 === 'undefined') { return scope && payload.id ? `${scope}@${payload.id}` : payload.id; + } const id2 = payload.id2; if (typeof id2 === 'object' && ('global' in id2) !== ('local' in id2)) { return typeof id2['global'] !== 'undefined' ? `:${scope}:${id2['global']}` : @@ -102,24 +103,29 @@ static browserMainThread(tracingModel) { const processes = tracingModel.sortedProcesses(); // Avoid warning for an empty model. - if (!processes.length) + if (!processes.length) { return null; + } const browserMainThreadName = 'CrBrowserMain'; const browserProcesses = []; const browserMainThreads = []; for (const process of processes) { - if (process.name().toLowerCase().endsWith('browser')) + if (process.name().toLowerCase().endsWith('browser')) { browserProcesses.push(process); + } browserMainThreads.push(...process.sortedThreads().filter(t => t.name() === browserMainThreadName)); } - if (browserMainThreads.length === 1) + if (browserMainThreads.length === 1) { return browserMainThreads[0]; - if (browserProcesses.length === 1) + } + if (browserProcesses.length === 1) { return browserProcesses[0].threadByName(browserMainThreadName); + } const tracingStartedInBrowser = tracingModel.devToolsMetadataEvents().filter(e => e.name === 'TracingStartedInBrowser'); - if (tracingStartedInBrowser.length === 1) + if (tracingStartedInBrowser.length === 1) { return tracingStartedInBrowser[0].thread; + } Common.console.error('Failed to find browser main thread in trace, some timeline features may be unavailable'); return null; } @@ -135,8 +141,9 @@ * @param {!Array.<!SDK.TracingManager.EventPayload>} events */ addEvents(events) { - for (let i = 0; i < events.length; ++i) + for (let i = 0; i < events.length; ++i) { this._addEvent(events[i]); + } } tracingComplete() { @@ -145,14 +152,16 @@ this._backingStorage.finishWriting(); this._firstWritePending = false; for (const process of this._processById.values()) { - for (const thread of process._threads.values()) + for (const thread of process._threads.values()) { thread.tracingComplete(); + } } } dispose() { - if (!this._firstWritePending) + if (!this._firstWritePending) { this._backingStorage.reset(); + } } /** @@ -165,13 +174,15 @@ for (const thread of process._threads.values()) { for (const event of thread.events()) { event.startTime += offset; - if (typeof event.endTime === 'number') + if (typeof event.endTime === 'number') { event.endTime += offset; + } } for (const event of thread.asyncEvents()) { event.startTime += offset; - if (typeof event.endTime === 'number') + if (typeof event.endTime === 'number') { event.endTime += offset; + } } } } @@ -195,22 +206,25 @@ const isAccessible = payload.ph === phase.SnapshotObject; let backingStorage = null; const keepStringsLessThan = 10000; - if (isAccessible && stringPayload.length > keepStringsLessThan) + if (isAccessible && stringPayload.length > keepStringsLessThan) { backingStorage = this._backingStorage.appendAccessibleString(stringPayload); - else + } else { this._backingStorage.appendString(stringPayload); + } const timestamp = payload.ts / 1000; // We do allow records for unrelated threads to arrive out-of-order, // so there's a chance we're getting records from the past. if (timestamp && (!this._minimumRecordTime || timestamp < this._minimumRecordTime) && - (payload.ph === phase.Begin || payload.ph === phase.Complete || payload.ph === phase.Instant)) + (payload.ph === phase.Begin || payload.ph === phase.Complete || payload.ph === phase.Instant)) { this._minimumRecordTime = timestamp; + } const endTimeStamp = (payload.ts + (payload.dur || 0)) / 1000; this._maximumRecordTime = Math.max(this._maximumRecordTime, endTimeStamp); const event = process._addEvent(payload); - if (!event) + if (!event) { return; + } if (payload.ph === phase.Sample) { this._addSampleEvent(event); return; @@ -218,14 +232,17 @@ // Build async event when we've got events from all threads & processes, so we can sort them and process in the // chronological order. However, also add individual async events to the thread flow (above), so we can easily // display them on the same chart as other events, should we choose so. - if (SDK.TracingModel.isAsyncPhase(payload.ph)) + if (SDK.TracingModel.isAsyncPhase(payload.ph)) { this._asyncEvents.push(event); + } event._setBackingStorage(backingStorage); - if (event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)) + if (event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory)) { this._devToolsMetadataEvents.push(event); + } - if (payload.ph !== phase.Metadata) + if (payload.ph !== phase.Metadata) { return; + } switch (payload.name) { case SDK.TracingModel.MetadataEvent.ProcessSortIndex: @@ -251,10 +268,11 @@ _addSampleEvent(event) { const id = `${event.thread.process().id()}:${event.id}`; const group = this._profileGroups.get(id); - if (group) + if (group) { group._addChild(event); - else + } else { this._profileGroups.set(id, new SDK.TracingModel.ProfileEventsGroup(event)); + } } /** @@ -316,10 +334,11 @@ this._asyncEvents.sort(SDK.TracingModel.Event.compareStartTime); for (let i = 0; i < this._asyncEvents.length; ++i) { const event = this._asyncEvents[i]; - if (SDK.TracingModel.isNestableAsyncPhase(event.phase)) + if (SDK.TracingModel.isNestableAsyncPhase(event.phase)) { this._addNestableAsyncEvent(event); - else + } else { this._addAsyncEvent(event); + } } this._asyncEvents = []; this._closeOpenAsyncEvents(); @@ -335,8 +354,9 @@ this._openAsyncEvents.clear(); for (const eventStack of this._openNestableAsyncEvents.values()) { - while (eventStack.length) + while (eventStack.length) { eventStack.pop().setEndTime(this._maximumRecordTime); + } } this._openNestableAsyncEvents.clear(); } @@ -361,13 +381,15 @@ break; case phase.NestableAsyncInstant: - if (openEventsStack && openEventsStack.length) + if (openEventsStack && openEventsStack.length) { openEventsStack.peekLast()._addStep(event); + } break; case phase.NestableAsyncEnd: - if (!openEventsStack || !openEventsStack.length) + if (!openEventsStack || !openEventsStack.length) { break; + } const top = openEventsStack.pop(); if (top.name !== event.name) { console.error( @@ -542,15 +564,19 @@ static fromPayload(payload, thread) { const event = new SDK.TracingModel.Event( payload.cat, payload.name, /** @type {!SDK.TracingModel.Phase} */ (payload.ph), payload.ts / 1000, thread); - if (payload.args) + if (payload.args) { event.addArgs(payload.args); - if (typeof payload.dur === 'number') + } + if (typeof payload.dur === 'number') { event.setEndTime((payload.ts + payload.dur) / 1000); + } const id = SDK.TracingModel._extractId(payload); - if (typeof id !== 'undefined') + if (typeof id !== 'undefined') { event.id = id; - if (payload.bind_id) + } + if (payload.bind_id) { event.bind_id = payload.bind_id; + } return event; } @@ -602,8 +628,9 @@ addArgs(args) { // Shallow copy args to avoid modifying original payload which may be saved to file. for (const name in args) { - if (name in this.args) + if (name in this.args) { console.error('Same argument name (' + name + ') is used for begin and end phases of ' + this.name); + } this.args[name] = args[name]; } } @@ -612,10 +639,11 @@ * @param {!SDK.TracingModel.Event} endEvent */ _complete(endEvent) { - if (endEvent.args) + if (endEvent.args) { this.addArgs(endEvent.args); - else + } else { console.error('Missing mandatory event argument \'args\' at ' + endEvent.startTime); + } this.setEndTime(endEvent.startTime); } @@ -653,14 +681,16 @@ static fromPayload(payload, thread) { const snapshot = new SDK.TracingModel.ObjectSnapshot(payload.cat, payload.name, payload.ts / 1000, thread); const id = SDK.TracingModel._extractId(payload); - if (typeof id !== 'undefined') + if (typeof id !== 'undefined') { snapshot.id = id; + } if (!payload.args || !payload.args['snapshot']) { console.error('Missing mandatory \'snapshot\' argument at ' + payload.ts / 1000); return snapshot; } - if (payload.args) + if (payload.args) { snapshot.addArgs(payload.args); + } return snapshot; } @@ -696,8 +726,9 @@ * @return {!Promise<?>} */ objectPromise() { - if (!this._objectPromise) + if (!this._objectPromise) { this._objectPromise = new Promise(this.requestObject.bind(this)); + } return this._objectPromise; } @@ -706,8 +737,9 @@ * @param {?function():!Promise.<?>} backingStorage */ _setBackingStorage(backingStorage) { - if (!backingStorage) + if (!backingStorage) { return; + } this._backingStorage = backingStorage; this.args = {}; } @@ -898,8 +930,9 @@ case phases.End: this._events[i] = null; // Mark for removal. // Quietly ignore unbalanced close events, they're legit (we could have missed start one). - if (!stack.length) + if (!stack.length) { continue; + } const top = stack.pop(); if (top.name !== e.name || top.categoriesString !== e.categoriesString) { console.error( @@ -914,8 +947,9 @@ break; } } - while (stack.length) + while (stack.length) { stack.pop().setEndTime(this._model.maximumRecordTime()); + } this._events.remove(null, false); } @@ -929,8 +963,9 @@ SDK.TracingModel.Event.fromPayload(payload, this); if (SDK.TracingModel.isTopLevelEvent(event)) { // Discard nested "top-level" events. - if (this._lastTopLevelEvent && this._lastTopLevelEvent.endTime > event.startTime) + if (this._lastTopLevelEvent && this._lastTopLevelEvent.endTime > event.startTime) { return null; + } this._lastTopLevelEvent = event; } this._events.push(event);
diff --git a/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js b/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js index bc5263a..febd281c 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sdk_test_runner/PageMockTestRunner.js
@@ -131,8 +131,9 @@ reload() { this._fireEvent('Page.frameStartedLoading', {frameId: this._mainFrame.id}); - for (const context of this._executionContexts) + for (const context of this._executionContexts) { this._fireEvent('Runtime.executionContextDestroyed', {executionContextId: context.id}); + } this._scripts = []; @@ -141,8 +142,9 @@ this._fireEvent('Runtime.executionContextsCleared', {}); this._executionContexts.push(this._createExecutionContext(this._mainFrame, false)); - for (const context of this._executionContexts) + for (const context of this._executionContexts) { this._fireEvent('Runtime.executionContextCreated', {context: context}); + } this._fireEvent('Page.frameNavigated', {frame: this._mainFrame}); @@ -169,8 +171,9 @@ this._enabledDomains.add('Debugger'); this._sendResponse(id, {}); - for (const script of this._scripts) + for (const script of this._scripts) { this._fireEvent('Debugger.scriptParsed', script); + } } _debuggerGetScriptSource(id, params) { @@ -189,8 +192,9 @@ this._enabledDomains.add('Runtime'); this._sendResponse(id, {}); - for (const context of this._executionContexts) + for (const context of this._executionContexts) { this._fireEvent('Runtime.executionContextCreated', {context: context}); + } } _pageEnable(id, params) { @@ -207,8 +211,9 @@ _isSupportedDomain(methodName) { const domain = methodName.split('.')[0]; - if (domain === 'Page') + if (domain === 'Page') { return this._type === SDK.Target.Type.Frame; + } return true; } @@ -216,15 +221,17 @@ _dispatch(sessionId, id, methodName, params) { if (sessionId) { const child = this._children.get(sessionId); - if (child) + if (child) { child._dispatch('', id, methodName, params); + } return; } const handler = (this._isSupportedDomain(methodName) ? this._dispatchMap[methodName] : null); - if (handler) + if (handler) { return handler.call(this, id, params); + } this._sendResponse( id, undefined, {message: 'Can\'t handle command ' + methodName, code: Protocol.DevToolsStubErrorCode}); @@ -243,8 +250,9 @@ _fireEvent(methodName, params) { const domain = methodName.split('.')[0]; - if (!this._enabledDomains.has(domain)) + if (!this._enabledDomains.has(domain)) { return; + } const message = {method: methodName, params: params}; if (this._root) {
diff --git a/third_party/blink/renderer/devtools/front_end/search/SearchConfig.js b/third_party/blink/renderer/devtools/front_end/search/SearchConfig.js index 0ba3f5c..27b9c38 100644 --- a/third_party/blink/renderer/devtools/front_end/search/SearchConfig.js +++ b/third_party/blink/renderer/devtools/front_end/search/SearchConfig.js
@@ -83,8 +83,9 @@ for (let i = 0; i < queryParts.length; ++i) { const queryPart = queryParts[i]; - if (!queryPart) + if (!queryPart) { continue; + } const fileQuery = this._parseFileQuery(queryPart); if (fileQuery) { this._fileQueries.push(fileQuery); @@ -99,8 +100,9 @@ continue; } if (queryPart.startsWith('"')) { - if (!queryPart.endsWith('"')) + if (!queryPart.endsWith('"')) { continue; + } this._queries.push(this._parseQuotedQuery(queryPart)); continue; } @@ -114,11 +116,13 @@ * @return {boolean} */ filePathMatchesFileQuery(filePath) { - if (!this._fileRegexQueries) + if (!this._fileRegexQueries) { return true; + } for (let i = 0; i < this._fileRegexQueries.length; ++i) { - if (!!filePath.match(this._fileRegexQueries[i].regex) === this._fileRegexQueries[i].isNegative) + if (!!filePath.match(this._fileRegexQueries[i].regex) === this._fileRegexQueries[i].isNegative) { return false; + } } return true; } @@ -145,8 +149,9 @@ */ _parseFileQuery(query) { const match = query.match(Search.SearchConfig.FilePatternRegex); - if (!match) + if (!match) { return null; + } const isNegative = !!match[1]; query = match[3]; let result = ''; @@ -157,11 +162,13 @@ } else if (char === '\\') { ++i; const nextChar = query[i]; - if (nextChar === ' ') + if (nextChar === ' ') { result += ' '; + } } else { - if (String.regexSpecialCharacters().indexOf(query.charAt(i)) !== -1) + if (String.regexSpecialCharacters().indexOf(query.charAt(i)) !== -1) { result += '\\'; + } result += query.charAt(i); } }
diff --git a/third_party/blink/renderer/devtools/front_end/search/SearchResultsPane.js b/third_party/blink/renderer/devtools/front_end/search/SearchResultsPane.js index 47030ca..6452c62f 100644 --- a/third_party/blink/renderer/devtools/front_end/search/SearchResultsPane.js +++ b/third_party/blink/renderer/devtools/front_end/search/SearchResultsPane.js
@@ -34,8 +34,9 @@ const treeElement = new Search.SearchResultsPane.SearchResultsTreeElement(this._searchConfig, searchResult); this._treeOutline.appendChild(treeElement); // Expand until at least a certain number of matches is expanded. - if (this._matchesExpandedCount < Search.SearchResultsPane._matchesExpandedByDefault) + if (this._matchesExpandedCount < Search.SearchResultsPane._matchesExpandedByDefault) { treeElement.expand(); + } this._matchesExpandedCount += searchResult.matchesCount(); } }; @@ -62,8 +63,9 @@ * @override */ onexpand() { - if (this._initialized) + if (this._initialized) { return; + } this._updateMatchesUI(); this._initialized = true; @@ -102,8 +104,9 @@ matchesCountSpan.textContent = `${this._searchResult.matchesCount()}`; this.listItemElement.appendChild(matchesCountSpan); - if (this.expanded) + if (this.expanded) { this._updateMatchesUI(); + } /** * @param {string} text @@ -127,14 +130,16 @@ const queries = this._searchConfig.queries(); const regexes = []; - for (let i = 0; i < queries.length; ++i) + for (let i = 0; i < queries.length; ++i) { regexes.push(createSearchRegex(queries[i], !this._searchConfig.ignoreCase(), this._searchConfig.isRegex())); + } for (let i = fromIndex; i < toIndex; ++i) { const lineContent = searchResult.matchLineContent(i).trim(); let matchRanges = []; - for (let j = 0; j < regexes.length; ++j) + for (let j = 0; j < regexes.length; ++j) { matchRanges = matchRanges.concat(this._regexMatchRanges(lineContent, regexes[j])); + } const anchor = Components.Linkifier.linkifyRevealable(searchResult.matchRevealable(i), ''); anchor.classList.add('search-match-link'); @@ -175,8 +180,9 @@ */ _createContentSpan(lineContent, matchRanges) { let trimBy = 0; - if (matchRanges.length > 0 && matchRanges[0].offset > 20) + if (matchRanges.length > 0 && matchRanges[0].offset > 20) { trimBy = 15; + } lineContent = lineContent.substring(trimBy, 1000 + trimBy); if (trimBy) { matchRanges = matchRanges.map(range => new TextUtils.SourceRange(range.offset - trimBy + 1, range.length)); @@ -198,8 +204,9 @@ regex.lastIndex = 0; let match; const matchRanges = []; - while ((regex.lastIndex < lineContent.length) && (match = regex.exec(lineContent))) + while ((regex.lastIndex < lineContent.length) && (match = regex.exec(lineContent))) { matchRanges.push(new TextUtils.SourceRange(match.index, match[0].length)); + } return matchRanges; }
diff --git a/third_party/blink/renderer/devtools/front_end/search/SearchView.js b/third_party/blink/renderer/devtools/front_end/search/SearchView.js index 4e8c5dd0..600e754 100644 --- a/third_party/blink/renderer/devtools/front_end/search/SearchView.js +++ b/third_party/blink/renderer/devtools/front_end/search/SearchView.js
@@ -106,18 +106,21 @@ * @param {boolean=} searchImmediately */ async toggle(queryCandidate, searchImmediately) { - if (queryCandidate) + if (queryCandidate) { this._search.value = queryCandidate; - if (this.isShowing()) + } + if (this.isShowing()) { this.focus(); - else + } else { this._focusOnShow = true; + } this._initScope(); - if (searchImmediately) + if (searchImmediately) { this._onAction(); - else + } else { this._startIndexing(); + } } /** @@ -148,10 +151,12 @@ this._progressIndicator = null; this._isIndexing = false; this._indexingFinished(finished); - if (!finished) + if (!finished) { this._pendingSearchConfig = null; - if (!this._pendingSearchConfig) + } + if (!this._pendingSearchConfig) { return; + } const searchConfig = this._pendingSearchConfig; this._pendingSearchConfig = null; this._innerStartSearch(searchConfig); @@ -159,8 +164,9 @@ _startIndexing() { this._isIndexing = true; - if (this._progressIndicator) + if (this._progressIndicator) { this._progressIndicator.done(); + } this._progressIndicator = new UI.ProgressIndicator(); this._searchMessageElement.textContent = Common.UIString('Indexing\u2026'); this._progressIndicator.show(this._searchProgressPlaceholderElement); @@ -178,15 +184,17 @@ * @param {!Search.SearchResult} searchResult */ _onSearchResult(searchId, searchResult) { - if (searchId !== this._searchId || !this._progressIndicator) + if (searchId !== this._searchId || !this._progressIndicator) { return; + } if (this._progressIndicator && this._progressIndicator.isCanceled()) { this._onIndexingFinished(); return; } this._addSearchResult(searchResult); - if (!searchResult.matchesCount()) + if (!searchResult.matchesCount()) { return; + } if (!this._searchResultsPane) { this._searchResultsPane = new Search.SearchResultsPane(/** @type {!Search.SearchConfig} */ (this._searchConfig)); this._showPane(this._searchResultsPane); @@ -199,10 +207,12 @@ * @param {boolean} finished */ _onSearchFinished(searchId, finished) { - if (searchId !== this._searchId || !this._progressIndicator) + if (searchId !== this._searchId || !this._progressIndicator) { return; - if (!this._searchResultsPane) + } + if (!this._searchResultsPane) { this._nothingFound(); + } this._searchFinished(finished); this._searchConfig = null; } @@ -214,15 +224,17 @@ this._resetSearch(); ++this._searchId; this._initScope(); - if (!this._isIndexing) + if (!this._isIndexing) { this._startIndexing(); + } this._pendingSearchConfig = searchConfig; } _innerStartSearch(searchConfig) { this._searchConfig = searchConfig; - if (this._progressIndicator) + if (this._progressIndicator) { this._progressIndicator.done(); + } this._progressIndicator = new UI.ProgressIndicator(); this._searchStarted(this._progressIndicator); this._searchScope.performSearch( @@ -237,10 +249,12 @@ } _stopSearch() { - if (this._progressIndicator && !this._isIndexing) + if (this._progressIndicator && !this._isIndexing) { this._progressIndicator.cancel(); - if (this._searchScope) + } + if (this._searchScope) { this._searchScope.stopSearch(); + } this._searchConfig = null; } @@ -249,8 +263,9 @@ */ _searchStarted(progressIndicator) { this._resetCounters(); - if (!this._searchingView) + if (!this._searchingView) { this._searchingView = new UI.EmptyWidget(Common.UIString('Searching\u2026')); + } this._showPane(this._searchingView); this._searchMessageElement.textContent = Common.UIString('Searching\u2026'); progressIndicator.show(this._searchProgressPlaceholderElement); @@ -284,10 +299,12 @@ * @param {?UI.Widget} panel */ _showPane(panel) { - if (this._visiblePane) + if (this._visiblePane) { this._visiblePane.detach(); - if (panel) + } + if (panel) { panel.show(this._searchResultsElement); + } this._visiblePane = panel; } @@ -298,8 +315,9 @@ } _nothingFound() { - if (!this._notFoundView) + if (!this._notFoundView) { this._notFoundView = new UI.EmptyWidget(Common.UIString('No matches found.')); + } this._showPane(this._notFoundView); this._searchResultsMessageElement.textContent = Common.UIString('No matches found.'); } @@ -311,8 +329,9 @@ const matchesCount = searchResult.matchesCount(); this._searchMatchesCount += matchesCount; this._searchResultsCount++; - if (matchesCount) + if (matchesCount) { this._nonEmptySearchResultsCount++; + } this._updateSearchResultsMessage(); } @@ -363,8 +382,9 @@ _onAction() { const searchConfig = this._buildSearchConfig(); - if (!searchConfig.query() || !searchConfig.query().length) + if (!searchConfig.query() || !searchConfig.query().length) { return; + } this._save(); this._startSearch(searchConfig); }
diff --git a/third_party/blink/renderer/devtools/front_end/security/SecurityModel.js b/third_party/blink/renderer/devtools/front_end/security/SecurityModel.js index 0e47659..e0eb5de 100644 --- a/third_party/blink/renderer/devtools/front_end/security/SecurityModel.js +++ b/third_party/blink/renderer/devtools/front_end/security/SecurityModel.js
@@ -48,8 +48,9 @@ // and so that failed/cancelled requests appear at the bottom of the origins list. Protocol.Security.SecurityState.Unknown ]; - for (let i = 0; i < ordering.length; i++) + for (let i = 0; i < ordering.length; i++) { securityStateMap.set(ordering[i], i + 1); + } Security.SecurityModel._symbolicToNumericSecurityState = securityStateMap; } const aScore = securityStateMap.get(a) || 0;
diff --git a/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js b/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js index 93bc05c..859056e 100644 --- a/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js +++ b/third_party/blink/renderer/devtools/front_end/security/SecurityPanel.js
@@ -47,8 +47,9 @@ const certificateButton = UI.createTextButton(text, async e => { e.consume(); const names = await SDK.multitargetNetworkManager.getCertificate(origin); - if (names.length > 0) + if (names.length > 0) { InspectorFrontendHost.showCertificateViewer(names); + } }, 'origin-button'); UI.ARIAUtils.markAsMenuButton(certificateButton); return certificateButton; @@ -125,8 +126,9 @@ */ showOrigin(origin) { const originState = this._origins.get(origin); - if (!originState.originView) + if (!originState.originView) { originState.originView = new Security.SecurityOriginView(this, origin, originState); + } this._setVisibleView(originState.originView); } @@ -136,8 +138,9 @@ */ wasShown() { super.wasShown(); - if (!this._visibleView) + if (!this._visibleView) { this.selectAndSwitchToMainView(); + } } /** @@ -151,16 +154,19 @@ * @param {!UI.VBox} view */ _setVisibleView(view) { - if (this._visibleView === view) + if (this._visibleView === view) { return; + } - if (this._visibleView) + if (this._visibleView) { this._visibleView.detach(); + } this._visibleView = view; - if (view) + if (view) { this.splitWidget().setMainWidget(view); + } } /** @@ -168,8 +174,9 @@ */ _onResponseReceived(event) { const request = /** @type {!SDK.NetworkRequest} */ (event.data); - if (request.resourceType() === Common.resourceTypes.Document) + if (request.resourceType() === Common.resourceTypes.Document) { this._lastResponseReceivedForLoaderId.set(request.loaderId, request); + } } /** @@ -186,8 +193,9 @@ let securityState = /** @type {!Protocol.Security.SecurityState} */ (request.securityState()); if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable || - request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) + request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) { securityState = Protocol.Security.SecurityState.Insecure; + } if (this._origins.has(origin)) { const originState = this._origins.get(origin); @@ -195,11 +203,13 @@ originState.securityState = this._securityStateMin(oldSecurityState, securityState); if (oldSecurityState !== originState.securityState) { const securityDetails = /** @type {?Protocol.Network.SecurityDetails} */ (request.securityDetails()); - if (securityDetails) + if (securityDetails) { originState.securityDetails = securityDetails; + } this._sidebarTree.updateOrigin(origin, securityState); - if (originState.originView) + if (originState.originView) { originState.originView.setSecurityState(securityState); + } } } else { // This stores the first security details we see for an origin, but we should @@ -209,8 +219,9 @@ originState.securityState = securityState; const securityDetails = request.securityDetails(); - if (securityDetails) + if (securityDetails) { originState.securityDetails = securityDetails; + } originState.loadedFromCache = request.cached(); @@ -235,22 +246,25 @@ * @param {!SDK.NetworkRequest} request */ _updateFilterRequestCounts(request) { - if (request.mixedContentType === Protocol.Security.MixedContentType.None) + if (request.mixedContentType === Protocol.Security.MixedContentType.None) { return; + } /** @type {!Network.NetworkLogView.MixedContentFilterValues} */ let filterKey = Network.NetworkLogView.MixedContentFilterValues.All; - if (request.wasBlocked()) + if (request.wasBlocked()) { filterKey = Network.NetworkLogView.MixedContentFilterValues.Blocked; - else if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable) + } else if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable) { filterKey = Network.NetworkLogView.MixedContentFilterValues.BlockOverridden; - else if (request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) + } else if (request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) { filterKey = Network.NetworkLogView.MixedContentFilterValues.Displayed; + } - if (!this._filterRequestCounts.has(filterKey)) + if (!this._filterRequestCounts.has(filterKey)) { this._filterRequestCounts.set(filterKey, 1); - else + } else { this._filterRequestCounts.set(filterKey, this._filterRequestCounts.get(filterKey) + 1); + } this._mainView.refreshExplanations(); } @@ -277,8 +291,9 @@ * @param {!Security.SecurityModel} securityModel */ modelAdded(securityModel) { - if (this._securityModel) + if (this._securityModel) { return; + } this._securityModel = securityModel; const resourceTreeModel = securityModel.resourceTreeModel(); @@ -296,8 +311,9 @@ networkManager.addEventListener(SDK.NetworkManager.Events.RequestFinished, this._onRequestFinished, this), ]; - if (resourceTreeModel.isInterstitialShowing()) + if (resourceTreeModel.isInterstitialShowing()) { this._onInterstitialShown(); + } } /** @@ -305,8 +321,9 @@ * @param {!Security.SecurityModel} securityModel */ modelRemoved(securityModel) { - if (this._securityModel !== securityModel) + if (this._securityModel !== securityModel) { return; + } delete this._securityModel; Common.EventTarget.removeEventListeners(this._eventListeners); @@ -334,8 +351,9 @@ const origin = Common.ParsedURL.extractOrigin(request ? request.url() : frame.url); this._sidebarTree.setMainOrigin(origin); - if (request) + if (request) { this._processRequest(request); + } } _onInterstitialShown() { @@ -428,8 +446,9 @@ * @param {boolean} hidden */ toggleOriginsList(hidden) { - for (const element of this._originGroups.values()) + for (const element of this._originGroups.values()) { element.hidden = hidden; + } } /** @@ -464,10 +483,11 @@ let newParent; if (origin === this._mainOrigin) { newParent = this._originGroups.get(Security.SecurityPanelSidebarTree.OriginGroup.MainOrigin); - if (securityState === Protocol.Security.SecurityState.Secure) + if (securityState === Protocol.Security.SecurityState.Secure) { newParent.title = ls`Main origin (secure)`; - else + } else { newParent.title = ls`Main origin (non-secure)`; + } } else { switch (securityState) { case Protocol.Security.SecurityState.Secure: @@ -486,8 +506,9 @@ if (oldParent !== newParent) { if (oldParent) { oldParent.removeChild(originElement); - if (oldParent.childCount() === 0) + if (oldParent.childCount() === 0) { oldParent.hidden = true; + } } newParent.appendChild(originElement); newParent.hidden = false; @@ -552,8 +573,9 @@ * @param {!Protocol.Security.SecurityState} newSecurityState */ setSecurityState(newSecurityState) { - if (this._securityState) + if (this._securityState) { this._iconElement.classList.remove(this._cssPrefix + '-' + this._securityState); + } this._securityState = newSecurityState; this._iconElement.classList.add(this._cssPrefix + '-' + newSecurityState); @@ -652,8 +674,9 @@ if (explanation.recommendations && explanation.recommendations.length) { const recommendationList = text.createChild('ul', 'security-explanation-recommendations'); - for (const recommendation of explanation.recommendations) + for (const recommendation of explanation.recommendations) { recommendationList.createChild('li').textContent = recommendation; + } } return text; } @@ -746,15 +769,17 @@ const requestsAnchor = element.createChild('div', 'security-mixed-content devtools-link'); UI.ARIAUtils.markAsLink(requestsAnchor); requestsAnchor.tabIndex = 0; - if (filterRequestCount === 1) + if (filterRequestCount === 1) { requestsAnchor.textContent = Common.UIString('View %d request in Network Panel', filterRequestCount); - else + } else { requestsAnchor.textContent = Common.UIString('View %d requests in Network Panel', filterRequestCount); + } requestsAnchor.addEventListener('click', this.showNetworkFilter.bind(this, filterKey)); requestsAnchor.addEventListener('keydown', event => { - if (isEnterKey(event)) + if (isEnterKey(event)) { this.showNetworkFilter(filterKey, event); + } }); } @@ -820,10 +845,12 @@ let table = new Security.SecurityDetailsTable(); connectionSection.appendChild(table.element()); table.addRow(Common.UIString('Protocol'), originState.securityDetails.protocol); - if (originState.securityDetails.keyExchange) + if (originState.securityDetails.keyExchange) { table.addRow(Common.UIString('Key exchange'), originState.securityDetails.keyExchange); - if (originState.securityDetails.keyExchangeGroup) + } + if (originState.securityDetails.keyExchangeGroup) { table.addRow(Common.UIString('Key exchange group'), originState.securityDetails.keyExchangeGroup); + } table.addRow( Common.UIString('Cipher'), originState.securityDetails.cipher + @@ -863,8 +890,9 @@ Security.SecurityPanel.createCertificateViewerButtonForOrigin( Common.UIString('Open full certificate details'), origin)); - if (!sctSection) + if (!sctSection) { return; + } // Show summary of SCT(s) of Certificate Transparency. const sctSummaryTable = new Security.SecurityDetailsTable(); @@ -897,10 +925,11 @@ if (sctListLength) { function toggleSctDetailsDisplay() { const isDetailsShown = !sctTableWrapper.classList.contains('hidden'); - if (isDetailsShown) + if (isDetailsShown) { toggleSctsDetailsLink.textContent = ls`Show full details`; - else + } else { toggleSctsDetailsLink.textContent = ls`Hide full details`; + } sctSummaryTable.element().classList.toggle('hidden'); sctTableWrapper.classList.toggle('hidden'); } @@ -970,8 +999,9 @@ for (let i = 0; i < sanList.length; i++) { const span = sanDiv.createChild('span', 'san-entry'); span.textContent = sanList[i]; - if (listIsTruncated && i >= truncatedNumToShow) + if (listIsTruncated && i >= truncatedNumToShow) { span.classList.add('truncated-entry'); + } } if (listIsTruncated) { function toggleSANTruncation() { @@ -1002,8 +1032,9 @@ */ setSecurityState(newSecurityState) { for (const className of Array.prototype.slice.call(this._originLockIcon.classList)) { - if (className.startsWith('security-property-')) + if (className.startsWith('security-property-')) { this._originLockIcon.classList.remove(className); + } } this._originLockIcon.classList.add('security-property-' + newSecurityState); @@ -1035,9 +1066,10 @@ row.createChild('div').textContent = key; const valueDiv = row.createChild('div'); - if (typeof value === 'string') + if (typeof value === 'string') { valueDiv.textContent = value; - else + } else { valueDiv.appendChild(value); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/security_test_runner/SecurityTestRunner.js b/third_party/blink/renderer/devtools/front_end/security_test_runner/SecurityTestRunner.js index 1842949f..c968246a 100644 --- a/third_party/blink/renderer/devtools/front_end/security_test_runner/SecurityTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/security_test_runner/SecurityTestRunner.js
@@ -12,15 +12,17 @@ const originGroup = Security.SecurityPanelSidebarTree.OriginGroup[key]; const element = Security.SecurityPanel._instance()._sidebarTree._originGroups.get(originGroup); - if (element.hidden) + if (element.hidden) { continue; + } TestRunner.addResult('Group: ' + element.title); const originTitles = element.childrenListElement.getElementsByTagName('span'); for (const originTitle of originTitles) { - if (originTitle.className !== 'tree-element-title') + if (originTitle.className !== 'tree-element-title') { TestRunner.dumpDeepInnerHTML(originTitle); + } } } };
diff --git a/third_party/blink/renderer/devtools/front_end/services/ServiceManager.js b/third_party/blink/renderer/devtools/front_end/services/ServiceManager.js index b142533..9c0ee7fa 100644 --- a/third_party/blink/renderer/devtools/front_end/services/ServiceManager.js +++ b/third_party/blink/renderer/devtools/front_end/services/ServiceManager.js
@@ -34,15 +34,19 @@ const isUnderTest = Host.isUnderTest(); const queryParams = []; - if (remoteBase) + if (remoteBase) { queryParams.push('remoteBase=' + remoteBase); - if (debugFrontend) + } + if (debugFrontend) { queryParams.push('debugFrontend=' + debugFrontend); - if (isUnderTest) + } + if (isUnderTest) { queryParams.push('isUnderTest=true'); + } - if (queryParams.length) + if (queryParams.length) { url += `?${queryParams.join('&')}`; + } const worker = new Worker(url); const connection = new Services.ServiceManager.Connection(new Services.ServiceManager.WorkerServicePort(worker)); @@ -104,8 +108,9 @@ const id = this._lastId++; const message = JSON.stringify({id: id, method: method, params: params || {}}); return this._port.send(message).then(success => { - if (!success) + if (!success) { return Promise.resolve(null); + } return new Promise(fulfill => this._callbacks.set(id, fulfill)); }); } @@ -122,8 +127,9 @@ return; } if (object.id) { - if (object.error) + if (object.error) { console.error('Service error: ' + object.error); + } this._callbacks.get(object.id)(object.error ? null : object.result); this._callbacks.delete(object.id); return; @@ -141,11 +147,13 @@ } _connectionClosed() { - for (const callback of this._callbacks.values()) + for (const callback of this._callbacks.values()) { callback(null); + } this._callbacks.clear(); - for (const service of this._services.values()) + for (const service of this._services.values()) { service._dispatchNotification('disposed'); + } this._services.clear(); } }; @@ -236,8 +244,9 @@ * @return {!Promise<boolean>} */ _open() { - if (!this._connectionPromise) + if (!this._connectionPromise) { this._connectionPromise = new Promise(promiseBody.bind(this)); + } return this._connectionPromise; /** @@ -275,8 +284,9 @@ * @this {Services.ServiceManager.RemoteServicePort} */ function onClose() { - if (!this._socket) + if (!this._socket) { fulfill(false); + } this._socketClosed(!!this._socket); } } @@ -317,8 +327,9 @@ _socketClosed(notifyClient) { this._socket = null; delete this._connectionPromise; - if (notifyClient) + if (notifyClient) { this._closeHandler(); + } } }; @@ -384,8 +395,9 @@ */ close() { return this._workerPromise.then(() => { - if (this._worker) + if (this._worker) { this._worker.terminate(); + } return false; }); }
diff --git a/third_party/blink/renderer/devtools/front_end/settings/FrameworkBlackboxSettingsTab.js b/third_party/blink/renderer/devtools/front_end/settings/FrameworkBlackboxSettingsTab.js index c2a998ed..fc3f1c2 100644 --- a/third_party/blink/renderer/devtools/front_end/settings/FrameworkBlackboxSettingsTab.js +++ b/third_party/blink/renderer/devtools/front_end/settings/FrameworkBlackboxSettingsTab.js
@@ -55,8 +55,9 @@ _settingUpdated() { this._list.clear(); const patterns = this._setting.getAsArray(); - for (let i = 0; i < patterns.length; ++i) + for (let i = 0; i < patterns.length; ++i) { this._list.appendItem(patterns[i], true); + } } _addButtonClicked() { @@ -77,8 +78,9 @@ element.createChild('div', 'blackbox-separator'); element.createChild('div', 'blackbox-behavior').textContent = item.disabled ? this._disabledLabel : this._blackboxLabel; - if (item.disabled) + if (item.disabled) { element.classList.add('blackbox-disabled'); + } return element; } @@ -104,8 +106,9 @@ item.disabled = editor.control('behavior').value === this._disabledLabel; const list = this._setting.getAsArray(); - if (isNew) + if (isNew) { list.push(item); + } this._setting.setAsArray(list); } @@ -125,8 +128,9 @@ * @return {!UI.ListWidget.Editor} */ _createEditor() { - if (this._editor) + if (this._editor) { return this._editor; + } const editor = new UI.ListWidget.Editor(); this._editor = editor; @@ -159,12 +163,14 @@ const pattern = input.value.trim(); const patterns = this._setting.getAsArray(); - if (!pattern.length) + if (!pattern.length) { return {valid: false, errorMessage: ls`Pattern cannot be empty`}; + } for (let i = 0; i < patterns.length; ++i) { - if (i !== index && patterns[i].pattern === pattern) + if (i !== index && patterns[i].pattern === pattern) { return {valid: false, errorMessage: ls`Pattern already exists`}; + } } let regex; @@ -172,10 +178,11 @@ regex = new RegExp(pattern); } catch (e) { } - if (!regex) + if (!regex) { return {valid: false, errorMessage: ls`Pattern must be a valid regular expression`}; - else + } else { return {valid: true}; + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/settings/SettingsScreen.js b/third_party/blink/renderer/devtools/front_end/settings/SettingsScreen.js index bbcabfd..5d0405f 100644 --- a/third_party/blink/renderer/devtools/front_end/settings/SettingsScreen.js +++ b/third_party/blink/renderer/devtools/front_end/settings/SettingsScreen.js
@@ -69,8 +69,9 @@ static _showSettingsScreen(name) { const settingsScreen = /** @type {!Settings.SettingsScreen} */ (self.runtime.sharedInstance(Settings.SettingsScreen)); - if (settingsScreen.isShowing()) + if (settingsScreen.isShowing()) { return; + } const dialog = new UI.Dialog(); dialog.addCloseButton(); settingsScreen.show(dialog.contentElement); @@ -99,8 +100,9 @@ */ _keyDown(event) { const shiftKeyCode = 16; - if (event.keyCode === shiftKeyCode && ++this._developerModeCounter > 5) + if (event.keyCode === shiftKeyCode && ++this._developerModeCounter > 5) { this.contentElement.classList.add('settings-developer-mode'); + } } }; @@ -116,8 +118,9 @@ constructor(name, id) { super(); this.element.classList.add('settings-tab-container'); - if (id) + if (id) { this.element.id = id; + } const header = this.element.createChild('header'); header.createChild('h1').createTextChild(name); this.containerElement = this.element.createChild('div', 'settings-container-wrapper') @@ -153,8 +156,9 @@ ['', 'Appearance', 'Sources', 'Elements', 'Network', 'Performance', 'Console', 'Extensions']; /** @type {!Map<string, !Element>} */ this._nameToSection = new Map(); - for (const sectionName of explicitSectionOrder) + for (const sectionName of explicitSectionOrder) { this._sectionElement(sectionName); + } self.runtime.extensions('setting').forEach(this._addSetting.bind(this)); self.runtime.extensions(UI.SettingUI).forEach(this._addSettingUI.bind(this)); @@ -173,10 +177,12 @@ */ static isSettingVisible(extension) { const descriptor = extension.descriptor(); - if (!('title' in descriptor)) + if (!('title' in descriptor)) { return false; - if (!('category' in descriptor)) + } + if (!('category' in descriptor)) { return false; + } return true; } @@ -184,13 +190,15 @@ * @param {!Runtime.Extension} extension */ _addSetting(extension) { - if (!Settings.GenericSettingsTab.isSettingVisible(extension)) + if (!Settings.GenericSettingsTab.isSettingVisible(extension)) { return; + } const sectionElement = this._sectionElement(extension.descriptor()['category']); const setting = Common.moduleSetting(extension.descriptor()['settingName']); const settingControl = UI.SettingsUI.createControlForSetting(setting); - if (settingControl) + if (settingControl) { sectionElement.appendChild(settingControl); + } } /** @@ -208,8 +216,9 @@ function appendCustomSetting(object) { const settingUI = /** @type {!UI.SettingUI} */ (object); const element = settingUI.settingElement(); - if (element) + if (element) { this._sectionElement(sectionName).appendChild(element); + } } } @@ -239,8 +248,9 @@ if (experiments.length) { const experimentsSection = this._appendSection(); experimentsSection.appendChild(this._createExperimentsWarningSubsection()); - for (let i = 0; i < experiments.length; ++i) + for (let i = 0; i < experiments.length; ++i) { experimentsSection.appendChild(this._createExperimentCheckbox(experiments[i])); + } } } @@ -325,8 +335,9 @@ * @param {!Runtime.Extension} extension */ function revealModuleSetting(extension) { - if (!Settings.GenericSettingsTab.isSettingVisible(extension)) + if (!Settings.GenericSettingsTab.isSettingVisible(extension)) { return; + } if (extension.descriptor()['settingName'] === setting.name) { InspectorFrontendHost.bringToFront(); Settings.SettingsScreen._showSettingsScreen(); @@ -351,8 +362,9 @@ */ function revealSettingsView(extension) { const location = extension.descriptor()['location']; - if (location !== 'settings-view') + if (location !== 'settings-view') { return; + } const settings = extension.descriptor()['settings']; if (settings && settings.indexOf(setting.name) !== -1) { InspectorFrontendHost.bringToFront();
diff --git a/third_party/blink/renderer/devtools/front_end/snippets/ScriptSnippetFileSystem.js b/third_party/blink/renderer/devtools/front_end/snippets/ScriptSnippetFileSystem.js index ad3092e..ed8322a 100644 --- a/third_party/blink/renderer/devtools/front_end/snippets/ScriptSnippetFileSystem.js +++ b/third_party/blink/renderer/devtools/front_end/snippets/ScriptSnippetFileSystem.js
@@ -153,12 +153,14 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ Snippets.evaluateScriptSnippet = async function(uiSourceCode) { - if (!uiSourceCode.url().startsWith('snippet://')) + if (!uiSourceCode.url().startsWith('snippet://')) { return; + } const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return; + } const runtimeModel = executionContext.runtimeModel; @@ -186,8 +188,9 @@ runtimeModel, result.exceptionDetails, /* messageType */ undefined, /* timestamp */ undefined, url)); return; } - if (!result.object) + if (!result.object) { return; + } const scripts = executionContext.debuggerModel.scriptsForSourceURL(url); const scriptId = scripts[scripts.length - 1].scriptId;
diff --git a/third_party/blink/renderer/devtools/front_end/snippets/SnippetsQuickOpen.js b/third_party/blink/renderer/devtools/front_end/snippets/SnippetsQuickOpen.js index c48bf1a..c2c3228 100644 --- a/third_party/blink/renderer/devtools/front_end/snippets/SnippetsQuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/snippets/SnippetsQuickOpen.js
@@ -14,8 +14,9 @@ * @param {string} promptValue */ selectItem(itemIndex, promptValue) { - if (itemIndex === null) + if (itemIndex === null) { return; + } Snippets.evaluateScriptSnippet(this._snippets[itemIndex]); }
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/BinaryResourceViewFactory.js b/third_party/blink/renderer/devtools/front_end/source_frame/BinaryResourceViewFactory.js index 343ab16..4b8889d 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/BinaryResourceViewFactory.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/BinaryResourceViewFactory.js
@@ -105,8 +105,9 @@ */ static uint8ArrayToHexString(uint8Array) { let output = ''; - for (let i = 0; i < uint8Array.length; i++) + for (let i = 0; i < uint8Array.length; i++) { output += SourceFrame.BinaryResourceViewFactory.numberToHex(uint8Array[i], 2); + } return output; } @@ -117,8 +118,9 @@ */ static numberToHex(number, padding) { let hex = number.toString(16); - while (hex.length < padding) + while (hex.length < padding) { hex = '0' + hex; + } return hex; }
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/FontView.js b/third_party/blink/renderer/devtools/front_end/source_frame/FontView.js index 22786038..a01c5ef 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/FontView.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/FontView.js
@@ -64,8 +64,9 @@ } _createContentIfNeeded() { - if (this.fontPreviewElement) + if (this.fontPreviewElement) { return; + } const uniqueFontName = 'WebInspectorFontPreview' + (++SourceFrame.FontView._fontId); @@ -75,8 +76,9 @@ const fontPreview = createElement('div'); for (let i = 0; i < SourceFrame.FontView._fontPreviewLines.length; ++i) { - if (i > 0) + if (i > 0) { fontPreview.createChild('br'); + } fontPreview.createTextChild(SourceFrame.FontView._fontPreviewLines[i]); } this.fontPreviewElement = fontPreview.cloneNode(true); @@ -109,8 +111,9 @@ * @override */ onResize() { - if (this._inResize) + if (this._inResize) { return; + } this._inResize = true; try { @@ -129,8 +132,9 @@ } updateFontPreviewSize() { - if (!this.fontPreviewElement || !this.isShowing()) + if (!this.fontPreviewElement || !this.isShowing()) { return; + } this.fontPreviewElement.style.removeProperty('visibility'); const dimension = this._measureElement();
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/ImageView.js b/third_party/blink/renderer/devtools/front_end/source_frame/ImageView.js index c6f5e86d..8815c0f 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/ImageView.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/ImageView.js
@@ -95,14 +95,16 @@ async _updateContentIfNeeded() { const content = await this._contentProvider.requestContent(); - if (this._cachedContent === content) + if (this._cachedContent === content) { return; + } const contentEncoded = await this._contentProvider.contentEncoded(); this._cachedContent = content; let imageSrc = Common.ContentProvider.contentAsDataURL(content, this._mimeType, contentEncoded); - if (content === null) + if (content === null) { imageSrc = this._url; + } const loadPromise = new Promise(x => this._imagePreviewElement.onload = x); this._imagePreviewElement.src = imageSrc; const size = content && !contentEncoded ? content.length : base64ToSize(content); @@ -114,8 +116,9 @@ _contextMenu(event) { const contextMenu = new UI.ContextMenu(event); - if (!this._parsedURL.isDataURL()) + if (!this._parsedURL.isDataURL()) { contextMenu.clipboardSection().appendItem(Common.UIString('Copy image URL'), this._copyImageURL.bind(this)); + } if (this._imagePreviewElement.src) { contextMenu.clipboardSection().appendItem( Common.UIString('Copy image as data URI'), this._copyImageAsDataURL.bind(this)); @@ -150,8 +153,9 @@ */ async _handleDrop(dataTransfer) { const items = dataTransfer.items; - if (!items.length || items[0].kind !== 'file') + if (!items.length || items[0].kind !== 'file') { return; + } const entry = items[0].webkitGetAsEntry(); const encoded = !entry.name.endsWith('.svg'); @@ -165,14 +169,16 @@ result = null; console.error('Can\'t read file: ' + e); } - if (typeof result !== 'string') + if (typeof result !== 'string') { return; + } this._uiSourceCode.setContent(encoded ? btoa(result) : result, encoded); }; - if (encoded) + if (encoded) { reader.readAsBinaryString(file); - else + } else { reader.readAsText(file); + } }); } };
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/JSONView.js b/third_party/blink/renderer/devtools/front_end/source_frame/JSONView.js index 53fe818..f709ee18 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/JSONView.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/JSONView.js
@@ -60,8 +60,9 @@ static async createView(content) { // We support non-strict JSON parsing by parsing an AST tree which is why we offload it to a worker. const parsedJSON = await SourceFrame.JSONView._parseJSON(content); - if (!parsedJSON || typeof parsedJSON.data !== 'object') + if (!parsedJSON || typeof parsedJSON.data !== 'object') { return null; + } const jsonView = new SourceFrame.JSONView(parsedJSON); const searchableView = new UI.SearchableView(jsonView); @@ -91,10 +92,12 @@ */ static _parseJSON(text) { let returnObj = null; - if (text) + if (text) { returnObj = SourceFrame.JSONView._extractJSON(/** @type {string} */ (text)); - if (!returnObj) + } + if (!returnObj) { return Promise.resolve(/** @type {?SourceFrame.ParsedJSON} */ (null)); + } return Formatter.formatterWorkerPool().parseJSONRelaxed(returnObj.data).then(handleReturnedJSON); /** @@ -102,8 +105,9 @@ * @return {?SourceFrame.ParsedJSON} */ function handleReturnedJSON(data) { - if (!data) + if (!data) { return null; + } returnObj.data = data; return returnObj; } @@ -115,23 +119,26 @@ */ static _extractJSON(text) { // Do not treat HTML as JSON. - if (text.startsWith('<')) + if (text.startsWith('<')) { return null; + } let inner = SourceFrame.JSONView._findBrackets(text, '{', '}'); const inner2 = SourceFrame.JSONView._findBrackets(text, '[', ']'); inner = inner2.length > inner.length ? inner2 : inner; // Return on blank payloads or on payloads significantly smaller than original text. - if (inner.length === -1 || text.length - inner.length > 80) + if (inner.length === -1 || text.length - inner.length > 80) { return null; + } const prefix = text.substring(0, inner.start); const suffix = text.substring(inner.end + 1); text = text.substring(inner.start, inner.end + 1); // Only process valid JSONP. - if (suffix.trim().length && !(suffix.trim().startsWith(')') && prefix.trim().endsWith('('))) + if (suffix.trim().length && !(suffix.trim().startsWith(')') && prefix.trim().endsWith('('))) { return null; + } return new SourceFrame.ParsedJSON(text, prefix, suffix); } @@ -146,8 +153,9 @@ const start = text.indexOf(open); const end = text.lastIndexOf(close); let length = end - start - 1; - if (start === -1 || end === -1 || end < start) + if (start === -1 || end === -1 || end < start) { length = -1; + } return {start: start, end: end, length: length}; } @@ -159,8 +167,9 @@ } _initialize() { - if (this._initialized) + if (this._initialized) { return; + } this._initialized = true; const obj = SDK.RemoteObject.fromLocalObject(this._parsedJSON.data); @@ -178,11 +187,13 @@ * @param {number} index */ _jumpToMatch(index) { - if (!this._searchRegex) + if (!this._searchRegex) { return; + } const previousFocusElement = this._currentSearchTreeElements[this._currentSearchFocusIndex]; - if (previousFocusElement) + if (previousFocusElement) { previousFocusElement.setSearchRegex(this._searchRegex); + } const newFocusElement = this._currentSearchTreeElements[index]; if (newFocusElement) { @@ -198,8 +209,9 @@ * @param {number} count */ _updateSearchCount(count) { - if (!this._searchableView) + if (!this._searchableView) { return; + } this._searchableView.updateSearchMatchesCount(count); } @@ -208,8 +220,9 @@ */ _updateSearchIndex(index) { this._currentSearchFocusIndex = index; - if (!this._searchableView) + if (!this._searchableView) { return; + } this._searchableView.updateCurrentMatchIndex(index); } @@ -221,8 +234,9 @@ this._currentSearchTreeElements = []; for (let element = this._treeOutline.rootElement(); element; element = element.traverseNextTreeElement(false)) { - if (!(element instanceof ObjectUI.ObjectPropertyTreeElement)) + if (!(element instanceof ObjectUI.ObjectPropertyTreeElement)) { continue; + } element.revertHighlightChanges(); } this._updateSearchCount(0); @@ -242,17 +256,20 @@ this._searchRegex = searchConfig.toSearchRegex(true); for (let element = this._treeOutline.rootElement(); element; element = element.traverseNextTreeElement(false)) { - if (!(element instanceof ObjectUI.ObjectPropertyTreeElement)) + if (!(element instanceof ObjectUI.ObjectPropertyTreeElement)) { continue; + } const hasMatch = element.setSearchRegex(this._searchRegex); - if (hasMatch) + if (hasMatch) { this._currentSearchTreeElements.push(element); + } if (previousSearchFocusElement === element) { const currentIndex = this._currentSearchTreeElements.length - 1; - if (hasMatch || jumpBackwards) + if (hasMatch || jumpBackwards) { newIndex = currentIndex; - else + } else { newIndex = currentIndex + 1; + } } } this._updateSearchCount(this._currentSearchTreeElements.length); @@ -270,8 +287,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._currentSearchTreeElements.length) + if (!this._currentSearchTreeElements.length) { return; + } const newIndex = mod(this._currentSearchFocusIndex + 1, this._currentSearchTreeElements.length); this._jumpToMatch(newIndex); } @@ -280,8 +298,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._currentSearchTreeElements.length) + if (!this._currentSearchTreeElements.length) { return; + } const newIndex = mod(this._currentSearchFocusIndex - 1, this._currentSearchTreeElements.length); this._jumpToMatch(newIndex); }
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/PreviewFactory.js b/third_party/blink/renderer/devtools/front_end/source_frame/PreviewFactory.js index 8d27446..bad56158 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/PreviewFactory.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/PreviewFactory.js
@@ -10,8 +10,9 @@ */ static async createPreview(provider, mimeType) { let resourceType = Common.ResourceType.fromMimeType(mimeType); - if (resourceType === Common.resourceTypes.Other) + if (resourceType === Common.resourceTypes.Other) { resourceType = provider.contentType(); + } switch (resourceType) { case Common.resourceTypes.Image: @@ -21,19 +22,23 @@ } let content = await provider.requestContent(); - if (!content) + if (!content) { return new UI.EmptyWidget(Common.UIString('Nothing to preview')); + } - if (await provider.contentEncoded()) + if (await provider.contentEncoded()) { content = window.atob(content); + } const parsedXML = SourceFrame.XMLView.parseXML(content, mimeType); - if (parsedXML) + if (parsedXML) { return SourceFrame.XMLView.createSearchableView(parsedXML); + } const jsonView = await SourceFrame.JSONView.createView(content); - if (jsonView) + if (jsonView) { return jsonView; + } if (resourceType.isTextType()) { const highlighterType =
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/ResourceSourceFrame.js b/third_party/blink/renderer/devtools/front_end/source_frame/ResourceSourceFrame.js index a9640e8f..8fb0f69 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/ResourceSourceFrame.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/ResourceSourceFrame.js
@@ -39,8 +39,9 @@ constructor(resource, autoPrettyPrint, codeMirrorOptions) { super(async () => { let content = await resource.requestContent(); - if (await resource.contentEncoded()) + if (await resource.contentEncoded()) { content = window.atob(content); + } return content; }, codeMirrorOptions); this._resource = resource; @@ -95,8 +96,9 @@ searchableView.show(this.contentElement); const toolbar = new UI.Toolbar('toolbar', this.contentElement); - for (const item of sourceFrame.syncToolbarItems()) + for (const item of sourceFrame.syncToolbarItems()) { toolbar.appendToolbarItem(item); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/SourceCodeDiff.js b/third_party/blink/renderer/devtools/front_end/source_frame/SourceCodeDiff.js index ea77057..beadc0d 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/SourceCodeDiff.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/SourceCodeDiff.js
@@ -19,20 +19,23 @@ * @param {?string} newContent */ highlightModifiedLines(oldContent, newContent) { - if (typeof oldContent !== 'string' || typeof newContent !== 'string') + if (typeof oldContent !== 'string' || typeof newContent !== 'string') { return; + } const diff = SourceFrame.SourceCodeDiff.computeDiff(Diff.Diff.lineDiff(oldContent.split('\n'), newContent.split('\n'))); const changedLines = []; for (let i = 0; i < diff.length; ++i) { const diffEntry = diff[i]; - if (diffEntry.type === SourceFrame.SourceCodeDiff.EditType.Delete) + if (diffEntry.type === SourceFrame.SourceCodeDiff.EditType.Delete) { continue; + } for (let lineNumber = diffEntry.from; lineNumber < diffEntry.to; ++lineNumber) { const position = this._textEditor.textEditorPositionHandle(lineNumber, 0); - if (position) + if (position) { changedLines.push(position); + } } } this._updateHighlightedLines(changedLines); @@ -44,8 +47,9 @@ * @param {!Array<!TextEditor.TextEditorPositionHandle>} newLines */ _updateHighlightedLines(newLines) { - if (this._animationTimeout) + if (this._animationTimeout) { clearTimeout(this._animationTimeout); + } this._animationTimeout = null; this._textEditor.operation(operation.bind(this)); @@ -65,8 +69,9 @@ function toggleLines(value) { for (let i = 0; i < this._animatedLines.length; ++i) { const location = this._animatedLines[i].resolve(); - if (location) + if (location) { this._textEditor.toggleLineClass(location.lineNumber, 'highlight-line-modification', value); + } } } } @@ -85,8 +90,9 @@ for (let i = 0; i < diff.length; ++i) { const token = diff[i]; if (token[0] === Diff.Diff.Operation.Equal) { - if (isInsideBlock) + if (isInsideBlock) { flush(); + } currentLineNumber += token[1].length; continue; } @@ -103,8 +109,9 @@ hasAdded = true; } } - if (isInsideBlock) + if (isInsideBlock) { flush(); + } if (result.length > 1 && result[0].from === 0 && result[1].from === 0) { const merged = {type: SourceFrame.SourceCodeDiff.EditType.Modify, from: 0, to: result[1].to}; result.splice(0, 2, merged);
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/SourceFrame.js b/third_party/blink/renderer/devtools/front_end/source_frame/SourceFrame.js index 358558c..7710bc21 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/SourceFrame.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/SourceFrame.js
@@ -75,8 +75,9 @@ this._textEditor.addEventListener( SourceFrame.SourcesTextEditor.Events.SelectionChanged, this._updateSourcePosition, this); this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged, event => { - if (!this._muteChangeEventsForSetContent) + if (!this._muteChangeEventsForSetContent) { this.onTextChanged(event.data.oldRange, event.data.newRange); + } }); /** @type {boolean} */ this._muteChangeEventsForSetContent = false; @@ -105,8 +106,9 @@ * @return {!Array<number>} */ editorToRawLocation: (editorLineNumber, editorColumnNumber = 0) => { - if (!this._pretty) + if (!this._pretty) { return [editorLineNumber, editorColumnNumber]; + } return this._prettyToRawLocation(editorLineNumber, editorColumnNumber); }, @@ -116,8 +118,9 @@ * @return {!Array<number>} */ rawToEditorLocation: (lineNumber, columnNumber = 0) => { - if (!this._pretty) + if (!this._pretty) { return [lineNumber, columnNumber]; + } return this._rawToPrettyLocation(lineNumber, columnNumber); } }; @@ -172,10 +175,12 @@ if (this._pretty) { this._textEditor.setLineNumberFormatter(lineNumber => { const line = this._prettyToRawLocation(lineNumber - 1, 0)[0] + 1; - if (lineNumber === 1) + if (lineNumber === 1) { return String(line); - if (line !== this._prettyToRawLocation(lineNumber - 2, 0)[0] + 1) + } + if (line !== this._prettyToRawLocation(lineNumber - 2, 0)[0] + 1) { return String(line); + } return '-'; }); } else { @@ -199,8 +204,9 @@ * @return {!Array<number>} */ _prettyToRawLocation(line, column) { - if (!this._formattedMap) + if (!this._formattedMap) { return [line, column]; + } return this._formattedMap.formattedToOriginal(line, column); } @@ -210,8 +216,9 @@ * @return {!Array<number>} */ _rawToPrettyLocation(line, column) { - if (!this._formattedMap) + if (!this._formattedMap) { return [line, column]; + } return this._formattedMap.originalToFormatted(line, column); } @@ -221,8 +228,9 @@ */ setEditable(editable) { this._editable = editable; - if (this._loaded) + if (this._loaded) { this._textEditor.setReadOnly(!editable); + } } /** @@ -273,10 +281,11 @@ this._formattedContentPromise = null; this._formattedMap = null; this._prettyToggle.setEnabled(true); - if (this._shouldAutoPrettyPrint && TextUtils.isMinified(content)) + if (this._shouldAutoPrettyPrint && TextUtils.isMinified(content)) { await this._setPretty(true); - else + } else { this.setContent(this._rawContent); + } } } @@ -284,8 +293,9 @@ * @return {!Promise<{content: string, map: !Formatter.FormatterSourceMapping}>} */ _requestFormattedContent() { - if (this._formattedContentPromise) + if (this._formattedContentPromise) { return this._formattedContentPromise; + } let fulfill; this._formattedContentPromise = new Promise(x => fulfill = x); new Formatter.ScriptFormatter(this._highlighterType, this._rawContent || '', (content, map) => { @@ -307,11 +317,13 @@ } _innerRevealPositionIfNeeded() { - if (!this._positionToReveal) + if (!this._positionToReveal) { return; + } - if (!this.loaded || !this.isShowing()) + if (!this.loaded || !this.isShowing()) { return; + } const [line, column] = this._transformer.rawToEditorLocation(this._positionToReveal.line, this._positionToReveal.column); @@ -378,12 +390,14 @@ onTextChanged(oldRange, newRange) { const wasPretty = this.pretty; this._pretty = this._prettyCleanGeneration !== null && this.textEditor.isClean(this._prettyCleanGeneration); - if (this._pretty !== wasPretty) + if (this._pretty !== wasPretty) { this._updatePrettyPrintState(); + } this._prettyToggle.setEnabled(this.isClean()); - if (this._searchConfig && this._searchableView) + if (this._searchConfig && this._searchableView) { this.performSearch(this._searchConfig, false, false); + } } /** @@ -413,18 +427,23 @@ * @return {string} */ _simplifyMimeType(content, mimeType) { - if (!mimeType) + if (!mimeType) { return ''; + } // There are plenty of instances where TSX/JSX files are served with out the trailing x, i.e. JSX with a 'js' suffix // which breaks the formatting. Therefore, if the mime type is TypeScript or JavaScript, we switch to the TSX/JSX // superset so that we don't break formatting. - if (mimeType.indexOf('typescript') >= 0) + if (mimeType.indexOf('typescript') >= 0) { return 'text/typescript-jsx'; - if (mimeType.indexOf('javascript') >= 0 || mimeType.indexOf('jscript') >= 0 || mimeType.indexOf('ecmascript') >= 0) + } + if (mimeType.indexOf('javascript') >= 0 || mimeType.indexOf('jscript') >= 0 || + mimeType.indexOf('ecmascript') >= 0) { return 'text/jsx'; + } // A hack around the fact that files with "php" extension might be either standalone or html embedded php scripts. - if (mimeType === 'text/x-php' && content.match(/\<\?.*\?\>/g)) + if (mimeType === 'text/x-php' && content.match(/\<\?.*\?\>/g)) { return 'application/x-httpd-php'; + } return mimeType; } @@ -499,17 +518,19 @@ this._searchRegex = regex; this._searchResults = this._collectRegexMatches(regex); - if (this._searchableView) + if (this._searchableView) { this._searchableView.updateSearchMatchesCount(this._searchResults.length); + } - if (!this._searchResults.length) + if (!this._searchResults.length) { this._textEditor.cancelSearchResultsHighlight(); - else if (shouldJump && jumpBackwards) + } else if (shouldJump && jumpBackwards) { this.jumpToPreviousSearchResult(); - else if (shouldJump) + } else if (shouldJump) { this.jumpToNextSearchResult(); - else + } else { this._textEditor.highlightSearchResults(regex, null); + } } /** @@ -519,25 +540,29 @@ * @param {boolean=} jumpBackwards */ performSearch(searchConfig, shouldJump, jumpBackwards) { - if (this._searchableView) + if (this._searchableView) { this._searchableView.updateSearchMatchesCount(0); + } this._resetSearch(); this._searchConfig = searchConfig; - if (this.loaded) + if (this.loaded) { this._doFindSearchMatches(searchConfig, shouldJump, !!jumpBackwards); - else + } else { this._delayedFindSearchMatches = this._doFindSearchMatches.bind(this, searchConfig, shouldJump, !!jumpBackwards); + } this._ensureContentLoaded(); } _resetCurrentSearchResultIndex() { - if (!this._searchResults.length) + if (!this._searchResults.length) { return; + } this._currentSearchResultIndex = -1; - if (this._searchableView) + if (this._searchableView) { this._searchableView.updateCurrentMatchIndex(this._currentSearchResultIndex); + } this._textEditor.highlightSearchResults(/** @type {!RegExp} */ (this._searchRegex), null); } @@ -555,11 +580,13 @@ searchCanceled() { const range = this._currentSearchResultIndex !== -1 ? this._searchResults[this._currentSearchResultIndex] : null; this._resetSearch(); - if (!this.loaded) + if (!this.loaded) { return; + } this._textEditor.cancelSearchResultsHighlight(); - if (range) + if (range) { this.setSelection(range); + } } jumpToLastSearchResult() { @@ -607,11 +634,13 @@ } jumpToSearchResult(index) { - if (!this.loaded || !this._searchResults.length) + if (!this.loaded || !this._searchResults.length) { return; + } this._currentSearchResultIndex = (index + this._searchResults.length) % this._searchResults.length; - if (this._searchableView) + if (this._searchableView) { this._searchableView.updateCurrentMatchIndex(this._currentSearchResultIndex); + } this._textEditor.highlightSearchResults( /** @type {!RegExp} */ (this._searchRegex), this._searchResults[this._currentSearchResultIndex]); } @@ -623,8 +652,9 @@ */ replaceSelectionWith(searchConfig, replacement) { const range = this._searchResults[this._currentSearchResultIndex]; - if (!range) + if (!range) { return; + } this._textEditor.highlightSearchResults(/** @type {!RegExp} */ (this._searchRegex), null); const oldText = this._textEditor.text(range); @@ -663,8 +693,9 @@ } const ranges = this._collectRegexMatches(regex); - if (!ranges.length) + if (!ranges.length) { return; + } // Calculate the position of the end of the last range to be edited. const currentRangeIndex = ranges.lowerBound(this._textEditor.selection(), TextUtils.TextRange.comparator); @@ -694,8 +725,9 @@ match = regexObject.exec(line); if (match) { const matchEndIndex = match.index + Math.max(match[0].length, 1); - if (match[0].length) + if (match[0].length) { ranges.push(new TextUtils.TextRange(i, offset + match.index, i, offset + matchEndIndex)); + } offset += matchEndIndex; line = line.substring(matchEndIndex); } @@ -729,8 +761,9 @@ _updateSourcePosition() { const selections = this._textEditor.selections(); - if (!selections.length) + if (!selections.length) { return; + } if (selections.length > 1) { this._sourcePosition.setText(Common.UIString('%d selection regions', selections.length)); return;
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/SourcesTextEditor.js b/third_party/blink/renderer/devtools/front_end/source_frame/SourcesTextEditor.js index 8b90bcee..fb09994 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/SourcesTextEditor.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/SourcesTextEditor.js
@@ -16,8 +16,9 @@ bracketMatchingSetting: Common.moduleSetting('textEditorBracketMatching'), padBottom: true }; - if (codeMirrorOptions) + if (codeMirrorOptions) { Object.assign(defaultCodeMirrorOptions, codeMirrorOptions); + } super(defaultCodeMirrorOptions); @@ -95,32 +96,39 @@ const indents = {}; for (let lineNumber = 0; lineNumber < lines.length; ++lineNumber) { const text = lines[lineNumber]; - if (text.length === 0 || !TextUtils.TextUtils.isSpaceChar(text[0])) + if (text.length === 0 || !TextUtils.TextUtils.isSpaceChar(text[0])) { continue; + } if (tabRegex.test(text)) { ++tabLines; continue; } let i = 0; - while (i < text.length && TextUtils.TextUtils.isSpaceChar(text[i])) + while (i < text.length && TextUtils.TextUtils.isSpaceChar(text[i])) { ++i; - if (i % 2 !== 0) + } + if (i % 2 !== 0) { continue; + } indents[i] = 1 + (indents[i] || 0); } const linesCountPerIndentThreshold = 3 * lines.length / 100; - if (tabLines && tabLines > linesCountPerIndentThreshold) + if (tabLines && tabLines > linesCountPerIndentThreshold) { return '\t'; + } let minimumIndent = Infinity; for (const i in indents) { - if (indents[i] < linesCountPerIndentThreshold) + if (indents[i] < linesCountPerIndentThreshold) { continue; + } const indent = parseInt(i, 10); - if (minimumIndent > indent) + if (minimumIndent > indent) { minimumIndent = indent; + } } - if (minimumIndent === Infinity) + if (minimumIndent === Infinity) { return Common.moduleSetting('textEditorIndent').get(); + } return ' '.repeat(minimumIndent); } @@ -151,16 +159,18 @@ function innerHighlightRegex() { if (range) { this.scrollLineIntoView(range.startLine); - if (range.endColumn > TextEditor.CodeMirrorTextEditor.maxHighlightLength) + if (range.endColumn > TextEditor.CodeMirrorTextEditor.maxHighlightLength) { this.setSelection(range); - else + } else { this.setSelection(TextUtils.TextRange.createFromLocation(range.startLine, range.startColumn)); + } } this._tokenHighlighter.highlightSearchResults(regex, range); } - if (!this._selectionBeforeSearch) + if (!this._selectionBeforeSearch) { this._selectionBeforeSearch = this.selection(); + } this.codeMirror().operation(innerHighlightRegex.bind(this)); } @@ -199,13 +209,15 @@ * @param {boolean} leftToNumbers */ installGutter(type, leftToNumbers) { - if (this._gutters.indexOf(type) !== -1) + if (this._gutters.indexOf(type) !== -1) { return; + } - if (leftToNumbers) + if (leftToNumbers) { this._gutters.unshift(type); - else + } else { this._gutters.push(type); + } this.codeMirror().setOption('gutters', this._gutters.slice()); this.refresh(); @@ -216,8 +228,9 @@ */ uninstallGutter(type) { const index = this._gutters.indexOf(type); - if (index === -1) + if (index === -1) { return; + } this.codeMirror().clearGutter(type); this._gutters.splice(index, 1); this.codeMirror().setOption('gutters', this._gutters.slice()); @@ -242,8 +255,9 @@ this.clearPositionHighlight(); this._executionLine = this.codeMirror().getLineHandle(lineNumber); - if (!this._executionLine) + if (!this._executionLine) { return; + } this.showExecutionLineBackground(); this.codeMirror().addLineClass(this._executionLine, 'wrap', 'cm-execution-line-outline'); @@ -251,28 +265,32 @@ if (token && !token.type && token.startColumn + 1 === token.endColumn) { const tokenContent = this.codeMirror().getLine(lineNumber)[token.startColumn]; - if (tokenContent === '.' || tokenContent === '(') + if (tokenContent === '.' || tokenContent === '(') { token = this.tokenAtTextPosition(lineNumber, token.endColumn + 1); + } } let endColumn; - if (token && token.type) + if (token && token.type) { endColumn = token.endColumn; - else + } else { endColumn = this.codeMirror().getLine(lineNumber).length; + } this._executionLineTailMarker = this.codeMirror().markText( {line: lineNumber, ch: columnNumber}, {line: lineNumber, ch: endColumn}, {className: 'cm-execution-line-tail'}); } showExecutionLineBackground() { - if (this._executionLine) + if (this._executionLine) { this.codeMirror().addLineClass(this._executionLine, 'wrap', 'cm-execution-line'); + } } hideExecutionLineBackground() { - if (this._executionLine) + if (this._executionLine) { this.codeMirror().removeLineClass(this._executionLine, 'wrap', 'cm-execution-line'); + } } clearExecutionLine() { @@ -284,8 +302,9 @@ } delete this._executionLine; - if (this._executionLineTailMarker) + if (this._executionLineTailMarker) { this._executionLineTailMarker.clear(); + } delete this._executionLineTailMarker; } @@ -295,12 +314,14 @@ * @param {boolean} toggled */ toggleLineClass(lineNumber, className, toggled) { - if (this.hasLineClass(lineNumber, className) === toggled) + if (this.hasLineClass(lineNumber, className) === toggled) { return; + } const lineHandle = this.codeMirror().getLineHandle(lineNumber); - if (!lineHandle) + if (!lineHandle) { return; + } if (toggled) { this.codeMirror().addLineClass(lineHandle, 'gutter', className); @@ -360,8 +381,9 @@ */ editRange(range, text, origin) { const newRange = super.editRange(range, text, origin); - if (Common.moduleSetting('textEditorAutoDetectIndent').get()) + if (Common.moduleSetting('textEditorAutoDetectIndent').get()) { this._onUpdateEditorIndentation(); + } return newRange; } @@ -377,8 +399,9 @@ _setEditorIndentation(lines) { const extraKeys = {}; let indent = Common.moduleSetting('textEditorIndent').get(); - if (Common.moduleSetting('textEditorAutoDetectIndent').get()) + if (Common.moduleSetting('textEditorAutoDetectIndent').get()) { indent = SourceFrame.SourcesTextEditor._guessIndentationLevel(lines); + } if (indent === TextUtils.TextUtils.Indent.TabCharacter) { this.codeMirror().setOption('indentWithTabs', true); @@ -387,8 +410,9 @@ this.codeMirror().setOption('indentWithTabs', false); this.codeMirror().setOption('indentUnit', indent.length); extraKeys.Tab = function(codeMirror) { - if (codeMirror.somethingSelected()) + if (codeMirror.somethingSelected()) { return CodeMirror.Pass; + } const pos = codeMirror.getCursor('head'); codeMirror.replaceRange(indent.substring(pos.ch % indent.length), codeMirror.getCursor()); }; @@ -410,8 +434,9 @@ for (let i = 0; i < this._autoAppendedSpaces.length; ++i) { const position = this._autoAppendedSpaces[i].resolve(); - if (!position) + if (!position) { continue; + } const line = this.line(position.lineNumber); if (line.length === position.columnNumber && TextUtils.TextUtils.lineIndent(line).length === line.length) { this.codeMirror().replaceRange( @@ -429,8 +454,9 @@ } _cursorActivity() { - if (!this._isSearchActive()) + if (!this._isSearchActive()) { this.codeMirror().operation(this._tokenHighlighter.highlightSelectedTokens.bind(this._tokenHighlighter)); + } const start = this.codeMirror().getCursor('anchor'); const end = this.codeMirror().getCursor('head'); @@ -443,8 +469,9 @@ * @param {?TextUtils.TextRange} to */ _reportJump(from, to) { - if (from && to && from.equal(to)) + if (from && to && from.equal(to)) { return; + } this.dispatchEventToListeners(SourceFrame.SourcesTextEditor.Events.JumpHappened, {from: from, to: to}); } @@ -466,10 +493,12 @@ * @param {{ranges: !Array.<{head: !CodeMirror.Pos, anchor: !CodeMirror.Pos}>}} selection */ _fireBeforeSelectionChanged(codeMirror, selection) { - if (!this._isHandlingMouseDownEvent) + if (!this._isHandlingMouseDownEvent) { return; - if (!selection.ranges.length) + } + if (!selection.ranges.length) { return; + } const primarySelection = selection.ranges[0]; this._reportJump( @@ -527,10 +556,11 @@ const whitespaceMode = Common.moduleSetting('showWhitespacesInEditor').get(); this.element.classList.toggle('show-whitespaces', whitespaceMode === 'all'); - if (whitespaceMode === 'all') + if (whitespaceMode === 'all') { return this._allWhitespaceOverlayMode(mimeType); - else if (whitespaceMode === 'trailing') + } else if (whitespaceMode === 'trailing') { return this._trailingWhitespaceOverlayMode(mimeType); + } return mimeType; } @@ -544,8 +574,9 @@ (CodeMirror.mimeModes[mimeType].name || CodeMirror.mimeModes[mimeType]) : CodeMirror.mimeModes['text/plain']; modeName += '+all-whitespaces'; - if (CodeMirror.modes[modeName]) + if (CodeMirror.modes[modeName]) { return modeName; + } function modeConstructor(config, parserConfig) { function nextToken(stream) { @@ -558,8 +589,9 @@ } return 'whitespace whitespace-' + spaces; } - while (!stream.eol() && stream.peek() !== ' ') + while (!stream.eol() && stream.peek() !== ' ') { stream.next(); + } return null; } const whitespaceMode = {token: nextToken}; @@ -578,16 +610,18 @@ (CodeMirror.mimeModes[mimeType].name || CodeMirror.mimeModes[mimeType]) : CodeMirror.mimeModes['text/plain']; modeName += '+trailing-whitespaces'; - if (CodeMirror.modes[modeName]) + if (CodeMirror.modes[modeName]) { return modeName; + } function modeConstructor(config, parserConfig) { function nextToken(stream) { - if (stream.match(/^\s+$/, true)) + if (stream.match(/^\s+$/, true)) { return true ? 'trailing-whitespace' : null; - do + } + do { stream.next(); - while (!stream.eol() && stream.peek() !== ' '); + } while (!stream.eol() && stream.peek() !== ' '); return null; } const whitespaceMode = {token: nextToken}; @@ -599,8 +633,9 @@ _setupWhitespaceHighlight() { const doc = this.element.ownerDocument; - if (doc._codeMirrorWhitespaceStyleInjected || !Common.moduleSetting('showWhitespacesInEditor').get()) + if (doc._codeMirrorWhitespaceStyleInjected || !Common.moduleSetting('showWhitespacesInEditor').get()) { return; + } doc._codeMirrorWhitespaceStyleInjected = true; const classBase = '.show-whitespaces .CodeMirror .cm-whitespace-'; const spaceChar = '·'; @@ -689,8 +724,9 @@ * @return {!Object|undefined} */ CodeMirror.commands.sourcesDismiss = function(codemirror) { - if (codemirror.listSelections().length === 1 && codemirror._codeMirrorTextEditor._isSearchActive()) + if (codemirror.listSelections().length === 1 && codemirror._codeMirrorTextEditor._isSearchActive()) { return CodeMirror.Pass; + } return CodeMirror.commands.dismiss(codemirror); }; @@ -711,16 +747,18 @@ const indent = TextUtils.TextUtils.lineIndent(line); let indentToInsert = '\n' + indent + codeMirror._codeMirrorTextEditor.indent(); let isCollapsedBlock = false; - if (selection.head.ch === 0) + if (selection.head.ch === 0) { return CodeMirror.Pass; + } if (line.substr(selection.head.ch - 1, 2) === '{}') { indentToInsert += '\n' + indent; isCollapsedBlock = true; } else if (line.substr(selection.head.ch - 1, 1) !== '{') { return CodeMirror.Pass; } - if (i > 0 && allSelectionsAreCollapsedBlocks !== isCollapsedBlock) + if (i > 0 && allSelectionsAreCollapsedBlocks !== isCollapsedBlock) { return CodeMirror.Pass; + } replacements.push(indentToInsert); allSelectionsAreCollapsedBlocks = isCollapsedBlock; } @@ -745,15 +783,17 @@ * @return {*} */ '\'}\'': function(codeMirror) { - if (codeMirror.somethingSelected()) + if (codeMirror.somethingSelected()) { return CodeMirror.Pass; + } let selections = codeMirror.listSelections(); let replacements = []; for (let i = 0; i < selections.length; ++i) { const selection = selections[i]; const line = codeMirror.getLine(selection.head.line); - if (line !== TextUtils.TextUtils.lineIndent(line)) + if (line !== TextUtils.TextUtils.lineIndent(line)) { return CodeMirror.Pass; + } replacements.push('}'); } codeMirror.replaceSelections(replacements); @@ -763,8 +803,9 @@ for (let i = 0; i < selections.length; ++i) { const selection = selections[i]; const matchingBracket = codeMirror.findMatchingBracket(selection.head); - if (!matchingBracket || !matchingBracket.match) + if (!matchingBracket || !matchingBracket.match) { return; + } updatedSelections.push({head: selection.head, anchor: new CodeMirror.Pos(selection.head.line, 0)}); const line = codeMirror.getLine(matchingBracket.to.line); const indent = TextUtils.TextUtils.lineIndent(line); @@ -801,17 +842,20 @@ this._searchResultMarker.clear(); delete this._searchResultMarker; } - if (this._highlightDescriptor && this._highlightDescriptor.selectionStart) + if (this._highlightDescriptor && this._highlightDescriptor.selectionStart) { this._codeMirror.removeLineClass(this._highlightDescriptor.selectionStart.line, 'wrap', 'cm-line-with-selection'); + } const selectionStart = this._highlightRange ? new CodeMirror.Pos(this._highlightRange.startLine, this._highlightRange.startColumn) : null; - if (selectionStart) + if (selectionStart) { this._codeMirror.addLineClass(selectionStart.line, 'wrap', 'cm-line-with-selection'); + } if (oldRegex && this._highlightRegex.toString() === oldRegex.toString()) { // Do not re-add overlay mode if regex did not change for better performance. - if (this._highlightDescriptor) + if (this._highlightDescriptor) { this._highlightDescriptor.selectionStart = selectionStart; + } } else { this._removeHighlight(); this._setHighlighter(this._searchHighlighter.bind(this, this._highlightRegex), selectionStart); @@ -832,22 +876,27 @@ highlightSelectedTokens() { delete this._highlightRegex; delete this._highlightRange; - if (this._highlightDescriptor && this._highlightDescriptor.selectionStart) + if (this._highlightDescriptor && this._highlightDescriptor.selectionStart) { this._codeMirror.removeLineClass(this._highlightDescriptor.selectionStart.line, 'wrap', 'cm-line-with-selection'); + } this._removeHighlight(); const selectionStart = this._codeMirror.getCursor('start'); const selectionEnd = this._codeMirror.getCursor('end'); - if (selectionStart.line !== selectionEnd.line) + if (selectionStart.line !== selectionEnd.line) { return; - if (selectionStart.ch === selectionEnd.ch) + } + if (selectionStart.ch === selectionEnd.ch) { return; + } const selections = this._codeMirror.getSelections(); - if (selections.length > 1) + if (selections.length > 1) { return; + } const selectedText = selections[0]; if (this._isWord(selectedText, selectionStart.line, selectionStart.ch, selectionEnd.ch)) { - if (selectionStart) + if (selectionStart) { this._codeMirror.addLineClass(selectionStart.line, 'wrap', 'cm-line-with-selection'); + } this._setHighlighter(this._tokenHighlighter.bind(this, selectedText, selectionStart), selectionStart); } } @@ -877,12 +926,14 @@ * @param {!CodeMirror.StringStream} stream */ _searchHighlighter(regex, stream) { - if (stream.column() === 0) + if (stream.column() === 0) { delete this._searchMatchLength; + } if (this._searchMatchLength) { if (this._searchMatchLength > 2) { - for (let i = 0; i < this._searchMatchLength - 2; ++i) + for (let i = 0; i < this._searchMatchLength - 2; ++i) { stream.next(); + } this._searchMatchLength = 1; return 'search-highlight'; } else { @@ -895,8 +946,9 @@ if (match) { stream.next(); const matchLength = match[0].length; - if (matchLength === 1) + if (matchLength === 1) { return 'search-highlight search-highlight-full'; + } this._searchMatchLength = matchLength; return 'search-highlight search-highlight-start'; } @@ -911,12 +963,13 @@ */ _tokenHighlighter(token, selectionStart, stream) { const tokenFirstChar = token.charAt(0); - if (stream.match(token) && (stream.eol() || !TextUtils.TextUtils.isWordChar(stream.peek()))) + if (stream.match(token) && (stream.eol() || !TextUtils.TextUtils.isWordChar(stream.peek()))) { return stream.column() === selectionStart.ch ? 'token-highlight column-with-selection' : 'token-highlight'; + } let eatenChar; - do + do { eatenChar = stream.next(); - while (eatenChar && (TextUtils.TextUtils.isWordChar(eatenChar) || stream.peek() !== tokenFirstChar)); + } while (eatenChar && (TextUtils.TextUtils.isWordChar(eatenChar) || stream.peek() !== tokenFirstChar)); } /**
diff --git a/third_party/blink/renderer/devtools/front_end/source_frame/XMLView.js b/third_party/blink/renderer/devtools/front_end/source_frame/XMLView.js index 8af5c23..f82d39f 100644 --- a/third_party/blink/renderer/devtools/front_end/source_frame/XMLView.js +++ b/third_party/blink/renderer/devtools/front_end/source_frame/XMLView.js
@@ -55,8 +55,9 @@ } catch (e) { return null; } - if (parsedXML.body) + if (parsedXML.body) { return null; + } return parsedXML; } @@ -65,18 +66,21 @@ * @param {boolean} shouldJump */ _jumpToMatch(index, shouldJump) { - if (!this._searchConfig) + if (!this._searchConfig) { return; + } const regex = this._searchConfig.toSearchRegex(true); const previousFocusElement = this._currentSearchTreeElements[this._currentSearchFocusIndex]; - if (previousFocusElement) + if (previousFocusElement) { previousFocusElement.setSearchRegex(regex); + } const newFocusElement = this._currentSearchTreeElements[index]; if (newFocusElement) { this._updateSearchIndex(index); - if (shouldJump) + if (shouldJump) { newFocusElement.reveal(true); + } newFocusElement.setSearchRegex(regex, UI.highlightedCurrentSearchResultClassName); } else { this._updateSearchIndex(0); @@ -87,8 +91,9 @@ * @param {number} count */ _updateSearchCount(count) { - if (!this._searchableView) + if (!this._searchableView) { return; + } this._searchableView.updateSearchMatchesCount(count); } @@ -97,8 +102,9 @@ */ _updateSearchIndex(index) { this._currentSearchFocusIndex = index; - if (!this._searchableView) + if (!this._searchableView) { return; + } this._searchableView.updateCurrentMatchIndex(index); } @@ -107,8 +113,9 @@ * @param {boolean=} jumpBackwards */ _innerPerformSearch(shouldJump, jumpBackwards) { - if (!this._searchConfig) + if (!this._searchConfig) { return; + } let newIndex = this._currentSearchFocusIndex; const previousSearchFocusElement = this._currentSearchTreeElements[newIndex]; this._innerSearchCanceled(); @@ -116,17 +123,20 @@ const regex = this._searchConfig.toSearchRegex(true); for (let element = this._treeOutline.rootElement(); element; element = element.traverseNextTreeElement(false)) { - if (!(element instanceof SourceFrame.XMLView.Node)) + if (!(element instanceof SourceFrame.XMLView.Node)) { continue; + } const hasMatch = element.setSearchRegex(regex); - if (hasMatch) + if (hasMatch) { this._currentSearchTreeElements.push(element); + } if (previousSearchFocusElement === element) { const currentIndex = this._currentSearchTreeElements.length - 1; - if (hasMatch || jumpBackwards) + if (hasMatch || jumpBackwards) { newIndex = currentIndex; - else + } else { newIndex = currentIndex + 1; + } } } this._updateSearchCount(this._currentSearchTreeElements.length); @@ -142,8 +152,9 @@ _innerSearchCanceled() { for (let element = this._treeOutline.rootElement(); element; element = element.traverseNextTreeElement(false)) { - if (!(element instanceof SourceFrame.XMLView.Node)) + if (!(element instanceof SourceFrame.XMLView.Node)) { continue; + } element.revertHighlightChanges(); } this._updateSearchCount(0); @@ -174,8 +185,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._currentSearchTreeElements.length) + if (!this._currentSearchTreeElements.length) { return; + } const newIndex = mod(this._currentSearchFocusIndex + 1, this._currentSearchTreeElements.length); this._jumpToMatch(newIndex, true); @@ -185,8 +197,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._currentSearchTreeElements.length) + if (!this._currentSearchTreeElements.length) { return; + } const newIndex = mod(this._currentSearchFocusIndex - 1, this._currentSearchTreeElements.length); this._jumpToMatch(newIndex, true); @@ -242,11 +255,13 @@ node = node.nextSibling; const nodeType = currentNode.nodeType; // ignore empty TEXT - if (nodeType === 3 && currentNode.nodeValue.match(/\s+/)) + if (nodeType === 3 && currentNode.nodeValue.match(/\s+/)) { continue; + } // ignore ATTRIBUTE, ENTITY_REFERENCE, ENTITY, DOCUMENT, DOCUMENT_TYPE, DOCUMENT_FRAGMENT, NOTATION - if ((nodeType !== 1) && (nodeType !== 3) && (nodeType !== 4) && (nodeType !== 7) && (nodeType !== 8)) + if ((nodeType !== 1) && (nodeType !== 3) && (nodeType !== 4) && (nodeType !== 7) && (nodeType !== 8)) { continue; + } root.appendChild(new SourceFrame.XMLView.Node(currentNode, false, xmlView)); } } @@ -258,14 +273,17 @@ */ setSearchRegex(regex, additionalCssClassName) { this.revertHighlightChanges(); - if (!regex) + if (!regex) { return false; - if (this._closeTag && this.parent && !this.parent.expanded) + } + if (this._closeTag && this.parent && !this.parent.expanded) { return false; + } regex.lastIndex = 0; let cssClasses = UI.highlightedSearchResultClassName; - if (additionalCssClassName) + if (additionalCssClassName) { cssClasses += ' ' + additionalCssClassName; + } const content = this.listItemElement.textContent.replace(/\xA0/g, ' '); let match = regex.exec(content); const ranges = []; @@ -273,8 +291,9 @@ ranges.push(new TextUtils.SourceRange(match.index, match[0].length)); match = regex.exec(content); } - if (ranges.length) + if (ranges.length) { UI.highlightRangesWithStyleClass(this.listItemElement, ranges, cssClasses, this._highlightChanges); + } return !!this._highlightChanges.length; } @@ -338,8 +357,9 @@ */ _setTitle(items) { const titleFragment = createDocumentFragment(); - for (let i = 0; i < items.length; i += 2) + for (let i = 0; i < items.length; i += 2) { titleFragment.createChild('span', items[i + 1]).textContent = items[i]; + } this.title = titleFragment; this._xmlView._innerPerformSearch(false, false); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js b/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js index f675a4b..0e5128a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js +++ b/third_party/blink/renderer/devtools/front_end/sources/BreakpointEditDialog.js
@@ -23,8 +23,9 @@ const logpointPrefix = Sources.BreakpointEditDialog.LogpointPrefix; const logpointSuffix = Sources.BreakpointEditDialog._LogpointSuffix; this._isLogpoint = oldCondition.startsWith(logpointPrefix) && oldCondition.endsWith(logpointSuffix); - if (this._isLogpoint) + if (this._isLogpoint) { oldCondition = oldCondition.substring(logpointPrefix.length, oldCondition.length - logpointSuffix.length); + } this._isLogpoint = this._isLogpoint || preferLogpoint; this.element.classList.add('sources-edit-breakpoint-dialog'); @@ -46,16 +47,18 @@ this._updatePlaceholder(); this._editor.widget().element.classList.add('condition-editor'); this._editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor)); - if (oldCondition) + if (oldCondition) { this._editor.setText(oldCondition); + } this._editor.widget().markAsExternallyManaged(); this._editor.widget().show(this.contentElement); this._editor.setSelection(this._editor.fullRange()); this._editor.widget().focus(); this._editor.widget().element.addEventListener('keydown', this._onKeyDown.bind(this), true); this.contentElement.addEventListener('blur', event => { - if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this.element)) + if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this.element)) { this._finishEditing(true); + } }, true); }); } @@ -93,13 +96,15 @@ * @param {boolean} committed */ _finishEditing(committed) { - if (this._finished) + if (this._finished) { return; + } this._finished = true; this._editor.widget().detach(); let condition = this._editor.text(); - if (this._isLogpoint) + if (this._isLogpoint) { condition = Sources.BreakpointEditDialog._conditionForLogpoint(condition); + } this._onFinish({committed, condition}); } @@ -110,13 +115,15 @@ if (isEnterKey(event) && !event.shiftKey) { event.consume(true); const expression = this._editor.text(); - if (event.ctrlKey || await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression)) + if (event.ctrlKey || await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression)) { this._finishEditing(true); - else + } else { this._editor.newlineAndIndent(); + } } - if (isEscKey(event)) + if (isEscKey(event)) { this._finishEditing(false); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/CSSPlugin.js b/third_party/blink/renderer/devtools/front_end/sources/CSSPlugin.js index fea8b45..3dcbb65 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/CSSPlugin.js +++ b/third_party/blink/renderer/devtools/front_end/sources/CSSPlugin.js
@@ -70,14 +70,18 @@ _registerShortcuts() { const shortcutKeys = UI.ShortcutsScreen.SourcesPanelShortcuts; - for (const descriptor of shortcutKeys.IncreaseCSSUnitByOne) + for (const descriptor of shortcutKeys.IncreaseCSSUnitByOne) { this._shortcuts[descriptor.key] = this._handleUnitModification.bind(this, 1); - for (const descriptor of shortcutKeys.DecreaseCSSUnitByOne) + } + for (const descriptor of shortcutKeys.DecreaseCSSUnitByOne) { this._shortcuts[descriptor.key] = this._handleUnitModification.bind(this, -1); - for (const descriptor of shortcutKeys.IncreaseCSSUnitByTen) + } + for (const descriptor of shortcutKeys.IncreaseCSSUnitByTen) { this._shortcuts[descriptor.key] = this._handleUnitModification.bind(this, 10); - for (const descriptor of shortcutKeys.DecreaseCSSUnitByTen) + } + for (const descriptor of shortcutKeys.DecreaseCSSUnitByTen) { this._shortcuts[descriptor.key] = this._handleUnitModification.bind(this, -10); + } } /** @@ -86,13 +90,15 @@ _handleKeyDown(event) { const shortcutKey = UI.KeyboardShortcut.makeKeyFromEvent(/** @type {!KeyboardEvent} */ (event)); const handler = this._shortcuts[shortcutKey]; - if (handler && handler()) + if (handler && handler()) { event.consume(true); + } } _textEditorScrolled() { - if (this._swatchPopoverHelper.isShowing()) + if (this._swatchPopoverHelper.isShowing()) { this._swatchPopoverHelper.hide(true); + } } /** @@ -102,8 +108,9 @@ */ _modifyUnit(unit, change) { const unitValue = parseInt(unit, 10); - if (isNaN(unitValue)) + if (isNaN(unitValue)) { return null; + } const tail = unit.substring((unitValue).toString().length); return String.sprintf('%d%s', unitValue + change, tail); } @@ -116,20 +123,24 @@ const selection = this._textEditor.selection().normalize(); let token = this._textEditor.tokenAtTextPosition(selection.startLine, selection.startColumn); if (!token) { - if (selection.startColumn > 0) + if (selection.startColumn > 0) { token = this._textEditor.tokenAtTextPosition(selection.startLine, selection.startColumn - 1); - if (!token) + } + if (!token) { return false; + } } - if (token.type !== 'css-number') + if (token.type !== 'css-number') { return false; + } const cssUnitRange = new TextUtils.TextRange(selection.startLine, token.startColumn, selection.startLine, token.endColumn); const cssUnitText = this._textEditor.text(cssUnitRange); const newUnitText = this._modifyUnit(cssUnitText, change); - if (!newUnitText) + if (!newUnitText) { return false; + } this._textEditor.editRange(cssUnitRange, newUnitText); selection.startColumn = token.startColumn; selection.endColumn = selection.startColumn + newUnitText.length; @@ -156,17 +167,20 @@ const results = TextUtils.TextUtils.splitStringByRegexes(line, regexes); for (let i = 0; i < results.length; i++) { const result = results[i]; - if (result.regexIndex === -1 || !handlers.has(regexes[result.regexIndex])) + if (result.regexIndex === -1 || !handlers.has(regexes[result.regexIndex])) { continue; + } const delimiters = /[\s:;,(){}]/; const positionBefore = result.position - 1; const positionAfter = result.position + result.value.length; if (positionBefore >= 0 && !delimiters.test(line.charAt(positionBefore)) || - positionAfter < line.length && !delimiters.test(line.charAt(positionAfter))) + positionAfter < line.length && !delimiters.test(line.charAt(positionAfter))) { continue; + } const swatch = handlers.get(regexes[result.regexIndex])(result.value); - if (!swatch) + if (!swatch) { continue; + } swatches.push(swatch); swatchPositions.push(TextUtils.TextRange.createFromLocation(lineNumber, result.position)); } @@ -196,8 +210,9 @@ */ _createColorSwatch(text) { const color = Common.Color.parse(text); - if (!color) + if (!color) { return null; + } const swatch = InlineEditor.ColorSwatch.create(); swatch.setColor(color); swatch.iconElement().title = Common.UIString('Open color picker.'); @@ -211,8 +226,9 @@ * @return {?InlineEditor.BezierSwatch} */ _createBezierSwatch(text) { - if (!UI.Geometry.CubicBezier.parse(text)) + if (!UI.Geometry.CubicBezier.parse(text)) { return null; + } const swatch = InlineEditor.BezierSwatch.create(); swatch.setBezierText(text); swatch.iconElement().title = Common.UIString('Open cubic bezier editor.'); @@ -235,10 +251,11 @@ this._editedSwatchTextRange.endColumn += swatch.textContent.length; this._currentSwatch = swatch; - if (swatch instanceof InlineEditor.ColorSwatch) + if (swatch instanceof InlineEditor.ColorSwatch) { this._showSpectrum(swatch); - else if (swatch instanceof InlineEditor.BezierSwatch) + } else if (swatch instanceof InlineEditor.BezierSwatch) { this._showBezierEditor(swatch); + } } /** @@ -267,8 +284,9 @@ _spectrumChanged(event) { const colorString = /** @type {string} */ (event.data); const color = Common.Color.parse(colorString); - if (!color) + if (!color) { return; + } this._currentSwatch.setColor(color); this._changeSwatchText(colorString); } @@ -314,16 +332,18 @@ */ _swatchPopoverHidden(commitEdit) { this._muteSwatchProcessing = false; - if (!commitEdit && this._hadSwatchChange) + if (!commitEdit && this._hadSwatchChange) { this._textEditor.undo(); + } } /** * @param {!Common.Event} event */ _onTextChanged(event) { - if (!this._muteSwatchProcessing) + if (!this._muteSwatchProcessing) { this._updateSwatches(event.data.newRange.startLine, event.data.newRange.endLine); + } } /** @@ -341,12 +361,14 @@ */ _cssSuggestions(prefixRange, substituteRange) { const prefix = this._textEditor.text(prefixRange); - if (prefix.startsWith('$')) + if (prefix.startsWith('$')) { return null; + } const propertyToken = this._backtrackPropertyToken(prefixRange.startLine, prefixRange.startColumn - 1); - if (!propertyToken) + if (!propertyToken) { return null; + } const line = this._textEditor.line(prefixRange.startLine); const tokenContent = line.substring(propertyToken.startColumn, propertyToken.endColumn); @@ -367,18 +389,22 @@ for (let i = 0; i < backtrackDepth && tokenPosition >= 0; ++i) { const token = this._textEditor.tokenAtTextPosition(lineNumber, tokenPosition); - if (!token) + if (!token) { return null; - if (token.type === 'css-property') + } + if (token.type === 'css-property') { return seenColon ? token : null; - if (token.type && !(token.type.indexOf('whitespace') !== -1 || token.type.startsWith('css-comment'))) + } + if (token.type && !(token.type.indexOf('whitespace') !== -1 || token.type.startsWith('css-comment'))) { return null; + } if (!token.type && line.substring(token.startColumn, token.endColumn) === ':') { - if (!seenColon) + if (!seenColon) { seenColon = true; - else + } else { return null; + } } tokenPosition = token.startColumn - 1; } @@ -389,8 +415,9 @@ * @override */ dispose() { - if (this._swatchPopoverHelper.isShowing()) + if (this._swatchPopoverHelper.isShowing()) { this._swatchPopoverHelper.hide(true); + } this._textEditor.removeEventListener( SourceFrame.SourcesTextEditor.Events.ScrollChanged, this._textEditorScrolled, this); this._textEditor.removeEventListener(UI.TextEditor.Events.TextChanged, this._onTextChanged, this);
diff --git a/third_party/blink/renderer/devtools/front_end/sources/CallStackSidebarPane.js b/third_party/blink/renderer/devtools/front_end/sources/CallStackSidebarPane.js index c0285a1c..f0ae060 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/CallStackSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/sources/CallStackSidebarPane.js
@@ -104,8 +104,9 @@ let asyncStackTrace = details.asyncStackTrace; if (!asyncStackTrace && details.asyncStackTraceId) { - if (details.asyncStackTraceId.debuggerId) + if (details.asyncStackTraceId.debuggerId) { debuggerModel = SDK.DebuggerModel.modelForDebuggerId(details.asyncStackTraceId.debuggerId); + } asyncStackTrace = debuggerModel ? await debuggerModel.fetchAsyncStackTrace(details.asyncStackTraceId) : null; } let peviousStackTrace = details.callFrames; @@ -129,8 +130,9 @@ if (asyncStackTrace.parent) { asyncStackTrace = asyncStackTrace.parent; } else if (asyncStackTrace.parentId) { - if (asyncStackTrace.parentId.debuggerId) + if (asyncStackTrace.parentId.debuggerId) { debuggerModel = SDK.DebuggerModel.modelForDebuggerId(asyncStackTrace.parentId.debuggerId); + } asyncStackTrace = debuggerModel ? await debuggerModel.fetchAsyncStackTrace(asyncStackTrace.parentId) : null; } else { asyncStackTrace = null; @@ -138,8 +140,9 @@ } this._showMoreMessageElement.classList.toggle('hidden', !asyncStackTrace); this._items.replaceAll(items); - if (this._maxAsyncStackChainDepth === Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth) + if (this._maxAsyncStackChainDepth === Sources.CallStackSidebarPane._defaultMaxAsyncStackChainDepth) { this._list.selectNextItem(true /* canWrap */, false /* center */); + } this._updatedForTest(); } @@ -164,16 +167,18 @@ this._muteActivateItem = true; if (!this._showBlackboxed && this._items.every(item => item.isBlackboxed)) { this._showBlackboxed = true; - for (let i = 0; i < this._items.length; ++i) + for (let i = 0; i < this._items.length; ++i) { this._list.refreshItemByIndex(i); + } this._blackboxedMessageElement.classList.toggle('hidden', true); } else { const itemsSet = new Set(items); let hasBlackboxed = false; for (let i = 0; i < this._items.length; ++i) { const item = this._items.at(i); - if (itemsSet.has(item)) + if (itemsSet.has(item)) { this._list.refreshItemByIndex(i); + } hasBlackboxed = hasBlackboxed || item.isBlackboxed; } this._blackboxedMessageElement.classList.toggle('hidden', this._showBlackboxed || !hasBlackboxed); @@ -232,12 +237,15 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected'); - if (toElement) + } + if (toElement) { toElement.classList.add('selected'); - if (to) + } + if (to) { this._activateItem(to); + } } /** @@ -250,8 +258,9 @@ showAllLink.textContent = Common.UIString('Show blackboxed frames'); showAllLink.addEventListener('click', () => { this._showBlackboxed = true; - for (const item of this._items) + for (const item of this._items) { this._refreshItem(item); + } this._blackboxedMessageElement.classList.toggle('hidden', true); }); return element; @@ -277,15 +286,18 @@ */ _onContextMenu(event) { const item = this._list.itemForNode(/** @type {?Node} */ (event.target)); - if (!item) + if (!item) { return; + } const contextMenu = new UI.ContextMenu(event); const debuggerCallFrame = item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol]; - if (debuggerCallFrame) + if (debuggerCallFrame) { contextMenu.defaultSection().appendItem(Common.UIString('Restart frame'), () => debuggerCallFrame.restart()); + } contextMenu.defaultSection().appendItem(Common.UIString('Copy stack trace'), this._copyStackTrace.bind(this)); - if (item.uiLocation) + if (item.uiLocation) { this.appendBlackboxURLContextMenuItems(contextMenu, item.uiLocation.uiSourceCode); + } contextMenu.show(); } @@ -294,8 +306,9 @@ */ _onClick(event) { const item = this._list.itemForNode(/** @type {?Node} */ (event.target)); - if (item) + if (item) { this._activateItem(item); + } } /** @@ -303,8 +316,9 @@ */ _activateItem(item) { const uiLocation = item.uiLocation; - if (this._muteActivateItem || !uiLocation) + if (this._muteActivateItem || !uiLocation) { return; + } const debuggerCallFrame = item[Sources.CallStackSidebarPane._debuggerCallFrameSymbol]; if (debuggerCallFrame && UI.context.flavor(SDK.DebuggerModel.CallFrame) !== debuggerCallFrame) { debuggerCallFrame.debuggerModel.setSelectedCallFrame(debuggerCallFrame); @@ -320,10 +334,12 @@ */ appendBlackboxURLContextMenuItems(contextMenu, uiSourceCode) { const binding = Persistence.persistence.binding(uiSourceCode); - if (binding) + if (binding) { uiSourceCode = binding.network; - if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) + } + if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) { return; + } const canBlackbox = Bindings.blackboxManager.canBlackboxUISourceCode(uiSourceCode); const isBlackboxed = Bindings.blackboxManager.isBlackboxedUISourceCode(uiSourceCode); const isContentScript = uiSourceCode.project().type() === Workspace.projectTypes.ContentScripts; @@ -367,8 +383,9 @@ const text = []; for (const item of this._items) { let itemText = item.title; - if (item.uiLocation) + if (item.uiLocation) { itemText += ' (' + item.uiLocation.linkText(true /* skipTrim */) + ')'; + } text.push(itemText); } InspectorFrontendHost.copyText(text.join('\n')); @@ -464,8 +481,9 @@ items.add(item); } asyncHeaderItem.isBlackboxed = asyncHeaderItem[whiteboxedItemsSymbol].size === 0; - if (shouldUpdate) + if (shouldUpdate) { updateDelegate(asyncHeaderItem); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js index 0558680..62126fa 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js +++ b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPausedMessage.js
@@ -35,11 +35,13 @@ static async _createDOMBreakpointHitMessage(details) { const messageWrapper = createElement('span'); const domDebuggerModel = details.debuggerModel.target().model(SDK.DOMDebuggerModel); - if (!details.auxData || !domDebuggerModel) + if (!details.auxData || !domDebuggerModel) { return messageWrapper; + } const data = domDebuggerModel.resolveDOMBreakpointData(/** @type {!Object} */ (details.auxData)); - if (!data) + if (!data) { return messageWrapper; + } const mainElement = messageWrapper.createChild('div', 'status-main'); mainElement.appendChild(UI.Icon.create('smallicon-info', 'status-icon')); @@ -54,10 +56,11 @@ const targetNodeLink = await Common.Linkifier.linkify(data.targetNode); let messageElement; if (data.insertion) { - if (data.targetNode === data.node) + if (data.targetNode === data.node) { messageElement = UI.formatLocalized('Child %s added', [targetNodeLink]); - else + } else { messageElement = UI.formatLocalized('Descendant %s added', [targetNodeLink]); + } } else { messageElement = UI.formatLocalized('Descendant %s removed', [targetNodeLink]); } @@ -76,8 +79,9 @@ async render(details, debuggerWorkspaceBinding, breakpointManager) { this._contentElement.removeChildren(); this._contentElement.hidden = !details; - if (!details) + if (!details) { return; + } const status = this._contentElement.createChild('div', 'paused-status'); @@ -122,8 +126,9 @@ } status.classList.toggle('error-reason', errorLike); - if (messageWrapper) + if (messageWrapper) { status.appendChild(messageWrapper); + } /** * @param {string} mainText
diff --git a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js index d3cc9a28..b03d58a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js +++ b/third_party/blink/renderer/devtools/front_end/sources/DebuggerPlugin.js
@@ -54,8 +54,9 @@ this._scriptsPanel = Sources.SourcesPanel.instance(); this._breakpointManager = Bindings.breakpointManager; - if (uiSourceCode.project().type() === Workspace.projectTypes.Debugger) + if (uiSourceCode.project().type() === Workspace.projectTypes.Debugger) { this._textEditor.element.classList.add('source-frame-debugger-script'); + } this._popoverHelper = new UI.PopoverHelper(this._scriptsPanel.element, this._getPopoverRequest.bind(this)); this._popoverHelper.setDisableOnClick(true); @@ -75,8 +76,9 @@ this._boundBlur = this._onBlur.bind(this); this._textEditor.element.addEventListener('focusout', this._boundBlur, false); this._boundWheel = event => { - if (this._executionLocation && UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) + if (this._executionLocation && UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) { event.preventDefault(); + } }; this._textEditor.element.addEventListener('wheel', this._boundWheel, true); @@ -130,8 +132,9 @@ this._showBlackboxInfobarIfNeeded(); const scriptFiles = this._scriptFileForDebuggerModel.valuesArray(); - for (let i = 0; i < scriptFiles.length; ++i) + for (let i = 0; i < scriptFiles.length; ++i) { scriptFiles[i].checkMapping(); + } this._hasLineWithoutMapping = false; this._updateLinesWithoutMappingHighlight(); @@ -153,16 +156,18 @@ _showBlackboxInfobarIfNeeded() { const uiSourceCode = this._uiSourceCode; - if (!uiSourceCode.contentType().hasScripts()) + if (!uiSourceCode.contentType().hasScripts()) { return; + } const projectType = uiSourceCode.project().type(); if (!Bindings.blackboxManager.isBlackboxedUISourceCode(uiSourceCode)) { this._hideBlackboxInfobar(); return; } - if (this._blackboxInfobar) + if (this._blackboxInfobar) { this._blackboxInfobar.dispose(); + } const infobar = new UI.Infobar(UI.Infobar.Type.Warning, Common.UIString('This script is blackboxed in debugger')); this._blackboxInfobar = infobar; @@ -171,8 +176,9 @@ Common.UIString('Debugger will skip stepping through this script, and will not stop on exceptions')); const scriptFile = this._scriptFileForDebuggerModel.size ? this._scriptFileForDebuggerModel.valuesArray()[0] : null; - if (scriptFile && scriptFile.hasSourceMapURL()) + if (scriptFile && scriptFile.hasSourceMapURL()) { infobar.createDetailsRowMessage(Common.UIString('Source map found, but ignored for blackboxed file.')); + } infobar.createDetailsRowMessage(); infobar.createDetailsRowMessage(Common.UIString('Possible ways to cancel this behavior are:')); @@ -184,15 +190,17 @@ function unblackbox() { Bindings.blackboxManager.unblackboxUISourceCode(uiSourceCode); - if (projectType === Workspace.projectTypes.ContentScripts) + if (projectType === Workspace.projectTypes.ContentScripts) { Bindings.blackboxManager.unblackboxContentScripts(); + } } this._textEditor.attachInfobar(this._blackboxInfobar); } _hideBlackboxInfobar() { - if (!this._blackboxInfobar) + if (!this._blackboxInfobar) { return; + } this._blackboxInfobar.dispose(); this._blackboxInfobar = null; } @@ -293,8 +301,9 @@ * @param {string} url */ function addSourceMapURLDialogCallback(scriptFile, url) { - if (!url) + if (!url) { return; + } scriptFile.addSourceMapURL(url); } @@ -318,13 +327,15 @@ } _workingCopyChanged() { - if (this._scriptFileForDebuggerModel.size) + if (this._scriptFileForDebuggerModel.size) { return; + } - if (this._uiSourceCode.isDirty()) + if (this._uiSourceCode.isDirty()) { this._muteBreakpointsWhileEditing(); - else + } else { this._restoreBreakpointsAfterEditing(); + } } /** @@ -332,8 +343,9 @@ */ _workingCopyCommitted(event) { this._scriptsPanel.updateLastModificationTime(); - if (!this._scriptFileForDebuggerModel.size) + if (!this._scriptFileForDebuggerModel.size) { this._restoreBreakpointsAfterEditing(); + } } _didMergeToVM() { @@ -345,18 +357,21 @@ } _muteBreakpointsWhileEditing() { - if (this._muted) + if (this._muted) { return; - for (const decoration of this._breakpointDecorations) + } + for (const decoration of this._breakpointDecorations) { this._updateBreakpointDecoration(decoration); + } this._muted = true; } _restoreBreakpointsIfConsistentScripts() { const scriptFiles = this._scriptFileForDebuggerModel.valuesArray(); for (let i = 0; i < scriptFiles.length; ++i) { - if (scriptFiles[i].hasDivergedFromVM() || scriptFiles[i].isMergingToVM()) + if (scriptFiles[i].hasDivergedFromVM() || scriptFiles[i].isMergingToVM()) { return; + } } this._restoreBreakpointsAfterEditing(); @@ -373,13 +388,15 @@ this._breakpointDecorations.clear(); this._textEditor.operation(() => decorations.map(decoration => decoration.hide())); for (const decoration of decorations) { - if (!decoration.breakpoint) + if (!decoration.breakpoint) { continue; + } const enabled = decoration.enabled; decoration.breakpoint.remove(); const location = decoration.handle.resolve(); - if (location) + if (location) { this._setBreakpoint(location.lineNumber, location.columnNumber, decoration.condition, enabled); + } } } @@ -396,16 +413,19 @@ * @return {?UI.PopoverRequest} */ _getPopoverRequest(event) { - if (UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) + if (UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) { return null; + } const target = UI.context.flavor(SDK.Target); const debuggerModel = target ? target.model(SDK.DebuggerModel) : null; - if (!debuggerModel || !debuggerModel.isPaused()) + if (!debuggerModel || !debuggerModel.isPaused()) { return null; + } const textPosition = this._textEditor.coordinatesToCursorPosition(event.x, event.y); - if (!textPosition) + if (!textPosition) { return null; + } const mouseLine = textPosition.startLine; const mouseColumn = textPosition.startColumn; @@ -417,8 +437,9 @@ if (textSelection && !textSelection.isEmpty()) { if (textSelection.startLine !== textSelection.endLine || textSelection.startLine !== mouseLine || - mouseColumn < textSelection.startColumn || mouseColumn > textSelection.endColumn) + mouseColumn < textSelection.startColumn || mouseColumn > textSelection.endColumn) { return null; + } const leftCorner = this._textEditor.cursorPositionToCoordinates(textSelection.startLine, textSelection.startColumn); @@ -429,15 +450,17 @@ endHighlight = textSelection.endColumn - 1; } else { const token = this._textEditor.tokenAtTextPosition(textPosition.startLine, textPosition.startColumn); - if (!token || !token.type) + if (!token || !token.type) { return null; + } editorLineNumber = textPosition.startLine; const line = this._textEditor.line(editorLineNumber); const tokenContent = line.substring(token.startColumn, token.endColumn); const isIdentifier = this._isIdentifier(token.type); - if (!isIdentifier && (token.type !== 'js-keyword' || tokenContent !== 'this')) + if (!isIdentifier && (token.type !== 'js-keyword' || tokenContent !== 'this')) { return null; + } const leftCorner = this._textEditor.cursorPositionToCoordinates(editorLineNumber, token.startColumn); const rightCorner = this._textEditor.cursorPositionToCoordinates(editorLineNumber, token.endColumn - 1); @@ -447,10 +470,12 @@ endHighlight = token.endColumn - 1; while (startHighlight > 1 && line.charAt(startHighlight - 1) === '.') { const tokenBefore = this._textEditor.tokenAtTextPosition(editorLineNumber, startHighlight - 2); - if (!tokenBefore || !tokenBefore.type) + if (!tokenBefore || !tokenBefore.type) { return null; - if (tokenBefore.type === 'js-meta') + } + if (tokenBefore.type === 'js-meta') { break; + } startHighlight = tokenBefore.startColumn; } } @@ -462,8 +487,9 @@ box: anchorBox, show: async popover => { const selectedCallFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); - if (!selectedCallFrame) + if (!selectedCallFrame) { return false; + } const evaluationText = this._textEditor.line(editorLineNumber).substring(startHighlight, endHighlight + 1); const resolvedText = await Sources.SourceMapNamesResolver.resolveExpression( /** @type {!SDK.DebuggerModel.CallFrame} */ (selectedCallFrame), evaluationText, this._uiSourceCode, @@ -476,14 +502,16 @@ returnByValue: false, generatePreview: false }); - if (!result.object) + if (!result.object) { return false; + } objectPopoverHelper = await ObjectUI.ObjectPopoverHelper.buildObjectPopover(result.object, popover); const potentiallyUpdatedCallFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); if (!objectPopoverHelper || selectedCallFrame !== potentiallyUpdatedCallFrame) { debuggerModel.runtimeModel().releaseObjectGroup('popover'); - if (objectPopoverHelper) + if (objectPopoverHelper) { objectPopoverHelper.dispose(); + } return false; } const highlightRange = @@ -515,30 +543,34 @@ if (UI.shortcutRegistry.eventMatchesAction(event, 'debugger.toggle-breakpoint')) { const selection = this._textEditor.selection(); - if (!selection) + if (!selection) { return; + } this._toggleBreakpoint(selection.startLine, false); event.consume(true); return; } if (UI.shortcutRegistry.eventMatchesAction(event, 'debugger.toggle-breakpoint-enabled')) { const selection = this._textEditor.selection(); - if (!selection) + if (!selection) { return; + } this._toggleBreakpoint(selection.startLine, true); event.consume(true); return; } if (UI.shortcutRegistry.eventMatchesAction(event, 'debugger.breakpoint-input-window')) { const selection = this._textEditor.selection(); - if (!selection) + if (!selection) { return; + } const breakpoints = this._lineBreakpointDecorations(selection.startLine) .map(decoration => decoration.breakpoint) .filter(breakpoint => !!breakpoint); let breakpoint; - if (breakpoints.length) + if (breakpoints.length) { breakpoint = breakpoints[0]; + } const isLogpoint = breakpoint ? breakpoint.condition().includes(Sources.BreakpointEditDialog.LogpointPrefix) : false; this._editBreakpointCondition(selection.startLine, breakpoint, null, isLogpoint); @@ -550,8 +582,9 @@ this._controlDown = true; if (event.key === (Host.isMac() ? 'Meta' : 'Control')) { this._controlTimeout = setTimeout(() => { - if (this._executionLocation && this._controlDown) + if (this._executionLocation && this._controlDown) { this._showContinueToLocations(); + } }, 150); } } @@ -562,8 +595,9 @@ */ _onMouseMove(event) { if (this._executionLocation && this._controlDown && UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) { - if (!this._continueToLocationDecorations) + if (!this._continueToLocationDecorations) { this._showContinueToLocations(); + } } if (this._continueToLocationDecorations) { const textPosition = this._textEditor.coordinatesToCursorPosition(event.x, event.y); @@ -577,32 +611,39 @@ * @param {boolean} hovered */ _setAsyncStepInHoveredLine(editorLineNumber, hovered) { - if (this._asyncStepInHoveredLine === editorLineNumber && this._asyncStepInHovered === hovered) + if (this._asyncStepInHoveredLine === editorLineNumber && this._asyncStepInHovered === hovered) { return; - if (this._asyncStepInHovered && this._asyncStepInHoveredLine) + } + if (this._asyncStepInHovered && this._asyncStepInHoveredLine) { this._textEditor.toggleLineClass(this._asyncStepInHoveredLine, 'source-frame-async-step-in-hovered', false); + } this._asyncStepInHoveredLine = editorLineNumber; this._asyncStepInHovered = hovered; - if (this._asyncStepInHovered && this._asyncStepInHoveredLine) + if (this._asyncStepInHovered && this._asyncStepInHoveredLine) { this._textEditor.toggleLineClass(this._asyncStepInHoveredLine, 'source-frame-async-step-in-hovered', true); + } } /** * @param {!MouseEvent} event */ _onMouseDown(event) { - if (!this._executionLocation || !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) + if (!this._executionLocation || !UI.KeyboardShortcut.eventHasCtrlOrMeta(event)) { return; - if (!this._continueToLocationDecorations) + } + if (!this._continueToLocationDecorations) { return; + } event.consume(); const textPosition = this._textEditor.coordinatesToCursorPosition(event.x, event.y); - if (!textPosition) + if (!textPosition) { return; + } for (const decoration of this._continueToLocationDecorations.keys()) { const range = decoration.find(); - if (range.from.line !== textPosition.startLine || range.to.line !== textPosition.startLine) + if (range.from.line !== textPosition.startLine || range.to.line !== textPosition.startLine) { continue; + } if (range.from.ch <= textPosition.startColumn && textPosition.startColumn <= range.to.ch) { this._continueToLocationDecorations.get(decoration)(); break; @@ -614,8 +655,9 @@ * @param {!Event} event */ _onBlur(event) { - if (this._textEditor.element.isAncestor(/** @type {!Node} */ (event.target))) + if (this._textEditor.element.isAncestor(/** @type {!Node} */ (event.target))) { return; + } this._clearControlDown(); } @@ -644,14 +686,16 @@ const dialog = new Sources.BreakpointEditDialog(editorLineNumber, oldCondition, !!preferLogpoint, result => { dialog.detach(); this._textEditor.removeDecoration(decorationElement, editorLineNumber); - if (!result.committed) + if (!result.committed) { return; - if (breakpoint) + } + if (breakpoint) { breakpoint.setCondition(result.condition); - else if (location) + } else if (location) { this._setBreakpoint(location.lineNumber, location.columnNumber, result.condition, true); - else + } else { this._createNewBreakpoint(editorLineNumber, result.condition, true); + } }); this._textEditor.addDecoration(decorationElement, editorLineNumber); dialog.markAsExternallyManaged(); @@ -675,23 +719,27 @@ if (this._textEditor.isShowing()) { // We need SourcesTextEditor to be initialized prior to this call. @see crbug.com/506566 setImmediate(() => { - if (this._controlDown) + if (this._controlDown) { this._showContinueToLocations(); - else + } else { this._generateValuesInSource(); + } }); } } _generateValuesInSource() { - if (!Common.moduleSetting('inlineVariableValues').get()) + if (!Common.moduleSetting('inlineVariableValues').get()) { return; + } const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return; + } const callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); - if (!callFrame) + if (!callFrame) { return; + } const localScope = callFrame.localScope(); const functionLocation = callFrame.functionLocation(); @@ -705,11 +753,13 @@ _showContinueToLocations() { this._popoverHelper.hidePopover(); const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return; + } const callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); - if (!callFrame) + if (!callFrame) { return; + } const start = callFrame.functionLocation() || callFrame.location(); const debuggerModel = callFrame.debuggerModel; debuggerModel.getPossibleBreakpoints(start, null, true) @@ -729,30 +779,35 @@ for (const location of locations) { const editorLocation = this._transformer.rawToEditorLocation(location.lineNumber, location.columnNumber); let token = this._textEditor.tokenAtTextPosition(editorLocation[0], editorLocation[1]); - if (!token) + if (!token) { continue; + } const line = this._textEditor.line(editorLocation[0]); let tokenContent = line.substring(token.startColumn, token.endColumn); if (!token.type && tokenContent === '.') { token = this._textEditor.tokenAtTextPosition(editorLocation[0], token.endColumn + 1); tokenContent = line.substring(token.startColumn, token.endColumn); } - if (!token.type) + if (!token.type) { continue; + } const validKeyword = token.type === 'js-keyword' && (tokenContent === 'this' || tokenContent === 'return' || tokenContent === 'new' || tokenContent === 'continue' || tokenContent === 'break'); - if (!validKeyword && !this._isIdentifier(token.type)) + if (!validKeyword && !this._isIdentifier(token.type)) { continue; - if (previousCallLine === editorLocation[0] && location.type !== Protocol.Debugger.BreakLocationType.Call) + } + if (previousCallLine === editorLocation[0] && location.type !== Protocol.Debugger.BreakLocationType.Call) { continue; + } let highlightRange = new TextUtils.TextRange(editorLocation[0], token.startColumn, editorLocation[0], token.endColumn - 1); let decoration = this._textEditor.highlightRange(highlightRange, 'source-frame-continue-to-location'); this._continueToLocationDecorations.set(decoration, location.continueToLocation.bind(location)); - if (location.type === Protocol.Debugger.BreakLocationType.Call) + if (location.type === Protocol.Debugger.BreakLocationType.Call) { previousCallLine = editorLocation[0]; + } let isAsyncCall = (line[token.startColumn - 1] === '.' && tokenContent === 'then') || tokenContent === 'setTimeout' || tokenContent === 'setInterval' || tokenContent === 'postMessage'; @@ -799,42 +854,52 @@ let position = line.indexOf('(', column); const argumentsStart = position; - if (position === -1) + if (position === -1) { return null; + } position++; skipWhitespace(); - if (position >= line.length) + if (position >= line.length) { return null; + } nextToken(); - if (!token) + if (!token) { return null; + } from = token.startColumn; if (token.type === 'js-keyword' && tokenText === 'async') { skipWhitespace(); - if (position >= line.length) + if (position >= line.length) { return {from: from, to: to}; + } nextToken(); - if (!token) + if (!token) { return {from: from, to: to}; + } } - if (token.type === 'js-keyword' && tokenText === 'function') + if (token.type === 'js-keyword' && tokenText === 'function') { return {from: from, to: to}; + } - if (token.type === 'js-string') + if (token.type === 'js-string') { return {from: argumentsStart, to: to}; + } - if (token.type && this._isIdentifier(token.type)) + if (token.type && this._isIdentifier(token.type)) { return {from: from, to: to}; + } - if (tokenText !== '(') + if (tokenText !== '(') { return null; + } const closeParen = line.indexOf(')', position); - if (closeParen === -1 || line.substring(position, closeParen).indexOf('(') !== -1) + if (closeParen === -1 || line.substring(position, closeParen).indexOf('(') !== -1) { return {from: from, to: to}; + } return {from: from, to: closeParen + 1}; function nextToken() { @@ -867,10 +932,11 @@ * @param {boolean} isCurrentPosition */ _asyncStepIn(location, isCurrentPosition) { - if (!isCurrentPosition) + if (!isCurrentPosition) { location.continueToLocation(asyncStepIn); - else + } else { asyncStepIn(); + } function asyncStepIn() { location.debuggerModel.scheduleStepIntoAsync(); @@ -884,15 +950,17 @@ _prepareScopeVariables(callFrame, allProperties) { const properties = allProperties.properties; this._clearValueWidgets(); - if (!properties || !properties.length || properties.length > 500 || !this._textEditor.isShowing()) + if (!properties || !properties.length || properties.length > 500 || !this._textEditor.isShowing()) { return; + } const functionUILocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation( /** @type {!SDK.DebuggerModel.Location} */ (callFrame.functionLocation())); const executionUILocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(callFrame.location()); if (!functionUILocation || !executionUILocation || functionUILocation.uiSourceCode !== this._uiSourceCode || - executionUILocation.uiSourceCode !== this._uiSourceCode) + executionUILocation.uiSourceCode !== this._uiSourceCode) { return; + } const functionEditorLocation = this._transformer.rawToEditorLocation(functionUILocation.lineNumber, functionUILocation.columnNumber); @@ -901,20 +969,23 @@ const fromLine = functionEditorLocation[0]; const fromColumn = functionEditorLocation[1]; const toLine = executionEditorLocation[0]; - if (fromLine >= toLine || toLine - fromLine > 500 || fromLine < 0 || toLine >= this._textEditor.linesCount) + if (fromLine >= toLine || toLine - fromLine > 500 || fromLine < 0 || toLine >= this._textEditor.linesCount) { return; + } const valuesMap = new Map(); - for (const property of properties) + for (const property of properties) { valuesMap.set(property.name, property.value); + } /** @type {!Map.<number, !Set<string>>} */ const namesPerLine = new Map(); let skipObjectProperty = false; const tokenizer = new TextEditor.CodeMirrorUtils.TokenizerFactory().createTokenizer('text/javascript'); tokenizer(this._textEditor.line(fromLine).substring(fromColumn), processToken.bind(this, fromLine)); - for (let i = fromLine + 1; i < toLine; ++i) + for (let i = fromLine + 1; i < toLine; ++i) { tokenizer(this._textEditor.line(i), processToken.bind(this, i)); + } /** * @param {number} editorLineNumber @@ -967,12 +1038,15 @@ let renderedNameCount = 0; for (const name of names) { - if (renderedNameCount > 10) + if (renderedNameCount > 10) { break; - if (namesPerLine.get(i - 1) && namesPerLine.get(i - 1).has(name)) - continue; // Only render name once in the given continuous block. - if (renderedNameCount) + } + if (namesPerLine.get(i - 1) && namesPerLine.get(i - 1).has(name)) { + continue; + } // Only render name once in the given continuous block. + if (renderedNameCount) { widget.createTextChild(', '); + } const nameValuePair = widget.createChild('span'); widget.__nameToToken.set(name, nameValuePair); nameValuePair.createTextChild(name + ' = '); @@ -1015,8 +1089,9 @@ _clearExecutionLine() { this._textEditor.operation(() => { - if (this._executionLocation) + if (this._executionLocation) { this._textEditor.clearExecutionLine(); + } this._executionLocation = null; if (this._clearValueWidgetsTimer) { clearTimeout(this._clearValueWidgetsTimer); @@ -1031,26 +1106,30 @@ clearTimeout(this._clearValueWidgetsTimer); this._clearValueWidgetsTimer = null; this._textEditor.operation(() => { - for (const line of this._valueWidgets.keys()) + for (const line of this._valueWidgets.keys()) { this._textEditor.removeDecoration(this._valueWidgets.get(line), line); + } this._valueWidgets.clear(); }); } _clearContinueToLocationsNoRestore() { - if (!this._continueToLocationDecorations) + if (!this._continueToLocationDecorations) { return; + } this._textEditor.operation(() => { - for (const decoration of this._continueToLocationDecorations.keys()) + for (const decoration of this._continueToLocationDecorations.keys()) { this._textEditor.removeHighlight(decoration); + } this._continueToLocationDecorations = null; this._setAsyncStepInHoveredLine(null, false); }); } _clearContinueToLocations() { - if (!this._continueToLocationDecorations) + if (!this._continueToLocationDecorations) { return; + } this._textEditor.operation(() => { this._textEditor.showExecutionLineBackground(); this._generateValuesInSource(); @@ -1075,10 +1154,12 @@ _breakpointDecoration(editorLineNumber, editorColumnNumber) { for (const decoration of this._breakpointDecorations) { const location = decoration.handle.resolve(); - if (!location) + if (!location) { continue; - if (location.lineNumber === editorLineNumber && location.columnNumber === editorColumnNumber) + } + if (location.lineNumber === editorLineNumber && location.columnNumber === editorColumnNumber) { return decoration; + } } return null; } @@ -1098,13 +1179,15 @@ * @this {Sources.DebuggerPlugin} */ function update() { - if (!this._scheduledBreakpointDecorationUpdates) + if (!this._scheduledBreakpointDecorationUpdates) { return; + } const editorLineNumbers = new Set(); for (const decoration of this._scheduledBreakpointDecorationUpdates) { const location = decoration.handle.resolve(); - if (!location) + if (!location) { continue; + } editorLineNumbers.add(location.lineNumber); } this._scheduledBreakpointDecorationUpdates = null; @@ -1118,8 +1201,9 @@ } updateInlineDecorations.call(this, lineNumber, decorations); } - if (!waitingForInlineDecorations) + if (!waitingForInlineDecorations) { this._breakpointDecorationsUpdatedForTest(); + } } /** @@ -1154,18 +1238,21 @@ new TextUtils.TextRange(editorLineNumber, 0, editorLineNumber, lineEnd), Sources.DebuggerPlugin.BreakpointDecoration.bookmarkSymbol); for (const bookmark of bookmarks) { - if (!actualBookmarks.has(bookmark)) + if (!actualBookmarks.has(bookmark)) { bookmark.clear(); + } } - if (!decorations.length) + if (!decorations.length) { return; + } if (decorations.length > 1) { for (const decoration of decorations) { decoration.update(); - if (!this._muted) + if (!this._muted) { decoration.show(); - else + } else { decoration.hide(); + } } } else { decorations[0].update(); @@ -1184,14 +1271,16 @@ _inlineBreakpointClick(decoration, event) { event.consume(true); if (decoration.breakpoint) { - if (event.shiftKey) + if (event.shiftKey) { decoration.breakpoint.setEnabled(!decoration.breakpoint.enabled()); - else + } else { decoration.breakpoint.remove(); + } } else { const editorLocation = decoration.handle.resolve(); - if (!editorLocation) + if (!editorLocation) { return; + } const location = this._transformer.editorToRawLocation(editorLocation.lineNumber, editorLocation.columnNumber); this._setBreakpoint(location[0], location[1], decoration.condition, true); } @@ -1204,8 +1293,9 @@ _inlineBreakpointContextMenu(decoration, event) { event.consume(true); const editorLocation = decoration.handle.resolve(); - if (!editorLocation) + if (!editorLocation) { return; + } const location = this._transformer.editorToRawLocation(editorLocation[0], editorLocation[1]); const contextMenu = new UI.ContextMenu(event); if (decoration.breakpoint) { @@ -1232,14 +1322,17 @@ */ _shouldIgnoreExternalBreakpointEvents(event) { const uiLocation = /** @type {!Workspace.UILocation} */ (event.data.uiLocation); - if (uiLocation.uiSourceCode !== this._uiSourceCode) + if (uiLocation.uiSourceCode !== this._uiSourceCode) { return true; - if (this._muted) + } + if (this._muted) { return true; + } const scriptFiles = this._scriptFileForDebuggerModel.valuesArray(); for (let i = 0; i < scriptFiles.length; ++i) { - if (scriptFiles[i].isDivergingFromVM() || scriptFiles[i].isMergingToVM()) + if (scriptFiles[i].isDivergingFromVM() || scriptFiles[i].isMergingToVM()) { return true; + } } return false; } @@ -1248,8 +1341,9 @@ * @param {!Common.Event} event */ _breakpointAdded(event) { - if (this._shouldIgnoreExternalBreakpointEvents(event)) + if (this._shouldIgnoreExternalBreakpointEvents(event)) { return; + } const uiLocation = /** @type {!Workspace.UILocation} */ (event.data.uiLocation); const breakpoint = /** @type {!Bindings.BreakpointManager.Breakpoint} */ (event.data.breakpoint); this._addBreakpoint(uiLocation, breakpoint); @@ -1295,22 +1389,26 @@ function addInlineDecorations(editorLineNumber, possibleLocations) { this._possibleBreakpointsRequested.delete(editorLineNumber); const decorations = this._lineBreakpointDecorations(editorLineNumber); - for (const decoration of decorations) + for (const decoration of decorations) { this._updateBreakpointDecoration(decoration); - if (!decorations.some(decoration => !!decoration.breakpoint)) + } + if (!decorations.some(decoration => !!decoration.breakpoint)) { return; + } /** @type {!Set<number>} */ const columns = new Set(); for (const decoration of decorations) { const editorLocation = decoration.handle.resolve(); - if (!editorLocation) + if (!editorLocation) { continue; + } columns.add(editorLocation.columnNumber); } for (const location of possibleLocations) { const editorLocation = this._transformer.rawToEditorLocation(location.lineNumber, location.columnNumber); - if (columns.has(editorLocation[1])) + if (columns.has(editorLocation[1])) { continue; + } const handle = this._textEditor.textEditorPositionHandle(editorLocation[0], editorLocation[1]); const decoration = new Sources.DebuggerPlugin.BreakpointDecoration(this._textEditor, handle, '', false, null); decoration.element.addEventListener('click', this._inlineBreakpointClick.bind(this, decoration), true); @@ -1326,13 +1424,15 @@ * @param {!Common.Event} event */ _breakpointRemoved(event) { - if (this._shouldIgnoreExternalBreakpointEvents(event)) + if (this._shouldIgnoreExternalBreakpointEvents(event)) { return; + } const uiLocation = /** @type {!Workspace.UILocation} */ (event.data.uiLocation); const breakpoint = /** @type {!Bindings.BreakpointManager.Breakpoint} */ (event.data.breakpoint); const decoration = this._decorationByBreakpoint.get(breakpoint); - if (!decoration) + if (!decoration) { return; + } this._decorationByBreakpoint.delete(breakpoint); const editorLocation = this._transformer.rawToEditorLocation(uiLocation.lineNumber, uiLocation.columnNumber); @@ -1352,29 +1452,34 @@ _initializeBreakpoints() { const breakpointLocations = this._breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode); - for (const breakpointLocation of breakpointLocations) + for (const breakpointLocation of breakpointLocations) { this._addBreakpoint(breakpointLocation.uiLocation, breakpointLocation.breakpoint); + } } _updateLinesWithoutMappingHighlight() { const isSourceMapSource = !!Bindings.CompilerScriptMapping.uiSourceCodeOrigin(this._uiSourceCode); - if (!isSourceMapSource) + if (!isSourceMapSource) { return; + } const linesCount = this._textEditor.linesCount; for (let i = 0; i < linesCount; ++i) { const lineHasMapping = Bindings.CompilerScriptMapping.uiLineHasMapping(this._uiSourceCode, i); - if (!lineHasMapping) + if (!lineHasMapping) { this._hasLineWithoutMapping = true; - if (this._hasLineWithoutMapping) + } + if (this._hasLineWithoutMapping) { this._textEditor.toggleLineClass(i, 'cm-line-without-source-mapping', !lineHasMapping); + } } } _updateScriptFiles() { for (const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)) { const scriptFile = Bindings.debuggerWorkspaceBinding.scriptFile(this._uiSourceCode, debuggerModel); - if (scriptFile) + if (scriptFile) { this._updateScriptFile(debuggerModel); + } } } @@ -1389,27 +1494,32 @@ oldScriptFile.removeEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); oldScriptFile.removeEventListener( Bindings.ResourceScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); - if (this._muted && !this._uiSourceCode.isDirty()) + if (this._muted && !this._uiSourceCode.isDirty()) { this._restoreBreakpointsIfConsistentScripts(); + } } - if (!newScriptFile) + if (!newScriptFile) { return; + } this._scriptFileForDebuggerModel.set(debuggerModel, newScriptFile); newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); newScriptFile.addEventListener(Bindings.ResourceScriptFile.Events.DidDivergeFromVM, this._didDivergeFromVM, this); newScriptFile.checkMapping(); - if (newScriptFile.hasSourceMapURL()) + if (newScriptFile.hasSourceMapURL()) { this._showSourceMapInfobar(); + } } _showSourceMapInfobar() { - if (this._sourceMapInfobar) + if (this._sourceMapInfobar) { return; + } this._sourceMapInfobar = UI.Infobar.create( UI.Infobar.Type.Info, Common.UIString('Source Map detected.'), Common.settings.createSetting('sourceMapInfobarDisabled', false)); - if (!this._sourceMapInfobar) + if (!this._sourceMapInfobar) { return; + } this._sourceMapInfobar.createDetailsRowMessage(Common.UIString( 'Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files.')); this._sourceMapInfobar.createDetailsRowMessage(Common.UIString( @@ -1421,14 +1531,16 @@ _detectMinified() { const content = this._uiSourceCode.content(); - if (!content || !TextUtils.isMinified(content)) + if (!content || !TextUtils.isMinified(content)) { return; + } this._prettyPrintInfobar = UI.Infobar.create( UI.Infobar.Type.Info, Common.UIString('Pretty-print this minified file?'), Common.settings.createSetting('prettyPrintInfobarDisabled', false)); - if (!this._prettyPrintInfobar) + if (!this._prettyPrintInfobar) { return; + } this._prettyPrintInfobar.setCloseCallback(() => this._prettyPrintInfobar = null); const toolbar = new UI.Toolbar(''); @@ -1449,17 +1561,20 @@ * @param {!Common.Event} event */ _handleGutterClick(event) { - if (this._muted) + if (this._muted) { return; + } const eventData = /** @type {!SourceFrame.SourcesTextEditor.GutterClickEventData} */ (event.data); - if (eventData.gutterType !== SourceFrame.SourcesTextEditor.lineNumbersGutterType) + if (eventData.gutterType !== SourceFrame.SourcesTextEditor.lineNumbersGutterType) { return; + } const editorLineNumber = eventData.lineNumber; const eventObject = eventData.event; - if (eventObject.button !== 0 || eventObject.altKey || eventObject.ctrlKey || eventObject.metaKey) + if (eventObject.button !== 0 || eventObject.altKey || eventObject.ctrlKey || eventObject.metaKey) { return; + } this._toggleBreakpoint(editorLineNumber, eventObject.shiftKey); eventObject.consume(true); @@ -1478,10 +1593,11 @@ const hasDisabled = this._textEditor.hasLineClass(editorLineNumber, 'cm-breakpoint-disabled'); const breakpoints = decorations.map(decoration => decoration.breakpoint).filter(breakpoint => !!breakpoint); for (const breakpoint of breakpoints) { - if (onlyDisable) + if (onlyDisable) { breakpoint.setEnabled(hasDisabled); - else + } else { breakpoint.remove(); + } } } @@ -1511,12 +1627,14 @@ * @param {boolean} onlyDisable */ toggleBreakpointOnCurrentLine(onlyDisable) { - if (this._muted) + if (this._muted) { return; + } const selection = this._textEditor.selection(); - if (!selection) + if (!selection) { return; + } this._toggleBreakpoint(selection.startLine, onlyDisable); } @@ -1527,8 +1645,9 @@ * @param {boolean} enabled */ _setBreakpoint(lineNumber, columnNumber, condition, enabled) { - if (!Bindings.CompilerScriptMapping.uiLineHasMapping(this._uiSourceCode, lineNumber)) + if (!Bindings.CompilerScriptMapping.uiLineHasMapping(this._uiSourceCode, lineNumber)) { return; + } Common.moduleSetting('breakpointsActive').set(true); this._breakpointManager.setBreakpoint(this._uiSourceCode, lineNumber, columnNumber, condition, enabled); @@ -1560,20 +1679,24 @@ * @override */ dispose() { - for (const decoration of this._breakpointDecorations) + for (const decoration of this._breakpointDecorations) { decoration.dispose(); + } this._breakpointDecorations.clear(); if (this._scheduledBreakpointDecorationUpdates) { - for (const decoration of this._scheduledBreakpointDecorationUpdates) + for (const decoration of this._scheduledBreakpointDecorationUpdates) { decoration.dispose(); + } this._scheduledBreakpointDecorationUpdates.clear(); } this._hideBlackboxInfobar(); - if (this._sourceMapInfobar) + if (this._sourceMapInfobar) { this._sourceMapInfobar.dispose(); - if (this._prettyPrintInfobar) + } + if (this._prettyPrintInfobar) { this._prettyPrintInfobar.dispose(); + } this._scriptsPanel.element.removeEventListener('scroll', this._boundPopoverHelperHide, true); for (const script of this._scriptFileForDebuggerModel.values()) { script.removeEventListener(Bindings.ResourceScriptFile.Events.DidMergeToVM, this._didMergeToVM, this); @@ -1643,27 +1766,32 @@ * @return {number} */ static mostSpecificFirst(decoration1, decoration2) { - if (decoration1.enabled !== decoration2.enabled) + if (decoration1.enabled !== decoration2.enabled) { return decoration1.enabled ? -1 : 1; - if (!!decoration1.condition !== !!decoration2.condition) + } + if (!!decoration1.condition !== !!decoration2.condition) { return !!decoration1.condition ? -1 : 1; + } return 0; } update() { - if (!this.condition) + if (!this.condition) { this.element.setIconType('smallicon-inline-breakpoint'); - else + } else { this.element.setIconType('smallicon-inline-breakpoint-conditional'); + } this.element.classList.toggle('cm-inline-disabled', !this.enabled); } show() { - if (this.bookmark) + if (this.bookmark) { return; + } const editorLocation = this.handle.resolve(); - if (!editorLocation) + if (!editorLocation) { return; + } this.bookmark = this._textEditor.addBookmark( editorLocation.lineNumber, editorLocation.columnNumber, this.element, Sources.DebuggerPlugin.BreakpointDecoration.bookmarkSymbol); @@ -1671,8 +1799,9 @@ } hide() { - if (!this.bookmark) + if (!this.bookmark) { return; + } this.bookmark.clear(); this.bookmark = null; }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/EditingLocationHistoryManager.js b/third_party/blink/renderer/devtools/front_end/sources/EditingLocationHistoryManager.js index 7c282a36..3ee065a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/EditingLocationHistoryManager.js +++ b/third_party/blink/renderer/devtools/front_end/sources/EditingLocationHistoryManager.js
@@ -54,10 +54,12 @@ * @param {!Common.Event} event */ _onJumpHappened(event) { - if (event.data.from) + if (event.data.from) { this._updateActiveState(event.data.from); - if (event.data.to) + } + if (event.data.to) { this._pushActiveState(event.data.to); + } } rollback() { @@ -70,15 +72,17 @@ updateCurrentState() { const sourceFrame = this._currentSourceFrameCallback(); - if (!sourceFrame) + if (!sourceFrame) { return; + } this._updateActiveState(sourceFrame.textEditor.selection()); } pushNewState() { const sourceFrame = this._currentSourceFrameCallback(); - if (!sourceFrame) + if (!sourceFrame) { return; + } this._pushActiveState(sourceFrame.textEditor.selection()); } @@ -87,11 +91,13 @@ */ _updateActiveState(selection) { const active = this._historyManager.active(); - if (!active) + if (!active) { return; + } const sourceFrame = this._currentSourceFrameCallback(); - if (!sourceFrame) + if (!sourceFrame) { return; + } const entry = new Sources.EditingLocationHistoryEntry(this._sourcesView, this, sourceFrame, selection); active.merge(entry); } @@ -101,8 +107,9 @@ */ _pushActiveState(selection) { const sourceFrame = this._currentSourceFrameCallback(); - if (!sourceFrame) + if (!sourceFrame) { return; + } const entry = new Sources.EditingLocationHistoryEntry(this._sourcesView, this, sourceFrame, selection); this._historyManager.push(entry); } @@ -147,8 +154,9 @@ * @param {!Sources.HistoryEntry} entry */ merge(entry) { - if (this._projectId !== entry._projectId || this._url !== entry._url) + if (this._projectId !== entry._projectId || this._url !== entry._url) { return; + } this._positionHandle = entry._positionHandle; } @@ -176,8 +184,9 @@ reveal() { const position = this._positionHandle.resolve(); const uiSourceCode = Workspace.workspace.uiSourceCode(this._projectId, this._url); - if (!position || !uiSourceCode) + if (!position || !uiSourceCode) { return; + } this._editingLocationManager.updateCurrentState(); this._sourcesView.showSourceLocation(uiSourceCode, position.lineNumber, position.columnNumber);
diff --git a/third_party/blink/renderer/devtools/front_end/sources/FilePathScoreFunction.js b/third_party/blink/renderer/devtools/front_end/sources/FilePathScoreFunction.js index d9c3b8c..769c7aa0 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/FilePathScoreFunction.js +++ b/third_party/blink/renderer/devtools/front_end/sources/FilePathScoreFunction.js
@@ -50,8 +50,9 @@ * @return {number} */ score(data, matchIndexes) { - if (!data || !this._query) + if (!data || !this._query) { return 0; + } const n = this._query.length; const m = data.length; if (!this._score || this._score.length < n * m) { @@ -77,8 +78,9 @@ } } } - if (matchIndexes) + if (matchIndexes) { this._restoreMatchIndexes(sequence, n, m, matchIndexes); + } const maxDataLength = 256; return score[n * m - 1] * maxDataLength + (maxDataLength - data.length); } @@ -89,8 +91,9 @@ * @return {boolean} */ _testWordStart(data, j) { - if (j === 0) + if (j === 0) { return true; + } const prevChar = data.charAt(j - 1); return prevChar === '_' || prevChar === '-' || prevChar === '/' || @@ -133,19 +136,25 @@ const isPathTokenStart = j === 0 || data[j - 1] === '/'; const isCapsMatch = query[i] === data[j] && query[i] === this._queryUpperCase[i]; let score = 10; - if (isPathTokenStart) + if (isPathTokenStart) { score += 4; - if (isWordStart) + } + if (isWordStart) { score += 2; - if (isCapsMatch) + } + if (isCapsMatch) { score += 6; - if (isFileName) + } + if (isFileName) { score += 4; + } // promote the case of making the whole match in the filename - if (j === this._fileNameIndex + 1 && i === 0) + if (j === this._fileNameIndex + 1 && i === 0) { score += 5; - if (isFileName && isWordStart) + } + if (isFileName && isWordStart) { score += 3; + } return score; } @@ -161,10 +170,12 @@ const isFileName = j > this._fileNameIndex; const isPathTokenStart = j === 0 || data[j - 1] === '/'; let score = 10; - if (isFileName) + if (isFileName) { score += 4; - if (isPathTokenStart) + } + if (isPathTokenStart) { score += 5; + } score += sequenceLength * 4; return score; } @@ -178,12 +189,14 @@ * @return {number} */ _match(query, data, i, j, consecutiveMatch) { - if (this._queryUpperCase[i] !== this._dataUpperCase[j]) + if (this._queryUpperCase[i] !== this._dataUpperCase[j]) { return 0; + } - if (!consecutiveMatch) + if (!consecutiveMatch) { return this._singleCharScore(query, data, i, j); - else + } else { return this._sequenceCharScore(query, data, i, j - consecutiveMatch, consecutiveMatch); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/FilteredUISourceCodeListProvider.js b/third_party/blink/renderer/devtools/front_end/sources/FilteredUISourceCodeListProvider.js index 0dfdcb3..8961db9 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/FilteredUISourceCodeListProvider.js +++ b/third_party/blink/renderer/devtools/front_end/sources/FilteredUISourceCodeListProvider.js
@@ -33,8 +33,9 @@ this._uiSourceCodes = []; const projects = Workspace.workspace.projects().filter(this.filterProject.bind(this)); for (let i = 0; i < projects.length; ++i) { - if (skipProject && projects[i] === skipProject) + if (skipProject && projects[i] === skipProject) { continue; + } const uiSourceCodes = projects[i].uiSourceCodes().filter(this._filterUISourceCode.bind(this)); this._uiSourceCodes = this._uiSourceCodes.concat(uiSourceCodes); } @@ -101,8 +102,9 @@ itemScoreAt(itemIndex, query) { const uiSourceCode = this._uiSourceCodes[itemIndex]; const score = this._defaultScores ? (this._defaultScores.get(uiSourceCode) || 0) : 0; - if (!query || query.length < 2) + if (!query || query.length < 2) { return score; + } if (this._query !== query) { this._query = query; @@ -111,8 +113,9 @@ let multiplier = 10; if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem && - !Persistence.persistence.binding(uiSourceCode)) + !Persistence.persistence.binding(uiSourceCode)) { multiplier = 5; + } const fullDisplayName = uiSourceCode.fullDisplayName(); return score + multiplier * this._scorer.score(fullDisplayName, null); @@ -139,12 +142,14 @@ this._renderSubtitleElement(subtitleElement, fullDisplayName); subtitleElement.title = fullDisplayName; const ranges = []; - for (let i = 0; i < indexes.length; ++i) + for (let i = 0; i < indexes.length; ++i) { ranges.push({offset: indexes[i], length: 1}); + } if (indexes[0] > fileNameIndex) { - for (let i = 0; i < ranges.length; ++i) + for (let i = 0; i < ranges.length; ++i) { ranges[i].offset -= fileNameIndex + 1; + } UI.highlightRangesWithStyleClass(titleElement, ranges, 'highlight'); } else { UI.highlightRangesWithStyleClass(subtitleElement, ranges, 'highlight'); @@ -158,8 +163,9 @@ _renderSubtitleElement(element, text) { element.removeChildren(); let splitPosition = text.lastIndexOf('/'); - if (text.length > 55) + if (text.length > 55) { splitPosition = text.length - 55; + } const first = element.createChild('div', 'first-part'); first.textContent = text.substring(0, splitPosition); const second = element.createChild('div', 'second-part'); @@ -174,15 +180,18 @@ */ selectItem(itemIndex, promptValue) { const parsedExpression = promptValue.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/); - if (!parsedExpression) + if (!parsedExpression) { return; + } let lineNumber; let columnNumber; - if (parsedExpression[2]) + if (parsedExpression[2]) { lineNumber = parseInt(parsedExpression[2].substr(1), 10) - 1; - if (parsedExpression[3]) + } + if (parsedExpression[3]) { columnNumber = parseInt(parsedExpression[3].substr(1), 10) - 1; + } const uiSourceCode = itemIndex !== null ? this._uiSourceCodes[itemIndex] : null; this.uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber); } @@ -194,8 +203,9 @@ */ rewriteQuery(query) { query = query ? query.trim() : ''; - if (!query || query === ':') + if (!query || query === ':') { return ''; + } const lineNumberMatch = query.match(/^([^:]+)((?::[^:]*){0,2})$/); this._queryLineNumberAndColumnNumber = lineNumberMatch ? lineNumberMatch[2] : ''; return lineNumberMatch ? lineNumberMatch[1] : query; @@ -206,8 +216,9 @@ */ _uiSourceCodeAdded(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); - if (!this._filterUISourceCode(uiSourceCode) || !this.filterProject(uiSourceCode.project())) + if (!this._filterUISourceCode(uiSourceCode) || !this.filterProject(uiSourceCode.project())) { return; + } this._uiSourceCodes.push(uiSourceCode); this.refresh(); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/GoToLineQuickOpen.js b/third_party/blink/renderer/devtools/front_end/sources/GoToLineQuickOpen.js index 6b11376..5410af6 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/GoToLineQuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/sources/GoToLineQuickOpen.js
@@ -10,11 +10,13 @@ */ selectItem(itemIndex, promptValue) { const uiSourceCode = this._currentUISourceCode(); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } const position = this._parsePosition(promptValue); - if (!position) + if (!position) { return; + } Common.Revealer.reveal(uiSourceCode.uiLocation(position.line - 1, position.column - 1)); } @@ -24,19 +26,22 @@ * @return {string} */ notFoundText(query) { - if (!this._currentUISourceCode()) + if (!this._currentUISourceCode()) { return Common.UIString('No file selected.'); + } const position = this._parsePosition(query); if (!position) { const sourceFrame = this._currentSourceFrame(); - if (!sourceFrame) + if (!sourceFrame) { return ls`Type a number to go to that line.`; + } const currentLineNumber = sourceFrame.textEditor.currentLineNumber() + 1; const linesCount = sourceFrame.textEditor.linesCount; return ls`Current line: ${currentLineNumber}. Type a line number between 1 and ${linesCount} to navigate to.`; } - if (position.column && position.column > 1) + if (position.column && position.column > 1) { return ls`Go to line ${position.line} and column ${position.column}.`; + } return ls`Go to line ${position.line}.`; } @@ -46,12 +51,14 @@ */ _parsePosition(query) { const parts = query.match(/([0-9]+)(\:[0-9]*)?/); - if (!parts || !parts[0] || parts[0].length !== query.length) + if (!parts || !parts[0] || parts[0].length !== query.length) { return null; + } const line = parseInt(parts[1], 10); let column; - if (parts[2]) + if (parts[2]) { column = parseInt(parts[2].substring(1), 10); + } return {line: Math.max(line | 0, 1), column: Math.max(column | 0, 1)}; } @@ -60,8 +67,9 @@ */ _currentUISourceCode() { const sourcesView = UI.context.flavor(Sources.SourcesView); - if (!sourcesView) + if (!sourcesView) { return null; + } return sourcesView.currentUISourceCode(); } @@ -70,8 +78,9 @@ */ _currentSourceFrame() { const sourcesView = UI.context.flavor(Sources.SourcesView); - if (!sourcesView) + if (!sourcesView) { return null; + } return sourcesView.currentSourceFrame(); } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/GutterDiffPlugin.js b/third_party/blink/renderer/devtools/front_end/sources/GutterDiffPlugin.js index 4f8eddc..7aef92d 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/GutterDiffPlugin.js +++ b/third_party/blink/renderer/devtools/front_end/sources/GutterDiffPlugin.js
@@ -37,18 +37,21 @@ this._textEditor.operation(operation); function operation() { - for (const decoration of removed) + for (const decoration of removed) { decoration.remove(); - for (const decoration of added) + } + for (const decoration of added) { decoration.install(); + } } } _update() { - if (this._uiSourceCode) + if (this._uiSourceCode) { this._workspaceDiff.requestDiff(this._uiSourceCode).then(this._innerUpdate.bind(this)); - else + } else { this._innerUpdate(null); + } } /** @@ -66,8 +69,9 @@ for (let i = 0; i < this._decorations.length; ++i) { const decoration = this._decorations[i]; const lineNumber = decoration.lineNumber(); - if (lineNumber === -1) + if (lineNumber === -1) { continue; + } oldDecorations.set(lineNumber, decoration); } @@ -77,8 +81,9 @@ const newDecorations = new Map(); for (let i = 0; i < diff.length; ++i) { const diffEntry = diff[i]; - for (let lineNumber = diffEntry.from; lineNumber < diffEntry.to; ++lineNumber) + for (let lineNumber = diffEntry.from; lineNumber < diffEntry.to; ++lineNumber) { newDecorations.set(lineNumber, {lineNumber: lineNumber, type: diffEntry.type}); + } } const decorationDiff = oldDecorations.diff(newDecorations, (e1, e2) => e1.type === e2.type); @@ -118,8 +123,9 @@ } static _appendRevealDiffContextMenu(contextMenu, uiSourceCode) { - if (!WorkspaceDiff.workspaceDiff().isUISourceCodeModified(uiSourceCode)) + if (!WorkspaceDiff.workspaceDiff().isUISourceCodeModified(uiSourceCode)) { return; + } contextMenu.revealSection().appendItem(ls`Local Modifications...`, () => { Common.Revealer.reveal(new WorkspaceDiff.DiffUILocation(uiSourceCode)); }); @@ -129,8 +135,9 @@ * @override */ dispose() { - for (const decoration of this._decorations) + for (const decoration of this._decorations) { decoration.remove(); + } WorkspaceDiff.workspaceDiff().unsubscribeFromDiffChange(this._uiSourceCode, this._update, this); } }; @@ -145,12 +152,13 @@ this._textEditor = textEditor; this._position = this._textEditor.textEditorPositionHandle(lineNumber, 0); this._className = ''; - if (type === SourceFrame.SourceCodeDiff.EditType.Insert) + if (type === SourceFrame.SourceCodeDiff.EditType.Insert) { this._className = 'diff-entry-insert'; - else if (type === SourceFrame.SourceCodeDiff.EditType.Delete) + } else if (type === SourceFrame.SourceCodeDiff.EditType.Delete) { this._className = 'diff-entry-delete'; - else if (type === SourceFrame.SourceCodeDiff.EditType.Modify) + } else if (type === SourceFrame.SourceCodeDiff.EditType.Modify) { this._className = 'diff-entry-modify'; + } this.type = type; } @@ -159,15 +167,17 @@ */ lineNumber() { const location = this._position.resolve(); - if (!location) + if (!location) { return -1; + } return location.lineNumber; } install() { const location = this._position.resolve(); - if (!location) + if (!location) { return; + } const element = createElementWithClass('div', 'diff-marker'); element.textContent = '\xA0'; this._textEditor.setGutterDecoration(location.lineNumber, Sources.GutterDiffPlugin.DiffGutterType, element); @@ -176,8 +186,9 @@ remove() { const location = this._position.resolve(); - if (!location) + if (!location) { return; + } this._textEditor.setGutterDecoration(location.lineNumber, Sources.GutterDiffPlugin.DiffGutterType, null); this._textEditor.toggleLineClass(location.lineNumber, this._className, false); } @@ -200,8 +211,9 @@ appendApplicableItems(event, contextMenu, target) { let uiSourceCode = /** @type {!Workspace.UISourceCode} */ (target); const binding = Persistence.persistence.binding(uiSourceCode); - if (binding) + if (binding) { uiSourceCode = binding.network; + } Sources.GutterDiffPlugin._appendRevealDiffContextMenu(contextMenu, uiSourceCode); } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/InplaceFormatterEditorAction.js b/third_party/blink/renderer/devtools/front_end/sources/InplaceFormatterEditorAction.js index aa3578f..fc4342f2 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/InplaceFormatterEditorAction.js +++ b/third_party/blink/renderer/devtools/front_end/sources/InplaceFormatterEditorAction.js
@@ -19,8 +19,9 @@ */ _editorClosed(event) { const wasSelected = /** @type {boolean} */ (event.data.wasSelected); - if (wasSelected) + if (wasSelected) { this._updateButton(null); + } } /** @@ -36,8 +37,9 @@ * @return {!UI.ToolbarButton} */ button(sourcesView) { - if (this._button) + if (this._button) { return this._button; + } this._sourcesView = sourcesView; this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected, this._editorSelected.bind(this)); @@ -55,12 +57,15 @@ * @return {boolean} */ _isFormattable(uiSourceCode) { - if (!uiSourceCode) + if (!uiSourceCode) { return false; - if (uiSourceCode.project().canSetFileContent()) + } + if (uiSourceCode.project().canSetFileContent()) { return true; - if (Persistence.persistence.binding(uiSourceCode)) + } + if (Persistence.persistence.binding(uiSourceCode)) { return true; + } return uiSourceCode.contentType().isStyleSheet(); } @@ -69,13 +74,15 @@ */ _formatSourceInPlace(event) { const uiSourceCode = this._sourcesView.currentUISourceCode(); - if (!this._isFormattable(uiSourceCode)) + if (!this._isFormattable(uiSourceCode)) { return; + } - if (uiSourceCode.isDirty()) + if (uiSourceCode.isDirty()) { contentLoaded.call(this, uiSourceCode.workingCopy()); - else + } else { uiSourceCode.requestContent().then(contentLoaded.bind(this)); + } /** * @this {Sources.InplaceFormatterEditorAction} @@ -92,8 +99,9 @@ * @param {!Formatter.FormatterSourceMapping} formatterMapping */ function innerCallback(formattedContent, formatterMapping) { - if (uiSourceCode.workingCopy() === formattedContent) + if (uiSourceCode.workingCopy() === formattedContent) { return; + } const sourceFrame = this._sourcesView.viewForFile(uiSourceCode); let start = [0, 0]; if (sourceFrame) {
diff --git a/third_party/blink/renderer/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js index 44f19e1..fdd14af 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/sources/JavaScriptBreakpointsSidebarPane.js
@@ -91,8 +91,9 @@ promises.push( this._resetEntry(/** @type {!Element}*/ (entry), uiLocation, isSelected, hasEnabled, hasDisabled, showCoumn)); entry[Sources.JavaScriptBreakpointsSidebarPane._breakpointLocationsSymbol] = locations; - if (isSelected) + if (isSelected) { shouldShowView = true; + } entry = entry.nextSibling; } while (entry) { @@ -100,8 +101,9 @@ entry.remove(); entry = next; } - if (shouldShowView) + if (shouldShowView) { UI.viewManager.showView('sources.jsBreakpoints'); + } this._listElement.classList.toggle( 'breakpoints-list-deactivated', !Common.moduleSetting('breakpointsActive').get()); return Promise.all(promises).then(() => this._didUpdateForTest()); @@ -144,8 +146,9 @@ */ _breakpointLocations(event) { const node = event.target.enclosingNodeOrSelfWithClass('breakpoint-entry'); - if (!node) + if (!node) { return []; + } return node[Sources.JavaScriptBreakpointsSidebarPane._breakpointLocationsSymbol] || []; } @@ -155,8 +158,9 @@ _breakpointCheckboxClicked(event) { const breakpoints = this._breakpointLocations(event).map(breakpointLocation => breakpointLocation.breakpoint); const newState = event.target.checkboxElement.checked; - for (const breakpoint of breakpoints) + for (const breakpoint of breakpoints) { breakpoint.setEnabled(newState); + } event.consume(); } @@ -167,11 +171,13 @@ const uiLocations = this._breakpointLocations(event).map(breakpointLocation => breakpointLocation.uiLocation); let uiLocation = null; for (const uiLocationCandidate of uiLocations) { - if (!uiLocation || uiLocationCandidate.columnNumber < uiLocation.columnNumber) + if (!uiLocation || uiLocationCandidate.columnNumber < uiLocation.columnNumber) { uiLocation = uiLocationCandidate; + } } - if (uiLocation) + if (uiLocation) { Common.Revealer.reveal(uiLocation); + } } /** @@ -212,13 +218,15 @@ * @param {boolean} toggleState */ _toggleAllBreakpoints(toggleState) { - for (const breakpointLocation of this._breakpointManager.allBreakpointLocations()) + for (const breakpointLocation of this._breakpointManager.allBreakpointLocations()) { breakpointLocation.breakpoint.setEnabled(toggleState); + } } _removeAllBreakpoints() { - for (const breakpointLocation of this._breakpointManager.allBreakpointLocations()) + for (const breakpointLocation of this._breakpointManager.allBreakpointLocations()) { breakpointLocation.breakpoint.remove(false /* keepInStorage */); + } } /** @@ -226,8 +234,9 @@ */ _removeOtherBreakpoints(selectedBreakpoints) { for (const breakpointLocation of this._breakpointManager.allBreakpointLocations()) { - if (!selectedBreakpoints.has(breakpointLocation.breakpoint)) + if (!selectedBreakpoints.has(breakpointLocation.breakpoint)) { breakpointLocation.breakpoint.remove(false /* keepInStorage */); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/JavaScriptCompilerPlugin.js b/third_party/blink/renderer/devtools/front_end/sources/JavaScriptCompilerPlugin.js index 9e87115..69f1edb55 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/JavaScriptCompilerPlugin.js +++ b/third_party/blink/renderer/devtools/front_end/sources/JavaScriptCompilerPlugin.js
@@ -19,8 +19,9 @@ this._disposed = false; this._textEditor.addEventListener(UI.TextEditor.Events.TextChanged, this._scheduleCompile, this); - if (this._uiSourceCode.hasCommits() || this._uiSourceCode.isDirty()) + if (this._uiSourceCode.hasCommits() || this._uiSourceCode.isDirty()) { this._scheduleCompile(); + } } /** @@ -29,13 +30,16 @@ * @return {boolean} */ static accepts(uiSourceCode) { - if (uiSourceCode.extension() === 'js') + if (uiSourceCode.extension() === 'js') { return true; - if (Snippets.isSnippetsUISourceCode(uiSourceCode)) + } + if (Snippets.isSnippetsUISourceCode(uiSourceCode)) { return true; + } for (const debuggerModel of SDK.targetManager.models(SDK.DebuggerModel)) { - if (Bindings.debuggerWorkspaceBinding.scriptFile(uiSourceCode, debuggerModel)) + if (Bindings.debuggerWorkspaceBinding.scriptFile(uiSourceCode, debuggerModel)) { return true; + } } return false; } @@ -45,8 +49,9 @@ this._recompileScheduled = true; return; } - if (this._timeout) + if (this._timeout) { clearTimeout(this._timeout); + } this._timeout = setTimeout(this._compile.bind(this), Sources.JavaScriptCompilerPlugin.CompileDelay); } @@ -57,23 +62,27 @@ const debuggerModels = SDK.targetManager.models(SDK.DebuggerModel); for (let i = 0; i < debuggerModels.length; ++i) { const scriptFile = Bindings.debuggerWorkspaceBinding.scriptFile(this._uiSourceCode, debuggerModels[i]); - if (scriptFile) + if (scriptFile) { return debuggerModels[i].runtimeModel(); + } } return SDK.targetManager.mainTarget() ? SDK.targetManager.mainTarget().model(SDK.RuntimeModel) : null; } async _compile() { const runtimeModel = this._findRuntimeModel(); - if (!runtimeModel) + if (!runtimeModel) { return; + } const currentExecutionContext = UI.context.flavor(SDK.ExecutionContext); - if (!currentExecutionContext) + if (!currentExecutionContext) { return; + } const code = this._textEditor.text(); - if (code.length > 1024 * 100) + if (code.length > 1024 * 100) { return; + } this._compiling = true; const result = await runtimeModel.compileScript(code, '', false, currentExecutionContext.id); @@ -84,10 +93,12 @@ this._scheduleCompile(); return; } - if (this._message) + if (this._message) { this._uiSourceCode.removeMessage(this._message); - if (this._disposed || !result || !result.exceptionDetails) + } + if (this._disposed || !result || !result.exceptionDetails) { return; + } const exceptionDetails = result.exceptionDetails; const text = SDK.RuntimeModel.simpleTextFromException(exceptionDetails); @@ -104,11 +115,13 @@ */ dispose() { this._textEditor.removeEventListener(UI.TextEditor.Events.TextChanged, this._scheduleCompile, this); - if (this._message) + if (this._message) { this._uiSourceCode.removeMessage(this._message); + } this._disposed = true; - if (this._timeout) + if (this._timeout) { clearTimeout(this._timeout); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js b/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js index 4126950..d6a6e31c6a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js +++ b/third_party/blink/renderer/devtools/front_end/sources/NavigatorView.js
@@ -81,8 +81,9 @@ * @param {!UI.TreeElement} treeElement */ static _treeElementOrder(treeElement) { - if (treeElement._boostOrder) + if (treeElement._boostOrder) { return 0; + } if (!Sources.NavigatorView._typeOrders) { const weights = {}; @@ -102,14 +103,15 @@ let order = Sources.NavigatorView._typeOrders[treeElement._nodeType]; if (treeElement._uiSourceCode) { const contentType = treeElement._uiSourceCode.contentType(); - if (contentType.isDocument()) + if (contentType.isDocument()) { order += 3; - else if (contentType.isScript()) + } else if (contentType.isScript()) { order += 5; - else if (contentType.isStyleSheet()) + } else if (contentType.isStyleSheet()) { order += 10; - else + } else { order += 15; + } } return order; @@ -141,10 +143,12 @@ const typeWeight1 = Sources.NavigatorView._treeElementOrder(treeElement1); const typeWeight2 = Sources.NavigatorView._treeElementOrder(treeElement2); - if (typeWeight1 > typeWeight2) + if (typeWeight1 > typeWeight2) { return 1; - if (typeWeight1 < typeWeight2) + } + if (typeWeight1 < typeWeight2) { return -1; + } return treeElement1.titleAsText().compareTo(treeElement2.titleAsText()); } @@ -164,10 +168,11 @@ */ function updateVisibility() { const showTree = this._scriptsTree.firstChild(); - if (showTree) + if (showTree) { placeholder.hideWidget(); - else + } else { placeholder.showWidget(); + } this._scriptsTree.element.classList.toggle('hidden', !showTree); } } @@ -180,11 +185,13 @@ // Update UISourceCode titles. const networkNodes = this._uiSourceCodeNodes.get(binding.network); - for (const networkNode of networkNodes) + for (const networkNode of networkNodes) { networkNode.updateTitle(); + } const fileSystemNodes = this._uiSourceCodeNodes.get(binding.fileSystem); - for (const fileSystemNode of fileSystemNodes) + for (const fileSystemNode of fileSystemNodes) { fileSystemNode.updateTitle(); + } // Update folder titles. const pathTokens = Persistence.FileSystemWorkspaceBinding.relativePath(binding.fileSystem); @@ -194,15 +201,17 @@ const folderId = this._folderNodeId(binding.fileSystem.project(), null, null, binding.fileSystem.origin(), folderPath); const folderNode = this._subfolderNodes.get(folderId); - if (folderNode) + if (folderNode) { folderNode.updateTitle(); + } folderPath += '/'; } // Update fileSystem root title. const fileSystemRoot = this._rootNode.child(binding.fileSystem.project().id()); - if (fileSystemRoot) + if (fileSystemRoot) { fileSystemRoot.updateTitle(); + } } /** @@ -222,14 +231,16 @@ this._workspace.addEventListener(Workspace.Workspace.Events.ProjectAdded, event => { const project = /** @type {!Workspace.Project} */ (event.data); this._projectAdded(project); - if (project.type() === Workspace.projectTypes.FileSystem) + if (project.type() === Workspace.projectTypes.FileSystem) { this._computeUniqueFileSystemProjectNames(); + } }); this._workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, event => { const project = /** @type {!Workspace.Project} */ (event.data); this._removeProject(project); - if (project.type() === Workspace.projectTypes.FileSystem) + if (project.type() === Workspace.projectTypes.FileSystem) { this._computeUniqueFileSystemProjectNames(); + } }); this._workspace.projects().forEach(this._projectAdded.bind(this)); this._computeUniqueFileSystemProjectNames(); @@ -256,8 +267,9 @@ */ _frameAttributionAdded(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data.uiSourceCode); - if (!this._acceptsUISourceCode(uiSourceCode)) + if (!this._acceptsUISourceCode(uiSourceCode)) { return; + } const addedFrame = /** @type {?SDK.ResourceTreeFrame} */ (event.data.frame); // This event does not happen for UISourceCodes without initial attribution. @@ -269,8 +281,9 @@ */ _frameAttributionRemoved(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data.uiSourceCode); - if (!this._acceptsUISourceCode(uiSourceCode)) + if (!this._acceptsUISourceCode(uiSourceCode)) { return; + } const removedFrame = /** @type {?SDK.ResourceTreeFrame} */ (event.data.frame); const node = Array.from(this._uiSourceCodeNodes.get(uiSourceCode)).find(node => node.frame() === removedFrame); @@ -289,13 +302,15 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _addUISourceCode(uiSourceCode) { - if (!this._acceptsUISourceCode(uiSourceCode)) + if (!this._acceptsUISourceCode(uiSourceCode)) { return; + } const frames = Bindings.NetworkProject.framesForUISourceCode(uiSourceCode); if (frames.length) { - for (const frame of frames) + for (const frame of frames) { this._addUISourceCodeNode(uiSourceCode, frame); + } } else { this._addUISourceCodeNode(uiSourceCode, null); } @@ -309,10 +324,11 @@ _addUISourceCodeNode(uiSourceCode, frame) { const isFromSourceMap = uiSourceCode.contentType().isFromSourceMap(); let path; - if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) + if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem) { path = Persistence.FileSystemWorkspaceBinding.relativePath(uiSourceCode).slice(0, -1); - else + } else { path = Common.ParsedURL.extractPath(uiSourceCode.url()).split('/').slice(1, -1); + } const project = uiSourceCode.project(); const target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); @@ -360,8 +376,9 @@ */ _projectAdded(project) { if (!this.acceptProject(project) || project.type() !== Workspace.projectTypes.FileSystem || - Snippets.isSnippetsProject(project) || this._rootNode.child(project.id())) + Snippets.isSnippetsProject(project) || this._rootNode.child(project.id())) { return; + } this._rootNode.appendChild(new Sources.NavigatorGroupTreeNode( this, project, project.id(), Sources.NavigatorView.Types.FileSystem, project.displayName())); this._selectDefaultTreeNode(); @@ -370,22 +387,25 @@ // TODO(einbinder) remove this code after crbug.com/964075 is fixed _selectDefaultTreeNode() { const children = this._rootNode.children(); - if (children.length && !this._scriptsTree.selectedTreeElement) + if (children.length && !this._scriptsTree.selectedTreeElement) { children[0].treeNode().select(true /* omitFocus */, false /* selectedByUser */); + } } _computeUniqueFileSystemProjectNames() { const fileSystemProjects = this._workspace.projectsForType(Workspace.projectTypes.FileSystem); - if (!fileSystemProjects.length) + if (!fileSystemProjects.length) { return; + } const encoder = new Persistence.PathEncoder(); const reversedPaths = fileSystemProjects.map(project => { const fileSystem = /** @type {!Persistence.FileSystemWorkspaceBinding.FileSystem} */ (project); return encoder.encode(fileSystem.fileSystemPath()).reverse(); }); const reversedIndex = new Common.Trie(); - for (const reversedPath of reversedPaths) + for (const reversedPath of reversedPaths) { reversedIndex.add(reversedPath); + } for (let i = 0; i < fileSystemProjects.length; ++i) { const reversedPath = reversedPaths[i]; @@ -395,8 +415,9 @@ reversedIndex.add(reversedPath); const path = encoder.decode(reversedPath.substring(0, commonPrefix.length + 1).reverse()); const fileSystemNode = this._rootNode.child(project.id()); - if (fileSystemNode) + if (fileSystemNode) { fileSystemNode.setTitle(path); + } } } @@ -405,13 +426,16 @@ */ _removeProject(project) { const uiSourceCodes = project.uiSourceCodes(); - for (let i = 0; i < uiSourceCodes.length; ++i) + for (let i = 0; i < uiSourceCodes.length; ++i) { this._removeUISourceCode(uiSourceCodes[i]); - if (project.type() !== Workspace.projectTypes.FileSystem) + } + if (project.type() !== Workspace.projectTypes.FileSystem) { return; + } const fileSystemNode = this._rootNode.child(project.id()); - if (!fileSystemNode) + if (!fileSystemNode) { return; + } this._rootNode.removeChild(fileSystemNode); } @@ -441,29 +465,34 @@ * @return {!Sources.NavigatorTreeNode} */ _folderNode(uiSourceCode, project, target, frame, projectOrigin, path, fromSourceMap) { - if (Snippets.isSnippetsUISourceCode(uiSourceCode)) + if (Snippets.isSnippetsUISourceCode(uiSourceCode)) { return this._rootNode; + } - if (target && !this._groupByFolder && !fromSourceMap) + if (target && !this._groupByFolder && !fromSourceMap) { return this._domainNode(uiSourceCode, project, target, frame, projectOrigin); + } const folderPath = path.join('/'); const folderId = this._folderNodeId(project, target, frame, projectOrigin, folderPath); let folderNode = this._subfolderNodes.get(folderId); - if (folderNode) + if (folderNode) { return folderNode; + } if (!path.length) { - if (target) + if (target) { return this._domainNode(uiSourceCode, project, target, frame, projectOrigin); + } return /** @type {!Sources.NavigatorTreeNode} */ (this._rootNode.child(project.id())); } const parentNode = this._folderNode(uiSourceCode, project, target, frame, projectOrigin, path.slice(0, -1), fromSourceMap); let type = fromSourceMap ? Sources.NavigatorView.Types.SourceMapFolder : Sources.NavigatorView.Types.NetworkFolder; - if (project.type() === Workspace.projectTypes.FileSystem) + if (project.type() === Workspace.projectTypes.FileSystem) { type = Sources.NavigatorView.Types.FileSystemFolder; + } const name = path[path.length - 1]; folderNode = new Sources.NavigatorFolderTreeNode(this, project, folderId, type, folderPath, name); @@ -482,17 +511,20 @@ */ _domainNode(uiSourceCode, project, target, frame, projectOrigin) { const frameNode = this._frameNode(project, target, frame); - if (!this._groupByDomain) + if (!this._groupByDomain) { return frameNode; + } let domainNode = frameNode.child(projectOrigin); - if (domainNode) + if (domainNode) { return domainNode; + } domainNode = new Sources.NavigatorGroupTreeNode( this, project, projectOrigin, Sources.NavigatorView.Types.Domain, this._computeProjectDisplayName(target, projectOrigin)); - if (frame && projectOrigin === Common.ParsedURL.extractOrigin(frame.url)) + if (frame && projectOrigin === Common.ParsedURL.extractOrigin(frame.url)) { domainNode.treeNode()._boostOrder = true; + } frameNode.appendChild(domainNode); return domainNode; } @@ -504,12 +536,14 @@ * @return {!Sources.NavigatorTreeNode} */ _frameNode(project, target, frame) { - if (!this._groupByFrame || !frame) + if (!this._groupByFrame || !frame) { return this._targetNode(project, target); + } let frameNode = this._frameNodes.get(frame); - if (frameNode) + if (frameNode) { return frameNode; + } frameNode = new Sources.NavigatorGroupTreeNode( this, project, target.id() + ':' + frame.id, Sources.NavigatorView.Types.Frame, frame.displayName()); @@ -530,8 +564,9 @@ function hoverCallback(hovered) { if (hovered) { const overlayModel = target.model(SDK.OverlayModel); - if (overlayModel) + if (overlayModel) { overlayModel.highlightFrame(frame.id); + } } else { SDK.OverlayModel.hideDOMNodeHighlight(); } @@ -545,8 +580,9 @@ * @return {!Sources.NavigatorTreeNode} */ _targetNode(project, target) { - if (target === SDK.targetManager.mainTarget()) + if (target === SDK.targetManager.mainTarget()) { return this._rootNode; + } let targetNode = this._rootNode.child('target:' + target.id()); if (!targetNode) { @@ -569,12 +605,14 @@ const runtimeModel = target.model(SDK.RuntimeModel); const executionContexts = runtimeModel ? runtimeModel.executionContexts() : []; for (const context of executionContexts) { - if (context.name && context.origin && projectOrigin.startsWith(context.origin)) + if (context.name && context.origin && projectOrigin.startsWith(context.origin)) { return context.name; + } } - if (!projectOrigin) + if (!projectOrigin) { return Common.UIString('(no domain)'); + } const parsedURL = new Common.ParsedURL(projectOrigin); const prettyURL = parsedURL.isValid ? parsedURL.host + (parsedURL.port ? (':' + parsedURL.port) : '') : ''; @@ -590,10 +628,12 @@ revealUISourceCode(uiSourceCode, select) { const nodes = this._uiSourceCodeNodes.get(uiSourceCode); const node = nodes.firstValue(); - if (!node) + if (!node) { return null; - if (this._scriptsTree.selectedTreeElement) + } + if (this._scriptsTree.selectedTreeElement) { this._scriptsTree.selectedTreeElement.deselect(); + } this._lastSelectedUISourceCode = uiSourceCode; // TODO(dgozman): figure out revealing multiple. node.reveal(select); @@ -614,8 +654,9 @@ */ _removeUISourceCode(uiSourceCode) { const nodes = this._uiSourceCodeNodes.get(uiSourceCode); - for (const node of nodes) + for (const node of nodes) { this._removeUISourceCodeNode(node); + } } /** @@ -634,12 +675,15 @@ while (node) { parentNode = node.parent; - if (!parentNode || !node.isEmpty()) + if (!parentNode || !node.isEmpty()) { break; - if (parentNode === this._rootNode && project.type() === Workspace.projectTypes.FileSystem) + } + if (parentNode === this._rootNode && project.type() === Workspace.projectTypes.FileSystem) { break; - if (!(node instanceof Sources.NavigatorGroupTreeNode || node instanceof Sources.NavigatorFolderTreeNode)) + } + if (!(node instanceof Sources.NavigatorGroupTreeNode || node instanceof Sources.NavigatorFolderTreeNode)) { break; + } if (node._type === Sources.NavigatorView.Types.Frame) { this._discardFrame(/** @type {!SDK.ResourceTreeFrame} */ (frame)); break; @@ -653,8 +697,9 @@ } reset() { - for (const node of this._uiSourceCodeNodes.valuesArray()) + for (const node of this._uiSourceCodeNodes.valuesArray()) { node.dispose(); + } this._scriptsTree.removeChildren(); this._uiSourceCodeNodes.clear(); @@ -674,8 +719,9 @@ */ _renameShortcut() { const node = this._scriptsTree.selectedTreeElement && this._scriptsTree.selectedTreeElement._node; - if (!node || !node._uiSourceCode || !node._uiSourceCode.canRename()) + if (!node || !node._uiSourceCode || !node._uiSourceCode.canRename()) { return false; + } this.rename(node, false); return true; } @@ -719,8 +765,9 @@ */ _handleContextMenuDelete(uiSourceCode) { const shouldDelete = window.confirm(Common.UIString('Are you sure you want to delete this file?')); - if (shouldDelete) + if (shouldDelete) { uiSourceCode.project().deleteFile(uiSourceCode); + } } /** @@ -775,14 +822,16 @@ function removeFolder() { const shouldRemove = window.confirm(Common.UIString('Are you sure you want to remove this folder?')); - if (shouldRemove) + if (shouldRemove) { project.remove(); + } } if (project.type() === Workspace.projectTypes.FileSystem) { contextMenu.defaultSection().appendAction('sources.add-folder-to-workspace', undefined, true); - if (node instanceof Sources.NavigatorGroupTreeNode) + if (node instanceof Sources.NavigatorGroupTreeNode) { contextMenu.defaultSection().appendItem(Common.UIString('Remove folder from workspace'), removeFolder); + } } contextMenu.show(); @@ -802,12 +851,14 @@ * @param {boolean} committed */ function callback(committed) { - if (!creatingNewUISourceCode) + if (!creatingNewUISourceCode) { return; - if (!committed) + } + if (!committed) { uiSourceCode.remove(); - else if (node._treeElement.listItemElement.hasFocus()) + } else if (node._treeElement.listItemElement.hasFocus()) { this._sourceSelected(uiSourceCode, true); + } } } @@ -818,15 +869,18 @@ */ async create(project, path, uiSourceCodeToCopy) { let content = ''; - if (uiSourceCodeToCopy) + if (uiSourceCodeToCopy) { content = (await uiSourceCodeToCopy.requestContent()) || ''; + } const uiSourceCode = await project.createFile(path, null, content); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } this._sourceSelected(uiSourceCode, false); const node = this.revealUISourceCode(uiSourceCode, true); - if (node) + if (node) { this.rename(node, true); + } } _groupingChanged() { @@ -851,14 +905,17 @@ */ _discardFrame(frame) { const node = this._frameNodes.get(frame); - if (!node) + if (!node) { return; + } - if (node.parent) + if (node.parent) { node.parent.removeChild(node); + } this._frameNodes.delete(frame); - for (const child of frame.childFrames) + for (const child of frame.childFrames) { this._discardFrame(child); + } } /** @@ -874,8 +931,9 @@ */ targetRemoved(target) { const targetNode = this._rootNode.child('target:' + target.id()); - if (targetNode) + if (targetNode) { this._rootNode.removeChild(targetNode); + } } /** @@ -884,8 +942,9 @@ _targetNameChanged(event) { const target = /** @type {!SDK.Target} */ (event.data); const targetNode = this._rootNode.child('target:' + target.id()); - if (targetNode) + if (targetNode) { targetNode.setTitle(target.name()); + } } }; @@ -920,12 +979,13 @@ this._navigatorView = navigatorView; this._hoverCallback = hoverCallback; let iconType = 'largeicon-navigator-folder'; - if (type === Sources.NavigatorView.Types.Domain) + if (type === Sources.NavigatorView.Types.Domain) { iconType = 'largeicon-navigator-domain'; - else if (type === Sources.NavigatorView.Types.Frame) + } else if (type === Sources.NavigatorView.Types.Frame) { iconType = 'largeicon-navigator-frame'; - else if (type === Sources.NavigatorView.Types.Worker) + } else if (type === Sources.NavigatorView.Types.Worker) { iconType = 'largeicon-navigator-worker'; + } this.setLeadingIcons([UI.Icon.create(iconType, 'icon')]); } @@ -966,8 +1026,9 @@ * @param {!Event} event */ _handleContextMenuEvent(event) { - if (!this._node) + if (!this._node) { return; + } this.select(); this._navigatorView.handleFolderContextMenu(event, this._node); } @@ -976,8 +1037,9 @@ * @param {!Event} event */ _mouseMove(event) { - if (this._hovered || !this._hoverCallback) + if (this._hovered || !this._hoverCallback) { return; + } this._hovered = true; this._hoverCallback(true); } @@ -986,8 +1048,9 @@ * @param {!Event} event */ _mouseLeave(event) { - if (!this._hoverCallback) + if (!this._hoverCallback) { return; + } this._hovered = false; this._hoverCallback(false); } @@ -1021,21 +1084,24 @@ if (binding) { const container = createElementWithClass('span', 'icon-stack'); let iconType = 'largeicon-navigator-file-sync'; - if (Snippets.isSnippetsUISourceCode(binding.fileSystem)) + if (Snippets.isSnippetsUISourceCode(binding.fileSystem)) { iconType = 'largeicon-navigator-snippet'; + } const icon = UI.Icon.create(iconType, 'icon'); const badge = UI.Icon.create('badge-navigator-file-sync', 'icon-badge'); // TODO(allada) This does not play well with dark theme. Add an actual icon and use it. - if (Persistence.networkPersistenceManager.project() === binding.fileSystem.project()) + if (Persistence.networkPersistenceManager.project() === binding.fileSystem.project()) { badge.style.filter = 'hue-rotate(160deg)'; + } container.appendChild(icon); container.appendChild(badge); container.title = Persistence.PersistenceUtils.tooltipForUISourceCode(this._uiSourceCode); this.setLeadingIcons([container]); } else { let iconType = 'largeicon-navigator-file'; - if (Snippets.isSnippetsUISourceCode(this._uiSourceCode)) + if (Snippets.isSnippetsUISourceCode(this._uiSourceCode)) { iconType = 'largeicon-navigator-snippet'; + } const defaultIcon = UI.Icon.create(iconType, 'icon'); this.setLeadingIcons([defaultIcon]); } @@ -1059,8 +1125,9 @@ } _shouldRenameOnMouseDown() { - if (!this._uiSourceCode.canRename()) + if (!this._uiSourceCode.canRename()) { return false; + } const isSelected = this === this.treeOutline.selectedTreeElement; return isSelected && this.treeOutline.element.hasFocus() && !UI.isBeingEdited(this.treeOutline.element); } @@ -1079,8 +1146,9 @@ * @this {Sources.NavigatorSourceTreeElement} */ function rename() { - if (this._shouldRenameOnMouseDown()) + if (this._shouldRenameOnMouseDown()) { this._navigatorView.rename(this._node, false); + } } } @@ -1194,34 +1262,39 @@ } populate() { - if (this.isPopulated()) + if (this.isPopulated()) { return; - if (this.parent) + } + if (this.parent) { this.parent.populate(); + } this._populated = true; this.wasPopulated(); } wasPopulated() { const children = this.children(); - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { this.treeNode().appendChild(/** @type {!UI.TreeElement} */ (children[i].treeNode())); + } } /** * @param {!Sources.NavigatorTreeNode} node */ didAddChild(node) { - if (this.isPopulated()) + if (this.isPopulated()) { this.treeNode().appendChild(/** @type {!UI.TreeElement} */ (node.treeNode())); + } } /** * @param {!Sources.NavigatorTreeNode} node */ willRemoveChild(node) { - if (this.isPopulated()) + if (this.isPopulated()) { this.treeNode().removeChild(/** @type {!UI.TreeElement} */ (node.treeNode())); + } } /** @@ -1343,8 +1416,9 @@ * @return {!UI.TreeElement} */ treeNode() { - if (this._treeElement) + if (this._treeElement) { return this._treeElement; + } this._treeElement = new Sources.NavigatorSourceTreeElement(this._navigatorView, this._uiSourceCode, '', this); this.updateTitle(); @@ -1362,19 +1436,22 @@ * @param {boolean=} ignoreIsDirty */ updateTitle(ignoreIsDirty) { - if (!this._treeElement) + if (!this._treeElement) { return; + } let titleText = this._uiSourceCode.displayName(); - if (!ignoreIsDirty && this._uiSourceCode.isDirty()) + if (!ignoreIsDirty && this._uiSourceCode.isDirty()) { titleText = '*' + titleText; + } this._treeElement.title = titleText; this._treeElement.updateIcon(); let tooltip = this._uiSourceCode.url(); - if (this._uiSourceCode.contentType().isFromSourceMap()) + if (this._uiSourceCode.contentType().isFromSourceMap()) { tooltip = Common.UIString('%s (from source map)', this._uiSourceCode.displayName()); + } this._treeElement.tooltip = tooltip; } @@ -1400,16 +1477,18 @@ this.parent.populate(); this.parent.treeNode().expand(); this._treeElement.reveal(true); - if (select) + if (select) { this._treeElement.select(true); + } } /** * @param {function(boolean)=} callback */ rename(callback) { - if (!this._treeElement) + if (!this._treeElement) { return; + } this._treeElement.listItemElement.focus(); @@ -1453,8 +1532,9 @@ function afterEditing(committed) { UI.markBeingEdited(treeOutlineElement, false); this.updateTitle(); - if (callback) + if (callback) { callback(committed); + } } this.updateTitle(true); @@ -1488,16 +1568,18 @@ * @return {!UI.TreeElement} */ treeNode() { - if (this._treeElement) + if (this._treeElement) { return this._treeElement; + } this._treeElement = this._createTreeElement(this._title, this); this.updateTitle(); return this._treeElement; } updateTitle() { - if (!this._treeElement || this._project.type() !== Workspace.projectTypes.FileSystem) + if (!this._treeElement || this._project.type() !== Workspace.projectTypes.FileSystem) { return; + } const absoluteFileSystemPath = Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id()) + '/' + this._folderPath; const hasMappedFiles = Persistence.persistence.filePathHasBindings(absoluteFileSystemPath); @@ -1523,8 +1605,9 @@ * @override */ wasPopulated() { - if (!this._treeElement || this._treeElement._node !== this) + if (!this._treeElement || this._treeElement._node !== this) { return; + } this._addChildrenRecursive(); } @@ -1533,8 +1616,9 @@ for (let i = 0; i < children.length; ++i) { const child = children[i]; this.didAddChild(child); - if (child instanceof Sources.NavigatorFolderTreeNode) + if (child instanceof Sources.NavigatorFolderTreeNode) { child._addChildrenRecursive(); + } } } @@ -1551,8 +1635,9 @@ return node._title; } - if (!this._treeElement) + if (!this._treeElement) { return; + } let children = this.children(); @@ -1565,8 +1650,9 @@ } let oldNode; - if (children.length === 2) + if (children.length === 2) { oldNode = children[0] !== node ? children[0] : children[1]; + } if (oldNode && oldNode._isMerged) { delete oldNode._isMerged; const mergedToNodes = []; @@ -1598,19 +1684,22 @@ } const oldTreeElement = this._treeElement; const treeElement = this._createTreeElement(titleText, this); - for (let i = 0; i < mergedToNodes.length; ++i) + for (let i = 0; i < mergedToNodes.length; ++i) { mergedToNodes[i]._treeElement = treeElement; + } oldTreeElement.parent.appendChild(treeElement); oldTreeElement.setNode(nodes[nodes.length - 1]); oldTreeElement.title = nodes.map(titleForNode).join('/'); oldTreeElement.parent.removeChild(oldTreeElement); this._treeElement.appendChild(oldTreeElement); - if (oldTreeElement.expanded) + if (oldTreeElement.expanded) { treeElement.expand(); + } } - if (this.isPopulated()) + if (this.isPopulated()) { this._treeElement.appendChild(node.treeNode()); + } } /** @@ -1618,8 +1707,9 @@ * @param {!Sources.NavigatorTreeNode} node */ willRemoveChild(node) { - if (node._isMerged || !this.isPopulated()) + if (node._isMerged || !this.isPopulated()) { return; + } this._treeElement.removeChild(node._treeElement); } }; @@ -1655,8 +1745,9 @@ * @return {!UI.TreeElement} */ treeNode() { - if (this._treeElement) + if (this._treeElement) { return this._treeElement; + } this._treeElement = new Sources.NavigatorFolderTreeElement(this._navigatorView, this._type, this._title, this._hoverCallback); this._treeElement.setNode(this); @@ -1671,20 +1762,24 @@ } updateTitle() { - if (!this._treeElement || this._project.type() !== Workspace.projectTypes.FileSystem) + if (!this._treeElement || this._project.type() !== Workspace.projectTypes.FileSystem) { return; + } const fileSystemPath = Persistence.FileSystemWorkspaceBinding.fileSystemPath(this._project.id()); const wasActive = this._treeElement.listItemElement.classList.contains('has-mapped-files'); const isActive = Persistence.persistence.filePathHasBindings(fileSystemPath); - if (wasActive === isActive) + if (wasActive === isActive) { return; + } this._treeElement.listItemElement.classList.toggle('has-mapped-files', isActive); - if (this._treeElement.childrenListElement.hasFocus()) + if (this._treeElement.childrenListElement.hasFocus()) { return; - if (isActive) + } + if (isActive) { this._treeElement.expand(); - else + } else { this._treeElement.collapse(); + } } /** @@ -1693,7 +1788,8 @@ */ setTitle(title) { this._title = title; - if (this._treeElement) + if (this._treeElement) { this._treeElement.title = this._title; + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/OpenFileQuickOpen.js b/third_party/blink/renderer/devtools/front_end/sources/OpenFileQuickOpen.js index 39dfe70..0afe84f 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/OpenFileQuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/sources/OpenFileQuickOpen.js
@@ -22,12 +22,14 @@ uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber) { Host.userMetrics.actionTaken(Host.UserMetrics.Action.SelectFileFromFilePicker); - if (!uiSourceCode) + if (!uiSourceCode) { return; - if (typeof lineNumber === 'number') + } + if (typeof lineNumber === 'number') { Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber)); - else + } else { Common.Revealer.reveal(uiSourceCode); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sources/OutlineQuickOpen.js b/third_party/blink/renderer/devtools/front_end/sources/OutlineQuickOpen.js index f5a525c..ac5c149 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/OutlineQuickOpen.js +++ b/third_party/blink/renderer/devtools/front_end/sources/OutlineQuickOpen.js
@@ -63,8 +63,9 @@ itemScoreAt(itemIndex, query) { const item = this._items[itemIndex]; const methodName = query.split('(')[0]; - if (methodName.toLowerCase() === item.title.toLowerCase()) + if (methodName.toLowerCase() === item.title.toLowerCase()) { return 1 / (1 + item.line); + } return -item.line - 1; } @@ -88,14 +89,17 @@ * @param {string} promptValue */ selectItem(itemIndex, promptValue) { - if (itemIndex === null) + if (itemIndex === null) { return; + } const uiSourceCode = this._currentUISourceCode(); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } const lineNumber = this._items[itemIndex].line; - if (!isNaN(lineNumber) && lineNumber >= 0) + if (!isNaN(lineNumber) && lineNumber >= 0) { Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, this._items[itemIndex].column)); + } } @@ -104,8 +108,9 @@ */ _currentUISourceCode() { const sourcesView = UI.context.flavor(Sources.SourcesView); - if (!sourcesView) + if (!sourcesView) { return null; + } return sourcesView.currentUISourceCode(); } @@ -114,10 +119,12 @@ * @return {string} */ notFoundText() { - if (!this._currentUISourceCode()) + if (!this._currentUISourceCode()) { return Common.UIString('No file selected.'); - if (!this._active) + } + if (!this._active) { return Common.UIString('Open a JavaScript or CSS file to see symbols'); + } return Common.UIString('No results found'); } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/ScopeChainSidebarPane.js b/third_party/blink/renderer/devtools/front_end/sources/ScopeChainSidebarPane.js index f1ac922..0c333e6 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/ScopeChainSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/sources/ScopeChainSidebarPane.js
@@ -79,8 +79,9 @@ case Protocol.Debugger.ScopeType.Local: foundLocalScope = true; emptyPlaceholder = Common.UIString('No variables'); - if (thisObject) + if (thisObject) { extraProperties.push(new SDK.RemoteObjectProperty('this', thisObject)); + } if (i === 0) { const exception = details.exception(); if (exception) { @@ -98,17 +99,19 @@ break; case Protocol.Debugger.ScopeType.Closure: const scopeName = scope.name(); - if (scopeName) + if (scopeName) { title = Common.UIString('Closure (%s)', UI.beautifyFunctionName(scopeName)); - else + } else { title = Common.UIString('Closure'); + } emptyPlaceholder = Common.UIString('No variables'); break; } let subtitle = scope.description(); - if (!title || title === subtitle) + if (!title || title === subtitle) { subtitle = undefined; + } const titleElement = createElementWithClass('div', 'scope-chain-sidebar-pane-section-header'); titleElement.createChild('div', 'scope-chain-sidebar-pane-section-subtitle').textContent = subtitle; @@ -119,10 +122,11 @@ true, extraProperties); this._expandController.watchSection(title + (subtitle ? ':' + subtitle : ''), section); - if (scope.type() === Protocol.Debugger.ScopeType.Global) + if (scope.type() === Protocol.Debugger.ScopeType.Global) { section.objectTreeElement().collapse(); - else if (!foundLocalScope || scope.type() === Protocol.Debugger.ScopeType.Local) + } else if (!foundLocalScope || scope.type() === Protocol.Debugger.ScopeType.Local) { section.objectTreeElement().expand(); + } section.element.classList.add('scope-chain-sidebar-pane-section'); this.contentElement.appendChild(section.element);
diff --git a/third_party/blink/renderer/devtools/front_end/sources/ScriptFormatterEditorAction.js b/third_party/blink/renderer/devtools/front_end/sources/ScriptFormatterEditorAction.js index 9706b778..fc9a1685 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/ScriptFormatterEditorAction.js +++ b/third_party/blink/renderer/devtools/front_end/sources/ScriptFormatterEditorAction.js
@@ -20,8 +20,9 @@ this._updateButton(uiSourceCode); if (this._isFormatableScript(uiSourceCode) && this._pathsToFormatOnLoad.has(uiSourceCode.url()) && - !Sources.sourceFormatter.hasFormatted(uiSourceCode)) + !Sources.sourceFormatter.hasFormatted(uiSourceCode)) { this._showFormatted(uiSourceCode); + } } /** @@ -31,11 +32,13 @@ const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data.uiSourceCode); const wasSelected = /** @type {boolean} */ (event.data.wasSelected); - if (wasSelected) + if (wasSelected) { this._updateButton(null); + } const original = Sources.sourceFormatter.discardFormattedUISourceCode(uiSourceCode); - if (original) + if (original) { this._pathsToFormatOnLoad.delete(original.url()); + } } /** @@ -51,8 +54,9 @@ * @return {!UI.ToolbarButton} */ button(sourcesView) { - if (this._button) + if (this._button) { return this._button; + } this._sourcesView = sourcesView; this._sourcesView.addEventListener(Sources.SourcesView.Events.EditorSelected, this._editorSelected.bind(this)); @@ -70,14 +74,18 @@ * @return {boolean} */ _isFormatableScript(uiSourceCode) { - if (!uiSourceCode) + if (!uiSourceCode) { return false; - if (uiSourceCode.project().canSetFileContent()) + } + if (uiSourceCode.project().canSetFileContent()) { return false; - if (uiSourceCode.project().type() === Workspace.projectTypes.Formatter) + } + if (uiSourceCode.project().type() === Workspace.projectTypes.Formatter) { return false; - if (Persistence.persistence.binding(uiSourceCode)) + } + if (Persistence.persistence.binding(uiSourceCode)) { return false; + } return uiSourceCode.contentType().hasScripts(); } @@ -86,8 +94,9 @@ */ _toggleFormatScriptSource(event) { const uiSourceCode = this._sourcesView.currentUISourceCode(); - if (!this._isFormatableScript(uiSourceCode)) + if (!this._isFormatableScript(uiSourceCode)) { return; + } this._pathsToFormatOnLoad.add(uiSourceCode.url()); this._showFormatted(uiSourceCode); } @@ -97,8 +106,9 @@ */ async _showFormatted(uiSourceCode) { const formatData = await Sources.sourceFormatter.format(uiSourceCode); - if (uiSourceCode !== this._sourcesView.currentUISourceCode()) + if (uiSourceCode !== this._sourcesView.currentUISourceCode()) { return; + } const sourceFrame = this._sourcesView.viewForFile(uiSourceCode); let start = [0, 0]; if (sourceFrame) {
diff --git a/third_party/blink/renderer/devtools/front_end/sources/ScriptOriginPlugin.js b/third_party/blink/renderer/devtools/front_end/sources/ScriptOriginPlugin.js index 706d4f2..a731ccc 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/ScriptOriginPlugin.js +++ b/third_party/blink/renderer/devtools/front_end/sources/ScriptOriginPlugin.js
@@ -35,8 +35,9 @@ // Handle anonymous scripts with an originStackTrace. const script = Sources.ScriptOriginPlugin._script(this._uiSourceCode); - if (!script || !script.originStackTrace) + if (!script || !script.originStackTrace) { return []; + } const link = Sources.ScriptOriginPlugin._linkifier.linkifyStackTraceTopFrame( script.debuggerModel.target(), script.originStackTrace); return [new UI.ToolbarItem(link)]; @@ -50,8 +51,9 @@ const locations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode, 0, 0); for (const location of locations) { const script = location.script(); - if (script.originStackTrace) + if (script.originStackTrace) { return script; + } } return null; }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SearchSourcesView.js b/third_party/blink/renderer/devtools/front_end/sources/SearchSourcesView.js index a6c0a3c..c27d3bf 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SearchSourcesView.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SearchSourcesView.js
@@ -54,8 +54,9 @@ _showSearch() { const selection = UI.inspectorView.element.window().getSelection(); let queryCandidate = ''; - if (selection.rangeCount) + if (selection.rangeCount) { queryCandidate = selection.toString().replace(/\r?\n.*/, ''); + } return Sources.SearchSourcesView.openSearch(queryCandidate); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SimpleHistoryManager.js b/third_party/blink/renderer/devtools/front_end/sources/SimpleHistoryManager.js index eb1ca562..8cd47747 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SimpleHistoryManager.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SimpleHistoryManager.js
@@ -74,15 +74,17 @@ * @param {function(!Sources.HistoryEntry):boolean} filterOutCallback */ filterOut(filterOutCallback) { - if (this.readOnly()) + if (this.readOnly()) { return; + } const filteredEntries = []; let removedBeforeActiveEntry = 0; for (let i = 0; i < this._entries.length; ++i) { - if (!filterOutCallback(this._entries[i])) + if (!filterOutCallback(this._entries[i])) { filteredEntries.push(this._entries[i]); - else if (i <= this._activeEntryIndex) + } else if (i <= this._activeEntryIndex) { ++removedBeforeActiveEntry; + } } this._entries = filteredEntries; this._activeEntryIndex = Math.max(0, this._activeEntryIndex - removedBeforeActiveEntry); @@ -106,13 +108,16 @@ * @param {!Sources.HistoryEntry} entry */ push(entry) { - if (this.readOnly()) + if (this.readOnly()) { return; - if (!this.empty()) + } + if (!this.empty()) { this._entries.splice(this._activeEntryIndex + 1); + } this._entries.push(entry); - if (this._entries.length > this._historyDepth) + if (this._entries.length > this._historyDepth) { this._entries.shift(); + } this._activeEntryIndex = this._entries.length - 1; } @@ -120,14 +125,17 @@ * @return {boolean} */ rollback() { - if (this.empty()) + if (this.empty()) { return false; + } let revealIndex = this._activeEntryIndex - 1; - while (revealIndex >= 0 && !this._entries[revealIndex].valid()) + while (revealIndex >= 0 && !this._entries[revealIndex].valid()) { --revealIndex; - if (revealIndex < 0) + } + if (revealIndex < 0) { return false; + } this.readOnlyLock(); this._entries[revealIndex].reveal(); @@ -143,10 +151,12 @@ rollover() { let revealIndex = this._activeEntryIndex + 1; - while (revealIndex < this._entries.length && !this._entries[revealIndex].valid()) + while (revealIndex < this._entries.length && !this._entries[revealIndex].valid()) { ++revealIndex; - if (revealIndex >= this._entries.length) + } + if (revealIndex >= this._entries.length) { return false; + } this.readOnlyLock(); this._entries[revealIndex].reveal();
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js b/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js index 09e70e6..668b10a 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js
@@ -50,8 +50,9 @@ _onUISourceCodeRemoved(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); const cacheEntry = this._formattedSourceCodes.get(uiSourceCode); - if (cacheEntry && cacheEntry.formatData) + if (cacheEntry && cacheEntry.formatData) { this._discardFormatData(cacheEntry.formatData); + } this._formattedSourceCodes.remove(uiSourceCode); } @@ -61,8 +62,9 @@ */ discardFormattedUISourceCode(formattedUISourceCode) { const formatData = Sources.SourceFormatData._for(formattedUISourceCode); - if (!formatData) + if (!formatData) { return null; + } this._discardFormatData(formatData); this._formattedSourceCodes.remove(formatData.originalSourceCode); return formatData.originalSourceCode; @@ -92,8 +94,9 @@ */ async format(uiSourceCode) { const cacheEntry = this._formattedSourceCodes.get(uiSourceCode); - if (cacheEntry) + if (cacheEntry) { return cacheEntry.promise; + } let fulfillFormatPromise; const resultPromise = new Promise(fulfill => { @@ -113,8 +116,9 @@ */ function formatDone(formattedContent, formatterMapping) { const cacheEntry = this._formattedSourceCodes.get(uiSourceCode); - if (!cacheEntry || cacheEntry.promise !== resultPromise) + if (!cacheEntry || cacheEntry.promise !== resultPromise) { return; + } let formattedURL; let count = 0; let suffix = ''; @@ -163,8 +167,9 @@ rawLocationToUILocation(rawLocation) { const script = rawLocation.script(); const formatData = script && Sources.SourceFormatData._for(script); - if (!formatData) + if (!formatData) { return null; + } const lineNumber = rawLocation.lineNumber; const columnNumber = rawLocation.columnNumber || 0; const formattedLocation = formatData.mapping.originalToFormatted(lineNumber, columnNumber); @@ -180,8 +185,9 @@ */ uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) { const formatData = Sources.SourceFormatData._for(uiSourceCode); - if (!formatData) + if (!formatData) { return []; + } const [originalLine, originalColumn] = formatData.mapping.formattedToOriginal(lineNumber, columnNumber); const scripts = this._scriptsForUISourceCode(formatData.originalSourceCode) .filter(script => script.containsLocation(originalLine, originalColumn)); @@ -194,17 +200,21 @@ */ _setSourceMappingEnabled(formatData, enabled) { const scripts = this._scriptsForUISourceCode(formatData.originalSourceCode); - if (!scripts.length) + if (!scripts.length) { return; - if (enabled) { - for (const script of scripts) - script[Sources.SourceFormatData._formatDataSymbol] = formatData; - } else { - for (const script of scripts) - delete script[Sources.SourceFormatData._formatDataSymbol]; } - for (const script of scripts) + if (enabled) { + for (const script of scripts) { + script[Sources.SourceFormatData._formatDataSymbol] = formatData; + } + } else { + for (const script of scripts) { + delete script[Sources.SourceFormatData._formatDataSymbol]; + } + } + for (const script of scripts) { Bindings.debuggerWorkspaceBinding.updateLocations(script); + } } /** @@ -246,8 +256,9 @@ rawLocationToUILocation(rawLocation) { const styleHeader = rawLocation.header(); const formatData = styleHeader && Sources.SourceFormatData._for(styleHeader); - if (!formatData) + if (!formatData) { return null; + } const formattedLocation = formatData.mapping.originalToFormatted(rawLocation.lineNumber, rawLocation.columnNumber || 0); return formatData.formattedSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]); @@ -260,8 +271,9 @@ */ uiLocationToRawLocations(uiLocation) { const formatData = Sources.SourceFormatData._for(uiLocation.uiSourceCode); - if (!formatData) + if (!formatData) { return []; + } const [originalLine, originalColumn] = formatData.mapping.formattedToOriginal(uiLocation.lineNumber, uiLocation.columnNumber); const headers = formatData.originalSourceCode[this._headersSymbol]; @@ -272,8 +284,9 @@ formatData.mapping.originalToFormatted(header.startLine, header.startColumn); const [originalEndLine, originalEndColumn] = formatData.mapping.formattedToOriginal(formattedStartLine, formattedStartColumn, header.contentLength); - if (header.containsLocation(originalLine, originalColumn, originalEndLine, originalEndColumn)) + if (header.containsLocation(originalLine, originalColumn, originalEndLine, originalEndColumn)) { locations.push(new SDK.CSSLocation(header, originalLine, originalColumn)); + } } return locations; }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourceMapNamesResolver.js b/third_party/blink/renderer/devtools/front_end/sources/SourceMapNamesResolver.js index cfd256f..8045d53 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourceMapNamesResolver.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourceMapNamesResolver.js
@@ -32,8 +32,9 @@ if (scope.type() === Protocol.Debugger.ScopeType.Global || !startLocation || !endLocation || !startLocation.script() || !startLocation.script().sourceMapURL || - (startLocation.script() !== endLocation.script())) + (startLocation.script() !== endLocation.script())) { return Promise.resolve(/** @type {!Array<!Sources.SourceMapNamesResolver.Identifier>}*/ ([])); + } const script = startLocation.script(); return script.requestContent().then(onContent); @@ -43,8 +44,9 @@ * @return {!Promise<!Array<!Sources.SourceMapNamesResolver.Identifier>>} */ function onContent(content) { - if (!content) + if (!content) { return Promise.resolve(/** @type {!Array<!Sources.SourceMapNamesResolver.Identifier>}*/ ([])); + } const text = new TextUtils.Text(content); const scopeRange = new TextUtils.TextRange( @@ -69,8 +71,9 @@ const cursor = new TextUtils.TextCursor(text.lineEndings()); for (let i = 0; i < identifiers.length; ++i) { const id = identifiers[i]; - if (id.offset < prefix.length) + if (id.offset < prefix.length) { continue; + } const start = scopeStart + id.offset - prefix.length; cursor.resetTo(start); result.push(new Sources.SourceMapNamesResolver.Identifier(id.name, cursor.lineNumber(), cursor.columnNumber())); @@ -85,13 +88,15 @@ */ Sources.SourceMapNamesResolver._resolveScope = function(scope) { let identifiersPromise = scope[Sources.SourceMapNamesResolver._cachedIdentifiersSymbol]; - if (identifiersPromise) + if (identifiersPromise) { return identifiersPromise; + } const script = scope.callFrame().script; const sourceMap = Bindings.debuggerWorkspaceBinding.sourceMapForScript(script); - if (!sourceMap) + if (!sourceMap) { return Promise.resolve(new Map()); + } /** @type {!Map<string, !TextUtils.Text>} */ const textCache = new Map(); @@ -109,16 +114,18 @@ for (let i = 0; i < identifiers.length; ++i) { const id = identifiers[i]; const entry = sourceMap.findEntry(id.lineNumber, id.columnNumber); - if (entry && entry.name) + if (entry && entry.name) { namesMapping.set(id.name, entry.name); + } } // Resolve missing identifier names from sourcemap ranges. const promises = []; for (let i = 0; i < identifiers.length; ++i) { const id = identifiers[i]; - if (namesMapping.has(id.name)) + if (namesMapping.has(id.name)) { continue; + } const promise = resolveSourceName(id).then(onSourceNameResolved.bind(null, namesMapping, id)); promises.push(promise); } @@ -133,8 +140,9 @@ * @param {?string} sourceName */ function onSourceNameResolved(namesMapping, id, sourceName) { - if (!sourceName) + if (!sourceName) { return; + } namesMapping.set(id.name, sourceName); } @@ -147,15 +155,17 @@ const endEntry = sourceMap.findEntry(id.lineNumber, id.columnNumber + id.name.length); if (!startEntry || !endEntry || !startEntry.sourceURL || startEntry.sourceURL !== endEntry.sourceURL || !startEntry.sourceLineNumber || !startEntry.sourceColumnNumber || !endEntry.sourceLineNumber || - !endEntry.sourceColumnNumber) + !endEntry.sourceColumnNumber) { return Promise.resolve(/** @type {?string} */ (null)); + } const sourceTextRange = new TextUtils.TextRange( startEntry.sourceLineNumber, startEntry.sourceColumnNumber, endEntry.sourceLineNumber, endEntry.sourceColumnNumber); const uiSourceCode = Bindings.debuggerWorkspaceBinding.uiSourceCodeForSourceMapSourceURL( script.debuggerModel, startEntry.sourceURL, script.isContentScript()); - if (!uiSourceCode) + if (!uiSourceCode) { return Promise.resolve(/** @type {?string} */ (null)); + } return uiSourceCode.requestContent().then(onSourceContent.bind(null, sourceTextRange)); } @@ -166,8 +176,9 @@ * @return {?string} */ function onSourceContent(sourceTextRange, content) { - if (!content) + if (!content) { return null; + } let text = textCache.get(content); if (!text) { text = new TextUtils.Text(content); @@ -186,13 +197,15 @@ */ Sources.SourceMapNamesResolver._allVariablesInCallFrame = function(callFrame) { const cached = callFrame[Sources.SourceMapNamesResolver._cachedMapSymbol]; - if (cached) + if (cached) { return Promise.resolve(cached); + } const promises = []; const scopeChain = callFrame.scopeChain(); - for (let i = 0; i < scopeChain.length; ++i) + for (let i = 0; i < scopeChain.length; ++i) { promises.push(Sources.SourceMapNamesResolver._resolveScope(scopeChain[i])); + } return Promise.all(promises).then(mergeVariables); @@ -205,8 +218,9 @@ for (const map of nameMappings) { for (const compiledName of map.keys()) { const originalName = map.get(compiledName); - if (!reverseMapping.has(originalName)) + if (!reverseMapping.has(originalName)) { reverseMapping.set(originalName, compiledName); + } } } callFrame[Sources.SourceMapNamesResolver._cachedMapSymbol] = reverseMapping; @@ -225,8 +239,9 @@ */ Sources.SourceMapNamesResolver.resolveExpression = function( callFrame, originalText, uiSourceCode, lineNumber, startColumnNumber, endColumnNumber) { - if (!uiSourceCode.contentType().isFromSourceMap()) + if (!uiSourceCode.contentType().isFromSourceMap()) { return Promise.resolve(''); + } return Sources.SourceMapNamesResolver._allVariablesInCallFrame(callFrame).then( reverseMapping => findCompiledName(callFrame.debuggerModel, reverseMapping)); @@ -237,8 +252,9 @@ * @return {!Promise<string>} */ function findCompiledName(debuggerModel, reverseMapping) { - if (reverseMapping.has(originalText)) + if (reverseMapping.has(originalText)) { return Promise.resolve(reverseMapping.get(originalText) || ''); + } return Sources.SourceMapNamesResolver._resolveExpression( debuggerModel, uiSourceCode, lineNumber, startColumnNumber, endColumnNumber); @@ -258,15 +274,18 @@ const rawLocations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiSourceCode, lineNumber, startColumnNumber); const rawLocation = rawLocations.find(location => location.debuggerModel === debuggerModel); - if (!rawLocation) + if (!rawLocation) { return Promise.resolve(''); + } const script = rawLocation.script(); - if (!script) + if (!script) { return Promise.resolve(''); + } const sourceMap = Bindings.debuggerWorkspaceBinding.sourceMapForScript(script); - if (!sourceMap) + if (!sourceMap) { return Promise.resolve(''); + } return script.requestContent().then(onContent); @@ -275,15 +294,17 @@ * @return {!Promise<string>} */ function onContent(content) { - if (!content) + if (!content) { return Promise.resolve(''); + } const text = new TextUtils.Text(content); const textRange = sourceMap.reverseMapTextRange( uiSourceCode.url(), new TextUtils.TextRange(lineNumber, startColumnNumber, lineNumber, endColumnNumber)); const originalText = text.extract(textRange); - if (!originalText) + if (!originalText) { return Promise.resolve(''); + } return Formatter.formatterWorkerPool().evaluatableJavaScriptSubstring(originalText); } }; @@ -293,10 +314,12 @@ * @return {!Promise<?SDK.RemoteObject>} */ Sources.SourceMapNamesResolver.resolveThisObject = function(callFrame) { - if (!callFrame) + if (!callFrame) { return Promise.resolve(/** @type {?SDK.RemoteObject} */ (null)); - if (!callFrame.scopeChain().length) + } + if (!callFrame.scopeChain().length) { return Promise.resolve(callFrame.thisObject()); + } return Sources.SourceMapNamesResolver._resolveScope(callFrame.scopeChain()[0]).then(onScopeResolved); @@ -306,8 +329,9 @@ */ function onScopeResolved(namesMapping) { const thisMappings = namesMapping.inverse().get('this'); - if (!thisMappings || thisMappings.size !== 1) + if (!thisMappings || thisMappings.size !== 1) { return Promise.resolve(callFrame.thisObject()); + } const thisMapping = thisMappings.valuesArray()[0]; return callFrame @@ -341,8 +365,9 @@ if (scope.type() === Protocol.Debugger.ScopeType.Global || !startLocation || !endLocation || !startLocation.script() || !startLocation.script().sourceMapURL || - startLocation.script() !== endLocation.script()) + startLocation.script() !== endLocation.script()) { return scope.object(); + } return new Sources.SourceMapNamesResolver.RemoteObject(scope); }; @@ -475,10 +500,11 @@ const namesMapping = await Sources.SourceMapNamesResolver._resolveScope(this._scope); let name; - if (typeof argumentName === 'string') + if (typeof argumentName === 'string') { name = argumentName; - else + } else { name = /** @type {string} */ (argumentName.value); + } let actualName = name; for (const compiledName of namesMapping.keys()) {
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourcesNavigator.js b/third_party/blink/renderer/devtools/front_end/sources/SourcesNavigator.js index d229f38..a5d28810 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourcesNavigator.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourcesNavigator.js
@@ -52,14 +52,17 @@ */ _inspectedURLChanged(event) { const mainTarget = SDK.targetManager.mainTarget(); - if (event.data !== mainTarget) + if (event.data !== mainTarget) { return; + } const inspectedURL = mainTarget && mainTarget.inspectedURL(); - if (!inspectedURL) + if (!inspectedURL) { return; + } for (const uiSourceCode of this.workspace().uiSourceCodes()) { - if (this.acceptProject(uiSourceCode.project()) && uiSourceCode.url() === inspectedURL) + if (this.acceptProject(uiSourceCode.project()) && uiSourceCode.url() === inspectedURL) { this.revealUISourceCode(uiSourceCode, true); + } } } @@ -70,10 +73,12 @@ uiSourceCodeAdded(uiSourceCode) { const mainTarget = SDK.targetManager.mainTarget(); const inspectedURL = mainTarget && mainTarget.inspectedURL(); - if (!inspectedURL) + if (!inspectedURL) { return; - if (uiSourceCode.url() === inspectedURL) + } + if (uiSourceCode.url() === inspectedURL) { this.revealUISourceCode(uiSourceCode, true); + } } }; @@ -92,8 +97,9 @@ const toolbar = new UI.Toolbar('navigator-toolbar'); toolbar.appendItemsAtLocation('files-navigator-toolbar').then(() => { - if (!toolbar.empty()) + if (!toolbar.empty()) { this.contentElement.insertBefore(toolbar.element, this.contentElement.firstChild); + } }); } @@ -146,16 +152,18 @@ _onProjectAddOrRemoved(event) { const project = /** @type {!Workspace.Project} */ (event.data); if (project && project.type() === Workspace.projectTypes.FileSystem && - Persistence.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides') + Persistence.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides') { return; + } this._updateUI(); } _updateProjectAndUI() { this.reset(); const project = Persistence.networkPersistenceManager.project(); - if (project) + if (project) { this.tryAddProject(project); + } this._updateUI(); } @@ -183,8 +191,9 @@ async _setupNewWorkspace() { const fileSystem = await Persistence.isolatedFileSystemManager.addFileSystem('overrides'); - if (!fileSystem) + if (!fileSystem) { return; + } Common.settings.moduleSetting('persistenceNetworkOverridesEnabled').set(true); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourcesPanel.js b/third_party/blink/renderer/devtools/front_end/sources/SourcesPanel.js index 3c79383..8df7fdd 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourcesPanel.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourcesPanel.js
@@ -132,8 +132,9 @@ * @return {!Sources.SourcesPanel} */ static instance() { - if (Sources.SourcesPanel._instance) + if (Sources.SourcesPanel._instance) { return Sources.SourcesPanel._instance; + } return /** @type {!Sources.SourcesPanel} */ (self.runtime.sharedInstance(Sources.SourcesPanel)); } @@ -145,16 +146,18 @@ panel._sourcesView.rightToolbar().removeToolbarItems(); panel._sourcesView.bottomToolbar().removeToolbarItems(); const isInWrapper = Sources.SourcesPanel.WrapperView.isShowing() && !UI.inspectorView.isDrawerMinimized(); - if (panel._splitWidget.isVertical() || isInWrapper) + if (panel._splitWidget.isVertical() || isInWrapper) { panel._splitWidget.uninstallResizer(panel._sourcesView.toolbarContainerElement()); - else + } else { panel._splitWidget.installResizer(panel._sourcesView.toolbarContainerElement()); + } if (!isInWrapper) { panel._sourcesView.leftToolbar().appendToolbarItem(panel._toggleNavigatorSidebarButton); - if (panel._splitWidget.isVertical()) + if (panel._splitWidget.isVertical()) { panel._sourcesView.rightToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton); - else + } else { panel._sourcesView.bottomToolbar().appendToolbarItem(panel._toggleDebuggerSidebarButton); + } } } @@ -187,11 +190,13 @@ * @param {?SDK.Target} target */ _setTarget(target) { - if (!target) + if (!target) { return; + } const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return; + } if (debuggerModel.isPaused()) { this._showDebuggerPausedDetails( @@ -251,20 +256,23 @@ */ resolveLocation(locationName) { if (locationName === 'sources.sidebar-top' || locationName === 'sources.sidebar-bottom' || - locationName === 'sources.sidebar-tabs') + locationName === 'sources.sidebar-tabs') { return this._sidebarPaneStack; - else + } else { return this._navigatorTabbedLocation; + } } /** * @return {boolean} */ _ensureSourcesViewVisible() { - if (Sources.SourcesPanel.WrapperView.isShowing()) + if (Sources.SourcesPanel.WrapperView.isShowing()) { return true; - if (!UI.inspectorView.canSelectPanel('sources')) + } + if (!UI.inspectorView.canSelectPanel('sources')) { return false; + } UI.viewManager.showView('sources'); return true; } @@ -273,8 +281,9 @@ * @override */ onResize() { - if (Common.moduleSetting('sidebarPosition').get() === 'auto') - this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this)); // Do not force layout. + if (Common.moduleSetting('sidebarPosition').get() === 'auto') { + this.element.window().requestAnimationFrame(this._updateSidebarPosition.bind(this)); + } // Do not force layout. } /** @@ -291,13 +300,15 @@ _debuggerPaused(event) { const debuggerModel = /** @type {!SDK.DebuggerModel} */ (event.data); const details = debuggerModel.debuggerPausedDetails(); - if (!this._paused) + if (!this._paused) { this._setAsCurrentPanel(); + } - if (UI.context.flavor(SDK.Target) === debuggerModel.target()) + if (UI.context.flavor(SDK.Target) === debuggerModel.target()) { this._showDebuggerPausedDetails(/** @type {!SDK.DebuggerPausedDetails} */ (details)); - else if (!this._paused) + } else if (!this._paused) { UI.context.setFlavor(SDK.Target, debuggerModel.target()); + } } /** @@ -318,8 +329,9 @@ */ _debuggerResumed(debuggerModel) { const target = debuggerModel.target(); - if (UI.context.flavor(SDK.Target) !== target) + if (UI.context.flavor(SDK.Target) !== target) { return; + } this._paused = false; this._clearInterface(); this._toggleDebuggerSidebarButton.setEnabled(true); @@ -331,8 +343,9 @@ */ _debuggerWasEnabled(event) { const debuggerModel = /** @type {!SDK.DebuggerModel} */ (event.data); - if (UI.context.flavor(SDK.Target) !== debuggerModel.target()) + if (UI.context.flavor(SDK.Target) !== debuggerModel.target()) { return; + } this._updateDebuggerButtonsAndStatus(); } @@ -354,8 +367,9 @@ if (omitFocus) { const wrapperShowing = Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing(); - if (!this.isShowing() && !wrapperShowing) + if (!this.isShowing() && !wrapperShowing) { return; + } } else { this._showEditor(); } @@ -363,8 +377,9 @@ } _showEditor() { - if (Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing()) + if (Sources.SourcesPanel.WrapperView._instance && Sources.SourcesPanel.WrapperView._instance.isShowing()) { return; + } this._setAsCurrentPanel(); } @@ -394,10 +409,11 @@ const viewId = extensions[i].descriptor()['viewId']; if (navigatorView.acceptProject(uiSourceCode.project())) { navigatorView.revealUISourceCode(uiSourceCode, true); - if (skipReveal) + if (skipReveal) { this._navigatorTabbedLocation.tabbedPane().selectTab(viewId); - else + } else { UI.viewManager.showView(viewId); + } } } } @@ -430,10 +446,12 @@ */ _executionLineChanged(liveLocation) { const uiLocation = liveLocation.uiLocation(); - if (!uiLocation) + if (!uiLocation) { return; - if (window.performance.now() - this._lastModificationTime < Sources.SourcesPanel._lastModificationTimeout) + } + if (window.performance.now() - this._lastModificationTime < Sources.SourcesPanel._lastModificationTimeout) { return; + } this._sourcesView.showSourceLocation( uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber, undefined, true); } @@ -448,10 +466,12 @@ _callFrameChanged() { const callFrame = UI.context.flavor(SDK.DebuggerModel.CallFrame); - if (!callFrame) + if (!callFrame) { return; - if (this._executionLineLocation) + } + if (this._executionLineLocation) { this._executionLineLocation.dispose(); + } this._executionLineLocation = Bindings.debuggerWorkspaceBinding.createCallFrameLiveLocation( callFrame.location(), this._executionLineChanged.bind(this), this._liveLocationPool); } @@ -490,8 +510,9 @@ const details = currentDebuggerModel ? currentDebuggerModel.debuggerPausedDetails() : null; await this._debuggerPausedMessage.render(details, Bindings.debuggerWorkspaceBinding, Bindings.breakpointManager); - if (details) + if (details) { this._updateDebuggerButtonsAndStatusForTest(); + } } _updateDebuggerButtonsAndStatusForTest() { @@ -501,8 +522,9 @@ this._updateDebuggerButtonsAndStatus(); UI.context.setFlavor(SDK.DebuggerPausedDetails, null); - if (this._switchToPausedTargetTimeout) + if (this._switchToPausedTargetTimeout) { clearTimeout(this._switchToPausedTargetTimeout); + } this._liveLocationPool.disposeAll(); } @@ -511,10 +533,12 @@ */ _switchToPausedTarget(debuggerModel) { delete this._switchToPausedTargetTimeout; - if (this._paused) + if (this._paused) { return; - if (debuggerModel.isPaused()) + } + if (debuggerModel.isPaused()) { return; + } const debuggerModels = SDK.targetManager.models(SDK.DebuggerModel); for (let i = 0; i < debuggerModels.length; ++i) { if (debuggerModels[i].isPaused()) { @@ -530,8 +554,9 @@ _runSnippet() { const uiSourceCode = this._sourcesView.currentUISourceCode(); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } Snippets.evaluateScriptSnippet(uiSourceCode); } @@ -540,8 +565,9 @@ */ _editorSelected(event) { const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data); - if (this.editorView.mainWidget() && Common.moduleSetting('autoRevealInNavigator').get()) + if (this.editorView.mainWidget() && Common.moduleSetting('autoRevealInNavigator').get()) { this._revealInNavigator(uiSourceCode, true); + } } /** @@ -549,11 +575,13 @@ */ _togglePause() { const target = UI.context.flavor(SDK.Target); - if (!target) + if (!target) { return true; + } const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return true; + } if (this._paused) { this._paused = false; @@ -571,8 +599,9 @@ * @return {?SDK.DebuggerModel} */ _prepareToResume() { - if (!this._paused) + if (!this._paused) { return null; + } this._paused = false; @@ -586,8 +615,9 @@ */ _longResume(event) { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return; + } debuggerModel.skipAllPausesUntilReloadOrTimeout(500); debuggerModel.resume(); @@ -598,8 +628,9 @@ */ _terminateExecution(event) { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return; + } debuggerModel.runtimeModel().terminateExecution(); debuggerModel.resume(); } @@ -609,8 +640,9 @@ */ _stepOver() { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return true; + } debuggerModel.stepOver(); return true; @@ -621,8 +653,9 @@ */ _stepInto() { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return true; + } debuggerModel.stepInto(); return true; @@ -633,8 +666,9 @@ */ _stepIntoAsync() { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return true; + } debuggerModel.scheduleStepIntoAsync(); return true; } @@ -644,8 +678,9 @@ */ _stepOut() { const debuggerModel = this._prepareToResume(); - if (!debuggerModel) + if (!debuggerModel) { return true; + } debuggerModel.stepOut(); return true; @@ -656,16 +691,19 @@ */ _continueToLocation(uiLocation) { const executionContext = UI.context.flavor(SDK.ExecutionContext); - if (!executionContext) + if (!executionContext) { return; + } // Always use 0 column. const rawLocations = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocations(uiLocation.uiSourceCode, uiLocation.lineNumber, 0); const rawLocation = rawLocations.find(location => location.debuggerModel === executionContext.debuggerModel); - if (!rawLocation) + if (!rawLocation) { return; - if (!this._prepareToResume()) + } + if (!this._prepareToResume()) { return; + } rawLocation.continueToLocation(); } @@ -740,8 +778,9 @@ * @param {!Object} target */ _appendUISourceCodeItems(event, contextMenu, target) { - if (!(target instanceof Workspace.UISourceCode)) + if (!(target instanceof Workspace.UISourceCode)) { return; + } const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (target); if (!uiSourceCode.project().isServiceProject() && @@ -757,10 +796,12 @@ * @param {!Object} target */ _appendUISourceCodeFrameItems(event, contextMenu, target) { - if (!(target instanceof Sources.UISourceCodeFrame)) + if (!(target instanceof Sources.UISourceCodeFrame)) { return; - if (target.uiSourceCode().contentType().isFromSourceMap() || target.textEditor.selection().isEmpty()) + } + if (target.uiSourceCode().contentType().isFromSourceMap() || target.textEditor.selection().isEmpty()) { return; + } contextMenu.debugSection().appendAction('debugger.evaluate-selection'); } @@ -769,8 +810,9 @@ * @param {!Object} object */ appendUILocationItems(contextMenu, object) { - if (!(object instanceof Workspace.UILocation)) + if (!(object instanceof Workspace.UILocation)) { return; + } const uiLocation = /** @type {!Workspace.UILocation} */ (object); const uiSourceCode = uiLocation.uiSourceCode; @@ -800,8 +842,9 @@ * @param {!Object} target */ _appendRemoteObjectItems(contextMenu, target) { - if (!(target instanceof SDK.RemoteObject)) + if (!(target instanceof SDK.RemoteObject)) { return; + } const remoteObject = /** @type {!SDK.RemoteObject} */ (target); const executionContext = UI.context.flavor(SDK.ExecutionContext); contextMenu.debugSection().appendItem( @@ -817,12 +860,14 @@ * @param {!Object} target */ _appendNetworkRequestItems(contextMenu, target) { - if (!(target instanceof SDK.NetworkRequest)) + if (!(target instanceof SDK.NetworkRequest)) { return; + } const request = /** @type {!SDK.NetworkRequest} */ (target); const uiSourceCode = this._workspace.uiSourceCodeForURL(request.url()); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } const openText = Common.UIString('Open in Sources panel'); contextMenu.revealSection().appendItem(openText, this.showUILocation.bind(this, uiSourceCode.uiLocation(0, 0))); } @@ -838,16 +883,19 @@ * @param {?{location: ?SDK.DebuggerModel.Location}} response */ _didGetFunctionDetails(response) { - if (!response || !response.location) + if (!response || !response.location) { return; + } const location = response.location; - if (!location) + if (!location) { return; + } const uiLocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(location); - if (uiLocation) + if (uiLocation) { this.showUILocation(uiLocation); + } } _revealNavigatorSidebar() { @@ -863,21 +911,25 @@ _updateSidebarPosition() { let vertically; const position = Common.moduleSetting('sidebarPosition').get(); - if (position === 'right') + if (position === 'right') { vertically = false; - else if (position === 'bottom') + } else if (position === 'bottom') { vertically = true; - else + } else { vertically = UI.inspectorView.element.offsetWidth < 680; + } - if (this.sidebarPaneView && vertically === !this._splitWidget.isVertical()) + if (this.sidebarPaneView && vertically === !this._splitWidget.isVertical()) { return; + } - if (this.sidebarPaneView && this.sidebarPaneView.shouldHideOnDetach()) - return; // We can't reparent extension iframes. + if (this.sidebarPaneView && this.sidebarPaneView.shouldHideOnDetach()) { + return; + } // We can't reparent extension iframes. - if (this.sidebarPaneView) + if (this.sidebarPaneView) { this.sidebarPaneView.detach(); + } this._splitWidget.setVertical(!vertically); this._splitWidget.element.classList.toggle('sources-split-view-vertical', vertically); @@ -897,11 +949,13 @@ this._sidebarPaneStack.widget().element.appendChild(this._debuggerPausedMessage.element()); this._sidebarPaneStack.appendApplicableItems('sources.sidebar-top'); - if (this._threadsSidebarPane) + if (this._threadsSidebarPane) { this._sidebarPaneStack.showView(this._threadsSidebarPane); + } - if (!vertically) + if (!vertically) { this._sidebarPaneStack.appendView(this._watchSidebarPane); + } this._sidebarPaneStack.showView(this._callstackPane); const jsBreakpoints = /** @type {!UI.View} */ (UI.viewManager.view('sources.jsBreakpoints')); @@ -940,8 +994,9 @@ this._sidebarPaneStack.appendApplicableItems('sources.sidebar-bottom'); const extensionSidebarPanes = Extensions.extensionServer.sidebarPanes(); - for (let i = 0; i < extensionSidebarPanes.length; ++i) + for (let i = 0; i < extensionSidebarPanes.length; ++i) { this._addExtensionSidebarPane(extensionSidebarPanes[i]); + } this._splitWidget.setSidebarWidget(this.sidebarPaneView); } @@ -965,8 +1020,9 @@ * @param {!Extensions.ExtensionSidebarPane} pane */ _addExtensionSidebarPane(pane) { - if (pane.panelName() === this.name) + if (pane.panelName() === this.name) { this._extensionSidebarPanesContainer.appendView(pane); + } } /** @@ -981,11 +1037,13 @@ */ _handleDrop(dataTransfer) { const items = dataTransfer.items; - if (!items.length) + if (!items.length) { return; + } const entry = items[0].webkitGetAsEntry(); - if (!entry.isDirectory) + if (!entry.isDirectory) { return; + } InspectorFrontendHost.upgradeDraggedFileSystemPermissions(entry.filesystem); } }; @@ -1006,8 +1064,9 @@ * @return {!Promise} */ reveal(uiLocation, omitFocus) { - if (!(uiLocation instanceof Workspace.UILocation)) + if (!(uiLocation instanceof Workspace.UILocation)) { return Promise.reject(new Error('Internal error: not a ui location')); + } Sources.SourcesPanel.instance().showUILocation(uiLocation, omitFocus); return Promise.resolve(); } @@ -1025,11 +1084,13 @@ * @return {!Promise} */ reveal(rawLocation, omitFocus) { - if (!(rawLocation instanceof SDK.DebuggerModel.Location)) + if (!(rawLocation instanceof SDK.DebuggerModel.Location)) { return Promise.reject(new Error('Internal error: not a debugger location')); + } const uiLocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation); - if (!uiLocation) + if (!uiLocation) { return Promise.resolve(); + } Sources.SourcesPanel.instance().showUILocation(uiLocation, omitFocus); return Promise.resolve(); } @@ -1047,8 +1108,9 @@ * @return {!Promise} */ reveal(uiSourceCode, omitFocus) { - if (!(uiSourceCode instanceof Workspace.UISourceCode)) + if (!(uiSourceCode instanceof Workspace.UISourceCode)) { return Promise.reject(new Error('Internal error: not a ui source code')); + } Sources.SourcesPanel.instance().showUISourceCode(uiSourceCode, undefined, undefined, omitFocus); return Promise.resolve(); } @@ -1082,8 +1144,9 @@ */ handleAction(context, actionId) { const panel = Sources.SourcesPanel.instance(); - if (!panel._ensureSourcesViewVisible()) + if (!panel._ensureSourcesViewVisible()) { return false; + } switch (actionId) { case 'debugger.toggle-pause': panel._togglePause(); @@ -1166,10 +1229,11 @@ * @override */ wasShown() { - if (!Sources.SourcesPanel.instance().isShowing()) + if (!Sources.SourcesPanel.instance().isShowing()) { this._showViewInWrapper(); - else + } else { UI.inspectorView.setDrawerMinimized(true); + } Sources.SourcesPanel.updateResizerAndSidebarButtons(Sources.SourcesPanel.instance()); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourcesSearchScope.js b/third_party/blink/renderer/devtools/front_end/sources/SourcesSearchScope.js index 7dadf6c..0f6214e 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourcesSearchScope.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourcesSearchScope.js
@@ -48,22 +48,27 @@ * @return {number} */ static _filesComparator(uiSourceCode1, uiSourceCode2) { - if (uiSourceCode1.isDirty() && !uiSourceCode2.isDirty()) + if (uiSourceCode1.isDirty() && !uiSourceCode2.isDirty()) { return -1; - if (!uiSourceCode1.isDirty() && uiSourceCode2.isDirty()) + } + if (!uiSourceCode1.isDirty() && uiSourceCode2.isDirty()) { return 1; + } const isFileSystem1 = uiSourceCode1.project().type() === Workspace.projectTypes.FileSystem && !Persistence.persistence.binding(uiSourceCode1); const isFileSystem2 = uiSourceCode2.project().type() === Workspace.projectTypes.FileSystem && !Persistence.persistence.binding(uiSourceCode2); - if (isFileSystem1 !== isFileSystem2) + if (isFileSystem1 !== isFileSystem2) { return isFileSystem1 ? 1 : -1; + } const url1 = uiSourceCode1.url(); const url2 = uiSourceCode2.url(); - if (url1 && !url2) + if (url1 && !url2) { return -1; - if (!url1 && url2) + } + if (!url1 && url2) { return 1; + } return String.naturalOrderComparator(uiSourceCode1.fullDisplayName(), uiSourceCode2.fullDisplayName()); } @@ -90,12 +95,15 @@ const searchInAnonymousAndContentScripts = Common.moduleSetting('searchInAnonymousAndContentScripts').get(); return Workspace.workspace.projects().filter(project => { - if (project.type() === Workspace.projectTypes.Service) + if (project.type() === Workspace.projectTypes.Service) { return false; - if (!searchInAnonymousAndContentScripts && project.isServiceProject()) + } + if (!searchInAnonymousAndContentScripts && project.isServiceProject()) { return false; - if (!searchInAnonymousAndContentScripts && project.type() === Workspace.projectTypes.ContentScripts) + } + if (!searchInAnonymousAndContentScripts && project.type() === Workspace.projectTypes.ContentScripts) { return false; + } return true; }); } @@ -145,15 +153,19 @@ const uiSourceCodes = project.uiSourceCodes(); for (let i = 0; i < uiSourceCodes.length; ++i) { const uiSourceCode = uiSourceCodes[i]; - if (!uiSourceCode.contentType().isTextType()) + if (!uiSourceCode.contentType().isTextType()) { continue; + } const binding = Persistence.persistence.binding(uiSourceCode); - if (binding && binding.network === uiSourceCode) + if (binding && binding.network === uiSourceCode) { continue; - if (dirtyOnly && !uiSourceCode.isDirty()) + } + if (dirtyOnly && !uiSourceCode.isDirty()) { continue; - if (searchConfig.filePathMatchesFileQuery(uiSourceCode.fullDisplayName())) + } + if (searchConfig.filePathMatchesFileQuery(uiSourceCode.fullDisplayName())) { result.push(uiSourceCode.url()); + } } result.sort(String.naturalOrderComparator); return result; @@ -180,11 +192,13 @@ const uiSourceCodes = []; for (const file of files) { const uiSourceCode = project.uiSourceCodeForURL(file); - if (!uiSourceCode) + if (!uiSourceCode) { continue; + } const script = Bindings.DefaultScriptMapping.scriptForUISourceCode(uiSourceCode); - if (script && !script.isAnonymousScript()) + if (script && !script.isAnonymousScript()) { continue; + } uiSourceCodes.push(uiSourceCode); } uiSourceCodes.sort(Sources.SourcesSearchScope._filesComparator); @@ -216,18 +230,20 @@ const maxFileContentRequests = 20; let callbacksLeft = 0; - for (let i = 0; i < maxFileContentRequests && i < files.length; ++i) + for (let i = 0; i < maxFileContentRequests && i < files.length; ++i) { scheduleSearchInNextFileOrFinish.call(this); + } /** * @param {!Workspace.UISourceCode} uiSourceCode * @this {Sources.SourcesSearchScope} */ function searchInNextFile(uiSourceCode) { - if (uiSourceCode.isDirty()) + if (uiSourceCode.isDirty()) { contentLoaded.call(this, uiSourceCode, uiSourceCode.workingCopy()); - else + } else { uiSourceCode.requestContent().then(contentLoaded.bind(this, uiSourceCode)); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourcesView.js b/third_party/blink/renderer/devtools/front_end/sources/SourcesView.js index f02e8d4..226a54e 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/SourcesView.js +++ b/third_party/blink/renderer/devtools/front_end/sources/SourcesView.js
@@ -45,8 +45,9 @@ * @this {Sources.SourcesView} */ function appendButtonsForExtensions(actions) { - for (let i = 0; i < actions.length; ++i) + for (let i = 0; i < actions.length; ++i) { this._toolbarEditorActions.appendToolbarItem(actions[i].button(this)); + } } this._scriptViewToolbar = new UI.Toolbar('', this._toolbarContainerElement); this._scriptViewToolbar.element.style.flex = 'auto'; @@ -67,8 +68,9 @@ * @param {!Event} event */ function handleBeforeUnload(event) { - if (event.returnValue) + if (event.returnValue) { return; + } let unsavedSourceCodes = []; const projects = Workspace.workspace.projectsForType(Workspace.projectTypes.FileSystem); @@ -77,17 +79,20 @@ unsavedSourceCodes.concat(projects[i].uiSourceCodes().filter(sourceCode => sourceCode.isDirty())); } - if (!unsavedSourceCodes.length) + if (!unsavedSourceCodes.length) { return; + } event.returnValue = Common.UIString('DevTools have unsaved changes that will be permanently lost.'); UI.viewManager.showView('sources'); - for (let i = 0; i < unsavedSourceCodes.length; ++i) + for (let i = 0; i < unsavedSourceCodes.length; ++i) { Common.Revealer.reveal(unsavedSourceCodes[i]); + } } - if (!window.opener) + if (!window.opener) { window.addEventListener('beforeunload', handleBeforeUnload, true); + } this._shortcuts = {}; this.element.addEventListener('keydown', this._handleKeyDown.bind(this), false); @@ -128,7 +133,9 @@ if (sourcesView) { const uiSourceCodes = sourcesView._editorContainer.historyUISourceCodes(); for (let i = 1; i < uiSourceCodes.length; ++i) // Skip current element + { defaultScores.set(uiSourceCodes[i], uiSourceCodes.length - i); + } } return defaultScores; } @@ -159,15 +166,17 @@ * @param {function(!Event=):boolean} handler */ _registerShortcuts(keys, handler) { - for (let i = 0; i < keys.length; ++i) + for (let i = 0; i < keys.length; ++i) { this._shortcuts[keys[i].key] = handler; + } } _handleKeyDown(event) { const shortcutKey = UI.KeyboardShortcut.makeKeyFromEvent(event); const handler = this._shortcuts[shortcutKey]; - if (handler && handler()) + if (handler && handler()) { event.consume(true); + } } /** @@ -212,8 +221,9 @@ */ currentSourceFrame() { const view = this.visibleView(); - if (!(view instanceof Sources.UISourceCodeFrame)) + if (!(view instanceof Sources.UISourceCodeFrame)) { return null; + } return /** @type {!Sources.UISourceCodeFrame} */ (view); } @@ -229,8 +239,9 @@ */ _onCloseEditorTab() { const uiSourceCode = this._editorContainer.currentFile(); - if (!uiSourceCode) + if (!uiSourceCode) { return false; + } this._editorContainer.closeFile(uiSourceCode); return true; } @@ -255,11 +266,13 @@ * @param {!Workspace.UISourceCode} uiSourceCode */ _addUISourceCode(uiSourceCode) { - if (uiSourceCode.project().isServiceProject()) + if (uiSourceCode.project().isServiceProject()) { return; + } if (uiSourceCode.project().type() === Workspace.projectTypes.FileSystem && - Persistence.FileSystemWorkspaceBinding.fileSystemType(uiSourceCode.project()) === 'overrides') + Persistence.FileSystemWorkspaceBinding.fileSystemType(uiSourceCode.project()) === 'overrides') { return; + } this._editorContainer.addUISourceCode(uiSourceCode); } @@ -289,8 +302,9 @@ this._scriptViewToolbar.removeToolbarItems(); const view = this.visibleView(); if (view instanceof UI.SimpleView) { - for (const item of (/** @type {?UI.SimpleView} */ (view)).syncToolbarItems()) + for (const item of (/** @type {?UI.SimpleView} */ (view)).syncToolbarItems()) { this._scriptViewToolbar.appendToolbarItem(item); + } } } @@ -305,11 +319,13 @@ this._historyManager.updateCurrentState(); this._editorContainer.showFile(uiSourceCode); const currentSourceFrame = this.currentSourceFrame(); - if (currentSourceFrame && typeof lineNumber === 'number') + if (currentSourceFrame && typeof lineNumber === 'number') { currentSourceFrame.revealPosition(lineNumber, columnNumber, !omitHighlight); + } this._historyManager.pushNewState(); - if (!omitFocus) + if (!omitFocus) { this.visibleView().focus(); + } } /** @@ -321,15 +337,17 @@ let sourceView; const contentType = uiSourceCode.contentType(); - if (contentType === Common.resourceTypes.Image) + if (contentType === Common.resourceTypes.Image) { sourceView = new SourceFrame.ImageView(uiSourceCode.mimeType(), uiSourceCode); - else if (contentType === Common.resourceTypes.Font) + } else if (contentType === Common.resourceTypes.Font) { sourceView = new SourceFrame.FontView(uiSourceCode.mimeType(), uiSourceCode); - else + } else { sourceFrame = new Sources.UISourceCodeFrame(uiSourceCode); + } - if (sourceFrame) + if (sourceFrame) { this._historyManager.trackSourceFrameCursorJumps(sourceFrame); + } const widget = /** @type {!UI.Widget} */ (sourceFrame || sourceView); this._sourceViewByUISourceCode.set(uiSourceCode, widget); @@ -370,8 +388,9 @@ _removeSourceFrame(uiSourceCode) { const sourceView = this._sourceViewByUISourceCode.get(uiSourceCode); this._sourceViewByUISourceCode.remove(uiSourceCode); - if (sourceView && sourceView instanceof Sources.UISourceCodeFrame) + if (sourceView && sourceView instanceof Sources.UISourceCodeFrame) { /** @type {!Sources.UISourceCodeFrame} */ (sourceView).dispose(); + } } /** @@ -382,8 +401,9 @@ this._historyManager.removeHistoryForSourceCode(uiSourceCode); let wasSelected = false; - if (!this._editorContainer.currentFile()) + if (!this._editorContainer.currentFile()) { wasSelected = true; + } // SourcesNavigator does not need to update on EditorClosed. this._removeToolbarChangedListener(); @@ -402,12 +422,14 @@ _editorSelected(event) { const previousSourceFrame = event.data.previousView instanceof Sources.UISourceCodeFrame ? event.data.previousView : null; - if (previousSourceFrame) + if (previousSourceFrame) { previousSourceFrame.setSearchableView(null); + } const currentSourceFrame = event.data.currentView instanceof Sources.UISourceCodeFrame ? event.data.currentView : null; - if (currentSourceFrame) + if (currentSourceFrame) { currentSourceFrame.setSearchableView(this._searchableView); + } this._searchableView.setReplaceable(!!currentSourceFrame && currentSourceFrame.canEditSource()); this._searchableView.refreshSearch(); @@ -418,16 +440,18 @@ } _removeToolbarChangedListener() { - if (this._toolbarChangedListener) + if (this._toolbarChangedListener) { Common.EventTarget.removeEventListeners([this._toolbarChangedListener]); + } this._toolbarChangedListener = null; } _updateToolbarChangedListener() { this._removeToolbarChangedListener(); const sourceFrame = this.currentSourceFrame(); - if (!sourceFrame) + if (!sourceFrame) { return; + } this._toolbarChangedListener = sourceFrame.addEventListener( Sources.UISourceCodeFrame.Events.ToolbarItemsChanged, this._updateScriptViewToolbarItems, this); } @@ -436,8 +460,9 @@ * @override */ searchCanceled() { - if (this._searchView) + if (this._searchView) { this._searchView.searchCanceled(); + } delete this._searchView; delete this._searchConfig; @@ -451,8 +476,9 @@ */ performSearch(searchConfig, shouldJump, jumpBackwards) { const sourceFrame = this.currentSourceFrame(); - if (!sourceFrame) + if (!sourceFrame) { return; + } this._searchView = sourceFrame; this._searchConfig = searchConfig; @@ -464,8 +490,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchView) + if (!this._searchView) { return; + } if (this._searchView !== this.currentSourceFrame()) { this.performSearch(this._searchConfig, true); @@ -479,13 +506,15 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchView) + if (!this._searchView) { return; + } if (this._searchView !== this.currentSourceFrame()) { this.performSearch(this._searchConfig, true); - if (this._searchView) + if (this._searchView) { this._searchView.jumpToLastSearchResult(); + } return; } @@ -541,8 +570,9 @@ } _showGoToLineQuickOpen() { - if (this._editorContainer.currentFile()) + if (this._editorContainer.currentFile()) { QuickOpen.QuickOpen.show(':'); + } } _save() { @@ -558,8 +588,9 @@ * @param {?UI.Widget} sourceFrame */ _saveSourceFrame(sourceFrame) { - if (!(sourceFrame instanceof Sources.UISourceCodeFrame)) + if (!(sourceFrame instanceof Sources.UISourceCodeFrame)) { return; + } const uiSourceCodeFrame = /** @type {!Sources.UISourceCodeFrame} */ (sourceFrame); uiSourceCodeFrame.commitEditing(); } @@ -618,10 +649,12 @@ const namePrefix = fileNamePrefix(name); for (let i = 0; i < uiSourceCodes.length; ++i) { const uiSourceCode = uiSourceCodes[i]; - if (url !== uiSourceCode.parentURL()) + if (url !== uiSourceCode.parentURL()) { continue; - if (fileNamePrefix(uiSourceCode.name()) === namePrefix) + } + if (fileNamePrefix(uiSourceCode.name()) === namePrefix) { candidates.push(uiSourceCode.name()); + } } candidates.sort(String.naturalOrderComparator); const index = mod(candidates.indexOf(name) + 1, candidates.length); @@ -639,11 +672,13 @@ handleAction(context, actionId) { const sourcesView = UI.context.flavor(Sources.SourcesView); const currentUISourceCode = sourcesView.currentUISourceCode(); - if (!currentUISourceCode) + if (!currentUISourceCode) { return false; + } const nextUISourceCode = Sources.SourcesView.SwitchFileActionDelegate._nextFile(currentUISourceCode); - if (!nextUISourceCode) + if (!nextUISourceCode) { return false; + } sourcesView.showSourceLocation(nextUISourceCode); return true; } @@ -663,8 +698,9 @@ */ handleAction(context, actionId) { const sourcesView = UI.context.flavor(Sources.SourcesView); - if (!sourcesView) + if (!sourcesView) { return false; + } switch (actionId) { case 'sources.close-all':
diff --git a/third_party/blink/renderer/devtools/front_end/sources/TabbedEditorContainer.js b/third_party/blink/renderer/devtools/front_end/sources/TabbedEditorContainer.js index 9a82b5d7..0edc466 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/TabbedEditorContainer.js +++ b/third_party/blink/renderer/devtools/front_end/sources/TabbedEditorContainer.js
@@ -94,8 +94,9 @@ const currentScrollLineNumber = this._history.scrollLineNumber(binding.network.url()); this._history.remove(binding.network.url()); - if (!networkTabId) + if (!networkTabId) { return; + } if (!fileSystemTabId) { const networkView = this._tabbedPane.tabView(networkTabId); @@ -111,8 +112,9 @@ } this._closeTabs([networkTabId], true); - if (wasSelectedInNetwork) + if (wasSelectedInNetwork) { this._tabbedPane.selectTab(fileSystemTabId, false); + } this._updateHistory(); } @@ -179,8 +181,9 @@ */ closeFile(uiSourceCode) { const tabId = this._tabIds.get(uiSourceCode); - if (!tabId) + if (!tabId) { return; + } this._closeTabs([tabId]); } @@ -203,15 +206,17 @@ const uris = this._history._urls(); for (let i = 0; i < uris.length; ++i) { const uiSourceCode = uriToUISourceCode[uris[i]]; - if (uiSourceCode) + if (uiSourceCode) { result.push(uiSourceCode); + } } return result; } _addViewListeners() { - if (!this._currentView || !this._currentView.textEditor) + if (!this._currentView || !this._currentView.textEditor) { return; + } this._currentView.textEditor.addEventListener( SourceFrame.SourcesTextEditor.Events.ScrollChanged, this._scrollChanged, this); this._currentView.textEditor.addEventListener( @@ -219,8 +224,9 @@ } _removeViewListeners() { - if (!this._currentView || !this._currentView.textEditor) + if (!this._currentView || !this._currentView.textEditor) { return; + } this._currentView.textEditor.removeEventListener( SourceFrame.SourcesTextEditor.Events.ScrollChanged, this._scrollChanged, this); this._currentView.textEditor.removeEventListener( @@ -231,8 +237,9 @@ * @param {!Common.Event} event */ _scrollChanged(event) { - if (this._scrollTimer) + if (this._scrollTimer) { clearTimeout(this._scrollTimer); + } const lineNumber = /** @type {number} */ (event.data); this._scrollTimer = setTimeout(saveHistory.bind(this), 100); this._history.updateScrollLineNumber(this._currentFile.url(), lineNumber); @@ -263,8 +270,9 @@ _innerShowFile(uiSourceCode, userGesture) { const binding = Persistence.persistence.binding(uiSourceCode); uiSourceCode = binding ? binding.fileSystem : uiSourceCode; - if (this._currentFile === uiSourceCode) + if (this._currentFile === uiSourceCode) { return; + } this._removeViewListeners(); this._currentFile = uiSourceCode; @@ -272,8 +280,9 @@ const tabId = this._tabIds.get(uiSourceCode) || this._appendFileTab(uiSourceCode, userGesture); this._tabbedPane.selectTab(tabId, userGesture); - if (userGesture) + if (userGesture) { this._editorSelectedByUserAction(); + } const previousView = this._currentView; this._currentView = this.visibleView; @@ -295,8 +304,9 @@ _titleForFile(uiSourceCode) { const maxDisplayNameLength = 30; let title = uiSourceCode.displayName(true).trimMiddle(maxDisplayNameLength); - if (uiSourceCode.isDirty()) + if (uiSourceCode.isDirty()) { title += '*'; + } return title; } @@ -311,8 +321,9 @@ if (!shouldPrompt || confirm(Common.UIString('Are you sure you want to close unsaved file: %s?', uiSourceCode.name()))) { uiSourceCode.resetWorkingCopy(); - if (nextTabId) + if (nextTabId) { this._tabbedPane.selectTab(nextTabId, true); + } this._tabbedPane.closeTab(id, true); return true; } @@ -329,18 +340,21 @@ for (let i = 0; i < ids.length; ++i) { const id = ids[i]; const uiSourceCode = this._files[id]; - if (!forceCloseDirtyTabs && uiSourceCode.isDirty()) + if (!forceCloseDirtyTabs && uiSourceCode.isDirty()) { dirtyTabs.push(id); - else + } else { cleanTabs.push(id); + } } - if (dirtyTabs.length) + if (dirtyTabs.length) { this._tabbedPane.selectTab(dirtyTabs[0], true); + } this._tabbedPane.closeTabs(cleanTabs, true); for (let i = 0; i < dirtyTabs.length; ++i) { const nextTabId = i + 1 < dirtyTabs.length ? dirtyTabs[i + 1] : null; - if (!this._maybeCloseTab(dirtyTabs[i], nextTabId)) + if (!this._maybeCloseTab(dirtyTabs[i], nextTabId)) { break; + } } } @@ -350,8 +364,9 @@ */ _onContextMenu(tabId, contextMenu) { const uiSourceCode = this._files[tabId]; - if (uiSourceCode) + if (uiSourceCode) { contextMenu.appendApplicableItems(uiSourceCode); + } } /** @@ -360,16 +375,19 @@ addUISourceCode(uiSourceCode) { const binding = Persistence.persistence.binding(uiSourceCode); uiSourceCode = binding ? binding.fileSystem : uiSourceCode; - if (this._currentFile === uiSourceCode) + if (this._currentFile === uiSourceCode) { return; + } const uri = uiSourceCode.url(); const index = this._history.index(uri); - if (index === -1) + if (index === -1) { return; + } - if (!this._tabIds.has(uiSourceCode)) + if (!this._tabIds.has(uiSourceCode)) { this._appendFileTab(uiSourceCode, false); + } // Select tab if this file was the last to be shown. if (!index) { @@ -377,13 +395,15 @@ return; } - if (!this._currentFile) + if (!this._currentFile) { return; + } const currentProjectIsSnippets = Snippets.isSnippetsUISourceCode(this._currentFile); const addedProjectIsSnippets = Snippets.isSnippetsUISourceCode(uiSourceCode); - if (this._history.index(this._currentFile.url()) && currentProjectIsSnippets && !addedProjectIsSnippets) + if (this._history.index(this._currentFile.url()) && currentProjectIsSnippets && !addedProjectIsSnippets) { this._innerShowFile(uiSourceCode, false); + } } /** @@ -401,8 +421,9 @@ for (let i = 0; i < uiSourceCodes.length; ++i) { const uiSourceCode = uiSourceCodes[i]; const tabId = this._tabIds.get(uiSourceCode); - if (tabId) + if (tabId) { tabIds.push(tabId); + } } this._tabbedPane.closeTabs(tabIds); } @@ -480,12 +501,15 @@ _restoreEditorProperties(editorView, selection, firstLineNumber) { const sourceFrame = editorView instanceof SourceFrame.SourceFrame ? /** @type {!SourceFrame.SourceFrame} */ (editorView) : null; - if (!sourceFrame) + if (!sourceFrame) { return; - if (selection) + } + if (selection) { sourceFrame.setSelection(selection); - if (typeof firstLineNumber === 'number') + } + if (typeof firstLineNumber === 'number') { sourceFrame.scrollToLine(firstLineNumber); + } } /** @@ -508,8 +532,9 @@ this.dispatchEventToListeners(Sources.TabbedEditorContainer.Events.EditorClosed, uiSourceCode); - if (userGesture) + if (userGesture) { this._editorClosedByUserAction(uiSourceCode); + } } /** @@ -648,8 +673,9 @@ * @return {?Object} */ serializeToObject() { - if (!this._isSerializable) + if (!this._isSerializable) { return null; + } const serializedHistoryItem = {}; serializedHistoryItem.url = this.url; serializedHistoryItem.selectionRange = this.selectionRange; @@ -679,8 +705,9 @@ */ static fromObject(serializedHistory) { const items = []; - for (let i = 0; i < serializedHistory.length; ++i) + for (let i = 0; i < serializedHistory.length; ++i) { items.push(Sources.TabbedEditorContainer.HistoryItem.fromObject(serializedHistory[i])); + } return new Sources.TabbedEditorContainer.History(items); } @@ -715,11 +742,13 @@ * @param {!TextUtils.TextRange=} selectionRange */ updateSelectionRange(url, selectionRange) { - if (!selectionRange) + if (!selectionRange) { return; + } const index = this.index(url); - if (index === -1) + if (index === -1) { return; + } this._items[index].selectionRange = selectionRange; } @@ -738,8 +767,9 @@ */ updateScrollLineNumber(url, scrollLineNumber) { const index = this.index(url); - if (index === -1) + if (index === -1) { return; + } this._items[index].scrollLineNumber = scrollLineNumber; } @@ -786,10 +816,12 @@ const serializedHistory = []; for (let i = 0; i < this._items.length; ++i) { const serializedItem = this._items[i].serializeToObject(); - if (serializedItem) + if (serializedItem) { serializedHistory.push(serializedItem); - if (serializedHistory.length === Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount) + } + if (serializedHistory.length === Sources.TabbedEditorContainer.maximalPreviouslyViewedFilesCount) { break; + } } return serializedHistory; } @@ -799,8 +831,9 @@ */ _urls() { const result = []; - for (let i = 0; i < this._items.length; ++i) + for (let i = 0; i < this._items.length; ++i) { result.push(this._items[i].url); + } return result; } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/ThreadsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/sources/ThreadsSidebarPane.js index fdeef9a..229325b 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/ThreadsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/sources/ThreadsSidebarPane.js
@@ -53,8 +53,9 @@ */ function targetNameChanged(event) { const target = /** @type {!SDK.Target} */ (event.data); - if (target === debuggerModel.target()) + if (target === debuggerModel.target()) { updateTitle(); + } } debuggerModel.addEventListener(SDK.DebuggerModel.Events.DebuggerPaused, updatePausedState); @@ -94,12 +95,15 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected'); - if (toElement) + } + if (toElement) { toElement.classList.add('selected'); - if (to) + } + if (to) { UI.context.setFlavor(SDK.Target, to.target()); + } } /** @@ -109,8 +113,9 @@ modelAdded(debuggerModel) { this._items.insert(this._items.length, debuggerModel); const currentTarget = UI.context.flavor(SDK.Target); - if (currentTarget === debuggerModel.target()) + if (currentTarget === debuggerModel.target()) { this._list.selectItem(debuggerModel); + } } /** @@ -127,7 +132,8 @@ _targetFlavorChanged(event) { const target = /** @type {!SDK.Target} */ (event.data); const debuggerModel = target.model(SDK.DebuggerModel); - if (debuggerModel) + if (debuggerModel) { this._list.selectItem(debuggerModel); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/sources/UISourceCodeFrame.js b/third_party/blink/renderer/devtools/front_end/sources/UISourceCodeFrame.js index e4702d4..137d817 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/UISourceCodeFrame.js +++ b/third_party/blink/renderer/devtools/front_end/sources/UISourceCodeFrame.js
@@ -34,8 +34,9 @@ super(workingCopy); this._uiSourceCode = uiSourceCode; - if (Runtime.experiments.isEnabled('sourceDiff')) + if (Runtime.experiments.isEnabled('sourceDiff')) { this._diff = new SourceFrame.SourceCodeDiff(this.textEditor); + } this._muteSourceCodeEvents = false; this._isSettingContent = false; @@ -77,8 +78,9 @@ * @return {!Promise<string>} */ function workingCopy() { - if (uiSourceCode.isDirty()) + if (uiSourceCode.isDirty()) { return Promise.resolve(uiSourceCode.workingCopy()); + } return uiSourceCode.requestContent(); } } @@ -125,14 +127,17 @@ this._unloadUISourceCode(); this._uiSourceCode = uiSourceCode; if (uiSourceCode.contentLoaded()) { - if (uiSourceCode.workingCopy() !== this.textEditor.text()) + if (uiSourceCode.workingCopy() !== this.textEditor.text()) { this._innerSetContent(uiSourceCode.workingCopy()); + } } else { uiSourceCode.requestContent().then(() => { - if (this._uiSourceCode !== uiSourceCode) + if (this._uiSourceCode !== uiSourceCode) { return; - if (uiSourceCode.workingCopy() !== this.textEditor.text()) + } + if (uiSourceCode.workingCopy() !== this.textEditor.text()) { this._innerSetContent(uiSourceCode.workingCopy()); + } }); } this._initializeUISourceCode(); @@ -140,8 +145,9 @@ _unloadUISourceCode() { this._disposePlugins(); - for (const message of this._allMessages()) + for (const message of this._allMessages()) { this._removeMessageFromSource(message); + } Common.EventTarget.removeEventListeners(this._messageAndDecorationListeners); Common.EventTarget.removeEventListeners(this._uiSourceCodeEventListeners); this._uiSourceCode.removeWorkingCopyGetter(); @@ -159,8 +165,9 @@ ]; Persistence.persistence.subscribeForBindingEvent(this._uiSourceCode, this._boundOnBindingChanged); - for (const message of this._allMessages()) + for (const message of this._allMessages()) { this._addMessageToSource(message); + } this._installMessageAndDecorationListeners(); this._updateStyle(); this._decorateAllTypes(); @@ -180,16 +187,18 @@ // We need CodeMirrorTextEditor to be initialized prior to this call as it calls |cursorPositionToCoordinates| internally. @see crbug.com/506566 setImmediate(this._updateBucketDecorations.bind(this)); this.setEditable(this._canEditSource()); - for (const plugin of this._plugins) + for (const plugin of this._plugins) { plugin.wasShown(); + } } /** * @override */ willHide() { - for (const plugin of this._plugins) + for (const plugin of this._plugins) { plugin.willHide(); + } super.willHide(); UI.context.setFlavor(Sources.UISourceCodeFrame, null); this._uiSourceCode.removeWorkingCopyGetter(); @@ -198,8 +207,9 @@ _refreshHighlighterType() { const binding = Persistence.persistence.binding(this._uiSourceCode); const highlighterType = binding ? binding.network.mimeType() : this._uiSourceCode.mimeType(); - if (this.highlighterType() === highlighterType) + if (this.highlighterType() === highlighterType) { return; + } this._disposePlugins(); this.setHighlighterType(highlighterType); this._ensurePluginsLoaded(); @@ -209,18 +219,23 @@ * @return {boolean} */ _canEditSource() { - if (Persistence.persistence.binding(this._uiSourceCode)) + if (Persistence.persistence.binding(this._uiSourceCode)) { return true; - if (this._uiSourceCode.project().canSetFileContent()) + } + if (this._uiSourceCode.project().canSetFileContent()) { return true; - if (this._uiSourceCode.project().isServiceProject()) + } + if (this._uiSourceCode.project().isServiceProject()) { return false; + } if (this._uiSourceCode.project().type() === Workspace.projectTypes.Network && - Persistence.networkPersistenceManager.active()) + Persistence.networkPersistenceManager.active()) { return true; + } // Because live edit fails on large whitespace changes, pretty printed scripts are not editable. - if (this.pretty && this._uiSourceCode.contentType().hasScripts()) + if (this.pretty && this._uiSourceCode.contentType().hasScripts()) { return false; + } return this._uiSourceCode.contentType() !== Common.resourceTypes.Document; } @@ -229,8 +244,9 @@ } commitEditing() { - if (!this._uiSourceCode.isDirty()) + if (!this._uiSourceCode.isDirty()) { return; + } this._muteSourceCodeEvents = true; this._uiSourceCode.commitWorkingCopy(); @@ -245,8 +261,9 @@ this._disposePlugins(); this._rowMessageBuckets.clear(); super.setContent(content); - for (const message of this._allMessages()) + for (const message of this._allMessages()) { this._addMessageToSource(message); + } this._decorateAllTypes(); this._ensurePluginsLoaded(); } @@ -272,14 +289,16 @@ const wasPretty = this.pretty; super.onTextChanged(oldRange, newRange); this._errorPopoverHelper.hidePopover(); - if (this._isSettingContent) + if (this._isSettingContent) { return; + } Sources.SourcesPanel.instance().updateLastModificationTime(); this._muteSourceCodeEvents = true; - if (this.isClean()) + if (this.isClean()) { this._uiSourceCode.resetWorkingCopy(); - else + } else { this._uiSourceCode.setWorkingCopyGetter(this.textEditor.text.bind(this.textEditor)); + } this._muteSourceCodeEvents = false; if (wasPretty !== this.pretty) { this._updateStyle(); @@ -292,8 +311,9 @@ * @param {!Common.Event} event */ _onWorkingCopyChanged(event) { - if (this._muteSourceCodeEvents) + if (this._muteSourceCodeEvents) { return; + } this._innerSetContent(this._uiSourceCode.workingCopy()); } @@ -301,51 +321,62 @@ * @param {!Common.Event} event */ _onWorkingCopyCommitted(event) { - if (!this._muteSourceCodeEvents) + if (!this._muteSourceCodeEvents) { this._innerSetContent(this._uiSourceCode.workingCopy()); + } this.contentCommitted(); this._updateStyle(); } _ensurePluginsLoaded() { - if (!this.loaded || this._plugins.length) + if (!this.loaded || this._plugins.length) { return; + } const binding = Persistence.persistence.binding(this._uiSourceCode); const pluginUISourceCode = binding ? binding.network : this._uiSourceCode; // The order of these plugins matters for toolbar items - if (Sources.DebuggerPlugin.accepts(pluginUISourceCode)) + if (Sources.DebuggerPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.DebuggerPlugin(this.textEditor, pluginUISourceCode, this.transformer())); - if (Sources.CSSPlugin.accepts(pluginUISourceCode)) + } + if (Sources.CSSPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.CSSPlugin(this.textEditor)); - if (!this.pretty && Sources.JavaScriptCompilerPlugin.accepts(pluginUISourceCode)) + } + if (!this.pretty && Sources.JavaScriptCompilerPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.JavaScriptCompilerPlugin(this.textEditor, pluginUISourceCode)); - if (Sources.SnippetsPlugin.accepts(pluginUISourceCode)) + } + if (Sources.SnippetsPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.SnippetsPlugin(this.textEditor, pluginUISourceCode)); - if (Sources.ScriptOriginPlugin.accepts(pluginUISourceCode)) + } + if (Sources.ScriptOriginPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.ScriptOriginPlugin(this.textEditor, pluginUISourceCode)); + } if (!this.pretty && Runtime.experiments.isEnabled('sourceDiff') && - Sources.GutterDiffPlugin.accepts(pluginUISourceCode)) + Sources.GutterDiffPlugin.accepts(pluginUISourceCode)) { this._plugins.push(new Sources.GutterDiffPlugin(this.textEditor, pluginUISourceCode)); + } this.dispatchEventToListeners(Sources.UISourceCodeFrame.Events.ToolbarItemsChanged); - for (const plugin of this._plugins) + for (const plugin of this._plugins) { plugin.wasShown(); + } } _disposePlugins() { this.textEditor.operation(() => { - for (const plugin of this._plugins) + for (const plugin of this._plugins) { plugin.dispose(); + } }); this._plugins = []; } _onBindingChanged() { const binding = Persistence.persistence.binding(this._uiSourceCode); - if (binding === this._persistenceBinding) + if (binding === this._persistenceBinding) { return; + } this._unloadUISourceCode(); this._persistenceBinding = binding; this._initializeUISourceCode(); @@ -361,10 +392,12 @@ _innerSetContent(content) { this._isSettingContent = true; const oldContent = this.textEditor.text(); - if (this._diff) + if (this._diff) { this._diff.highlightModifiedLines(oldContent, content); - if (oldContent !== content) + } + if (oldContent !== content) { this.setContent(content); + } this._isSettingContent = false; } @@ -378,8 +411,9 @@ const location = this.transformer().editorToRawLocation(editorLineNumber, editorColumnNumber); contextMenu.appendApplicableItems(new Workspace.UILocation(this._uiSourceCode, location[0], location[1])); contextMenu.appendApplicableItems(this); - for (const plugin of this._plugins) + for (const plugin of this._plugins) { await plugin.populateTextAreaContextMenu(contextMenu, editorLineNumber, editorColumnNumber); + } } dispose() { @@ -403,14 +437,17 @@ * @param {!Workspace.UISourceCode.Message} message */ _addMessageToSource(message) { - if (!this.loaded) + if (!this.loaded) { return; + } const editorLocation = this.transformer().rawToEditorLocation(message.lineNumber(), message.columnNumber()); let editorLineNumber = editorLocation[0]; - if (editorLineNumber >= this.textEditor.linesCount) + if (editorLineNumber >= this.textEditor.linesCount) { editorLineNumber = this.textEditor.linesCount - 1; - if (editorLineNumber < 0) + } + if (editorLineNumber < 0) { editorLineNumber = 0; + } let messageBucket = this._rowMessageBuckets.get(editorLineNumber); if (!messageBucket) { @@ -432,19 +469,23 @@ * @param {!Workspace.UISourceCode.Message} message */ _removeMessageFromSource(message) { - if (!this.loaded) + if (!this.loaded) { return; + } const editorLocation = this.transformer().rawToEditorLocation(message.lineNumber(), message.columnNumber()); let editorLineNumber = editorLocation[0]; - if (editorLineNumber >= this.textEditor.linesCount) + if (editorLineNumber >= this.textEditor.linesCount) { editorLineNumber = this.textEditor.linesCount - 1; - if (editorLineNumber < 0) + } + if (editorLineNumber < 0) { editorLineNumber = 0; + } const messageBucket = this._rowMessageBuckets.get(editorLineNumber); - if (!messageBucket) + if (!messageBucket) { return; + } messageBucket.removeMessage(message); if (!messageBucket.uniqueMessagesCount()) { messageBucket.detachFromEditor(); @@ -459,8 +500,9 @@ _getErrorPopoverContent(event) { const element = event.target.enclosingNodeOrSelfWithClass('text-editor-line-decoration-icon') || event.target.enclosingNodeOrSelfWithClass('text-editor-line-decoration-wave'); - if (!element) + if (!element) { return null; + } const anchor = element.enclosingNodeOrSelfWithClass('text-editor-line-decoration-icon') ? element.boxInWindow() : new AnchorBox(event.clientX, event.clientY, 1, 1); @@ -476,8 +518,9 @@ } _updateBucketDecorations() { - for (const bucket of this._rowMessageBuckets.values()) + for (const bucket of this._rowMessageBuckets.values()) { bucket._updateDecoration(); + } } /** @@ -500,8 +543,9 @@ * @param {string} type */ async _decorateTypeThrottled(type) { - if (this._typeDecorationsPending.has(type)) + if (this._typeDecorationsPending.has(type)) { return; + } this._typeDecorationsPending.add(type); const decorator = await self.runtime.extensions(SourceFrame.LineDecorator) .find(extension => extension.descriptor()['decoratorType'] === type) @@ -514,12 +558,14 @@ } _decorateAllTypes() { - if (!this.loaded) + if (!this.loaded) { return; + } for (const extension of self.runtime.extensions(SourceFrame.LineDecorator)) { const type = extension.descriptor()['decoratorType']; - if (this._uiSourceCode.decorationsForType(type)) + if (this._uiSourceCode.decorationsForType(type)) { this._decorateTypeThrottled(type); + } } } @@ -535,8 +581,9 @@ rightToolbarItems.pushAll(plugin.rightToolbarItems()); } - if (!rightToolbarItems.length) + if (!rightToolbarItems.length) { return leftToolbarItems; + } return [...leftToolbarItems, new UI.ToolbarSeparator(true), ...rightToolbarItems]; } @@ -549,8 +596,9 @@ */ async populateLineGutterContextMenu(contextMenu, lineNumber) { await super.populateLineGutterContextMenu(contextMenu, lineNumber); - for (const plugin of this._plugins) + for (const plugin of this._plugins) { await plugin.populateLineGutterContextMenu(contextMenu, lineNumber); + } } }; @@ -607,8 +655,9 @@ } setRepeatCount(repeatCount) { - if (this._repeatCount === repeatCount) + if (this._repeatCount === repeatCount) { return; + } this._repeatCount = repeatCount; this._updateMessageRepeatCount(); } @@ -655,10 +704,12 @@ columnNumber = Math.min(columnNumber, lineText.length); const lineIndent = TextUtils.TextUtils.lineIndent(lineText).length; const startColumn = Math.max(columnNumber - 1, lineIndent); - if (this._decorationStartColumn === startColumn) + if (this._decorationStartColumn === startColumn) { return; - if (this._decorationStartColumn !== null) + } + if (this._decorationStartColumn !== null) { this.textEditor.removeDecoration(this._decoration, editorLineNumber); + } this.textEditor.addDecoration(this._decoration, editorLineNumber, startColumn); this._decorationStartColumn = startColumn; } @@ -669,16 +720,18 @@ messagesDescription() { this._messagesDescriptionElement.removeChildren(); UI.appendStyle(this._messagesDescriptionElement, 'source_frame/messagesPopover.css'); - for (let i = 0; i < this._messages.length; ++i) + for (let i = 0; i < this._messages.length; ++i) { this._messagesDescriptionElement.appendChild(this._messages[i].element); + } return this._messagesDescriptionElement; } detachFromEditor() { const position = this._lineHandle.resolve(); - if (!position) + if (!position) { return; + } const editorLineNumber = position.lineNumber; if (this._level) { this.textEditor.toggleLineClass( @@ -720,24 +773,29 @@ removeMessage(message) { for (let i = 0; i < this._messages.length; ++i) { const rowMessage = this._messages[i]; - if (!rowMessage.message().isEqual(message)) + if (!rowMessage.message().isEqual(message)) { continue; + } rowMessage.setRepeatCount(rowMessage.repeatCount() - 1); - if (!rowMessage.repeatCount()) + if (!rowMessage.repeatCount()) { this._messages.splice(i, 1); + } this._updateDecoration(); return; } } _updateDecoration() { - if (!this._sourceFrame.isShowing()) + if (!this._sourceFrame.isShowing()) { return; - if (!this._messages.length) + } + if (!this._messages.length) { return; + } const position = this._lineHandle.resolve(); - if (!position) + if (!position) { return; + } const editorLineNumber = position.lineNumber; let columnNumber = Number.MAX_VALUE; @@ -747,21 +805,24 @@ const editorLocation = this._sourceFrame.transformer().rawToEditorLocation(editorLineNumber, message.columnNumber()); columnNumber = Math.min(columnNumber, editorLocation[1]); - if (!maxMessage || Workspace.UISourceCode.Message.messageLevelComparator(maxMessage, message) < 0) + if (!maxMessage || Workspace.UISourceCode.Message.messageLevelComparator(maxMessage, message) < 0) { maxMessage = message; + } } this._updateWavePosition(editorLineNumber, columnNumber); - if (this._level === maxMessage.level()) + if (this._level === maxMessage.level()) { return; + } if (this._level) { this.textEditor.toggleLineClass( editorLineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], false); this._icon.type = ''; } this._level = maxMessage.level(); - if (!this._level) + if (!this._level) { return; + } this.textEditor.toggleLineClass(editorLineNumber, Sources.UISourceCodeFrame._lineClassPerLevel[this._level], true); this._icon.type = Sources.UISourceCodeFrame._iconClassPerLevel[this._level]; }
diff --git a/third_party/blink/renderer/devtools/front_end/sources/WatchExpressionsSidebarPane.js b/third_party/blink/renderer/devtools/front_end/sources/WatchExpressionsSidebarPane.js index 7373762..2681def8 100644 --- a/third_party/blink/renderer/devtools/front_end/sources/WatchExpressionsSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/sources/WatchExpressionsSidebarPane.js
@@ -76,8 +76,9 @@ _saveExpressions() { const toSave = []; for (let i = 0; i < this._watchExpressions.length; i++) { - if (this._watchExpressions[i].expression()) + if (this._watchExpressions[i].expression()) { toSave.push(this._watchExpressions[i].expression()); + } } this._watchExpressionsSetting.set(toSave); @@ -101,8 +102,9 @@ const watchExpressionStrings = this._watchExpressionsSetting.get(); for (let i = 0; i < watchExpressionStrings.length; ++i) { const expression = watchExpressionStrings[i]; - if (!expression) + if (!expression) { continue; + } this._createWatchExpression(expression); } @@ -152,11 +154,13 @@ */ _populateContextMenu(contextMenu, event) { let isEditing = false; - for (const watchExpression of this._watchExpressions) + for (const watchExpression of this._watchExpressions) { isEditing |= watchExpression.isEditing(); + } - if (!isEditing) + if (!isEditing) { contextMenu.debugSection().appendItem(Common.UIString('Add watch expression'), this._addButtonClicked.bind(this)); + } if (this._watchExpressions.length > 1) { contextMenu.debugSection().appendItem( @@ -165,11 +169,13 @@ const target = event.deepElementFromPoint(); - if (!target) + if (!target) { return; + } for (const watchExpression of this._watchExpressions) { - if (watchExpression.element().isSelfOrAncestor(target)) + if (watchExpression.element().isSelfOrAncestor(target)) { watchExpression._populateContextMenu(contextMenu, event); + } } } @@ -204,8 +210,9 @@ */ handleAction(context, actionId) { const frame = UI.context.flavor(Sources.UISourceCodeFrame); - if (!frame) + if (!frame) { return false; + } const text = frame.textEditor.text(frame.textEditor.selection()); this._focusAndAddExpressionToWatch(text); return true; @@ -231,8 +238,9 @@ } const frame = UI.context.flavor(Sources.UISourceCodeFrame); - if (!frame || frame.textEditor.selection().isEmpty()) + if (!frame || frame.textEditor.selection().isEmpty()) { return; + } contextMenu.debugSection().appendAction('sources.add-to-watch'); } @@ -317,8 +325,9 @@ * @param {boolean=} canceled */ _finishEditing(event, canceled) { - if (event) + if (event) { event.consume(canceled); + } this._editing = false; this._textPrompt.detach(); @@ -334,16 +343,18 @@ */ _dblClickOnWatchExpression(event) { event.consume(); - if (!this.isEditing()) + if (!this.isEditing()) { this.startEditing(); + } } /** * @param {?string} newExpression */ _updateExpression(newExpression) { - if (this._expression) + if (this._expression) { this._expandController.stopWatchSectionsWithId(this._expression); + } this._expression = newExpression; this.update(); this.dispatchEventToListeners(Sources.WatchExpression.Events.ExpressionUpdated, this); @@ -420,14 +431,16 @@ * @this {Sources.WatchExpression} */ function handleClick() { - if (!this._objectPropertiesSection) + if (!this._objectPropertiesSection) { return; + } const objectTreeElement = this._objectPropertiesSection.objectTreeElement(); - if (objectTreeElement.expanded) + if (objectTreeElement.expanded) { objectTreeElement.collapse(); - else + } else { objectTreeElement.expand(); + } } } @@ -435,8 +448,9 @@ * @param {!Event} event */ _promptKeyDown(event) { - if (isEnterKey(event) || isEscKey(event)) + if (isEnterKey(event) || isEscKey(event)) { this._finishEditing(event, isEscKey(event)); + } } /** @@ -450,12 +464,14 @@ } - if (!this.isEditing() && this._result && (this._result.type === 'number' || this._result.type === 'string')) + if (!this.isEditing() && this._result && (this._result.type === 'number' || this._result.type === 'string')) { contextMenu.clipboardSection().appendItem(Common.UIString('Copy value'), this._copyValueButtonClicked.bind(this)); + } const target = event.deepElementFromPoint(); - if (target && this._valueElement.isSelfOrAncestor(target)) + if (target && this._valueElement.isSelfOrAncestor(target)) { contextMenu.appendApplicableItems(this._result); + } } _copyValueButtonClicked() {
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/AutocompleteTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/AutocompleteTestRunner.js index 496c83b3..2169afb6 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/AutocompleteTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/AutocompleteTestRunner.js
@@ -22,8 +22,9 @@ } } - if (lineNumber === -1) + if (lineNumber === -1) { throw new Error('Test case is invalid: cursor position is not marked with \'|\' symbol.'); + } textEditor.setText(lines.join('\n').replace('|', '')); textEditor.setSelection(TextUtils.TextRange.createFromLocation(lineNumber, columnNumber));
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js index 0c423a9..fa3790d 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/DebuggerTestRunner.js
@@ -10,8 +10,9 @@ SourcesTestRunner.startDebuggerTest = function(callback, quiet) { console.assert(TestRunner.debuggerModel.debuggerEnabled(), 'Debugger has to be enabled'); - if (quiet !== undefined) + if (quiet !== undefined) { SourcesTestRunner._quiet = quiet; + } UI.viewManager.showView('sources'); TestRunner.addSniffer(SDK.DebuggerModel.prototype, '_pausedScript', SourcesTestRunner._pausedScript, true); @@ -139,10 +140,11 @@ SourcesTestRunner.waitUntilPaused = function(callback) { callback = TestRunner.safeWrap(callback); - if (SourcesTestRunner._pausedScriptArguments) + if (SourcesTestRunner._pausedScriptArguments) { callback.apply(callback, SourcesTestRunner._pausedScriptArguments); - else + } else { SourcesTestRunner._waitUntilPausedCallback = callback; + } }; SourcesTestRunner.waitUntilPausedPromise = function() { @@ -156,10 +158,11 @@ SourcesTestRunner.waitUntilResumed = function(callback) { callback = TestRunner.safeWrap(callback); - if (!SourcesTestRunner._pausedScriptArguments) + if (!SourcesTestRunner._pausedScriptArguments) { callback(); - else + } else { SourcesTestRunner._waitUntilResumedCallback = callback; + } }; SourcesTestRunner.waitUntilResumedPromise = function() { @@ -167,8 +170,9 @@ }; SourcesTestRunner.resumeExecution = function(callback) { - if (UI.panels.sources.paused()) + if (UI.panels.sources.paused()) { UI.panels.sources._togglePause(); + } SourcesTestRunner.waitUntilResumed(callback); }; @@ -184,16 +188,18 @@ const statusElement = this.element.querySelector('.paused-message'); caption = statusElement.deepTextContent(); - if (callFrames) + if (callFrames) { step1(); + } } function paused(frames, reason, breakpointIds, async) { callFrames = frames; asyncStackTrace = async; - if (typeof caption === 'string') + if (typeof caption === 'string') { step1(); + } } function step1() { @@ -248,8 +254,9 @@ SourcesTestRunner.captureStackTrace(callFrames, asyncStackTrace); TestRunner.addResult(''); - while (action === 'Print') + while (action === 'Print') { action = actions.shift(); + } } if (!action) { @@ -302,8 +309,9 @@ const isFramework = uiLocation ? Bindings.blackboxManager.isBlackboxedUISourceCode(uiLocation.uiSourceCode) : false; - if (options.dropFrameworkCallFrames && isFramework) + if (options.dropFrameworkCallFrames && isFramework) { continue; + } let url; let lineNumber; @@ -321,14 +329,16 @@ s = s.replace(/scheduleTestFunction.+$/, 'scheduleTestFunction <omitted>'); results.push(s); - if (options.printReturnValue && returnValueFunction && returnValueFunction.call(frame)) + if (options.printReturnValue && returnValueFunction && returnValueFunction.call(frame)) { results.push(' <return>: ' + returnValueFunction.call(frame).description); + } if (frame.functionName === 'scheduleTestFunction') { const remainingFrames = callFrames.length - 1 - i; - if (remainingFrames) + if (remainingFrames) { results.push(' <... skipped remaining frames ...>'); + } break; } @@ -349,8 +359,9 @@ results.push(' [' + (asyncStackTrace.description || 'Async Call') + ']'); const printed = printCallFrames(asyncStackTrace.callFrames, runtimeCallFramePosition); - if (!printed) + if (!printed) { results.pop(); + } asyncStackTrace = asyncStackTrace.parent; } @@ -362,15 +373,17 @@ TestRunner.addResult('==Source frame contents start=='); const textEditor = sourceFrame._textEditor; - for (let i = 0; i < textEditor.linesCount; ++i) + for (let i = 0; i < textEditor.linesCount; ++i) { TestRunner.addResult(textEditor.line(i)); + } TestRunner.addResult('==Source frame contents end=='); }; SourcesTestRunner._pausedScript = function(callFrames, reason, auxData, breakpointIds, asyncStackTrace) { - if (!SourcesTestRunner._quiet) + if (!SourcesTestRunner._quiet) { TestRunner.addResult('Script execution paused.'); + } const debuggerModel = this.target().model(SDK.DebuggerModel); SourcesTestRunner._pausedScriptArguments = [ @@ -386,8 +399,9 @@ }; SourcesTestRunner._resumedScript = function() { - if (!SourcesTestRunner._quiet) + if (!SourcesTestRunner._quiet) { TestRunner.addResult('Script execution resumed.'); + } delete SourcesTestRunner._pausedScriptArguments; @@ -403,10 +417,11 @@ panel.showUISourceCode(uiSourceCode); const sourceFrame = panel.visibleView; - if (sourceFrame.loaded) + if (sourceFrame.loaded) { callback(sourceFrame); - else + } else { TestRunner.addSniffer(sourceFrame, 'setContent', callback && callback.bind(null, sourceFrame)); + } }; SourcesTestRunner.showUISourceCodePromise = function(uiSourceCode) { @@ -433,8 +448,9 @@ const uiSourceCodes = panel._workspace.uiSourceCodes(); for (let i = 0; i < uiSourceCodes.length; ++i) { - if (uiSourceCodes[i].project().type() === Workspace.projectTypes.Service) + if (uiSourceCodes[i].project().type() === Workspace.projectTypes.Service) { continue; + } if (uiSourceCodes[i].name() === scriptName) { callback(uiSourceCodes[i]); @@ -457,8 +473,9 @@ SourcesTestRunner.setBreakpoint = function(sourceFrame, lineNumber, condition, enabled) { const debuggerPlugin = SourcesTestRunner.debuggerPlugin(sourceFrame); - if (!debuggerPlugin._muted) + if (!debuggerPlugin._muted) { debuggerPlugin._setBreakpoint(lineNumber, 0, condition, enabled); + } }; SourcesTestRunner.removeBreakpoint = function(sourceFrame, lineNumber) { @@ -480,8 +497,9 @@ SourcesTestRunner.toggleBreakpoint = function(sourceFrame, lineNumber, disableOnly) { const debuggerPlugin = SourcesTestRunner.debuggerPlugin(sourceFrame); - if (!debuggerPlugin._muted) + if (!debuggerPlugin._muted) { debuggerPlugin._toggleBreakpoint(lineNumber, disableOnly); + } }; SourcesTestRunner.waitBreakpointSidebarPane = function(waitUntilResolved) { @@ -491,12 +509,14 @@ .then(checkIfReady); function checkIfReady() { - if (!waitUntilResolved) + if (!waitUntilResolved) { return; + } for (const {breakpoint} of Bindings.breakpointManager.allBreakpointLocations()) { - if (breakpoint._uiLocations.size === 0 && breakpoint.enabled()) + if (breakpoint._uiLocations.size === 0 && breakpoint.enabled()) { return SourcesTestRunner.waitBreakpointSidebarPane(); + } } } }; @@ -505,8 +525,9 @@ const paneElement = self.runtime.sharedInstance(Sources.JavaScriptBreakpointsSidebarPane).contentElement; const empty = paneElement.querySelector('.gray-info-message'); - if (empty) + if (empty) { return TestRunner.textContentWithLineBreaks(empty); + } const entries = Array.from(paneElement.querySelectorAll('.breakpoint-entry')); return entries.map(TestRunner.textContentWithLineBreaks).join('\n'); @@ -525,11 +546,13 @@ const textContent = TestRunner.textContentWithLineBreaks(sections[i].element); const text = TestRunner.clearSpecificInfoFromStackFrames(textContent); - if (text.length > 0) + if (text.length > 0) { TestRunner.addResult(text); + } - if (!sections[i].objectTreeElement().expanded) + if (!sections[i].objectTreeElement().expanded) { TestRunner.addResult(' <section collapsed>'); + } } }; @@ -537,8 +560,9 @@ const children = self.runtime.sharedInstance(Sources.ScopeChainSidebarPane).contentElement.children; const sections = []; - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { sections.push(children[i]._section); + } return sections; }; @@ -546,8 +570,9 @@ SourcesTestRunner.expandScopeVariablesSidebarPane = function(callback) { const sections = SourcesTestRunner.scopeChainSections(); - for (let i = 0; i < sections.length - 1; ++i) + for (let i = 0; i < sections.length - 1; ++i) { sections[i].expand(); + } TestRunner.deprecatedRunAfterPendingDispatches(callback); }; @@ -597,8 +622,9 @@ const treeElement = children[i]; const property = treeElement.property; - if (property.name === childName) + if (property.name === childName) { return treeElement; + } } }; @@ -632,8 +658,9 @@ return Promise.resolve(trimmedSource); }; - if (preRegisterCallback) + if (preRegisterCallback) { preRegisterCallback(script); + } debuggerModel._registerScript(script); return script; @@ -665,8 +692,9 @@ SourcesTestRunner.scriptFormatter = function() { return self.runtime.allInstances(Sources.SourcesView.EditorAction).then(function(editorActions) { for (let i = 0; i < editorActions.length; ++i) { - if (editorActions[i] instanceof Sources.ScriptFormatterEditorAction) + if (editorActions[i] instanceof Sources.ScriptFormatterEditorAction) { return editorActions[i]; + } } return null; @@ -707,8 +735,9 @@ function checkIfReady() { for (const {breakpoint} of Bindings.breakpointManager.allBreakpointLocations()) { - if (breakpoint._uiLocations.size === 0 && breakpoint.enabled()) + if (breakpoint._uiLocations.size === 0 && breakpoint.enabled()) { return SourcesTestRunner.waitDebuggerPluginDecorations().then(checkIfReady); + } } return Promise.resolve(); @@ -719,8 +748,9 @@ const textEditor = sourceFrame._textEditor; for (let lineNumber = 0; lineNumber < textEditor.linesCount; ++lineNumber) { - if (!textEditor.hasLineClass(lineNumber, 'cm-breakpoint')) + if (!textEditor.hasLineClass(lineNumber, 'cm-breakpoint')) { continue; + } const disabled = textEditor.hasLineClass(lineNumber, 'cm-breakpoint-disabled'); const conditional = textEditor.hasLineClass(lineNumber, 'cm-breakpoint-conditional'); @@ -765,8 +795,9 @@ }; SourcesTestRunner.waitUntilDebuggerPluginLoaded = async function(sourceFrame) { - while (!SourcesTestRunner.debuggerPlugin(sourceFrame)) + while (!SourcesTestRunner.debuggerPlugin(sourceFrame)) { await TestRunner.addSnifferPromise(sourceFrame, '_ensurePluginsLoaded'); + } return SourcesTestRunner.debuggerPlugin(sourceFrame); }; @@ -775,8 +806,9 @@ const auxData = {'eventName': id}; - if (targetName) + if (targetName) { auxData.targetName = targetName; + } const breakpoint = SDK.domDebuggerManager.resolveEventListenerBreakpoint(auxData);
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/EditorTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/EditorTestRunner.js index a693414f..ef530848 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/EditorTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/EditorTestRunner.js
@@ -18,8 +18,9 @@ }; function textWithSelection(text, selections) { - if (!selections.length) + if (!selections.length) { return text; + } function lineWithCursor(line, column, cursorChar) { return line.substring(0, column) + cursorChar + line.substring(column); @@ -34,8 +35,9 @@ const endCursorChar = (selection.isEmpty() ? '|' : '<'); lines[selection.endLine] = lineWithCursor(lines[selection.endLine], selection.endColumn, endCursorChar); - if (!selection.isEmpty()) + if (!selection.isEmpty()) { lines[selection.startLine] = lineWithCursor(lines[selection.startLine], selection.startColumn, '>'); + } } return lines.join('\n'); @@ -44,8 +46,9 @@ SourcesTestRunner.dumpTextWithSelection = function(textEditor, dumpWhiteSpaces) { let text = textWithSelection(textEditor.text(), textEditor.selections()); - if (dumpWhiteSpaces) + if (dumpWhiteSpaces) { text = text.replace(/ /g, '.'); + } TestRunner.addResult(text); }; @@ -121,8 +124,9 @@ }; if (modifiers) { - for (let i = 0; i < modifiers.length; ++i) + for (let i = 0; i < modifiers.length; ++i) { event[modifiers[i]] = true; + } } return event; @@ -149,8 +153,9 @@ } function fakeCodeMirrorInputEvent(editor, character) { - if (typeof character !== 'string') + if (typeof character !== 'string') { return; + } const input = editor._codeMirror.display.input; const value = input.textarea.value; const newValue = @@ -181,8 +186,9 @@ code = code || eventCodes[originalCode] || originalCode; - if (typeof code === 'string') + if (typeof code === 'string') { code = code.charCodeAt(0); + } if (fakeCodeMirrorKeyEvent(editor, 'keydown', code, charCode, modifiers)) { callback(); @@ -220,10 +226,11 @@ for (let i = 0; i < sortedKeys.length; ++i) { let keyName = sortedKeys[i]; - if (!keyName.length) + if (!keyName.length) { keyName = '<Empty string>'; - else + } else { keyName = '\'' + keyName + '\''; + } TestRunner.addResult(keyName + ': ' + listHashMap[sortedKeys[i]]); }
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/LiveEditTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/LiveEditTestRunner.js index 3136a0a..bb975c6 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/LiveEditTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/LiveEditTestRunner.js
@@ -14,8 +14,9 @@ const line = sourceFrame._textEditor.line(i); const column = line.indexOf(string); - if (column === -1) + if (column === -1) { continue; + } const range = new TextUtils.TextRange(i, column, i, column + string.length); sourceFrame._textEditor.editRange(range, replacement);
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/SearchTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/SearchTestRunner.js index 5a601dd..5849ddf1 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/SearchTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/SearchTestRunner.js
@@ -55,8 +55,9 @@ const uiSourceCode = searchResult._uiSourceCode; const searchMatches = searchResult._searchMatches; - if (!searchMatches.length) + if (!searchMatches.length) { continue; + } TestRunner.addResult( 'Search result #' + (i + 1) + ': uiSourceCode.url = ' + uiSourceCode.url().replace(/VM\d+/, 'VMXX')); @@ -76,14 +77,17 @@ SourcesTestRunner.replaceAndDumpChange = function(sourceFrame, searchConfig, replacement, replaceAll) { const modifiers = []; - if (searchConfig.isRegex) + if (searchConfig.isRegex) { modifiers.push('regex'); + } - if (searchConfig.caseSensitive) + if (searchConfig.caseSensitive) { modifiers.push('caseSensitive'); + } - if (replaceAll) + if (replaceAll) { modifiers.push('replaceAll'); + } const modifiersString = (modifiers.length ? ' (' + modifiers.join(', ') + ')' : ''); TestRunner.addResult( @@ -91,8 +95,9 @@ editor = sourceFrame._textEditor; const oldLines = []; - for (let i = 0; i < editor.linesCount; ++i) + for (let i = 0; i < editor.linesCount; ++i) { oldLines.push(editor.line(i)); + } const searchableView = UI.panels.sources.sourcesView().searchableView(); searchableView.showSearchField(); @@ -104,33 +109,38 @@ searchableView._replaceInputElement.value = replacement; searchableView._performSearch(true, true); - if (replaceAll) + if (replaceAll) { searchableView._replaceAll(); - else + } else { searchableView._replace(); + } const newLines = []; - for (let i = 0; i < editor.linesCount; ++i) + for (let i = 0; i < editor.linesCount; ++i) { newLines.push(editor.line(i)); + } for (let i = 0; i < newLines.length; ++i) { - if (oldLines[i] === newLines[i]) + if (oldLines[i] === newLines[i]) { continue; + } const oldLine = oldLines[i]; const newLine = newLines[i]; let prefixLength = 0; - for (let j = 0; j < oldLine.length && j < newLine.length && newLine[j] === oldLine[j]; ++j) + for (let j = 0; j < oldLine.length && j < newLine.length && newLine[j] === oldLine[j]; ++j) { ++prefixLength; + } let postfixLength = 0; for (let j = 0; j < oldLine.length && j < newLine.length && newLine[newLine.length - j - 1] === oldLine[oldLine.length - j - 1]; - ++j) + ++j) { ++postfixLength; + } const prefix = oldLine.substring(0, prefixLength); const removed = oldLine.substring(prefixLength, oldLine.length - postfixLength);
diff --git a/third_party/blink/renderer/devtools/front_end/sources_test_runner/SourcesTestRunner.js b/third_party/blink/renderer/devtools/front_end/sources_test_runner/SourcesTestRunner.js index d589808..0d35fd1 100644 --- a/third_party/blink/renderer/devtools/front_end/sources_test_runner/SourcesTestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/sources_test_runner/SourcesTestRunner.js
@@ -24,21 +24,24 @@ let icons = treeElement._leadingIconsElement.querySelectorAll('[is=ui-icon]'); icons = Array.prototype.slice.call(icons); const iconTypes = icons.map(icon => icon._iconType); - if (iconTypes.length) + if (iconTypes.length) { titleText = titleText + '[' + iconTypes.join(', ') + '] '; + } } titleText += treeElement.title; if (treeElement._nodeType === Sources.NavigatorView.Types.FileSystem || treeElement._nodeType === Sources.NavigatorView.Types.FileSystemFolder) { const hasMappedFiles = treeElement.listItemElement.classList.contains('has-mapped-files'); - if (!hasMappedFiles) + if (!hasMappedFiles) { titleText += ' [dimmed]'; + } } TestRunner.addResult(prefix + titleText); treeElement.expand(); const children = treeElement.children(); - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { dumpNavigatorTreeElement(prefix + ' ', children[i]); + } } /** @@ -46,8 +49,9 @@ */ function dumpNavigatorTreeOutline(treeOutline) { const children = treeOutline.rootElement().children(); - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { dumpNavigatorTreeElement('', children[i]); + } } }; @@ -82,8 +86,9 @@ */ SourcesTestRunner.addScriptUISourceCode = function(url, content, isContentScript, worldId) { content += '\n//# sourceURL=' + url; - if (isContentScript) + if (isContentScript) { content = `testRunner.evaluateScriptInIsolatedWorld(${worldId}, \`${content}\`)`; + } TestRunner.evaluateInPageAnonymously(content); return TestRunner.waitForUISourceCode(url); }; @@ -97,10 +102,11 @@ Formatter.Formatter.locationToPosition(text2.computeLineEndings(), formattedLocation[0], formattedLocation[1]); const expectedFormattedPosition = text2.indexOf(testToken); - if (expectedFormattedPosition === formattedPosition) + if (expectedFormattedPosition === formattedPosition) { TestRunner.addResult(String.sprintf('Correct mapping for <%s>', testToken)); - else + } else { TestRunner.addResult(String.sprintf('ERROR: Wrong mapping for <%s>', testToken)); + } } SourcesTestRunner.testPrettyPrint = function(mimeType, text, mappingQueries, next) { @@ -111,8 +117,9 @@ TestRunner.addResult(formattedSource); TestRunner.addResult('------ >8 ======'); - while (mappingQueries && mappingQueries.length) + while (mappingQueries && mappingQueries.length) { testSourceMapping(text, formattedSource, mapping, mappingQueries.shift()); + } next(); } @@ -128,15 +135,17 @@ function onChunk(isLastChunk, outlineItems) { items.pushAll(outlineItems); - if (!isLastChunk) + if (!isLastChunk) { return; + } TestRunner.addResult('Text:'); TestRunner.addResult(text.split('\n').map(line => ' ' + line).join('\n')); TestRunner.addResult('Outline:'); - for (const item of items) + for (const item of items) { TestRunner.addResult(' ' + item.name + (item.arguments || '') + ':' + item.line + ':' + item.column); + } fulfill(); }
diff --git a/third_party/blink/renderer/devtools/front_end/terminal/TerminalWidget.js b/third_party/blink/renderer/devtools/front_end/terminal/TerminalWidget.js index 1d7bfe35..4ec72111 100644 --- a/third_party/blink/renderer/devtools/front_end/terminal/TerminalWidget.js +++ b/third_party/blink/renderer/devtools/front_end/terminal/TerminalWidget.js
@@ -65,8 +65,9 @@ * @override */ onResize() { - if (this._term) + if (this._term) { this._term.fit(); + } } _disposed() { @@ -77,8 +78,9 @@ * @override */ ownerViewDisposed() { - if (this._backend) + if (this._backend) { this._backend.dispose(); + } } _linkify() { @@ -86,8 +88,9 @@ this._mutationObserver.disconnect(); this._linkifier.reset(); const rows = this._term['rowContainer'].children; - for (let i = 0; i < rows.length; i++) + for (let i = 0; i < rows.length; i++) { this._linkifyTerminalLine(rows[i]); + } this._mutationObserver.observe(this.contentElement, this._config); } @@ -101,8 +104,9 @@ while (string) { const linkString = regex1.exec(string) || regex2.exec(string); - if (!linkString) + if (!linkString) { break; + } const text = linkString[0]; const path = linkString[1]; @@ -124,8 +128,9 @@ string = string.substring(linkIndex + text.length); } - if (string) + if (string) { container.appendChild(createTextNode(string)); + } return container; }
diff --git a/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js b/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js index 9c71e667..eec2722 100644 --- a/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js +++ b/third_party/blink/renderer/devtools/front_end/test_runner/TestRunner.js
@@ -39,17 +39,19 @@ TestRunner.completeTest = () => console.log('Test completed'); // Auto-start unit tests - if (!self.testRunner) + if (!self.testRunner) { eval(`(function test(){${testScript}})()\n//# sourceURL=${testScriptURL}`); - else + } else { self.eval(`function test(){${testScript}}\n//# sourceURL=${testScriptURL}`); + } return; } // Convert the test script into an expression (if needed) testScript = testScript.trimRight(); - if (testScript.endsWith(';')) + if (testScript.endsWith(';')) { testScript = testScript.slice(0, testScript.length - 1); + } (async function() { try { @@ -107,10 +109,12 @@ * @param {!Array<string>} textArray */ TestRunner.addResults = function(textArray) { - if (!textArray) + if (!textArray) { return; - for (let i = 0, size = textArray.length; i < size; ++i) + } + for (let i = 0, size = textArray.length; i < size; ++i) { TestRunner.addResult(textArray[i]); + } }; /** @@ -127,8 +131,9 @@ } TestRunner.addResult('\ntest: ' + test.name); let testPromise = test(); - if (!(testPromise instanceof Promise)) + if (!(testPromise instanceof Promise)) { testPromise = Promise.resolve(); + } testPromise.then(nextTest); } }; @@ -143,16 +148,18 @@ override = TestRunner.safeWrap(override); const original = receiver[methodName]; - if (typeof original !== 'function') + if (typeof original !== 'function') { throw new Error('Cannot find method to override: ' + methodName); + } receiver[methodName] = function(var_args) { let result; try { result = original.apply(this, arguments); } finally { - if (!opt_sticky) + if (!opt_sticky) { receiver[methodName] = original; + } } // In case of exception the override won't be called. try { @@ -208,8 +215,9 @@ TestRunner.loadModule = async function(module) { const promise = new Promise(resolve => TestRunner._resolveOnFinishInits = resolve); await self.runtime.loadModulePromise(module); - if (!TestRunner._pendingInits) + if (!TestRunner._pendingInits) { return; + } return promise; }; @@ -253,17 +261,19 @@ * @this {*} */ function result() { - if (!func) + if (!func) { return; + } const wrapThis = this; try { return func.apply(wrapThis, arguments); } catch (e) { TestRunner.addResult('Exception while running: ' + func + '\n' + (e.stack || e)); - if (onexception) + if (onexception) { TestRunner.safeWrap(onexception)(); - else + } else { TestRunner.completeTest(); + } } } return result; @@ -281,8 +291,9 @@ * @this {*} */ async function result() { - if (!func) + if (!func) { return; + } const wrapThis = this; try { return await func.apply(wrapThis, arguments); @@ -303,8 +314,9 @@ let result = 0; while (currentNode && currentNode !== node) { if (currentNode.nodeName === 'OL' && - !(currentNode.classList && currentNode.classList.contains('object-properties-section'))) + !(currentNode.classList && currentNode.classList.contains('object-properties-section'))) { ++result; + } currentNode = currentNode.parentNode; } return Array(result * 4 + 1).join(' '); @@ -318,10 +330,11 @@ if (currentNode.nodeType === Node.TEXT_NODE) { buffer += currentNode.nodeValue; } else if (currentNode.nodeName === 'LI' || currentNode.nodeName === 'TR') { - if (!ignoreFirst) + if (!ignoreFirst) { buffer += '\n' + padding(currentNode); - else + } else { ignoreFirst = false; + } } else if (currentNode.nodeName === 'STYLE') { currentNode = currentNode.traverseNextNode(node); continue; @@ -341,10 +354,11 @@ let currentNode = node; while (currentNode.traverseNextNode(node)) { currentNode = currentNode.traverseNextNode(node); - if (currentNode.nodeType === Node.TEXT_NODE) + if (currentNode.nodeType === Node.TEXT_NODE) { buffer += currentNode.nodeValue; - else if (currentNode.nodeName === 'STYLE') + } else if (currentNode.nodeName === 'STYLE') { currentNode = currentNode.traverseNextNode(node); + } } return buffer; }; @@ -423,8 +437,9 @@ const sourceURL = `test://evaluations/${TestRunner._evaluateInPageCounter++}/` + fileName; const lineOffset = parseInt(source[1], 10); code = '\n'.repeat(lineOffset - 1) + code; - if (code.indexOf('sourceURL=') === -1) + if (code.indexOf('sourceURL=') === -1) { code += `//# sourceURL=${sourceURL}`; + } const response = await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'}); const error = response[Protocol.Error]; if (error) { @@ -445,8 +460,9 @@ TestRunner.evaluateInPageAnonymously = async function(code, userGesture) { const response = await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console', userGesture}); - if (!response[Protocol.Error]) + if (!response[Protocol.Error]) { return response.result.value; + } TestRunner.addResult( 'Error: ' + (response.exceptionDetails && response.exceptionDetails.text || 'exception from evaluateInPageAnonymously.')); @@ -470,8 +486,9 @@ {expression: code, objectGroup: 'console', includeCommandLineAPI: false, awaitPromise: true}); const error = response[Protocol.Error]; - if (!error && !response.exceptionDetails) + if (!error && !response.exceptionDetails) { return response.result.value; + } TestRunner.addResult( 'Error: ' + (error || response.exceptionDetails && response.exceptionDetails.text || 'exception while evaluation in page.')); @@ -523,8 +540,9 @@ * @param {string} failureText */ TestRunner.check = function(passCondition, failureText) { - if (!passCondition) + if (!passCondition) { TestRunner.addResult('FAIL: ' + failureText); + } }; /** @@ -546,10 +564,11 @@ // <!DOCTYPE...> tag needs to be first const doctypeRegex = /(<!DOCTYPE.*?>)/i; const baseTag = `<base href="${TestRunner.url()}">`; - if (html.match(doctypeRegex)) + if (html.match(doctypeRegex)) { html = html.replace(doctypeRegex, '$1' + baseTag); - else + } else { html = baseTag + html; + } } html = html.replace(/'/g, '\\\'').replace(/\n/g, '\\n'); return TestRunner.evaluateInPageAnonymously(`document.write(\`${html}\`);document.close();`); @@ -656,8 +675,9 @@ TestRunner._pendingInits++; await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'}); TestRunner._pendingInits--; - if (!TestRunner._pendingInits) + if (!TestRunner._pendingInits) { TestRunner._resolveOnFinishInits(); + } }; /** @@ -697,8 +717,9 @@ * @return {string} */ TestRunner.formatters.formatAsTypeNameOrNull = function(value) { - if (value === null) + if (value === null) { return 'null'; + } return TestRunner.formatters.formatAsTypeName(value); }; @@ -707,8 +728,9 @@ * @return {string|!Date} */ TestRunner.formatters.formatAsRecentTime = function(value) { - if (typeof value !== 'object' || !(value instanceof Date)) + if (typeof value !== 'object' || !(value instanceof Date)) { return TestRunner.formatters.formatAsTypeName(value); + } const delta = Date.now() - value; return 0 <= delta && delta < 30 * 60 * 1000 ? '<plausible>' : value; }; @@ -718,11 +740,13 @@ * @return {string} */ TestRunner.formatters.formatAsURL = function(value) { - if (!value) + if (!value) { return value; + } const lastIndex = value.lastIndexOf('devtools/'); - if (lastIndex < 0) + if (lastIndex < 0) { return value; + } return '.../' + value.substr(lastIndex); }; @@ -731,8 +755,9 @@ * @return {string} */ TestRunner.formatters.formatAsDescription = function(value) { - if (!value) + if (!value) { return value; + } return '"' + value.replace(/^function [gs]et /, 'function ') + '"'; }; @@ -755,8 +780,9 @@ propertyNames.sort(); for (let i = 0; i < propertyNames.length; ++i) { const prop = propertyNames[i]; - if (!object.hasOwnProperty(prop)) + if (!object.hasOwnProperty(prop)) { continue; + } const prefixWithName = ' ' + prefix + prop + ' : '; const propValue = object[prop]; if (customFormatters && customFormatters[prop]) { @@ -782,8 +808,9 @@ prefix = prefix || ''; firstLinePrefix = firstLinePrefix || prefix; TestRunner.addResult(firstLinePrefix + '['); - for (let i = 0; i < array.length; ++i) + for (let i = 0; i < array.length; ++i) { TestRunner.dump(array[i], customFormatters, prefix + ' '); + } TestRunner.addResult(prefix + ']'); }; @@ -798,21 +825,25 @@ function innerHTML(prefix, node) { const openTag = []; if (node.nodeType === Node.TEXT_NODE) { - if (!node.parentElement || node.parentElement.nodeName !== 'STYLE') + if (!node.parentElement || node.parentElement.nodeName !== 'STYLE') { TestRunner.addResult(node.nodeValue); + } return; } openTag.push('<' + node.nodeName); const attrs = node.attributes; - for (let i = 0; attrs && i < attrs.length; ++i) + for (let i = 0; attrs && i < attrs.length; ++i) { openTag.push(attrs[i].name + '=' + attrs[i].value); + } openTag.push('>'); TestRunner.addResult(prefix + openTag.join(' ')); - for (let child = node.firstChild; child; child = child.nextSibling) + for (let child = node.firstChild; child; child = child.nextSibling) { innerHTML(prefix + ' ', child); - if (node.shadowRoot) + } + if (node.shadowRoot) { innerHTML(prefix + ' ', node.shadowRoot); + } TestRunner.addResult(prefix + '</' + node.nodeName + '>'); } innerHTML('', node); @@ -823,16 +854,20 @@ * @return {string} */ TestRunner.deepTextContent = function(node) { - if (!node) + if (!node) { return ''; - if (node.nodeType === Node.TEXT_NODE && node.nodeValue) + } + if (node.nodeType === Node.TEXT_NODE && node.nodeValue) { return !node.parentElement || node.parentElement.nodeName !== 'STYLE' ? node.nodeValue : ''; + } let res = ''; const children = node.childNodes; - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { res += TestRunner.deepTextContent(children[i]); - if (node.shadowRoot) + } + if (node.shadowRoot) { res += TestRunner.deepTextContent(node.shadowRoot); + } return res; }; @@ -848,16 +883,17 @@ TestRunner.addResult(prefixWithName + 'was skipped due to prefix length limit'); return; } - if (value === null) + if (value === null) { TestRunner.addResult(prefixWithName + 'null'); - else if (value && value.constructor && value.constructor.name === 'Array') + } else if (value && value.constructor && value.constructor.name === 'Array') { TestRunner.addArray(/** @type {!Array} */ (value), customFormatters, prefix, prefixWithName); - else if (typeof value === 'object') + } else if (typeof value === 'object') { TestRunner.addObject(/** @type {!Object} */ (value), customFormatters, prefix, prefixWithName); - else if (typeof value === 'string') + } else if (typeof value === 'string') { TestRunner.addResult(prefixWithName + '"' + value + '"'); - else + } else { TestRunner.addResult(prefixWithName + value); + } }; /** @@ -892,8 +928,9 @@ * @param {!Common.Event} event */ function onEventFired(event) { - if (!condition(event.data)) + if (!condition(event.data)) { return; + } obj.removeEventListener(eventName, onEventFired); resolve(event.data); } @@ -907,8 +944,9 @@ TestRunner.waitForTarget = function(filter) { filter = filter || (target => true); for (const target of SDK.targetManager.targets()) { - if (filter(target)) + if (filter(target)) { return Promise.resolve(target); + } } return new Promise(fulfill => { const observer = /** @type {!SDK.TargetManager.Observer} */ ({ @@ -948,8 +986,9 @@ * @return {!Promise} */ TestRunner.waitForExecutionContext = function(runtimeModel) { - if (runtimeModel.executionContexts().length) + if (runtimeModel.executionContexts().length) { return Promise.resolve(runtimeModel.executionContexts()[0]); + } return runtimeModel.once(SDK.RuntimeModel.Events.ExecutionContextCreated); }; @@ -959,8 +998,9 @@ */ TestRunner.waitForExecutionContextDestroyed = function(context) { const runtimeModel = context.runtimeModel; - if (runtimeModel.executionContexts().indexOf(context) === -1) + if (runtimeModel.executionContexts().indexOf(context) === -1) { return Promise.resolve(); + } return TestRunner.waitForEvent( SDK.RuntimeModel.Events.ExecutionContextDestroyed, runtimeModel, destroyedContext => destroyedContext === context); @@ -972,8 +1012,9 @@ * @param {string=} message */ TestRunner.assertGreaterOrEqual = function(a, b, message) { - if (a < b) + if (a < b) { TestRunner.addResult('FAILED: ' + (message ? message + ': ' : '') + a + ' < ' + b); + } }; /** @@ -1073,8 +1114,9 @@ TestRunner.runWhenPageLoads = function(callback) { const oldCallback = TestRunner._pageLoadedCallback; function chainedCallback() { - if (oldCallback) + if (oldCallback) { oldCallback(); + } callback(); } TestRunner._pageLoadedCallback = TestRunner.safeWrap(chainedCallback); @@ -1122,14 +1164,16 @@ * @param {string} message */ TestRunner.assertEquals = function(expected, found, message) { - if (expected === found) + if (expected === found) { return; + } let error; - if (message) + if (message) { error = 'Failure (' + message + '):'; - else + } else { error = 'Failure:'; + } throw new Error(error + ' expected <' + expected + '> found <' + found + '>'); }; @@ -1152,8 +1196,9 @@ override = TestRunner.safeWrap(override); const original = receiver[methodName]; - if (typeof original !== 'function') + if (typeof original !== 'function') { throw new Error('Cannot find method to override: ' + methodName); + } receiver[methodName] = function(var_args) { try { @@ -1161,8 +1206,9 @@ } catch (e) { throw new Error('Exception in overriden method \'' + methodName + '\': ' + e); } finally { - if (!opt_sticky) + if (!opt_sticky) { receiver[methodName] = original; + } } }; @@ -1271,8 +1317,9 @@ TestRunner.addResult('Loaded modules:'); const loadedModules = TestRunner.loadedModules().sort(moduleSorter); for (const module of loadedModules) { - if (previous.has(module)) + if (previous.has(module)) { continue; + } TestRunner.addResult(' ' + module._descriptor.name); } return loadedModules; @@ -1289,18 +1336,22 @@ * @return {boolean} */ function matches(uiSourceCode) { - if (projectType && uiSourceCode.project().type() !== projectType) + if (projectType && uiSourceCode.project().type() !== projectType) { return false; - if (!projectType && uiSourceCode.project().type() === Workspace.projectTypes.Service) + } + if (!projectType && uiSourceCode.project().type() === Workspace.projectTypes.Service) { return false; - if (urlSuffix && !uiSourceCode.url().endsWith(urlSuffix)) + } + if (urlSuffix && !uiSourceCode.url().endsWith(urlSuffix)) { return false; + } return true; } for (const uiSourceCode of Workspace.workspace.uiSourceCodes()) { - if (urlSuffix && matches(uiSourceCode)) + if (urlSuffix && matches(uiSourceCode)) { return Promise.resolve(uiSourceCode); + } } return TestRunner.waitForEvent(Workspace.Workspace.Events.UISourceCodeAdded, Workspace.workspace, matches); @@ -1341,10 +1392,11 @@ const node_parts = []; for (let i = 0; i < node.childNodes.length; i++) { - if (node.childNodes[i].getAttribute) + if (node.childNodes[i].getAttribute) { node_parts.push(node.childNodes[i].getAttribute('class')); - else + } else { node_parts.push('*'); + } } TestRunner.addResult(str + ': ' + node_parts.join(', ')); @@ -1364,8 +1416,9 @@ * messages printed at the top of the test expectation file (default behavior). */ TestRunner._printDevToolsConsole = function() { - if (TestRunner._isDebugTest()) + if (TestRunner._isDebugTest()) { return; + } console.log = TestRunner._consoleOutputHook.bind(TestRunner, 'log'); console.error = TestRunner._consoleOutputHook.bind(TestRunner, 'error'); console.info = TestRunner._consoleOutputHook.bind(TestRunner, 'info'); @@ -1391,12 +1444,14 @@ * @override */ targetAdded(target) { - if (TestRunner._startedTest) + if (TestRunner._startedTest) { return; + } TestRunner._startedTest = true; TestRunner._setupTestHelpers(target); - if (TestRunner._isStartupTest()) + if (TestRunner._isStartupTest()) { return; + } TestRunner .loadHTML(` <head> @@ -1445,8 +1500,9 @@ self['onerror'] = completeTestOnError; TestRunner._printDevToolsConsole(); SDK.targetManager.observeTargets(new TestRunner._TestObserver()); - if (!TestRunner._isStartupTest()) + if (!TestRunner._isStartupTest()) { return; + } /** * Startup test initialization: * 1. Wait for DevTools app UI to load
diff --git a/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js b/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js index bcc46b0..486dd04 100644 --- a/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js +++ b/third_party/blink/renderer/devtools/front_end/text_editor/CodeMirrorTextEditor.js
@@ -144,8 +144,9 @@ fallthrough: 'devtools-common' }; - if (options.bracketMatchingSetting) + if (options.bracketMatchingSetting) { options.bracketMatchingSetting.addChangeListener(this._enableBracketMatchingIfNeeded, this); + } this._enableBracketMatchingIfNeeded(); this._codeMirror.setOption('keyMap', Host.isMac() ? 'devtools-mac' : 'devtools-pc'); @@ -153,8 +154,9 @@ this._codeMirror.setOption('flattenSpans', false); let maxHighlightLength = options.maxHighlightLength; - if (typeof maxHighlightLength !== 'number') + if (typeof maxHighlightLength !== 'number') { maxHighlightLength = TextEditor.CodeMirrorTextEditor.maxHighlightLength; + } this._codeMirror.setOption('maxHighlightLength', maxHighlightLength); this._codeMirror.setOption('mode', null); this._codeMirror.setOption('crudeMeasuringFrom', 1000); @@ -188,10 +190,12 @@ this._readOnly = false; this._mimeType = ''; - if (options.mimeType) + if (options.mimeType) { this.setMimeType(options.mimeType); - if (options.autoHeight) + } + if (options.autoHeight) { this._codeMirror.setSize(null, 'auto'); + } this._placeholderElement = null; if (options.placeholder) { @@ -207,8 +211,9 @@ */ static autocompleteCommand(codeMirror) { const autocompleteController = codeMirror._codeMirrorTextEditor._autocompleteController; - if (autocompleteController) + if (autocompleteController) { autocompleteController.autocomplete(true); + } } /** @@ -256,16 +261,18 @@ */ static _overrideModeWithPrefixedTokens(modeName, tokenPrefix) { const oldModeName = modeName + '-old'; - if (CodeMirror.modes[oldModeName]) + if (CodeMirror.modes[oldModeName]) { return; + } CodeMirror.defineMode(oldModeName, CodeMirror.modes[modeName]); CodeMirror.defineMode(modeName, modeConstructor); function modeConstructor(config, parserConfig) { const innerConfig = {}; - for (const i in parserConfig) + for (const i in parserConfig) { innerConfig[i] = parserConfig[i]; + } innerConfig.name = oldModeName; const codeMirrorMode = CodeMirror.getMode(config, innerConfig); codeMirrorMode.name = modeName; @@ -288,21 +295,24 @@ const nameToExtension = new Map(); const extensions = self.runtime.extensions(TextEditor.CodeMirrorMimeMode); - for (const extension of extensions) + for (const extension of extensions) { nameToExtension.set(extension.descriptor()['fileName'], extension); + } const modesToLoad = new Set(); for (const extension of extensions) { const descriptor = extension.descriptor(); - if (installed.has(extension) || descriptor['mimeTypes'].indexOf(mimeType) === -1) + if (installed.has(extension) || descriptor['mimeTypes'].indexOf(mimeType) === -1) { continue; + } modesToLoad.add(extension); const deps = descriptor['dependencies'] || []; for (let i = 0; i < deps.length; ++i) { const extension = nameToExtension.get(deps[i]); - if (extension && !installed.has(extension)) + if (extension && !installed.has(extension)) { modesToLoad.add(extension); + } } } return Array.from(modesToLoad); @@ -321,8 +331,9 @@ * @param {!Object} instance */ function installMode(extension, instance) { - if (TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions.has(extension)) + if (TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions.has(extension)) { return; + } const mode = /** @type {!TextEditor.CodeMirrorMimeMode} */ (instance); mode.install(extension); TextEditor.CodeMirrorTextEditor._loadedMimeModeExtensions.add(extension); @@ -344,8 +355,9 @@ } const skippedText = codeMirror.getRange(newCursor, cursor, '#'); - if (/^\s+$/.test(skippedText)) + if (/^\s+$/.test(skippedText)) { codeMirror.execCommand('goGroupLeft'); + } codeMirror.setExtending(false); } @@ -360,8 +372,9 @@ } const skippedText = codeMirror.getRange(cursor, newCursor, '#'); - if (/^\s+$/.test(skippedText)) + if (/^\s+$/.test(skippedText)) { codeMirror.execCommand('goGroupRight'); + } codeMirror.setExtending(false); } @@ -481,34 +494,42 @@ const text = this.line(lineNumber); const length = text.length; - if ((columnNumber === length && direction === 1) || (columnNumber === 0 && direction === -1)) + if ((columnNumber === length && direction === 1) || (columnNumber === 0 && direction === -1)) { return this._normalizePositionForOverlappingColumn(lineNumber, length, columnNumber + direction); + } let charNumber = direction === 1 ? columnNumber : columnNumber - 1; // Move through initial spaces if any. - while (valid(charNumber, length) && TextUtils.TextUtils.isSpaceChar(text[charNumber])) + while (valid(charNumber, length) && TextUtils.TextUtils.isSpaceChar(text[charNumber])) { charNumber += direction; - if (!valid(charNumber, length)) + } + if (!valid(charNumber, length)) { return constrainPosition(lineNumber, length, charNumber); + } if (TextUtils.TextUtils.isStopChar(text[charNumber])) { - while (valid(charNumber, length) && TextUtils.TextUtils.isStopChar(text[charNumber])) + while (valid(charNumber, length) && TextUtils.TextUtils.isStopChar(text[charNumber])) { charNumber += direction; - if (!valid(charNumber, length)) + } + if (!valid(charNumber, length)) { return constrainPosition(lineNumber, length, charNumber); + } return {lineNumber: lineNumber, columnNumber: direction === -1 ? charNumber + 1 : charNumber}; } charNumber += direction; while (valid(charNumber, length) && !isWordStart(text, charNumber) && !isWordEnd(text, charNumber) && - TextUtils.TextUtils.isWordChar(text[charNumber])) + TextUtils.TextUtils.isWordChar(text[charNumber])) { charNumber += direction; + } - if (!valid(charNumber, length)) + if (!valid(charNumber, length)) { return constrainPosition(lineNumber, length, charNumber); - if (isWordStart(text, charNumber) || isWordEnd(text, charNumber)) + } + if (isWordStart(text, charNumber) || isWordEnd(text, charNumber)) { return {lineNumber: lineNumber, columnNumber: charNumber}; + } return {lineNumber: lineNumber, columnNumber: direction === -1 ? charNumber + 1 : charNumber}; @@ -525,15 +546,17 @@ const move = this._camelCaseMoveFromPosition(selection.endLine, selection.endColumn, direction); selection.endLine = move.lineNumber; selection.endColumn = move.columnNumber; - if (!shift) + if (!shift) { selections[i] = selection.collapseToEnd(); + } } this.setSelections(selections); } dispose() { - if (this._options.bracketMatchingSetting) + if (this._options.bracketMatchingSetting) { this._options.bracketMatchingSetting.removeChangeListener(this._enableBracketMatchingIfNeeded, this); + } } _enableBracketMatchingIfNeeded() { @@ -547,8 +570,9 @@ * @override */ wasShown() { - if (this._needsRefresh) + if (this._needsRefresh) { this.refresh(); + } } /** @@ -586,16 +610,18 @@ e.consume(false); return; } - if (this._autocompleteController && this._autocompleteController.keyDown(e)) + if (this._autocompleteController && this._autocompleteController.keyDown(e)) { e.consume(true); + } } /** * @param {!Event} e */ _handlePostKeyDown(e) { - if (e.defaultPrevented) + if (e.defaultPrevented) { e.consume(true); + } } /** @@ -608,8 +634,9 @@ delete this._autocompleteController; } - if (config) + if (config) { this._autocompleteController = new TextEditor.TextEditorAutocompleteController(this, this._codeMirror, config); + } } /** @@ -619,8 +646,9 @@ */ cursorPositionToCoordinates(lineNumber, column) { if (lineNumber >= this._codeMirror.lineCount() || lineNumber < 0 || column < 0 || - column > this._codeMirror.getLine(lineNumber).length) + column > this._codeMirror.getLine(lineNumber).length) { return null; + } const metrics = this._codeMirror.cursorCoords(new CodeMirror.Pos(lineNumber, column)); return {x: metrics.left, y: metrics.top, height: metrics.bottom - metrics.top}; } @@ -632,12 +660,14 @@ */ coordinatesToCursorPosition(x, y) { const element = this.element.ownerDocument.elementFromPoint(x, y); - if (!element || !element.isSelfOrDescendant(this._codeMirror.getWrapperElement())) + if (!element || !element.isSelfOrDescendant(this._codeMirror.getWrapperElement())) { return null; + } const gutterBox = this._codeMirror.getGutterElement().boxInWindow(); if (x >= gutterBox.x && x <= gutterBox.x + gutterBox.width && y >= gutterBox.y && - y <= gutterBox.y + gutterBox.height) + y <= gutterBox.y + gutterBox.height) { return null; + } const coords = this._codeMirror.coordsChar({left: x, top: y}); return TextEditor.CodeMirrorUtils.toRange(coords, coords); } @@ -660,11 +690,13 @@ * @return {?{startColumn: number, endColumn: number, type: string}} */ tokenAtTextPosition(lineNumber, columnNumber) { - if (lineNumber < 0 || lineNumber >= this._codeMirror.lineCount()) + if (lineNumber < 0 || lineNumber >= this._codeMirror.lineCount()) { return null; + } const token = this._codeMirror.getTokenAt(new CodeMirror.Pos(lineNumber, (columnNumber || 0) + 1)); - if (!token) + if (!token) { return null; + } return {startColumn: token.start, endColumn: token.end, type: token.type}; } @@ -688,8 +720,9 @@ */ _hasLongLines() { function lineIterator(lineHandle) { - if (lineHandle.text.length > TextEditor.CodeMirrorTextEditor.LongLineModeLineLengthThreshold) + if (lineHandle.text.length > TextEditor.CodeMirrorTextEditor.LongLineModeLineLengthThreshold) { hasLongLines = true; + } return hasLongLines; } let hasLongLines = false; @@ -723,18 +756,20 @@ this._mimeType = mimeType; const modesToLoad = TextEditor.CodeMirrorTextEditor._collectUninstalledModes(mimeType); - if (!modesToLoad.length) + if (!modesToLoad.length) { setMode.call(this); - else + } else { TextEditor.CodeMirrorTextEditor._installMimeTypeModes(modesToLoad).then(setMode.bind(this)); + } /** * @this {TextEditor.CodeMirrorTextEditor} */ function setMode() { const rewrittenMimeType = this.rewriteMimeType(mimeType); - if (this._codeMirror.options.mode !== rewrittenMimeType) + if (this._codeMirror.options.mode !== rewrittenMimeType) { this._codeMirror.setOption('mode', rewrittenMimeType); + } } } @@ -767,8 +802,9 @@ * @param {boolean} readOnly */ setReadOnly(readOnly) { - if (this._readOnly === readOnly) + if (this._readOnly === readOnly) { return; + } this.clearPositionHighlight(); this._readOnly = readOnly; this.element.classList.toggle('CodeMirror-readonly', readOnly); @@ -830,8 +866,9 @@ const bookmarks = []; for (let i = 0; i < markers.length; i++) { const bookmark = markers[i][TextEditor.TextEditorBookMark._symbol]; - if (bookmark && (!type || bookmark.type() === type)) + if (bookmark && (!type || bookmark.type() === type)) { bookmarks.push(bookmark); + } } return bookmarks; } @@ -892,8 +929,9 @@ const widget = this._codeMirror.addLineWidget(lineNumber, element); let update = null; if (typeof startColumn !== 'undefined') { - if (typeof endColumn === 'undefined') + if (typeof endColumn === 'undefined') { endColumn = Infinity; + } update = this._updateFloatingDecoration.bind(this, element, lineNumber, startColumn, endColumn); update(); } @@ -925,8 +963,9 @@ * @param {!TextEditor.CodeMirrorTextEditor.Decoration} decoration */ function innerUpdateDecorations(decoration) { - if (decoration.update) + if (decoration.update) { decoration.update(); + } } } @@ -942,8 +981,9 @@ * @param {!TextEditor.CodeMirrorTextEditor.Decoration} decoration */ function innerRemoveDecoration(decoration) { - if (decoration.element !== element) + if (decoration.element !== element) { return; + } this._codeMirror.removeLineWidget(decoration.widget); this._decorations.delete(lineNumber, decoration); } @@ -956,27 +996,31 @@ */ revealPosition(lineNumber, columnNumber, shouldHighlight) { lineNumber = Number.constrain(lineNumber, 0, this._codeMirror.lineCount() - 1); - if (typeof columnNumber !== 'number') + if (typeof columnNumber !== 'number') { columnNumber = 0; + } columnNumber = Number.constrain(columnNumber, 0, this._codeMirror.getLine(lineNumber).length); this.clearPositionHighlight(); this._highlightedLine = this._codeMirror.getLineHandle(lineNumber); - if (!this._highlightedLine) + if (!this._highlightedLine) { return; + } this.scrollLineIntoView(lineNumber); if (shouldHighlight) { this._codeMirror.addLineClass( this._highlightedLine, null, this._readOnly ? 'cm-readonly-highlight' : 'cm-highlight'); - if (!this._readOnly) + if (!this._readOnly) { this._clearHighlightTimeout = setTimeout(this.clearPositionHighlight.bind(this), 2000); + } } this.setSelection(TextUtils.TextRange.createFromLocation(lineNumber, columnNumber)); } clearPositionHighlight() { - if (this._clearHighlightTimeout) + if (this._clearHighlightTimeout) { clearTimeout(this._clearHighlightTimeout); + } delete this._clearHighlightTimeout; if (this._highlightedLine) { @@ -999,8 +1043,9 @@ * @param {number} height */ _updatePaddingBottom(width, height) { - if (!this._options.padBottom) + if (!this._options.padBottom) { return; + } const scrollInfo = this._codeMirror.getScrollInfo(); let newPaddingBottom; const linesElement = this._codeMirrorElement.querySelector('.CodeMirror-lines'); @@ -1018,8 +1063,9 @@ _resizeEditor() { const parentElement = this.element.parentElement; - if (!parentElement || !this.isShowing()) + if (!parentElement || !this.isShowing()) { return; + } this._codeMirror.operation(() => { const scrollLeft = this._codeMirror.doc.scrollLeft; const scrollTop = this._codeMirror.doc.scrollTop; @@ -1039,8 +1085,9 @@ * @override */ onResize() { - if (this._autocompleteController) + if (this._autocompleteController) { this._autocompleteController.clearAutocomplete(); + } this._resizeEditor(); this._editorSizeInSync = true; if (this._selectionSetScheduled) { @@ -1068,8 +1115,9 @@ * @override */ clearAutocomplete() { - if (this._autocompleteController) + if (this._autocompleteController) { this._autocompleteController.clearAutocomplete(); + } } /** @@ -1083,12 +1131,14 @@ let wordStart = column; if (column !== 0 && isWordChar(line.charAt(column - 1))) { wordStart = column - 1; - while (wordStart > 0 && isWordChar(line.charAt(wordStart - 1))) + while (wordStart > 0 && isWordChar(line.charAt(wordStart - 1))) { --wordStart; + } } let wordEnd = column; - while (wordEnd < line.length && isWordChar(line.charAt(wordEnd))) + while (wordEnd < line.length && isWordChar(line.charAt(wordEnd))) { ++wordEnd; + } return new TextUtils.TextRange(lineNumber, wordStart, lineNumber, wordEnd); } @@ -1097,15 +1147,17 @@ * @param {!Array.<!CodeMirror.ChangeObject>} changes */ _changes(codeMirror, changes) { - if (!changes.length) + if (!changes.length) { return; + } this._updatePlaceholder(); // We do not show "scroll beyond end of file" span for one line documents, so we need to check if "document has one line" changed. const hasOneLine = this._codeMirror.lineCount() === 1; - if (hasOneLine !== this._hasOneLine) + if (hasOneLine !== this._hasOneLine) { this._resizeEditor(); + } this._hasOneLine = hasOneLine; this._decorations.valuesArray().forEach(decoration => this._codeMirror.removeLineWidget(decoration.widget)); @@ -1260,13 +1312,15 @@ } this._detectLineSeparator(text); - if (this._hasLongLines()) + if (this._hasLongLines()) { this._enableLongLinesMode(); - else + } else { this._disableLongLinesMode(); + } - if (!this.isShowing()) + if (!this.isShowing()) { this.refresh(); + } } /** @@ -1275,8 +1329,9 @@ * @return {string} */ text(textRange) { - if (!textRange) + if (!textRange) { return this._codeMirror.getValue(this._lineSeparator); + } const pos = TextEditor.CodeMirrorUtils.toPos(textRange.normalize()); return this._codeMirror.getRange(pos.start, pos.end, this._lineSeparator); } @@ -1286,8 +1341,9 @@ * @return {string} */ textWithCurrentSuggestion() { - if (!this._autocompleteController) + if (!this._autocompleteController) { return this.text(); + } return this._autocompleteController.textWithCurrentSuggestion(); } @@ -1342,8 +1398,9 @@ } _updatePlaceholder() { - if (!this._placeholderElement) + if (!this._placeholderElement) { return; + } this._placeholderElement.remove(); @@ -1378,8 +1435,9 @@ */ CodeMirror.commands.UserIndent = function(codeMirror) { const ranges = codeMirror.listSelections(); - if (ranges.length === 0) + if (ranges.length === 0) { return; + } if (codeMirror.somethingSelected()) { codeMirror.indentSelection('add'); @@ -1398,8 +1456,9 @@ const selections = codeMirror.listSelections(); if (selections.length === 1) { const range = TextEditor.CodeMirrorUtils.toRange(selections[0].anchor, selections[0].head); - if (range.isEmpty() && !/^\s/.test(codeMirror.getLine(range.startLine))) + if (range.isEmpty() && !/^\s/.test(codeMirror.getLine(range.startLine))) { return CodeMirror.Pass; + } } codeMirror.execCommand('indentLess'); }; @@ -1433,8 +1492,9 @@ const cursor = codemirror.getCursor('start'); codemirror._codeMirrorTextEditor._innerRevealLine(cursor.line, scrollInfo); const autocompleteController = codemirror._codeMirrorTextEditor._autocompleteController; - if (autocompleteController) + if (autocompleteController) { autocompleteController.clearAutocomplete(); + } }; /** @@ -1446,8 +1506,9 @@ const cursor = codemirror.getCursor('start'); codemirror._codeMirrorTextEditor._innerRevealLine(cursor.line, scrollInfo); const autocompleteController = codemirror._codeMirrorTextEditor._autocompleteController; - if (autocompleteController) + if (autocompleteController) { autocompleteController.clearAutocomplete(); + } }; /** @@ -1458,8 +1519,9 @@ const selections = codemirror.listSelections(); const selection = selections[0]; if (selections.length === 1) { - if (TextEditor.CodeMirrorUtils.toRange(selection.anchor, selection.head).isEmpty()) + if (TextEditor.CodeMirrorUtils.toRange(selection.anchor, selection.head).isEmpty()) { return CodeMirror.Pass; + } codemirror.setSelection(selection.anchor, selection.anchor, {scroll: false}); codemirror._codeMirrorTextEditor.scrollLineIntoView(selection.anchor.line); return; @@ -1474,8 +1536,9 @@ * @return {!Object|undefined} */ CodeMirror.commands.goSmartPageUp = function(codemirror) { - if (codemirror._codeMirrorTextEditor.selection().equal(TextUtils.TextRange.createFromLocation(0, 0))) + if (codemirror._codeMirrorTextEditor.selection().equal(TextUtils.TextRange.createFromLocation(0, 0))) { return CodeMirror.Pass; + } codemirror.execCommand('goPageUp'); }; @@ -1484,8 +1547,10 @@ * @return {!Object|undefined} */ CodeMirror.commands.goSmartPageDown = function(codemirror) { - if (codemirror._codeMirrorTextEditor.selection().equal(codemirror._codeMirrorTextEditor.fullRange().collapseToEnd())) + if (codemirror._codeMirrorTextEditor.selection().equal( + codemirror._codeMirrorTextEditor.fullRange().collapseToEnd())) { return CodeMirror.Pass; + } codemirror.execCommand('goPageDown'); }; @@ -1513,8 +1578,9 @@ */ resolve() { const lineNumber = this._lineHandle ? this._codeMirror.getLineNumber(this._lineHandle) : null; - if (typeof lineNumber !== 'number') + if (typeof lineNumber !== 'number') { return null; + } return {lineNumber: lineNumber, columnNumber: this._columnNumber}; } @@ -1543,8 +1609,9 @@ } selectionWillChange() { - if (!this._muteSelectionListener) + if (!this._muteSelectionListener) { delete this._fullWordSelection; + } } /** @@ -1554,8 +1621,9 @@ */ _findRange(selections, range) { for (let i = 0; i < selections.length; ++i) { - if (range.equal(selections[i])) + if (range.equal(selections[i])) { return true; + } } return false; } @@ -1572,8 +1640,9 @@ for (let i = 0; i < selections.length; ++i) { const selection = selections[i]; anyEmptySelection = anyEmptySelection || selection.isEmpty(); - if (selection.startLine !== selection.endLine) + if (selection.startLine !== selection.endLine) { return; + } } if (anyEmptySelection) { this._expandSelectionsToWords(selections); @@ -1582,12 +1651,13 @@ const last = selections[selections.length - 1]; let next = last; - do + do { next = this._findNextOccurrence(next, !!this._fullWordSelection); - while (next && this._findRange(selections, next) && !next.equal(last)); + } while (next && this._findRange(selections, next) && !next.equal(last)); - if (!next) + if (!next) { return; + } selections.push(next); this._muteSelectionListener = true; @@ -1629,12 +1699,14 @@ let matchedColumnNumber; const textToFind = this._textEditor.text(range); function findWordInLine(wordRegex, lineNumber, lineText, from, to) { - if (typeof matchedLineNumber === 'number') + if (typeof matchedLineNumber === 'number') { return true; + } wordRegex.lastIndex = from; const result = wordRegex.exec(lineText); - if (!result || result.index + textToFind.length > to) + if (!result || result.index + textToFind.length > to) { return false; + } matchedLineNumber = lineNumber; matchedColumnNumber = result.index; return true; @@ -1642,13 +1714,15 @@ let iteratedLineNumber; function lineIterator(regex, lineHandle) { - if (findWordInLine(regex, iteratedLineNumber++, lineHandle.text, 0, lineHandle.text.length)) + if (findWordInLine(regex, iteratedLineNumber++, lineHandle.text, 0, lineHandle.text.length)) { return true; + } } let regexSource = textToFind.escapeForRegExp(); - if (fullWord) + if (fullWord) { regexSource = '\\b' + regexSource + '\\b'; + } const wordRegex = new RegExp(regexSource, 'g'); const currentLineText = this._codeMirror.getLine(range.startLine); @@ -1659,8 +1733,9 @@ this._codeMirror.eachLine(0, range.startLine, lineIterator.bind(null, wordRegex)); findWordInLine(wordRegex, range.startLine, currentLineText, 0, range.startColumn); - if (typeof matchedLineNumber !== 'number') + if (typeof matchedLineNumber !== 'number') { return null; + } return new TextUtils.TextRange( matchedLineNumber, matchedColumnNumber, matchedLineNumber, matchedColumnNumber + textToFind.length); } @@ -1725,15 +1800,17 @@ clear() { const position = this._marker.find(); this._marker.clear(); - if (position) + if (position) { this._editor._updateDecorations(position.line); + } } refresh() { this._marker.changed(); const position = this._marker.find(); - if (position) + if (position) { this._editor._updateDecorations(position.line); + } } /** @@ -1797,8 +1874,9 @@ } _onCompositionStart() { - if (this.textarea.selectionEnd === this.textarea.value.length) + if (this.textarea.selectionEnd === this.textarea.value.length) { return; + } // CodeMirror always expects the caret to be at the end of the textarea // When in IME composition mode, clip the textarea to how CodeMirror expects it, // and then let CodeMirror do it's thing. @@ -1842,16 +1920,19 @@ * @return {boolean} */ poll() { - if (this.contextMenuPending || this.composing) + if (this.contextMenuPending || this.composing) { return super.poll(); + } const text = this.textarea.value; let start = 0; const length = Math.min(this.prevInput.length, text.length); - while (start < length && this.prevInput[start] === text[start]) + while (start < length && this.prevInput[start] === text[start]) { ++start; + } let end = 0; - while (end < length - start && this.prevInput[this.prevInput.length - end - 1] === text[text.length - end - 1]) + while (end < length - start && this.prevInput[this.prevInput.length - end - 1] === text[text.length - end - 1]) { ++end; + } // CodeMirror expects the user to be typing into a blank <textarea>. // Pass a fake textarea into super.poll that only contains the users input.
diff --git a/third_party/blink/renderer/devtools/front_end/text_editor/TextEditorAutocompleteController.js b/third_party/blink/renderer/devtools/front_end/text_editor/TextEditorAutocompleteController.js index e9df519..f36d48e 100644 --- a/third_party/blink/renderer/devtools/front_end/text_editor/TextEditorAutocompleteController.js +++ b/third_party/blink/renderer/devtools/front_end/text_editor/TextEditorAutocompleteController.js
@@ -44,8 +44,9 @@ } _initializeIfNeeded() { - if (this._initialized) + if (this._initialized) { return; + } this._initialized = true; this._codeMirror.on('scroll', this._onScroll); this._codeMirror.on('cursorActivity', this._onCursorActivity); @@ -79,8 +80,9 @@ _beforeChange(codeMirror, changeObject) { this._updatedLines = this._updatedLines || {}; for (let i = changeObject.from.line; i <= changeObject.to.line; ++i) { - if (this._updatedLines[i] === undefined) + if (this._updatedLines[i] === undefined) { this._updatedLines[i] = this._codeMirror.getLine(i); + } } } @@ -96,8 +98,9 @@ * @this {TextEditor.TextEditorAutocompleteController} */ function addWord(word) { - if (word.length && (word[0] < '0' || word[0] > '9')) + if (word.length && (word[0] < '0' || word[0] > '9')) { this._dictionary.addWord(word); + } } } @@ -118,8 +121,9 @@ _substituteRange(lineNumber, columnNumber) { let range = this._config.substituteRangeCallback ? this._config.substituteRangeCallback(lineNumber, columnNumber) : null; - if (!range && this._config.isWordChar) + if (!range && this._config.isWordChar) { range = this._textEditor.wordRangeForCursorPosition(lineNumber, columnNumber, this._config.isWordChar); + } return range; } @@ -132,16 +136,19 @@ _wordsWithQuery(queryRange, substituteRange, force) { const external = this._config.suggestionsCallback ? this._config.suggestionsCallback(queryRange, substituteRange, force) : null; - if (external) + if (external) { return external; + } - if (!this._dictionary || (!force && queryRange.isEmpty())) + if (!this._dictionary || (!force && queryRange.isEmpty())) { return Promise.resolve([]); + } let completions = this._dictionary.wordsWithPrefix(this._textEditor.text(queryRange)); const substituteWord = this._textEditor.text(substituteRange); - if (this._dictionary.wordCount(substituteWord) === 1) + if (this._dictionary.wordCount(substituteWord) === 1) { completions = completions.filter(word => word !== substituteWord); + } completions.sort((a, b) => this._dictionary.wordCount(b) - this._dictionary.wordCount(a) || a.length - b.length); return Promise.resolve(completions.map(item => ({text: item}))); @@ -152,23 +159,27 @@ * @param {!Array.<!CodeMirror.ChangeObject>} changes */ _changes(codeMirror, changes) { - if (!changes.length) + if (!changes.length) { return; + } if (this._dictionary && this._updatedLines) { - for (const lineNumber in this._updatedLines) + for (const lineNumber in this._updatedLines) { this._removeWordsFromText(this._updatedLines[lineNumber]); + } delete this._updatedLines; const linesToUpdate = {}; for (let changeIndex = 0; changeIndex < changes.length; ++changeIndex) { const changeObject = changes[changeIndex]; const editInfo = TextEditor.CodeMirrorUtils.changeObjectToEditOperation(changeObject); - for (let i = editInfo.newRange.startLine; i <= editInfo.newRange.endLine; ++i) + for (let i = editInfo.newRange.startLine; i <= editInfo.newRange.endLine; ++i) { linesToUpdate[i] = this._codeMirror.getLine(i); + } } - for (const lineNumber in linesToUpdate) + for (const lineNumber in linesToUpdate) { this._addWordsFromText(linesToUpdate[lineNumber]); + } } let singleCharInput = false; @@ -189,18 +200,21 @@ } } if (this._queryRange) { - if (singleCharInput) + if (singleCharInput) { this._queryRange.endColumn++; - else if (singleCharDelete) + } else if (singleCharDelete) { this._queryRange.endColumn--; - if (singleCharDelete || singleCharInput) + } + if (singleCharDelete || singleCharInput) { this._setHint(this._lastHintText); + } } - if (singleCharInput || singleCharDelete) + if (singleCharInput || singleCharDelete) { setImmediate(this.autocomplete.bind(this)); - else + } else { this.clearAutocomplete(); + } } _blur() { @@ -213,16 +227,19 @@ */ _validateSelectionsContexts(mainSelection) { const selections = this._codeMirror.listSelections(); - if (selections.length <= 1) + if (selections.length <= 1) { return true; + } const mainSelectionContext = this._textEditor.text(mainSelection); for (let i = 0; i < selections.length; ++i) { const wordRange = this._substituteRange(selections[i].head.line, selections[i].head.ch); - if (!wordRange) + if (!wordRange) { return false; + } const context = this._textEditor.text(wordRange); - if (context !== mainSelectionContext) + if (context !== mainSelectionContext) { return false; + } } return true; } @@ -248,8 +265,9 @@ queryRange.endColumn = cursor.ch; const query = this._textEditor.text(queryRange); let hadSuggestBox = false; - if (this._suggestBox) + if (this._suggestBox) { hadSuggestBox = true; + } this._wordsWithQuery(queryRange, substituteRange, force).then(wordsAcquired.bind(this)); /** @@ -265,18 +283,21 @@ } if (!this._suggestBox) { this._suggestBox = new UI.SuggestBox(this, 20); - if (this._config.anchorBehavior) + if (this._config.anchorBehavior) { this._suggestBox.setAnchorBehavior(this._config.anchorBehavior); + } } const oldQueryRange = this._queryRange; this._queryRange = queryRange; if (!oldQueryRange || queryRange.startLine !== oldQueryRange.startLine || - queryRange.startColumn !== oldQueryRange.startColumn) + queryRange.startColumn !== oldQueryRange.startColumn) { this._updateAnchorBox(); + } this._suggestBox.updateSuggestions(this._anchorBox, wordsWithQuery, true, !this._isCursorAtEndOfLine(), query); - if (this._suggestBox.visible) + if (this._suggestBox.visible) { this._tooltipGlassPane.hide(); + } this._onSuggestionsShownForTest(wordsWithQuery); } } @@ -311,12 +332,14 @@ } _clearHint() { - if (!this._hintElement.textContent) + if (!this._hintElement.textContent) { return; + } this._lastHintText = ''; this._hintElement.textContent = ''; - if (this._hintMarker) + if (this._hintMarker) { this._hintMarker.refresh(); + } } /** @@ -334,8 +357,9 @@ } _hideSuggestBox() { - if (!this._suggestBox) + if (!this._suggestBox) { return; + } this._suggestBox.hide(); this._suggestBox = null; this._queryRange = null; @@ -355,8 +379,9 @@ this._tooltipGlassPane.hide(); return true; } - if (!this._suggestBox) + if (!this._suggestBox) { return false; + } switch (event.keyCode) { case UI.KeyboardShortcut.Keys.Tab.code: this._suggestBox.acceptSuggestion(); @@ -400,8 +425,9 @@ const oldSuggestion = this._currentSuggestion; this._currentSuggestion = suggestion; this._setHint(suggestion ? suggestion.text : ''); - if ((oldSuggestion ? oldSuggestion.text : '') !== (suggestion ? suggestion.text : '')) + if ((oldSuggestion ? oldSuggestion.text : '') !== (suggestion ? suggestion.text : '')) { this._textEditor.dispatchEventToListeners(UI.TextEditor.Events.SuggestionChanged); + } } /** @@ -424,8 +450,9 @@ * @return {string} */ textWithCurrentSuggestion() { - if (!this._queryRange || this._currentSuggestion === null) + if (!this._queryRange || this._currentSuggestion === null) { return this._codeMirror.getValue(); + } const selections = this._codeMirror.listSelections().slice(); let last = {line: 0, column: 0}; @@ -445,8 +472,9 @@ _onScroll() { this._tooltipGlassPane.hide(); - if (!this._suggestBox) + if (!this._suggestBox) { return; + } const cursor = this._codeMirror.getCursor(); const scrollInfo = this._codeMirror.getScrollInfo(); const topmostLineNumber = this._codeMirror.lineAtHeight(scrollInfo.top, 'local'); @@ -464,10 +492,12 @@ const tooltip = this._config.tooltipCallback ? await this._config.tooltipCallback(cursor.line, cursor.ch) : null; const newCursor = this._codeMirror.getCursor(); - if (newCursor.line !== cursor.line && newCursor.ch !== cursor.ch) + if (newCursor.line !== cursor.line && newCursor.ch !== cursor.ch) { return; - if (this._suggestBox && this._suggestBox.visible) + } + if (this._suggestBox && this._suggestBox.visible) { return; + } if (!tooltip) { this._tooltipGlassPane.hide(); @@ -487,8 +517,9 @@ _onCursorActivity() { this._updateTooltip(); - if (!this._suggestBox) + if (!this._suggestBox) { return; + } const cursor = this._codeMirror.getCursor(); let shouldCloseAutocomplete = !(cursor.line === this._queryRange.startLine && this._queryRange.startColumn <= cursor.ch && @@ -498,8 +529,9 @@ const line = this._codeMirror.getLine(cursor.line); shouldCloseAutocomplete = this._config.isWordChar ? !this._config.isWordChar(line.charAt(cursor.ch - 1)) : false; } - if (shouldCloseAutocomplete) + if (shouldCloseAutocomplete) { this.clearAutocomplete(); + } this._onCursorActivityHandledForTest(); }
diff --git a/third_party/blink/renderer/devtools/front_end/text_utils/Text.js b/third_party/blink/renderer/devtools/front_end/text_utils/Text.js index c1f2da2..5476b97f 100644 --- a/third_party/blink/renderer/devtools/front_end/text_utils/Text.js +++ b/third_party/blink/renderer/devtools/front_end/text_utils/Text.js
@@ -17,8 +17,9 @@ * @return {!Array<number>} */ lineEndings() { - if (!this._lineEndings) + if (!this._lineEndings) { this._lineEndings = this._value.computeLineEndings(); + } return this._lineEndings; } @@ -64,8 +65,9 @@ const lineStart = lineNumber > 0 ? lineEndings[lineNumber - 1] + 1 : 0; const lineEnd = lineEndings[lineNumber]; let lineContent = this._value.substring(lineStart, lineEnd); - if (lineContent.length > 0 && lineContent.charAt(lineContent.length - 1) === '\r') + if (lineContent.length > 0 && lineContent.charAt(lineContent.length - 1) === '\r') { lineContent = lineContent.substring(0, lineContent.length - 1); + } return lineContent; } @@ -140,8 +142,9 @@ */ advance(offset) { this._offset = offset; - while (this._lineNumber < this._lineEndings.length && this._lineEndings[this._lineNumber] < this._offset) + while (this._lineNumber < this._lineEndings.length && this._lineEndings[this._lineNumber] < this._offset) { ++this._lineNumber; + } this._columnNumber = this._lineNumber ? this._offset - this._lineEndings[this._lineNumber - 1] - 1 : this._offset; }
diff --git a/third_party/blink/renderer/devtools/front_end/text_utils/TextRange.js b/third_party/blink/renderer/devtools/front_end/text_utils/TextRange.js index 9bc7f414..b044f97 100644 --- a/third_party/blink/renderer/devtools/front_end/text_utils/TextRange.js +++ b/third_party/blink/renderer/devtools/front_end/text_utils/TextRange.js
@@ -102,8 +102,9 @@ * @return {boolean} */ immediatelyPrecedes(range) { - if (!range) + if (!range) { return false; + } return this.endLine === range.startLine && this.endColumn === range.startColumn; } @@ -112,8 +113,9 @@ * @return {boolean} */ immediatelyFollows(range) { - if (!range) + if (!range) { return false; + } return range.immediatelyPrecedes(this); } @@ -150,10 +152,11 @@ * @return {!TextUtils.TextRange} */ normalize() { - if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn)) + if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn)) { return new TextUtils.TextRange(this.endLine, this.endColumn, this.startLine, this.startColumn); - else + } else { return this.clone(); + } } /** @@ -180,14 +183,18 @@ * @return {number} */ compareTo(other) { - if (this.startLine > other.startLine) + if (this.startLine > other.startLine) { return 1; - if (this.startLine < other.startLine) + } + if (this.startLine < other.startLine) { return -1; - if (this.startColumn > other.startColumn) + } + if (this.startColumn > other.startColumn) { return 1; - if (this.startColumn < other.startColumn) + } + if (this.startColumn < other.startColumn) { return -1; + } return 0; } @@ -197,10 +204,12 @@ * @return {number} */ compareToPosition(lineNumber, columnNumber) { - if (lineNumber < this.startLine || (lineNumber === this.startLine && columnNumber < this.startColumn)) + if (lineNumber < this.startLine || (lineNumber === this.startLine && columnNumber < this.startColumn)) { return -1; - if (lineNumber > this.endLine || (lineNumber === this.endLine && columnNumber > this.endColumn)) + } + if (lineNumber > this.endLine || (lineNumber === this.endLine && columnNumber > this.endColumn)) { return 1; + } return 0; } @@ -221,10 +230,12 @@ relativeTo(line, column) { const relative = this.clone(); - if (this.startLine === line) + if (this.startLine === line) { relative.startColumn -= column; - if (this.endLine === line) + } + if (this.endLine === line) { relative.endColumn -= column; + } relative.startLine -= line; relative.endLine -= line; @@ -239,10 +250,12 @@ relativeFrom(line, column) { const relative = this.clone(); - if (this.startLine === 0) + if (this.startLine === 0) { relative.startColumn += column; - if (this.endLine === 0) + } + if (this.endLine === 0) { relative.endColumn += column; + } relative.startLine += line; relative.endLine += line; @@ -258,16 +271,19 @@ console.assert(originalRange.startLine === editedRange.startLine); console.assert(originalRange.startColumn === editedRange.startColumn); const rebase = this.clone(); - if (!this.follows(originalRange)) + if (!this.follows(originalRange)) { return rebase; + } const lineDelta = editedRange.endLine - originalRange.endLine; const columnDelta = editedRange.endColumn - originalRange.endColumn; rebase.startLine += lineDelta; rebase.endLine += lineDelta; - if (rebase.startLine === editedRange.endLine) + if (rebase.startLine === editedRange.endLine) { rebase.startColumn += columnDelta; - if (rebase.endLine === editedRange.endLine) + } + if (rebase.endLine === editedRange.endLine) { rebase.endColumn += columnDelta; + } return rebase; } @@ -285,12 +301,15 @@ * @return {boolean} */ containsLocation(lineNumber, columnNumber) { - if (this.startLine === this.endLine) + if (this.startLine === this.endLine) { return this.startLine === lineNumber && this.startColumn <= columnNumber && columnNumber <= this.endColumn; - if (this.startLine === lineNumber) + } + if (this.startLine === lineNumber) { return this.startColumn <= columnNumber; - if (this.endLine === lineNumber) + } + if (this.endLine === lineNumber) { return columnNumber <= this.endColumn; + } return this.startLine < lineNumber && lineNumber < this.endLine; } };
diff --git a/third_party/blink/renderer/devtools/front_end/text_utils/TextUtils.js b/third_party/blink/renderer/devtools/front_end/text_utils/TextUtils.js index 1fb8f6d0..e7be880 100644 --- a/third_party/blink/renderer/devtools/front_end/text_utils/TextUtils.js +++ b/third_party/blink/renderer/devtools/front_end/text_utils/TextUtils.js
@@ -59,8 +59,9 @@ */ isWord: function(word) { for (let i = 0; i < word.length; ++i) { - if (!TextUtils.TextUtils.isWordChar(word.charAt(i))) + if (!TextUtils.TextUtils.isWordChar(word.charAt(i))) { return false; + } } return true; }, @@ -98,15 +99,17 @@ let startWord = -1; for (let i = 0; i < text.length; ++i) { if (!isWordChar(text.charAt(i))) { - if (startWord !== -1) + if (startWord !== -1) { wordCallback(text.substring(startWord, i)); + } startWord = -1; } else if (startWord === -1) { startWord = i; } } - if (startWord !== -1) + if (startWord !== -1) { wordCallback(text.substring(startWord)); + } }, /** @@ -115,8 +118,9 @@ */ lineIndent: function(line) { let indentation = 0; - while (indentation < line.length && TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))) + while (indentation < line.length && TextUtils.TextUtils.isSpaceChar(line.charAt(indentation))) { ++indentation; + } return line.substr(0, indentation); }, @@ -146,10 +150,11 @@ const globalRegexes = []; for (let i = 0; i < regexes.length; i++) { const regex = regexes[i]; - if (!regex.global) + if (!regex.global) { globalRegexes.push(new RegExp(regex.source, regex.flags ? regex.flags + 'g' : 'g')); - else + } else { globalRegexes.push(regex); + } } doSplit(text, 0, 0); return matches; @@ -171,8 +176,9 @@ regex.lastIndex = 0; while ((result = regex.exec(text)) !== null) { const stringBeforeMatch = text.substring(currentIndex, result.index); - if (stringBeforeMatch) + if (stringBeforeMatch) { doSplit(stringBeforeMatch, regexIndex + 1, startIndex + currentIndex); + } const match = result[0]; matches.push({ value: match, @@ -183,8 +189,9 @@ currentIndex = result.index + match.length; } const stringAfterMatches = text.substring(currentIndex); - if (stringAfterMatches) + if (stringAfterMatches) { doSplit(stringAfterMatches, regexIndex + 1, startIndex + currentIndex); + } } } }; @@ -217,14 +224,16 @@ const filters = []; for (let i = 0; i < splitResult.length; i++) { const regexIndex = splitResult[i].regexIndex; - if (regexIndex === -1) + if (regexIndex === -1) { continue; + } const result = splitResult[i].captureGroups; if (regexIndex === 0) { - if (this._keys.indexOf(/** @type {string} */ (result[1])) !== -1) + if (this._keys.indexOf(/** @type {string} */ (result[1])) !== -1) { filters.push({key: result[1], text: result[2], negative: !!result[0]}); - else + } else { filters.push({text: result[1] + ':' + result[2], negative: !!result[0]}); + } } else if (regexIndex === 1) { try { filters.push({regex: new RegExp(result[1], 'i'), negative: !!result[0]}); @@ -287,8 +296,9 @@ const character = buffer[index]; if (character === '"') { this._closingDoubleQuoteRegex.lastIndex = index; - if (!this._closingDoubleQuoteRegex.test(buffer)) + if (!this._closingDoubleQuoteRegex.test(buffer)) { break; + } index = this._closingDoubleQuoteRegex.lastIndex - 1; } else if (character === '{') { ++this._balance; @@ -300,8 +310,9 @@ } if (!this._balance) { this._lastBalancedIndex = index + 1; - if (!this._findMultiple) + if (!this._findMultiple) { break; + } } } else if (character === ']' && !this._balance) { this._reportBalanced(); @@ -314,8 +325,9 @@ } _reportBalanced() { - if (!this._lastBalancedIndex) + if (!this._lastBalancedIndex) { return; + } this._callback(this._buffer.slice(0, this._lastBalancedIndex)); this._buffer = this._buffer.slice(this._lastBalancedIndex); this._index -= this._lastBalancedIndex; @@ -353,10 +365,12 @@ let lastPosition = 0; do { let eolIndex = text.indexOf('\n', lastPosition); - if (eolIndex < 0) + if (eolIndex < 0) { eolIndex = text.length; - if (eolIndex - lastPosition > kMaxNonMinifiedLength && text.substr(lastPosition, 3) !== '//#') + } + if (eolIndex - lastPosition > kMaxNonMinifiedLength && text.substr(lastPosition, 3) !== '//#') { return true; + } lastPosition = eolIndex + 1; } while (--linesToCheck >= 0 && lastPosition < text.length); @@ -365,10 +379,12 @@ lastPosition = text.length; do { let eolIndex = text.lastIndexOf('\n', lastPosition); - if (eolIndex < 0) + if (eolIndex < 0) { eolIndex = 0; - if (lastPosition - eolIndex > kMaxNonMinifiedLength && text.substr(lastPosition, 3) !== '//#') + } + if (lastPosition - eolIndex > kMaxNonMinifiedLength && text.substr(lastPosition, 3) !== '//#') { return true; + } lastPosition = eolIndex - 1; } while (--linesToCheck >= 0 && lastPosition > 0); return false;
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/CountersGraph.js b/third_party/blink/renderer/devtools/front_end/timeline/CountersGraph.js index aece6d0..8c012baf 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/CountersGraph.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/CountersGraph.js
@@ -91,11 +91,13 @@ */ setModel(model, track) { if (this._model !== model) { - if (this._model) + if (this._model) { this._model.removeEventListener(Timeline.PerformanceModel.Events.WindowChanged, this._onWindowChanged, this); + } this._model = model; - if (this._model) + if (this._model) { this._model.addEventListener(Timeline.PerformanceModel.Events.WindowChanged, this._onWindowChanged, this); + } } this._calculator.setZeroTime(model ? model.timelineModel().minimumRecordTime() : 0); for (let i = 0; i < this._counters.length; ++i) { @@ -104,26 +106,31 @@ } this.scheduleRefresh(); this._track = track; - if (!track) + if (!track) { return; + } const events = track.syncEvents(); for (let i = 0; i < events.length; ++i) { const event = events[i]; - if (event.name !== TimelineModel.TimelineModel.RecordType.UpdateCounters) + if (event.name !== TimelineModel.TimelineModel.RecordType.UpdateCounters) { continue; + } const counters = event.args.data; - if (!counters) + if (!counters) { return; + } for (const name in counters) { const counter = this._countersByName[name]; - if (counter) + if (counter) { counter.appendSample(event.startTime, counters[name]); + } } const gpuMemoryLimitCounterName = 'gpuMemoryLimitKB'; - if (gpuMemoryLimitCounterName in counters) + if (gpuMemoryLimitCounterName in counters) { this._gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]); + } } } @@ -181,8 +188,9 @@ counter._calculateVisibleIndexes(this._calculator); counter._calculateXValues(this._canvas.width); } - for (const counterUI of this._counterUI) + for (const counterUI of this._counterUI) { counterUI._drawGraph(this._canvas); + } } /** @@ -193,8 +201,9 @@ let minDistance = Infinity; let bestTime; for (const counterUI of this._counterUI) { - if (!counterUI.counter.times.length) + if (!counterUI.counter.times.length) { continue; + } const index = counterUI._recordIndexAt(x); const distance = Math.abs(x * window.devicePixelRatio - counterUI.counter.x[index]); if (distance < minDistance) { @@ -217,8 +226,9 @@ } _clearCurrentValueAndMarker() { - for (let i = 0; i < this._counterUI.length; i++) + for (let i = 0; i < this._counterUI.length; i++) { this._counterUI[i]._clearCurrentValueAndMarker(); + } } /** @@ -231,10 +241,12 @@ } _refreshCurrentValues() { - if (this._markerXPosition === undefined) + if (this._markerXPosition === undefined) { return; - for (let i = 0; i < this._counterUI.length; ++i) + } + for (let i = 0; i < this._counterUI.length; ++i) { this._counterUI[i].updateCurrentValue(this._markerXPosition); + } } refresh() { @@ -263,8 +275,9 @@ * @param {number} value */ appendSample(time, value) { - if (this.values.length && this.values.peekLast() === value) + if (this.values.length && this.values.peekLast() === value) { return; + } this.times.push(time); this.values.push(value); } @@ -289,16 +302,19 @@ let minValue; for (let i = this._minimumIndex; i <= this._maximumIndex; i++) { const value = this.values[i]; - if (minValue === undefined || value < minValue) + if (minValue === undefined || value < minValue) { minValue = value; - if (maxValue === undefined || value > maxValue) + } + if (maxValue === undefined || value > maxValue) { maxValue = value; + } } minValue = minValue || 0; maxValue = maxValue || 1; if (this._limitValue) { - if (maxValue > this._limitValue * 0.5) + if (maxValue > this._limitValue * 0.5) { maxValue = Math.max(maxValue, this._limitValue); + } minValue = Math.min(minValue, this._limitValue); } return {min: minValue, max: maxValue}; @@ -326,14 +342,16 @@ * @param {number} width */ _calculateXValues(width) { - if (!this.values.length) + if (!this.values.length) { return; + } const xFactor = width / (this._maxTime - this._minTime); this.x = new Array(this.values.length); - for (let i = this._minimumIndex + 1; i <= this._maximumIndex; i++) + for (let i = this._minimumIndex + 1; i <= this._maximumIndex; i++) { this.x[i] = xFactor * (this.times[i] - this._minTime); + } } }; @@ -416,8 +434,9 @@ * @param {number} x */ updateCurrentValue(x) { - if (!this.visible() || !this.counter.values.length || !this.counter.x) + if (!this.visible() || !this.counter.values.length || !this.counter.x) { return; + } const index = this._recordIndexAt(x); const value = Number.withThousandsSeparator(this.counter.values[index]); this._value.textContent = Common.UIString(this._currentValueLabel, value); @@ -447,16 +466,18 @@ const counter = this.counter; const values = counter.values; - if (!values.length) + if (!values.length) { return; + } const bounds = counter._calculateBounds(); const minValue = bounds.min; const maxValue = bounds.max; this.setRange(minValue, maxValue); - if (!this.visible()) + if (!this.visible()) { return; + } const yValues = this.graphYValues; const maxYRange = maxValue - minValue; @@ -464,8 +485,9 @@ ctx.save(); ctx.lineWidth = window.devicePixelRatio; - if (ctx.lineWidth % 2) + if (ctx.lineWidth % 2) { ctx.translate(0.5, 0.5); + } ctx.beginPath(); let value = values[counter._minimumIndex]; let currentY = Math.round(originY + height - (value - minValue) * yFactor); @@ -475,8 +497,9 @@ const x = Math.round(counter.x[i]); ctx.lineTo(x, currentY); const currentValue = values[i]; - if (typeof currentValue !== 'undefined') + if (typeof currentValue !== 'undefined') { value = currentValue; + } currentY = Math.round(originY + height - (value - minValue) * yFactor); ctx.lineTo(x, currentY); yValues[i] = currentY;
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/EventsTimelineTreeView.js b/third_party/blink/renderer/devtools/front_end/timeline/EventsTimelineTreeView.js index b36a3158..5476697 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/EventsTimelineTreeView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/EventsTimelineTreeView.js
@@ -63,8 +63,9 @@ _onFilterChanged() { const selectedEvent = this.lastSelectedNode() && this.lastSelectedNode().event; this.refreshTree(); - if (selectedEvent) + if (selectedEvent) { this._selectEvent(selectedEvent, false); + } } /** @@ -81,8 +82,9 @@ continue; } const child = /** @type {!TimelineModel.TimelineProfileTree.Node} */ (iterator.value); - if (child.event === event) + if (child.event === event) { return child; + } iterators.push(child.children().values()); } return null; @@ -94,11 +96,13 @@ */ _selectEvent(event, expand) { const node = this._findNodeWithEvent(event); - if (!node) + if (!node) { return; + } this.selectProfileNode(node, false); - if (expand) + if (expand) { this.dataGridNodeForTreeNode(node).expand(); + } } /** @@ -128,8 +132,9 @@ */ _showDetailsForNode(node) { const traceEvent = node.event; - if (!traceEvent) + if (!traceEvent) { return false; + } Timeline.TimelineUIUtils .buildTraceEventDetails(traceEvent, this.model().timelineModel(), this._linkifier, this._badgePool, false) .then(fragment => this._detailsView.element.appendChild(fragment)); @@ -179,8 +184,9 @@ const categories = Timeline.TimelineUIUtils.categories(); for (const categoryName in categories) { const category = categories[categoryName]; - if (!category.visible) + if (!category.visible) { continue; + } const checkbox = new UI.ToolbarCheckbox(category.title, undefined, categoriesFilterChanged.bind(this, categoryName)); checkbox.setChecked(true);
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/ExtensionTracingSession.js b/third_party/blink/renderer/devtools/front_end/timeline/ExtensionTracingSession.js index fffe10f..0c1add9 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/ExtensionTracingSession.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/ExtensionTracingSession.js
@@ -42,8 +42,9 @@ * @param {?SDK.TracingModel} tracingModel */ loadingComplete(tracingModel) { - if (!tracingModel) + if (!tracingModel) { return; + } this._performanceModel.addExtensionEvents(this._provider.longDisplayName(), tracingModel, this._timeOffset); this._completionCallback(); }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/PerformanceModel.js b/third_party/blink/renderer/devtools/front_end/timeline/PerformanceModel.js index be41243..0b8e574b 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/PerformanceModel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/PerformanceModel.js
@@ -89,13 +89,16 @@ let inputEvents = null; let animationEvents = null; for (const track of this._timelineModel.tracks()) { - if (track.type === TimelineModel.TimelineModel.TrackType.Input) + if (track.type === TimelineModel.TimelineModel.TrackType.Input) { inputEvents = track.asyncEvents; - if (track.type === TimelineModel.TimelineModel.TrackType.Animation) + } + if (track.type === TimelineModel.TimelineModel.TrackType.Animation) { animationEvents = track.asyncEvents; + } } - if (inputEvents || animationEvents) + if (inputEvents || animationEvents) { this._irModel.populate(inputEvents || [], animationEvents || []); + } const mainTracks = this._timelineModel.tracks().filter( track => track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame && @@ -120,8 +123,9 @@ */ addExtensionEvents(title, model, timeOffset) { this._extensionTracingModels.push({model: model, title: title, timeOffset: timeOffset}); - if (!this._tracingModel) + if (!this._tracingModel) { return; + } model.adjustTime(this._tracingModel.minimumRecordTime() + (timeOffset / 1000) - this._recordStartTime); this.dispatchEventToListeners(Timeline.PerformanceModel.Events.ExtensionDataAdded); } @@ -130,8 +134,9 @@ * @return {!SDK.TracingModel} */ tracingModel() { - if (!this._tracingModel) + if (!this._tracingModel) { throw 'call setTracingModel before accessing PerformanceModel'; + } return this._tracingModel; } @@ -146,10 +151,12 @@ * @return {!SDK.FilmStripModel} filmStripModel */ filmStripModel() { - if (this._filmStripModel) + if (this._filmStripModel) { return this._filmStripModel; - if (!this._tracingModel) + } + if (!this._tracingModel) { throw 'call setTracingModel before accessing PerformanceModel'; + } this._filmStripModel = new SDK.FilmStripModel(this._tracingModel); return this._filmStripModel; } @@ -183,10 +190,12 @@ } dispose() { - if (this._tracingModel) + if (this._tracingModel) { this._tracingModel.dispose(); - for (const extensionEntry of this._extensionTracingModels) + } + for (const extensionEntry of this._extensionTracingModels) { extensionEntry.model.dispose(); + } } /** @@ -230,8 +239,9 @@ let tasks = []; for (const track of timelineModel.tracks()) { // Deliberately pick up last main frame's track. - if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) + if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) { tasks = track.tasks; + } } if (!tasks.length) { this.setWindow({left: timelineModel.minimumRecordTime(), right: timelineModel.maximumRecordTime()});
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineController.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineController.js index 12cf4215..0d6e19e3 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineController.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineController.js
@@ -59,34 +59,40 @@ ]; categoriesArray.push(TimelineModel.TimelineModel.Category.LatencyInfo); - if (Runtime.experiments.isEnabled('timelineFlowEvents')) + if (Runtime.experiments.isEnabled('timelineFlowEvents')) { categoriesArray.push('devtools.timeline.async'); + } - if (Runtime.experiments.isEnabled('timelineV8RuntimeCallStats') && options.enableJSSampling) + if (Runtime.experiments.isEnabled('timelineV8RuntimeCallStats') && options.enableJSSampling) { categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling')); + } if (!Runtime.queryParam('timelineTracingJSProfileDisabled') && options.enableJSSampling) { categoriesArray.push(disabledByDefault('v8.cpu_profiler')); - if (Common.moduleSetting('highResolutionCpuProfiling').get()) + if (Common.moduleSetting('highResolutionCpuProfiling').get()) { categoriesArray.push(disabledByDefault('v8.cpu_profiler.hires')); + } } categoriesArray.push(disabledByDefault('devtools.timeline.stack')); - if (Runtime.experiments.isEnabled('timelineInvalidationTracking')) + if (Runtime.experiments.isEnabled('timelineInvalidationTracking')) { categoriesArray.push(disabledByDefault('devtools.timeline.invalidationTracking')); + } if (options.capturePictures) { categoriesArray.push( disabledByDefault('devtools.timeline.layers'), disabledByDefault('devtools.timeline.picture'), disabledByDefault('blink.graphics_context_annotations')); } - if (options.captureFilmStrip) + if (options.captureFilmStrip) { categoriesArray.push(disabledByDefault('devtools.screenshot')); + } this._extensionSessions = providers.map(provider => new Timeline.ExtensionTracingSession(provider, this._performanceModel)); this._extensionSessions.forEach(session => session.start()); this._performanceModel.setRecordStartTime(Date.now()); const response = await this._startRecordingWithCategories(categoriesArray.join(','), options.enableJSSampling); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { await this._waitForTracingToStop(false); + } return response; } @@ -94,8 +100,9 @@ * @return {!Promise<!Timeline.PerformanceModel>} */ async stopRecording() { - if (this._tracingManager) + if (this._tracingManager) { this._tracingManager.stop(); + } this._client.loadingStarted(); await this._waitForTracingToStop(true); @@ -110,8 +117,9 @@ */ _waitForTracingToStop(awaitTracingCompleteCallback) { const tracingStoppedPromises = []; - if (this._tracingManager && awaitTracingCompleteCallback) + if (this._tracingManager && awaitTracingCompleteCallback) { tracingStoppedPromises.push(new Promise(resolve => this._tracingCompleteCallback = resolve)); + } tracingStoppedPromises.push(this._stopProfilingOnAllModels()); const extensionCompletionPromises = this._extensionSessions.map(session => session.stop()); @@ -127,8 +135,9 @@ * @param {!SDK.CPUProfilerModel} cpuProfilerModel */ modelAdded(cpuProfilerModel) { - if (this._profiling) + if (this._profiling) { cpuProfilerModel.startRecording(); + } } /** @@ -158,8 +167,9 @@ Common.console.warn(Common.UIString('CPU profile for a target is not available.')); return; } - if (!this._cpuProfiles) + if (!this._cpuProfiles) { this._cpuProfiles = new Map(); + } this._cpuProfiles.set(targetId, cpuProfile); } @@ -188,10 +198,12 @@ // caused by starting CPU profiler, that needs to traverse JS heap to collect // all the functions data. await SDK.targetManager.suspendAllTargets('performance-timeline'); - if (enableJSSampling && Runtime.queryParam('timelineTracingJSProfileDisabled')) + if (enableJSSampling && Runtime.queryParam('timelineTracingJSProfileDisabled')) { await this._startProfilingOnAllModels(); - if (!this._tracingManager) + } + if (!this._tracingManager) { return; + } const samplingFrequencyHz = Common.moduleSetting('highResolutionCpuProfiling').get() ? 10000 : 1000; const options = 'sampling-frequency=' + samplingFrequencyHz; @@ -235,8 +247,9 @@ * @param {?Protocol.Profiler.Profile} cpuProfile */ _injectCpuProfileEvent(pid, tid, cpuProfile) { - if (!cpuProfile) + if (!cpuProfile) { return; + } const cpuProfileEvent = /** @type {!SDK.TracingManager.EventPayload} */ ({ cat: SDK.TracingModel.DevToolsMetadataEventCategory, ph: SDK.TracingModel.Phase.Instant, @@ -256,42 +269,48 @@ const metadataEventTypes = TimelineModel.TimelineModel.DevToolsMetadataEvent; const metadataEvents = this._tracingModel.devToolsMetadataEvents(); const browserMetaEvent = metadataEvents.find(e => e.name === metadataEventTypes.TracingStartedInBrowser); - if (!browserMetaEvent) + if (!browserMetaEvent) { return null; + } /** @type {!Multimap<string, string>} */ const pseudoPidToFrames = new Multimap(); /** @type {!Map<string, number>} */ const targetIdToPid = new Map(); const frames = browserMetaEvent.args.data['frames']; - for (const frameInfo of frames) + for (const frameInfo of frames) { targetIdToPid.set(frameInfo.frame, frameInfo.processId); + } for (const event of metadataEvents) { const data = event.args.data; switch (event.name) { case metadataEventTypes.FrameCommittedInBrowser: - if (data.processId) + if (data.processId) { targetIdToPid.set(data.frame, data.processId); - else + } else { pseudoPidToFrames.set(data.processPseudoId, data.frame); + } break; case metadataEventTypes.ProcessReadyInBrowser: - for (const frame of pseudoPidToFrames.get(data.processPseudoId) || []) + for (const frame of pseudoPidToFrames.get(data.processPseudoId) || []) { targetIdToPid.set(frame, data.processId); + } break; } } const mainFrame = frames.find(frame => !frame.parent); const mainRendererProcessId = mainFrame.processId; const mainProcess = this._tracingModel.processById(mainRendererProcessId); - if (mainProcess) + if (mainProcess) { targetIdToPid.set(SDK.targetManager.mainTarget().id(), mainProcess.id()); + } return targetIdToPid; } _injectCpuProfileEvents() { - if (!this._cpuProfiles) + if (!this._cpuProfiles) { return; + } const metadataEventTypes = TimelineModel.TimelineModel.DevToolsMetadataEvent; const metadataEvents = this._tracingModel.devToolsMetadataEvents(); @@ -300,12 +319,14 @@ if (targetIdToPid) { for (const [id, profile] of this._cpuProfiles) { const pid = targetIdToPid.get(id); - if (!pid) + if (!pid) { continue; + } const process = this._tracingModel.processById(pid); const thread = process && process.threadByName(TimelineModel.TimelineModel.RendererMainThreadName); - if (thread) + if (thread) { this._injectCpuProfileEvent(pid, thread.id(), profile); + } } } else { // Legacy backends support.
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineDetailsView.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineDetailsView.js index fba72354..e32051e 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineDetailsView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineDetailsView.js
@@ -54,17 +54,20 @@ */ setModel(model, track) { if (this._model !== model) { - if (this._model) + if (this._model) { this._model.removeEventListener(Timeline.PerformanceModel.Events.WindowChanged, this._onWindowChanged, this); + } this._model = model; - if (this._model) + if (this._model) { this._model.addEventListener(Timeline.PerformanceModel.Events.WindowChanged, this._onWindowChanged, this); + } } this._track = track; this._tabbedPane.closeTabs( [Timeline.TimelineDetailsView.Tab.PaintProfiler, Timeline.TimelineDetailsView.Tab.LayerViewer], false); - for (const view of this._rangeDetailViews.values()) + for (const view of this._rangeDetailViews.values()) { view.setModel(model, track); + } this._lazyPaintProfilerView = null; this._lazyLayersView = null; this.setSelection(null); @@ -76,8 +79,9 @@ _setContent(node) { const allTabs = this._tabbedPane.otherTabs(Timeline.TimelineDetailsView.Tab.Details); for (let i = 0; i < allTabs.length; ++i) { - if (!this._rangeDetailViews.has(allTabs[i])) + if (!this._rangeDetailViews.has(allTabs[i])) { this._tabbedPane.closeTab(allTabs[i]); + } } this._defaultDetailsContentElement.removeChildren(); this._defaultDetailsContentElement.appendChild(node); @@ -99,8 +103,9 @@ */ _appendTab(id, tabTitle, view, isCloseable) { this._tabbedPane.appendTab(id, tabTitle, view, undefined, undefined, isCloseable); - if (this._preferredTabId !== this._tabbedPane.selectedTabId) + if (this._preferredTabId !== this._tabbedPane.selectedTabId) { this._tabbedPane.selectTab(id); + } } /** @@ -121,8 +126,9 @@ * @param {!Common.Event} event */ _onWindowChanged(event) { - if (!this._selection) + if (!this._selection) { this._updateContentsFromWindow(); + } } _updateContentsFromWindow() { @@ -160,8 +166,9 @@ if (frame.layerTree) { const layersView = this._layersView(); layersView.showLayerTree(frame.layerTree); - if (!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.LayerViewer)) + if (!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.LayerViewer)) { this._appendTab(Timeline.TimelineDetailsView.Tab.LayerViewer, Common.UIString('Layers'), layersView); + } } break; case Timeline.TimelineSelection.Type.NetworkRequest: @@ -182,8 +189,9 @@ * @param {!Common.Event} event */ _tabSelected(event) { - if (!event.data.isUserGesture) + if (!event.data.isUserGesture) { return; + } this.setPreferredTab(event.data.tabId); this._updateContents(); } @@ -192,8 +200,9 @@ * @return {!UI.Widget} */ _layersView() { - if (this._lazyLayersView) + if (this._lazyLayersView) { return this._lazyLayersView; + } this._lazyLayersView = new Timeline.TimelineLayersView(this._model.timelineModel(), this._showSnapshotInPaintProfiler.bind(this)); return this._lazyLayersView; @@ -203,8 +212,9 @@ * @return {!Timeline.TimelinePaintProfilerView} */ _paintProfilerView() { - if (this._lazyPaintProfilerView) + if (this._lazyPaintProfilerView) { return this._lazyPaintProfilerView; + } this._lazyPaintProfilerView = new Timeline.TimelinePaintProfilerView(this._model.frameModel()); return this._lazyPaintProfilerView; } @@ -229,8 +239,9 @@ _appendDetailsTabsForTraceEventAndShowDetails(event, content) { this._setContent(content); if (event.name === TimelineModel.TimelineModel.RecordType.Paint || - event.name === TimelineModel.TimelineModel.RecordType.RasterTask) + event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { this._showEventInPaintProfiler(event); + } } /** @@ -238,14 +249,17 @@ */ _showEventInPaintProfiler(event) { const paintProfilerModel = SDK.targetManager.models(SDK.PaintProfilerModel)[0]; - if (!paintProfilerModel) + if (!paintProfilerModel) { return; + } const paintProfilerView = this._paintProfilerView(); const hasProfileData = paintProfilerView.setEvent(paintProfilerModel, event); - if (!hasProfileData) + if (!hasProfileData) { return; - if (this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler)) + } + if (this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler)) { return; + } this._appendTab( Timeline.TimelineDetailsView.Tab.PaintProfiler, Common.UIString('Paint Profiler'), paintProfilerView); } @@ -255,8 +269,9 @@ * @param {number} endTime */ _updateSelectedRangeStats(startTime, endTime) { - if (!this._model || !this._track) + if (!this._model || !this._track) { return; + } const aggregatedStats = Timeline.TimelineUIUtils.statsForTimeRange(this._track.syncEvents(), startTime, endTime); const startOffset = startTime - this._model.timelineModel().minimumRecordTime(); const endOffset = endTime - this._model.timelineModel().minimumRecordTime();
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineEventOverview.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineEventOverview.js index f24d822..45569b2 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineEventOverview.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineEventOverview.js
@@ -42,8 +42,9 @@ this.element.classList.add('overview-strip'); /** @type {?Timeline.PerformanceModel} */ this._model = null; - if (title) + if (title) { this.element.createChild('div', 'timeline-overview-strip-title').textContent = title; + } } /** @@ -82,16 +83,18 @@ */ update() { super.update(); - if (!this._model) + if (!this._model) { return; + } const height = this.height(); const descriptors = Timeline.TimelineUIUtils.eventDispatchDesciptors(); /** @type {!Map.<string,!Timeline.TimelineUIUtils.EventDispatchTypeDescriptor>} */ const descriptorsByType = new Map(); let maxPriority = -1; for (const descriptor of descriptors) { - for (const type of descriptor.eventTypes) + for (const type of descriptor.eventTypes) { descriptorsByType.set(type, descriptor); + } maxPriority = Math.max(maxPriority, descriptor.priority); } @@ -105,11 +108,13 @@ for (const track of this._model.timelineModel().tracks()) { for (let i = 0; i < track.events.length; ++i) { const event = track.events[i]; - if (event.name !== TimelineModel.TimelineModel.RecordType.EventDispatch) + if (event.name !== TimelineModel.TimelineModel.RecordType.EventDispatch) { continue; + } const descriptor = descriptorsByType.get(event.args['data']['type']); - if (!descriptor || descriptor.priority !== priority) + if (!descriptor || descriptor.priority !== priority) { continue; + } const start = Number.constrain(Math.floor((event.startTime - timeOffset) * scale), 0, canvasWidth); const end = Number.constrain(Math.ceil((event.endTime - timeOffset) * scale), 0, canvasWidth); const width = Math.max(end - start, minWidth); @@ -133,8 +138,9 @@ */ update() { super.update(); - if (!this._model) + if (!this._model) { return; + } const timelineModel = this._model.timelineModel(); const bandHeight = this.height() / 2; const timeOffset = timelineModel.minimumRecordTime(); @@ -185,8 +191,9 @@ */ update() { super.update(); - if (!this._model) + if (!this._model) { return; + } const timelineModel = this._model.timelineModel(); const /** @const */ quantSizePx = 4 * window.devicePixelRatio; const width = this.width(); @@ -201,15 +208,17 @@ const otherIndex = categoryOrder.indexOf('other'); const idleIndex = 0; console.assert(idleIndex === categoryOrder.indexOf('idle')); - for (let i = idleIndex + 1; i < categoryOrder.length; ++i) + for (let i = idleIndex + 1; i < categoryOrder.length; ++i) { categories[categoryOrder[i]]._overviewIndex = i; + } const backgroundContext = this._backgroundCanvas.getContext('2d'); for (const track of timelineModel.tracks()) { - if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) + if (track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame) { drawThreadEvents(this.context(), track.events); - else + } else { drawThreadEvents(backgroundContext, track.events); + } } applyPattern(backgroundContext); @@ -299,8 +308,9 @@ */ update() { super.update(); - if (!this._model) + if (!this._model) { return; + } const height = this.height(); const timeOffset = this._model.timelineModel().minimumRecordTime(); @@ -313,16 +323,18 @@ const markersPath = new Path2D(); for (let i = 0; i < frames.length; ++i) { const frame = frames[i]; - if (!frame.hasWarnings()) + if (!frame.hasWarnings()) { continue; + } paintWarningDecoration(frame.startTime, frame.duration); } for (const track of this._model.timelineModel().tracks()) { const events = track.events; for (let i = 0; i < events.length; ++i) { - if (!TimelineModel.TimelineData.forEvent(events[i]).warning) + if (!TimelineModel.TimelineData.forEvent(events[i]).warning) { continue; + } paintWarningDecoration(events[i].startTime, events[i].duration); } } @@ -362,16 +374,19 @@ update() { super.update(); const frames = this._model ? this._model.filmStripModel().frames() : []; - if (!frames.length) + if (!frames.length) { return; + } const drawGeneration = Symbol('drawGeneration'); this._drawGeneration = drawGeneration; this._imageByFrame(frames[0]).then(image => { - if (this._drawGeneration !== drawGeneration) + if (this._drawGeneration !== drawGeneration) { return; - if (!image || !image.naturalWidth || !image.naturalHeight) + } + if (!image || !image.naturalWidth || !image.naturalHeight) { return; + } const imageHeight = this.height() - 2 * Timeline.TimelineFilmStripOverview.Padding; const imageWidth = Math.ceil(imageHeight * image.naturalWidth / image.naturalHeight); const popoverScale = Math.min(200 / image.naturalWidth, 1); @@ -398,11 +413,13 @@ * @param {number} imageHeight */ _drawFrames(imageWidth, imageHeight) { - if (!imageWidth || !this._model) + if (!imageWidth || !this._model) { return; + } const filmStripModel = this._model.filmStripModel(); - if (!filmStripModel.frames().length) + if (!filmStripModel.frames().length) { return; + } const padding = Timeline.TimelineFilmStripOverview.Padding; const width = this.width(); const zeroTime = filmStripModel.zeroTime(); @@ -415,8 +432,9 @@ for (let x = padding; x < width; x += imageWidth + 2 * padding) { const time = zeroTime + (x + imageWidth / 2) * scale; const frame = filmStripModel.frameByTimestamp(time); - if (!frame) + if (!frame) { continue; + } context.rect(x - 0.5, 0.5, imageWidth + 1, imageHeight + 1); this._imageByFrame(frame).then(drawFrameImage.bind(this, x)); } @@ -430,8 +448,9 @@ */ function drawFrameImage(x, image) { // Ignore draws deferred from a previous update call. - if (this._drawGeneration !== drawGeneration || !image) + if (this._drawGeneration !== drawGeneration || !image) { return; + } context.drawImage(image, x, 1, imageWidth, imageHeight); } } @@ -442,13 +461,15 @@ * @return {!Promise<?Element>} */ overviewInfoPromise(x) { - if (!this._model || !this._model.filmStripModel().frames().length) + if (!this._model || !this._model.filmStripModel().frames().length) { return Promise.resolve(/** @type {?Element} */ (null)); + } const time = this.calculator().positionToTime(x); const frame = this._model.filmStripModel().frameByTimestamp(time); - if (frame === this._lastFrame) + if (frame === this._lastFrame) { return Promise.resolve(this._lastElement); + } const imagePromise = frame ? this._imageByFrame(frame) : Promise.resolve(this._emptyImage); return imagePromise.then(createFrameElement.bind(this)); @@ -459,8 +480,9 @@ */ function createFrameElement(image) { const element = createElementWithClass('div', 'frame'); - if (image) + if (image) { element.createChild('div', 'thumbnail').appendChild(image); + } this._lastFrame = frame; this._lastElement = element; return element; @@ -494,11 +516,13 @@ */ update() { super.update(); - if (!this._model) + if (!this._model) { return; + } const frames = this._model.frames(); - if (!frames.length) + if (!frames.length) { return; + } const height = this.height(); const /** @const */ padding = 1 * window.devicePixelRatio; const /** @const */ baseFrameDurationMs = 1e3 / 60; @@ -581,21 +605,24 @@ function isUpdateCountersEvent(event) { return event.name === TimelineModel.TimelineModel.RecordType.UpdateCounters; } - for (let i = 0; i < trackEvents.length; i++) + for (let i = 0; i < trackEvents.length; i++) { trackEvents[i] = trackEvents[i].filter(isUpdateCountersEvent); + } /** * @param {!SDK.TracingModel.Event} event */ function calculateMinMaxSizes(event) { const counters = event.args.data; - if (!counters || !counters.jsHeapSizeUsed) + if (!counters || !counters.jsHeapSizeUsed) { return; + } maxUsedHeapSize = Math.max(maxUsedHeapSize, counters.jsHeapSizeUsed); minUsedHeapSize = Math.min(minUsedHeapSize, counters.jsHeapSizeUsed); } - for (let i = 0; i < trackEvents.length; i++) + for (let i = 0; i < trackEvents.length; i++) { trackEvents[i].forEach(calculateMinMaxSizes); + } minUsedHeapSize = Math.min(minUsedHeapSize, maxUsedHeapSize); const lineWidth = 1; @@ -611,15 +638,17 @@ */ function buildHistogram(event) { const counters = event.args.data; - if (!counters || !counters.jsHeapSizeUsed) + if (!counters || !counters.jsHeapSizeUsed) { return; + } const x = Math.round((event.startTime - minTime) * xFactor); const y = Math.round((counters.jsHeapSizeUsed - minUsedHeapSize) * yFactor); // TODO(alph): use sum instead of max. histogram[x] = Math.max(histogram[x] || 0, y); } - for (let i = 0; i < trackEvents.length; i++) + for (let i = 0; i < trackEvents.length; i++) { trackEvents[i].forEach(buildHistogram); + } const ctx = this.context(); const heightBeyondView = height + lowerOffset + lineWidth; @@ -631,16 +660,18 @@ let isFirstPoint = true; let lastX = 0; for (let x = 0; x < histogram.length; x++) { - if (typeof histogram[x] === 'undefined') + if (typeof histogram[x] === 'undefined') { continue; + } if (isFirstPoint) { isFirstPoint = false; y = histogram[x]; ctx.lineTo(-lineWidth, height - y); } const nextY = histogram[x]; - if (Math.abs(nextY - y) > 2 && Math.abs(x - lastX) > 1) + if (Math.abs(nextY - y) > 2 && Math.abs(x - lastX) > 1) { ctx.lineTo(x, height - y); + } y = nextY; ctx.lineTo(x, height - y); lastX = x; @@ -724,8 +755,9 @@ */ setModel(model) { super.setModel(model); - if (this._model) + if (this._model) { this._coverageModel = model.mainTarget().model(Coverage.CoverageModel); + } } /** @@ -735,8 +767,9 @@ super.update(); const ratio = window.devicePixelRatio; - if (!this._coverageModel) + if (!this._coverageModel) { return; + } let total = 0; let total_used = 0; @@ -750,15 +783,17 @@ for (const [stamp, used] of info.usedByTimestamp()) { total_used += used; - if (!totalByTimestamp.has(stamp)) + if (!totalByTimestamp.has(stamp)) { totalByTimestamp.set(stamp, new Set()); + } totalByTimestamp.get(stamp).add(info); - if (!usedByTimestamp.has(stamp)) + if (!usedByTimestamp.has(stamp)) { usedByTimestamp.set(stamp, used); - else + } else { usedByTimestamp.set(stamp, usedByTimestamp.get(stamp) + used); + } } } } @@ -772,8 +807,9 @@ const sortedByTimestamp = Array.from(totalByTimestamp.entries()).sort((a, b) => a[0] - b[0]); for (const [stamp, infos] of sortedByTimestamp) { for (const info of infos.values()) { - if (seen.has(info)) + if (seen.has(info)) { continue; + } seen.add(info); sumTotal += info.size(); @@ -805,8 +841,9 @@ ctx.lineTo(-lineWidth, height - yOffset); for (const [stamp, coverage] of coverageByTimestamp) { - if (stamp > maxTime) + if (stamp > maxTime) { break; + } const x = (stamp - minTime) * xFactor; yOffset = coverage * yFactor; ctx.lineTo(x, height - yOffset); @@ -822,8 +859,9 @@ ctx.stroke(); for (const [stamp, coverage] of coverageByTimestamp) { - if (stamp > maxTime) + if (stamp > maxTime) { break; + } ctx.beginPath(); const x = (stamp - minTime) * xFactor; const y = height - coverage * yFactor;
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js index 8f7c4f54..b2a177a 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js
@@ -112,20 +112,25 @@ const entryType = this._entryType(entryIndex); if (entryType === entryTypes.Event) { const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); - if (event.phase === SDK.TracingModel.Phase.AsyncStepInto || event.phase === SDK.TracingModel.Phase.AsyncStepPast) + if (event.phase === SDK.TracingModel.Phase.AsyncStepInto || + event.phase === SDK.TracingModel.Phase.AsyncStepPast) { return event.name + ':' + event.args['step']; - if (event._blackboxRoot) + } + if (event._blackboxRoot) { return Common.UIString('Blackboxed'); - if (this._performanceModel.timelineModel().isMarkerEvent(event)) + } + if (this._performanceModel.timelineModel().isMarkerEvent(event)) { return Timeline.TimelineUIUtils.markerShortTitle(event); + } return Timeline.TimelineUIUtils.eventTitle(event); } if (entryType === entryTypes.ExtensionEvent) { const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); return event.name; } - if (entryType === entryTypes.Screenshot) + if (entryType === entryTypes.Screenshot) { return ''; + } let title = this._entryIndexToTitle[entryIndex]; if (!title) { title = Common.UIString('Unexpected entryIndex %d', entryIndex); @@ -189,22 +194,25 @@ * @return {!PerfUI.FlameChart.TimelineData} */ timelineData() { - if (this._timelineData) + if (this._timelineData) { return this._timelineData; + } this._timelineData = new PerfUI.FlameChart.TimelineData([], [], [], []); - if (!this._model) + if (!this._model) { return this._timelineData; + } this._flowEventIndexById.clear(); this._minimumBoundary = this._model.minimumRecordTime(); this._timeSpan = this._model.isEmpty() ? 1000 : this._model.maximumRecordTime() - this._minimumBoundary; this._currentLevel = 0; - if (this._model.isGenericTrace()) + if (this._model.isGenericTrace()) { this._processGenericTrace(); - else + } else { this._processInspectorTrace(); + } return this._timelineData; } @@ -231,8 +239,9 @@ for (const track of tracksByProcess.get(process)) { const group = this._appendSyncEvents( track, track.events, track.name, threadGroupStyle, eventEntryType, true /* selectable */); - if (!this._timelineData.selectedGroup || track.name === TimelineModel.TimelineModel.BrowserMainThreadName) + if (!this._timelineData.selectedGroup || track.name === TimelineModel.TimelineModel.BrowserMainThreadName) { this._timelineData.selectedGroup = group; + } } } } @@ -297,8 +306,9 @@ const group = this._appendSyncEvents( track, track.events, track.url ? ls`Main \u2014 ${track.url}` : ls`Main`, this._headerLevel1, eventEntryType, true /* selectable */); - if (group) + if (group) { this._timelineData.selectedGroup = group; + } } else { this._appendSyncEvents( track, track.events, track.url ? ls`Frame \u2014 ${track.url}` : ls`Subframe`, this._headerLevel1, @@ -311,8 +321,9 @@ this._headerLevel1, eventEntryType, true /* selectable */); break; case TimelineModel.TimelineModel.TrackType.Raster: - if (!rasterCount) + if (!rasterCount) { this._appendHeader(ls`Raster`, this._headerLevel1, false /* selectable */); + } ++rasterCount; this._appendSyncEvents( track, track.events, ls`Rasterizer Thread ${rasterCount}`, this._headerLevel2, eventEntryType, @@ -330,11 +341,13 @@ break; } } - if (this._timelineData.selectedGroup) + if (this._timelineData.selectedGroup) { this._timelineData.selectedGroup.expanded = true; + } - for (let extensionIndex = 0; extensionIndex < this._extensionInfo.length; extensionIndex++) + for (let extensionIndex = 0; extensionIndex < this._extensionInfo.length; extensionIndex++) { this._innerAppendExtensionEvents(extensionIndex); + } this._markers.sort((a, b) => a.startTime() - b.startTime()); this._timelineData.markers = this._markers; @@ -368,15 +381,19 @@ const entryTypes = Timeline.TimelineFlameChartDataProvider.EntryType; this.timelineData(); for (let i = 0; i < this._entryData.length; ++i) { - if (this._entryType(i) !== entryTypes.Event) + if (this._entryType(i) !== entryTypes.Event) { continue; + } const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[i]); - if (event.startTime > endTime) + if (event.startTime > endTime) { continue; - if ((event.endTime || event.startTime) < startTime) + } + if ((event.endTime || event.startTime) < startTime) { continue; - if (filter.accept(event)) + } + if (filter.accept(event)) { result.push(i); + } } result.sort( (a, b) => SDK.TracingModel.Event.compareStartTime( @@ -395,8 +412,9 @@ * @return {?PerfUI.FlameChart.Group} */ _appendSyncEvents(track, events, title, style, entryType, selectable) { - if (!events.length) + if (!events.length) { return null; + } const isExtension = entryType === Timeline.TimelineFlameChartDataProvider.EntryType.ExtensionEvent; const openEvents = []; const flowEventsEnabled = Runtime.experiments.isEnabled('timelineFlowEvents'); @@ -415,40 +433,50 @@ Timeline.TimelineUIUtils.markerStyleForEvent(e))); } if (!SDK.TracingModel.isFlowPhase(e.phase)) { - if (!e.endTime && e.phase !== SDK.TracingModel.Phase.Instant) + if (!e.endTime && e.phase !== SDK.TracingModel.Phase.Instant) { continue; - if (SDK.TracingModel.isAsyncPhase(e.phase)) + } + if (SDK.TracingModel.isAsyncPhase(e.phase)) { continue; - if (!isExtension && !this._performanceModel.isVisible(e)) + } + if (!isExtension && !this._performanceModel.isVisible(e)) { continue; + } } - while (openEvents.length && openEvents.peekLast().endTime <= e.startTime) + while (openEvents.length && openEvents.peekLast().endTime <= e.startTime) { openEvents.pop(); + } e._blackboxRoot = false; if (blackboxingEnabled && this._isBlackboxedEvent(e)) { const parent = openEvents.peekLast(); - if (parent && parent._blackboxRoot) + if (parent && parent._blackboxRoot) { continue; + } e._blackboxRoot = true; } if (!group) { group = this._appendHeader(title, style, selectable); - if (selectable) + if (selectable) { group._track = track; + } } const level = this._currentLevel + openEvents.length; - if (flowEventsEnabled) + if (flowEventsEnabled) { this._appendFlowEvent(e, level); + } const index = this._appendEvent(e, level); - if (openEvents.length) + if (openEvents.length) { this._entryParent[index] = openEvents.peekLast(); - if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e)) + } + if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e)) { this._timelineData.entryTotalTimes[this._entryData.length] = undefined; + } maxStackDepth = Math.max(maxStackDepth, openEvents.length + 1); - if (e.endTime) + if (e.endTime) { openEvents.push(e); + } } this._entryTypeByLevel.length = this._currentLevel + maxStackDepth; this._entryTypeByLevel.fill(entryType, this._currentLevel); @@ -461,8 +489,9 @@ * @return {boolean} */ _isBlackboxedEvent(event) { - if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame) + if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame) { return false; + } const url = event.args['data']['url']; return url && this._isBlackboxedURL(url); } @@ -485,18 +514,21 @@ * @return {?PerfUI.FlameChart.Group} */ _appendAsyncEventsGroup(track, header, events, style, entryType, selectable) { - if (!events.length) + if (!events.length) { return null; + } const lastUsedTimeByLevel = []; let group = null; for (let i = 0; i < events.length; ++i) { const asyncEvent = events[i]; - if (!this._performanceModel.isVisible(asyncEvent)) + if (!this._performanceModel.isVisible(asyncEvent)) { continue; + } if (!group && header) { group = this._appendHeader(header, style, selectable); - if (selectable) + if (selectable) { group._track = track; + } } const startTime = asyncEvent.startTime; let level; @@ -513,8 +545,9 @@ _appendInteractionRecords() { const interactionRecords = this._performanceModel.interactionRecords(); - if (!interactionRecords.length) + if (!interactionRecords.length) { return; + } this._appendHeader(ls`Interactions`, this._interactionsHeaderLevel1, false /* selectable */); for (const segment of interactionRecords) { const index = this._entryData.length; @@ -536,12 +569,14 @@ const timelineModel = this._performanceModel.timelineModel(); for (const track of this._model.tracks()) { for (const event of track.events) { - if (!timelineModel.isMarkerEvent(event)) + if (!timelineModel.isMarkerEvent(event)) { continue; - if (timelineModel.isLCPCandidateEvent(event) || timelineModel.isLCPInvalidateEvent(event)) + } + if (timelineModel.isLCPCandidateEvent(event) || timelineModel.isLCPInvalidateEvent(event)) { lcpEvents.push(event); - else + } else { metricEvents.push(event); + } } } @@ -554,8 +589,9 @@ const key = e.args['data']['navigationId']; const previousLastEvent = lcpEventsByNavigationId.get(key); - if (!previousLastEvent || previousLastEvent.args['data']['candidateIndex'] < e.args['data']['candidateIndex']) + if (!previousLastEvent || previousLastEvent.args['data']['candidateIndex'] < e.args['data']['candidateIndex']) { lcpEventsByNavigationId.set(key, e); + } } const latestCandidates = Array.from(lcpEventsByNavigationId.values()); @@ -590,8 +626,9 @@ } ++this._currentLevel; - if (!hasFilmStrip) + if (!hasFilmStrip) { return; + } this._appendHeader('', this._screenshotsHeader, false /* selectable */); this._entryTypeByLevel[this._currentLevel] = Timeline.TimelineFlameChartDataProvider.EntryType.Screenshot; let prevTimestamp; @@ -599,12 +636,14 @@ this._entryData.push(screenshot); this._timelineData.entryLevels.push(this._currentLevel); this._timelineData.entryStartTimes.push(screenshot.timestamp); - if (prevTimestamp) + if (prevTimestamp) { this._timelineData.entryTotalTimes.push(screenshot.timestamp - prevTimestamp); + } prevTimestamp = screenshot.timestamp; } - if (screenshots.length) + if (screenshots.length) { this._timelineData.entryTotalTimes.push(this._model.maximumRecordTime() - prevTimestamp); + } ++this._currentLevel; } @@ -637,10 +676,11 @@ '%s (self %s)', Number.millisToString(totalTime, true), Number.millisToString(selfTime, true)) : Number.millisToString(totalTime, true); } - if (this._performanceModel.timelineModel().isMarkerEvent(event)) + if (this._performanceModel.timelineModel().isMarkerEvent(event)) { title = Timeline.TimelineUIUtils.eventTitle(event); - else + } else { title = this.entryTitle(entryIndex); + } warning = Timeline.TimelineUIUtils.eventWarning(event); } else if (type === Timeline.TimelineFlameChartDataProvider.EntryType.Frame) { const frame = /** @type {!TimelineModel.TimelineFrame} */ (this._entryData[entryIndex]); @@ -675,8 +715,9 @@ // This is not annotated due to closure compiler failure to properly infer cache container's template type. function patchColorAndCache(cache, key, lookupColor) { let color = cache.get(key); - if (color) + if (color) { return color; + } const parsedColor = Common.Color.parse(lookupColor(key)); color = parsedColor.setAlpha(0.7).asString(Common.Color.Format.RGBA) || ''; cache.set(key, color); @@ -687,15 +728,19 @@ const type = this._entryType(entryIndex); if (type === entryTypes.Event) { const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); - if (this._model.isGenericTrace()) + if (this._model.isGenericTrace()) { return this._genericTraceEventColor(event); - if (this._performanceModel.timelineModel().isMarkerEvent(event)) + } + if (this._performanceModel.timelineModel().isMarkerEvent(event)) { return Timeline.TimelineUIUtils.markerStyleForEvent(event).color; - if (!SDK.TracingModel.isAsyncPhase(event.phase)) + } + if (!SDK.TracingModel.isAsyncPhase(event.phase)) { return this._colorForEvent(event); + } if (event.hasCategory(TimelineModel.TimelineModel.Category.Console) || - event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) + event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) { return this._consoleColorGenerator.colorForID(event.name); + } if (event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)) { const phase = TimelineModel.TimelineIRModel.phaseForEvent(event) || TimelineModel.TimelineIRModel.Phases.Uncategorized; @@ -705,10 +750,12 @@ const category = Timeline.TimelineUIUtils.eventStyle(event).category; return patchColorAndCache(this._asyncColorByCategory, category, () => category.color); } - if (type === entryTypes.Frame) + if (type === entryTypes.Frame) { return 'white'; - if (type === entryTypes.InteractionRecord) + } + if (type === entryTypes.InteractionRecord) { return 'transparent'; + } if (type === entryTypes.ExtensionEvent) { const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); return this._extensionColorGenerator.colorForID(event.name); @@ -770,8 +817,9 @@ } const image = this._screenshotImageCache.get(screenshot); - if (!image) + if (!image) { return; + } const imageX = barX + 1; const imageY = barY + 1; const imageHeight = barHeight - 2; @@ -835,8 +883,9 @@ context.fillRect(barX, barY + barHeight - 3, width, 2); } } - if (TimelineModel.TimelineData.forEvent(event).warning) + if (TimelineModel.TimelineData.forEvent(event).warning) { paintWarningDecoration(barX, barWidth - 1.5); + } } /** @@ -869,10 +918,12 @@ forceDecoration(entryIndex) { const entryTypes = Timeline.TimelineFlameChartDataProvider.EntryType; const type = this._entryType(entryIndex); - if (type === entryTypes.Frame) + if (type === entryTypes.Frame) { return true; - if (type === entryTypes.Screenshot) + } + if (type === entryTypes.Screenshot) { return true; + } if (type === entryTypes.Event) { const event = /** @type {!SDK.TracingModel.Event} */ (this._entryData[entryIndex]); @@ -886,8 +937,9 @@ */ appendExtensionEvents(entry) { this._extensionInfo.push(entry); - if (this._timelineData) + if (this._timelineData) { this._innerAppendExtensionEvents(this._extensionInfo.length - 1); + } } /** @@ -897,13 +949,15 @@ const entry = this._extensionInfo[index]; const entryType = Timeline.TimelineFlameChartDataProvider.EntryType.ExtensionEvent; const allThreads = [].concat(...entry.model.sortedProcesses().map(process => process.sortedThreads())); - if (!allThreads.length) + if (!allThreads.length) { return; + } const singleTrack = allThreads.length === 1 && (!allThreads[0].events().length || !allThreads[0].asyncEvents().length); - if (!singleTrack) + if (!singleTrack) { this._appendHeader(entry.title, this._headerLevel1, false /* selectable */); + } const style = singleTrack ? this._headerLevel2 : this._headerLevel1; let threadIndex = 0; for (const thread of allThreads) { @@ -1031,8 +1085,9 @@ timelineSelection = Timeline.TimelineSelection.fromFrame( /** @type {!TimelineModel.TimelineFrame} */ (this._entryData[entryIndex])); } - if (timelineSelection) + if (timelineSelection) { this._lastSelection = new Timeline.TimelineFlameChartView.Selection(timelineSelection, entryIndex); + } return timelineSelection; } @@ -1060,16 +1115,19 @@ * @return {number} */ entryIndexForSelection(selection) { - if (!selection || selection.type() === Timeline.TimelineSelection.Type.Range) + if (!selection || selection.type() === Timeline.TimelineSelection.Type.Range) { return -1; + } - if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) + if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) { return this._lastSelection.entryIndex; + } const index = this._entryData.indexOf( /** @type {!SDK.TracingModel.Event|!TimelineModel.TimelineFrame|!TimelineModel.TimelineIRModel.Phases} */ (selection.object())); - if (index !== -1) + if (index !== -1) { this._lastSelection = new Timeline.TimelineFlameChartView.Selection(selection, index); + } return index; } @@ -1078,8 +1136,9 @@ * @return {boolean} */ buildFlowForInitiator(entryIndex) { - if (this._lastInitiatorEntry === entryIndex) + if (this._lastInitiatorEntry === entryIndex) { return false; + } this._lastInitiatorEntry = entryIndex; let event = this.eventByIndex(entryIndex); const td = this._timelineData; @@ -1092,11 +1151,13 @@ let initiator; for (; event; event = this._eventParent(event)) { initiator = TimelineModel.TimelineData.forEvent(event).initiator(); - if (initiator) + if (initiator) { break; + } } - if (!initiator) + if (!initiator) { break; + } const eventIndex = event[Timeline.TimelineFlameChartDataProvider._indexSymbol]; const initiatorIndex = initiator[Timeline.TimelineFlameChartDataProvider._indexSymbol]; td.flowStartTimes.push(initiator.endTime || initiator.startTime);
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartNetworkDataProvider.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartNetworkDataProvider.js index 10fb33e7..70a3c4b 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartNetworkDataProvider.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartNetworkDataProvider.js
@@ -60,13 +60,15 @@ * @return {!PerfUI.FlameChart.TimelineData} */ timelineData() { - if (this._timelineData) + if (this._timelineData) { return this._timelineData; + } /** @type {!Array<!TimelineModel.TimelineModel.NetworkRequest>} */ this._requests = []; this._timelineData = new PerfUI.FlameChart.TimelineData([], [], [], []); - if (this._model) + if (this._model) { this._appendTimelineData(); + } return this._timelineData; } @@ -101,8 +103,9 @@ * @return {?Timeline.TimelineSelection} */ createSelection(index) { - if (index === -1) + if (index === -1) { return null; + } const request = this._requests[index]; this._lastSelection = new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request), index); @@ -114,14 +117,17 @@ * @return {number} */ entryIndexForSelection(selection) { - if (!selection) + if (!selection) { return -1; + } - if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) + if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) { return this._lastSelection.entryIndex; + } - if (selection.type() !== Timeline.TimelineSelection.Type.NetworkRequest) + if (selection.type() !== Timeline.TimelineSelection.Type.NetworkRequest) { return -1; + } const request = /** @type{!TimelineModel.TimelineModel.NetworkRequest} */ (selection.object()); const index = this._requests.indexOf(request); if (index !== -1) { @@ -186,8 +192,9 @@ */ decorateEntry(index, context, text, barX, barY, barWidth, barHeight, unclippedBarX, timeToPixelRatio) { const request = /** @type {!TimelineModel.TimelineModel.NetworkRequest} */ (this._requests[index]); - if (!request.timing) + if (!request.timing) { return false; + } const beginTime = request.beginTime(); /** @@ -279,8 +286,9 @@ const /** @const */ minTextWidthPx = 20; if (textWidth >= minTextWidthPx) { text = this.entryTitle(index) || ''; - if (request.fromServiceWorker) + if (request.fromServiceWorker) { text = 'âš™ ' + text; + } if (text) { const /** @const */ textPadding = 4; const /** @const */ textBaseline = 5; @@ -311,15 +319,17 @@ prepareHighlightedEntryInfo(index) { const /** @const */ maxURLChars = 80; const request = /** @type {!TimelineModel.TimelineModel.NetworkRequest} */ (this._requests[index]); - if (!request.url) + if (!request.url) { return null; + } const element = createElement('div'); const root = UI.createShadowRootWithCoreStyles(element, 'timeline/timelineFlamechartPopover.css'); const contents = root.createChild('div', 'timeline-flamechart-popover'); const startTime = request.getStartTime(); const duration = request.endTime - startTime; - if (startTime && isFinite(duration)) + if (startTime && isFinite(duration)) { contents.createChild('span', 'timeline-info-network-time').textContent = Number.millisToString(duration, true); + } if (typeof request.priority === 'string') { const div = contents.createChild('span'); div.textContent = @@ -355,8 +365,9 @@ } _updateTimelineData() { - if (!this._timelineData) + if (!this._timelineData) { return; + } const lastTimeByLevel = []; let maxLevel = 0; for (let i = 0; i < this._requests.length; ++i) { @@ -367,15 +378,17 @@ this._timelineData.entryLevels[i] = -1; continue; } - while (lastTimeByLevel.length && lastTimeByLevel.peekLast() <= beginTime) + while (lastTimeByLevel.length && lastTimeByLevel.peekLast() <= beginTime) { lastTimeByLevel.pop(); + } this._timelineData.entryLevels[i] = lastTimeByLevel.length; lastTimeByLevel.push(r.endTime); maxLevel = Math.max(maxLevel, lastTimeByLevel.length); } for (let i = 0; i < this._requests.length; ++i) { - if (this._timelineData.entryLevels[i] === -1) + if (this._timelineData.entryLevels[i] === -1) { this._timelineData.entryLevels[i] = maxLevel; + } } this._timelineData = new PerfUI.FlameChart.TimelineData( this._timelineData.entryLevels, this._timelineData.entryTotalTimes, this._timelineData.entryStartTimes,
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js index afaea6a..24b29d8 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartView.js
@@ -92,8 +92,9 @@ _updateColorMapper() { /** @type {!Map<string, string>} */ this._urlToColorCache = new Map(); - if (!this._model) + if (!this._model) { return; + } const colorByProduct = this._groupBySetting.get() === Timeline.AggregatedTimelineTreeView.GroupBy.Product; this._mainDataProvider.setEventColorMapping( colorByProduct ? this._colorByProductForEvent.bind(this) : Timeline.TimelineUIUtils.eventColor); @@ -146,8 +147,9 @@ * @param {?PerfUI.FlameChart.Group} group */ updateSelectedGroup(flameChart, group) { - if (flameChart !== this._mainFlameChart) + if (flameChart !== this._mainFlameChart) { return; + } const track = group ? this._mainDataProvider.groupTrack(group) : null; this._selectedTrack = track; this._updateTrack(); @@ -157,8 +159,9 @@ * @param {?Timeline.PerformanceModel} model */ setModel(model) { - if (model === this._model) + if (model === this._model) { return; + } Common.EventTarget.removeEventListeners(this._eventListeners); this._model = model; this._selectedTrack = null; @@ -203,11 +206,13 @@ } _appendExtensionData() { - if (!this._model) + if (!this._model) { return; + } const extensions = this._model.extensionInfo(); - while (this._nextExtensionIndex < extensions.length) + while (this._nextExtensionIndex < extensions.length) { this._mainDataProvider.appendExtensionEvents(extensions[this._nextExtensionIndex++]); + } this._mainFlameChart.scheduleUpdate(); } @@ -218,15 +223,18 @@ SDK.OverlayModel.hideDOMNodeHighlight(); const entryIndex = /** @type {number} */ (commonEvent.data); const event = this._mainDataProvider.eventByIndex(entryIndex); - if (!event) + if (!event) { return; + } const target = this._model && this._model.timelineModel().targetByEvent(event); - if (!target) + if (!target) { return; + } const timelineData = TimelineModel.TimelineData.forEvent(event); const backendNodeId = timelineData.backendNodeId; - if (!backendNodeId) + if (!backendNodeId) { return; + } new SDK.DeferredDOMNode(target, backendNodeId).highlight(); } @@ -236,10 +244,11 @@ highlightEvent(event) { const entryIndex = event ? this._mainDataProvider.entryIndexForSelection(Timeline.TimelineSelection.fromTraceEvent(event)) : -1; - if (entryIndex >= 0) + if (entryIndex >= 0) { this._mainFlameChart.highlightEntry(entryIndex); - else + } else { this._mainFlameChart.hideHighlight(); + } } /** @@ -258,17 +267,19 @@ this._networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights, this); this._showMemoryGraphSetting.addChangeListener(this._updateCountersGraphToggle, this); Bindings.blackboxManager.addChangeListener(this._boundRefresh); - if (this._needsResizeToPreferredHeights) + if (this._needsResizeToPreferredHeights) { this.resizeToPreferredHeights(); + } this._mainFlameChart.scheduleUpdate(); this._networkFlameChart.scheduleUpdate(); } _updateCountersGraphToggle() { - if (this._showMemoryGraphSetting.get()) + if (this._showMemoryGraphSetting.get()) { this._chartSplitWidget.showBoth(); - else + } else { this._chartSplitWidget.hideSidebar(); + } } /** @@ -279,8 +290,9 @@ this._mainFlameChart.setSelectedEntry(index); index = this._networkDataProvider.entryIndexForSelection(selection); this._networkFlameChart.setSelectedEntry(index); - if (this._detailsView) + if (this._detailsView) { this._detailsView.setSelection(selection); + } } /** @@ -290,8 +302,9 @@ _onEntrySelected(dataProvider, event) { const entryIndex = /** @type{number} */ (event.data); if (Runtime.experiments.isEnabled('timelineEventInitiators') && dataProvider === this._mainDataProvider) { - if (this._mainDataProvider.buildFlowForInitiator(entryIndex)) + if (this._mainDataProvider.buildFlowForInitiator(entryIndex)) { this._mainFlameChart.scheduleUpdate(); + } } this._delegate.select(dataProvider.createSelection(entryIndex)); } @@ -322,8 +335,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchResults || !this._searchResults.length) + if (!this._searchResults || !this._searchResults.length) { return; + } const index = typeof this._selectedSearchResult !== 'undefined' ? this._searchResults.indexOf(this._selectedSearchResult) : -1; @@ -334,8 +348,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchResults || !this._searchResults.length) + if (!this._searchResults || !this._searchResults.length) { return; + } const index = typeof this._selectedSearchResult !== 'undefined' ? this._searchResults.indexOf(this._selectedSearchResult) : 0; this._selectSearchResult(mod(index - 1, this._searchResults.length)); @@ -374,17 +389,20 @@ const oldSelectedSearchResult = this._selectedSearchResult; delete this._selectedSearchResult; this._searchResults = []; - if (!this._searchRegex || !this._model) + if (!this._searchRegex || !this._model) { return; + } const regExpFilter = new Timeline.TimelineFilters.RegExp(this._searchRegex); const window = this._model.window(); this._searchResults = this._mainDataProvider.search(window.left, window.right, regExpFilter); this._searchableView.updateSearchMatchesCount(this._searchResults.length); - if (!shouldJump || !this._searchResults.length) + if (!shouldJump || !this._searchResults.length) { return; + } let selectedIndex = this._searchResults.indexOf(oldSelectedSearchResult); - if (selectedIndex === -1) + if (selectedIndex === -1) { selectedIndex = jumpBackwards ? this._searchResults.length - 1 : 0; + } this._selectSearchResult(selectedIndex); } @@ -392,8 +410,9 @@ * @override */ searchCanceled() { - if (typeof this._selectedSearchResult !== 'undefined') + if (typeof this._selectedSearchResult !== 'undefined') { this._delegate.select(null); + } delete this._searchResults; delete this._selectedSearchResult; delete this._searchRegex; @@ -466,8 +485,9 @@ * @return {?string} */ title() { - if (this._style.lowPriority) + if (this._style.lowPriority) { return null; + } const startTime = Number.millisToString(this._startOffset); return ls`${this._style.title} at ${startTime}`; } @@ -482,8 +502,9 @@ draw(context, x, height, pixelsPerMillisecond) { const lowPriorityVisibilityThresholdInPixelsPerMs = 4; - if (this._style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs) + if (this._style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs) { return; + } context.save(); if (this._style.tall) {
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineHistoryManager.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineHistoryManager.js index ecd5308..2834f25 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineHistoryManager.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineHistoryManager.js
@@ -33,8 +33,9 @@ this._buildPreview(performanceModel); this._button.setText(this._title(performanceModel)); this._updateState(); - if (this._recordings.length <= Timeline.TimelineHistoryManager._maxRecordings) + if (this._recordings.length <= Timeline.TimelineHistoryManager._maxRecordings) { return; + } const lruModel = this._recordings.reduce((a, b) => lastUsedTime(a) < lastUsedTime(b) ? a : b); this._recordings.splice(this._recordings.indexOf(lruModel), 1); lruModel.dispose(); @@ -73,13 +74,15 @@ * @return {!Promise<?Timeline.PerformanceModel>} */ async showHistoryDropDown() { - if (this._recordings.length < 2 || !this._enabled) + if (this._recordings.length < 2 || !this._enabled) { return null; + } const model = await Timeline.TimelineHistoryManager.DropDown.show( this._recordings, /** @type {!Timeline.PerformanceModel} */ (this._lastActiveModel), this._button.element); - if (!model) + if (!model) { return null; + } const index = this._recordings.indexOf(model); if (index < 0) { console.assert(false, `selected recording not found`); @@ -98,11 +101,13 @@ * @return {?Timeline.PerformanceModel} */ navigate(direction) { - if (!this._enabled || !this._lastActiveModel) + if (!this._enabled || !this._lastActiveModel) { return null; + } const index = this._recordings.indexOf(this._lastActiveModel); - if (index < 0) + if (index < 0) { return null; + } const newIndex = Number.constrain(index + direction, 0, this._recordings.length - 1); const model = this._recordings[newIndex]; this._setCurrentModel(model); @@ -140,11 +145,13 @@ */ static _coarseAge(time) { const seconds = Math.round((Date.now() - time) / 1000); - if (seconds < 50) + if (seconds < 50) { return Common.UIString('moments'); + } const minutes = Math.round(seconds / 60); - if (minutes < 50) + if (minutes < 50) { return Common.UIString('%s m', minutes); + } const hours = Math.round(minutes / 60); return Common.UIString('%s h', hours); } @@ -207,8 +214,9 @@ container.style.height = this._totalHeight + 'px'; const filmStripModel = performanceModel.filmStripModel(); const lastFrame = filmStripModel.frames().peekLast(); - if (!lastFrame) + if (!lastFrame) { return container; + } lastFrame.imageDataPromise() .then(data => UI.loadImageFromData(data)) .then(image => image && container.appendChild(image)); @@ -297,15 +305,17 @@ * @return {!Promise<?Timeline.PerformanceModel>} */ static show(models, currentModel, anchor) { - if (Timeline.TimelineHistoryManager.DropDown._instance) + if (Timeline.TimelineHistoryManager.DropDown._instance) { return Promise.resolve(/** @type {?Timeline.PerformanceModel} */ (null)); + } const instance = new Timeline.TimelineHistoryManager.DropDown(models); return instance._show(anchor, currentModel); } static cancelIfShowing() { - if (!Timeline.TimelineHistoryManager.DropDown._instance) + if (!Timeline.TimelineHistoryManager.DropDown._instance) { return; + } Timeline.TimelineHistoryManager.DropDown._instance._close(null); } @@ -330,8 +340,9 @@ _onMouseMove(event) { const node = event.target.enclosingNodeOrSelfWithClass('preview-item'); const listItem = node && this._listControl.itemForNode(node); - if (!listItem) + if (!listItem) { return; + } this._listControl.selectItem(listItem); } @@ -339,8 +350,9 @@ * @param {!Event} event */ _onClick(event) { - if (!event.target.enclosingNodeOrSelfWithClass('preview-item')) + if (!event.target.enclosingNodeOrSelfWithClass('preview-item')) { return; + } this._close(this._listControl.selectedItem()); } @@ -408,10 +420,12 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected'); - if (toElement) + } + if (toElement) { toElement.classList.add('selected'); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineLayersView.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineLayersView.js index 2947116..9342274e 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineLayersView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineLayersView.js
@@ -46,10 +46,11 @@ */ showLayerTree(frameLayerTree) { this._frameLayerTree = frameLayerTree; - if (this.isShowing()) + if (this.isShowing()) { this._update(); - else + } else { this._updateWhenVisible = true; + } } /** @@ -68,8 +69,9 @@ _onPaintProfilerRequested(event) { const selection = /** @type {!LayerViewer.LayerView.Selection} */ (event.data); this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect => { - if (snapshotWithRect) + if (snapshotWithRect) { this._showPaintProfilerCallback(snapshotWithRect.snapshot); + } }); }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineLoader.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineLoader.js index c1027192..5c61893e 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineLoader.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineLoader.js
@@ -39,8 +39,9 @@ loader._canceledCallback = fileReader.cancel.bind(fileReader); loader._totalSize = file.size; fileReader.read(loader).then(success => { - if (!success) + if (!success) { loader._reportErrorAndCancelLoading(fileReader.error().message); + } }); return loader; } @@ -84,8 +85,9 @@ this._backingStorage.reset(); this._client.loadingComplete(null); this._client = null; - if (this._canceledCallback) + if (this._canceledCallback) { this._canceledCallback(); + } } /** @@ -94,13 +96,15 @@ * @return {!Promise} */ write(chunk) { - if (!this._client) + if (!this._client) { return Promise.resolve(); + } this._loadedBytes += chunk.length; - if (this._firstRawChunk) + if (this._firstRawChunk) { this._client.loadingStarted(); - else + } else { this._client.loadingProgress(this._totalSize ? this._loadedBytes / this._totalSize : undefined); + } this._firstRawChunk = false; if (this._state === Timeline.TimelineLoader.State.Initial) { @@ -126,19 +130,23 @@ const startPos = this._buffer.length - objectName.length; this._buffer += chunk; const pos = this._buffer.indexOf(objectName, startPos); - if (pos === -1) + if (pos === -1) { return Promise.resolve(); + } chunk = this._buffer.slice(pos + objectName.length); this._state = Timeline.TimelineLoader.State.ReadingEvents; } - if (this._state !== Timeline.TimelineLoader.State.ReadingEvents) + if (this._state !== Timeline.TimelineLoader.State.ReadingEvents) { return Promise.resolve(); - if (this._jsonTokenizer.write(chunk)) + } + if (this._jsonTokenizer.write(chunk)) { return Promise.resolve(); + } this._state = Timeline.TimelineLoader.State.SkippingTail; - if (this._firstChunk) + if (this._firstChunk) { this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline input, wrong JSON brackets balance')); + } return Promise.resolve(); } @@ -150,8 +158,9 @@ if (!this._firstChunk) { const commaIndex = json.indexOf(','); - if (commaIndex !== -1) + if (commaIndex !== -1) { json = json.slice(commaIndex + 1); + } json = '[' + json; } @@ -182,8 +191,9 @@ * @param {string=} message */ _reportErrorAndCancelLoading(message) { - if (message) + if (message) { Common.console.error(message); + } this.cancel(); } @@ -199,8 +209,9 @@ * @override */ async close() { - if (!this._client) + if (!this._client) { return; + } this._client.processingStarted(); setTimeout(() => this._finalizeTrace(), 0); }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelinePaintProfilerView.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelinePaintProfilerView.js index c4c1153..da5e06bb 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelinePaintProfilerView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelinePaintProfilerView.js
@@ -70,18 +70,21 @@ this._event = event; this._updateWhenVisible(); - if (this._event.name === TimelineModel.TimelineModel.RecordType.Paint) + if (this._event.name === TimelineModel.TimelineModel.RecordType.Paint) { return !!TimelineModel.TimelineData.forEvent(event).picture; - if (this._event.name === TimelineModel.TimelineModel.RecordType.RasterTask) + } + if (this._event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { return this._frameModel.hasRasterTile(this._event); + } return false; } _updateWhenVisible() { - if (this.isShowing()) + if (this.isShowing()) { this._update(); - else + } else { this._needsUpdateWhenVisible = true; + } } _update() { @@ -127,8 +130,9 @@ } _releaseSnapshot() { - if (!this._lastLoadedSnapshot) + if (!this._lastLoadedSnapshot) { return; + } this._lastLoadedSnapshot.release(); this._lastLoadedSnapshot = null; } @@ -160,8 +164,9 @@ * @override */ onResize() { - if (this._imageElement.src) + if (this._imageElement.src) { this._updateImagePosition(); + } } _updateImagePosition() { @@ -207,8 +212,9 @@ */ showImage(imageURL) { this._imageContainer.classList.toggle('hidden', !imageURL); - if (imageURL) + if (imageURL) { this._imageElement.src = imageURL; + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js index 4d4f7be..74d990cb 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelinePanel.js
@@ -73,8 +73,9 @@ this._startCoverage = Common.settings.createSetting('timelineStartCoverage', false); this._startCoverage.setTitle(ls`Coverage`); - if (!Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')) + if (!Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')) { this._startCoverage.set(false); + } this._showMemorySetting = Common.settings.createSetting('timelineShowMemory', false); @@ -159,8 +160,9 @@ * @param {!Array.<!SDK.TracingManager.EventPayload>} events */ loadFromEvents(events) { - if (this._state !== Timeline.TimelinePanel.State.Idle) + if (this._state !== Timeline.TimelinePanel.State.Idle) { return; + } this._prepareToLoadTimeline(); this._loader = Timeline.TimelineLoader.loadFromEvents(events, this); } @@ -335,8 +337,9 @@ } _createFileSelector() { - if (this._fileSelectorElement) + if (this._fileSelectorElement) { this._fileSelectorElement.remove(); + } this._fileSelectorElement = UI.createFileSelectorElement(this._loadFromFile.bind(this)); this._timelinePane.element.appendChild(this._fileSelectorElement); } @@ -354,31 +357,36 @@ * @suppress {deprecated} */ async _saveToFile() { - if (this._state !== Timeline.TimelinePanel.State.Idle) + if (this._state !== Timeline.TimelinePanel.State.Idle) { return; + } const performanceModel = this._performanceModel; - if (!performanceModel) + if (!performanceModel) { return; + } const now = new Date(); const fileName = 'Profile-' + now.toISO8601Compact() + '.json'; const stream = new Bindings.FileOutputStream(); const accepted = await stream.open(fileName); - if (!accepted) + if (!accepted) { return; + } const error = await performanceModel.save(stream); - if (!error) + if (!error) { return; + } Common.console.error( Common.UIString('Failed to save timeline: %s (%s, %s)', error.message, error.name, error.code)); } async _showHistory() { const model = await this._historyManager.showHistoryDropDown(); - if (model && model !== this._performanceModel) + if (model && model !== this._performanceModel) { this._setModel(model); + } } /** @@ -387,8 +395,9 @@ */ _navigateHistory(direction) { const model = this._historyManager.navigate(direction); - if (model && model !== this._performanceModel) + if (model && model !== this._performanceModel) { this._setModel(model); + } return true; } @@ -400,8 +409,9 @@ * @param {!File} file */ _loadFromFile(file) { - if (this._state !== Timeline.TimelinePanel.State.Idle) + if (this._state !== Timeline.TimelinePanel.State.Idle) { return; + } this._prepareToLoadTimeline(); this._loader = Timeline.TimelineLoader.loadFromFile(file, this); this._createFileSelector(); @@ -411,8 +421,9 @@ * @param {string} url */ _loadFromURL(url) { - if (this._state !== Timeline.TimelinePanel.State.Idle) + if (this._state !== Timeline.TimelinePanel.State.Idle) { return; + } this._prepareToLoadTimeline(); this._loader = Timeline.TimelineLoader.loadFromURL(url, this); } @@ -420,20 +431,25 @@ _updateOverviewControls() { this._overviewControls = []; this._overviewControls.push(new Timeline.TimelineEventOverviewResponsiveness()); - if (Runtime.experiments.isEnabled('inputEventsOnTimelineOverview')) + if (Runtime.experiments.isEnabled('inputEventsOnTimelineOverview')) { this._overviewControls.push(new Timeline.TimelineEventOverviewInput()); + } this._overviewControls.push(new Timeline.TimelineEventOverviewFrames()); this._overviewControls.push(new Timeline.TimelineEventOverviewCPUActivity()); this._overviewControls.push(new Timeline.TimelineEventOverviewNetwork()); if (this._showScreenshotsSetting.get() && this._performanceModel && - this._performanceModel.filmStripModel().frames().length) + this._performanceModel.filmStripModel().frames().length) { this._overviewControls.push(new Timeline.TimelineFilmStripOverview()); - if (this._showMemorySetting.get()) + } + if (this._showMemorySetting.get()) { this._overviewControls.push(new Timeline.TimelineEventOverviewMemory()); - if (this._startCoverage.get()) + } + if (this._startCoverage.get()) { this._overviewControls.push(new Timeline.TimelineEventOverviewCoverage()); - for (const control of this._overviewControls) + } + for (const control of this._overviewControls) { control.setModel(this._performanceModel); + } this._overviewPane.setOverviewControls(this._overviewControls); } @@ -444,22 +460,27 @@ } _updateSettingsPaneVisibility() { - if (this._showSettingsPaneSetting.get()) + if (this._showSettingsPaneSetting.get()) { this._settingsPane.showWidget(); - else + } else { this._settingsPane.hideWidget(); + } } _updateShowSettingsToolbarButton() { const messages = []; - if (MobileThrottling.throttlingManager().cpuThrottlingRate() !== 1) + if (MobileThrottling.throttlingManager().cpuThrottlingRate() !== 1) { messages.push(Common.UIString('- CPU throttling is enabled')); - if (SDK.multitargetNetworkManager.isThrottling()) + } + if (SDK.multitargetNetworkManager.isThrottling()) { messages.push(Common.UIString('- Network throttling is enabled')); - if (this._captureLayersAndPicturesSetting.get()) + } + if (this._captureLayersAndPicturesSetting.get()) { messages.push(Common.UIString('- Significant overhead due to paint instrumentation')); - if (this._disableCaptureJSProfileSetting.get()) + } + if (this._disableCaptureJSProfileSetting.get()) { messages.push(Common.UIString('- JavaScript sampling is disabled')); + } this._showSettingsPaneButton.setDefaultWithRedColor(messages.length); this._showSettingsPaneButton.setToggleWithRedColor(messages.length); @@ -509,10 +530,11 @@ this._setUIControlsEnabled(false); this._hideLandingPage(); const response = await this._controller.startRecording(recordingOptions, enabledTraceProviders); - if (response[Protocol.Error]) + if (response[Protocol.Error]) { this._recordingFailed(response[Protocol.Error]); - else + } else { this._recordingStarted(); + } } async _stopRecording() { @@ -533,8 +555,9 @@ * @param {string} error The error message to display */ _recordingFailed(error) { - if (this._statusPane) + if (this._statusPane) { this._statusPane.hide(); + } this._statusPane = new Timeline.TimelinePanel.StatusPane({description: error}, () => this.loadingComplete(null)); this._statusPane.showPane(this._statusPaneContainer); this._statusPane.updateStatus(ls`Recording failed`); @@ -576,8 +599,9 @@ } _recordReload() { - if (this._state !== Timeline.TimelinePanel.State.Idle) + if (this._state !== Timeline.TimelinePanel.State.Idle) { return; + } this._recordingPageReload = true; this._startRecording(); Host.userMetrics.actionTaken(Host.UserMetrics.Action.TimelinePageReloadStarted); @@ -602,8 +626,9 @@ * @param {!Timeline.PerformanceModel} model */ _applyFilters(model) { - if (model.timelineModel().isGenericTrace() || Runtime.experiments.isEnabled('timelineShowAllEvents')) + if (model.timelineModel().isGenericTrace() || Runtime.experiments.isEnabled('timelineShowAllEvents')) { return; + } model.setFilters([Timeline.TimelineUIUtils.visibleEventsFilter()]); } @@ -616,8 +641,9 @@ Timeline.PerformanceModel.Events.WindowChanged, this._onModelWindowChanged, this); } this._performanceModel = model; - if (model) + if (model) { this._applyFilters(model); + } this._flameChart.setModel(model); this._updateOverviewControls(); @@ -629,16 +655,19 @@ model.timelineModel().minimumRecordTime(), model.timelineModel().maximumRecordTime()); const lineLevelProfile = self.runtime.sharedInstance(PerfUI.LineLevelProfile.Performance); lineLevelProfile.reset(); - for (const profile of model.timelineModel().cpuProfiles()) + for (const profile of model.timelineModel().cpuProfiles()) { lineLevelProfile.appendCPUProfile(profile); + } this._setMarkers(model.timelineModel()); this._flameChart.setSelection(null); this._overviewPane.setWindowTimes(model.window().left, model.window().right); } - for (const control of this._overviewControls) + for (const control of this._overviewControls) { control.setModel(model); - if (this._flameChart) + } + if (this._flameChart) { this._flameChart.resizeToPreferredHeights(); + } this._updateTimelineControls(); } @@ -646,8 +675,9 @@ if (this._recordingPageReload) { const target = this._controller.mainTarget(); const resourceModel = target.model(SDK.ResourceTreeModel); - if (resourceModel) + if (resourceModel) { resourceModel.reloadPage(); + } } this._reset(); this._setState(Timeline.TimelinePanel.State.Recording); @@ -720,14 +750,16 @@ loadingStarted() { this._hideLandingPage(); - if (this._statusPane) + if (this._statusPane) { this._statusPane.hide(); + } this._statusPane = new Timeline.TimelinePanel.StatusPane({showProgress: true}, this._cancelLoading.bind(this)); this._statusPane.showPane(this._statusPaneContainer); this._statusPane.updateStatus(Common.UIString('Loading profile\u2026')); // FIXME: make loading from backend cancelable as well. - if (!this._loader) + if (!this._loader) { this._statusPane.finish(); + } this.loadingProgress(0); } @@ -736,8 +768,9 @@ * @param {number=} progress */ loadingProgress(progress) { - if (typeof progress === 'number') + if (typeof progress === 'number') { this._statusPane.updateProgressBar(Common.UIString('Received'), progress * 100); + } } /** @@ -755,8 +788,9 @@ delete this._loader; this._setState(Timeline.TimelinePanel.State.Idle); - if (this._statusPane) + if (this._statusPane) { this._statusPane.hide(); + } delete this._statusPane; if (!tracingModel) { @@ -764,8 +798,9 @@ return; } - if (!this._performanceModel) + if (!this._performanceModel) { this._performanceModel = new Timeline.PerformanceModel(); + } this._performanceModel.setTracingModel(tracingModel); this._setModel(this._performanceModel); this._historyManager.addRecording(this._performanceModel); @@ -779,8 +814,9 @@ } _showRecordingStarted() { - if (this._statusPane) + if (this._statusPane) { return; + } this._statusPane = new Timeline.TimelinePanel.StatusPane({showTimer: true, showProgress: true}, this._stopRecording.bind(this)); this._statusPane.showPane(this._statusPaneContainer); @@ -788,8 +824,9 @@ } _cancelLoading() { - if (this._loader) + if (this._loader) { this._loader.cancel(); + } } /** @@ -800,8 +837,9 @@ const recordTypes = TimelineModel.TimelineModel.RecordType; const zeroTime = timelineModel.minimumRecordTime(); for (const event of timelineModel.timeMarkerEvents()) { - if (event.name === recordTypes.TimeStamp || event.name === recordTypes.ConsoleTime) + if (event.name === recordTypes.TimeStamp || event.name === recordTypes.ConsoleTime) { continue; + } markers.set(event.startTime, Timeline.TimelineUIUtils.createEventDivider(event, zeroTime)); } this._overviewPane.setMarkers(markers); @@ -812,14 +850,16 @@ */ async _loadEventFired(event) { if (this._state !== Timeline.TimelinePanel.State.Recording || !this._recordingPageReload || - this._controller.mainTarget() !== event.data.resourceTreeModel.target()) + this._controller.mainTarget() !== event.data.resourceTreeModel.target()) { return; + } const controller = this._controller; await new Promise(r => setTimeout(r, this._millisecondsToRecordAfterLoadEvent)); // Check if we're still in the same recording session. - if (controller !== this._controller || this._state !== Timeline.TimelinePanel.State.Recording) + if (controller !== this._controller || this._state !== Timeline.TimelinePanel.State.Recording) { return; + } this._stopRecording(); } @@ -846,8 +886,9 @@ */ _jumpToFrame(offset) { const currentFrame = this._selection && this._frameForSelection(this._selection); - if (!currentFrame) + if (!currentFrame) { return; + } const frames = this._performanceModel.frames(); let index = frames.indexOf(currentFrame); console.assert(index >= 0, 'Can\'t find current frame in the frame list'); @@ -873,14 +914,16 @@ * @param {number} time */ selectEntryAtTime(events, time) { - if (!events) + if (!events) { return; + } // Find best match, then backtrack to the first visible entry. for (let index = events.upperBound(time, (time, event) => time - event.startTime) - 1; index >= 0; --index) { const event = events[index]; const endTime = event.endTime || event.startTime; - if (SDK.TracingModel.isTopLevelEvent(event) && endTime < time) + if (SDK.TracingModel.isTopLevelEvent(event) && endTime < time) { break; + } if (this._performanceModel.isVisible(event) && endTime >= time) { this.select(Timeline.TimelineSelection.fromTraceEvent(event)); return; @@ -904,10 +947,11 @@ _revealTimeRange(startTime, endTime) { const window = this._performanceModel.window(); let offset = 0; - if (window.right < endTime) + if (window.right < endTime) { offset = endTime - window.right; - else if (window.left > startTime) + } else if (window.left > startTime) { offset = startTime - window.left; + } this._performanceModel.setWindow({left: window.left + offset, right: window.right + offset}, /* animate */ true); } @@ -916,17 +960,20 @@ */ _handleDrop(dataTransfer) { const items = dataTransfer.items; - if (!items.length) + if (!items.length) { return; + } const item = items[0]; if (item.kind === 'string') { const url = dataTransfer.getData('text/uri-list'); - if (new Common.ParsedURL(url).isValid) + if (new Common.ParsedURL(url).isValid) { this._loadFromURL(url); + } } else if (item.kind === 'file') { const entry = items[0].webkitGetAsEntry(); - if (!entry.isFile) + if (!entry.isFile) { return; + } entry.file(this._loadFromFile.bind(this)); } } @@ -1170,8 +1217,9 @@ } _stopTimer() { - if (!this._timeUpdateTimer) + if (!this._timeUpdateTimer) { return; + } clearInterval(this._timeUpdateTimer); this._updateTimer(true); delete this._timeUpdateTimer; @@ -1181,8 +1229,9 @@ * @param {boolean=} precise */ _updateTimer(precise) { - if (!this._timeUpdateTimer) + if (!this._timeUpdateTimer) { return; + } const elapsed = (Date.now() - this._startTime) / 1000; this._time.textContent = Common.UIString('%s\xa0sec', elapsed.toFixed(precise ? 1 : 0)); }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineTreeView.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineTreeView.js index 2b454dd..58f1f3f 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineTreeView.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineTreeView.js
@@ -203,11 +203,13 @@ */ _linkifyLocation(event) { const target = this._model.timelineModel().targetByEvent(event); - if (!target) + if (!target) { return null; + } const frame = TimelineModel.TimelineProfileTree.eventStackFrame(event); - if (!frame) + if (!frame) { return null; + } return this._linkifier.maybeLinkifyConsoleCallFrame(target, frame); } @@ -217,12 +219,14 @@ */ selectProfileNode(treeNode, suppressSelectedEvent) { const pathToRoot = []; - for (let node = treeNode; node; node = node.parent) + for (let node = treeNode; node; node = node.parent) { pathToRoot.push(node); + } for (let i = pathToRoot.length - 1; i > 0; --i) { const gridNode = this.dataGridNodeForTreeNode(pathToRoot[i]); - if (gridNode && gridNode.dataGrid) + if (gridNode && gridNode.dataGrid) { gridNode.expand(); + } } const gridNode = this.dataGridNodeForTreeNode(treeNode); if (gridNode.dataGrid) { @@ -258,11 +262,13 @@ } this._sortingChanged(); this._updateDetailsForSelection(); - if (this._searchableView) + if (this._searchableView) { this._searchableView.refreshSearch(); + } const rootNode = this._dataGrid.rootNode(); - if (rootNode.children.length > 0) + if (rootNode.children.length > 0) { rootNode.children[0].select(); + } } /** @@ -295,8 +301,9 @@ _sortingChanged() { const columnId = this._dataGrid.sortColumnId(); - if (!columnId) + if (!columnId) { return; + } let sortFunction; switch (columnId) { case 'startTime': @@ -355,8 +362,9 @@ } _onShowModeChanged() { - if (this._splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) + if (this._splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) { return; + } this._lastSelectedNode = undefined; this._updateDetailsForSelection(); } @@ -365,15 +373,18 @@ const selectedNode = this._dataGrid.selectedNode ? /** @type {!Timeline.TimelineTreeView.TreeGridNode} */ (this._dataGrid.selectedNode)._profileNode : null; - if (selectedNode === this._lastSelectedNode) + if (selectedNode === this._lastSelectedNode) { return; + } this._lastSelectedNode = selectedNode; - if (this._splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) + if (this._splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) { return; + } this._detailsView.detachChildWidgets(); this._detailsView.element.removeChildren(); - if (selectedNode && this._showDetailsForNode(selectedNode)) + if (selectedNode && this._showDetailsForNode(selectedNode)) { return; + } const banner = this._detailsView.element.createChild('div', 'full-widget-dimmed-banner'); banner.createTextChild(Common.UIString('Select item for details.')); } @@ -395,8 +406,9 @@ this._dataGrid.dataGridNodeFromNode(/** @type {!Node} */ (event.target))) : null; const profileNode = gridNode && gridNode._profileNode; - if (profileNode === this._lastHoveredProfileNode) + if (profileNode === this._lastHoveredProfileNode) { return; + } this._lastHoveredProfileNode = profileNode; this._onHover(profileNode); } @@ -406,11 +418,13 @@ * @param {!DataGrid.DataGridNode} gridNode */ _onContextMenu(contextMenu, gridNode) { - if (gridNode._linkElement && !contextMenu.containsTarget(gridNode._linkElement)) + if (gridNode._linkElement && !contextMenu.containsTarget(gridNode._linkElement)) { contextMenu.appendApplicableItems(gridNode._linkElement); + } const profileNode = gridNode._profileNode; - if (profileNode) + if (profileNode) { this._appendContextMenuItems(contextMenu, profileNode); + } } /** @@ -441,8 +455,9 @@ performSearch(searchConfig, shouldJump, jumpBackwards) { this._searchResults = []; this._currentResult = 0; - if (!this._root) + if (!this._root) { return; + } const searchRegex = searchConfig.toSearchRegex(); this._searchResults = this._root.searchTree(event => Timeline.TimelineUIUtils.testContentMatching(event, searchRegex)); @@ -453,8 +468,9 @@ * @override */ jumpToNextSearchResult() { - if (!this._searchResults.length) + if (!this._searchResults.length) { return; + } this.selectProfileNode(this._searchResults[this._currentResult], false); this._currentResult = mod(this._currentResult + 1, this._searchResults.length); } @@ -463,8 +479,9 @@ * @override */ jumpToPreviousSearchResult() { - if (!this._searchResults.length) + if (!this._searchResults.length) { return; + } this.selectProfileNode(this._searchResults[this._currentResult], false); this._currentResult = mod(this._currentResult - 1, this._searchResults.length); } @@ -514,8 +531,9 @@ * @return {!Element} */ createCell(columnId) { - if (columnId === 'activity') + if (columnId === 'activity') { return this._createNameCell(columnId); + } return this._createValueCell(columnId) || super.createCell(columnId); } @@ -535,18 +553,21 @@ const info = treeView._displayInfoForGroupNode(this._profileNode); name.textContent = info.name; icon.style.backgroundColor = info.color; - if (info.icon) + if (info.icon) { iconContainer.insertBefore(info.icon, icon); + } } else if (event) { const data = event.args['data']; const deoptReason = data && data['deoptReason']; - if (deoptReason) + if (deoptReason) { container.createChild('div', 'activity-warning').title = Common.UIString('Not optimized: %s', deoptReason); + } name.textContent = Timeline.TimelineUIUtils.eventTitle(event); this._linkElement = this._treeView._linkifyLocation(event); - if (this._linkElement) + if (this._linkElement) { container.createChild('div', 'activity-link').appendChild(this._linkElement); + } const eventStyle = Timeline.TimelineUIUtils.eventStyle(event); const eventCategory = eventStyle.category; UI.ARIAUtils.setAccessibleName(icon, eventCategory.title); @@ -560,8 +581,9 @@ * @return {?Element} */ _createValueCell(columnId) { - if (columnId !== 'self' && columnId !== 'total' && columnId !== 'startTime') + if (columnId !== 'self' && columnId !== 'total' && columnId !== 'startTime') { return null; + } let showPercents = false; let value; @@ -622,11 +644,13 @@ * @override */ populate() { - if (this._populated) + if (this._populated) { return; + } this._populated = true; - if (!this._profileNode.children) + if (!this._profileNode.children) { return; + } for (const node of this._profileNode.children().values()) { const gridNode = new Timeline.TimelineTreeView.TreeGridNode( node, this._grandTotalTime, this._maxSelfTime, this._maxTotalTime, this._treeView); @@ -679,15 +703,17 @@ this._updateExtensionResolver(); super.updateContents(selection); const rootNode = this._dataGrid.rootNode(); - if (rootNode.children.length) + if (rootNode.children.length) { rootNode.children[0].select(); + } } _updateExtensionResolver() { this._executionContextNamesByOrigin = new Map(); for (const runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)) { - for (const context of runtimeModel.executionContexts()) + for (const context of runtimeModel.executionContexts()) { this._executionContextNamesByOrigin.set(context.origin, context.name); + } } } @@ -697,12 +723,13 @@ * @this {Timeline.AggregatedTimelineTreeView} */ _beautifyDomainName(name) { - if (Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(name)) + if (Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(name)) { name = Common.UIString('[Chrome extensions overhead]'); - else if (Timeline.AggregatedTimelineTreeView._isV8NativeURL(name)) + } else if (Timeline.AggregatedTimelineTreeView._isV8NativeURL(name)) { name = Common.UIString('[V8 Runtime]'); - else if (name.startsWith('chrome-extension')) + } else if (name.startsWith('chrome-extension')) { name = this._executionContextNamesByOrigin.get(name) || name; + } return name; } @@ -729,8 +756,9 @@ let domainName = id ? this._beautifyDomainName(id) : undefined; if (domainName) { const productName = this._productByEvent(/** @type {!SDK.TracingModel.Event} */ (node.event)); - if (productName) + if (productName) { domainName += ' \u2014 ' + productName; + } } return {name: domainName || unattributed, color: color}; } @@ -800,8 +828,9 @@ console.assert(!!treeNode.parent, 'Attempt to build stack for tree root'); let result = []; // Do not add root to the stack, as it's the tree itself. - for (let node = treeNode; node && node.parent; node = node.parent) + for (let node = treeNode; node && node.parent; node = node.parent) { result.push(node); + } result = result.reverse(); for (let node = treeNode; node && node.children() && node.children().size;) { const children = Array.from(node.children().values()); @@ -821,8 +850,9 @@ _onStackViewSelectionChanged() { const treeNode = this._stackView.selectedTreeNode(); - if (treeNode) + if (treeNode) { this.selectProfileNode(treeNode, true); + } } /** @@ -873,21 +903,28 @@ */ _domainByEvent(groupSubdomains, event) { const url = TimelineModel.TimelineProfileTree.eventURL(event); - if (!url) + if (!url) { return ''; - if (Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(url)) + } + if (Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(url)) { return Timeline.AggregatedTimelineTreeView._extensionInternalPrefix; - if (Timeline.AggregatedTimelineTreeView._isV8NativeURL(url)) + } + if (Timeline.AggregatedTimelineTreeView._isV8NativeURL(url)) { return Timeline.AggregatedTimelineTreeView._v8NativePrefix; + } const parsedURL = url.asParsedURL(); - if (!parsedURL) + if (!parsedURL) { return ''; - if (parsedURL.scheme === 'chrome-extension') + } + if (parsedURL.scheme === 'chrome-extension') { return parsedURL.scheme + '://' + parsedURL.host; - if (!groupSubdomains) + } + if (!groupSubdomains) { return parsedURL.host; - if (/^[.0-9]+$/.test(parsedURL.host)) + } + if (/^[.0-9]+$/.test(parsedURL.host)) { return parsedURL.host; + } const domainMatch = /([^.]*\.)?[^.]*$/.exec(parsedURL.host); return domainMatch && domainMatch[0] || ''; } @@ -898,12 +935,15 @@ */ _productByEvent(event) { const url = TimelineModel.TimelineProfileTree.eventURL(event); - if (!url) + if (!url) { return ''; - if (this._productByURLCache.has(url)) + } + if (this._productByURLCache.has(url)) { return this._productByURLCache.get(url); - if (!this._productRegistry) + } + if (!this._productRegistry) { return ''; + } const parsedURL = url.asParsedURL(); const name = parsedURL && this._productRegistry.nameForUrl(parsedURL) || ''; this._productByURLCache.set(url, name); @@ -916,12 +956,14 @@ */ _productAndBadgeByEvent(event) { const url = TimelineModel.TimelineProfileTree.eventURL(event); - if (!url || !this._productRegistry) + if (!url || !this._productRegistry) { return null; + } const parsedURL = url.asParsedURL(); const name = parsedURL && this._productRegistry.nameForUrl(parsedURL) || this._domainByEvent(true, event); - if (!name) + if (!name) { return null; + } const icon = parsedURL && this._badgePool.badgeForURL(parsedURL); return {name: this._beautifyDomainName(name), badge: icon}; } @@ -932,13 +974,16 @@ * @param {!TimelineModel.TimelineProfileTree.Node} node */ _appendContextMenuItems(contextMenu, node) { - if (this._groupBySetting.get() !== Timeline.AggregatedTimelineTreeView.GroupBy.Frame) + if (this._groupBySetting.get() !== Timeline.AggregatedTimelineTreeView.GroupBy.Frame) { return; - if (!node.isGroupNode()) + } + if (!node.isGroupNode()) { return; + } const frame = this._model.timelineModel().pageFrameById(/** @type {string} */ (node.id)); - if (!frame || !frame.ownerNode) + if (!frame || !frame.ownerNode) { return; + } contextMenu.appendApplicableItems(frame.ownerNode); } @@ -1062,8 +1107,9 @@ for (const node of stack) { const gridNode = new Timeline.TimelineTreeView.GridNode(node, totalTime, totalTime, totalTime, this._treeView); rootNode.appendChild(gridNode); - if (node === selectedNode) + if (node === selectedNode) { nodeToReveal = gridNode; + } } nodeToReveal.revealAndSelect(); }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js index e89b1db3..de25132d 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineUIUtils.js
@@ -37,8 +37,9 @@ * @return {!Object.<string, !Timeline.TimelineRecordStyle>} */ static _initEventStyles() { - if (Timeline.TimelineUIUtils._eventStylesMap) + if (Timeline.TimelineUIUtils._eventStylesMap) { return Timeline.TimelineUIUtils._eventStylesMap; + } const type = TimelineModel.TimelineModel.RecordType; const categories = Timeline.TimelineUIUtils.categories(); @@ -198,8 +199,9 @@ * @return {string} */ static frameDisplayName(frame) { - if (!TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame)) + if (!TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame)) { return UI.beautifyFunctionName(frame.functionName); + } const nativeGroup = TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName); const groups = TimelineModel.TimelineJSProfileProcessor.NativeGroups; switch (nativeGroup) { @@ -220,8 +222,9 @@ const title = Timeline.TimelineUIUtils.eventStyle(traceEvent).title; const tokens = [title]; const url = TimelineModel.TimelineData.forEvent(traceEvent).url; - if (url) + if (url) { tokens.push(url); + } appendObjectProperties(traceEvent.args, 2); return regExp.test(tokens.join('|')); @@ -230,17 +233,19 @@ * @param {number} depth */ function appendObjectProperties(object, depth) { - if (!depth) + if (!depth) { return; + } for (const key in object) { const value = object[key]; const type = typeof value; - if (type === 'string') + if (type === 'string') { tokens.push(value); - else if (type === 'number') + } else if (type === 'number') { tokens.push(String(value)); - else if (type === 'object') + } else if (type === 'object') { appendObjectProperties(value, depth - 1); + } } } } @@ -252,8 +257,9 @@ static eventURL(event) { const data = event.args['data'] || event.args['beginData']; const url = data && data.url; - if (url) + if (url) { return url; + } const stackTrace = data && data['stackTrace']; const frame = stackTrace && stackTrace.length && stackTrace[0] || TimelineModel.TimelineData.forEvent(event).topFrame(); @@ -267,8 +273,9 @@ static eventStyle(event) { const eventStyles = Timeline.TimelineUIUtils._initEventStyles(); if (event.hasCategory(TimelineModel.TimelineModel.Category.Console) || - event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) + event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) { return {title: event.name, category: Timeline.TimelineUIUtils.categories()['scripting']}; + } if (event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)) { /** @const */ @@ -293,8 +300,9 @@ static eventColor(event) { if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame) { const frame = event.args['data']; - if (Timeline.TimelineUIUtils.isUserFrame(frame)) + if (Timeline.TimelineUIUtils.isUserFrame(frame)) { return Timeline.TimelineUIUtils.colorForId(frame.url); + } } return Timeline.TimelineUIUtils.eventStyle(event).category.color; } @@ -309,21 +317,25 @@ static eventColorByProduct(productRegistry, model, urlToColorCache, event) { const url = Timeline.TimelineUIUtils.eventURL(event) || ''; let color = urlToColorCache.get(url); - if (color) + if (color) { return color; + } const defaultColor = '#f2ecdc'; const parsedURL = url.asParsedURL(); - if (!parsedURL) + if (!parsedURL) { return defaultColor; + } let name = productRegistry && productRegistry.nameForUrl(parsedURL); if (!name) { name = parsedURL.host; const rootFrames = model.rootFrames(); - if (rootFrames.some(pageFrame => new Common.ParsedURL(pageFrame.url).host === name)) + if (rootFrames.some(pageFrame => new Common.ParsedURL(pageFrame.url).host === name)) { color = defaultColor; + } } - if (!color) + if (!color) { color = name ? ProductRegistry.BadgePool.colorForEntryName(name) : defaultColor; + } urlToColorCache.set(url, color); return color; } @@ -335,17 +347,22 @@ static eventTitle(event) { const recordType = TimelineModel.TimelineModel.RecordType; const eventData = event.args['data']; - if (event.name === recordType.JSFrame) + if (event.name === recordType.JSFrame) { return Timeline.TimelineUIUtils.frameDisplayName(eventData); + } const title = Timeline.TimelineUIUtils.eventStyle(event).title; - if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) + if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) { return title; - if (event.name === recordType.TimeStamp) + } + if (event.name === recordType.TimeStamp) { return ls`${title}: ${eventData['message']}`; - if (event.name === recordType.Animation && eventData && eventData['name']) + } + if (event.name === recordType.Animation && eventData && eventData['name']) { return ls`${title}: ${eventData['name']}`; - if (event.name === recordType.EventDispatch && eventData && eventData['type']) + } + if (event.name === recordType.EventDispatch && eventData && eventData['type']) { return ls`${title}: ${eventData['type']}`; + } return title; } @@ -476,18 +493,20 @@ case recordType.Paint: { const width = Timeline.TimelineUIUtils.quadWidth(eventData.clip); const height = Timeline.TimelineUIUtils.quadHeight(eventData.clip); - if (width && height) + if (width && height) { detailsText = Common.UIString('%d\xa0\u00d7\xa0%d', width, height); + } break; } case recordType.ParseHTML: { const startLine = event.args['beginData']['startLine']; const endLine = event.args['endData'] && event.args['endData']['endLine']; const url = Bindings.displayNameForURL(event.args['beginData']['url']); - if (endLine >= 0) + if (endLine >= 0) { detailsText = Common.UIString('%s [%s\u2026%s]', url, startLine + 1, endLine + 1); - else + } else { detailsText = Common.UIString('%s [%s\u2026]', url, startLine + 1); + } break; } case recordType.CompileModule: @@ -496,15 +515,17 @@ case recordType.CompileScript: case recordType.EvaluateScript: { const url = eventData && eventData['url']; - if (url) + if (url) { detailsText = Bindings.displayNameForURL(url) + ':' + (eventData['lineNumber'] + 1); + } break; } case recordType.WasmCompiledModule: case recordType.WasmModuleCacheHit: { const url = event.args['url']; - if (url) + if (url) { detailsText = Bindings.displayNameForURL(url); + } break; } @@ -512,8 +533,9 @@ case recordType.XHRReadyStateChange: case recordType.XHRLoad: { const url = eventData['url']; - if (url) + if (url) { detailsText = Bindings.displayNameForURL(url); + } break; } case recordType.TimeStamp: @@ -534,8 +556,9 @@ case recordType.ResizeImage: case recordType.DecodeLazyPixelRef: { const url = TimelineModel.TimelineData.forEvent(event).url; - if (url) + if (url) { detailsText = Bindings.displayNameForURL(url); + } break; } @@ -552,10 +575,11 @@ break; default: - if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) + if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) { detailsText = null; - else + } else { detailsText = linkifyTopCallFrameAsText(); + } break; } @@ -569,11 +593,13 @@ */ function linkifyLocationAsText(scriptId, lineNumber, columnNumber) { const debuggerModel = target ? target.model(SDK.DebuggerModel) : null; - if (!target || target.isDisposed() || !scriptId || !debuggerModel) + if (!target || target.isDisposed() || !scriptId || !debuggerModel) { return null; + } const rawLocation = debuggerModel.createRawLocationByScriptId(scriptId, lineNumber, columnNumber); - if (!rawLocation) + if (!rawLocation) { return null; + } const uiLocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation); return uiLocation ? uiLocation.linkText() : null; } @@ -583,13 +609,15 @@ */ function linkifyTopCallFrameAsText() { const frame = TimelineModel.TimelineData.forEvent(event).topFrame(); - if (!frame) + if (!frame) { return null; + } let text = linkifyLocationAsText(frame.scriptId, frame.lineNumber, frame.columnNumber); if (!text) { text = frame.url; - if (typeof frame.lineNumber === 'number') + if (typeof frame.lineNumber === 'number') { text += ':' + (frame.lineNumber + 1); + } } return text; } @@ -638,8 +666,9 @@ case recordType.ResourceReceiveResponse: case recordType.ResourceFinish: { const url = TimelineModel.TimelineData.forEvent(event).url; - if (url) + if (url) { details = Components.Linkifier.linkifyURL(url); + } break; } case recordType.FunctionCall: @@ -659,26 +688,30 @@ case recordType.CompileScript: case recordType.EvaluateScript: { const url = eventData['url']; - if (url) + if (url) { details = linkifyLocation('', url, eventData['lineNumber'], 0); + } break; } case recordType.ParseScriptOnBackground: { const url = eventData['url']; - if (url) + if (url) { details = linkifyLocation('', url, 0, 0); + } break; } default: - if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) + if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) { detailsText = null; - else + } else { details = linkifyTopCallFrame(); + } break; } - if (!details && detailsText) + if (!details && detailsText) { details = createTextNode(detailsText); + } return details; /** @@ -760,15 +793,18 @@ /** @type {!Set<number>} */ const nodeIdsToResolve = new Set(); const timelineData = TimelineModel.TimelineData.forEvent(event); - if (timelineData.backendNodeId) + if (timelineData.backendNodeId) { nodeIdsToResolve.add(timelineData.backendNodeId); + } const invalidationTrackingEvents = TimelineModel.InvalidationTracker.invalidationEventsFor(event); - if (invalidationTrackingEvents) + if (invalidationTrackingEvents) { Timeline.TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve, invalidationTrackingEvents); + } if (nodeIdsToResolve.size) { const domModel = target.model(SDK.DOMModel); - if (domModel) + if (domModel) { relatedNodesMap = await domModel.pushNodesByBackendIdsToFrontend(nodeIdsToResolve); + } } } @@ -786,10 +822,12 @@ const initiator = timelineData.initiator(); let url = null; - if (timelineData.warning) + if (timelineData.warning) { contentHelper.appendWarningRow(event); - if (event.name === recordTypes.JSFrame && eventData['deoptReason']) + } + if (event.name === recordTypes.JSFrame && eventData['deoptReason']) { contentHelper.appendWarningRow(event, TimelineModel.TimelineModel.WarningType.V8Deopt); + } if (detailed && !Number.isNaN(event.duration + 0)) { contentHelper.appendTextRow(ls`Total Time`, Number.millisToString(event.duration, true)); @@ -818,8 +856,9 @@ case recordTypes.FunctionCall: const detailsNode = Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event, model.targetByEvent(event), linkifier); - if (detailsNode) + if (detailsNode) { contentHelper.appendElementRow(ls`Function`, detailsNode); + } break; case recordTypes.TimerFire: case recordTypes.TimerInstall: @@ -839,34 +878,42 @@ case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: url = timelineData.url; - if (url) + if (url) { contentHelper.appendElementRow(ls`Resource`, Components.Linkifier.linkifyURL(url)); - if (eventData['requestMethod']) + } + if (eventData['requestMethod']) { contentHelper.appendTextRow(ls`Request Method`, eventData['requestMethod']); - if (typeof eventData['statusCode'] === 'number') + } + if (typeof eventData['statusCode'] === 'number') { contentHelper.appendTextRow(ls`Status Code`, eventData['statusCode']); - if (eventData['mimeType']) + } + if (eventData['mimeType']) { contentHelper.appendTextRow(ls`MIME Type`, eventData['mimeType']); + } if ('priority' in eventData) { const priority = PerfUI.uiLabelForNetworkPriority(eventData['priority']); contentHelper.appendTextRow(ls`Priority`, priority); } - if (eventData['encodedDataLength']) + if (eventData['encodedDataLength']) { contentHelper.appendTextRow(ls`Encoded Data`, ls`${eventData['encodedDataLength']} Bytes`); - if (eventData['decodedBodyLength']) + } + if (eventData['decodedBodyLength']) { contentHelper.appendTextRow(ls`Decoded Body`, ls`${eventData['decodedBodyLength']} Bytes`); + } break; case recordTypes.CompileModule: contentHelper.appendLocationRow(ls`Module`, event.args['fileName'], 0); break; case recordTypes.CompileScript: url = eventData && eventData['url']; - if (url) + if (url) { contentHelper.appendLocationRow(ls`Script`, url, eventData['lineNumber'], eventData['columnNumber']); + } contentHelper.appendTextRow(ls`Streamed`, eventData['streamed']); const producedCacheSize = eventData && eventData['producedCacheSize']; - if (producedCacheSize) + if (producedCacheSize) { contentHelper.appendTextRow(ls`Produced Cache Size`, producedCacheSize); + } const cacheConsumeOptions = eventData && eventData['cacheConsumeOptions']; if (cacheConsumeOptions) { contentHelper.appendTextRow(ls`Cache Consume Options`, cacheConsumeOptions); @@ -876,8 +923,9 @@ break; case recordTypes.EvaluateScript: url = eventData && eventData['url']; - if (url) + if (url) { contentHelper.appendLocationRow(ls`Script`, url, eventData['lineNumber'], eventData['columnNumber']); + } break; case recordTypes.WasmStreamFromResponseCallback: case recordTypes.WasmCompiledModule: @@ -886,14 +934,17 @@ case recordTypes.WasmModuleCacheInvalid: if (eventData) { url = event.args['url']; - if (url) + if (url) { contentHelper.appendTextRow(ls`Url`, url); + } const producedCachedSize = event.args['producedCachedSize']; - if (producedCachedSize) + if (producedCachedSize) { contentHelper.appendTextRow(ls`Produced Cache Size`, producedCachedSize); + } const consumedCachedSize = event.args['consumedCachedSize']; - if (consumedCachedSize) + if (consumedCachedSize) { contentHelper.appendTextRow(ls`Consumed Cache Size`, consumedCachedSize); + } } break; case recordTypes.Paint: @@ -916,13 +967,15 @@ case recordTypes.DrawLazyPixelRef: relatedNodeLabel = ls`Owner Element`; url = timelineData.url; - if (url) + if (url) { contentHelper.appendElementRow(ls`Image URL`, Components.Linkifier.linkifyURL(url)); + } break; case recordTypes.ParseAuthorStyleSheet: url = eventData['styleSheetUrl']; - if (url) + if (url) { contentHelper.appendElementRow(ls`Stylesheet URL`, Components.Linkifier.linkifyURL(url)); + } break; case recordTypes.UpdateLayoutTree: // We don't want to see default details. case recordTypes.RecalculateStyles: @@ -942,27 +995,32 @@ case recordTypes.WebSocketReceiveHandshakeResponse: case recordTypes.WebSocketDestroy: const initiatorData = initiator ? initiator.args['data'] : eventData; - if (typeof initiatorData['webSocketURL'] !== 'undefined') + if (typeof initiatorData['webSocketURL'] !== 'undefined') { contentHelper.appendTextRow(ls`URL`, initiatorData['webSocketURL']); - if (typeof initiatorData['webSocketProtocol'] !== 'undefined') + } + if (typeof initiatorData['webSocketProtocol'] !== 'undefined') { contentHelper.appendTextRow(ls`WebSocket Protocol`, initiatorData['webSocketProtocol']); - if (typeof eventData['message'] !== 'undefined') + } + if (typeof eventData['message'] !== 'undefined') { contentHelper.appendTextRow(ls`Message`, eventData['message']); + } break; case recordTypes.EmbedderCallback: contentHelper.appendTextRow(ls`Callback Function`, eventData['callbackName']); break; case recordTypes.Animation: - if (event.phase === SDK.TracingModel.Phase.NestableAsyncInstant) + if (event.phase === SDK.TracingModel.Phase.NestableAsyncInstant) { contentHelper.appendTextRow(ls`State`, eventData['state']); + } break; case recordTypes.ParseHTML: { const beginData = event.args['beginData']; const startLine = beginData['startLine'] - 1; const endLine = event.args['endData'] ? event.args['endData']['endLine'] - 1 : undefined; url = beginData['url']; - if (url) + if (url) { contentHelper.appendLocationRange(ls`Range`, url, startLine, endLine); + } break; } @@ -997,8 +1055,9 @@ default: { const detailsNode = Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event, model.targetByEvent(event), linkifier); - if (detailsNode) + if (detailsNode) { contentHelper.appendElementRow(ls`Details`, detailsNode); + } break; } } @@ -1023,8 +1082,9 @@ } if (initiator || timelineData.stackTraceForSelfOrInitiator() || - TimelineModel.InvalidationTracker.invalidationEventsFor(event)) + TimelineModel.InvalidationTracker.invalidationEventsFor(event)) { Timeline.TimelineUIUtils._generateCauses(event, model.targetByEvent(event), relatedNodesMap, contentHelper); + } const stats = {}; const showPieChart = detailed && Timeline.TimelineUIUtils._aggregatedStatsForTraceEvent(stats, model, event); @@ -1045,8 +1105,9 @@ */ static _maybeAppendProductToDetails(contentHelper, badgePool, url) { const parsedURL = url ? url.asParsedURL() : null; - if (parsedURL) + if (parsedURL) { contentHelper.appendElementRow('', badgePool.badgeForURL(parsedURL)); + } } /** @@ -1056,8 +1117,9 @@ * @return {!Object<string, number>} */ static statsForTimeRange(events, startTime, endTime) { - if (!events.length) + if (!events.length) { return {'idle': endTime - startTime}; + } buildRangeStatsCacheIfNeeded(events); const aggregatedStats = subtractStats(aggregatedStatsAtTime(endTime), aggregatedStatsAtTime(startTime)); @@ -1099,8 +1161,9 @@ */ function subtractStats(a, b) { const result = Object.assign({}, a); - for (const key in b) + for (const key in b) { result[key] -= b[key]; + } return result; } @@ -1108,8 +1171,9 @@ * @param {!Array<!SDK.TracingModel.Event>} events */ function buildRangeStatsCacheIfNeeded(events) { - if (events[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol]) + if (events[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol]) { return; + } // aggeregatedStats is a map by categories. For each category there's an array // containing sorted time points which records accumulated value of the category. @@ -1137,8 +1201,9 @@ statsArrays = {time: [], value: []}; aggregatedStats[category] = statsArrays; } - if (statsArrays.time.length && statsArrays.time.peekLast() === time) + if (statsArrays.time.length && statsArrays.time.peekLast() === time) { return; + } const lastValue = statsArrays.value.length ? statsArrays.value.peekLast() : 0; statsArrays.value.push(lastValue + time - lastTime); statsArrays.time.push(time); @@ -1150,11 +1215,13 @@ * @param {number} time */ function categoryChange(from, to, time) { - if (from) + if (from) { updateCategory(from, time); + } lastTime = time; - if (to) + if (to) { updateCategory(to, time); + } } /** @@ -1163,8 +1230,9 @@ function onStartEvent(e) { const category = Timeline.TimelineUIUtils.eventStyle(e).category.name; const parentCategory = categoryStack.length ? categoryStack.peekLast() : null; - if (category !== parentCategory) + if (category !== parentCategory) { categoryChange(parentCategory, category, e.startTime); + } categoryStack.push(category); } @@ -1174,8 +1242,9 @@ function onEndEvent(e) { const category = categoryStack.pop(); const parentCategory = categoryStack.length ? categoryStack.peekLast() : null; - if (category !== parentCategory) + if (category !== parentCategory) { categoryChange(category, parentCategory, e.endTime); + } } const obj = /** @type {!Object} */ (events); @@ -1197,8 +1266,9 @@ const color = Timeline.TimelineUIUtils.networkCategoryColor(category); contentHelper.addSection(ls`Network request`, color); - if (request.url) + if (request.url) { contentHelper.appendElementRow(ls`URL`, Components.Linkifier.linkifyURL(request.url)); + } Timeline.TimelineUIUtils._maybeAppendProductToDetails(contentHelper, badgePool, request.url); // The time from queueing the request until resource processing is finished. @@ -1219,44 +1289,52 @@ contentHelper.appendTextRow(ls`Duration`, textRow); } - if (request.requestMethod) + if (request.requestMethod) { contentHelper.appendTextRow(ls`Request Method`, request.requestMethod); + } if (typeof request.priority === 'string') { const priority = PerfUI.uiLabelForNetworkPriority(/** @type {!Protocol.Network.ResourcePriority} */ (request.priority)); contentHelper.appendTextRow(ls`Priority`, priority); } - if (request.mimeType) + if (request.mimeType) { contentHelper.appendTextRow(ls`Mime Type`, request.mimeType); + } let lengthText = ''; - if (request.memoryCached()) + if (request.memoryCached()) { lengthText += ls` (from memory cache)`; - else if (request.cached()) + } else if (request.cached()) { lengthText += ls` (from cache)`; - else if (request.timing && request.timing.pushStart) + } else if (request.timing && request.timing.pushStart) { lengthText += ls` (from push)`; - if (request.fromServiceWorker) + } + if (request.fromServiceWorker) { lengthText += ls` (from service worker)`; - if (request.encodedDataLength || !lengthText) + } + if (request.encodedDataLength || !lengthText) { lengthText = `${Number.bytesToString(request.encodedDataLength)}${lengthText}`; + } contentHelper.appendTextRow(ls`Encoded Data`, lengthText); - if (request.decodedBodyLength) + if (request.decodedBodyLength) { contentHelper.appendTextRow(ls`Decoded Body`, Number.bytesToString(request.decodedBodyLength)); + } const title = ls`Initiator`; const sendRequest = request.children[0]; const topFrame = TimelineModel.TimelineData.forEvent(sendRequest).topFrame(); if (topFrame) { const link = linkifier.maybeLinkifyConsoleCallFrame(target, topFrame); - if (link) + if (link) { contentHelper.appendElementRow(title, link); + } } else { const initiator = TimelineModel.TimelineData.forEvent(sendRequest).initiator(); if (initiator) { const initiatorURL = TimelineModel.TimelineData.forEvent(initiator).url; if (initiatorURL) { const link = linkifier.maybeLinkifyScriptLocation(target, null, initiatorURL, 0); - if (link) + if (link) { contentHelper.appendElementRow(title, link); + } } } } @@ -1265,8 +1343,9 @@ request.previewElement = await Components.ImagePreview.build( target, request.url, false, {imageAltText: Components.ImagePreview.defaultAltTextForImageURL(request.url)}); } - if (request.previewElement) + if (request.previewElement) { contentHelper.appendElementRow(ls`Preview`, request.previewElement); + } return contentHelper.fragment; } @@ -1355,10 +1434,11 @@ const invalidationTrackingEvents = TimelineModel.InvalidationTracker.invalidationEventsFor(event); const invalidations = {}; invalidationTrackingEvents.forEach(function(invalidation) { - if (!invalidations[invalidation.type]) + if (!invalidations[invalidation.type]) { invalidations[invalidation.type] = [invalidation]; - else + } else { invalidations[invalidation.type].push(invalidation); + } }); Object.keys(invalidations).forEach(function(type) { @@ -1410,8 +1490,9 @@ for (let index = 0; index < invalidations.length; index++) { const invalidation = invalidations[index]; let causeKey = ''; - if (invalidation.cause.reason) + if (invalidation.cause.reason) { causeKey += invalidation.cause.reason + '.'; + } if (invalidation.cause.stackTrace) { invalidation.cause.stackTrace.forEach(function(stackFrame) { causeKey += stackFrame['functionName'] + '.'; @@ -1422,10 +1503,11 @@ }); } - if (causeToInvalidationMap.has(causeKey)) + if (causeToInvalidationMap.has(causeKey)) { causeToInvalidationMap.get(causeKey).push(invalidation); - else + } else { causeToInvalidationMap.set(causeKey, [invalidation]); + } } return causeToInvalidationMap.valuesArray(); } @@ -1457,21 +1539,26 @@ } const index = events.binaryIndexOf(event.startTime, eventComparator); // Not a main thread event? - if (index < 0) + if (index < 0) { return false; + } let hasChildren = false; const endTime = event.endTime; if (endTime) { for (let i = index; i < events.length; i++) { const nextEvent = events[i]; - if (nextEvent.startTime >= endTime) + if (nextEvent.startTime >= endTime) { break; - if (!nextEvent.selfTime) + } + if (!nextEvent.selfTime) { continue; - if (nextEvent.thread !== event.thread) + } + if (nextEvent.thread !== event.thread) { continue; - if (i > index) + } + if (i > index) { hasChildren = true; + } const categoryName = Timeline.TimelineUIUtils.eventStyle(nextEvent).category.name; total[categoryName] = (total[categoryName] || 0) + nextEvent.selfTime; } @@ -1479,8 +1566,9 @@ if (SDK.TracingModel.isAsyncPhase(event.phase)) { if (event.endTime) { let aggregatedTotal = 0; - for (const categoryName in total) + for (const categoryName in total) { aggregatedTotal += total[categoryName]; + } total['idle'] = Math.max(0, event.endTime - event.startTime - aggregatedTotal); } return false; @@ -1495,13 +1583,15 @@ */ static async buildPicturePreviewContent(event, target) { const snapshotWithRect = await new TimelineModel.LayerPaintEvent(event, target).snapshotPromise(); - if (!snapshotWithRect) + if (!snapshotWithRect) { return null; + } const imageURLPromise = snapshotWithRect.snapshot.replay(); snapshotWithRect.snapshot.release(); const imageURL = await imageURLPromise; - if (!imageURL) + if (!imageURL) { return null; + } const container = createElement('div'); UI.appendStyle(container, 'components/imagePreview.css'); container.classList.add('image-preview-container', 'vbox', 'link'); @@ -1526,8 +1616,9 @@ const startTime = Number.millisToString(event.startTime - zeroTime); eventDivider.title = Common.UIString('%s at %s', Timeline.TimelineUIUtils.eventTitle(event), startTime); const style = Timeline.TimelineUIUtils.markerStyleForEvent(event); - if (style.tall) + if (style.tall) { eventDivider.style.backgroundColor = style.color; + } return eventDivider; } @@ -1538,8 +1629,9 @@ const eventStyles = Timeline.TimelineUIUtils._initEventStyles(); const result = []; for (const name in eventStyles) { - if (!eventStyles[name].hidden) + if (!eventStyles[name].hidden) { result.push(name); + } } return result; } @@ -1555,8 +1647,9 @@ * @return {!Object.<string, !Timeline.TimelineCategory>} */ static categories() { - if (Timeline.TimelineUIUtils._categories) + if (Timeline.TimelineUIUtils._categories) { return Timeline.TimelineUIUtils._categories; + } Timeline.TimelineUIUtils._categories = { loading: new Timeline.TimelineCategory('loading', ls`Loading`, true, 'hsl(214, 67%, 74%)', 'hsl(214, 67%, 66%)'), scripting: @@ -1581,8 +1674,9 @@ */ static generatePieChart(aggregatedStats, selfCategory, selfTime) { let total = 0; - for (const categoryName in aggregatedStats) + for (const categoryName in aggregatedStats) { total += aggregatedStats[categoryName]; + } const element = createElementWithClass('div', 'timeline-details-view-pie-chart-wrapper hbox'); const pieChart = new PerfUI.PieChart({ @@ -1603,8 +1697,9 @@ * @param {string} color */ function appendLegendRow(name, title, value, color) { - if (!value) + if (!value) { return; + } pieChart.addSlice(value, color, title); } @@ -1626,8 +1721,9 @@ // Add other categories. for (const categoryName in Timeline.TimelineUIUtils.categories()) { const category = Timeline.TimelineUIUtils.categories()[categoryName]; - if (category === selfCategory) + if (category === selfCategory) { continue; + } appendLegendRow(category.name, category.title, aggregatedStats[category.name], category.childColor); } return element; @@ -1656,8 +1752,9 @@ filmStripPreview.addEventListener('click', frameClicked.bind(null, filmStripFrame), false); } - if (frame.layerTree) + if (frame.layerTree) { contentHelper.appendElementRow(ls`Layer tree`, Components.Linkifier.linkifyRevealable(frame.layerTree, ls`Show`)); + } /** * @param {!SDK.FilmStripModel.Frame} filmStripFrame @@ -1677,8 +1774,9 @@ const durationText = Common.UIString( '%s (at %s)', Number.millisToString(frame.endTime - frame.startTime, true), Number.millisToString(frame.startTimeOffset, true)); - if (!frame.hasWarnings()) + if (!frame.hasWarnings()) { return UI.formatLocalized('%s', [durationText]); + } const link = UI.XLink.create('https://developers.google.com/web/fundamentals/performance/rendering/', ls`jank`); return UI.formatLocalized('%s. Long frame times are an indication of %s', [durationText, link]); @@ -1722,8 +1820,9 @@ * @return {!Array.<!Timeline.TimelineUIUtils.EventDispatchTypeDescriptor>} */ static eventDispatchDesciptors() { - if (Timeline.TimelineUIUtils._eventDispatchDesciptors) + if (Timeline.TimelineUIUtils._eventDispatchDesciptors) { return Timeline.TimelineUIUtils._eventDispatchDesciptors; + } const lightOrange = 'hsl(40,100%,80%)'; const orange = 'hsl(40,100%,50%)'; const green = 'hsl(90,100%,40%)'; @@ -1867,8 +1966,9 @@ static eventWarning(event, warningType) { const timelineData = TimelineModel.TimelineData.forEvent(event); const warning = warningType || timelineData.warning; - if (!warning) + if (!warning) { return null; + } const warnings = TimelineModel.TimelineModel.WarningType; const span = createElement('span'); const eventData = event.args['data']; @@ -1914,8 +2014,9 @@ */ static displayNameForFrame(frame, trimAt) { const url = frame.url; - if (!trimAt) + if (!trimAt) { trimAt = 30; + } return url.startsWith('about:') ? `"${frame.name.trimMiddle(trimAt)}"` : frame.url.trimEnd(trimAt); } }; @@ -1985,8 +2086,9 @@ const topFrame = first.cause.stackTrace && first.cause.stackTrace[0]; const truncatedNodesElement = this._getTruncatedNodesElement(this._invalidations); - if (truncatedNodesElement === null) + if (truncatedNodesElement === null) { return UI.formatLocalized(reason, []); + } const title = UI.formatLocalized('%s for %s', [reason, truncatedNodesElement]); @@ -2027,8 +2129,9 @@ const invalidation = this._invalidations[i]; const invalidationNode = this._createInvalidationNode(invalidation, true); if (invalidationNode) { - if (!firstNode) + if (!firstNode) { nodeList.createTextChild(ls`, `); + } firstNode = false; nodeList.appendChild(invalidationNode); @@ -2214,8 +2317,9 @@ text.createTextChild(String(content)); const cell = createElement('td'); cell.className = 'timeline-details'; - if (styleName) + if (styleName) { cell.className += ' ' + styleName; + } cell.textContent = content; return cell; } @@ -2241,10 +2345,11 @@ row.appendChild(titleCell); const cell = createElement('td'); cell.className = 'details'; - if (content instanceof Node) + if (content instanceof Node) { cell.appendChild(content); - else + } else { cell.createTextChild(content || ''); + } row.appendChild(cell); this._contentTable.appendChild(row); } @@ -2283,8 +2388,9 @@ if (title) { const titleElement = this.element.createChild('div', 'timeline-details-chip-title'); - if (swatchColor) + if (swatchColor) { titleElement.createChild('div').style.backgroundColor = swatchColor; + } titleElement.createTextChild(title); } @@ -2317,17 +2423,20 @@ */ appendElementRow(title, content, isWarning, isStacked) { const rowElement = this._tableElement.createChild('div', 'timeline-details-view-row'); - if (isWarning) + if (isWarning) { rowElement.classList.add('timeline-details-warning'); - if (isStacked) + } + if (isStacked) { rowElement.classList.add('timeline-details-stack-values'); + } const titleElement = rowElement.createChild('div', 'timeline-details-view-row-title'); titleElement.textContent = title; const valueElement = rowElement.createChild('div', 'timeline-details-view-row-value'); - if (content instanceof Node) + if (content instanceof Node) { valueElement.appendChild(content); - else + } else { valueElement.createTextChild(content || ''); + } } /** @@ -2337,11 +2446,13 @@ * @param {number=} startColumn */ appendLocationRow(title, url, startLine, startColumn) { - if (!this._linkifier || !this._target) + if (!this._linkifier || !this._target) { return; + } const link = this._linkifier.maybeLinkifyScriptLocation(this._target, null, url, startLine, startColumn); - if (!link) + if (!link) { return; + } this.appendElementRow(title, link); } @@ -2352,12 +2463,14 @@ * @param {number=} endLine */ appendLocationRange(title, url, startLine, endLine) { - if (!this._linkifier || !this._target) + if (!this._linkifier || !this._target) { return; + } const locationContent = createElement('span'); const link = this._linkifier.maybeLinkifyScriptLocation(this._target, null, url, startLine); - if (!link) + if (!link) { return; + } locationContent.appendChild(link); locationContent.createTextChild(String.sprintf(' [%s\u2026%s]', startLine + 1, endLine + 1 || '')); this.appendElementRow(title, locationContent); @@ -2368,8 +2481,9 @@ * @param {!Protocol.Runtime.StackTrace} stackTrace */ appendStackTrace(title, stackTrace) { - if (!this._linkifier || !this._target) + if (!this._linkifier || !this._target) { return; + } const rowElement = this._tableElement.createChild('div', 'timeline-details-view-row'); rowElement.createChild('div', 'timeline-details-view-row-title').textContent = title; @@ -2381,8 +2495,9 @@ * @param {!Protocol.Runtime.StackTrace} stackTrace */ createChildStackTraceElement(parentElement, stackTrace) { - if (!this._linkifier || !this._target) + if (!this._linkifier || !this._target) { return; + } parentElement.classList.add('timeline-details-stack-values'); const stackTraceElement = parentElement.createChild('div', 'timeline-details-view-row-value timeline-details-view-row-stack-trace'); @@ -2397,8 +2512,9 @@ */ appendWarningRow(event, warningType) { const warning = Timeline.TimelineUIUtils.eventWarning(event, warningType); - if (warning) + if (warning) { this.appendElementRow(ls`Warning`, warning, true); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineFrameModel.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineFrameModel.js index 5ccc2b0..6f245b4 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineFrameModel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineFrameModel.js
@@ -46,8 +46,9 @@ * @return {!Array<!TimelineModel.TimelineFrame>} */ frames(startTime, endTime) { - if (!startTime && !endTime) + if (!startTime && !endTime) { return this._frames; + } const firstFrame = this._frames.lowerBound(startTime || 0, (time, frame) => time - frame.endTime); const lastFrame = this._frames.lowerBound(endTime || Infinity, (time, frame) => time - frame.startTime); return this._frames.slice(firstFrame, lastFrame); @@ -59,12 +60,14 @@ */ hasRasterTile(rasterTask) { const data = rasterTask.args['tileData']; - if (!data) + if (!data) { return false; + } const frameId = data['sourceFrameNumber']; const frame = frameId && this._frameById[frameId]; - if (!frame || !frame.layerTree) + if (!frame || !frame.layerTree) { return false; + } return true; } @@ -73,14 +76,16 @@ * @return Promise<?{rect: !Protocol.DOM.Rect, snapshot: !SDK.PaintProfilerSnapshot}>} */ rasterTilePromise(rasterTask) { - if (!this._target) + if (!this._target) { return Promise.resolve(null); + } const data = rasterTask.args['tileData']; const frameId = data['sourceFrameNumber']; const tileId = data['tileId'] && data['tileId']['id_ref']; const frame = frameId && this._frameById[frameId]; - if (!frame || !frame.layerTree || !tileId) + if (!frame || !frame.layerTree || !tileId) { return Promise.resolve(null); + } return frame.layerTree.layerTreePromise().then(layerTree => layerTree && layerTree.pictureForRasterTile(tileId)); } @@ -107,8 +112,9 @@ * @param {number} startTime */ handleBeginFrame(startTime) { - if (!this._lastFrame) + if (!this._lastFrame) { this._startFrame(startTime); + } this._lastBeginFrame = startTime; } @@ -130,8 +136,9 @@ if (idleTimeEnd > this._lastFrame.startTime) { this._lastFrame.idle = true; this._startFrame(idleTimeEnd); - if (this._framePendingActivation) + if (this._framePendingActivation) { this._commitPendingFrame(); + } this._lastBeginFrame = null; } this._lastNeedsBeginFrame = null; @@ -142,21 +149,25 @@ } handleActivateLayerTree() { - if (!this._lastFrame) + if (!this._lastFrame) { return; - if (this._framePendingActivation && !this._lastNeedsBeginFrame) + } + if (this._framePendingActivation && !this._lastNeedsBeginFrame) { this._commitPendingFrame(); + } } handleRequestMainThreadFrame() { - if (!this._lastFrame) + if (!this._lastFrame) { return; + } this._mainFrameRequested = true; } handleCompositeLayers() { - if (!this._framePendingCommit) + if (!this._framePendingCommit) { return; + } this._framePendingActivation = this._framePendingCommit; this._framePendingCommit = null; this._mainFrameRequested = false; @@ -175,16 +186,18 @@ * @param {boolean} needsBeginFrame */ handleNeedFrameChanged(startTime, needsBeginFrame) { - if (needsBeginFrame) + if (needsBeginFrame) { this._lastNeedsBeginFrame = startTime; + } } /** * @param {number} startTime */ _startFrame(startTime) { - if (this._lastFrame) + if (this._lastFrame) { this._flushFrame(this._lastFrame, startTime); + } this._lastFrame = new TimelineModel.TimelineFrame(startTime, startTime - this._minimumRecordTime); } @@ -195,16 +208,18 @@ _flushFrame(frame, endTime) { frame._setLayerTree(this._lastLayerTree); frame._setEndTime(endTime); - if (this._lastLayerTree) + if (this._lastLayerTree) { this._lastLayerTree._setPaints(frame._paints); + } if (this._frames.length && (frame.startTime !== this._frames.peekLast().endTime || frame.startTime > frame.endTime)) { console.assert( false, `Inconsistent frame time for frame ${this._frames.length} (${frame.startTime} - ${frame.endTime})`); } this._frames.push(frame); - if (typeof frame._mainFrameId === 'number') + if (typeof frame._mainFrameId === 'number') { this._frameById[frame._mainFrameId] = frame; + } } _commitPendingFrame() { @@ -224,8 +239,9 @@ let j = 0; this._currentProcessMainThread = threadData.length && threadData[0].thread || null; for (let i = 0; i < events.length; ++i) { - while (j + 1 < threadData.length && threadData[j + 1].time <= events[i].startTime) + while (j + 1 < threadData.length && threadData[j + 1].time <= events[i].startTime) { this._currentProcessMainThread = threadData[++j].thread; + } this._addTraceEvent(events[i]); } this._currentProcessMainThread = null; @@ -236,8 +252,9 @@ */ _addTraceEvent(event) { const eventNames = TimelineModel.TimelineModel.RecordType; - if (event.startTime && event.startTime < this._minimumRecordTime) + if (event.startTime && event.startTime < this._minimumRecordTime) { this._minimumRecordTime = event.startTime; + } if (event.name === eventNames.SetLayerTreeId) { this._layerTreeId = event.args['layerTreeId'] || event.args['data']['layerTreeId']; @@ -248,10 +265,11 @@ this.handleLayerTreeSnapshot(new TimelineModel.TracingFrameLayerTree(this._target, snapshot)); } else { this._processCompositorEvents(event); - if (event.thread === this._currentProcessMainThread) + if (event.thread === this._currentProcessMainThread) { this._addMainThreadTraceEvent(event); - else if (this._lastFrame && event.selfTime && !SDK.TracingModel.isTopLevelEvent(event)) + } else if (this._lastFrame && event.selfTime && !SDK.TracingModel.isTopLevelEvent(event)) { this._lastFrame._addTimeForCategory(this._categoryMapper(event), event.selfTime); + } } } @@ -261,20 +279,22 @@ _processCompositorEvents(event) { const eventNames = TimelineModel.TimelineModel.RecordType; - if (event.args['layerTreeId'] !== this._layerTreeId) + if (event.args['layerTreeId'] !== this._layerTreeId) { return; + } const timestamp = event.startTime; - if (event.name === eventNames.BeginFrame) + if (event.name === eventNames.BeginFrame) { this.handleBeginFrame(timestamp); - else if (event.name === eventNames.DrawFrame) + } else if (event.name === eventNames.DrawFrame) { this.handleDrawFrame(timestamp); - else if (event.name === eventNames.ActivateLayerTree) + } else if (event.name === eventNames.ActivateLayerTree) { this.handleActivateLayerTree(); - else if (event.name === eventNames.RequestMainThreadFrame) + } else if (event.name === eventNames.RequestMainThreadFrame) { this.handleRequestMainThreadFrame(); - else if (event.name === eventNames.NeedsBeginFrameChanged) + } else if (event.name === eventNames.NeedsBeginFrameChanged) { this.handleNeedFrameChanged(timestamp, event.args['data'] && event.args['data']['needsBeginFrame']); + } } /** @@ -297,13 +317,16 @@ } this._addTimeForCategory(this._framePendingCommit.timeByCategory, event); - if (event.name === eventNames.BeginMainThreadFrame && event.args['data'] && event.args['data']['frameId']) + if (event.name === eventNames.BeginMainThreadFrame && event.args['data'] && event.args['data']['frameId']) { this._framePendingCommit.mainFrameId = event.args['data']['frameId']; + } if (event.name === eventNames.Paint && event.args['data']['layerId'] && - TimelineModel.TimelineData.forEvent(event).picture && this._target) + TimelineModel.TimelineData.forEvent(event).picture && this._target) { this._framePendingCommit.paints.push(new TimelineModel.LayerPaintEvent(event, this._target)); - if (event.name === eventNames.CompositeLayers && event.args['layerTreeId'] === this._layerTreeId) + } + if (event.name === eventNames.CompositeLayers && event.args['layerTreeId'] === this._layerTreeId) { this.handleCompositeLayers(); + } } /** @@ -311,8 +334,9 @@ * @param {!SDK.TracingModel.Event} event */ _addTimeForCategory(timeByCategory, event) { - if (!event.selfTime) + if (!event.selfTime) { return; + } const categoryName = this._categoryMapper(event); timeByCategory[categoryName] = (timeByCategory[categoryName] || 0) + event.selfTime; } @@ -344,8 +368,9 @@ */ async layerTreePromise() { const result = await this._snapshot.objectPromise(); - if (!result) + if (!result) { return null; + } const viewport = result['device_viewport_size']; const tiles = result['active_tiles']; const rootLayer = result['active_tree']['root_layer']; @@ -423,8 +448,9 @@ * @param {!Object} timeByCategory */ _addTimeForCategories(timeByCategory) { - for (const category in timeByCategory) + for (const category in timeByCategory) { this._addTimeForCategory(category, timeByCategory[category]); + } } /** @@ -470,8 +496,9 @@ picturePromise() { const picture = TimelineModel.TimelineData.forEvent(this._event).picture; return picture.objectPromise().then(result => { - if (!result) + if (!result) { return null; + } const rect = result['params'] && result['params']['layer_rect']; const picture = result['skp64']; return rect && picture ? {rect: rect, serializedPicture: picture} : null; @@ -484,8 +511,9 @@ snapshotPromise() { const paintProfilerModel = this._target && this._target.model(SDK.PaintProfilerModel); return this.picturePromise().then(picture => { - if (!picture || !paintProfilerModel) + if (!picture || !paintProfilerModel) { return null; + } return paintProfilerModel.loadSnapshot(picture.serializedPicture) .then(snapshot => snapshot ? {rect: picture.rect, snapshot: snapshot} : null); });
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineIRModel.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineIRModel.js index 8abb0ae5..7f6871e 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineIRModel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineIRModel.js
@@ -23,11 +23,13 @@ */ populate(inputLatencies, animations) { this.reset(); - if (!inputLatencies) + if (!inputLatencies) { return; + } this._processInputLatencies(inputLatencies); - if (animations) + if (animations) { this._processAnimations(animations); + } const range = new Common.SegmentedRange(); range.appendRange(this._drags); // Drags take lower precedence than animation, as we can't detect them reliably. range.appendRange(this._cssAnimations); @@ -54,8 +56,9 @@ for (let i = 0; i < events.length; ++i) { const event = events[i]; - if (i > 0 && events[i].startTime < events[i - 1].startTime) + if (i > 0 && events[i].startTime < events[i - 1].startTime) { console.assert(false, 'Unordered input events'); + } const type = this._inputEventType(event.name); switch (type) { case eventTypes.ScrollBegin: @@ -64,10 +67,11 @@ break; case eventTypes.ScrollEnd: - if (scrollStart) + if (scrollStart) { this._scrolls.append(this._segmentForEventRange(scrollStart, event, phases.Scroll)); - else + } else { this._scrolls.append(this._segmentForEvent(event, phases.Scroll)); + } scrollStart = null; break; @@ -87,8 +91,9 @@ case eventTypes.FlingCancel: // FIXME: also process renderer fling events. - if (!flingStart) + if (!flingStart) { break; + } this._scrolls.append(this._segmentForEventRange(flingStart, event, phases.Fling)); flingStart = null; break; @@ -160,10 +165,11 @@ case eventTypes.MouseWheel: // Do not consider first MouseWheel as trace viewer's implementation does -- in case of MouseWheel it's not really special. - if (mouseWheel && canMerge(thresholdsMs.mouse, mouseWheel, event)) + if (mouseWheel && canMerge(thresholdsMs.mouse, mouseWheel, event)) { this._scrolls.append(this._segmentForEventRange(mouseWheel, event, phases.Scroll)); - else + } else { this._scrolls.append(this._segmentForEvent(event, phases.Scroll)); + } mouseWheel = event; break; } @@ -184,8 +190,9 @@ * @param {!Array<!SDK.TracingModel.AsyncEvent>} events */ _processAnimations(events) { - for (let i = 0; i < events.length; ++i) + for (let i = 0; i < events.length; ++i) { this._cssAnimations.append(this._segmentForEvent(events[i], TimelineModel.TimelineIRModel.Phases.Animation)); + } } /** @@ -251,8 +258,9 @@ _inputEventType(eventName) { const prefix = 'InputLatency::'; if (!eventName.startsWith(prefix)) { - if (eventName === TimelineModel.TimelineIRModel.InputEvents.ImplSideFling) + if (eventName === TimelineModel.TimelineIRModel.InputEvents.ImplSideFling) { return /** @type {!TimelineModel.TimelineIRModel.InputEvents} */ (eventName); + } console.error('Unrecognized input latency event: ' + eventName); return null; }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineJSProfile.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineJSProfile.js index df66bb9..d2478f2 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineJSProfile.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineJSProfile.js
@@ -24,14 +24,16 @@ console.error(`Node with unknown id ${samples[i]} at index ${i}`); continue; } - if (node === gcNode || node === idleNode) + if (node === gcNode || node === idleNode) { continue; + } let callFrames = nodeToStackMap.get(node); if (!callFrames) { callFrames = /** @type {!Array<!Protocol.Runtime.CallFrame>} */ (new Array(node.depth + 1)); nodeToStackMap.set(node, callFrames); - for (let j = 0; node.parent; node = node.parent) + for (let j = 0; node.parent; node = node.parent) { callFrames[j++] = /** @type {!Protocol.Runtime.CallFrame} */ (node); + } } const jsSampleEvent = new SDK.TracingModel.Event( SDK.TracingModel.DevToolsTimelineEventCategory, TimelineModel.TimelineModel.RecordType.JSSample, @@ -99,8 +101,9 @@ */ function onInstantEvent(e, parent) { e.ordinal = ++ordinal; - if (parent && isJSInvocationEvent(parent)) + if (parent && isJSInvocationEvent(parent)) { extractStackTrace(e); + } } /** @@ -126,8 +129,9 @@ console.error(`Trying to truncate higher than the current stack size at ${time}`); depth = jsFramesStack.length; } - for (let k = 0; k < jsFramesStack.length; ++k) + for (let k = 0; k < jsFramesStack.length; ++k) { jsFramesStack[k].setEndTime(time); + } jsFramesStack.length = depth; } @@ -143,23 +147,27 @@ * @param {!Array<!Protocol.Runtime.CallFrame>} stack */ function filterStackFrames(stack) { - if (showAllEvents) + if (showAllEvents) { return; + } let previousNativeFrameName = null; let j = 0; for (let i = 0; i < stack.length; ++i) { const frame = stack[i]; const url = frame.url; const isNativeFrame = url && url.startsWith('native '); - if (!showNativeFunctions && isNativeFrame) + if (!showNativeFunctions && isNativeFrame) { continue; + } const isNativeRuntimeFrame = TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame); - if (isNativeRuntimeFrame && !showNativeName(frame.functionName)) + if (isNativeRuntimeFrame && !showNativeName(frame.functionName)) { continue; + } const nativeFrameName = isNativeRuntimeFrame ? TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName) : null; - if (previousNativeFrameName && previousNativeFrameName === nativeFrameName) + if (previousNativeFrameName && previousNativeFrameName === nativeFrameName) { continue; + } previousNativeFrameName = nativeFrameName; stack[j++] = frame; } @@ -181,8 +189,9 @@ for (i = lockedJsStackDepth.peekLast() || 0; i < minFrames; ++i) { const newFrame = callFrames[i]; const oldFrame = jsFramesStack[i].args['data']; - if (!equalFrames(newFrame, oldFrame)) + if (!equalFrames(newFrame, oldFrame)) { break; + } jsFramesStack[i].setEndTime(Math.max(jsFramesStack[i].endTime, endTime)); } truncateJSStack(i, e.startTime); @@ -218,10 +227,12 @@ * @return {?TimelineModel.TimelineJSProfileProcessor.NativeGroups} */ static nativeGroup(nativeName) { - if (nativeName.startsWith('Parse')) + if (nativeName.startsWith('Parse')) { return TimelineModel.TimelineJSProfileProcessor.NativeGroups.Parse; - if (nativeName.startsWith('Compile') || nativeName.startsWith('Recompile')) + } + if (nativeName.startsWith('Compile') || nativeName.startsWith('Recompile')) { return TimelineModel.TimelineJSProfileProcessor.NativeGroups.Compile; + } return null; } @@ -234,17 +245,21 @@ */ static buildTraceProfileFromCpuProfile(profile, tid, injectPageEvent, name) { const events = []; - if (injectPageEvent) + if (injectPageEvent) { appendEvent('TracingStartedInPage', {data: {'sessionId': '1'}}, 0, 0, 'M'); - if (!name) + } + if (!name) { name = ls`Thread ${tid}`; + } appendEvent(SDK.TracingModel.MetadataEvent.ThreadName, {name}, 0, 0, 'M', '__metadata'); - if (!profile) + if (!profile) { return events; + } const idToNode = new Map(); const nodes = profile['nodes']; - for (let i = 0; i < nodes.length; ++i) + for (let i = 0; i < nodes.length; ++i) { idToNode.set(nodes[i].id, nodes[i]); + } let programEvent = null; let functionEvent = null; let nextTime = profile.startTime; @@ -260,8 +275,9 @@ closeEvents(); continue; } - if (!programEvent) + if (!programEvent) { programEvent = appendEvent('MessageLoop::RunTask', {}, currentTime, 0, 'X', 'toplevel'); + } if (name === '(program)') { if (functionEvent) { functionEvent.dur = currentTime - functionEvent.ts; @@ -269,8 +285,9 @@ } } else { // A JS function. - if (!functionEvent) + if (!functionEvent) { functionEvent = appendEvent('FunctionCall', {data: {'sessionId': '1'}}, currentTime); + } } } closeEvents(); @@ -278,10 +295,12 @@ return events; function closeEvents() { - if (programEvent) + if (programEvent) { programEvent.dur = currentTime - programEvent.ts; - if (functionEvent) + } + if (functionEvent) { functionEvent.dur = currentTime - functionEvent.ts; + } programEvent = null; functionEvent = null; } @@ -298,8 +317,9 @@ function appendEvent(name, args, ts, dur, ph, cat) { const event = /** @type {!SDK.TracingManager.EventPayload} */ ( {cat: cat || 'disabled-by-default-devtools.timeline', name, ph: ph || 'X', pid: 1, tid, ts, args}); - if (dur) + if (dur) { event.dur = dur; + } events.push(event); return event; }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js index c2303ec..a1e481c 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModel.js
@@ -52,16 +52,21 @@ const startEvent = TimelineModel.TimelineModel._topLevelEventEndingAfter(events, startTime); for (let i = startEvent; i < events.length; ++i) { const e = events[i]; - if ((e.endTime || e.startTime) < startTime) + if ((e.endTime || e.startTime) < startTime) { continue; - if (e.startTime >= endTime) + } + if (e.startTime >= endTime) { break; - if (SDK.TracingModel.isAsyncPhase(e.phase) || SDK.TracingModel.isFlowPhase(e.phase)) + } + if (SDK.TracingModel.isAsyncPhase(e.phase) || SDK.TracingModel.isFlowPhase(e.phase)) { continue; - while (stack.length && stack.peekLast().endTime <= e.startTime) + } + while (stack.length && stack.peekLast().endTime <= e.startTime) { onEndEvent(stack.pop()); - if (filter && !filter(e)) + } + if (filter && !filter(e)) { continue; + } if (e.duration) { onStartEvent(e); stack.push(e); @@ -69,8 +74,9 @@ onInstantEvent && onInstantEvent(e, stack.peekLast() || null); } } - while (stack.length) + while (stack.length) { onEndEvent(stack.pop()); + } } /** @@ -79,8 +85,9 @@ */ static _topLevelEventEndingAfter(events, time) { let index = events.upperBound(time, (time, event) => time - event.startTime) - 1; - while (index > 0 && !SDK.TracingModel.isTopLevelEvent(events[index])) + while (index > 0 && !SDK.TracingModel.isTopLevelEvent(events[index])) { index--; + } return Math.max(index, 0); } @@ -134,8 +141,9 @@ static globalEventId(event, field) { const data = event.args['data'] || event.args['beginData']; const id = data && data[field]; - if (!id) + if (!id) { return ''; + } return `${event.thread.process().id()}.${id}`; } @@ -185,10 +193,11 @@ // TODO(alph): Drop the support at some point. const metadataEvents = this._processMetadataEvents(tracingModel); this._isGenericTrace = !metadataEvents; - if (metadataEvents) + if (metadataEvents) { this._processMetadataAndThreads(tracingModel, metadataEvents); - else + } else { this._processGenericTrace(tracingModel); + } } this._inspectedTargetEvents.sort(SDK.TracingModel.Event.compareStartTime); this._processAsyncBrowserEvents(tracingModel); @@ -201,8 +210,9 @@ */ _processGenericTrace(tracingModel) { let browserMainThread = SDK.TracingModel.browserMainThread(tracingModel); - if (!browserMainThread && tracingModel.sortedProcesses().length) + if (!browserMainThread && tracingModel.sortedProcesses().length) { browserMainThread = tracingModel.sortedProcesses()[0].sortedThreads()[0]; + } for (const process of tracingModel.sortedProcesses()) { for (const thread of process.sortedThreads()) { this._processThreadEvents( @@ -221,26 +231,31 @@ const metaEvent = metadataEvents.page[i]; const process = metaEvent.thread.process(); const endTime = i + 1 < length ? metadataEvents.page[i + 1].startTime : Infinity; - if (startTime === endTime) + if (startTime === endTime) { continue; + } this._legacyCurrentPage = metaEvent.args['data'] && metaEvent.args['data']['page']; for (const thread of process.sortedThreads()) { let workerUrl = null; if (thread.name() === TimelineModel.TimelineModel.WorkerThreadName || thread.name() === TimelineModel.TimelineModel.WorkerThreadNameLegacy) { const workerMetaEvent = metadataEvents.workers.find(e => { - if (e.args['data']['workerThreadId'] !== thread.id()) + if (e.args['data']['workerThreadId'] !== thread.id()) { return false; + } // This is to support old traces. - if (e.args['data']['sessionId'] === this._sessionId) + if (e.args['data']['sessionId'] === this._sessionId) { return true; + } return !!this._pageFrames.get(TimelineModel.TimelineModel.eventFrameId(e)); }); - if (!workerMetaEvent) + if (!workerMetaEvent) { continue; + } const workerId = workerMetaEvent.args['data']['workerId']; - if (workerId) + if (workerId) { this._workerIdByThread.set(thread, workerId); + } workerUrl = workerMetaEvent.args['data']['url'] || ''; } this._processThreadEvents( @@ -271,23 +286,27 @@ const allMetadataEvents = tracingModel.devToolsMetadataEvents(); for (const process of tracingModel.sortedProcesses()) { const data = processData.get(process.id()); - if (!data) + if (!data) { continue; + } data.sort((a, b) => a.from - b.from || a.to - b.to); const ranges = []; let lastUrl = null; let lastMainUrl = null; let hasMain = false; for (const item of data) { - if (!ranges.length || item.from > ranges.peekLast().to) + if (!ranges.length || item.from > ranges.peekLast().to) { ranges.push({from: item.from, to: item.to}); - else + } else { ranges.peekLast().to = item.to; - if (item.main) + } + if (item.main) { hasMain = true; + } if (item.url) { - if (item.main) + if (item.main) { lastMainUrl = item.url; + } lastUrl = item.url; } } @@ -301,16 +320,20 @@ thread.name() === TimelineModel.TimelineModel.WorkerThreadName || thread.name() === TimelineModel.TimelineModel.WorkerThreadNameLegacy) { const workerMetaEvent = allMetadataEvents.find(e => { - if (e.name !== TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingSessionIdForWorker) + if (e.name !== TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingSessionIdForWorker) { return false; - if (e.thread.process() !== process) + } + if (e.thread.process() !== process) { return false; - if (e.args['data']['workerThreadId'] !== thread.id()) + } + if (e.args['data']['workerThreadId'] !== thread.id()) { return false; + } return !!this._pageFrames.get(TimelineModel.TimelineModel.eventFrameId(e)); }); - if (!workerMetaEvent) + if (!workerMetaEvent) { continue; + } this._workerIdByThread.set(thread, workerMetaEvent.args['data']['workerId'] || ''); this._processThreadEvents( tracingModel, ranges, thread, false /* isMainThread */, true /* isWorker */, false /* forMainFrame */, @@ -336,8 +359,9 @@ for (const event of metadataEvents) { if (event.name === TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage) { pageDevToolsMetadataEvents.push(event); - if (event.args['data'] && event.args['data']['persistentIds']) + if (event.args['data'] && event.args['data']['persistentIds']) { this._persistentIds = true; + } const frames = ((event.args['data'] && event.args['data']['frames']) || []); frames.forEach(payload => this._addPageFrame(event, payload)); this._mainFrame = this.rootFrames()[0]; @@ -348,8 +372,9 @@ this._mainFrameNodeId = event.args['frameTreeNodeId']; } } - if (!pageDevToolsMetadataEvents.length) + if (!pageDevToolsMetadataEvents.length) { return null; + } const sessionId = pageDevToolsMetadataEvents[0].args['sessionId'] || pageDevToolsMetadataEvents[0].args['data']['sessionId']; @@ -363,11 +388,13 @@ function checkSessionId(event) { let args = event.args; // FIXME: put sessionId into args["data"] for TracingStartedInPage event. - if (args['data']) + if (args['data']) { args = args['data']; + } const id = args['sessionId']; - if (id === sessionId) + if (id === sessionId) { return true; + } mismatchingIds.add(id); return false; } @@ -388,8 +415,9 @@ */ _processSyncBrowserEvents(tracingModel) { const browserMain = SDK.TracingModel.browserMainThread(tracingModel); - if (browserMain) + if (browserMain) { browserMain.events().forEach(this._processBrowserEvent, this); + } } /** @@ -397,8 +425,9 @@ */ _processAsyncBrowserEvents(tracingModel) { const browserMain = SDK.TracingModel.browserMainThread(tracingModel); - if (browserMain) + if (browserMain) { this._processAsyncEvents(browserMain, [{from: 0, to: Infinity}]); + } } /** @@ -406,8 +435,9 @@ */ _buildGPUEvents(tracingModel) { const thread = tracingModel.threadByName('GPU Process', 'CrGpuMain'); - if (!thread) + if (!thread) { return; + } const gpuEventName = TimelineModel.TimelineModel.RecordType.GPUTask; const track = this._ensureNamedTrack(TimelineModel.TimelineModel.TrackType.GPU); track.thread = thread; @@ -451,8 +481,9 @@ if (!cpuProfile) { cpuProfileEvent = events.find(e => e.name === TimelineModel.TimelineModel.RecordType.Profile); - if (!cpuProfileEvent) + if (!cpuProfileEvent) { return null; + } target = this.targetByEvent(cpuProfileEvent); const profileGroup = tracingModel.profileGroup(cpuProfileEvent); if (!profileGroup) { @@ -469,10 +500,12 @@ }); for (const profileEvent of profileGroup.children) { const eventData = profileEvent.args['data']; - if ('startTime' in eventData) + if ('startTime' in eventData) { cpuProfile.startTime = eventData['startTime']; - if ('endTime' in eventData) + } + if ('endTime' in eventData) { cpuProfile.endTime = eventData['endTime']; + } const nodesAndSamples = eventData['cpuProfile'] || {}; const samples = nodesAndSamples['samples'] || []; const lines = eventData['lines'] || Array(samples.length).fill(0); @@ -485,8 +518,9 @@ return null; } } - if (!cpuProfile.endTime) + if (!cpuProfile.endTime) { cpuProfile.endTime = cpuProfile.timeDeltas.reduce((x, y) => x + y, cpuProfile.startTime); + } } try { @@ -510,12 +544,14 @@ const jsSamples = jsProfileModel ? TimelineModel.TimelineJSProfileProcessor.generateTracingEventsFromCpuProfile(jsProfileModel, thread) : null; - if (jsSamples && jsSamples.length) + if (jsSamples && jsSamples.length) { events = events.mergeOrdered(jsSamples, SDK.TracingModel.Event.orderedCompareStartTime); + } if (jsSamples || events.some(e => e.name === TimelineModel.TimelineModel.RecordType.JSSample)) { const jsFrameEvents = TimelineModel.TimelineJSProfileProcessor.generateJSFrameEvents(events); - if (jsFrameEvents && jsFrameEvents.length) + if (jsFrameEvents && jsFrameEvents.length) { events = jsFrameEvents.mergeOrdered(events, SDK.TracingModel.Event.orderedCompareStartTime); + } } return events; } @@ -554,26 +590,32 @@ let i = events.lowerBound(range.from, (time, event) => time - event.startTime); for (; i < events.length; i++) { const event = events[i]; - if (event.startTime >= range.to) + if (event.startTime >= range.to) { break; - while (eventStack.length && eventStack.peekLast().endTime <= event.startTime) + } + while (eventStack.length && eventStack.peekLast().endTime <= event.startTime) { eventStack.pop(); - if (!this._processEvent(event)) + } + if (!this._processEvent(event)) { continue; + } if (!SDK.TracingModel.isAsyncPhase(event.phase) && event.duration) { if (eventStack.length) { const parent = eventStack.peekLast(); parent.selfTime -= event.duration; - if (parent.selfTime < 0) + if (parent.selfTime < 0) { this._fixNegativeDuration(parent, event); + } } event.selfTime = event.duration; - if (!eventStack.length) + if (!eventStack.length) { track.tasks.push(event); + } eventStack.push(event); } - if (this.isMarkerEvent(event)) + if (this.isMarkerEvent(event)) { this._timeMarkerEvents.push(event); + } track.events.push(event); this._inspectedTargetEvents.push(event); @@ -609,8 +651,9 @@ * @return {!Array<!SDK.TracingModel.AsyncEvent>} */ function group(type) { - if (!groups.has(type)) + if (!groups.has(type)) { groups.set(type, []); + } return groups.get(type); } @@ -621,8 +664,9 @@ for (; i < asyncEvents.length; ++i) { const asyncEvent = asyncEvents[i]; - if (asyncEvent.startTime >= range.to) + if (asyncEvent.startTime >= range.to) { break; + } if (asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.Console)) { group(TimelineModel.TimelineModel.TrackType.Console).push(asyncEvent); @@ -643,16 +687,19 @@ asyncEvent.name === TimelineModel.TimelineModel.RecordType.ImplSideFling) { const lastStep = asyncEvent.steps.peekLast(); // FIXME: fix event termination on the back-end instead. - if (lastStep.phase !== SDK.TracingModel.Phase.AsyncEnd) + if (lastStep.phase !== SDK.TracingModel.Phase.AsyncEnd) { continue; + } const data = lastStep.args['data']; asyncEvent.causedFrame = !!(data && data['INPUT_EVENT_LATENCY_RENDERER_SWAP_COMPONENT']); if (asyncEvent.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)) { - if (!this._knownInputEvents.has(lastStep.id)) + if (!this._knownInputEvents.has(lastStep.id)) { continue; + } if (asyncEvent.name === TimelineModel.TimelineModel.RecordType.InputLatencyMouseMove && - !asyncEvent.causedFrame) + !asyncEvent.causedFrame) { continue; + } const rendererMain = data['INPUT_EVENT_LATENCY_RENDERER_MAIN_COMPONENT']; if (rendererMain) { const time = rendererMain['time'] / 1000; @@ -696,13 +743,15 @@ this._currentTaskLayoutAndRecalcEvents = []; } - if (this._currentScriptEvent && event.startTime > this._currentScriptEvent.endTime) + if (this._currentScriptEvent && event.startTime > this._currentScriptEvent.endTime) { this._currentScriptEvent = null; + } const eventData = event.args['data'] || event.args['beginData'] || {}; const timelineData = TimelineModel.TimelineData.forEvent(event); - if (eventData['stackTrace']) + if (eventData['stackTrace']) { timelineData.stackTrace = eventData['stackTrace']; + } if (timelineData.stackTrace && event.name !== recordTypes.JSSample) { // TraceEvents come with 1-based line & column numbers. The frontend code // requires 0-based ones. Adjust the values. @@ -712,13 +761,15 @@ } } let pageFrameId = TimelineModel.TimelineModel.eventFrameId(event); - if (!pageFrameId && eventStack.length) + if (!pageFrameId && eventStack.length) { pageFrameId = TimelineModel.TimelineData.forEvent(eventStack.peekLast()).frameId; + } timelineData.frameId = pageFrameId || (this._mainFrame && this._mainFrame.frameId) || ''; this._asyncEventTracker.processEvent(event); - if (this.isMarkerEvent(event)) + if (this.isMarkerEvent(event)) { this._ensureNamedTrack(TimelineModel.TimelineModel.TrackType.Timings); + } switch (event.name) { case recordTypes.ResourceSendRequest: @@ -734,11 +785,13 @@ case recordTypes.UpdateLayoutTree: case recordTypes.RecalculateStyles: this._invalidationTracker.didRecalcStyle(event); - if (event.args['beginData']) + if (event.args['beginData']) { timelineData.setInitiator(this._lastScheduleStyleRecalculation[event.args['beginData']['frame']]); + } this._lastRecalculateStylesEvent = event; - if (this._currentScriptEvent) + if (this._currentScriptEvent) { this._currentTaskLayoutAndRecalcEvents.push(event); + } break; case recordTypes.ScheduleStyleInvalidationTracking: @@ -754,8 +807,9 @@ let layoutInitator = event; const frameId = eventData['frame']; if (!this._layoutInvalidate[frameId] && this._lastRecalculateStylesEvent && - this._lastRecalculateStylesEvent.endTime > event.startTime) + this._lastRecalculateStylesEvent.endTime > event.startTime) { layoutInitator = TimelineModel.TimelineData.forEvent(this._lastRecalculateStylesEvent).initiator(); + } this._layoutInvalidate[frameId] = layoutInitator; break; } @@ -765,53 +819,63 @@ const frameId = event.args['beginData']['frame']; timelineData.setInitiator(this._layoutInvalidate[frameId]); // In case we have no closing Layout event, endData is not available. - if (event.args['endData']) + if (event.args['endData']) { timelineData.backendNodeId = event.args['endData']['rootNode']; + } this._layoutInvalidate[frameId] = null; - if (this._currentScriptEvent) + if (this._currentScriptEvent) { this._currentTaskLayoutAndRecalcEvents.push(event); + } break; } case recordTypes.Task: - if (event.duration > TimelineModel.TimelineModel.Thresholds.LongTask) + if (event.duration > TimelineModel.TimelineModel.Thresholds.LongTask) { timelineData.warning = TimelineModel.TimelineModel.WarningType.LongTask; + } break; case recordTypes.EventDispatch: - if (event.duration > TimelineModel.TimelineModel.Thresholds.RecurringHandler) + if (event.duration > TimelineModel.TimelineModel.Thresholds.RecurringHandler) { timelineData.warning = TimelineModel.TimelineModel.WarningType.LongHandler; + } break; case recordTypes.TimerFire: case recordTypes.FireAnimationFrame: - if (event.duration > TimelineModel.TimelineModel.Thresholds.RecurringHandler) + if (event.duration > TimelineModel.TimelineModel.Thresholds.RecurringHandler) { timelineData.warning = TimelineModel.TimelineModel.WarningType.LongRecurringHandler; + } break; case recordTypes.FunctionCall: // Compatibility with old format. - if (typeof eventData['scriptName'] === 'string') + if (typeof eventData['scriptName'] === 'string') { eventData['url'] = eventData['scriptName']; - if (typeof eventData['scriptLine'] === 'number') + } + if (typeof eventData['scriptLine'] === 'number') { eventData['lineNumber'] = eventData['scriptLine']; + } // Fallthrough. case recordTypes.EvaluateScript: case recordTypes.CompileScript: - if (typeof eventData['lineNumber'] === 'number') + if (typeof eventData['lineNumber'] === 'number') { --eventData['lineNumber']; - if (typeof eventData['columnNumber'] === 'number') + } + if (typeof eventData['columnNumber'] === 'number') { --eventData['columnNumber']; + } // Fallthrough intended. case recordTypes.RunMicrotasks: // Microtasks technically are not necessarily scripts, but for purpose of // forced sync style recalc or layout detection they are. - if (!this._currentScriptEvent) + if (!this._currentScriptEvent) { this._currentScriptEvent = event; + } break; case recordTypes.SetLayerTreeId: @@ -824,8 +888,9 @@ // We currently only show layer tree for the main frame. const frameId = TimelineModel.TimelineModel.eventFrameId(event); const pageFrame = this._pageFrames.get(frameId); - if (!pageFrame || pageFrame.parent) + if (!pageFrame || pageFrame.parent) { return false; + } this._mainFrameLayerTreeId = eventData['layerTreeId']; break; @@ -833,8 +898,9 @@ this._invalidationTracker.didPaint(event); timelineData.backendNodeId = eventData['nodeId']; // Only keep layer paint events, skip paints for subframes that get painted to the same layer as parent. - if (!eventData['layerId']) + if (!eventData['layerId']) { break; + } const layerId = eventData['layerId']; this._lastPaintForLayer[layerId] = event; break; @@ -843,8 +909,9 @@ case recordTypes.DisplayItemListSnapshot: case recordTypes.PictureSnapshot: { const layerUpdateEvent = this._findAncestorEvent(recordTypes.UpdateLayer); - if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this._mainFrameLayerTreeId) + if (!layerUpdateEvent || layerUpdateEvent.args['layerTreeId'] !== this._mainFrameLayerTreeId) { break; + } const paintEvent = this._lastPaintForLayer[layerUpdateEvent.args['layerId']]; if (paintEvent) { TimelineModel.TimelineData.forEvent(paintEvent).picture = @@ -870,8 +937,9 @@ paintImageEvent = decodeLazyPixelRefEvent && this._paintImageEventByPixelRefId[decodeLazyPixelRefEvent.args['LazyPixelRef']]; } - if (!paintImageEvent) + if (!paintImageEvent) { break; + } const paintImageData = TimelineModel.TimelineData.forEvent(paintImageEvent); timelineData.backendNodeId = paintImageData.backendNodeId; timelineData.url = paintImageData.url; @@ -880,8 +948,9 @@ case recordTypes.DrawLazyPixelRef: { const paintImageEvent = this._findAncestorEvent(recordTypes.PaintImage); - if (!paintImageEvent) + if (!paintImageEvent) { break; + } this._paintImageEventByPixelRefId[event.args['LazyPixelRef']] = paintImageEvent; const paintImageData = TimelineModel.TimelineData.forEvent(paintImageEvent); timelineData.backendNodeId = paintImageData.backendNodeId; @@ -890,8 +959,9 @@ } case recordTypes.FrameStartedLoading: - if (timelineData.frameId !== event.args['frame']) + if (timelineData.frameId !== event.args['frame']) { return false; + } break; case recordTypes.MarkLCPCandidate: @@ -901,14 +971,16 @@ case recordTypes.MarkDOMContent: case recordTypes.MarkLoad: { const frameId = TimelineModel.TimelineModel.eventFrameId(event); - if (!this._pageFrames.has(frameId)) + if (!this._pageFrames.has(frameId)) { return false; + } break; } case recordTypes.CommitLoad: { - if (this._browserFrameTracking) + if (this._browserFrameTracking) { break; + } const frameId = TimelineModel.TimelineModel.eventFrameId(event); const isMainFrame = !!eventData['isMainFrame']; const pageFrame = this._pageFrames.get(frameId); @@ -918,23 +990,26 @@ // We should only have one main frame which has persistent id, // unless it's an old trace without 'persistentIds' flag. if (!this._persistentIds) { - if (eventData['page'] && eventData['page'] !== this._legacyCurrentPage) + if (eventData['page'] && eventData['page'] !== this._legacyCurrentPage) { return false; + } } else if (isMainFrame) { return false; } else if (!this._addPageFrame(event, eventData)) { return false; } } - if (isMainFrame) + if (isMainFrame) { this._mainFrame = this._pageFrames.get(frameId); + } break; } case recordTypes.FireIdleCallback: if (event.duration > - eventData['allottedMilliseconds'] + TimelineModel.TimelineModel.Thresholds.IdleCallbackAddon) + eventData['allottedMilliseconds'] + TimelineModel.TimelineModel.Thresholds.IdleCallbackAddon) { timelineData.warning = TimelineModel.TimelineModel.WarningType.IdleDeadlineExceeded; + } break; } return true; @@ -946,38 +1021,43 @@ _processBrowserEvent(event) { if (event.name === TimelineModel.TimelineModel.RecordType.LatencyInfoFlow) { const frameId = event.args['frameTreeNodeId']; - if (typeof frameId === 'number' && frameId === this._mainFrameNodeId) + if (typeof frameId === 'number' && frameId === this._mainFrameNodeId) { this._knownInputEvents.add(event.bind_id); + } return; } if (event.name === TimelineModel.TimelineModel.RecordType.ResourceWillSendRequest) { const requestId = event.args['data']['requestId']; - if (typeof requestId === 'string') + if (typeof requestId === 'string') { this._requestsFromBrowser.set(requestId, event); + } return; } if (event.hasCategory(SDK.TracingModel.DevToolsMetadataEventCategory) && event.args['data']) { const data = event.args['data']; if (event.name === TimelineModel.TimelineModel.DevToolsMetadataEvent.TracingStartedInBrowser) { - if (!data['persistentIds']) + if (!data['persistentIds']) { return; + } this._browserFrameTracking = true; this._mainFrameNodeId = data['frameTreeNodeId']; const frames = data['frames'] || []; frames.forEach(payload => { const parent = payload['parent'] && this._pageFrames.get(payload['parent']); - if (payload['parent'] && !parent) + if (payload['parent'] && !parent) { return; + } let frame = this._pageFrames.get(payload['frame']); if (!frame) { frame = new TimelineModel.TimelineModel.PageFrame(payload); this._pageFrames.set(frame.frameId, frame); - if (parent) + if (parent) { parent.addChild(frame); - else + } else { this._mainFrame = frame; + } } // TODO(dgozman): this should use event.startTime, but due to races between tracing start // in different processes we cannot do this yet. @@ -990,8 +1070,9 @@ let frame = this._pageFrames.get(data['frame']); if (!frame) { const parent = data['parent'] && this._pageFrames.get(data['parent']); - if (!parent) + if (!parent) { return; + } frame = new TimelineModel.TimelineModel.PageFrame(data); this._pageFrames.set(frame.frameId, frame); parent.addChild(frame); @@ -1002,15 +1083,17 @@ if (event.name === TimelineModel.TimelineModel.DevToolsMetadataEvent.ProcessReadyInBrowser && this._browserFrameTracking) { const frame = this._pageFrames.get(data['frame']); - if (frame) + if (frame) { frame.processReady(data['processPseudoId'], data['processId']); + } return; } if (event.name === TimelineModel.TimelineModel.DevToolsMetadataEvent.FrameDeletedInBrowser && this._browserFrameTracking) { const frame = this._pageFrames.get(data['frame']); - if (frame) + if (frame) { frame.deletedTime = event.startTime; + } return; } } @@ -1037,8 +1120,9 @@ _findAncestorEvent(name) { for (let i = this._eventStack.length - 1; i >= 0; --i) { const event = this._eventStack[i]; - if (event.name === name) + if (event.name === name) { return event; + } } return null; } @@ -1050,13 +1134,15 @@ */ _addPageFrame(event, payload) { const parent = payload['parent'] && this._pageFrames.get(payload['parent']); - if (payload['parent'] && !parent) + if (payload['parent'] && !parent) { return false; + } const pageFrame = new TimelineModel.TimelineModel.PageFrame(payload); this._pageFrames.set(pageFrame.frameId, pageFrame); pageFrame.update(event.startTime, payload); - if (parent) + if (parent) { parent.addChild(pageFrame); + } return true; } @@ -1170,8 +1256,9 @@ * @return {!Array<!TimelineModel.TimelineModel.NetworkRequest>} */ networkRequests() { - if (this.isGenericTrace()) + if (this.isGenericTrace()) { return []; + } /** @type {!Map<string,!TimelineModel.TimelineModel.NetworkRequest>} */ const requests = new Map(); /** @type {!Array<!TimelineModel.TimelineModel.NetworkRequest>} */ @@ -1186,11 +1273,13 @@ const events = this.inspectedTargetEvents(); for (let i = 0; i < events.length; ++i) { const e = events[i]; - if (!resourceTypes.has(e.name)) + if (!resourceTypes.has(e.name)) { continue; + } const id = TimelineModel.TimelineModel.globalEventId(e, 'requestId'); - if (e.name === types.ResourceSendRequest && this._requestsFromBrowser.has(e.args.data.requestId)) + if (e.name === types.ResourceSendRequest && this._requestsFromBrowser.has(e.args.data.requestId)) { addRequest(this._requestsFromBrowser.get(e.args.data.requestId), id); + } addRequest(e, id); } function addRequest(e, id) { @@ -1200,10 +1289,11 @@ } else { request = new TimelineModel.TimelineModel.NetworkRequest(e); requests.set(id, request); - if (request.startTime) + if (request.startTime) { requestsList.push(request); - else + } else { zeroStartRequestsList.push(request); + } } } return zeroStartRequestsList.concat(requestsList); @@ -1424,19 +1514,22 @@ * @return {!Array<!SDK.TracingModel.Event>} */ syncEvents() { - if (this.events.length) + if (this.events.length) { return this.events; + } - if (this._syncEvents) + if (this._syncEvents) { return this._syncEvents; + } const stack = []; this._syncEvents = []; for (const event of this.asyncEvents) { const startTime = event.startTime; const endTime = event.endTime; - while (stack.length && startTime >= stack.peekLast().endTime) + while (stack.length && startTime >= stack.peekLast().endTime) { stack.pop(); + } if (stack.length && endTime > stack.peekLast().endTime) { this._syncEvents = []; break; @@ -1572,17 +1665,22 @@ // This Math.min is likely because of BUG(chromium:865066). this.startTime = Math.min(this.startTime, event.startTime); const eventData = event.args['data']; - if (eventData['mimeType']) + if (eventData['mimeType']) { this.mimeType = eventData['mimeType']; - if ('priority' in eventData) + } + if ('priority' in eventData) { this.priority = eventData['priority']; - if (event.name === recordType.ResourceFinish) + } + if (event.name === recordType.ResourceFinish) { this.endTime = event.startTime; - if (eventData['finishTime']) + } + if (eventData['finishTime']) { this.finishTime = eventData['finishTime'] * 1000; + } if (!this.responseTime && - (event.name === recordType.ResourceReceiveResponse || event.name === recordType.ResourceReceivedData)) + (event.name === recordType.ResourceReceiveResponse || event.name === recordType.ResourceReceivedData)) { this.responseTime = event.startTime; + } const encodedDataLength = eventData['encodedDataLength'] || 0; if (event.name === recordType.ResourceMarkAsCached) { // This is a reliable signal for memory caching. @@ -1593,14 +1691,17 @@ // See BUG(chromium:998397): back-end over-approximates caching. this._maybeDiskCached = true; } - if (eventData['fromServiceWorker']) + if (eventData['fromServiceWorker']) { this.fromServiceWorker = true; - if (eventData['hasCachedResource']) + } + if (eventData['hasCachedResource']) { this.hasCachedResource = true; + } this.encodedDataLength = encodedDataLength; } - if (event.name === recordType.ResourceReceivedData) + if (event.name === recordType.ResourceReceivedData) { this.encodedDataLength += encodedDataLength; + } if (event.name === recordType.ResourceFinish && encodedDataLength) { this.encodedDataLength = encodedDataLength; // If a ResourceFinish event with an encoded data length is received, @@ -1609,16 +1710,21 @@ this._transferSize = encodedDataLength; } const decodedBodyLength = eventData['decodedBodyLength']; - if (event.name === recordType.ResourceFinish && decodedBodyLength) + if (event.name === recordType.ResourceFinish && decodedBodyLength) { this.decodedBodyLength = decodedBodyLength; - if (!this.url) + } + if (!this.url) { this.url = eventData['url']; - if (!this.requestMethod) + } + if (!this.requestMethod) { this.requestMethod = eventData['requestMethod']; - if (!this.timing) + } + if (!this.timing) { this.timing = eventData['timing']; - if (eventData['fromServiceWorker']) + } + if (eventData['fromServiceWorker']) { this.fromServiceWorker = true; + } } /** @@ -1730,8 +1836,9 @@ // FIXME: Move this to TimelineUIUtils.js. if (!this.cause.reason && this.cause.stackTrace && - this.type === TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking) + this.type === TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking) { this.cause.reason = 'Layout forced'; + } } }; @@ -1774,8 +1881,9 @@ // will be handled by StyleInvalidatorInvalidationTracking. // FIXME: Investigate if we can remove StyleInvalidator invalidations entirely. if (invalidation.type === recordTypes.StyleRecalcInvalidationTracking && - invalidation.cause.reason === 'StyleInvalidator') + invalidation.cause.reason === 'StyleInvalidator') { return; + } // Style invalidation events can occur before and during recalc style. didRecalcStyle // handles style invalidations that occur before the recalc style event but we need to @@ -1788,20 +1896,23 @@ const duringRecalcStyle = invalidation.startTime && this._lastRecalcStyle && invalidation.startTime >= this._lastRecalcStyle.startTime && invalidation.startTime <= this._lastRecalcStyle.endTime; - if (duringRecalcStyle) + if (duringRecalcStyle) { this._associateWithLastRecalcStyleEvent(invalidation); + } } // Record the invalidation so later events can look it up. - if (this._invalidations[invalidation.type]) + if (this._invalidations[invalidation.type]) { this._invalidations[invalidation.type].push(invalidation); - else + } else { this._invalidations[invalidation.type] = [invalidation]; + } if (invalidation.nodeId) { - if (this._invalidationsByNodeId[invalidation.nodeId]) + if (this._invalidationsByNodeId[invalidation.nodeId]) { this._invalidationsByNodeId[invalidation.nodeId].push(invalidation); - else + } else { this._invalidationsByNodeId[invalidation.nodeId] = [invalidation]; + } } } @@ -1815,16 +1926,18 @@ TimelineModel.TimelineModel.RecordType.StyleInvalidatorInvalidationTracking, TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking ]; - for (const invalidation of this._invalidationsOfTypes(types)) + for (const invalidation of this._invalidationsOfTypes(types)) { this._associateWithLastRecalcStyleEvent(invalidation); + } } /** * @param {!TimelineModel.InvalidationTrackingEvent} invalidation */ _associateWithLastRecalcStyleEvent(invalidation) { - if (invalidation.linkedRecalcStyleEvent) + if (invalidation.linkedRecalcStyleEvent) { return; + } const recordTypes = TimelineModel.TimelineModel.RecordType; const recalcStyleFrameId = this._lastRecalcStyle.args['beginData']['frame']; @@ -1865,8 +1978,9 @@ for (let j = 0; j < nodeInvalidations.length; j++) { const invalidation = nodeInvalidations[j]; if (invalidation.frame !== frameId || invalidation.invalidationSet !== setId || - invalidation.type !== TimelineModel.TimelineModel.RecordType.ScheduleStyleInvalidationTracking) + invalidation.type !== TimelineModel.TimelineModel.RecordType.ScheduleStyleInvalidationTracking) { continue; + } lastScheduleStyleRecalculation = invalidation; } if (!lastScheduleStyleRecalculation) { @@ -1885,14 +1999,17 @@ _addSyntheticStyleRecalcInvalidation(baseEvent, styleInvalidatorInvalidation) { const invalidation = new TimelineModel.InvalidationTrackingEvent(baseEvent); invalidation.type = TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking; - if (styleInvalidatorInvalidation.cause.reason) + if (styleInvalidatorInvalidation.cause.reason) { invalidation.cause.reason = styleInvalidatorInvalidation.cause.reason; - if (styleInvalidatorInvalidation.selectorPart) + } + if (styleInvalidatorInvalidation.selectorPart) { invalidation.selectorPart = styleInvalidatorInvalidation.selectorPart; + } this.addInvalidation(invalidation); - if (!invalidation.linkedRecalcStyleEvent) + if (!invalidation.linkedRecalcStyleEvent) { this._associateWithLastRecalcStyleEvent(invalidation); + } } /** @@ -1902,8 +2019,9 @@ const layoutFrameId = layoutEvent.args['beginData']['frame']; for (const invalidation of this._invalidationsOfTypes( [TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking])) { - if (invalidation.linkedLayoutEvent) + if (invalidation.linkedLayoutEvent) { continue; + } this._addInvalidationToEvent(layoutEvent, layoutFrameId, invalidation); invalidation.linkedLayoutEvent = true; } @@ -1922,12 +2040,14 @@ * @param {!TimelineModel.InvalidationTrackingEvent} invalidation */ _addInvalidationToEvent(event, eventFrameId, invalidation) { - if (eventFrameId !== invalidation.frame) + if (eventFrameId !== invalidation.frame) { return; - if (!event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol]) + } + if (!event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol]) { event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol] = [invalidation]; - else + } else { event[TimelineModel.InvalidationTracker._invalidationTrackingEventsSymbol].push(invalidation); + } } /** @@ -1936,21 +2056,24 @@ */ _invalidationsOfTypes(types) { const invalidations = this._invalidations; - if (!types) + if (!types) { types = Object.keys(invalidations); + } function* generator() { for (let i = 0; i < types.length; ++i) { const invalidationList = invalidations[types[i]] || []; - for (let j = 0; j < invalidationList.length; ++j) + for (let j = 0; j < invalidationList.length; ++j) { yield invalidationList[j]; + } } } return generator(); } _startNewFrameIfNeeded() { - if (!this._didPaint) + if (!this._didPaint) { return; + } this._initializePerFrameState(); } @@ -1977,13 +2100,15 @@ TimelineModel.TimelineAsyncEventTracker._initialize(); /** @type {!Map<!TimelineModel.TimelineModel.RecordType, !Map<string, !SDK.TracingModel.Event>>} */ this._initiatorByType = new Map(); - for (const initiator of TimelineModel.TimelineAsyncEventTracker._asyncEvents.keys()) + for (const initiator of TimelineModel.TimelineAsyncEventTracker._asyncEvents.keys()) { this._initiatorByType.set(initiator, new Map()); + } } static _initialize() { - if (TimelineModel.TimelineAsyncEventTracker._asyncEvents) + if (TimelineModel.TimelineAsyncEventTracker._asyncEvents) { return; + } const events = new Map(); let type = TimelineModel.TimelineModel.RecordType; @@ -2004,8 +2129,9 @@ TimelineModel.TimelineAsyncEventTracker._typeToInitiator = new Map(); for (const entry of events) { const types = entry[1].causes; - for (type of types) + for (type of types) { TimelineModel.TimelineAsyncEventTracker._typeToInitiator.set(type, entry[0]); + } } } @@ -2016,14 +2142,17 @@ let initiatorType = TimelineModel.TimelineAsyncEventTracker._typeToInitiator.get( /** @type {!TimelineModel.TimelineModel.RecordType} */ (event.name)); const isInitiator = !initiatorType; - if (!initiatorType) + if (!initiatorType) { initiatorType = /** @type {!TimelineModel.TimelineModel.RecordType} */ (event.name); + } const initiatorInfo = TimelineModel.TimelineAsyncEventTracker._asyncEvents.get(initiatorType); - if (!initiatorInfo) + if (!initiatorInfo) { return; + } const id = TimelineModel.TimelineModel.globalEventId(event, initiatorInfo.joinBy); - if (!id) + if (!id) { return; + } /** @type {!Map<string, !SDK.TracingModel.Event>|undefined} */ const initiatorMap = this._initiatorByType.get(initiatorType); if (isInitiator) { @@ -2033,8 +2162,9 @@ const initiator = initiatorMap.get(id) || null; const timelineData = TimelineModel.TimelineData.forEvent(event); timelineData.setInitiator(initiator); - if (!timelineData.frameId && initiator) + if (!timelineData.frameId && initiator) { timelineData.frameId = TimelineModel.TimelineModel.eventFrameId(initiator); + } } }; @@ -2065,11 +2195,13 @@ */ setInitiator(initiator) { this._initiator = initiator; - if (!initiator || this.url) + if (!initiator || this.url) { return; + } const initiatorURL = TimelineModel.TimelineData.forEvent(initiator).url; - if (initiatorURL) + if (initiatorURL) { this.url = initiatorURL; + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModelFilter.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModelFilter.js index 7e4cea1..02531e8 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModelFilter.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineModelFilter.js
@@ -34,12 +34,15 @@ * @return {!TimelineModel.TimelineModel.RecordType} */ static _eventType(event) { - if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) + if (event.hasCategory(TimelineModel.TimelineModel.Category.Console)) { return TimelineModel.TimelineModel.RecordType.ConsoleTime; - if (event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) + } + if (event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)) { return TimelineModel.TimelineModel.RecordType.UserTiming; - if (event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)) + } + if (event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)) { return TimelineModel.TimelineModel.RecordType.LatencyInfo; + } return /** @type !TimelineModel.TimelineModel.RecordType */ (event.name); } };
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineProfileTree.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineProfileTree.js index d16b466..82c2b973 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineProfileTree.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TimelineProfileTree.js
@@ -62,10 +62,12 @@ */ searchTree(matchFunction, results) { results = results || []; - if (this.event && matchFunction(this.event)) + if (this.event && matchFunction(this.event)) { results.push(this); - for (const child of this.children().values()) + } + for (const child of this.children().values()) { child.searchTree(matchFunction, results); + } return results; } }; @@ -107,8 +109,9 @@ _buildChildren() { /** @type {!Array<!TimelineModel.TimelineProfileTree.TopDownNode>} */ const path = []; - for (let node = this; node.parent && !node._isGroupNode; node = node.parent) + for (let node = this; node.parent && !node._isGroupNode; node = node.parent) { path.push(/** @type {!TimelineModel.TimelineProfileTree.TopDownNode} */ (node)); + } path.reverse(); /** @type {!TimelineModel.TimelineProfileTree.ChildrenCache} */ const children = new Map(); @@ -130,13 +133,16 @@ */ function onStartEvent(e) { ++depth; - if (depth > path.length + 2) + if (depth > path.length + 2) { return; - if (!matchPath(e)) + } + if (!matchPath(e)) { return; + } const duration = Math.min(endTime, e.endTime) - Math.max(startTime, e.startTime); - if (duration < 0) + if (duration < 0) { console.error('Negative event duration'); + } processEvent(e, duration); } @@ -145,8 +151,9 @@ */ function onInstantEvent(e) { ++depth; - if (matchedDepth === path.length && depth <= path.length + 2) + if (matchedDepth === path.length && depth <= path.length + 2) { processEvent(e, 0); + } --depth; } @@ -167,8 +174,9 @@ } else { id = eventIdCallback(e); groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : ''; - if (groupId) + if (groupId) { id += '/' + groupId; + } } let node = children.get(id); if (!node) { @@ -186,23 +194,29 @@ * @return {boolean} */ function matchPath(e) { - if (matchedDepth === path.length) + if (matchedDepth === path.length) { return true; - if (matchedDepth !== depth - 1) + } + if (matchedDepth !== depth - 1) { return false; - if (!e.endTime) + } + if (!e.endTime) { return false; + } if (!eventIdCallback) { - if (e === path[matchedDepth].event) + if (e === path[matchedDepth].event) { ++matchedDepth; + } return false; } let id = eventIdCallback(e); const groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : ''; - if (groupId) + if (groupId) { id += '/' + groupId; - if (id === path[matchedDepth].id) + } + if (id === path[matchedDepth].id) { ++matchedDepth; + } return false; } @@ -211,8 +225,9 @@ */ function onEndEvent(e) { --depth; - if (matchedDepth > depth) + if (matchedDepth > depth) { matchedDepth = depth; + } } this._children = children; @@ -255,10 +270,12 @@ */ _grouppedTopNodes() { const flatNodes = super.children(); - for (const node of flatNodes.values()) + for (const node of flatNodes.values()) { this.selfTime -= node.totalTime; - if (!this._eventGroupIdCallback) + } + if (!this._eventGroupIdCallback) { return flatNodes; + } const groupNodes = new Map(); for (const node of flatNodes.values()) { const groupId = this._eventGroupIdCallback(/** @type {!SDK.TracingModel.Event} */ (node.event)); @@ -311,8 +328,9 @@ */ _filterChildren(children) { for (const [id, child] of children) { - if (child.event && !this._textFilter.accept(child.event)) + if (child.event && !this._textFilter.accept(child.event)) { children.delete(/** @type {string|symbol} */ (id)); + } } return children; } @@ -322,8 +340,9 @@ * @return {!TimelineModel.TimelineProfileTree.ChildrenCache} */ children() { - if (!this._children) + if (!this._children) { this._children = this._filterChildren(this._grouppedTopNodes()); + } return this._children; } @@ -354,8 +373,9 @@ selfTimeStack.push(duration); const id = TimelineModel.TimelineProfileTree._eventId(e); const noNodeOnStack = !totalTimeById.has(id); - if (noNodeOnStack) + if (noNodeOnStack) { totalTimeById.set(id, duration); + } firstNodeStack.push(noNodeOnStack); } @@ -374,14 +394,16 @@ node.totalTime += totalTimeById.get(id); totalTimeById.delete(id); } - if (firstNodeStack.length) + if (firstNodeStack.length) { node.setHasChildren(); + } } this.selfTime = selfTimeStack.pop(); for (const pair of nodeById) { - if (pair[1].selfTime <= 0) + if (pair[1].selfTime <= 0) { nodeById.delete(/** @type {string} */ (pair[0])); + } } return nodeById; } @@ -391,8 +413,9 @@ */ _grouppedTopNodes() { const flatNodes = this._ungrouppedTopNodes(); - if (!this._eventGroupIdCallback) + if (!this._eventGroupIdCallback) { return flatNodes; + } const groupNodes = new Map(); for (const node of flatNodes.values()) { const groupId = this._eventGroupIdCallback(/** @type {!SDK.TracingModel.Event} */ (node.event)); @@ -485,8 +508,9 @@ * @return {!TimelineModel.TimelineProfileTree.ChildrenCache} */ children() { - if (this._cachedChildren) + if (this._cachedChildren) { return this._cachedChildren; + } /** @type {!Array<number>} */ const selfTimeStack = [0]; /** @type {!Array<string>} */ @@ -507,8 +531,9 @@ */ function onStartEvent(e) { const duration = Math.min(e.endTime, endTime) - Math.max(e.startTime, startTime); - if (duration < 0) + if (duration < 0) { console.assert(false, 'Negative duration of an event'); + } selfTimeStack[selfTimeStack.length - 1] -= duration; selfTimeStack.push(duration); const id = TimelineModel.TimelineProfileTree._eventId(e); @@ -525,11 +550,13 @@ eventStack.pop(); let node; for (node = self; node._depth > 1; node = node.parent) { - if (node.id !== eventIdStack[eventIdStack.length + 1 - node._depth]) + if (node.id !== eventIdStack[eventIdStack.length + 1 - node._depth]) { return; + } } - if (node.id !== id || eventIdStack.length < self._depth) + if (node.id !== id || eventIdStack.length < self._depth) { return; + } const childId = eventIdStack[eventIdStack.length - self._depth]; node = nodeById.get(childId); if (!node) { @@ -556,8 +583,9 @@ */ searchTree(matchFunction, results) { results = results || []; - if (this.event && matchFunction(this.event)) + if (this.event && matchFunction(this.event)) { results.push(this); + } return results; } }; @@ -568,13 +596,15 @@ */ TimelineModel.TimelineProfileTree.eventURL = function(event) { const data = event.args['data'] || event.args['beginData']; - if (data && data['url']) + if (data && data['url']) { return data['url']; + } let frame = TimelineModel.TimelineProfileTree.eventStackFrame(event); while (frame) { const url = frame['url']; - if (url) + if (url) { return url; + } frame = frame.parent; } return null; @@ -585,8 +615,9 @@ * @return {?Protocol.Runtime.CallFrame} */ TimelineModel.TimelineProfileTree.eventStackFrame = function(event) { - if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame) + if (event.name === TimelineModel.TimelineModel.RecordType.JSFrame) { return /** @type {?Protocol.Runtime.CallFrame} */ (event.args['data'] || null); + } return TimelineModel.TimelineData.forEvent(event).topFrame(); }; @@ -595,10 +626,12 @@ * @return {string} */ TimelineModel.TimelineProfileTree._eventId = function(event) { - if (event.name === TimelineModel.TimelineModel.RecordType.TimeStamp) + if (event.name === TimelineModel.TimelineModel.RecordType.TimeStamp) { return `${event.name}:${event.args.data.message}`; - if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame) + } + if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame) { return event.name; + } const frame = event.args['data']; const location = frame['scriptId'] || frame['url'] || ''; const functionName = frame['functionName'];
diff --git a/third_party/blink/renderer/devtools/front_end/timeline_model/TracingLayerTree.js b/third_party/blink/renderer/devtools/front_end/timeline_model/TracingLayerTree.js index cfaa503..c1a1dd5 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline_model/TracingLayerTree.js +++ b/third_party/blink/renderer/devtools/front_end/timeline_model/TracingLayerTree.js
@@ -53,8 +53,9 @@ // layer tree hierarchy, this code will eventually be removed. this._extractNodeIdsToResolve(idsToResolve, {}, root); } else { - for (let i = 0; i < layers.length; ++i) + for (let i = 0; i < layers.length; ++i) { this._extractNodeIdsToResolve(idsToResolve, {}, layers[i]); + } } await this.resolveBackendNodeIds(idsToResolve); @@ -70,8 +71,9 @@ const contentRoot = this.contentRoot(); this.setRoot(contentRoot); for (let i = 0; i < processedLayers.length; ++i) { - if (processedLayers[i].id() !== contentRoot.id()) + if (processedLayers[i].id() !== contentRoot.id()) { contentRoot.addChild(processedLayers[i]); + } } } this._setPaints(paints); @@ -82,8 +84,9 @@ */ setTiles(tiles) { this._tileById = new Map(); - for (const tile of tiles) + for (const tile of tiles) { this._tileById.set(tile.id, tile); + } } /** @@ -110,8 +113,9 @@ _setPaints(paints) { for (let i = 0; i < paints.length; ++i) { const layer = this._layersById[paints[i].layerId()]; - if (layer) + if (layer) { layer._addPaintEvent(paints[i]); + } } } @@ -122,17 +126,21 @@ */ _innerSetLayers(oldLayersById, payload) { let layer = /** @type {?TimelineModel.TracingLayer} */ (oldLayersById[payload.layer_id]); - if (layer) + if (layer) { layer._reset(payload); - else + } else { layer = new TimelineModel.TracingLayer(this._paintProfilerModel, payload); + } this._layersById[payload.layer_id] = layer; - if (payload.owner_node) + if (payload.owner_node) { layer._setNode(this.backendNodeIdToNode().get(payload.owner_node) || null); - if (!this.contentRoot() && layer.drawsContent()) + } + if (!this.contentRoot() && layer.drawsContent()) { this.setContentRoot(layer); - for (let i = 0; payload.children && i < payload.children.length; ++i) + } + for (let i = 0; payload.children && i < payload.children.length; ++i) { layer.addChild(this._innerSetLayers(oldLayersById, payload.children[i])); + } return layer; } @@ -143,10 +151,12 @@ */ _extractNodeIdsToResolve(nodeIdsToResolve, seenNodeIds, payload) { const backendNodeId = payload.owner_node; - if (backendNodeId && !this.backendNodeIdToNode().has(backendNodeId)) + if (backendNodeId && !this.backendNodeIdToNode().has(backendNodeId)) { nodeIdsToResolve.add(backendNodeId); - for (let i = 0; payload.children && i < payload.children.length; ++i) + } + for (let i = 0; payload.children && i < payload.children.length; ++i) { this._extractNodeIdsToResolve(nodeIdsToResolve, seenNodeIds, payload.children[i]); + } } }; @@ -231,8 +241,9 @@ * @param {!SDK.Layer} child */ addChild(child) { - if (child._parent) + if (child._parent) { console.assert(false, 'Child already has a parent'); + } this._children.push(child); child._parent = this; child._parentLayerId = this._layerId; @@ -259,8 +270,9 @@ */ nodeForSelfOrAncestor() { for (let layer = this; layer; layer = layer._parent) { - if (layer._node) + if (layer._node) { return layer._node; + } } return null; } @@ -376,8 +388,9 @@ */ snapshots() { return this._paints.map(paint => paint.snapshotPromise().then(snapshot => { - if (!snapshot) + if (!snapshot) { return null; + } const rect = {x: snapshot.rect[0], y: snapshot.rect[1], width: snapshot.rect[2], height: snapshot.rect[3]}; return {rect: rect, snapshot: snapshot.snapshot}; })); @@ -392,8 +405,9 @@ const fragments = pictures.filter(picture => picture && rectsOverlap(picture.rect, targetRect)) .map(picture => ({x: picture.rect[0], y: picture.rect[1], picture: picture.serializedPicture})); - if (!fragments.length || !this._paintProfilerModel) + if (!fragments.length || !this._paintProfilerModel) { return null; + } const x0 = fragments.reduce((min, item) => Math.min(min, item.x), Infinity); const y0 = fragments.reduce((min, item) => Math.min(min, item.y), Infinity); // Rect is in layer content coordinates, make it relative to picture by offsetting to the top left corner.
diff --git a/third_party/blink/renderer/devtools/front_end/toolbox_bootstrap/Toolbox.js b/third_party/blink/renderer/devtools/front_end/toolbox_bootstrap/Toolbox.js index 731f91b5..943b43f 100644 --- a/third_party/blink/renderer/devtools/front_end/toolbox_bootstrap/Toolbox.js +++ b/third_party/blink/renderer/devtools/front_end/toolbox_bootstrap/Toolbox.js
@@ -6,8 +6,9 @@ * @suppressGlobalPropertiesCheck */ function toolboxLoaded() { - if (!window.opener) + if (!window.opener) { return; + } const app = window.opener['Emulation']['AdvancedApp']['_instance'](); app['toolboxLoaded'](document); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js b/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js index ac714f32..418f109 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js
@@ -191,10 +191,11 @@ * @param {?string} placeholder */ export function setPlaceholder(element, placeholder) { - if (placeholder) + if (placeholder) { element.setAttribute('aria-placeholder', placeholder); - else + } else { element.removeAttribute('aria-placeholder'); + } } /** @@ -215,8 +216,9 @@ * @param {!Element} element */ export function ensureId(element) { - if (!element.id) + if (!element.id) { element.id = nextId('ariaElement'); + } } /** @@ -279,10 +281,11 @@ * @param {boolean} value */ export function setInvalid(element, value) { - if (value) + if (value) { element.setAttribute('aria-invalid', value); - else + } else { element.removeAttribute('aria-invalid'); + } } /** @@ -345,8 +348,9 @@ // The rest of DevTools shouldn't have to worry about this, // so there is some unfortunate code below. - if (_descriptionMap.has(element)) + if (_descriptionMap.has(element)) { _descriptionMap.get(element).remove(); + } element.removeAttribute('data-aria-utils-animation-hack'); if (!description) { @@ -386,8 +390,9 @@ // Lets try the next best thing, and just put the description element // next to it in the DOM. const inserted = element.insertAdjacentElement('afterend', descriptionElement); - if (inserted) + if (inserted) { return; + } // Uh oh, the insertion didn't work! That means we aren't currently in the DOM. // How can we find out when the element enters the DOM? @@ -395,8 +400,9 @@ element.setAttribute('data-aria-utils-animation-hack', 'sorry'); element.addEventListener('animationend', () => { // Someone might have made a new description in the meantime. - if (_descriptionMap.get(element) !== descriptionElement) + if (_descriptionMap.get(element) !== descriptionElement) { return; + } element.removeAttribute('data-aria-utils-animation-hack'); // Try it again. This time we are in the DOM, so it *should* work.
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ActionRegistry.js b/third_party/blink/renderer/devtools/front_end/ui/ActionRegistry.js index 32a5f3f..a4b37a1 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ActionRegistry.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ActionRegistry.js
@@ -19,17 +19,19 @@ * @this {UI.ActionRegistry} */ function registerExtension(extension) { - if (!extension.canInstantiate()) + if (!extension.canInstantiate()) { return; + } const actionId = extension.descriptor()['actionId']; console.assert(actionId); console.assert(!this._actionsById.get(actionId)); const action = new UI.Action(extension); - if (!action.category() || action.title()) + if (!action.category() || action.title()) { this._actionsById.set(actionId, action); - else + } else { console.error(`Category actions require a title for command menu: ${actionId}`); + } } } @@ -49,8 +51,9 @@ const extensions = []; actionIds.forEach(function(actionId) { const action = this._actionsById.get(actionId); - if (action) + if (action) { extensions.push(action._extension); + } }, this); return context.applicableExtensions(extensions).valuesArray().map(extensionToAction.bind(this)); @@ -137,8 +140,9 @@ * @param {boolean} enabled */ setEnabled(enabled) { - if (this._enabled === enabled) + if (this._enabled === enabled) { return; + } this._enabled = enabled; this.dispatchEventToListeners(UI.Action.Events.Enabled, enabled); @@ -180,8 +184,9 @@ const options = this._extension.descriptor()['options']; if (options) { for (const pair of options) { - if (pair['value'] !== this._toggled) + if (pair['value'] !== this._toggled) { title = pair['title']; + } } } return ls(title); @@ -199,8 +204,9 @@ */ setToggled(toggled) { console.assert(this.toggleable(), 'Shouldn\'t be toggling an untoggleable action', this.id()); - if (this._toggled === toggled) + if (this._toggled === toggled) { return; + } this._toggled = toggled; this.dispatchEventToListeners(UI.Action.Events.Toggled, toggled);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Context.js b/third_party/blink/renderer/devtools/front_end/ui/Context.js index 31b5be9..062c83c 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Context.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Context.js
@@ -17,12 +17,14 @@ */ setFlavor(flavorType, flavorValue) { const value = this._flavors.get(flavorType) || null; - if (value === flavorValue) + if (value === flavorValue) { return; - if (flavorValue) + } + if (flavorValue) { this._flavors.set(flavorType, flavorValue); - else + } else { this._flavors.remove(flavorType); + } this._dispatchFlavorChange(flavorType, flavorValue); } @@ -40,8 +42,9 @@ } } const dispatcher = this._eventDispatchers.get(flavorType); - if (!dispatcher) + if (!dispatcher) { return; + } dispatcher.dispatchEventToListeners(UI.Context.Events.FlavorChanged, flavorValue); } @@ -66,11 +69,13 @@ */ removeFlavorChangeListener(flavorType, listener, thisObject) { const dispatcher = this._eventDispatchers.get(flavorType); - if (!dispatcher) + if (!dispatcher) { return; + } dispatcher.removeEventListener(UI.Context.Events.FlavorChanged, listener, thisObject); - if (!dispatcher.hasEventListeners(UI.Context.Events.FlavorChanged)) + if (!dispatcher.hasEventListeners(UI.Context.Events.FlavorChanged)) { this._eventDispatchers.remove(flavorType); + } } /** @@ -98,8 +103,9 @@ const availableFlavors = this.flavors(); extensions.forEach(function(extension) { - if (self.runtime.isExtensionApplicableToContextTypes(extension, availableFlavors)) + if (self.runtime.isExtensionApplicableToContextTypes(extension, availableFlavors)) { targetExtensionSet.add(extension); + } }); return targetExtensionSet;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ContextMenu.js b/third_party/blink/renderer/devtools/front_end/ui/ContextMenu.js index 9e877c75..73d3c05 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ContextMenu.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ContextMenu.js
@@ -45,8 +45,9 @@ this._disabled = disabled; this._checked = checked; this._contextMenu = contextMenu; - if (type === 'item' || type === 'checkbox') + if (type === 'item' || type === 'checkbox') { this._id = contextMenu ? contextMenu._nextId() : 0; + } } /** @@ -84,10 +85,12 @@ switch (this._type) { case 'item': const result = {type: 'item', id: this._id, label: this._label, enabled: !this._disabled}; - if (this._customElement) + if (this._customElement) { result.element = this._customElement; - if (this._shortcut) + } + if (this._shortcut) { result.shortcut = this._shortcut; + } return result; case 'separator': return {type: 'separator'}; @@ -150,16 +153,19 @@ appendAction(actionId, label, optional) { const action = UI.actionRegistry.action(actionId); if (!action) { - if (!optional) + if (!optional) { console.error(`Action ${actionId} was not defined`); + } return; } - if (!label) + if (!label) { label = action.title(); + } const result = this.appendItem(label, action.execute.bind(action)); const shortcut = UI.shortcutRegistry.shortcutTitleForAction(actionId); - if (shortcut) + if (shortcut) { result.setShortcut(shortcut); + } } /** @@ -308,10 +314,12 @@ const nonEmptySections = this._sectionList.filter(section => !!section._items.length); for (const section of nonEmptySections) { - for (const item of section._items) + for (const item of section._items) { result.subItems.push(item._buildDescriptor()); - if (section !== nonEmptySections.peekLast()) + } + if (section !== nonEmptySections.peekLast()) { result.subItems.push({type: 'separator'}); + } } return result; } @@ -322,12 +330,14 @@ appendItemsAtLocation(location) { for (const extension of self.runtime.extensions('context-menu-item')) { const itemLocation = extension.descriptor()['location'] || ''; - if (!itemLocation.startsWith(location + '/')) + if (!itemLocation.startsWith(location + '/')) { continue; + } const section = itemLocation.substr(location.length + 1); - if (!section || section.includes('/')) + if (!section || section.includes('/')) { continue; + } this.section(section).appendAction(extension.descriptor()['actionId']); } @@ -363,8 +373,9 @@ this._id = 0; const target = event.deepElementFromPoint(); - if (target) + if (target) { this.appendApplicableItems(/** @type {!Object} */ (target)); + } } static initialize() { @@ -408,8 +419,9 @@ * @this {UI.ContextMenu} */ function populate(appendCallResults) { - if (UI.ContextMenu._pendingMenu !== this) + if (UI.ContextMenu._pendingMenu !== this) { return; + } delete UI.ContextMenu._pendingMenu; for (let i = 0; i < appendCallResults.length; ++i) { @@ -430,8 +442,9 @@ } discard() { - if (this._softMenu) + if (this._softMenu) { this._softMenu.discard(); + } } _innerShow() { @@ -463,8 +476,9 @@ * @param {function(?)} handler */ _setHandler(id, handler) { - if (handler) + if (handler) { this._handlers[id] = handler; + } } /** @@ -485,8 +499,9 @@ * @param {string} id */ _itemSelected(id) { - if (this._handlers[id]) + if (this._handlers[id]) { this._handlers[id].call(this); + } this._menuCleared(); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Dialog.js b/third_party/blink/renderer/devtools/front_end/ui/Dialog.js index 3a45ac64..cfa7d2e 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Dialog.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Dialog.js
@@ -64,8 +64,9 @@ show(where) { const document = /** @type {!Document} */ ( where instanceof Document ? where : (where || UI.inspectorView.element).ownerDocument); - if (UI.Dialog._instance) + if (UI.Dialog._instance) { UI.Dialog._instance.hide(); + } UI.Dialog._instance = this; this._disableTabIndexOnElements(document); super.show(document); @@ -113,8 +114,9 @@ } _restoreTabIndexOnElements() { - for (const element of this._tabIndexMap.keys()) + for (const element of this._tabIndexMap.keys()) { element.tabIndex = /** @type {number} */ (this._tabIndexMap.get(element)); + } this._tabIndexMap.clear(); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/DropTarget.js b/third_party/blink/renderer/devtools/front_end/ui/DropTarget.js index cb6c616..3dd21df 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/DropTarget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/DropTarget.js
@@ -32,8 +32,9 @@ * @param {!Event} event */ _onDragEnter(event) { - if (this._enabled && this._hasMatchingType(event)) + if (this._enabled && this._hasMatchingType(event)) { event.consume(true); + } } /** @@ -45,8 +46,9 @@ const found = Array.from(event.dataTransfer.items).find(item => { return transferType.kind === item.kind && !!transferType.type.exec(item.type); }); - if (found) + if (found) { return true; + } } return false; } @@ -55,12 +57,14 @@ * @param {!Event} event */ _onDragOver(event) { - if (!this._enabled || !this._hasMatchingType(event)) + if (!this._enabled || !this._hasMatchingType(event)) { return; + } event.dataTransfer.dropEffect = 'copy'; event.consume(true); - if (this._dragMaskElement) + if (this._dragMaskElement) { return; + } this._dragMaskElement = this._element.createChild('div', ''); const shadowRoot = UI.createShadowRootWithCoreStyles(this._dragMaskElement, 'ui/dropTarget.css'); shadowRoot.createChild('div', 'drop-target-message').textContent = this._messageText; @@ -74,8 +78,9 @@ _onDrop(event) { event.consume(true); this._removeMask(); - if (this._enabled) + if (this._enabled) { this._handleDrop(event.dataTransfer); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/ui/FilterBar.js b/third_party/blink/renderer/devtools/front_end/ui/FilterBar.js index 966e2e48..ad3a8a4 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/FilterBar.js +++ b/third_party/blink/renderer/devtools/front_end/ui/FilterBar.js
@@ -99,8 +99,9 @@ } _updateFilterBar() { - if (!this.parentWidget() || this._showingWidget) + if (!this.parentWidget() || this._showingWidget) { return; + } if (this.visible()) { this._showingWidget = true; this.showWidget(); @@ -125,8 +126,9 @@ _updateFilterButton() { let isActive = false; - for (const filter of this._filters) + for (const filter of this._filters) { isActive = isActive || filter.isActive(); + } this._filterButton.setDefaultWithRedColor(isActive); this._filterButton.setToggleWithRedColor(isActive); } @@ -199,8 +201,9 @@ * @return {!Promise<!UI.SuggestBox.Suggestions>} */ _completions(expression, prefix, force) { - if (this._suggestionProvider) + if (this._suggestionProvider) { return this._suggestionProvider(expression, prefix, force); + } return Promise.resolve([]); } /** @@ -276,8 +279,9 @@ this._typeFilterElements[0].tabIndex = 0; this._filtersElement.createChild('div', 'filter-bitset-filter-divider'); - for (let i = 0; i < items.length; ++i) + for (let i = 0; i < items.length; ++i) { this._addBit(items[i].name, items[i].label, items[i].title); + } if (setting) { this._setting = setting; @@ -320,8 +324,9 @@ const allowedTypes = this._setting.get(); this._allowedTypes = {}; for (const element of this._typeFilterElements) { - if (allowedTypes[element.typeName]) + if (allowedTypes[element.typeName]) { this._allowedTypes[element.typeName] = true; + } } this._update(); } @@ -351,8 +356,9 @@ typeFilterElement.typeName = name; typeFilterElement.createTextChild(label); UI.ARIAUtils.markAsOption(typeFilterElement); - if (title) + if (title) { typeFilterElement.title = title; + } typeFilterElement.addEventListener('click', this._onTypeFilterClicked.bind(this), false); typeFilterElement.addEventListener('keydown', this._onTypeFilterKeydown.bind(this), false); this._typeFilterElements.push(typeFilterElement); @@ -363,10 +369,11 @@ */ _onTypeFilterClicked(e) { let toggle; - if (Host.isMac()) + if (Host.isMac()) { toggle = e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey; - else + } else { toggle = e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey; + } this._toggleTypeFilter(e.target.typeName, toggle); } @@ -375,15 +382,18 @@ */ _onTypeFilterKeydown(event) { const element = /** @type {?Element} */ (event.target); - if (!element) + if (!element) { return; + } if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') { - if (this._keyFocusNextBit(element, true /* selectPrevious */)) + if (this._keyFocusNextBit(element, true /* selectPrevious */)) { event.consume(true); + } } else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') { - if (this._keyFocusNextBit(element, false /* selectPrevious */)) + if (this._keyFocusNextBit(element, false /* selectPrevious */)) { event.consume(true); + } } else if (isEnterOrSpaceKey(event)) { this._onTypeFilterClicked(event); } @@ -396,11 +406,13 @@ */ _keyFocusNextBit(target, selectPrevious) { const index = this._typeFilterElements.indexOf(target); - if (index === -1) + if (index === -1) { return false; + } const nextIndex = selectPrevious ? index - 1 : index + 1; - if (nextIndex < 0 || nextIndex >= this._typeFilterElements.length) + if (nextIndex < 0 || nextIndex >= this._typeFilterElements.length) { return false; + } const nextElement = this._typeFilterElements[nextIndex]; nextElement.tabIndex = 0; @@ -414,17 +426,19 @@ * @param {boolean} allowMultiSelect */ _toggleTypeFilter(typeName, allowMultiSelect) { - if (allowMultiSelect && typeName !== UI.NamedBitSetFilterUI.ALL_TYPES) + if (allowMultiSelect && typeName !== UI.NamedBitSetFilterUI.ALL_TYPES) { this._allowedTypes[UI.NamedBitSetFilterUI.ALL_TYPES] = false; - else + } else { this._allowedTypes = {}; + } this._allowedTypes[typeName] = !this._allowedTypes[typeName]; - if (this._setting) + if (this._setting) { this._setting.set(this._allowedTypes); - else + } else { this._update(); + } } }; @@ -451,10 +465,11 @@ this._label = UI.CheckboxLabel.create(title); this._filterElement.appendChild(this._label); this._checkboxElement = this._label.checkboxElement; - if (setting) + if (setting) { UI.SettingsUI.bindCheckbox(this._checkboxElement, setting); - else + } else { this._checkboxElement.checked = true; + } this._checkboxElement.addEventListener('change', this._fireUpdated.bind(this), false); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/FilterSuggestionBuilder.js b/third_party/blink/renderer/devtools/front_end/ui/FilterSuggestionBuilder.js index 9551ba2..83637d0 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/FilterSuggestionBuilder.js +++ b/third_party/blink/renderer/devtools/front_end/ui/FilterSuggestionBuilder.js
@@ -21,12 +21,14 @@ * @return {!Promise<!UI.SuggestBox.Suggestions>} */ completions(expression, prefix, force) { - if (!prefix && !force) + if (!prefix && !force) { return Promise.resolve([]); + } const negative = prefix.startsWith('-'); - if (negative) + if (negative) { prefix = prefix.substring(1); + } const modifier = negative ? '-' : ''; const valueDelimiterIndex = prefix.indexOf(':'); @@ -34,8 +36,9 @@ if (valueDelimiterIndex === -1) { const matcher = new RegExp('^' + prefix.escapeForRegExp(), 'i'); for (const key of this._keys) { - if (matcher.test(key)) + if (matcher.test(key)) { suggestions.push({text: modifier + key + ':'}); + } } } else { const key = prefix.substring(0, valueDelimiterIndex).toLowerCase(); @@ -44,8 +47,9 @@ const values = Array.from(this._valuesMap.get(key) || new Set()); this._valueSorter(key, values); for (const item of values) { - if (matcher.test(item) && (item !== value)) + if (matcher.test(item) && (item !== value)) { suggestions.push({text: modifier + key + ':' + item}); + } } } return Promise.resolve(suggestions); @@ -56,11 +60,13 @@ * @param {?string=} value */ addItem(key, value) { - if (!value) + if (!value) { return; + } - if (!this._valuesMap.get(key)) + if (!this._valuesMap.get(key)) { this._valuesMap.set(key, /** @type {!Set<string>} */ (new Set())); + } this._valuesMap.get(key).add(value); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ForwardedInputEventHandler.js b/third_party/blink/renderer/devtools/front_end/ui/ForwardedInputEventHandler.js index fa85a40..2313301 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ForwardedInputEventHandler.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ForwardedInputEventHandler.js
@@ -20,8 +20,9 @@ const keyCode = /** @type {number} */ (data.keyCode); const modifiers = /** @type {number} */ (data.modifiers); - if (type !== 'keydown') + if (type !== 'keydown') { return; + } UI.context.setFlavor(UI.ShortcutRegistry.ForwardedShortcut, UI.ShortcutRegistry.ForwardedShortcut.instance); UI.shortcutRegistry.handleKey(UI.KeyboardShortcut.makeKey(keyCode, modifiers), key);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Fragment.js b/third_party/blink/renderer/devtools/front_end/ui/Fragment.js index 3911e9be..f02830b 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Fragment.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Fragment.js
@@ -63,10 +63,11 @@ html += strings[i]; const close = strings[i].lastIndexOf('>'); const open = strings[i].indexOf('<', close + 1); - if (close !== -1 && open === -1) + if (close !== -1 && open === -1) { insideText = true; - else if (open !== -1) + } else if (open !== -1) { insideText = false; + } html += insideText ? UI.Fragment._textMarker : UI.Fragment._attributeMarker(i); } html += strings[strings.length - 1]; @@ -93,8 +94,9 @@ const name = node.attributes[i].name; if (!UI.Fragment._attributeMarkerRegex.test(name) && - !UI.Fragment._attributeMarkerRegex.test(node.attributes[i].value)) + !UI.Fragment._attributeMarkerRegex.test(node.attributes[i].value)) { continue; + } attributesToRemove.push(name); nodesToMark.push(node); @@ -105,16 +107,18 @@ valueIndex += bind.attr.values.length - 1; binds.push(bind); } - for (let i = 0; i < attributesToRemove.length; i++) + for (let i = 0; i < attributesToRemove.length; i++) { node.removeAttribute(attributesToRemove[i]); + } } if (node.nodeType === Node.TEXT_NODE && node.data.indexOf(UI.Fragment._textMarker) !== -1) { const texts = node.data.split(UI.Fragment._textMarkerRegex); node.data = texts[texts.length - 1]; for (let i = 0; i < texts.length - 1; i++) { - if (texts[i]) + if (texts[i]) { node.parentNode.insertBefore(createTextNode(texts[i]), node); + } const nodeToReplace = createElement('span'); nodesToMark.push(nodeToReplace); binds.push({replaceNodeIndex: valueIndex++}); @@ -124,15 +128,18 @@ if (node.nodeType === Node.TEXT_NODE && (!node.previousSibling || node.previousSibling.nodeType === Node.ELEMENT_NODE) && - (!node.nextSibling || node.nextSibling.nodeType === Node.ELEMENT_NODE) && /^\s*$/.test(node.data)) + (!node.nextSibling || node.nextSibling.nodeType === Node.ELEMENT_NODE) && /^\s*$/.test(node.data)) { emptyTextNodes.push(node); + } } - for (let i = 0; i < nodesToMark.length; i++) + for (let i = 0; i < nodesToMark.length; i++) { nodesToMark[i].classList.add(UI.Fragment._class(i)); + } - for (const emptyTextNode of emptyTextNodes) + for (const emptyTextNode of emptyTextNodes) { emptyTextNode.remove(); + } return {template: template, binds: binds}; } @@ -194,14 +201,17 @@ * @return {!Node} */ static _nodeForValue(value) { - if (value instanceof Node) + if (value instanceof Node) { return value; - if (value instanceof UI.Fragment) + } + if (value instanceof UI.Fragment) { return value._element; + } if (Array.isArray(value)) { const node = createDocumentFragment(); - for (const v of value) + for (const v of value) { node.appendChild(this._nodeForValue(v)); + } return node; } return createTextNode('' + value);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Geometry.js b/third_party/blink/renderer/devtools/front_end/ui/Geometry.js index 4f5bf4a3..db21c7b 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Geometry.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Geometry.js
@@ -58,8 +58,9 @@ normalize() { const length = this.length(); - if (length <= UI.Geometry._Eps) + if (length <= UI.Geometry._Eps) { return; + } this.x /= length; this.y /= length; @@ -93,8 +94,9 @@ * @return {!UI.Geometry.Point} */ projectOn(line) { - if (line.x === 0 && line.y === 0) + if (line.x === 0 && line.y === 0) { return new UI.Geometry.Point(0, 0); + } return line.scale((this.x * line.x + this.y * line.y) / (Math.pow(line.x, 2) + Math.pow(line.y, 2))); } @@ -134,8 +136,9 @@ static parse(text) { const keywordValues = UI.Geometry.CubicBezier.KeywordValues; const value = text.toLowerCase().replace(/\s+/g, ''); - if (Object.keys(keywordValues).indexOf(value) !== -1) + if (Object.keys(keywordValues).indexOf(value) !== -1) { return UI.Geometry.CubicBezier.parse(keywordValues[value]); + } const bezierRegex = /^cubic-bezier\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/; const match = value.match(bezierRegex); if (match) { @@ -172,8 +175,9 @@ const raw = 'cubic-bezier(' + this.controlPoints.join(', ') + ')'; const keywordValues = UI.Geometry.CubicBezier.KeywordValues; for (const keyword in keywordValues) { - if (raw === keywordValues[keyword]) + if (raw === keywordValues[keyword]) { return keyword; + } } return raw; } @@ -288,11 +292,13 @@ UI.Geometry.calculateAngle = function(u, v) { const uLength = u.length(); const vLength = v.length(); - if (uLength <= UI.Geometry._Eps || vLength <= UI.Geometry._Eps) + if (uLength <= UI.Geometry._Eps || vLength <= UI.Geometry._Eps) { return 0; + } const cos = UI.Geometry.scalarProduct(u, v) / uLength / vLength; - if (Math.abs(cos) > 1) + if (Math.abs(cos) > 1) { return 0; + } return UI.Geometry.radiansToDegrees(Math.acos(cos)); }; @@ -319,10 +325,12 @@ * @return {!{minX: number, maxX: number, minY: number, maxY: number}} */ UI.Geometry.boundsForTransformedPoints = function(matrix, points, aggregateBounds) { - if (!aggregateBounds) + if (!aggregateBounds) { aggregateBounds = {minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity}; - if (points.length % 3) + } + if (points.length % 3) { console.assert('Invalid size of points array'); + } for (let p = 0; p < points.length; p += 3) { let vector = new UI.Geometry.Vector(points[p], points[p + 1], points[p + 2]); vector = UI.Geometry.multiplyVectorByMatrixAndNormalize(vector, matrix); @@ -352,8 +360,9 @@ * @return {!UI.Size} */ clipTo(size) { - if (!size) + if (!size) { return this; + } return new UI.Size(Math.min(this.width, size.width), Math.min(this.height, size.height)); } @@ -510,8 +519,9 @@ */ this.preferred = preferred || this.minimum; - if (this.minimum.width > this.preferred.width || this.minimum.height > this.preferred.height) + if (this.minimum.width > this.preferred.width || this.minimum.height > this.preferred.height) { throw new Error('Minimum size is greater than preferred.'); + } } }; @@ -528,8 +538,9 @@ * @return {!UI.Constraints} */ UI.Constraints.prototype.widthToMax = function(value) { - if (typeof value === 'number') + if (typeof value === 'number') { return new UI.Constraints(this.minimum.widthToMax(value), this.preferred.widthToMax(value)); + } return new UI.Constraints(this.minimum.widthToMax(value.minimum), this.preferred.widthToMax(value.preferred)); }; @@ -538,8 +549,9 @@ * @return {!UI.Constraints} */ UI.Constraints.prototype.addWidth = function(value) { - if (typeof value === 'number') + if (typeof value === 'number') { return new UI.Constraints(this.minimum.addWidth(value), this.preferred.addWidth(value)); + } return new UI.Constraints(this.minimum.addWidth(value.minimum), this.preferred.addWidth(value.preferred)); }; @@ -548,8 +560,9 @@ * @return {!UI.Constraints} */ UI.Constraints.prototype.heightToMax = function(value) { - if (typeof value === 'number') + if (typeof value === 'number') { return new UI.Constraints(this.minimum.heightToMax(value), this.preferred.heightToMax(value)); + } return new UI.Constraints(this.minimum.heightToMax(value.minimum), this.preferred.heightToMax(value.preferred)); }; @@ -558,7 +571,8 @@ * @return {!UI.Constraints} */ UI.Constraints.prototype.addHeight = function(value) { - if (typeof value === 'number') + if (typeof value === 'number') { return new UI.Constraints(this.minimum.addHeight(value), this.preferred.addHeight(value)); + } return new UI.Constraints(this.minimum.addHeight(value.minimum), this.preferred.addHeight(value.preferred)); };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/GlassPane.js b/third_party/blink/renderer/devtools/front_end/ui/GlassPane.js index 6c06f67e..b6c2528d 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/GlassPane.js +++ b/third_party/blink/renderer/devtools/front_end/ui/GlassPane.js
@@ -130,8 +130,9 @@ * @param {!Document} document */ show(document) { - if (this.isShowing()) + if (this.isShowing()) { return; + } // Deliberately starts with 3000 to hide other z-indexed elements below. this.element.style.zIndex = 3000 + 1000 * UI.GlassPane._panes.size; document.body.addEventListener('mousedown', this._onMouseDownBound, true); @@ -141,8 +142,9 @@ } hide() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } UI.GlassPane._panes.delete(this); this.element.ownerDocument.body.removeEventListener('mousedown', this._onMouseDownBound, true); this._widget.detach(); @@ -152,17 +154,20 @@ * @param {!Event} event */ _onMouseDown(event) { - if (!this._onClickOutsideCallback) + if (!this._onClickOutsideCallback) { return; + } const node = event.deepElementFromPoint(); - if (!node || this.contentElement.isSelfOrAncestor(node)) + if (!node || this.contentElement.isSelfOrAncestor(node)) { return; + } this._onClickOutsideCallback.call(null, event); } _positionContent() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const showArrow = this._marginBehavior === UI.GlassPane.MarginBehavior.Arrow; const gutterSize = showArrow ? 8 : (this._marginBehavior === UI.GlassPane.MarginBehavior.NoMargin ? 0 : 3); @@ -207,10 +212,12 @@ if (behavior === UI.GlassPane.AnchorBehavior.PreferTop || behavior === UI.GlassPane.AnchorBehavior.PreferBottom) { const top = anchorBox.y - 2 * gutterSize; const bottom = containerHeight - anchorBox.y - anchorBox.height - 2 * gutterSize; - if (behavior === UI.GlassPane.AnchorBehavior.PreferTop && top < height && bottom > top) + if (behavior === UI.GlassPane.AnchorBehavior.PreferTop && top < height && bottom > top) { behavior = UI.GlassPane.AnchorBehavior.PreferBottom; - if (behavior === UI.GlassPane.AnchorBehavior.PreferBottom && bottom < height && top > bottom) + } + if (behavior === UI.GlassPane.AnchorBehavior.PreferBottom && bottom < height && top > bottom) { behavior = UI.GlassPane.AnchorBehavior.PreferTop; + } let arrowY; let enoughHeight = true; @@ -246,10 +253,11 @@ } positionX = Math.max(gutterSize, Math.min(anchorBox.x, containerWidth - width - gutterSize)); - if (!enoughHeight) + if (!enoughHeight) { positionX = Math.min(positionX + arrowSize, containerWidth - width - gutterSize); - else if (showArrow && positionX - arrowSize >= gutterSize) + } else if (showArrow && positionX - arrowSize >= gutterSize) { positionX -= arrowSize; + } width = Math.min(width, containerWidth - positionX - gutterSize); if (2 * arrowSize >= width) { this._arrowElement.classList.add('arrow-none'); @@ -261,10 +269,12 @@ } else { const left = anchorBox.x - 2 * gutterSize; const right = containerWidth - anchorBox.x - anchorBox.width - 2 * gutterSize; - if (behavior === UI.GlassPane.AnchorBehavior.PreferLeft && left < width && right > left) + if (behavior === UI.GlassPane.AnchorBehavior.PreferLeft && left < width && right > left) { behavior = UI.GlassPane.AnchorBehavior.PreferRight; - if (behavior === UI.GlassPane.AnchorBehavior.PreferRight && right < width && left > right) + } + if (behavior === UI.GlassPane.AnchorBehavior.PreferRight && right < width && left > right) { behavior = UI.GlassPane.AnchorBehavior.PreferLeft; + } let arrowX; let enoughWidth = true; @@ -300,10 +310,11 @@ } positionY = Math.max(gutterSize, Math.min(anchorBox.y, containerHeight - height - gutterSize)); - if (!enoughWidth) + if (!enoughWidth) { positionY = Math.min(positionY + arrowSize, containerHeight - height - gutterSize); - else if (showArrow && positionY - arrowSize >= gutterSize) + } else if (showArrow && positionY - arrowSize >= gutterSize) { positionY -= arrowSize; + } height = Math.min(height, containerHeight - positionY - gutterSize); if (2 * arrowSize >= height) { this._arrowElement.classList.add('arrow-none'); @@ -322,10 +333,11 @@ } this.contentElement.style.width = width + 'px'; - if (this._sizeBehavior === UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight) + if (this._sizeBehavior === UI.GlassPane.SizeBehavior.SetExactWidthMaxHeight) { this.contentElement.style.maxHeight = height + 'px'; - else + } else { this.contentElement.style.height = height + 'px'; + } this.contentElement.positionAt(positionX, positionY, container); this._widget.doResize(); @@ -360,8 +372,9 @@ */ static containerMoved(element) { for (const pane of UI.GlassPane._panes) { - if (pane.isShowing() && pane.element.ownerDocument === element.ownerDocument) + if (pane.isShowing() && pane.element.ownerDocument === element.ownerDocument) { pane._positionContent(); + } } } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/HistoryInput.js b/third_party/blink/renderer/devtools/front_end/ui/HistoryInput.js index 81784fc..d04cfc5 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/HistoryInput.js +++ b/third_party/blink/renderer/devtools/front_end/ui/HistoryInput.js
@@ -16,8 +16,9 @@ * @return {!UI.HistoryInput} */ static create() { - if (!UI.HistoryInput._constructor) + if (!UI.HistoryInput._constructor) { UI.HistoryInput._constructor = UI.registerCustomElement('input', 'history-input', UI.HistoryInput); + } return /** @type {!UI.HistoryInput} */ (UI.HistoryInput._constructor()); } @@ -26,8 +27,9 @@ * @param {!Event} event */ _onInput(event) { - if (this._history.length === this._historyPosition + 1) + if (this._history.length === this._historyPosition + 1) { this._history[this._history.length - 1] = this.value; + } } /** @@ -50,8 +52,9 @@ } _saveToHistory() { - if (this._history.length > 1 && this._history[this._history.length - 2] === this.value) + if (this._history.length > 1 && this._history[this._history.length - 2] === this.value) { return; + } this._history[this._history.length - 1] = this.value; this._historyPosition = this._history.length - 1; this._history.push('');
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Icon.js b/third_party/blink/renderer/devtools/front_end/ui/Icon.js index a7ef018..49137e97 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Icon.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Icon.js
@@ -19,14 +19,17 @@ * @return {!UI.Icon} */ static create(iconType, className) { - if (!UI.Icon._constructor) + if (!UI.Icon._constructor) { UI.Icon._constructor = UI.registerCustomElement('span', 'ui-icon', UI.Icon); + } const icon = /** @type {!UI.Icon} */ (UI.Icon._constructor()); - if (className) + if (className) { icon.className = className; - if (iconType) + } + if (iconType) { icon.setIconType(iconType); + } return icon; } @@ -75,8 +78,9 @@ */ _propertyValue() { if (!this._descriptor.coordinates) { - if (!this._descriptor.position || !UI.Icon._positionRegex.test(this._descriptor.position)) + if (!this._descriptor.position || !UI.Icon._positionRegex.test(this._descriptor.position)) { throw new Error(`ERROR: icon '${this._iconType}' has malformed position: '${this._descriptor.position}'`); + } const column = this._descriptor.position[0].toLowerCase().charCodeAt(0) - 97; const row = parseInt(this._descriptor.position.substring(1), 10) - 1; this._descriptor.coordinates = {
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Infobar.js b/third_party/blink/renderer/devtools/front_end/ui/Infobar.js index b6523a0..f09cade 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Infobar.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Infobar.js
@@ -47,16 +47,18 @@ * @return {?UI.Infobar} */ static create(type, text, disableSetting) { - if (disableSetting && disableSetting.get()) + if (disableSetting && disableSetting.get()) { return null; + } return new UI.Infobar(type, text, disableSetting); } dispose() { this.element.remove(); this._onResize(); - if (this._closeCallback) + if (this._closeCallback) { this._closeCallback.call(null); + } } /** @@ -82,8 +84,9 @@ } _onResize() { - if (this._parentView) + if (this._parentView) { this._parentView.doResize(); + } } _onDisable() {
diff --git a/third_party/blink/renderer/devtools/front_end/ui/InplaceEditor.js b/third_party/blink/renderer/devtools/front_end/ui/InplaceEditor.js index 31e4f83..4a61ff1 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/InplaceEditor.js +++ b/third_party/blink/renderer/devtools/front_end/ui/InplaceEditor.js
@@ -11,8 +11,9 @@ * @return {?UI.InplaceEditor.Controller} */ static startEditing(element, config) { - if (!UI.InplaceEditor._defaultInstance) + if (!UI.InplaceEditor._defaultInstance) { UI.InplaceEditor._defaultInstance = new UI.InplaceEditor(); + } return UI.InplaceEditor._defaultInstance.startEditing(element, config); } @@ -21,8 +22,9 @@ */ editorContent(editingContext) { const element = editingContext.element; - if (element.tagName === 'INPUT' && element.type === 'text') + if (element.tagName === 'INPUT' && element.type === 'text') { return element.value; + } return element.textContent; } @@ -37,8 +39,9 @@ editingContext.oldRole = oldRole; const oldTabIndex = element.getAttribute('tabIndex'); - if (typeof oldTabIndex !== 'number' || oldTabIndex < 0) + if (typeof oldTabIndex !== 'number' || oldTabIndex < 0) { element.tabIndex = 0; + } this._focusRestorer = new UI.ElementFocusRestorer(element); editingContext.oldTabIndex = oldTabIndex; } @@ -48,25 +51,28 @@ element.classList.remove('editing'); element.removeAttribute('contenteditable'); - if (typeof editingContext.oldRole !== 'string') + if (typeof editingContext.oldRole !== 'string') { element.removeAttribute('role'); - else + } else { element.role = editingContext.oldRole; + } - if (typeof editingContext.oldTabIndex !== 'number') + if (typeof editingContext.oldTabIndex !== 'number') { element.removeAttribute('tabIndex'); - else + } else { element.tabIndex = editingContext.oldTabIndex; + } element.scrollTop = 0; element.scrollLeft = 0; } cancelEditing(editingContext) { const element = editingContext.element; - if (element.tagName === 'INPUT' && element.type === 'text') + if (element.tagName === 'INPUT' && element.type === 'text') { element.value = editingContext.oldText; - else + } else { element.textContent = editingContext.oldText; + } } augmentEditingHandle(editingContext, handle) { @@ -78,8 +84,9 @@ * @return {?UI.InplaceEditor.Controller} */ startEditing(element, config) { - if (!UI.markBeingEdited(element, true)) + if (!UI.markBeingEdited(element, true)) { return null; + } config = config || new UI.InplaceEditor.Config(function() {}, function() {}); const editingContext = {element: element, config: config}; @@ -98,8 +105,9 @@ * @param {!Event=} e */ function blurEventListener(e) { - if (config.blurHandler && !config.blurHandler(element, e)) + if (config.blurHandler && !config.blurHandler(element, e)) { return; + } editingCommitted.call(element); } @@ -108,11 +116,13 @@ element.removeEventListener('blur', blurEventListener, false); element.removeEventListener('keydown', keyDownEventListener, true); - if (pasteCallback) + if (pasteCallback) { element.removeEventListener('paste', pasteEventListener, true); + } - if (self._focusRestorer) + if (self._focusRestorer) { self._focusRestorer.restore(); + } self.closeEditor(editingContext); } @@ -135,12 +145,13 @@ * @return {string} */ function defaultFinishHandler(event) { - if (isEnterKey(event)) + if (isEnterKey(event)) { return 'commit'; - else if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code || event.key === 'Escape') + } else if (event.keyCode === UI.KeyboardShortcut.Keys.Esc.code || event.key === 'Escape') { return 'cancel'; - else if (event.key === 'Tab') + } else if (event.key === 'Tab') { return 'move-' + (event.shiftKey ? 'backward' : 'forward'); + } return ''; } @@ -153,8 +164,9 @@ event.consume(true); } else if (result && result.startsWith('move-')) { moveDirection = result.substring(5); - if (event.key === 'Tab') + if (event.key === 'Tab') { event.consume(true); + } blurEventListener(); } } @@ -172,15 +184,17 @@ */ function keyDownEventListener(event) { let result = defaultFinishHandler(event); - if (!result && config.postKeydownFinishHandler) + if (!result && config.postKeydownFinishHandler) { result = config.postKeydownFinishHandler(event); + } handleEditingResult(result, event); } element.addEventListener('blur', blurEventListener, false); element.addEventListener('keydown', keyDownEventListener, true); - if (pasteCallback) + if (pasteCallback) { element.addEventListener('paste', pasteEventListener, true); + } const handle = {cancel: editingCancelled.bind(element), commit: editingCommitted.bind(element)}; this.augmentEditingHandle(editingContext, handle);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js b/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js index 960c308d..7337570 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js +++ b/third_party/blink/renderer/devtools/front_end/ui/InspectorView.js
@@ -88,8 +88,9 @@ // Store the initial selected panel for use in launch histograms Host.userMetrics.setLaunchPanel(this._tabbedPane.selectedTabId); - if (Host.isUnderTest()) + if (Host.isUnderTest()) { this._tabbedPane.setAutoSelectFirstItemOnShow(false); + } this._drawerSplitWidget.setMainWidget(this._tabbedPane); this._keyDownBound = this._keyDown.bind(this); @@ -132,12 +133,15 @@ * @return {?UI.ViewLocation} */ resolveLocation(locationName) { - if (locationName === 'drawer-view') + if (locationName === 'drawer-view') { return this._drawerTabbedLocation; - if (locationName === 'panel') + } + if (locationName === 'panel') { return this._tabbedLocation; - if (locationName === 'drawer-sidebar') + } + if (locationName === 'drawer-sidebar') { return this._drawerSidebarTabbedLocation; + } return null; } @@ -214,13 +218,15 @@ * @param {boolean} focus */ _showDrawer(focus) { - if (this._drawerTabbedPane.isShowing()) + if (this._drawerTabbedPane.isShowing()) { return; + } this._drawerSplitWidget.showBoth(); - if (focus) + if (focus) { this._focusRestorer = new UI.WidgetFocusRestorer(this._drawerTabbedPane); - else + } else { this._focusRestorer = null; + } } /** @@ -231,10 +237,12 @@ } _closeDrawer() { - if (!this._drawerTabbedPane.isShowing()) + if (!this._drawerTabbedPane.isShowing()) { return; - if (this._focusRestorer) + } + if (this._focusRestorer) { this._focusRestorer.restore(); + } this._drawerSplitWidget.hideSidebar(true); } @@ -266,24 +274,27 @@ */ _keyDown(event) { const keyboardEvent = /** @type {!KeyboardEvent} */ (event); - if (!UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent) || event.altKey || event.shiftKey) + if (!UI.KeyboardShortcut.eventHasCtrlOrMeta(keyboardEvent) || event.altKey || event.shiftKey) { return; + } // Ctrl/Cmd + 1-9 should show corresponding panel. const panelShortcutEnabled = Common.moduleSetting('shortcutPanelSwitch').get(); if (panelShortcutEnabled) { let panelIndex = -1; - if (event.keyCode > 0x30 && event.keyCode < 0x3A) + if (event.keyCode > 0x30 && event.keyCode < 0x3A) { panelIndex = event.keyCode - 0x31; - else if ( + } else if ( event.keyCode > 0x60 && event.keyCode < 0x6A && - keyboardEvent.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD) + keyboardEvent.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD) { panelIndex = event.keyCode - 0x61; + } if (panelIndex !== -1) { const panelName = this._tabbedPane.tabIds()[panelIndex]; if (panelName) { - if (!UI.Dialog.hasInstance() && !this._currentPanelLocked) + if (!UI.Dialog.hasInstance() && !this._currentPanelLocked) { this.showPanel(panelName); + } event.consume(true); } } @@ -332,13 +343,15 @@ } minimize() { - if (this._ownerSplitWidget) + if (this._ownerSplitWidget) { this._ownerSplitWidget.setSidebarMinimized(true); + } } restore() { - if (this._ownerSplitWidget) + if (this._ownerSplitWidget) { this._ownerSplitWidget.setSidebarMinimized(false); + } } }; @@ -362,10 +375,11 @@ handleAction(context, actionId) { switch (actionId) { case 'main.toggle-drawer': - if (UI.inspectorView.drawerVisible()) + if (UI.inspectorView.drawerVisible()) { UI.inspectorView._closeDrawer(); - else + } else { UI.inspectorView._showDrawer(true); + } return true; case 'main.next-tab': UI.inspectorView._tabbedPane.selectNextTab();
diff --git a/third_party/blink/renderer/devtools/front_end/ui/KeyboardShortcut.js b/third_party/blink/renderer/devtools/front_end/ui/KeyboardShortcut.js index baa5271..5bdc6b7 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/KeyboardShortcut.js +++ b/third_party/blink/renderer/devtools/front_end/ui/KeyboardShortcut.js
@@ -40,8 +40,9 @@ * @return {number} */ static makeKey(keyCode, modifiers) { - if (typeof keyCode === 'string') + if (typeof keyCode === 'string') { keyCode = keyCode.charCodeAt(0) - (/^[a-z]/.test(keyCode) ? 32 : 0); + } modifiers = modifiers || UI.KeyboardShortcut.Modifiers.None; return UI.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, modifiers); } @@ -52,14 +53,18 @@ */ static makeKeyFromEvent(keyboardEvent) { let modifiers = UI.KeyboardShortcut.Modifiers.None; - if (keyboardEvent.shiftKey) + if (keyboardEvent.shiftKey) { modifiers |= UI.KeyboardShortcut.Modifiers.Shift; - if (keyboardEvent.ctrlKey) + } + if (keyboardEvent.ctrlKey) { modifiers |= UI.KeyboardShortcut.Modifiers.Ctrl; - if (keyboardEvent.altKey) + } + if (keyboardEvent.altKey) { modifiers |= UI.KeyboardShortcut.Modifiers.Alt; - if (keyboardEvent.metaKey) + } + if (keyboardEvent.metaKey) { modifiers |= UI.KeyboardShortcut.Modifiers.Meta; + } // Use either a real or a synthetic keyCode (for events originating from extensions). const keyCode = keyboardEvent.keyCode || keyboardEvent['__keyCode']; @@ -122,12 +127,14 @@ break; } console.assert(keyString, 'Modifiers-only shortcuts are not allowed (encountered <' + shortcut + '>)'); - if (!keyString) + if (!keyString) { return null; + } const key = UI.KeyboardShortcut.Keys[keyString] || UI.KeyboardShortcut.KeyBindings[keyString]; - if (key && key.shiftKey) + if (key && key.shiftKey) { modifiers |= UI.KeyboardShortcut.Modifiers.Shift; + } return UI.KeyboardShortcut.makeDescriptor(key ? key : keyString, modifiers); } @@ -145,10 +152,12 @@ * @return {string} */ static _keyName(key) { - if (typeof key === 'string') + if (typeof key === 'string') { return key.toUpperCase(); - if (typeof key.name === 'string') + } + if (typeof key.name === 'string') { return key.name; + } return key.name[Host.platform()] || key.name.other || ''; }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ListControl.js b/third_party/blink/renderer/devtools/front_end/ui/ListControl.js index b85f52de..3ab1c9b 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ListControl.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ListControl.js
@@ -112,8 +112,9 @@ const oldSelectedItem = this._selectedItem; const oldSelectedElement = oldSelectedItem ? (this._itemToElement.get(oldSelectedItem) || null) : null; - for (let i = 0; i < data.removed.length; i++) + for (let i = 0; i < data.removed.length; i++) { this._itemToElement.delete(data.removed[i]); + } this._invalidate(from, to, data.inserted); if (this._selectedIndex >= to) { @@ -121,8 +122,9 @@ this._selectedItem = this._model.at(this._selectedIndex); } else if (this._selectedIndex >= from) { let index = this._findFirstSelectable(from + data.inserted, +1, false); - if (index === -1) + if (index === -1) { index = this._findFirstSelectable(from - 1, -1, false); + } this._select(index, oldSelectedItem, oldSelectedElement); } } @@ -146,8 +148,9 @@ const item = this._model.at(index); this._itemToElement.delete(item); this.invalidateRange(index, index + 1); - if (this._selectedIndex !== -1) + if (this._selectedIndex !== -1) { this._select(this._selectedIndex, null, null); + } } /** @@ -159,8 +162,9 @@ } viewportResized() { - if (this._mode === UI.ListMode.NonViewport) + if (this._mode === UI.ListMode.NonViewport) { return; + } // TODO(dgozman): try to keep visible scrollTop the same. const scrollTop = this.element.scrollTop; const viewportHeight = this.element.offsetHeight; @@ -185,10 +189,12 @@ * @return {?T} */ itemForNode(node) { - while (node && node.parentNodeOrShadowHost() !== this.element) + while (node && node.parentNodeOrShadowHost() !== this.element) { node = node.parentNodeOrShadowHost(); - if (!node) + } + if (!node) { return null; + } const element = /** @type {!Element} */ (node); const index = this._model.findIndex(item => this._itemToElement.get(item) === element); return index !== -1 ? this._model.at(index) : null; @@ -240,10 +246,12 @@ } } // Scrolling the item before selection ensures it is in the DOM. - if (index !== -1 && !dontScroll) + if (index !== -1 && !dontScroll) { this._scrollIntoView(index, center); - if (this._selectedIndex !== index) + } + if (this._selectedIndex !== index) { this._select(index); + } } /** @@ -252,8 +260,9 @@ * @return {boolean} */ selectPreviousItem(canWrap, center) { - if (this._selectedIndex === -1 && !canWrap) + if (this._selectedIndex === -1 && !canWrap) { return false; + } let index = this._selectedIndex === -1 ? this._model.length - 1 : this._selectedIndex - 1; index = this._findFirstSelectable(index, -1, !!canWrap); if (index !== -1) { @@ -270,8 +279,9 @@ * @return {boolean} */ selectNextItem(canWrap, center) { - if (this._selectedIndex === -1 && !canWrap) + if (this._selectedIndex === -1 && !canWrap) { return false; + } let index = this._selectedIndex === -1 ? 0 : this._selectedIndex + 1; index = this._findFirstSelectable(index, +1, !!canWrap); if (index !== -1) { @@ -287,8 +297,9 @@ * @return {boolean} */ selectItemPreviousPage(center) { - if (this._mode === UI.ListMode.NonViewport) + if (this._mode === UI.ListMode.NonViewport) { return false; + } let index = this._selectedIndex === -1 ? this._model.length - 1 : this._selectedIndex; index = this._findPageSelectable(index, -1); if (index !== -1) { @@ -304,8 +315,9 @@ * @return {boolean} */ selectItemNextPage(center) { - if (this._mode === UI.ListMode.NonViewport) + if (this._mode === UI.ListMode.NonViewport) { return false; + } let index = this._selectedIndex === -1 ? 0 : this._selectedIndex; index = this._findPageSelectable(index, +1); if (index !== -1) { @@ -336,10 +348,11 @@ } const scrollTop = this.element.scrollTop; - if (top < scrollTop) + if (top < scrollTop) { this._updateViewport(top, viewportHeight); - else if (bottom > scrollTop + viewportHeight) + } else if (bottom > scrollTop + viewportHeight) { this._updateViewport(bottom - viewportHeight, viewportHeight); + } } /** @@ -347,8 +360,9 @@ */ _onClick(event) { const item = this.itemForNode(/** @type {?Node} */ (event.target)); - if (item && this._delegate.isItemSelectable(item)) + if (item && this._delegate.isItemSelectable(item)) { this.selectItem(item); + } } /** @@ -370,8 +384,9 @@ selected = this.selectItemNextPage(false); break; } - if (selected) + if (selected) { event.consume(); + } } /** @@ -386,16 +401,19 @@ * @return {number} */ _indexAtOffset(offset) { - if (this._mode === UI.ListMode.NonViewport) + if (this._mode === UI.ListMode.NonViewport) { throw 'There should be no offset conversions in non-viewport mode'; - if (!this._model.length || offset < 0) + } + if (!this._model.length || offset < 0) { return 0; + } if (this._mode === UI.ListMode.VariousHeightItems) { return Math.min( this._model.length - 1, this._variableOffsets.lowerBound(offset, undefined, 0, this._model.length)); } - if (!this._fixedHeight) + if (!this._fixedHeight) { this._measureHeight(); + } return Math.min(this._model.length - 1, Math.floor(offset / this._fixedHeight)); } @@ -418,21 +436,26 @@ * @return {number} */ _offsetAtIndex(index) { - if (this._mode === UI.ListMode.NonViewport) + if (this._mode === UI.ListMode.NonViewport) { throw 'There should be no offset conversions in non-viewport mode'; - if (!this._model.length) + } + if (!this._model.length) { return 0; - if (this._mode === UI.ListMode.VariousHeightItems) + } + if (this._mode === UI.ListMode.VariousHeightItems) { return this._variableOffsets[index]; - if (!this._fixedHeight) + } + if (!this._fixedHeight) { this._measureHeight(); + } return index * this._fixedHeight; } _measureHeight() { this._fixedHeight = this._delegate.heightForItem(this._model.at(0)); - if (!this._fixedHeight) + if (!this._fixedHeight) { this._fixedHeight = UI.measurePreferredSize(this._elementAtIndex(0), this.element).height; + } } /** @@ -441,18 +464,22 @@ * @param {?Element=} oldElement */ _select(index, oldItem, oldElement) { - if (oldItem === undefined) + if (oldItem === undefined) { oldItem = this._selectedItem; - if (oldElement === undefined) + } + if (oldElement === undefined) { oldElement = this._itemToElement.get(oldItem) || null; + } this._selectedIndex = index; this._selectedItem = index === -1 ? null : this._model.at(index); const newItem = this._selectedItem; const newElement = this._selectedIndex !== -1 ? this._elementAtIndex(index) : null; - if (oldElement) + if (oldElement) { UI.ARIAUtils.setSelected(oldElement, false); - if (newElement) + } + if (newElement) { UI.ARIAUtils.setSelected(newElement, true); + } UI.ARIAUtils.setActiveDescendant(this.element, newElement); this._delegate.selectedItemChanged(oldItem, newItem, /** @type {?Element} */ (oldElement), newElement); } @@ -465,16 +492,19 @@ */ _findFirstSelectable(index, direction, canWrap) { const length = this._model.length; - if (!length) + if (!length) { return -1; + } for (let step = 0; step <= length; step++) { if (index < 0 || index >= length) { - if (!canWrap) + if (!canWrap) { return -1; + } index = (index + length) % length; } - if (this._delegate.isItemSelectable(this._model.at(index))) + if (this._delegate.isItemSelectable(this._model.at(index))) { return index; + } index += direction; } return -1; @@ -492,8 +522,9 @@ const viewportHeight = this.element.offsetHeight - 1; while (index >= 0 && index < this._model.length) { if (this._delegate.isItemSelectable(this._model.at(index))) { - if (Math.abs(this._offsetAtIndex(index) - startOffset) >= viewportHeight) + if (Math.abs(this._offsetAtIndex(index) - startOffset) >= viewportHeight) { return index; + } lastSelectable = index; } index += direction; @@ -530,8 +561,9 @@ if (this._mode === UI.ListMode.VariousHeightItems) { this._reallocateVariableOffsets(this._model.length + 1, from + 1); - for (let i = from + 1; i <= this._model.length; i++) + for (let i = from + 1; i <= this._model.length; i++) { this._variableOffsets[i] = this._variableOffsets[i - 1] + this._delegate.heightForItem(this._model.at(i - 1)); + } } const viewportHeight = this.element.offsetHeight; @@ -578,12 +610,15 @@ */ _invalidateNonViewportMode(start, remove, add) { let startElement = this._topElement; - for (let index = 0; index < start; index++) + for (let index = 0; index < start; index++) { startElement = startElement.nextElementSibling; - while (remove--) + } + while (remove--) { startElement.nextElementSibling.remove(); - while (add--) + } + while (add--) { this.element.insertBefore(this._elementAtIndex(start + add), startElement.nextElementSibling); + } } _clearViewport() {
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ListWidget.js b/third_party/blink/renderer/devtools/front_end/ui/ListWidget.js index 119b60d..11e9989 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ListWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ListWidget.js
@@ -52,8 +52,9 @@ * @param {boolean} editable */ appendItem(item, editable) { - if (this._lastSeparator && this._items.length) + if (this._lastSeparator && this._items.length) { this._list.appendChild(createElementWithClass('div', 'list-separator')); + } this._lastSeparator = false; this._items.push(item); @@ -77,8 +78,9 @@ * @param {number} index */ removeItem(index) { - if (this._editItem === this._items[index]) + if (this._editItem === this._items[index]) { this._stopEditing(); + } const element = this._elements[index]; @@ -88,10 +90,12 @@ const next = element.nextElementSibling; const nextIsSeparator = next && next.classList.contains('list-separator'); - if (previousIsSeparator && (nextIsSeparator || !next)) + if (previousIsSeparator && (nextIsSeparator || !next)) { previous.remove(); - if (nextIsSeparator && !previous) + } + if (nextIsSeparator && !previous) { next.remove(); + } element.remove(); this._elements.splice(index, 1); @@ -167,13 +171,15 @@ } _updatePlaceholder() { - if (!this._emptyPlaceholder) + if (!this._emptyPlaceholder) { return; + } - if (!this._elements.length && !this._editor) + if (!this._elements.length && !this._editor) { this._list.appendChild(this._emptyPlaceholder); - else + } else { this._emptyPlaceholder.remove(); + } } /** @@ -182,8 +188,9 @@ * @param {?Element} insertionPoint */ _startEditing(item, element, insertionPoint) { - if (element && this._editElement === element) + if (element && this._editElement === element) { return; + } this._stopEditing(); this._focusRestorer = new UI.ElementFocusRestorer(this.element); @@ -191,8 +198,9 @@ this._list.classList.add('list-editing'); this._editItem = item; this._editElement = element; - if (element) + if (element) { element.classList.add('hidden'); + } const index = element ? this._elements.indexOf(element) : -1; this._editor = this._delegate.beginEdit(item); @@ -213,12 +221,15 @@ _stopEditing() { this._list.classList.remove('list-editing'); - if (this._focusRestorer) + if (this._focusRestorer) { this._focusRestorer.restore(); - if (this._editElement) + } + if (this._editElement) { this._editElement.classList.remove('hidden'); - if (this._editor && this._editor.element.parentElement) + } + if (this._editor && this._editor.element.parentElement) { this._editor.element.remove(); + } this._editor = null; this._editItem = null; @@ -383,13 +394,15 @@ const {valid, errorMessage} = this._validators[index].call(null, this._item, this._index, input); input.classList.toggle('error-input', !valid && !forceValid); - if (valid || forceValid) + if (valid || forceValid) { UI.ARIAUtils.setInvalid(input, false); - else + } else { UI.ARIAUtils.setInvalid(input, true); + } - if (!forceValid && errorMessage && !this._errorMessageContainer.textContent) + if (!forceValid && errorMessage && !this._errorMessageContainer.textContent) { this._errorMessageContainer.textContent = errorMessage; + } allValid &= valid; } @@ -411,14 +424,16 @@ this._commitButton.textContent = commitButtonTitle; this.element.scrollIntoViewIfNeeded(false); - if (this._controls.length) + if (this._controls.length) { this._controls[0].focus(); + } this._validateControls(true); } _commitClicked() { - if (this._commitButton.disabled) + if (this._commitButton.disabled) { return; + } const commit = this._commit; this._commit = null;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Panel.js b/third_party/blink/renderer/devtools/front_end/ui/Panel.js index 30f0ad3..5bcacc0 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Panel.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Panel.js
@@ -71,10 +71,11 @@ */ showInfobar(infobar) { infobar.setCloseCallback(this._onInfobarClosed.bind(this, infobar)); - if (this.element.firstChild) + if (this.element.firstChild) { this.element.insertBefore(infobar.element, this.element.firstChild); - else + } else { this.element.appendChild(infobar.element); + } infobar.setParentView(this); this.doResize(); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Popover.js b/third_party/blink/renderer/devtools/front_end/ui/Popover.js index b8ba3bd..3295fb5 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Popover.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Popover.js
@@ -95,8 +95,9 @@ this.hidePopover(); return; } - if (this._eventInScheduledContent(event)) + if (this._eventInScheduledContent(event)) { return; + } this._startHidePopoverTimer(0); this._stopShowPopoverTimer(); @@ -108,13 +109,15 @@ */ _mouseMove(event) { // Pretend that nothing has happened. - if (this._eventInScheduledContent(event)) + if (this._eventInScheduledContent(event)) { return; + } this._startHidePopoverTimer(this._hideTimeout); this._stopShowPopoverTimer(); - if (event.which && this._disableOnClick) + if (event.which && this._disableOnClick) { return; + } this._startShowPopoverTimer( /** @type {!MouseEvent} */ (event), this.isPopoverVisible() ? this._showTimeout * 0.6 : this._showTimeout); } @@ -131,20 +134,24 @@ * @param {!Event} event */ _popoverMouseOut(popover, event) { - if (!popover.isShowing()) + if (!popover.isShowing()) { return; - if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(popover.contentElement)) + } + if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(popover.contentElement)) { this._startHidePopoverTimer(this._hideTimeout); + } } /** * @param {!Event} event */ _mouseOut(event) { - if (!this.isPopoverVisible()) + if (!this.isPopoverVisible()) { return; - if (!this._eventInScheduledContent(event)) + } + if (!this._eventInScheduledContent(event)) { this._startHidePopoverTimer(this._hideTimeout); + } } /** @@ -152,8 +159,9 @@ */ _startHidePopoverTimer(timeout) { // User has |timeout| ms to reach the popup. - if (!this._hidePopoverCallback || this._hidePopoverTimer) + if (!this._hidePopoverCallback || this._hidePopoverTimer) { return; + } this._hidePopoverTimer = setTimeout(() => { this._hidePopover(); @@ -167,8 +175,9 @@ */ _startShowPopoverTimer(event, timeout) { this._scheduledRequest = this._getRequest.call(null, event); - if (!this._scheduledRequest) + if (!this._scheduledRequest) { return; + } this._showPopoverTimer = setTimeout(() => { this._showPopoverTimer = null; @@ -179,8 +188,9 @@ } _stopShowPopoverTimer() { - if (!this._showPopoverTimer) + if (!this._showPopoverTimer) { return; + } clearTimeout(this._showPopoverTimer); this._showPopoverTimer = null; } @@ -198,8 +208,9 @@ } _hidePopover() { - if (!this._hidePopoverCallback) + if (!this._hidePopoverCallback) { return; + } this._hidePopoverCallback.call(null); this._hidePopoverCallback = null; } @@ -214,12 +225,14 @@ popover.setMarginBehavior(UI.GlassPane.MarginBehavior.Arrow); const request = this._scheduledRequest; request.show.call(null, popover).then(success => { - if (!success) + if (!success) { return; + } if (this._scheduledRequest !== request) { - if (request.hide) + if (request.hide) { request.hide.call(null); + } return; } @@ -237,8 +250,9 @@ popover.show(document); this._hidePopoverCallback = () => { - if (request.hide) + if (request.hide) { request.hide.call(null); + } popover.hide(); delete UI.PopoverHelper._popoverHelper; }; @@ -246,8 +260,9 @@ } _stopHidePopoverTimer() { - if (!this._hidePopoverTimer) + if (!this._hidePopoverTimer) { return; + } clearTimeout(this._hidePopoverTimer); this._hidePopoverTimer = null;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ProgressIndicator.js b/third_party/blink/renderer/devtools/front_end/ui/ProgressIndicator.js index 2c8bb284..ef72417 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ProgressIndicator.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ProgressIndicator.js
@@ -58,8 +58,9 @@ * @override */ done() { - if (this._isDone) + if (this._isDone) { return; + } this._isDone = true; this.element.remove(); } @@ -100,8 +101,9 @@ setWorked(worked, title) { this._worked = worked; this._progressElement.value = worked; - if (title) + if (title) { this.setTitle(title); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ReportView.js b/third_party/blink/renderer/devtools/front_end/ui/ReportView.js index ab90dc5..f033146 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ReportView.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ReportView.js
@@ -25,8 +25,9 @@ * @param {string} title */ setTitle(title) { - if (this._titleElement.textContent === title) + if (this._titleElement.textContent === title) { return; + } this._titleElement.textContent = title; } @@ -34,10 +35,12 @@ * @param {string} subtitle */ setSubtitle(subtitle) { - if (this._subtitleElement && this._subtitleElement.textContent === subtitle) + if (this._subtitleElement && this._subtitleElement.textContent === subtitle) { return; - if (!this._subtitleElement) + } + if (!this._subtitleElement) { this._subtitleElement = this._headerElement.createChild('div', 'report-subtitle'); + } this._subtitleElement.textContent = subtitle; } @@ -45,11 +48,13 @@ * @param {?Element} link */ setURL(link) { - if (!this._urlElement) + if (!this._urlElement) { this._urlElement = this._headerElement.createChild('div', 'report-url link'); + } this._urlElement.removeChildren(); - if (link) + if (link) { this._urlElement.appendChild(link); + } } /** @@ -78,13 +83,15 @@ sortSections(comparator) { const sections = /** @type {!Array<!UI.ReportView.Section>} */ (this.children().slice()); const sorted = sections.every((e, i, a) => !i || comparator(a[i - 1], a[i]) <= 0); - if (sorted) + if (sorted) { return; + } this.detachChildWidgets(); sections.sort(comparator); - for (const section of sections) + for (const section of sections) { section.show(this._sectionList); + } } /** @@ -114,8 +121,9 @@ constructor(title, className) { super(); this.element.classList.add('report-section'); - if (className) + if (className) { this.element.classList.add(className); + } this._headerElement = this.element.createChild('div', 'report-section-header'); this._titleElement = this._headerElement.createChild('div', 'report-section-title'); this.setTitle(title); @@ -136,8 +144,9 @@ * @param {string} title */ setTitle(title) { - if (this._titleElement.textContent !== title) + if (this._titleElement.textContent !== title) { this._titleElement.textContent = title; + } this._titleElement.classList.toggle('hidden', !this._titleElement.textContent); } @@ -163,8 +172,9 @@ this._fieldMap.set(title, row); row.createChild('div', 'report-field-value'); } - if (textValue) + if (textValue) { row.lastElementChild.textContent = textValue; + } return /** @type {!Element} */ (row.lastElementChild); } @@ -173,8 +183,9 @@ */ removeField(title) { const row = this._fieldMap.get(title); - if (row) + if (row) { row.remove(); + } this._fieldMap.delete(title); } @@ -184,8 +195,9 @@ */ setFieldVisible(title, visible) { const row = this._fieldMap.get(title); - if (row) + if (row) { row.classList.toggle('hidden', !visible); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ResizerWidget.js b/third_party/blink/renderer/devtools/front_end/ui/ResizerWidget.js index 6e3fbb3..bf345c7 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ResizerWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ResizerWidget.js
@@ -40,8 +40,9 @@ * @param {!Element} element */ addElement(element) { - if (this._elements.indexOf(element) !== -1) + if (this._elements.indexOf(element) !== -1) { return; + } this._elements.push(element); element.addEventListener('mousedown', this._installDragOnMouseDownBound, false); @@ -52,8 +53,9 @@ * @param {!Element} element */ removeElement(element) { - if (this._elements.indexOf(element) === -1) + if (this._elements.indexOf(element) === -1) { return; + } this._elements.remove(element); element.removeEventListener('mousedown', this._installDragOnMouseDownBound, false); @@ -68,10 +70,11 @@ * @param {!Element} element */ _updateElementCursor(element) { - if (this._isEnabled) + if (this._isEnabled) { element.style.setProperty('cursor', this.cursor()); - else + } else { element.style.removeProperty('cursor'); + } } /** @@ -94,8 +97,9 @@ */ _installDragOnMouseDown(event) { // Only handle drags of the nodes specified. - if (this._elements.indexOf(event.target) === -1) + if (this._elements.indexOf(event.target) === -1) { return false; + } UI.elementDragStart( /** @type {!Element} */ (event.target), this._dragStart.bind(this), this._drag.bind(this), this._dragEnd.bind(this), this.cursor(), event); @@ -106,8 +110,9 @@ * @return {boolean} */ _dragStart(event) { - if (!this._isEnabled) + if (!this._isEnabled) { return false; + } this._startX = event.pageX; this._startY = event.pageY; this.sendDragStart(this._startX, this._startY);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SearchableView.js b/third_party/blink/renderer/devtools/front_end/ui/SearchableView.js index b03b61f..6cacb7f 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SearchableView.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SearchableView.js
@@ -158,8 +158,9 @@ } _saveSetting() { - if (!this._setting) + if (!this._setting) { return; + } const settingValue = this._setting.get() || {}; settingValue.caseSensitive = this._caseSensitiveButton.toggled(); settingValue.isRegex = this._regexButton.toggled(); @@ -168,10 +169,12 @@ _loadSetting() { const settingValue = this._setting ? (this._setting.get() || {}) : {}; - if (this._searchProvider.supportsCaseSensitiveSearch()) + if (this._searchProvider.supportsCaseSensitiveSearch()) { this._caseSensitiveButton.setToggled(!!settingValue.caseSensitive); - if (this._searchProvider.supportsRegexSearch()) + } + if (this._searchProvider.supportsRegexSearch()) { this._regexButton.setToggled(!!settingValue.isRegex); + } } /** @@ -199,8 +202,9 @@ * @param {number} matches */ updateSearchMatchesCount(matches) { - if (this._searchProvider.currentSearchMatches === matches) + if (this._searchProvider.currentSearchMatches === matches) { return; + } this._searchProvider.currentSearchMatches = matches; this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentQuery ? matches : 0, -1); } @@ -221,8 +225,9 @@ closeSearch() { this.cancelSearch(); - if (this._footerElementContainer.hasFocus()) + if (this._footerElementContainer.hasFocus()) { this.focus(); + } } _toggleSearchBar(toggled) { @@ -231,8 +236,9 @@ } cancelSearch() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return; + } this.resetSearch(); delete this._searchIsVisible; this._toggleSearchBar(false); @@ -245,8 +251,9 @@ } refreshSearch() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return; + } this.resetSearch(); this._performSearch(false, false); } @@ -255,8 +262,9 @@ * @return {boolean} */ handleFindNextShortcut() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return false; + } this._searchProvider.jumpToNextSearchResult(); return true; } @@ -265,8 +273,9 @@ * @return {boolean} */ handleFindPreviousShortcut() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return false; + } this._searchProvider.jumpToPreviousSearchResult(); return true; } @@ -283,8 +292,9 @@ * @return {boolean} */ handleCancelSearchShortcut() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return false; + } this.closeSearch(); return true; } @@ -304,32 +314,36 @@ * @param {number} currentMatchIndex */ _updateSearchMatchesCountAndCurrentMatchIndex(matches, currentMatchIndex) { - if (!this._currentQuery) + if (!this._currentQuery) { this._matchesElement.textContent = ''; - else if (matches === 0 || currentMatchIndex >= 0) + } else if (matches === 0 || currentMatchIndex >= 0) { this._matchesElement.textContent = Common.UIString('%d of %d', currentMatchIndex + 1, matches); - else if (matches === 1) + } else if (matches === 1) { this._matchesElement.textContent = Common.UIString('1 match'); - else + } else { this._matchesElement.textContent = Common.UIString('%d matches', matches); + } this._updateSearchNavigationButtonState(matches > 0); } showSearchField() { - if (this._searchIsVisible) + if (this._searchIsVisible) { this.cancelSearch(); + } let queryCandidate; if (!this._searchInputElement.hasFocus()) { const selection = UI.inspectorView.element.window().getSelection(); - if (selection.rangeCount) + if (selection.rangeCount) { queryCandidate = selection.toString().replace(/\r?\n.*/, ''); + } } this._toggleSearchBar(true); this._updateReplaceVisibility(); - if (queryCandidate) + if (queryCandidate) { this._searchInputElement.value = queryCandidate; + } this._performSearch(false, false); this._searchInputElement.focus(); this._searchInputElement.select(); @@ -353,63 +367,72 @@ event.consume(true); return; } - if (!isEnterKey(event)) + if (!isEnterKey(event)) { return; + } - if (!this._currentQuery) + if (!this._currentQuery) { this._performSearch(true, true, event.shiftKey); - else + } else { this._jumpToNextSearchResult(event.shiftKey); + } } /** * @param {!Event} event */ _onReplaceKeyDown(event) { - if (isEnterKey(event)) + if (isEnterKey(event)) { this._replace(); + } } /** * @param {boolean=} isBackwardSearch */ _jumpToNextSearchResult(isBackwardSearch) { - if (!this._currentQuery) + if (!this._currentQuery) { return; + } - if (isBackwardSearch) + if (isBackwardSearch) { this._searchProvider.jumpToPreviousSearchResult(); - else + } else { this._searchProvider.jumpToNextSearchResult(); + } } _onNextButtonSearch(event) { - if (!this._searchNavigationNextElement.classList.contains('enabled')) + if (!this._searchNavigationNextElement.classList.contains('enabled')) { return; + } this._jumpToNextSearchResult(); this._searchInputElement.focus(); } _onPrevButtonSearch(event) { - if (!this._searchNavigationPrevElement.classList.contains('enabled')) + if (!this._searchNavigationPrevElement.classList.contains('enabled')) { return; + } this._jumpToNextSearchResult(true); this._searchInputElement.focus(); } _onFindClick(event) { - if (!this._currentQuery) + if (!this._currentQuery) { this._performSearch(true, true); - else + } else { this._jumpToNextSearchResult(); + } this._searchInputElement.focus(); } _onPreviousClick(event) { - if (!this._currentQuery) + if (!this._currentQuery) { this._performSearch(true, true, true); - else + } else { this._jumpToNextSearchResult(true); + } this._searchInputElement.focus(); } @@ -457,10 +480,11 @@ this._secondRowButtons.classList.toggle('hidden', !secondRowVisible); this._replaceInputElement.classList.toggle('hidden', !secondRowVisible); - if (secondRowVisible) + if (secondRowVisible) { this._replaceInputElement.focus(); - else + } else { this._searchInputElement.focus(); + } this.doResize(); } @@ -481,15 +505,17 @@ * @param {!Event} event */ _onInput(event) { - if (this._valueChangedTimeoutId) + if (this._valueChangedTimeoutId) { clearTimeout(this._valueChangedTimeoutId); + } const timeout = this._searchInputElement.value.length < 3 ? 200 : 0; this._valueChangedTimeoutId = setTimeout(this._onValueChanged.bind(this), timeout); } _onValueChanged() { - if (!this._searchIsVisible) + if (!this._searchIsVisible) { return; + } delete this._valueChangedTimeoutId; this._performSearch(false, true); } @@ -569,8 +595,9 @@ */ toSearchRegex(global) { let modifiers = this.caseSensitive ? '' : 'i'; - if (global) + if (global) { modifiers += 'g'; + } const query = this.isRegex ? '/' + this.query + '/' : this.query; let regex; @@ -586,8 +613,9 @@ } // Otherwise just do a plain text search. - if (!regex) + if (!regex) { regex = createPlainTextSearchRegex(query, modifiers); + } return regex; }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SegmentedButton.js b/third_party/blink/renderer/devtools/front_end/ui/SegmentedButton.js index 194ee18..a2b17af 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SegmentedButton.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SegmentedButton.js
@@ -31,11 +31,13 @@ * @param {string} value */ select(value) { - if (this._selected === value) + if (this._selected === value) { return; + } this._selected = value; - for (const key of this._buttons.keys()) + for (const key of this._buttons.keys()) { this._buttons.get(key).classList.toggle('segmented-button-segment-selected', key === this._selected); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SettingsUI.js b/third_party/blink/renderer/devtools/front_end/ui/SettingsUI.js index 5676b8d..8fc53a4 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SettingsUI.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SettingsUI.js
@@ -38,15 +38,17 @@ */ UI.SettingsUI.createSettingCheckbox = function(name, setting, omitParagraphElement, tooltip) { const label = UI.CheckboxLabel.create(name); - if (tooltip) + if (tooltip) { label.title = tooltip; + } const input = label.checkboxElement; input.name = name; UI.SettingsUI.bindCheckbox(input, setting); - if (omitParagraphElement) + if (omitParagraphElement) { return label; + } const p = createElement('p'); p.appendChild(label); @@ -86,8 +88,9 @@ function settingChanged() { const newValue = setting.get(); for (let i = 0; i < options.length; i++) { - if (options[i].value === newValue) + if (options[i].value === newValue) { select.selectedIndex = i; + } } } @@ -103,15 +106,17 @@ */ UI.SettingsUI.bindCheckbox = function(input, setting) { function settingChanged() { - if (input.checked !== setting.get()) + if (input.checked !== setting.get()) { input.checked = setting.get(); + } } setting.addChangeListener(settingChanged); settingChanged(); function inputChanged() { - if (setting.get() !== input.checked) + if (setting.get() !== input.checked) { setting.set(input.checked); + } } input.addEventListener('change', inputChanged, false); }; @@ -137,16 +142,18 @@ * @return {?Element} */ UI.SettingsUI.createControlForSetting = function(setting, subtitle) { - if (!setting.extension()) + if (!setting.extension()) { return null; + } const descriptor = setting.extension().descriptor(); const uiTitle = Common.UIString(setting.title() || ''); switch (descriptor['settingType']) { case 'boolean': return UI.SettingsUI.createSettingCheckbox(uiTitle, setting); case 'enum': - if (Array.isArray(descriptor['options'])) + if (Array.isArray(descriptor['options'])) { return UI.SettingsUI.createSettingSelect(uiTitle, descriptor['options'], setting, subtitle); + } console.error('Enum setting defined without options'); return null; default:
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js b/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js index 648ca00..c017e8b7 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ShortcutRegistry.js
@@ -42,8 +42,9 @@ for (const key of this._defaultKeyToActions.keysArray()) { const actions = this._defaultKeyToActions.get(key).valuesArray(); const applicableActions = this._actionRegistry.applicableActions(actions, new UI.Context()); - if (applicableActions.length) + if (applicableActions.length) { keys.push(Number(key)); + } } return keys; } @@ -64,8 +65,9 @@ const result = []; for (let i = 0; i < actionIds.length; ++i) { const descriptors = this.shortcutDescriptorsForAction(actionIds[i]); - for (let j = 0; j < descriptors.length; ++j) + for (let j = 0; j < descriptors.length; ++j) { result.push(descriptors[j].key); + } } return result; } @@ -76,8 +78,9 @@ */ shortcutTitleForAction(actionId) { const descriptors = this.shortcutDescriptorsForAction(actionId); - if (descriptors.length) + if (descriptors.length) { return descriptors[0].name; + } } /** @@ -107,8 +110,9 @@ addShortcutListener(element, actionId, listener, capture) { console.assert(this._defaultActionToShortcut.has(actionId), 'Unknown action ' + actionId); element.addEventListener('keydown', event => { - if (!this.eventMatchesAction(/** @type {!KeyboardEvent} */ (event), actionId) || !listener.call(null)) + if (!this.eventMatchesAction(/** @type {!KeyboardEvent} */ (event), actionId) || !listener.call(null)) { return; + } event.consume(true); }, capture); } @@ -121,45 +125,57 @@ async handleKey(key, domKey, event) { const keyModifiers = key >> 8; const actions = this._applicableActions(key); - if (!actions.length || isPossiblyInputKey()) + if (!actions.length || isPossiblyInputKey()) { return; - if (event) + } + if (event) { event.consume(true); - if (UI.Dialog.hasInstance()) + } + if (UI.Dialog.hasInstance()) { return; + } for (const action of actions) { - if (await action.execute()) + if (await action.execute()) { return; + } } /** * @return {boolean} */ function isPossiblyInputKey() { - if (!event || !UI.isEditing() || /^F\d+|Control|Shift|Alt|Meta|Escape|Win|U\+001B$/.test(domKey)) + if (!event || !UI.isEditing() || /^F\d+|Control|Shift|Alt|Meta|Escape|Win|U\+001B$/.test(domKey)) { return false; + } - if (!keyModifiers) + if (!keyModifiers) { return true; + } const modifiers = UI.KeyboardShortcut.Modifiers; // Undo/Redo will also cause input, so textual undo should take precedence over DevTools undo when editing. if (Host.isMac()) { - if (UI.KeyboardShortcut.makeKey('z', modifiers.Meta) === key) + if (UI.KeyboardShortcut.makeKey('z', modifiers.Meta) === key) { return true; - if (UI.KeyboardShortcut.makeKey('z', modifiers.Meta | modifiers.Shift) === key) + } + if (UI.KeyboardShortcut.makeKey('z', modifiers.Meta | modifiers.Shift) === key) { return true; + } } else { - if (UI.KeyboardShortcut.makeKey('z', modifiers.Ctrl) === key) + if (UI.KeyboardShortcut.makeKey('z', modifiers.Ctrl) === key) { return true; - if (UI.KeyboardShortcut.makeKey('y', modifiers.Ctrl) === key) + } + if (UI.KeyboardShortcut.makeKey('y', modifiers.Ctrl) === key) { return true; - if (!Host.isWin() && UI.KeyboardShortcut.makeKey('z', modifiers.Ctrl | modifiers.Shift) === key) + } + if (!Host.isWin() && UI.KeyboardShortcut.makeKey('z', modifiers.Ctrl | modifiers.Shift) === key) { return true; + } } - if ((keyModifiers & (modifiers.Ctrl | modifiers.Alt)) === (modifiers.Ctrl | modifiers.Alt)) + if ((keyModifiers & (modifiers.Ctrl | modifiers.Alt)) === (modifiers.Ctrl | modifiers.Alt)) { return Host.isWin(); + } return !hasModifier(modifiers.Ctrl) && !hasModifier(modifiers.Alt) && !hasModifier(modifiers.Meta); } @@ -179,8 +195,9 @@ */ registerShortcut(actionId, shortcut) { const descriptor = UI.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut); - if (!descriptor) + if (!descriptor) { return; + } this._defaultActionToShortcut.set(actionId, descriptor); this._defaultKeyToActions.set(String(descriptor.key), actionId); } @@ -200,8 +217,9 @@ const descriptor = extension.descriptor(); const bindings = descriptor['bindings']; for (let i = 0; bindings && i < bindings.length; ++i) { - if (!platformMatches(bindings[i].platform)) + if (!platformMatches(bindings[i].platform)) { continue; + } const shortcuts = bindings[i]['shortcut'].split(/\s+/); shortcuts.forEach(this.registerShortcut.bind(this, descriptor['actionId'])); } @@ -212,13 +230,15 @@ * @return {boolean} */ function platformMatches(platformsString) { - if (!platformsString) + if (!platformsString) { return true; + } const platforms = platformsString.split(','); let isMatch = false; const currentPlatform = Host.platform(); - for (let i = 0; !isMatch && i < platforms.length; ++i) + for (let i = 0; !isMatch && i < platforms.length; ++i) { isMatch = platforms[i] === currentPlatform; + } return isMatch; } }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ShortcutsScreen.js b/third_party/blink/renderer/devtools/front_end/ui/ShortcutsScreen.js index 82b58fa..1e13b2e 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ShortcutsScreen.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ShortcutsScreen.js
@@ -234,8 +234,9 @@ */ section(name) { let section = this._sections[name]; - if (!section) + if (!section) { this._sections[name] = section = new UI.ShortcutsSection(name); + } return section; } @@ -244,8 +245,9 @@ */ createShortcutsTabView() { const orderedSections = []; - for (const section in this._sections) + for (const section in this._sections) { orderedSections.push(this._sections[section]); + } function compareSections(a, b) { return a.order - b.order; } @@ -258,8 +260,9 @@ const scrollPane = widget.element.createChild('div', 'settings-container-wrapper'); const container = scrollPane.createChild('div'); container.className = 'settings-content settings-container'; - for (let i = 0; i < orderedSections.length; ++i) + for (let i = 0; i < orderedSections.length; ++i) { orderedSections[i].renderSection(container); + } const note = scrollPane.createChild('p', 'settings-footnote'); note.appendChild(UI.createDocumentationLink( @@ -380,8 +383,9 @@ _joinNodes(nodes, delimiter) { const result = createDocumentFragment(); for (let i = 0; i < nodes.length; ++i) { - if (i > 0) + if (i > 0) { result.appendChild(delimiter.cloneNode(true)); + } result.appendChild(nodes[i]); } return result;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js b/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js index 12568ad..0d1de20 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js
@@ -45,8 +45,9 @@ * @param {!AnchorBox} anchorBox */ show(document, anchorBox) { - if (!this._items.length) + if (!this._items.length) { return; + } this._document = document; @@ -67,8 +68,9 @@ this._contextMenuElement.addEventListener('mouseup', e => e.consume(), false); this._contextMenuElement.addEventListener('keydown', this._menuKeyDown.bind(this), false); - for (let i = 0; i < this._items.length; ++i) + for (let i = 0; i < this._items.length; ++i) { this._contextMenuElement.appendChild(this._createMenuItem(this._items[i])); + } this._glassPane.show(document); this._focusRestorer = new UI.ElementFocusRestorer(this._contextMenuElement); @@ -78,8 +80,9 @@ // If a user clicks on any submenu, prevent the menu system from closing. let subMenu = this._subMenu; while (subMenu) { - if (subMenu._contextMenuElement === event.path[0]) + if (subMenu._contextMenuElement === event.path[0]) { return; + } subMenu = subMenu._subMenu; } @@ -92,10 +95,12 @@ } discard() { - if (this._subMenu) + if (this._subMenu) { this._subMenu.discard(); - if (this._focusRestorer) + } + if (this._focusRestorer) { this._focusRestorer.restore(); + } if (this._glassPane) { this._glassPane.hide(); delete this._glassPane; @@ -105,24 +110,28 @@ delete this._hideOnUserGesture; } } - if (this._parentMenu) + if (this._parentMenu) { delete this._parentMenu._subMenu; + } } _createMenuItem(item) { - if (item.type === 'separator') + if (item.type === 'separator') { return this._createSeparator(); + } - if (item.type === 'subMenu') + if (item.type === 'subMenu') { return this._createSubMenu(item); + } const menuItemElement = createElementWithClass('div', 'soft-context-menu-item'); menuItemElement.tabIndex = -1; UI.ARIAUtils.markAsMenuItem(menuItemElement); const checkMarkElement = UI.Icon.create('smallicon-checkmark', 'checkmark'); menuItemElement.appendChild(checkMarkElement); - if (!item.checked) + if (!item.checked) { checkMarkElement.style.opacity = '0'; + } if (item.element) { const wrapper = menuItemElement.createChild('div', 'soft-context-menu-custom-item'); @@ -131,8 +140,9 @@ return menuItemElement; } - if (!item.enabled) + if (!item.enabled) { menuItemElement.classList.add('soft-context-menu-disabled'); + } menuItemElement.createTextChild(item.label); menuItemElement.createChild('span', 'soft-context-menu-shortcut').textContent = item.shortcut; @@ -149,10 +159,11 @@ if (item.type === 'checkbox') { const checkedState = item.checked ? ls`checked` : ls`unchecked`; - if (item.shortcut) + if (item.shortcut) { accessibleName = ls`${item.label}, ${item.shortcut}, ${checkedState}`; - else + } else { accessibleName = ls`${item.label}, ${checkedState}`; + } } else if (item.shortcut) { accessibleName = ls`${item.label}, ${item.shortcut}`; } @@ -215,8 +226,9 @@ */ _root() { let root = this; - while (root._parentMenu) + while (root._parentMenu) { root = root._parentMenu; + } return root; } @@ -240,8 +252,9 @@ clearTimeout(menuItemElement._subMenuTimer); delete menuItemElement._subMenuTimer; } - if (this._subMenu) + if (this._subMenu) { return; + } this._subMenu = new UI.SoftContextMenu(menuItemElement._subItems, this._itemSelectedCallback, this); const anchorBox = menuItemElement.boxInWindow(); @@ -264,8 +277,9 @@ } const relatedTarget = event.relatedTarget; - if (relatedTarget === this._contextMenuElement) + if (relatedTarget === this._contextMenuElement) { this._highlightMenuItem(null, true); + } } /** @@ -273,11 +287,13 @@ * @param {boolean} scheduleSubMenu */ _highlightMenuItem(menuItemElement, scheduleSubMenu) { - if (this._highlightedMenuItemElement === menuItemElement) + if (this._highlightedMenuItemElement === menuItemElement) { return; + } - if (this._subMenu) + if (this._subMenu) { this._subMenu.discard(); + } if (this._highlightedMenuItemElement) { this._highlightedMenuItemElement.classList.remove('force-white-icons'); this._highlightedMenuItemElement.classList.remove('soft-context-menu-item-mouse-over'); @@ -288,13 +304,15 @@ } this._highlightedMenuItemElement = menuItemElement; if (this._highlightedMenuItemElement) { - if (UI.themeSupport.hasTheme() || Host.isMac()) + if (UI.themeSupport.hasTheme() || Host.isMac()) { this._highlightedMenuItemElement.classList.add('force-white-icons'); + } this._highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over'); - if (this._highlightedMenuItemElement._customElement) + if (this._highlightedMenuItemElement._customElement) { this._highlightedMenuItemElement._customElement.focus(); - else + } else { this._highlightedMenuItemElement.focus(); + } if (scheduleSubMenu && this._highlightedMenuItemElement._subItems && !this._highlightedMenuItemElement._subMenuTimer) { this._highlightedMenuItemElement._subMenuTimer = @@ -307,20 +325,24 @@ let menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.previousSibling : this._contextMenuElement.lastChild; while (menuItemElement && - (menuItemElement._isSeparator || menuItemElement.classList.contains('soft-context-menu-disabled'))) + (menuItemElement._isSeparator || menuItemElement.classList.contains('soft-context-menu-disabled'))) { menuItemElement = menuItemElement.previousSibling; - if (menuItemElement) + } + if (menuItemElement) { this._highlightMenuItem(menuItemElement, false); + } } _highlightNext() { let menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.nextSibling : this._contextMenuElement.firstChild; while (menuItemElement && - (menuItemElement._isSeparator || menuItemElement.classList.contains('soft-context-menu-disabled'))) + (menuItemElement._isSeparator || menuItemElement.classList.contains('soft-context-menu-disabled'))) { menuItemElement = menuItemElement.nextSibling; - if (menuItemElement) + } + if (menuItemElement) { this._highlightMenuItem(menuItemElement, false); + } } _menuKeyDown(event) { @@ -338,8 +360,9 @@ } break; case 'ArrowRight': - if (!this._highlightedMenuItemElement) + if (!this._highlightedMenuItemElement) { break; + } if (this._highlightedMenuItemElement._subItems) { this._showSubMenu(this._highlightedMenuItemElement); this._subMenu._highlightNext(); @@ -349,15 +372,18 @@ this.discard(); break; case 'Enter': - if (!isEnterKey(event)) + if (!isEnterKey(event)) { return; + } // Fall through case ' ': // Space - if (!this._highlightedMenuItemElement || this._highlightedMenuItemElement._customElement) + if (!this._highlightedMenuItemElement || this._highlightedMenuItemElement._customElement) { return; + } this._triggerAction(this._highlightedMenuItemElement, event); - if (this._highlightedMenuItemElement._subItems) + if (this._highlightedMenuItemElement._subItems) { this._subMenu._highlightNext(); + } break; } event.consume(true);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SoftDropDown.js b/third_party/blink/renderer/devtools/front_end/ui/SoftDropDown.js index b41831f..14b8b89 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SoftDropDown.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SoftDropDown.js
@@ -40,21 +40,24 @@ this._listWasShowing200msAgo = false; this.element.addEventListener('mousedown', event => { - if (this._listWasShowing200msAgo) + if (this._listWasShowing200msAgo) { this._hide(event); - else if (!this.element.disabled) + } else if (!this.element.disabled) { this._show(event); + } }, false); this.element.addEventListener('keydown', this._onKeyDownButton.bind(this), false); this._list.element.addEventListener('keydown', this._onKeyDownList.bind(this), false); this._list.element.addEventListener('focusout', this._hide.bind(this), false); this._list.element.addEventListener('mousedown', event => event.consume(true), false); this._list.element.addEventListener('mouseup', event => { - if (event.target === this._list.element) + if (event.target === this._list.element) { return; + } - if (!this._listWasShowing200msAgo) + if (!this._listWasShowing200msAgo) { return; + } this._selectHighlightedItem(); this._hide(event); }, false); @@ -65,15 +68,17 @@ * @param {!Event} event */ _show(event) { - if (this._glassPane.isShowing()) + if (this._glassPane.isShowing()) { return; + } this._glassPane.setContentAnchorBox(this.element.boxInWindow()); this._glassPane.show(/** @type {!Document} **/ (this.element.ownerDocument)); this._list.element.focus(); UI.ARIAUtils.setExpanded(this.element, true); this._updateGlasspaneSize(); - if (this._selectedItem) + if (this._selectedItem) { this._list.selectItem(this._selectedItem); + } event.consume(true); setTimeout(() => this._listWasShowing200msAgo = true, 200); } @@ -121,8 +126,9 @@ break; } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -182,8 +188,9 @@ break; } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -206,8 +213,9 @@ */ setPlaceholderText(text) { this._placeholderText = text; - if (!this._selectedItem) + if (!this._selectedItem) { this._titleElement.textContent = this._placeholderText; + } } /** @@ -227,10 +235,11 @@ */ selectItem(item) { this._selectedItem = item; - if (this._selectedItem) + if (this._selectedItem) { this._titleElement.textContent = this._delegate.titleFor(this._selectedItem); - else + } else { this._titleElement.textContent = this._placeholderText; + } this._delegate.itemSelected(this._selectedItem); } @@ -242,8 +251,9 @@ createElementForItem(item) { const element = createElementWithClass('div', 'item'); element.addEventListener('mousemove', e => { - if ((e.movementX || e.movementY) && this._delegate.isItemSelectable(item)) + if ((e.movementX || e.movementY) && this._delegate.isItemSelectable(item)) { this._list.selectItem(item, false, /* Don't scroll */ true); + } }); element.classList.toggle('disabled', !this._delegate.isItemSelectable(item)); element.classList.toggle('highlighted', this._list.selectedItem() === item); @@ -280,10 +290,12 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('highlighted'); - if (toElement) + } + if (toElement) { toElement.classList.add('highlighted'); + } UI.ARIAUtils.setActiveDescendant(this._list.element, toElement); this._delegate.highlightedItemChanged(
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js b/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js index c5de115..bb083a537 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SplitWidget.js
@@ -110,13 +110,15 @@ * @param {boolean} isVertical */ setVertical(isVertical) { - if (this._isVertical === isVertical) + if (this._isVertical === isVertical) { return; + } this._innerSetVertical(isVertical); - if (this.isShowing()) + if (this.isShowing()) { this._updateLayout(); + } } /** @@ -130,8 +132,9 @@ this._resizerElementSize = null; this._sidebarSizeDIP = -1; this._restoreSidebarSizeFromSettings(); - if (this._shouldSaveShowMode) + if (this._shouldSaveShowMode) { this._restoreAndApplyShowModeFromSettings(); + } this._updateShowHideSidebarButton(); // FIXME: reverse SplitWidget.isVertical meaning. this._resizerWidget.setVertical(!isVertical); @@ -158,16 +161,19 @@ * @param {!UI.Widget} widget */ setMainWidget(widget) { - if (this._mainWidget === widget) + if (this._mainWidget === widget) { return; + } this.suspendInvalidations(); - if (this._mainWidget) + if (this._mainWidget) { this._mainWidget.detach(); + } this._mainWidget = widget; if (widget) { widget.element.slot = 'insertion-point-main'; - if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain || this._showMode === UI.SplitWidget.ShowMode.Both) + if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain || this._showMode === UI.SplitWidget.ShowMode.Both) { widget.show(this.element); + } } this.resumeInvalidations(); } @@ -176,16 +182,19 @@ * @param {!UI.Widget} widget */ setSidebarWidget(widget) { - if (this._sidebarWidget === widget) + if (this._sidebarWidget === widget) { return; + } this.suspendInvalidations(); - if (this._sidebarWidget) + if (this._sidebarWidget) { this._sidebarWidget.detach(); + } this._sidebarWidget = widget; if (widget) { widget.element.slot = 'insertion-point-sidebar'; - if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar || this._showMode === UI.SplitWidget.ShowMode.Both) + if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar || this._showMode === UI.SplitWidget.ShowMode.Both) { widget.show(this.element); + } } this.resumeInvalidations(); } @@ -209,12 +218,15 @@ * @param {!UI.Widget} widget */ childWasDetached(widget) { - if (this._detaching) + if (this._detaching) { return; - if (this._mainWidget === widget) + } + if (this._mainWidget === widget) { this._mainWidget = null; - if (this._sidebarWidget === widget) + } + if (this._sidebarWidget === widget) { this._sidebarWidget = null; + } this.invalidateConstraints(); } @@ -241,19 +253,22 @@ * @param {boolean} secondIsSidebar */ setSecondIsSidebar(secondIsSidebar) { - if (secondIsSidebar === this._secondIsSidebar) + if (secondIsSidebar === this._secondIsSidebar) { return; + } this._secondIsSidebar = secondIsSidebar; if (!this._mainWidget || !this._mainWidget.shouldHideOnDetach()) { - if (secondIsSidebar) + if (secondIsSidebar) { this.contentElement.insertBefore(this._mainElement, this._sidebarElement); - else + } else { this.contentElement.insertBefore(this._mainElement, this._resizerElement); + } } else if (!this._sidebarWidget || !this._sidebarWidget.shouldHideOnDetach()) { - if (secondIsSidebar) + if (secondIsSidebar) { this.contentElement.insertBefore(this._sidebarElement, this._resizerElement); - else + } else { this.contentElement.insertBefore(this._sidebarElement, this._mainElement); + } } else { console.error('Could not swap split widget side. Both children widgets contain iframes.'); this._secondIsSidebar = !secondIsSidebar; @@ -264,8 +279,9 @@ * @return {?string} */ sidebarSide() { - if (this._showMode !== UI.SplitWidget.ShowMode.Both) + if (this._showMode !== UI.SplitWidget.ShowMode.Both) { return null; + } return this._isVertical ? (this._secondIsSidebar ? 'right' : 'left') : (this._secondIsSidebar ? 'bottom' : 'top'); } @@ -323,10 +339,11 @@ function callback() { if (sideToShow) { // Make sure main is first in the children list. - if (sideToShow === this._mainWidget) + if (sideToShow === this._mainWidget) { this._mainWidget.show(this.element, this._sidebarWidget ? this._sidebarWidget.element : null); - else + } else { this._sidebarWidget.show(this.element); + } } if (sideToHide) { this._detaching = true; @@ -344,10 +361,11 @@ this._showFinishedForTest(); } - if (animate) + if (animate) { this._animate(true, callback.bind(this)); - else + } else { callback.call(this); + } this._sidebarSizeDIP = -1; this.setResizable(false); @@ -380,8 +398,9 @@ * @param {boolean=} animate */ showBoth(animate) { - if (this._showMode === UI.SplitWidget.ShowMode.Both) + if (this._showMode === UI.SplitWidget.ShowMode.Both) { animate = false; + } this._cancelAnimation(); this._mainElement.classList.remove('maximized', 'hidden'); @@ -391,10 +410,12 @@ // Make sure main is the first in the children list. this.suspendInvalidations(); - if (this._sidebarWidget) + if (this._sidebarWidget) { this._sidebarWidget.show(this.element); - if (this._mainWidget) + } + if (this._mainWidget) { this._mainWidget.show(this.element, this._sidebarWidget ? this._sidebarWidget.element : null); + } this.resumeInvalidations(); // Order widgets in DOM properly. this.setSecondIsSidebar(this._secondIsSidebar); @@ -466,12 +487,14 @@ * @param {boolean=} userAction */ _innerSetSidebarSizeDIP(sizeDIP, animate, userAction) { - if (this._showMode !== UI.SplitWidget.ShowMode.Both || !this.isShowing()) + if (this._showMode !== UI.SplitWidget.ShowMode.Both || !this.isShowing()) { return; + } sizeDIP = this._applyConstraints(sizeDIP, userAction); - if (this._sidebarSizeDIP === sizeDIP) + if (this._sidebarSizeDIP === sizeDIP) { return; + } if (!this._resizerElementSize) { this._resizerElementSize = @@ -542,10 +565,11 @@ this._animationCallback = callback || null; let animatedMarginPropertyName; - if (this._isVertical) + if (this._isVertical) { animatedMarginPropertyName = this._secondIsSidebar ? 'margin-right' : 'margin-left'; - else + } else { animatedMarginPropertyName = this._secondIsSidebar ? 'margin-bottom' : 'margin-top'; + } const marginFrom = reverse ? '0' : '-' + UI.zoomManager.dipToCSS(this._sidebarSizeDIP) + 'px'; const marginTo = reverse ? '-' + UI.zoomManager.dipToCSS(this._sidebarSizeDIP) + 'px' : '0'; @@ -559,8 +583,9 @@ } // 2. Issue onresize to the sidebar element, its size won't change. - if (!reverse) + if (!reverse) { this._sidebarWidget.doResize(); + } // 3. Configure and run animation this.contentElement.style.setProperty('transition', animatedMarginPropertyName + ' ' + animationTime + 'ms linear'); @@ -579,13 +604,15 @@ startTime = window.performance.now(); } else if (window.performance.now() < startTime + animationTime) { // Process regular animation frame. - if (this._mainWidget) + if (this._mainWidget) { this._mainWidget.doResize(); + } } else { // Complete animation. this._cancelAnimation(); - if (this._mainWidget) + if (this._mainWidget) { this._mainWidget.doResize(); + } this.dispatchEventToListeners(UI.SplitWidget.Events.SidebarSizeChanged, this.sidebarSize()); return; } @@ -622,41 +649,50 @@ let constraints = this._sidebarWidget ? this._sidebarWidget.constraints() : new UI.Constraints(); let minSidebarSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height; - if (!minSidebarSize) + if (!minSidebarSize) { minSidebarSize = UI.SplitWidget.MinPadding; + } minSidebarSize *= zoomFactor; - if (this._sidebarMinimized) + if (this._sidebarMinimized) { sidebarSize = minSidebarSize; + } let preferredSidebarSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height; - if (!preferredSidebarSize) + if (!preferredSidebarSize) { preferredSidebarSize = UI.SplitWidget.MinPadding; + } preferredSidebarSize *= zoomFactor; // Allow sidebar to be less than preferred by explicit user action. - if (sidebarSize < preferredSidebarSize) + if (sidebarSize < preferredSidebarSize) { preferredSidebarSize = Math.max(sidebarSize, minSidebarSize); + } preferredSidebarSize += zoomFactor; // 1 css pixel for splitter border. constraints = this._mainWidget ? this._mainWidget.constraints() : new UI.Constraints(); let minMainSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height; - if (!minMainSize) + if (!minMainSize) { minMainSize = UI.SplitWidget.MinPadding; + } minMainSize *= zoomFactor; let preferredMainSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height; - if (!preferredMainSize) + if (!preferredMainSize) { preferredMainSize = UI.SplitWidget.MinPadding; + } preferredMainSize *= zoomFactor; const savedMainSize = this.isVertical() ? this._savedVerticalMainSize : this._savedHorizontalMainSize; - if (savedMainSize !== null) + if (savedMainSize !== null) { preferredMainSize = Math.min(preferredMainSize, savedMainSize * zoomFactor); - if (userAction) + } + if (userAction) { preferredMainSize = minMainSize; + } // Enough space for preferred. const totalPreferred = preferredMainSize + preferredSidebarSize; - if (totalPreferred <= totalSize) + if (totalPreferred <= totalSize) { return Number.constrain(sidebarSize, preferredSidebarSize, totalSize - preferredMainSize); + } // Enough space for minimum. if (minMainSize + minSidebarSize <= totalSize) { @@ -704,10 +740,12 @@ * @return {!UI.Constraints} */ calculateConstraints() { - if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain) + if (this._showMode === UI.SplitWidget.ShowMode.OnlyMain) { return this._mainWidget ? this._mainWidget.constraints() : new UI.Constraints(); - if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar) + } + if (this._showMode === UI.SplitWidget.ShowMode.OnlySidebar) { return this._sidebarWidget ? this._sidebarWidget.constraints() : new UI.Constraints(); + } let mainConstraints = this._mainWidget ? this._mainWidget.constraints() : new UI.Constraints(); let sidebarConstraints = this._sidebarWidget ? this._sidebarWidget.constraints() : new UI.Constraints(); @@ -742,10 +780,11 @@ this._savedSidebarSizeDIP = constrainedSizeDIP; this._saveSetting(); this._innerSetSidebarSizeDIP(constrainedSizeDIP, false, true); - if (this.isVertical()) + if (this.isVertical()) { this._savedVerticalMainSize = this._totalSizeDIP() - this._sidebarSizeDIP; - else + } else { this._savedHorizontalMainSize = this._totalSizeDIP() - this._sidebarSizeDIP; + } } /** @@ -790,10 +829,11 @@ * @param {boolean} on */ toggleResizer(resizer, on) { - if (on) + if (on) { this.installResizer(resizer); - else + } else { this.uninstallResizer(resizer); + } } /** @@ -812,8 +852,9 @@ if (!size) { size = this._isVertical ? this._defaultSidebarWidth : this._defaultSidebarHeight; // If we have default value in percents, calculate it on first use. - if (0 < size && size < 1) + if (0 < size && size < 1) { size *= this._totalSizeDIP(); + } } return size; } @@ -847,19 +888,22 @@ } _saveSetting() { - if (!this._setting) + if (!this._setting) { return; + } const state = this._setting.get(); const orientationState = (this._isVertical ? state.vertical : state.horizontal) || {}; orientationState.size = this._savedSidebarSizeDIP; - if (this._shouldSaveShowMode) + if (this._shouldSaveShowMode) { orientationState.showMode = this._savedShowMode; + } - if (this._isVertical) + if (this._isVertical) { state.vertical = orientationState; - else + } else { state.horizontal = orientationState; + } this._setting.set(state); } @@ -891,18 +935,20 @@ * @this {UI.SplitWidget} */ function buttonClicked(event) { - if (this._showMode !== UI.SplitWidget.ShowMode.Both) + if (this._showMode !== UI.SplitWidget.ShowMode.Both) { this.showBoth(true); - else + } else { this.hideSidebar(true); + } } return this._showHideSidebarButton; } _updateShowHideSidebarButton() { - if (!this._showHideSidebarButton) + if (!this._showHideSidebarButton) { return; + } const sidebarHidden = this._showMode === UI.SplitWidget.ShowMode.OnlyMain; let glyph = ''; if (sidebarHidden) {
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SuggestBox.js b/third_party/blink/renderer/devtools/front_end/ui/SuggestBox.js index 4af9055..367a64b 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SuggestBox.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SuggestBox.js
@@ -116,8 +116,9 @@ */ _maxWidth(items) { const kMaxWidth = 300; - if (!items.length) + if (!items.length) { return kMaxWidth; + } let maxItem; let maxLength = -Infinity; for (let i = 0; i < items.length; i++) { @@ -137,8 +138,9 @@ * @suppressGlobalPropertiesCheck */ _show() { - if (this.visible()) + if (this.visible()) { return; + } // TODO(dgozman): take document as a parameter. this._glassPane.show(document); this._rowHeight = @@ -146,8 +148,9 @@ } hide() { - if (!this.visible()) + if (!this.visible()) { return; + } this._glassPane.hide(); } @@ -162,8 +165,9 @@ return true; } const suggestion = this._list.selectedItem(); - if (suggestion && suggestion.text) + if (suggestion && suggestion.text) { UI.ARIAUtils.alert(ls`${suggestion.title || suggestion.text}, suggestion`, this._element); + } this._suggestBoxDelegate.applySuggestion(suggestion, isIntermediateSuggestion); return this.visible() && !!suggestion; @@ -175,8 +179,9 @@ acceptSuggestion() { const result = this._applySuggestion(); this.hide(); - if (!result) + if (!result) { return false; + } this._suggestBoxDelegate.acceptSuggestion(); @@ -195,18 +200,21 @@ const icon = UI.Icon.create(item.iconType, 'suggestion-icon'); element.appendChild(icon); } - if (item.isSecondary) + if (item.isSecondary) { element.classList.add('secondary'); + } element.tabIndex = -1; const maxTextLength = 50 + query.length; const displayText = (item.title || item.text).trim().trimEndWithMaxLength(maxTextLength).replace(/\n/g, '\u21B5'); const titleElement = element.createChild('span', 'suggestion-title'); const index = displayText.toLowerCase().indexOf(query.toLowerCase()); - if (index > 0) + if (index > 0) { titleElement.createChild('span').textContent = displayText.substring(0, index); - if (index > -1) + } + if (index > -1) { titleElement.createChild('span', 'query').textContent = displayText.substring(index, index + query.length); + } titleElement.createChild('span').textContent = displayText.substring(index > -1 ? index + query.length : 0); titleElement.createChild('span', 'spacer'); if (item.subtitleRenderer) { @@ -246,8 +254,9 @@ * @param {?Element} toElement */ selectedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('selected', 'force-white-icons'); + } if (toElement) { toElement.classList.add('selected'); toElement.classList.add('force-white-icons'); @@ -260,8 +269,9 @@ */ _onClick(event) { const item = this._list.itemForNode(/** @type {?Node} */ (event.target)); - if (!item) + if (!item) { return; + } this._list.selectItem(item); this.acceptSuggestion(); @@ -276,15 +286,18 @@ * @return {boolean} */ _canShowBox(completions, highestPriorityItem, canShowForSingleItem, userEnteredText) { - if (!completions || !completions.length) + if (!completions || !completions.length) { return false; + } - if (completions.length > 1) + if (completions.length > 1) { return true; + } if (!highestPriorityItem || highestPriorityItem.isSecondary || - !highestPriorityItem.text.startsWith(userEnteredText)) + !highestPriorityItem.text.startsWith(userEnteredText)) { return true; + } // Do not show a single suggestion if it is the same as user-entered query, even if allowed to show single-item suggest boxes. return canShowForSingleItem && highestPriorityItem.text !== userEnteredText; @@ -310,10 +323,11 @@ this._list.invalidateItemHeight(); this._items.replaceAll(completions); - if (highestPriorityItem && !highestPriorityItem.isSecondary) + if (highestPriorityItem && !highestPriorityItem.isSecondary) { this._list.selectItem(highestPriorityItem, true); - else + } else { this._list.selectItem(null); + } } else { if (completions.length === 1) { this._onlyCompletion = completions[0];
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SyntaxHighlighter.js b/third_party/blink/renderer/devtools/front_end/ui/SyntaxHighlighter.js index fb2ebbd..bc51dbd 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/SyntaxHighlighter.js +++ b/third_party/blink/renderer/devtools/front_end/ui/SyntaxHighlighter.js
@@ -49,8 +49,9 @@ createSpan(content, className) { const span = createElement('span'); span.className = className.replace(/\S+/g, 'cm-$&'); - if (this._stripExtraWhitespace && className !== 'whitespace') + if (this._stripExtraWhitespace && className !== 'whitespace') { content = content.replace(/^[\n\r]*/, '').replace(/\s*$/, ''); + } span.createTextChild(content); return span; } @@ -81,8 +82,9 @@ const plainText = line.substring(plainTextStart, line.length); node.createTextChild(plainText); } - if (i < lines.length - 1) + if (i < lines.length - 1) { node.createTextChild('\n'); + } } } @@ -94,8 +96,9 @@ * @this {UI.SyntaxHighlighter} */ function processToken(token, tokenType, column, newColumn) { - if (!tokenType) + if (!tokenType) { return; + } if (column > plainTextStart) { const plainText = line.substring(plainTextStart, column);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/TabbedPane.js b/third_party/blink/renderer/devtools/front_end/ui/TabbedPane.js index 84c71d1..7e48db66 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/TabbedPane.js +++ b/third_party/blink/renderer/devtools/front_end/ui/TabbedPane.js
@@ -153,10 +153,11 @@ * @override */ focus() { - if (this.visibleView) + if (this.visibleView) { this.visibleView.focus(); - else + } else { this.contentElement.focus(); + } } /** @@ -180,8 +181,9 @@ */ setTabDelegate(delegate) { const tabs = this._tabs.slice(); - for (let i = 0; i < tabs.length; ++i) + for (let i = 0; i < tabs.length; ++i) { tabs[i].setDelegate(delegate); + } this._delegate = delegate; } @@ -200,13 +202,15 @@ tab.setDelegate(this._delegate); console.assert(!this._tabsById.has(id), `Tabbed pane already contains a tab with id '${id}'`); this._tabsById.set(id, tab); - if (index !== undefined) + if (index !== undefined) { this._tabs.splice(index, 0, tab); - else + } else { this._tabs.push(tab); + } this._tabsHistory.push(tab); - if (this._tabsHistory[0] === tab && this.isShowing()) + if (this._tabsHistory[0] === tab && this.isShowing()) { this.selectTab(tab.id, userGesture); + } this._updateTabElements(); } @@ -225,13 +229,16 @@ */ closeTabs(ids, userGesture) { const focused = this.hasFocus(); - for (let i = 0; i < ids.length; ++i) + for (let i = 0; i < ids.length; ++i) { this._innerCloseTab(ids[i], userGesture); + } this._updateTabElements(); - if (this._tabsHistory.length) + if (this._tabsHistory.length) { this.selectTab(this._tabsHistory[0].id, false); - if (focused) + } + if (focused) { this.focus(); + } } /** @@ -239,20 +246,24 @@ * @param {boolean=} userGesture */ _innerCloseTab(id, userGesture) { - if (!this._tabsById.has(id)) + if (!this._tabsById.has(id)) { return; - if (userGesture && !this._tabsById.get(id)._closeable) + } + if (userGesture && !this._tabsById.get(id)._closeable) { return; - if (this._currentTab && this._currentTab.id === id) + } + if (this._currentTab && this._currentTab.id === id) { this._hideCurrentTab(); + } const tab = this._tabsById.get(id); this._tabsById.delete(id); this._tabsHistory.splice(this._tabsHistory.indexOf(tab), 1); this._tabs.splice(this._tabs.indexOf(tab), 1); - if (tab._shown) + if (tab._shown) { this._hideTabElement(tab); + } const eventData = {tabId: id, view: tab.view, isUserGesture: userGesture}; this.dispatchEventToListeners(UI.TabbedPane.Events.TabClosed, eventData); @@ -274,8 +285,9 @@ otherTabs(id) { const result = []; for (let i = 0; i < this._tabs.length; ++i) { - if (this._tabs[i].id !== id) + if (this._tabs[i].id !== id) { result.push(this._tabs[i].id); + } } return result; } @@ -292,16 +304,18 @@ break; } } - if (index === -1) + if (index === -1) { return []; + } return this._tabs.slice(index + 1).map(function(tab) { return tab.id; }); } _viewHasFocus() { - if (this.visibleView && this.visibleView.hasFocus()) + if (this.visibleView && this.visibleView.hasFocus()) { return true; + } return this.contentElement === this.contentElement.getComponentRoot().activeElement; } @@ -312,14 +326,17 @@ * @return {boolean} */ selectTab(id, userGesture, forceFocus) { - if (this._currentTabLocked) + if (this._currentTabLocked) { return false; + } const focused = this._viewHasFocus(); const tab = this._tabsById.get(id); - if (!tab) + if (!tab) { return false; - if (this._currentTab && this._currentTab.id === id) + } + if (this._currentTab && this._currentTab.id === id) { return true; + } this.suspendInvalidations(); this._hideCurrentTab(); @@ -331,8 +348,9 @@ this._tabsHistory.splice(0, 0, tab); this._updateTabElements(); - if (focused || forceFocus) + if (focused || forceFocus) { this.focus(); + } const eventData = {tabId: id, view: tab.view, isUserGesture: userGesture}; this.dispatchEventToListeners(UI.TabbedPane.Events.TabSelected, eventData); @@ -389,18 +407,21 @@ */ toggleTabClass(id, className, force) { const tab = this._tabsById.get(id); - if (tab._toggleClass(className, force)) + if (tab._toggleClass(className, force)) { this._updateTabElements(); + } } /** * @param {!Common.Event} event */ _zoomChanged(event) { - for (let i = 0; i < this._tabs.length; ++i) + for (let i = 0; i < this._tabs.length; ++i) { delete this._tabs[i]._measuredWidth; - if (this.isShowing()) + } + if (this.isShowing()) { this._updateTabElements(); + } } /** @@ -410,8 +431,9 @@ */ changeTabTitle(id, tabTitle, tabTooltip) { const tab = this._tabsById.get(id); - if (tabTooltip !== undefined) + if (tabTooltip !== undefined) { tab.tooltip = tabTooltip; + } if (tab.title !== tabTitle) { tab.title = tabTitle; UI.ARIAUtils.setAccessibleName(tab.tabElement, tabTitle); @@ -425,19 +447,23 @@ */ changeTabView(id, view) { const tab = this._tabsById.get(id); - if (tab.view === view) + if (tab.view === view) { return; + } this.suspendInvalidations(); const isSelected = this._currentTab && this._currentTab.id === id; const shouldFocus = tab.view.hasFocus(); - if (isSelected) + if (isSelected) { this._hideTab(tab); + } tab.view = view; - if (isSelected) + if (isSelected) { this._showTab(tab); - if (shouldFocus) + } + if (shouldFocus) { tab.view.focus(); + } this.resumeInvalidations(); } @@ -457,13 +483,15 @@ */ wasShown() { const effectiveTab = this._currentTab || this._tabsHistory[0]; - if (effectiveTab && this._autoSelectFirstItemOnShow) + if (effectiveTab && this._autoSelectFirstItemOnShow) { this.selectTab(effectiveTab.id); + } } makeTabSlider() { - if (this._verticalTabLayout) + if (this._verticalTabLayout) { return; + } this._setTabSlider(true); } @@ -483,10 +511,11 @@ let constraints = super.calculateConstraints(); const minContentConstraints = new UI.Constraints(new UI.Size(0, 0), new UI.Size(50, 50)); constraints = constraints.widthToMax(minContentConstraints).heightToMax(minContentConstraints); - if (this._verticalTabLayout) + if (this._verticalTabLayout) { constraints = constraints.addWidth(new UI.Constraints(new UI.Size(120, 0))); - else + } else { constraints = constraints.addHeight(new UI.Constraints(new UI.Size(0, 30))); + } return constraints; } @@ -507,8 +536,9 @@ } _innerUpdateTabElements() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } if (!this._tabs.length) { this._contentElement.classList.add('has-no-tabs'); @@ -535,10 +565,11 @@ * @param {!UI.TabbedPaneTab} tab */ _showTabElement(index, tab) { - if (index >= this._tabsElement.children.length) + if (index >= this._tabsElement.children.length) { this._tabsElement.appendChild(tab.tabElement); - else + } else { this._tabsElement.insertBefore(tab.tabElement, this._tabsElement.children[index]); + } tab._shown = true; } @@ -560,8 +591,9 @@ dropDownContainer.addEventListener('click', this._dropDownClicked.bind(this)); dropDownContainer.addEventListener('keydown', this._dropDownKeydown.bind(this)); dropDownContainer.addEventListener('mousedown', event => { - if (event.which !== 1 || this._triggerDropDownTimeout) + if (event.which !== 1 || this._triggerDropDownTimeout) { return; + } this._triggerDropDownTimeout = setTimeout(this._dropDownClicked.bind(this, event), 200); }); return dropDownContainer; @@ -571,8 +603,9 @@ * @param {!Event} event */ _dropDownClicked(event) { - if (event.which !== 1) + if (event.which !== 1) { return; + } if (this._triggerDropDownTimeout) { clearTimeout(this._triggerDropDownTimeout); this._triggerDropDownTimeout = null; @@ -581,8 +614,9 @@ const menu = new UI.ContextMenu(event, false, rect.left, rect.bottom); for (let i = 0; i < this._tabs.length; ++i) { const tab = this._tabs[i]; - if (tab._shown) + if (tab._shown) { continue; + } menu.defaultSection().appendCheckboxItem( tab.title, this._dropDownMenuItemSelected.bind(this, tab), this._tabsHistory[0] === tab); } @@ -617,8 +651,9 @@ _numberOfTabsShown() { let numTabsShown = 0; for (const tab of this._tabs) { - if (tab._shown) + if (tab._shown) { numTabsShown++; + } } return numTabsShown; } @@ -637,32 +672,37 @@ } for (let i = 0; i < this._tabs.length; ++i) { - if (this._tabs[i]._shown && tabsToShowIndexes.indexOf(i) === -1) + if (this._tabs[i]._shown && tabsToShowIndexes.indexOf(i) === -1) { this._hideTabElement(this._tabs[i]); + } } for (let i = 0; i < tabsToShowIndexes.length; ++i) { const tab = this._tabs[tabsToShowIndexes[i]]; - if (!tab._shown) + if (!tab._shown) { this._showTabElement(i, tab); + } } - if (!this._overflowDisabled) + if (!this._overflowDisabled) { this._maybeShowDropDown(tabsToShowIndexes.length !== this._tabs.length); + } } /** * @param {boolean} hasMoreTabs */ _maybeShowDropDown(hasMoreTabs) { - if (hasMoreTabs && !this._dropDownButton.parentElement) + if (hasMoreTabs && !this._dropDownButton.parentElement) { this._headerContentsElement.appendChild(this._dropDownButton); - else if (!hasMoreTabs && this._dropDownButton.parentElement) + } else if (!hasMoreTabs && this._dropDownButton.parentElement) { this._headerContentsElement.removeChild(this._dropDownButton); + } } _measureDropDownButton() { - if (this._overflowDisabled || this._measuredDropDownButtonWidth) + if (this._overflowDisabled || this._measuredDropDownButtonWidth) { return; + } this._dropDownButton.classList.add('measuring'); this._headerContentsElement.appendChild(this._dropDownButton); this._measuredDropDownButtonWidth = this._dropDownButton.getBoundingClientRect().width; @@ -676,8 +716,9 @@ this._shrinkableTabs ? this._calculateMaxWidth(measuredWidths.slice(), this._totalWidth()) : Number.MAX_VALUE; let i = 0; - for (const tab of this._tabs) + for (const tab of this._tabs) { tab.setWidth(this._verticalTabLayout ? -1 : Math.min(maxWidth, measuredWidths[i++])); + } } _measureWidths() { @@ -685,8 +726,9 @@ this._tabsElement.style.setProperty('width', '2000px'); const measuringTabElements = []; for (const tab of this._tabs) { - if (typeof tab._measuredWidth === 'number') + if (typeof tab._measuredWidth === 'number') { continue; + } const measuringTabElement = tab._createTabElement(true); measuringTabElement.__tab = tab; measuringTabElements.push(measuringTabElement); @@ -700,13 +742,15 @@ } // Nuke elements from the UI - for (let i = 0; i < measuringTabElements.length; ++i) + for (let i = 0; i < measuringTabElements.length; ++i) { measuringTabElements[i].remove(); + } // Combine the results. const measuredWidths = []; - for (const tab of this._tabs) + for (const tab of this._tabs) { measuredWidths.push(tab._measuredWidth); + } this._tabsElement.style.removeProperty('width'); return measuredWidths; @@ -717,19 +761,22 @@ * @param {number} totalWidth */ _calculateMaxWidth(measuredWidths, totalWidth) { - if (!measuredWidths.length) + if (!measuredWidths.length) { return 0; + } measuredWidths.sort(function(x, y) { return x - y; }); let totalMeasuredWidth = 0; - for (let i = 0; i < measuredWidths.length; ++i) + for (let i = 0; i < measuredWidths.length; ++i) { totalMeasuredWidth += measuredWidths[i]; + } - if (totalWidth >= totalMeasuredWidth) + if (totalWidth >= totalMeasuredWidth) { return measuredWidths[measuredWidths.length - 1]; + } let totalExtraWidth = 0; for (let i = measuredWidths.length - 1; i > 0; --i) { @@ -758,18 +805,22 @@ let totalTabsWidth = 0; const tabCount = tabsOrdered.length; const tabsToLookAt = tabsOrdered.slice(0); - if (this._currentTab !== undefined) + if (this._currentTab !== undefined) { tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._currentTab), 1)[0]); - if (this._lastSelectedOverflowTab !== undefined) + } + if (this._lastSelectedOverflowTab !== undefined) { tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._lastSelectedOverflowTab), 1)[0]); + } for (let i = 0; i < tabCount; ++i) { const tab = this._automaticReorder ? tabsHistory[i] : tabsToLookAt[i]; totalTabsWidth += tab.width(); let minimalRequiredWidth = totalTabsWidth; - if (i !== tabCount - 1) + if (i !== tabCount - 1) { minimalRequiredWidth += measuredDropDownButtonWidth; - if (!this._verticalTabLayout && minimalRequiredWidth > totalWidth) + } + if (!this._verticalTabLayout && minimalRequiredWidth > totalWidth) { break; + } tabsToShowIndexes.push(tabsOrdered.indexOf(tab)); } @@ -781,8 +832,9 @@ } _hideCurrentTab() { - if (!this._currentTab) + if (!this._currentTab) { return; + } this._hideTab(this._currentTab); delete this._currentTab; @@ -800,24 +852,27 @@ } _updateTabSlider() { - if (!this._sliderEnabled) + if (!this._sliderEnabled) { return; + } if (!this._currentTab) { this._tabSlider.style.width = 0; return; } let left = 0; for (let i = 0; i < this._tabs.length && this._currentTab !== this._tabs[i]; i++) { - if (this._tabs[i]._shown) + if (this._tabs[i]._shown) { left += this._tabs[i]._measuredWidth; + } } const sliderWidth = this._currentTab._shown ? this._currentTab._measuredWidth : this._dropDownButton.offsetWidth; const scaleFactor = window.devicePixelRatio >= 1.5 ? ' scaleY(0.75)' : ''; this._tabSlider.style.transform = 'translateX(' + left + 'px)' + scaleFactor; this._tabSlider.style.width = sliderWidth + 'px'; - if (this._tabSlider.parentElement !== this._headerContentsElement) + if (this._tabSlider.parentElement !== this._headerContentsElement) { this._headerContentsElement.appendChild(this._tabSlider); + } } /** @@ -846,8 +901,9 @@ this._tabsElement.insertBefore(tab.tabElement, this._tabsElement.childNodes[index]); const oldIndex = this._tabs.indexOf(tab); this._tabs.splice(oldIndex, 1); - if (oldIndex < index) + if (oldIndex < index) { --index; + } this._tabs.splice(index, 0, tab); this.dispatchEventToListeners(UI.TabbedPane.Events.TabOrderChanged, {tabId: tab.id}); } @@ -887,21 +943,24 @@ * @param {!Event} event */ _keyDown(event) { - if (!this._currentTab) + if (!this._currentTab) { return; + } let nextTabElement = null; switch (event.key) { case 'ArrowUp': case 'ArrowLeft': nextTabElement = this._currentTab.tabElement.previousElementSibling; - if (!nextTabElement && !this._dropDownButton.parentElement) + if (!nextTabElement && !this._dropDownButton.parentElement) { nextTabElement = this._currentTab.tabElement.parentElement.lastElementChild; + } break; case 'ArrowDown': case 'ArrowRight': nextTabElement = this._currentTab.tabElement.nextElementSibling; - if (!nextTabElement && !this._dropDownButton.parentElement) + if (!nextTabElement && !this._dropDownButton.parentElement) { nextTabElement = this._currentTab.tabElement.parentElement.firstElementChild; + } break; case 'Enter': case ' ': @@ -973,11 +1032,13 @@ * @param {string} title */ set title(title) { - if (title === this._title) + if (title === this._title) { return; + } this._title = title; - if (this._titleElement) + if (this._titleElement) { this._titleElement.textContent = title; + } delete this._measuredWidth; } @@ -993,8 +1054,9 @@ */ _setIcon(icon) { this._icon = icon; - if (this._tabElement) + if (this._tabElement) { this._createIconElement(this._tabElement, this._titleElement, false); + } delete this._measuredWidth; } @@ -1006,8 +1068,9 @@ _toggleClass(className, force) { const element = this.tabElement; const hasClass = element.classList.contains(className); - if (hasClass === force) + if (hasClass === force) { return false; + } element.classList.toggle(className, force); delete this._measuredWidth; return true; @@ -1039,16 +1102,18 @@ */ set tooltip(tooltip) { this._tooltip = tooltip; - if (this._titleElement) + if (this._titleElement) { this._titleElement.title = tooltip || ''; + } } /** * @return {!Element} */ get tabElement() { - if (!this._tabElement) + if (!this._tabElement) { this._tabElement = this._createTabElement(false); + } return this._tabElement; } @@ -1085,8 +1150,9 @@ tabElement.__iconElement.remove(); tabElement.__iconElement = null; } - if (!this._icon) + if (!this._icon) { return; + } const iconContainer = createElementWithClass('span', 'tabbed-pane-header-tab-icon'); const iconNode = measuring ? this._icon.cloneNode(true) : this._icon; @@ -1110,8 +1176,9 @@ titleElement.textContent = this.title; titleElement.title = this.tooltip || ''; this._createIconElement(tabElement, titleElement, measuring); - if (!measuring) + if (!measuring) { this._titleElement = titleElement; + } if (this._closeable) { const closeButton = tabElement.createChild('div', 'tabbed-pane-close-button', 'dt-close-button'); @@ -1158,8 +1225,9 @@ * @param {!Event} event */ _tabMouseDown(event) { - if (event.target.classList.contains('tabbed-pane-close-button') || event.button === 1) + if (event.target.classList.contains('tabbed-pane-close-button') || event.button === 1) { return; + } this._tabbedPane.selectTab(this.id, true); } @@ -1168,8 +1236,9 @@ */ _tabMouseUp(event) { // This is needed to prevent middle-click pasting on linux when tabs are clicked. - if (event.button === 1) + if (event.button === 1) { event.consume(true); + } } /** @@ -1219,8 +1288,9 @@ contextMenu.defaultSection().appendItem(Common.UIString('Close tabs to the right'), closeToTheRight.bind(this)); contextMenu.defaultSection().appendItem(Common.UIString('Close all'), closeAll.bind(this)); } - if (this._delegate) + if (this._delegate) { this._delegate.onContextMenu(this.id, contextMenu); + } contextMenu.show(); } @@ -1229,8 +1299,9 @@ * @return {boolean} */ _startTabDragging(event) { - if (event.target.classList.contains('tabbed-pane-close-button')) + if (event.target.classList.contains('tabbed-pane-close-button')) { return false; + } this._dragStartX = event.pageX; this._tabElement.classList.add('dragging'); this._tabbedPane._tabSlider.remove(); @@ -1244,16 +1315,19 @@ const tabElements = this._tabbedPane._tabsElement.childNodes; for (let i = 0; i < tabElements.length; ++i) { let tabElement = tabElements[i]; - if (tabElement === this._tabElement) + if (tabElement === this._tabElement) { continue; + } const intersects = tabElement.offsetLeft + tabElement.clientWidth > this._tabElement.offsetLeft && this._tabElement.offsetLeft + this._tabElement.clientWidth > tabElement.offsetLeft; - if (!intersects) + if (!intersects) { continue; + } - if (Math.abs(event.pageX - this._dragStartX) < tabElement.clientWidth / 2 + 5) + if (Math.abs(event.pageX - this._dragStartX) < tabElement.clientWidth / 2 + 5) { break; + } if (event.pageX - this._dragStartX > 0) { tabElement = tabElement.nextSibling;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/TextPrompt.js b/third_party/blink/renderer/devtools/front_end/ui/TextPrompt.js index 5f86810..0b32379 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/TextPrompt.js +++ b/third_party/blink/renderer/devtools/front_end/ui/TextPrompt.js
@@ -101,8 +101,9 @@ * @return {!Element} */ _attachInternal(element) { - if (this._proxyElement) + if (this._proxyElement) { throw 'Cannot attach an attached TextPrompt'; + } this._element = element; this._boundOnKeyDown = this.onKeyDown.bind(this); @@ -126,8 +127,9 @@ this._suggestBox = new UI.SuggestBox(this, 20); - if (this._title) + if (this._title) { this._proxyElement.title = this._title; + } return this._proxyElement; } @@ -148,8 +150,9 @@ */ textWithCurrentSuggestion() { const text = this.text(); - if (!this._queryRange || !this._currentSuggestion) + if (!this._queryRange || !this._currentSuggestion) { return text; + } const suggestion = this._currentSuggestion.text; return text.substring(0, this._queryRange.startColumn) + suggestion + text.substring(this._queryRange.endColumn); } @@ -195,8 +198,9 @@ */ setTitle(title) { this._title = title; - if (this._proxyElement) + if (this._proxyElement) { this._proxyElement.title = title; + } } /** @@ -219,10 +223,11 @@ * @param {boolean} enabled */ setEnabled(enabled) { - if (enabled) + if (enabled) { this._element.setAttribute('contenteditable', 'plaintext-only'); - else + } else { this._element.removeAttribute('contenteditable'); + } this._element.classList.toggle('disabled', !enabled); } @@ -232,10 +237,12 @@ this._element.removeEventListener('input', this._boundOnInput, false); this._element.removeEventListener('selectstart', this._boundClearAutocomplete, false); this._element.removeEventListener('blur', this._boundClearAutocomplete, false); - if (this._isEditing) + if (this._isEditing) { this._stopEditing(); - if (this._suggestBox) + } + if (this._suggestBox) { this._suggestBox.hide(); + } } /** @@ -249,17 +256,20 @@ this._element.addEventListener('blur', this._blurListener, false); } this._oldTabIndex = this._element.tabIndex; - if (this._element.tabIndex < 0) + if (this._element.tabIndex < 0) { this._element.tabIndex = 0; + } this._focusRestorer = new UI.ElementFocusRestorer(this._element); - if (!this.text()) + if (!this.text()) { this.autoCompleteSoon(); + } } _stopEditing() { this._element.tabIndex = this._oldTabIndex; - if (this._blurListener) + if (this._blurListener) { this._element.removeEventListener('blur', this._blurListener, false); + } this._contentElement.classList.remove('text-prompt-editing'); delete this._isEditing; } @@ -295,10 +305,11 @@ case 'ArrowRight': case 'ArrowDown': case 'End': - if (this._isCaretAtEndOfPrompt()) + if (this._isCaretAtEndOfPrompt()) { handled = this.acceptAutoComplete(); - else + } else { this.clearAutocomplete(); + } break; case 'Escape': if (this.isSuggestBoxVisible()) { @@ -314,11 +325,13 @@ break; } - if (isEnterKey(event)) + if (isEnterKey(event)) { event.preventDefault(); + } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -327,8 +340,9 @@ */ _acceptSuggestionOnStopCharacters(key) { if (!this._currentSuggestion || !this._queryRange || key.length !== 1 || - !this._completionStopCharacters.includes(key)) + !this._completionStopCharacters.includes(key)) { return false; + } const query = this.text().substring(this._queryRange.startColumn, this._queryRange.endColumn); if (query && this._currentSuggestion.text.startsWith(query + key)) { @@ -345,8 +359,9 @@ const text = this.text(); if (event.data && !this._acceptSuggestionOnStopCharacters(event.data)) { const hasCommonPrefix = text.startsWith(this._previousText) || this._previousText.startsWith(text); - if (this._queryRange && hasCommonPrefix) + if (this._queryRange && hasCommonPrefix) { this._queryRange.endColumn += text.length - this._previousText.length; + } } this._refreshGhostText(); this._previousText = text; @@ -360,10 +375,12 @@ */ acceptAutoComplete() { let result = false; - if (this.isSuggestBoxVisible()) + if (this.isSuggestBoxVisible()) { result = this._suggestBox.acceptSuggestion(); - if (!result) + } + if (!result) { result = this._acceptSuggestionInternal(); + } return result; } @@ -371,14 +388,16 @@ clearAutocomplete() { const beforeText = this.textWithCurrentSuggestion(); - if (this.isSuggestBoxVisible()) + if (this.isSuggestBoxVisible()) { this._suggestBox.hide(); + } this._clearAutocompleteTimeout(); this._queryRange = null; this._refreshGhostText(); - if (beforeText !== this.textWithCurrentSuggestion()) + if (beforeText !== this.textWithCurrentSuggestion()) { this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged); + } } _refreshGhostText() { @@ -422,15 +441,17 @@ this._clearAutocompleteTimeout(); const selection = this._element.getComponentSelection(); const selectionRange = selection && selection.rangeCount ? selection.getRangeAt(0) : null; - if (!selectionRange) + if (!selectionRange) { return; + } let shouldExit; - if (!force && !this._isCaretAtEndOfPrompt() && !this.isSuggestBoxVisible()) + if (!force && !this._isCaretAtEndOfPrompt() && !this.isSuggestBoxVisible()) { shouldExit = true; - else if (!selection.isCollapsed) + } else if (!selection.isCollapsed) { shouldExit = true; + } if (shouldExit) { this.clearAutocomplete(); @@ -492,8 +513,9 @@ * @param {!UI.SuggestBox.Suggestions} completions */ _completionsReady(completionRequestId, selection, originalWordQueryRange, force, completions) { - if (this._completionRequestId !== completionRequestId) + if (this._completionRequestId !== completionRequestId) { return; + } const query = originalWordQueryRange.toString(); @@ -502,10 +524,11 @@ completions = completions.filter(item => !store.has(item.text) && !!store.add(item.text)); if (query || force) { - if (query) + if (query) { completions = completions.concat(this.additionalCompletions(query)); - else + } else { completions = this.additionalCompletions(query).concat(completions); + } } if (!completions.length) { @@ -519,8 +542,9 @@ fullWordRange.setStart(originalWordQueryRange.startContainer, originalWordQueryRange.startOffset); fullWordRange.setEnd(selectionRange.endContainer, selectionRange.endOffset); - if (query + selectionRange.toString() !== fullWordRange.toString()) + if (query + selectionRange.toString() !== fullWordRange.toString()) { return; + } const beforeRange = this._createRange(); beforeRange.setStart(this._element, 0); @@ -544,8 +568,9 @@ applySuggestion(suggestion, isIntermediateSuggestion) { this._currentSuggestion = suggestion; this._refreshGhostText(); - if (isIntermediateSuggestion) + if (isIntermediateSuggestion) { this.dispatchEventToListeners(UI.TextPrompt.Events.TextChanged); + } } /** @@ -559,8 +584,9 @@ * @return {boolean} */ _acceptSuggestionInternal() { - if (!this._queryRange) + if (!this._queryRange) { return false; + } const suggestionLength = this._currentSuggestion ? this._currentSuggestion.text.length : 0; const selectionRange = this._currentSuggestion ? this._currentSuggestion.selectionRange : null; @@ -582,8 +608,9 @@ setDOMSelection(startColumn, endColumn) { this._element.normalize(); const node = this._element.childNodes[0]; - if (!node || node === this._ghostTextElement) + if (!node || node === this._ghostTextElement) { return; + } const range = this._createRange(); range.setStart(node, startColumn); range.setEnd(node, endColumn); @@ -607,8 +634,9 @@ const selection = this._element.getComponentSelection(); // @see crbug.com/602541 const selectionRange = selection && selection.rangeCount ? selection.getRangeAt(0) : null; - if (!selectionRange || !selection.isCollapsed) + if (!selectionRange || !selection.isCollapsed) { return false; + } return selectionRange.startContainer.isSelfOrDescendant(this._element); } @@ -618,24 +646,29 @@ _isCaretAtEndOfPrompt() { const selection = this._element.getComponentSelection(); const selectionRange = selection && selection.rangeCount ? selection.getRangeAt(0) : null; - if (!selectionRange || !selection.isCollapsed) + if (!selectionRange || !selection.isCollapsed) { return false; + } let node = selectionRange.startContainer; - if (!node.isSelfOrDescendant(this._element)) + if (!node.isSelfOrDescendant(this._element)) { return false; + } - if (this._ghostTextElement.isAncestor(node)) + if (this._ghostTextElement.isAncestor(node)) { return true; + } - if (node.nodeType === Node.TEXT_NODE && selectionRange.startOffset < node.nodeValue.length) + if (node.nodeType === Node.TEXT_NODE && selectionRange.startOffset < node.nodeValue.length) { return false; + } let foundNextText = false; while (node) { if (node.nodeType === Node.TEXT_NODE && node.nodeValue.length) { - if (foundNextText && !this._ghostTextElement.isAncestor(node)) + if (foundNextText && !this._ghostTextElement.isAncestor(node)) { return false; + } foundNextText = true; } @@ -650,8 +683,9 @@ const selectionRange = this._createRange(); let container = this._element; - while (container.childNodes.length) + while (container.childNodes.length) { container = container.lastChild; + } const offset = container.nodeType === Node.TEXT_NODE ? container.textContent.length : 0; selectionRange.setStart(container, offset); selectionRange.setEnd(container, offset);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ThrottledWidget.js b/third_party/blink/renderer/devtools/front_end/ui/ThrottledWidget.js index bbb4f37..c08d8d7 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ThrottledWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ThrottledWidget.js
@@ -25,8 +25,9 @@ update() { this._updateWhenVisible = !this.isShowing(); - if (this._updateWhenVisible) + if (this._updateWhenVisible) { return; + } this._updateThrottler.schedule(innerUpdate.bind(this)); /** @@ -34,8 +35,9 @@ * @return {!Promise<?>} */ function innerUpdate() { - if (this.isShowing()) + if (this.isShowing()) { return this.doUpdate(); + } this._updateWhenVisible = true; return Promise.resolve(); } @@ -46,7 +48,8 @@ */ wasShown() { super.wasShown(); - if (this._updateWhenVisible) + if (this._updateWhenVisible) { this.update(); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js b/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js index 7a0a3163..fdb244de 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js
@@ -108,14 +108,16 @@ const topNotBottom = hostButtonPosition.y + buttonHeight * buttons.length < document.documentElement.offsetHeight; - if (topNotBottom) + if (topNotBottom) { buttons = buttons.reverse(); + } optionsBar.element.style.height = (buttonHeight * buttons.length) + 'px'; - if (topNotBottom) + if (topNotBottom) { optionsBar.element.style.top = (hostButtonPosition.y - 5) + 'px'; - else + } else { optionsBar.element.style.top = (hostButtonPosition.y - (buttonHeight * (buttons.length - 1)) - 6) + 'px'; + } optionsBar.element.style.left = (hostButtonPosition.x - 5) + 'px'; for (let i = 0; i < buttons.length; ++i) { @@ -127,22 +129,25 @@ buttons[hostButtonIndex].element.classList.add('emulate-active'); function mouseOver(e) { - if (e.which !== 1) + if (e.which !== 1) { return; + } const buttonElement = e.target.enclosingNodeOrSelfWithClass('toolbar-item'); buttonElement.classList.add('emulate-active'); } function mouseOut(e) { - if (e.which !== 1) + if (e.which !== 1) { return; + } const buttonElement = e.target.enclosingNodeOrSelfWithClass('toolbar-item'); buttonElement.classList.remove('emulate-active'); } function mouseUp(e) { - if (e.which !== 1) + if (e.which !== 1) { return; + } optionsGlassPane.hide(); document.documentElement.removeEventListener('mouseup', mouseUp, false); @@ -165,8 +170,9 @@ static createActionButton(action, showLabel) { const button = action.toggleable() ? makeToggle() : makeButton(); - if (showLabel) + if (showLabel) { button.setText(action.title()); + } button.addEventListener(UI.ToolbarButton.Events.Click, action.execute, action); action.addEventListener(UI.Action.Events.Enabled, enabledChanged); button.setEnabled(action.enabled()); @@ -178,8 +184,9 @@ function makeButton() { const button = new UI.ToolbarButton(action.title(), action.icon()); - if (action.title()) + if (action.title()) { UI.Tooltip.install(button.element, action.title(), action.id()); + } return button; } @@ -195,8 +202,9 @@ function toggled() { toggleButton.setToggled(action.toggled()); - if (action.title()) + if (action.title()) { UI.Tooltip.install(toggleButton.element, action.title(), action.id()); + } } } @@ -230,8 +238,9 @@ */ makeWrappable(growVertically) { this._contentElement.classList.add('wrappable'); - if (growVertically) + if (growVertically) { this._contentElement.classList.add('toolbar-grow-vertical'); + } } makeVertical() { @@ -262,8 +271,9 @@ */ setEnabled(enabled) { this._enabled = enabled; - for (const item of this._items) + for (const item of this._items) { item._applyEnabledState(this._enabled && item._enabled); + } } /** @@ -272,8 +282,9 @@ appendToolbarItem(item) { this._items.push(item); item._toolbar = this; - if (!this._enabled) + if (!this._enabled) { item._applyEnabledState(false); + } this._contentElement.insertBefore(item.element, this._insertionPoint); this._hideSeparatorDupes(); } @@ -294,8 +305,9 @@ } removeToolbarItems() { - for (const item of this._items) + for (const item of this._items) { delete item._toolbar; + } this._items = []; this._contentElement.removeChildren(); this._insertionPoint = this._contentElement.createChild('slot'); @@ -321,8 +333,9 @@ } _hideSeparatorDupes() { - if (!this._items.length) + if (!this._items.length) { return; + } // Don't hide first and last separators if they were added explicitly. let previousIsSeparator = false; let lastSeparator; @@ -340,8 +353,9 @@ nonSeparatorVisible = true; } } - if (lastSeparator && lastSeparator !== this._items.peekLast()) + if (lastSeparator && lastSeparator !== this._items.peekLast()) { lastSeparator.setVisible(false); + } this.element.classList.toggle('hidden', !!lastSeparator && lastSeparator.visible() && !nonSeparatorVisible); } @@ -355,10 +369,12 @@ const filtered = extensions.filter(e => e.descriptor()['location'] === location); const items = await Promise.all(filtered.map(extension => { const descriptor = extension.descriptor(); - if (descriptor['separator']) + if (descriptor['separator']) { return new UI.ToolbarSeparator(); - if (descriptor['actionId']) + } + if (descriptor['actionId']) { return UI.Toolbar.createActionButtonForId(descriptor['actionId'], descriptor['showLabel']); + } return extension.instance().then(p => p.item()); })); items.filter(item => item).forEach(item => this.appendToolbarItem(item)); @@ -384,8 +400,9 @@ * @param {string} title */ setTitle(title) { - if (this._title === title) + if (this._title === title) { return; + } this._title = title; UI.ARIAUtils.setAccessibleName(this.element, title); UI.Tooltip.install(this.element, title); @@ -395,8 +412,9 @@ * @param {boolean} value */ setEnabled(value) { - if (this._enabled === value) + if (this._enabled === value) { return; + } this._enabled = value; this._applyEnabledState(this._enabled && (!this._toolbar || this._toolbar._enabled)); } @@ -419,12 +437,14 @@ * @param {boolean} x */ setVisible(x) { - if (this._visible === x) + if (this._visible === x) { return; + } this.element.classList.toggle('hidden', !x); this._visible = x; - if (this._toolbar && !(this instanceof UI.ToolbarSeparator)) + if (this._toolbar && !(this instanceof UI.ToolbarSeparator)) { this._toolbar._hideSeparatorDupes(); + } } setRightAligned(alignRight) { @@ -479,8 +499,9 @@ this._textElement = this.element.createChild('div', 'toolbar-text hidden'); this.setTitle(title); - if (glyph) + if (glyph) { this.setGlyph(glyph); + } this.setText(text || ''); this._title = ''; } @@ -489,8 +510,9 @@ * @param {string} text */ setText(text) { - if (this._text === text) + if (this._text === text) { return; + } this._textElement.textContent = text; this._textElement.classList.toggle('hidden', !text); this._text = text; @@ -500,8 +522,9 @@ * @param {string} glyph */ setGlyph(glyph) { - if (this._glyph === glyph) + if (this._glyph === glyph) { return; + } this._glyphElement.setIconType(glyph); this._glyphElement.classList.toggle('hidden', !glyph); this.element.classList.toggle('toolbar-has-glyph', !!glyph); @@ -526,16 +549,18 @@ this.element.classList.add('toolbar-has-dropdown'); const dropdownArrowIcon = UI.Icon.create('smallicon-triangle-down', 'toolbar-dropdown-arrow'); this.element.appendChild(dropdownArrowIcon); - if (width) + if (width) { this.element.style.width = width + 'px'; + } } /** * @param {!Event} event */ _clicked(event) { - if (!this._enabled) + if (!this._enabled) { return; + } this.dispatchEventToListeners(UI.ToolbarButton.Events.Click, event); event.consume(); } @@ -544,8 +569,9 @@ * @param {!Event} event */ _mouseDown(event) { - if (!this._enabled) + if (!this._enabled) { return; + } this.dispatchEventToListeners(UI.ToolbarButton.Events.MouseDown, event); } }; @@ -576,15 +602,18 @@ this._proxyElement.classList.add('toolbar-prompt-proxy'); this._proxyElement.addEventListener('keydown', event => this._onKeydownCallback(event)); this._prompt.initialize(completions || (() => Promise.resolve([])), ' '); - if (tooltip) + if (tooltip) { this._prompt.setTitle(tooltip); + } this._prompt.setPlaceholder(placeholder, accessiblePlaceholder); this._prompt.addEventListener(UI.TextPrompt.Events.TextChanged, this._onChangeCallback.bind(this)); - if (growFactor) + if (growFactor) { this.element.style.flexGrow = growFactor; - if (shrinkFactor) + } + if (shrinkFactor) { this.element.style.flexShrink = shrinkFactor; + } const clearButton = this.element.createChild('div', 'toolbar-input-clear-button'); clearButton.appendChild(UI.Icon.create('mediumicon-gray-cross-hover', 'search-cancel-button')); @@ -610,8 +639,9 @@ */ setValue(value, notify) { this._prompt.setText(value); - if (notify) + if (notify) { this._onChangeCallback(); + } this._updateEmptyStyles(); } @@ -626,8 +656,9 @@ * @param {!Event} event */ _onKeydownCallback(event) { - if (!isEscKey(event) || !this._prompt.text()) + if (!isEscKey(event) || !this._prompt.text()) { return; + } this.setValue('', true); event.consume(true); } @@ -675,14 +706,16 @@ * @param {boolean} toggled */ setToggled(toggled) { - if (this._toggled === toggled) + if (this._toggled === toggled) { return; + } this._toggled = toggled; this.element.classList.toggle('toolbar-state-on', toggled); this.element.classList.toggle('toolbar-state-off', !toggled); UI.ARIAUtils.setPressed(this.element, toggled); - if (this._toggledGlyph && this._untoggledGlyph) + if (this._toggledGlyph && this._untoggledGlyph) { this.setGlyph(toggled ? this._toggledGlyph : this._untoggledGlyph); + } } /** @@ -725,8 +758,9 @@ return; } - if (!this._triggerTimeout) + if (!this._triggerTimeout) { this._triggerTimeout = setTimeout(this._trigger.bind(this, event), 200); + } } /** @@ -737,8 +771,9 @@ // Throttling avoids entering a bad state on Macs when rapidly triggering context menus just // after the window gains focus. See crbug.com/655556 - if (this._lastTriggerTime && Date.now() - this._lastTriggerTime < 300) + if (this._lastTriggerTime && Date.now() - this._lastTriggerTime < 300) { return; + } const contextMenu = new UI.ContextMenu( event, this._useSoftMenu, this.element.totalOffsetLeft(), this.element.totalOffsetTop() + this.element.offsetHeight); @@ -752,8 +787,9 @@ * @param {!Event} event */ _clicked(event) { - if (this._triggerTimeout) + if (this._triggerTimeout) { clearTimeout(this._triggerTimeout); + } this._trigger(event); } }; @@ -842,12 +878,14 @@ this._selectElement = this.element.createChild('select', 'toolbar-item'); const dropdownArrowIcon = UI.Icon.create('smallicon-triangle-down', 'toolbar-dropdown-arrow'); this.element.appendChild(dropdownArrowIcon); - if (changeHandler) + if (changeHandler) { this._selectElement.addEventListener('change', changeHandler, false); + } UI.ARIAUtils.setAccessibleName(this._selectElement, title); super.setTitle(title); - if (className) + if (className) { this._selectElement.classList.add(className); + } } /** @@ -886,8 +924,9 @@ createOption(label, value) { const option = this._selectElement.createChild('option'); option.text = label; - if (typeof value !== 'undefined') + if (typeof value !== 'undefined') { option.value = value; + } return option; } @@ -915,8 +954,9 @@ * @return {?Element} */ selectedOption() { - if (this._selectElement.selectedIndex >= 0) + if (this._selectElement.selectedIndex >= 0) { return this._selectElement[this._selectElement.selectedIndex]; + } return null; } @@ -984,8 +1024,9 @@ const dataOption = options[i]; const option = this.createOption(dataOption.label, dataOption.value); this._selectElement.appendChild(option); - if (this._setting.get() === dataOption.value) + if (this._setting.get() === dataOption.value) { this.setSelectedIndex(i); + } } } @@ -997,8 +1038,9 @@ } _settingChanged() { - if (this._muteSettingListener) + if (this._muteSettingListener) { return; + } const value = this._setting.get(); for (let i = 0; i < this._options.length; ++i) { @@ -1033,10 +1075,12 @@ super(UI.CheckboxLabel.create(text)); this.element.classList.add('checkbox'); this.inputElement = this.element.checkboxElement; - if (tooltip) + if (tooltip) { this.element.title = tooltip; - if (listener) + } + if (listener) { this.inputElement.addEventListener('click', listener, false); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Tooltip.js b/third_party/blink/renderer/devtools/front_end/ui/Tooltip.js index 765893a..89e11ef 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Tooltip.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Tooltip.js
@@ -55,18 +55,22 @@ _mouseMove(event) { const mouseEvent = /** @type {!MouseEvent} */ (event); const path = mouseEvent.composedPath(); - if (!path || mouseEvent.buttons !== 0 || (mouseEvent.movementX === 0 && mouseEvent.movementY === 0)) + if (!path || mouseEvent.buttons !== 0 || (mouseEvent.movementX === 0 && mouseEvent.movementY === 0)) { return; + } - if (this._anchorElement && path.indexOf(this._anchorElement) === -1) + if (this._anchorElement && path.indexOf(this._anchorElement) === -1) { this._hide(false); + } for (const element of path) { - if (element === this._anchorElement) + if (element === this._anchorElement) { return; + } // The offsetParent is null when the element or an ancestor has 'display: none'. - if (!(element instanceof Element) || element.offsetParent === null) + if (!(element instanceof Element) || element.offsetParent === null) { continue; + } if (element[UI.Tooltip._symbol]) { this._show(element, mouseEvent); return; @@ -92,10 +96,11 @@ } } - if (typeof tooltip.content === 'string') + if (typeof tooltip.content === 'string') { this._tooltipElement.setTextContentTruncatedIfNeeded(tooltip.content); - else + } else { this._tooltipElement.appendChild(tooltip.content); + } if (tooltip.actionId) { const shortcuts = UI.shortcutRegistry.shortcutDescriptorsForAction(tooltip.actionId); @@ -152,10 +157,12 @@ _hide(removeInstant) { delete this._anchorElement; this._tooltipElement.classList.remove('shown'); - if (Date.now() > this._tooltipLastOpened) + if (Date.now() > this._tooltipLastOpened) { this._tooltipLastClosed = Date.now(); - if (removeInstant) + } + if (removeInstant) { delete this._tooltipLastClosed; + } } _reset() {
diff --git a/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js b/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js index 4ebb7d3..3a0badd 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js +++ b/third_party/blink/renderer/devtools/front_end/ui/UIUtils.js
@@ -49,24 +49,28 @@ const dragHandler = new UI.DragHandler(); const dragStart = dragHandler.elementDragStart.bind( dragHandler, element, elementDragStart, elementDrag, elementDragEnd, cursor, event); - if (startDelay) + if (startDelay) { startTimer = setTimeout(dragStart, startDelay); - else + } else { dragStart(); + } } function onMouseUp() { - if (startTimer) + if (startTimer) { clearTimeout(startTimer); + } startTimer = null; } let startTimer; element.addEventListener('mousedown', onMouseDown, false); - if (startDelay) + if (startDelay) { element.addEventListener('mouseup', onMouseUp, false); - if (hoverCursor !== null) + } + if (hoverCursor !== null) { element.style.cursor = hoverCursor || cursor || ''; + } }; /** @@ -102,11 +106,13 @@ } _disposeGlassPane() { - if (!this._glassPaneInUse) + if (!this._glassPaneInUse) { return; + } this._glassPaneInUse = false; - if (--UI.DragHandler._glassPaneUsageCount) + if (--UI.DragHandler._glassPaneUsageCount) { return; + } UI.DragHandler._glassPane.hide(); delete UI.DragHandler._glassPane; delete UI.DragHandler._documentForMouseOut; @@ -122,14 +128,17 @@ */ elementDragStart(targetElement, elementDragStart, elementDrag, elementDragEnd, cursor, event) { // Only drag upon left button. Right will likely cause a context menu. So will ctrl-click on mac. - if (event.button || (Host.isMac() && event.ctrlKey)) + if (event.button || (Host.isMac() && event.ctrlKey)) { return; + } - if (this._elementDraggingEventListener) + if (this._elementDraggingEventListener) { return; + } - if (elementDragStart && !elementDragStart(/** @type {!MouseEvent} */ (event))) + if (elementDragStart && !elementDragStart(/** @type {!MouseEvent} */ (event))) { return; + } const targetDocument = event.target.ownerDocument; this._elementDraggingEventListener = elementDrag; @@ -147,8 +156,9 @@ targetDocument.addEventListener('mousemove', this._elementDragMove, true); targetDocument.addEventListener('mouseup', this._elementDragEnd, true); targetDocument.addEventListener('mouseout', this._mouseOutWhileDragging, true); - if (targetDocument !== this._dragEventsTargetDocumentTop) + if (targetDocument !== this._dragEventsTargetDocumentTop) { this._dragEventsTargetDocumentTop.addEventListener('mouseup', this._elementDragEnd, true); + } if (typeof cursor === 'string') { this._restoreCursorAfterDrag = restoreCursor.bind(this, targetElement.style.cursor); @@ -173,18 +183,21 @@ } _unregisterMouseOutWhileDragging() { - if (!UI.DragHandler._documentForMouseOut) + if (!UI.DragHandler._documentForMouseOut) { return; + } UI.DragHandler._documentForMouseOut.removeEventListener('mouseout', this._mouseOutWhileDragging, true); } _unregisterDragEvents() { - if (!this._dragEventsTargetDocument) + if (!this._dragEventsTargetDocument) { return; + } this._dragEventsTargetDocument.removeEventListener('mousemove', this._elementDragMove, true); this._dragEventsTargetDocument.removeEventListener('mouseup', this._elementDragEnd, true); - if (this._dragEventsTargetDocument !== this._dragEventsTargetDocumentTop) + if (this._dragEventsTargetDocument !== this._dragEventsTargetDocumentTop) { this._dragEventsTargetDocumentTop.removeEventListener('mouseup', this._elementDragEnd, true); + } delete this._dragEventsTargetDocument; delete this._dragEventsTargetDocumentTop; } @@ -197,8 +210,9 @@ this._elementDragEnd(event); return; } - if (this._elementDraggingEventListener(/** @type {!MouseEvent} */ (event))) + if (this._elementDraggingEventListener(/** @type {!MouseEvent} */ (event))) { this._cancelDragEvents(event); + } } /** @@ -208,8 +222,9 @@ this._unregisterDragEvents(); this._unregisterMouseOutWhileDragging(); - if (this._restoreCursorAfterDrag) + if (this._restoreCursorAfterDrag) { this._restoreCursorAfterDrag(); + } this._disposeGlassPane(); @@ -224,8 +239,9 @@ const elementDragEnd = this._elementEndDraggingEventListener; this._cancelDragEvents(/** @type {!MouseEvent} */ (event)); event.preventDefault(); - if (elementDragEnd) + if (elementDragEnd) { elementDragEnd(/** @type {!MouseEvent} */ (event)); + } } }; @@ -236,18 +252,22 @@ * @return {boolean} */ UI.isBeingEdited = function(node) { - if (!node || node.nodeType !== Node.ELEMENT_NODE) + if (!node || node.nodeType !== Node.ELEMENT_NODE) { return false; + } let element = /** {!Element} */ (node); - if (element.classList.contains('text-prompt') || element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') + if (element.classList.contains('text-prompt') || element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { return true; + } - if (!UI.__editingCount) + if (!UI.__editingCount) { return false; + } while (element) { - if (element.__editing) + if (element.__editing) { return true; + } element = element.parentElementOrShadowHost(); } return false; @@ -258,12 +278,14 @@ * @suppressGlobalPropertiesCheck */ UI.isEditing = function() { - if (UI.__editingCount) + if (UI.__editingCount) { return true; + } const focused = document.deepActiveElement(); - if (!focused) + if (!focused) { return false; + } return focused.classList.contains('text-prompt') || focused.nodeName === 'INPUT' || focused.nodeName === 'TEXTAREA'; }; @@ -274,14 +296,16 @@ */ UI.markBeingEdited = function(element, value) { if (value) { - if (element.__editing) + if (element.__editing) { return false; + } element.classList.add('being-edited'); element.__editing = true; UI.__editingCount = (UI.__editingCount || 0) + 1; } else { - if (!element.__editing) + if (!element.__editing) { return false; + } element.classList.remove('being-edited'); delete element.__editing; --UI.__editingCount; @@ -302,15 +326,17 @@ let direction = null; if (event.type === 'mousewheel') { // When shift is pressed while spinning mousewheel, delta comes as wheelDeltaX. - if (event.wheelDeltaY > 0 || event.wheelDeltaX > 0) + if (event.wheelDeltaY > 0 || event.wheelDeltaX > 0) { direction = 'Up'; - else if (event.wheelDeltaY < 0 || event.wheelDeltaX < 0) + } else if (event.wheelDeltaY < 0 || event.wheelDeltaX < 0) { direction = 'Down'; + } } else { - if (event.key === 'ArrowUp' || event.key === 'PageUp') + if (event.key === 'ArrowUp' || event.key === 'PageUp') { direction = 'Up'; - else if (event.key === 'ArrowDown' || event.key === 'PageDown') + } else if (event.key === 'ArrowDown' || event.key === 'PageDown') { direction = 'Down'; + } } return direction; }; @@ -322,20 +348,23 @@ */ UI._modifiedHexValue = function(hexString, event) { const direction = UI._valueModificationDirection(event); - if (!direction) + if (!direction) { return null; + } const mouseEvent = /** @type {!MouseEvent} */ (event); const number = parseInt(hexString, 16); - if (isNaN(number) || !isFinite(number)) + if (isNaN(number) || !isFinite(number)) { return null; + } const hexStrLen = hexString.length; const channelLen = hexStrLen / 3; // Colors are either rgb or rrggbb. - if (channelLen !== 1 && channelLen !== 2) + if (channelLen !== 1 && channelLen !== 2) { return null; + } // Precision modifier keys work with both mousewheel and up/down keys. // When ctrl is pressed, increase R by 1. @@ -344,16 +373,21 @@ // If no shortcut keys are pressed then increase hex value by 1. // Keys can be pressed together to increase RGB channels. e.g trying different shades. let delta = 0; - if (UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) + if (UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) { delta += Math.pow(16, channelLen * 2); - if (mouseEvent.shiftKey) + } + if (mouseEvent.shiftKey) { delta += Math.pow(16, channelLen); - if (mouseEvent.altKey) + } + if (mouseEvent.altKey) { delta += 1; - if (delta === 0) + } + if (delta === 0) { delta = 1; - if (direction === 'Down') + } + if (direction === 'Down') { delta *= -1; + } // Increase hex value by 1 and clamp from 0 ... maxValue. const maxValue = Math.pow(16, hexStrLen) - 1; @@ -361,8 +395,9 @@ // Ensure the result length is the same as the original hex value. let resultString = result.toString(16).toUpperCase(); - for (let i = 0, lengthDelta = hexStrLen - resultString.length; i < lengthDelta; ++i) + for (let i = 0, lengthDelta = hexStrLen - resultString.length; i < lengthDelta; ++i) { resultString = '0' + resultString; + } return resultString; }; @@ -374,8 +409,9 @@ */ UI._modifiedFloatNumber = function(number, event, modifierMultiplier) { const direction = UI._valueModificationDirection(event); - if (!direction) + if (!direction) { return null; + } const mouseEvent = /** @type {!MouseEvent} */ (event); @@ -385,23 +421,27 @@ // When alt is pressed, increase by 0.1. // Otherwise increase by 1. let delta = 1; - if (UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) + if (UI.KeyboardShortcut.eventHasCtrlOrMeta(mouseEvent)) { delta = 100; - else if (mouseEvent.shiftKey) + } else if (mouseEvent.shiftKey) { delta = 10; - else if (mouseEvent.altKey) + } else if (mouseEvent.altKey) { delta = 0.1; + } - if (direction === 'Down') + if (direction === 'Down') { delta *= -1; - if (modifierMultiplier) + } + if (modifierMultiplier) { delta *= modifierMultiplier; + } // Make the new number and constrain it to a precision of 6, this matches numbers the engine returns. // Use the Number constructor to forget the fixed precision, so 1.100000 will print as 1.1. const result = Number((number + delta).toFixed(6)); - if (!String(result).match(UI._numberRegex)) + if (!String(result).match(UI._numberRegex)) { return null; + } return result; }; @@ -421,8 +461,9 @@ prefix = matches[1]; suffix = matches[3]; number = UI._modifiedHexValue(matches[2], event); - if (number !== null) + if (number !== null) { replacementString = prefix + number + suffix; + } } else { matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString); if (matches && matches.length) { @@ -458,24 +499,28 @@ const arrowKeyOrMouseWheelEvent = (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.type === 'mousewheel'); const pageKeyPressed = (event.key === 'PageUp' || event.key === 'PageDown'); - if (!arrowKeyOrMouseWheelEvent && !pageKeyPressed) + if (!arrowKeyOrMouseWheelEvent && !pageKeyPressed) { return false; + } const selection = element.getComponentSelection(); - if (!selection.rangeCount) + if (!selection.rangeCount) { return false; + } const selectionRange = selection.getRangeAt(0); - if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) + if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element)) { return false; + } const originalValue = element.textContent; const wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, UI.StyleValueDelimiters, element); const wordString = wordRange.toString(); - if (suggestionHandler && suggestionHandler(wordString)) + if (suggestionHandler && suggestionHandler(wordString)) { return false; + } const replacementString = UI.createReplacementString(wordString, event, customNumberHandler); @@ -495,8 +540,9 @@ event.handled = true; event.preventDefault(); - if (finishHandler) + if (finishHandler) { finishHandler(originalValue, replacementString); + } return true; } @@ -541,30 +587,38 @@ * @return {string} */ Number.millisToString = function(ms, higherResolution) { - if (!isFinite(ms)) + if (!isFinite(ms)) { return '-'; + } - if (ms === 0) + if (ms === 0) { return '0'; + } - if (higherResolution && ms < 0.1) + if (higherResolution && ms < 0.1) { return UI._microsFormat.format(ms * 1000); - if (higherResolution && ms < 1000) + } + if (higherResolution && ms < 1000) { return UI._subMillisFormat.format(ms); - if (ms < 1000) + } + if (ms < 1000) { return UI._millisFormat.format(ms); + } const seconds = ms / 1000; - if (seconds < 60) + if (seconds < 60) { return UI._secondsFormat.format(seconds); + } const minutes = seconds / 60; - if (minutes < 60) + if (minutes < 60) { return UI._minutesFormat.format(minutes); + } const hours = minutes / 60; - if (hours < 24) + if (hours < 24) { return UI._hoursFormat.format(hours); + } const days = hours / 24; return UI._daysFormat.format(days); @@ -576,8 +630,9 @@ * @return {string} */ Number.secondsToString = function(seconds, higherResolution) { - if (!isFinite(seconds)) + if (!isFinite(seconds)) { return '-'; + } return Number.millisToString(seconds * 1000, higherResolution); }; @@ -586,20 +641,24 @@ * @return {string} */ Number.bytesToString = function(bytes) { - if (bytes < 1024) + if (bytes < 1024) { return Common.UIString('%.0f\xa0B', bytes); + } const kilobytes = bytes / 1024; - if (kilobytes < 100) + if (kilobytes < 100) { return Common.UIString('%.1f\xa0KB', kilobytes); - if (kilobytes < 1024) + } + if (kilobytes < 1024) { return Common.UIString('%.0f\xa0KB', kilobytes); + } const megabytes = kilobytes / 1024; - if (megabytes < 100) + if (megabytes < 100) { return Common.UIString('%.1f\xa0MB', megabytes); - else + } else { return Common.UIString('%.0f\xa0MB', megabytes); + } }; /** @@ -609,8 +668,9 @@ Number.withThousandsSeparator = function(num) { let str = num + ''; const re = /(\d+)(\d{3})/; - while (str.match(re)) - str = str.replace(re, '$1\xa0$2'); // \xa0 is a non-breaking space + while (str.match(re)) { + str = str.replace(re, '$1\xa0$2'); + } // \xa0 is a non-breaking space return str; }; @@ -661,10 +721,11 @@ */ UI.asyncStackTraceLabel = function(description) { if (description) { - if (description === 'Promise.resolve') + if (description === 'Promise.resolve') { return ls`Promise resolved (async)`; - else if (description === 'Promise.reject') + } else if (description === 'Promise.reject') { return ls`Promise rejected (async)`; + } return ls`${description} (async)`; } return Common.UIString('Async Call'); @@ -678,8 +739,9 @@ element.classList.add('platform-' + Host.platform()); // Detect overlay scrollbar enable by checking for nonzero scrollbar width. - if (!Host.isMac() && UI.measuredScrollbarWidth(element.ownerDocument) === 0) + if (!Host.isMac() && UI.measuredScrollbarWidth(element.ownerDocument) === 0) { element.classList.add('overlay-scrollbar-enabled'); + } }; /** @@ -687,10 +749,12 @@ * @return {number} */ UI.measuredScrollbarWidth = function(document) { - if (typeof UI._measuredScrollbarWidth === 'number') + if (typeof UI._measuredScrollbarWidth === 'number') { return UI._measuredScrollbarWidth; - if (!document) + } + if (!document) { return 16; + } const scrollDiv = document.createElement('div'); scrollDiv.setAttribute('style', 'width: 100px; height: 100px; overflow: scroll;'); document.body.appendChild(scrollDiv); @@ -708,8 +772,9 @@ UI.createShadowRootWithCoreStyles = function(element, cssFile, delegatesFocus) { const shadowRoot = element.attachShadow({mode: 'open', delegatesFocus}); UI._injectCoreStyles(shadowRoot); - if (cssFile) + if (cssFile) { UI.appendStyle(shadowRoot, cssFile); + } shadowRoot.addEventListener('focus', UI._focusChanged.bind(UI), true); return shadowRoot; }; @@ -729,13 +794,15 @@ * @param {!Event} event */ UI._windowFocused = function(document, event) { - if (event.target.document.nodeType === Node.DOCUMENT_NODE) + if (event.target.document.nodeType === Node.DOCUMENT_NODE) { document.body.classList.remove('inactive'); + } UI._keyboardFocus = true; const listener = () => { const activeElement = document.deepActiveElement(); - if (activeElement) + if (activeElement) { activeElement.removeAttribute('data-keyboard-focus'); + } UI._keyboardFocus = false; }; document.defaultView.requestAnimationFrame(() => { @@ -743,7 +810,6 @@ document.removeEventListener('mousedown', listener, true); }); document.addEventListener('mousedown', listener, true); - }; /** @@ -751,8 +817,9 @@ * @param {!Event} event */ UI._windowBlurred = function(document, event) { - if (event.target.document.nodeType === Node.DOCUMENT_NODE) + if (event.target.document.nodeType === Node.DOCUMENT_NODE) { document.body.classList.add('inactive'); + } }; /** @@ -763,8 +830,9 @@ const element = document ? document.deepActiveElement() : null; UI.Widget.focusWidgetForNode(element); UI.XWidget.focusWidgetForNode(element); - if (!UI._keyboardFocus) + if (!UI._keyboardFocus) { return; + } element.setAttribute('data-keyboard-focus', 'true'); element.addEventListener('blur', () => element.removeAttribute('data-keyboard-focus'), {once: true, capture: true}); }; @@ -783,10 +851,12 @@ } restore() { - if (!this._element) + if (!this._element) { return; - if (this._element.hasFocus() && this._previous) + } + if (this._element.hasFocus() && this._previous) { this._previous.focus(); + } this._previous = null; this._element = null; } @@ -824,8 +894,9 @@ element.removeEventListener('webkitAnimationEnd', animationEndCallback, false); } - if (element.classList.contains(className)) + if (element.classList.contains(className)) { element.classList.remove(className); + } element.addEventListener('webkitAnimationEnd', animationEndCallback, false); element.classList.add(className); @@ -849,8 +920,9 @@ .join(''); const ownerDocument = element.ownerDocument; - if (textNodes.length === 0) + if (textNodes.length === 0) { return highlightNodes; + } const nodeRanges = []; let rangeEndOffset = 0; @@ -868,13 +940,16 @@ const endOffset = startOffset + resultRanges[i].length; while (startIndex < textNodes.length && - nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) + nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) { startIndex++; + } let endIndex = startIndex; - while (endIndex < textNodes.length && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) + while (endIndex < textNodes.length && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) { endIndex++; - if (endIndex === textNodes.length) + } + if (endIndex === textNodes.length) { break; + } const highlightNode = ownerDocument.createElement('span'); highlightNode.className = styleClass; @@ -963,10 +1038,11 @@ const result = element.getBoundingClientRect(); element.positionAt(undefined, undefined); - if (oldParent) + if (oldParent) { oldParent.insertBefore(element, oldNextSibling); - else + } else { element.remove(); + } return new UI.Size(result.width, result.height); }; @@ -989,8 +1065,9 @@ add(object, method) { if (!this._handlers) { this._handlers = new Map(); - if (this._autoInvoke) + if (this._autoInvoke) { this.scheduleInvoke(); + } } let methods = this._handlers.get(object); if (!methods) { @@ -1004,8 +1081,9 @@ * @suppressGlobalPropertiesCheck */ scheduleInvoke() { - if (this._handlers) + if (this._handlers) { requestAnimationFrame(this._invoke.bind(this)); + } } _invoke() { @@ -1015,8 +1093,9 @@ for (let i = 0; i < keys.length; ++i) { const object = keys[i]; const methods = handlers.get(object).valuesArray(); - for (let j = 0; j < methods.length; ++j) + for (let j = 0; j < methods.length; ++j) { methods[j].call(object); + } } } }; @@ -1025,13 +1104,15 @@ UI._postUpdateHandlers = null; UI.startBatchUpdate = function() { - if (!UI._coalescingLevel++) + if (!UI._coalescingLevel++) { UI._postUpdateHandlers = new UI.InvokeOnceHandlers(false); + } }; UI.endBatchUpdate = function() { - if (--UI._coalescingLevel) + if (--UI._coalescingLevel) { return; + } UI._postUpdateHandlers.scheduleInvoke(); UI._postUpdateHandlers = null; }; @@ -1041,8 +1122,9 @@ * @param {function()} method */ UI.invokeOnceAfterBatchUpdate = function(object, method) { - if (!UI._postUpdateHandlers) + if (!UI._postUpdateHandlers) { UI._postUpdateHandlers = new UI.InvokeOnceHandlers(true); + } UI._postUpdateHandlers.add(object, method); }; @@ -1061,10 +1143,11 @@ function animationStep(timestamp) { const progress = Number.constrain((timestamp - start) / duration, 0, 1); func(...params.map(p => p.from + (p.to - p.from) * progress)); - if (progress < 1) + if (progress < 1) { raf = window.requestAnimationFrame(animationStep); - else if (animationComplete) + } else if (animationComplete) { animationComplete(); + } } return () => window.cancelAnimationFrame(raf); @@ -1093,8 +1176,9 @@ } _enable() { - if (this._longClickData) + if (this._longClickData) { return; + } const boundMouseDown = mouseDown.bind(this); const boundMouseUp = mouseUp.bind(this); const boundReset = this.reset.bind(this); @@ -1111,8 +1195,9 @@ * @this {UI.LongClickController} */ function mouseDown(e) { - if (e.which !== 1) + if (e.which !== 1) { return; + } const callback = this._callback; this._longClickInterval = setTimeout(callback.bind(null, e), 200); } @@ -1122,15 +1207,17 @@ * @this {UI.LongClickController} */ function mouseUp(e) { - if (e.which !== 1) + if (e.which !== 1) { return; + } this.reset(); } } dispose() { - if (!this._longClickData) + if (!this._longClickData) { return; + } this._element.removeEventListener('mousedown', this._longClickData.mouseDown, false); this._element.removeEventListener('mouseout', this._longClickData.reset, false); this._element.removeEventListener('mouseup', this._longClickData.mouseUp, false); @@ -1153,8 +1240,9 @@ document.defaultView.requestAnimationFrame(() => void(UI._keyboardFocus = false)); }, true); - if (!UI.themeSupport) + if (!UI.themeSupport) { UI.themeSupport = new UI.ThemeSupport(themeSetting); + } UI.themeSupport.applyTheme(document); const body = /** @type {!Element} */ (document.body); @@ -1199,10 +1287,12 @@ const element = createElementWithClass('button', className || ''); element.textContent = text; element.classList.add('text-button'); - if (primary) + if (primary) { element.classList.add('primary-button'); - if (clickHandler) + } + if (clickHandler) { element.addEventListener('click', clickHandler, false); + } element.type = 'button'; return element; }; @@ -1216,8 +1306,9 @@ const element = createElementWithClass('input', className || ''); element.spellcheck = false; element.classList.add('harmony-input'); - if (type) + if (type) { element.type = type; + } return element; }; @@ -1230,8 +1321,9 @@ UI.createLabel = function(title, className, associatedControl) { const element = createElementWithClass('label', className || ''); element.textContent = title; - if (associatedControl) + if (associatedControl) { UI.ARIAUtils.bindLabelToControl(element, associatedControl); + } return element; }; @@ -1284,8 +1376,9 @@ */ UI.appendStyle = function(node, cssFile) { const content = Runtime.cachedResources[cssFile] || ''; - if (!content) + if (!content) { console.error(cssFile + ' not preloaded. Check module.json'); + } let styleElement = createElement('style'); styleElement.textContent = content; node.appendChild(styleElement); @@ -1325,14 +1418,16 @@ * @return {!UI.CheckboxLabel} */ static create(title, checked, subtitle) { - if (!UI.CheckboxLabel._constructor) + if (!UI.CheckboxLabel._constructor) { UI.CheckboxLabel._constructor = UI.registerCustomElement('span', 'dt-checkbox', UI.CheckboxLabel); + } const element = /** @type {!UI.CheckboxLabel} */ (UI.CheckboxLabel._constructor()); element.checkboxElement.checked = !!checked; if (title !== undefined) { element.textElement.textContent = title; - if (subtitle !== undefined) + if (subtitle !== undefined) { element.textElement.createChild('div', 'dt-checkbox-subtitle').textContent = subtitle; + } } return element; } @@ -1391,8 +1486,9 @@ * @this {Element} */ function radioClickHandler(event) { - if (this.radioElement.checked || this.radioElement.disabled) + if (this.radioElement.checked || this.radioElement.disabled) { return; + } this.radioElement.checked = true; this.radioElement.dispatchEvent(new Event('change')); } @@ -1519,8 +1615,9 @@ function onChange() { const {valid} = validate(input.value); input.classList.toggle('error-input', !valid); - if (valid) + if (valid) { apply(input.value); + } } /** @@ -1529,20 +1626,23 @@ function onKeyDown(event) { if (isEnterKey(event)) { const {valid} = validate(input.value); - if (valid) + if (valid) { apply(input.value); + } event.preventDefault(); return; } - if (!numeric) + if (!numeric) { return; + } const value = UI._modifiedFloatNumber(parseFloat(input.value), event, modifierMultiplier); const stringValue = value ? String(value) : ''; const {valid} = validate(stringValue); - if (!valid || !value) + if (!valid || !value) { return; + } input.value = stringValue; apply(input.value); @@ -1553,8 +1653,9 @@ * @param {string} value */ function setValue(value) { - if (value === input.value) + if (value === input.value) { return; + } const {valid} = validate(value); input.classList.toggle('error-input', !valid); input.value = value; @@ -1572,13 +1673,16 @@ */ UI.trimText = function(context, text, maxWidth, trimFunction) { const maxLength = 200; - if (maxWidth <= 10) + if (maxWidth <= 10) { return ''; - if (text.length > maxLength) + } + if (text.length > maxLength) { text = trimFunction(text, maxLength); + } const textWidth = UI.measureTextWidth(context, text); - if (textWidth <= maxWidth) + if (textWidth <= maxWidth) { return text; + } let l = 0; let r = text.length; @@ -1626,8 +1730,9 @@ */ UI.measureTextWidth = function(context, text) { const maxCacheableLength = 200; - if (text.length > maxCacheableLength) + if (text.length > maxCacheableLength) { return context.measureText(text).width; + } let widthCache = UI.measureTextWidth._textWidthCache; if (!widthCache) { @@ -1689,8 +1794,9 @@ injectHighlightStyleSheets(element) { this._injectingStyleSheet = true; UI.appendStyle(element, 'ui/inspectorSyntaxHighlight.css'); - if (this._themeName === 'dark') + if (this._themeName === 'dark') { UI.appendStyle(element, 'ui/inspectorSyntaxHighlightDark.css'); + } this._injectingStyleSheet = false; } @@ -1716,16 +1822,19 @@ * @param {!Document} document */ applyTheme(document) { - if (!this.hasTheme()) + if (!this.hasTheme()) { return; + } - if (this._themeName === 'dark') + if (this._themeName === 'dark') { document.documentElement.classList.add('-theme-with-dark-background'); + } const styleSheets = document.styleSheets; const result = []; - for (let i = 0; i < styleSheets.length; ++i) + for (let i = 0; i < styleSheets.length; ++i) { result.push(this._patchForTheme(styleSheets[i].href, styleSheets[i])); + } result.push('/*# sourceURL=inspector.css.theme */'); const styleElement = createElement('style'); @@ -1740,8 +1849,9 @@ * @suppressGlobalPropertiesCheck */ themeStyleSheet(id, text) { - if (!this.hasTheme() || this._injectingStyleSheet) + if (!this.hasTheme() || this._injectingStyleSheet) { return ''; + } let patch = this._cachedThemePatches.get(id); if (!patch) { @@ -1761,8 +1871,9 @@ */ _patchForTheme(id, styleSheet) { const cached = this._cachedThemePatches.get(id); - if (cached) + if (cached) { return cached; + } try { const rules = styleSheet.cssRules; @@ -1775,10 +1886,12 @@ const output = []; const style = rules[j].style; const selectorText = rules[j].selectorText; - for (let i = 0; style && i < style.length; ++i) + for (let i = 0; style && i < style.length; ++i) { this._patchProperty(selectorText, style, style[i], output); - if (output.length) + } + if (output.length) { result.push(rules[j].selectorText + '{' + output.join('') + '}'); + } } const fullText = result.join('\n'); @@ -1801,31 +1914,39 @@ * - One can create specializations for dark themes via body.-theme-with-dark-background selector in host context. */ _patchProperty(selectorText, style, name, output) { - if (!this._themableProperties.has(name)) + if (!this._themableProperties.has(name)) { return; + } const value = style.getPropertyValue(name); - if (!value || value === 'none' || value === 'inherit' || value === 'initial' || value === 'transparent') + if (!value || value === 'none' || value === 'inherit' || value === 'initial' || value === 'transparent') { return; - if (name === 'background-image' && value.indexOf('gradient') === -1) + } + if (name === 'background-image' && value.indexOf('gradient') === -1) { return; + } - if (selectorText.indexOf('-theme-') !== -1) + if (selectorText.indexOf('-theme-') !== -1) { return; + } let colorUsage = UI.ThemeSupport.ColorUsage.Unknown; - if (name.indexOf('background') === 0 || name.indexOf('border') === 0) + if (name.indexOf('background') === 0 || name.indexOf('border') === 0) { colorUsage |= UI.ThemeSupport.ColorUsage.Background; - if (name.indexOf('background') === -1) + } + if (name.indexOf('background') === -1) { colorUsage |= UI.ThemeSupport.ColorUsage.Foreground; + } output.push(name); output.push(':'); const items = value.replace(Common.Color.Regex, '\0$1\0').split('\0'); - for (let i = 0; i < items.length; ++i) + for (let i = 0; i < items.length; ++i) { output.push(this.patchColorText(items[i], /** @type {!UI.ThemeSupport.ColorUsage} */ (colorUsage))); - if (style.getPropertyPriority(name)) + } + if (style.getPropertyPriority(name)) { output.push(' !important'); + } output.push(';'); } @@ -1836,12 +1957,14 @@ */ patchColorText(text, colorUsage) { const color = Common.Color.parse(text); - if (!color) + if (!color) { return text; + } const outColor = this.patchColor(color, colorUsage); let outText = outColor.asString(null); - if (!outText) + if (!outText) { outText = outColor.asString(outColor.hasAlpha() ? Common.Color.Format.RGBA : Common.Color.Format.RGB); + } return outText || text; } @@ -1873,10 +1996,11 @@ const minCap = colorUsage & UI.ThemeSupport.ColorUsage.Background ? 0.14 : 0; const maxCap = colorUsage & UI.ThemeSupport.ColorUsage.Foreground ? 0.9 : 1; lit = 1 - lit; - if (lit < minCap * 2) + if (lit < minCap * 2) { lit = minCap + lit / 2; - else if (lit > 2 * maxCap - 1) + } else if (lit > 2 * maxCap - 1) { lit = maxCap - 1 / 2 + lit / 2; + } break; } @@ -2027,8 +2151,9 @@ */ UI.createExpandableText = function(text, maxLength) { const clickHandler = () => { - if (expandElement.parentElement) + if (expandElement.parentElement) { expandElement.parentElement.insertBefore(createTextNode(text.slice(maxLength)), expandElement); + } expandElement.remove(); }; const fragment = createDocumentFragment(); @@ -2040,8 +2165,9 @@ expandElement.classList.add('expandable-inline-button'); expandElement.addEventListener('click', clickHandler); expandElement.addEventListener('keydown', event => { - if (event.key === 'Enter' || event.key === ' ') + if (event.key === 'Enter' || event.key === ' ') { clickHandler(); + } }); UI.ARIAUtils.markAsButton(expandElement); @@ -2056,8 +2182,9 @@ InspectorFrontendHost.copyText(text); }); copyButton.addEventListener('keydown', event => { - if (event.key === 'Enter' || event.key === ' ') + if (event.key === 'Enter' || event.key === ' ') { InspectorFrontendHost.copyText(text); + } }); UI.ARIAUtils.markAsButton(copyButton); return fragment; @@ -2083,8 +2210,9 @@ * @return {!Promise<?{node: !Node, tree: ?UI.TreeOutline}>} */ UI.Renderer.render = async function(object, options) { - if (!object) + if (!object) { throw new Error('Can\'t render ' + object); + } const renderer = await self.runtime.extension(UI.Renderer, object).instance(); return renderer ? renderer.render(object, options || {}) : null; };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/View.js b/third_party/blink/renderer/devtools/front_end/ui/View.js index 691eb919a..53efa5e 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/View.js +++ b/third_party/blink/renderer/devtools/front_end/ui/View.js
@@ -194,8 +194,9 @@ return Promise.resolve(result); } - if (this._extension.descriptor()['hasToolbar']) + if (this._extension.descriptor()['hasToolbar']) { return this.widget().then(widget => /** @type {!UI.ToolbarItem.ItemsProvider} */ (widget).toolbarItems()); + } return Promise.resolve([]); } @@ -206,8 +207,9 @@ async widget() { this._widgetRequested = true; const widget = await this._extension.instance(); - if (!(widget instanceof UI.Widget)) + if (!(widget instanceof UI.Widget)) { throw new Error('view className should point to a UI.Widget'); + } widget[UI.View._symbol] = this; return /** @type {!UI.Widget} */ (widget); } @@ -216,8 +218,9 @@ * @override */ async disposeView() { - if (!this._widgetRequested) + if (!this._widgetRequested) { return; + } const widget = await this.widget(); widget.ownerViewDisposed(); } @@ -312,12 +315,14 @@ * @param {!Array<!UI.ToolbarItem>} toolbarItems */ static _populateToolbar(element, toolbarItems) { - if (!toolbarItems.length) + if (!toolbarItems.length) { return; + } const toolbar = new UI.Toolbar(''); element.insertBefore(toolbar.element, element.firstChild); - for (const item of toolbarItems) + for (const item of toolbarItems) { toolbar.appendToolbarItem(item); + } } /** @@ -326,8 +331,9 @@ */ revealView(view) { const location = /** @type {?UI.ViewManager._Location} */ (view[UI.ViewManager._Location.symbol]); - if (!location) + if (!location) { return Promise.resolve(); + } location._reveal(); return location.showView(view); } @@ -371,8 +377,9 @@ } return this.resolveLocation(locationName).then(location => { - if (!location) + if (!location) { throw new Error('Could not resolve location for view: ' + viewId); + } location._reveal(); return location.showView(view, undefined, userGesture, omitFocus); }); @@ -383,13 +390,15 @@ * @return {!Promise<?UI.ViewManager._Location>} */ resolveLocation(location) { - if (!location) + if (!location) { return /** @type {!Promise<?UI.ViewManager._Location>} */ (Promise.resolve(null)); + } const resolverExtensions = self.runtime.extensions(UI.ViewLocationResolver) .filter(extension => extension.descriptor()['name'] === location); - if (!resolverExtensions.length) + if (!resolverExtensions.length) { throw new Error('Unresolved location: ' + location); + } const resolverExtension = resolverExtensions[0]; return resolverExtension.instance().then( resolver => /** @type {?UI.ViewManager._Location} */ (resolver.resolveLocation(location))); @@ -432,8 +441,9 @@ _viewsForLocation(location) { const result = []; for (const id of this._views.keys()) { - if (this._locationNameByViewId.get(id) === location) + if (this._locationNameByViewId.get(id) === location) { result.push(this._views.get(id)); + } } return result; } @@ -459,8 +469,9 @@ * @return {!Promise} */ _materialize() { - if (this._materializePromise) + if (this._materializePromise) { return this._materializePromise; + } const promises = []; promises.push(this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager, this.element))); promises.push(this._view.widget().then(widget => { @@ -469,8 +480,9 @@ this.setDefaultFocusedElement(null); this._view[UI.View._widgetSymbol] = widget; widget.show(this.element); - if (shouldFocus) + if (shouldFocus) { widget.focus(); + } })); this._materializePromise = Promise.all(promises); return this._materializePromise; @@ -521,8 +533,9 @@ * @return {!Promise} */ _materialize() { - if (this._materializePromise) + if (this._materializePromise) { return this._materializePromise; + } const promises = []; promises.push( this._view.toolbarItems().then(UI.ViewManager._populateToolbar.bind(UI.ViewManager, this._titleElement))); @@ -539,8 +552,9 @@ * @return {!Promise} */ _expand() { - if (this._titleElement.classList.contains('expanded')) + if (this._titleElement.classList.contains('expanded')) { return this._materialize(); + } this._titleElement.classList.add('expanded'); UI.ARIAUtils.setExpanded(this._titleElement, true); this._titleExpandIcon.setIconType('smallicon-triangle-down'); @@ -548,8 +562,9 @@ } _collapse() { - if (!this._titleElement.classList.contains('expanded')) + if (!this._titleElement.classList.contains('expanded')) { return; + } this._titleElement.classList.remove('expanded'); UI.ARIAUtils.setExpanded(this._titleElement, false); this._titleExpandIcon.setIconType('smallicon-triangle-right'); @@ -557,10 +572,11 @@ } _toggleExpanded() { - if (this._titleElement.classList.contains('expanded')) + if (this._titleElement.classList.contains('expanded')) { this._collapse(); - else + } else { this._expand(); + } } /** @@ -572,10 +588,11 @@ } else if (event.key === 'ArrowLeft') { this._collapse(); } else if (event.key === 'ArrowRight') { - if (!this._titleElement.classList.contains('expanded')) + if (!this._titleElement.classList.contains('expanded')) { this._expand(); - else if (this._widget) + } else if (this._widget) { this._widget.focus(); + } } } }; @@ -605,8 +622,9 @@ } _reveal() { - if (this._revealCallback) + if (this._revealCallback) { this._revealCallback(); + } } }; @@ -627,8 +645,9 @@ */ constructor(manager, revealCallback, location, restoreSelection, allowReorder, defaultTab) { const tabbedPane = new UI.TabbedPane(); - if (allowReorder) + if (allowReorder) { tabbedPane.setAllowTabReorder(true); + } super(manager, tabbedPane, revealCallback); this._tabbedPane = tabbedPane; @@ -639,15 +658,17 @@ this._closeableTabSetting = Common.settings.createSetting(location + '-closeableTabs', {}); this._tabOrderSetting = Common.settings.createSetting(location + '-tabOrder', {}); this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabOrderChanged, this._persistTabOrder, this); - if (restoreSelection) + if (restoreSelection) { this._lastSelectedTabSetting = Common.settings.createSetting(location + '-selectedTab', ''); + } this._defaultTab = defaultTab; /** @type {!Map.<string, !UI.View>} */ this._views = new Map(); - if (location) + if (location) { this.appendApplicableItems(location); + } } /** @@ -687,8 +708,9 @@ let i = 0; const persistedOrders = this._tabOrderSetting.get(); const orders = new Map(); - for (const view of views) + for (const view of views) { orders.set(view.viewId(), persistedOrders[view.viewId()] || (++i) * UI.ViewManager._TabbedLocation.orderStep); + } views.sort((a, b) => orders.get(a.viewId()) - orders.get(b.viewId())); } @@ -696,17 +718,20 @@ const id = view.viewId(); this._views.set(id, view); view[UI.ViewManager._Location.symbol] = this; - if (view.isTransient()) + if (view.isTransient()) { continue; - if (!view.isCloseable()) + } + if (!view.isCloseable()) { this._appendTab(view); - else if (this._closeableTabSetting.get()[id]) + } else if (this._closeableTabSetting.get()[id]) { this._appendTab(view); + } } - if (this._defaultTab && this._tabbedPane.hasTab(this._defaultTab)) + if (this._defaultTab && this._tabbedPane.hasTab(this._defaultTab)) { this._tabbedPane.selectTab(this._defaultTab); - else if (this._lastSelectedTabSetting && this._tabbedPane.hasTab(this._lastSelectedTabSetting.get())) + } else if (this._lastSelectedTabSetting && this._tabbedPane.hasTab(this._lastSelectedTabSetting.get())) { this._tabbedPane.selectTab(this._lastSelectedTabSetting.get()); + } } /** @@ -737,11 +762,13 @@ * @param {?UI.View=} insertBefore */ appendView(view, insertBefore) { - if (this._tabbedPane.hasTab(view.viewId())) + if (this._tabbedPane.hasTab(view.viewId())) { return; + } const oldLocation = view[UI.ViewManager._Location.symbol]; - if (oldLocation && oldLocation !== this) + if (oldLocation && oldLocation !== this) { oldLocation.removeView(view); + } view[UI.ViewManager._Location.symbol] = this; this._manager._views.set(view.viewId(), view); this._views.set(view.viewId(), view); @@ -788,8 +815,9 @@ showView(view, insertBefore, userGesture, omitFocus) { this.appendView(view, insertBefore); this._tabbedPane.selectTab(view.viewId(), userGesture); - if (!omitFocus) + if (!omitFocus) { this._tabbedPane.focus(); + } const widget = /** @type {!UI.ViewManager._ContainerWidget} */ (this._tabbedPane.tabView(view.viewId())); return widget._materialize(); } @@ -799,8 +827,9 @@ * @override */ removeView(view) { - if (!this._tabbedPane.hasTab(view.viewId())) + if (!this._tabbedPane.hasTab(view.viewId())) { return; + } delete view[UI.ViewManager._Location.symbol]; this._manager._views.delete(view.viewId()); @@ -813,8 +842,9 @@ */ _tabSelected(event) { const tabId = /** @type {string} */ (event.data.tabId); - if (this._lastSelectedTabSetting && event.data['isUserGesture']) + if (this._lastSelectedTabSetting && event.data['isUserGesture']) { this._lastSelectedTabSetting.set(tabId); + } } /** @@ -833,8 +863,9 @@ _persistTabOrder() { const tabIds = this._tabbedPane.tabIds(); const tabOrders = {}; - for (let i = 0; i < tabIds.length; i++) + for (let i = 0; i < tabIds.length; i++) { tabOrders[tabIds[i]] = (i + 1) * UI.ViewManager._TabbedLocation.orderStep; + } const oldTabOrder = this._tabOrderSetting.get(); const oldTabArray = Object.keys(oldTabOrder); @@ -871,8 +902,9 @@ /** @type {!Map<string, !UI.ViewManager._ExpandableContainerWidget>} */ this._expandableContainers = new Map(); - if (location) + if (location) { this.appendApplicableItems(location); + } } /** @@ -882,8 +914,9 @@ */ appendView(view, insertBefore) { const oldLocation = view[UI.ViewManager._Location.symbol]; - if (oldLocation && oldLocation !== this) + if (oldLocation && oldLocation !== this) { oldLocation.removeView(view); + } let container = this._expandableContainers.get(view.viewId()); if (!container) { @@ -918,8 +951,9 @@ */ removeView(view) { const container = this._expandableContainers.get(view.viewId()); - if (!container) + if (!container) { return; + } container.detach(); this._expandableContainers.delete(view.viewId()); @@ -932,8 +966,9 @@ * @param {string} locationName */ appendApplicableItems(locationName) { - for (const view of this._manager._viewsForLocation(locationName)) + for (const view of this._manager._viewsForLocation(locationName)) { this.appendView(view); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Widget.js b/third_party/blink/renderer/devtools/front_end/ui/Widget.js index 3a563b4..5ae5218 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Widget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Widget.js
@@ -56,8 +56,9 @@ static _incrementWidgetCounter(parentElement, childElement) { const count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); - if (!count) + if (!count) { return; + } while (parentElement) { parentElement.__widgetCounter = (parentElement.__widgetCounter || 0) + count; @@ -67,8 +68,9 @@ static _decrementWidgetCounter(parentElement, childElement) { const count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); - if (!count) + if (!count) { return; + } while (parentElement) { parentElement.__widgetCounter -= count; @@ -77,8 +79,9 @@ } static __assert(condition, message) { - if (!condition) + if (!condition) { throw new Error(message); + } } /** @@ -86,12 +89,14 @@ */ static focusWidgetForNode(node) { while (node) { - if (node.__widget) + if (node.__widget) { break; + } node = node.parentNodeOrShadowHost(); } - if (!node) + if (!node) { return; + } let widget = node.__widget; while (widget._parentWidget) { @@ -137,13 +142,16 @@ * @return {boolean} */ shouldHideOnDetach() { - if (!this.element.parentElement) + if (!this.element.parentElement) { return false; - if (this._hideOnDetach) + } + if (this._hideOnDetach) { return true; + } for (const child of this._children) { - if (child.shouldHideOnDetach()) + if (child.shouldHideOnDetach()) { return true; + } } return false; } @@ -160,8 +168,9 @@ } _parentIsShowing() { - if (this._isRoot) + if (this._isRoot) { return true; + } return !!this._parentWidget && this._parentWidget.isShowing(); } @@ -171,8 +180,9 @@ _callOnVisibleChildren(method) { const copy = this._children.slice(); for (let i = 0; i < copy.length; ++i) { - if (copy[i]._parentWidget === this && copy[i]._visible) + if (copy[i]._parentWidget === this && copy[i]._visible) { method.call(copy[i]); + } } } @@ -182,16 +192,18 @@ } _processWasShown() { - if (this._inNotification()) + if (this._inNotification()) { return; + } this.restoreScrollPositions(); this._notify(this.wasShown); this._callOnVisibleChildren(this._processWasShown); } _processWillHide() { - if (this._inNotification()) + if (this._inNotification()) { return; + } this.storeScrollPositions(); this._callOnVisibleChildren(this._processWillHide); @@ -204,10 +216,12 @@ } _processOnResize() { - if (this._inNotification()) + if (this._inNotification()) { return; - if (!this.isShowing()) + } + if (!this.isShowing()) { return; + } this._notify(this.onResize); this._callOnVisibleChildren(this._processOnResize); } @@ -249,8 +263,9 @@ if (!this._isRoot) { // Update widget hierarchy. let currentParent = parentElement; - while (currentParent && !currentParent.__widget) + while (currentParent && !currentParent.__widget) { currentParent = currentParent.parentElementOrShadowHost(); + } UI.Widget.__assert(currentParent, 'Attempt to attach widget to orphan node'); this._attach(currentParent.__widget); } @@ -262,18 +277,21 @@ * @param {!UI.Widget} parentWidget */ _attach(parentWidget) { - if (parentWidget === this._parentWidget) + if (parentWidget === this._parentWidget) { return; - if (this._parentWidget) + } + if (this._parentWidget) { this.detach(); + } this._parentWidget = parentWidget; this._parentWidget._children.push(this); this._isRoot = false; } showWidget() { - if (this._visible) + if (this._visible) { return; + } UI.Widget.__assert(this.element.parentElement, 'Attempt to show widget that is not hidden using hideWidget().'); this._showWidget(/** @type {!Element} */ (this.element.parentElement), this.element.nextSibling); } @@ -284,8 +302,9 @@ */ _showWidget(parentElement, insertBefore) { let currentParent = parentElement; - while (currentParent && !currentParent.__widget) + while (currentParent && !currentParent.__widget) { currentParent = currentParent.parentElementOrShadowHost(); + } if (this._isRoot) { UI.Widget.__assert(!currentParent, 'Attempt to show root widget under another widget'); @@ -296,38 +315,45 @@ } const wasVisible = this._visible; - if (wasVisible && this.element.parentElement === parentElement) + if (wasVisible && this.element.parentElement === parentElement) { return; + } this._visible = true; - if (!wasVisible && this._parentIsShowing()) + if (!wasVisible && this._parentIsShowing()) { this._processWillShow(); + } this.element.classList.remove('hidden'); // Reparent if (this.element.parentElement !== parentElement) { - if (!this._externallyManaged) + if (!this._externallyManaged) { UI.Widget._incrementWidgetCounter(parentElement, this.element); - if (insertBefore) + } + if (insertBefore) { UI.Widget._originalInsertBefore.call(parentElement, this.element, insertBefore); - else + } else { UI.Widget._originalAppendChild.call(parentElement, this.element); + } } - if (!wasVisible && this._parentIsShowing()) + if (!wasVisible && this._parentIsShowing()) { this._processWasShown(); + } - if (this._parentWidget && this._hasNonZeroConstraints()) + if (this._parentWidget && this._hasNonZeroConstraints()) { this._parentWidget.invalidateConstraints(); - else + } else { this._processOnResize(); + } } hideWidget() { - if (!this._visible) + if (!this._visible) { return; + } this._hideWidget(false); } @@ -338,8 +364,9 @@ this._visible = false; const parentElement = this.element.parentElement; - if (this._parentIsShowing()) + if (this._parentIsShowing()) { this._processWillHide(); + } if (removeFromDOM) { // Force legal removal @@ -349,18 +376,21 @@ this.element.classList.add('hidden'); } - if (this._parentIsShowing()) + if (this._parentIsShowing()) { this._processWasHidden(); - if (this._parentWidget && this._hasNonZeroConstraints()) + } + if (this._parentWidget && this._hasNonZeroConstraints()) { this._parentWidget.invalidateConstraints(); + } } /** * @param {boolean=} overrideHideOnDetach */ detach(overrideHideOnDetach) { - if (!this._parentWidget && !this._isRoot) + if (!this._parentWidget && !this._isRoot) { return; + } // hideOnDetach means that we should never remove element from dom - content // has iframes and detaching it will hurt. @@ -382,8 +412,9 @@ const childIndex = this._parentWidget._children.indexOf(this); UI.Widget.__assert(childIndex >= 0, 'Attempt to remove non-child widget'); this._parentWidget._children.splice(childIndex, 1); - if (this._parentWidget._defaultFocusedChild === this) + if (this._parentWidget._defaultFocusedChild === this) { this._parentWidget._defaultFocusedChild = null; + } this._parentWidget.childWasDetached(this); this._parentWidget = null; } else { @@ -393,8 +424,9 @@ detachChildWidgets() { const children = this._children.slice(); - for (let i = 0; i < children.length; ++i) + for (let i = 0; i < children.length; ++i) { children[i].detach(); + } } /** @@ -417,24 +449,29 @@ const elements = this.elementsToRestoreScrollPositionsFor(); for (let i = 0; i < elements.length; ++i) { const container = elements[i]; - if (container._scrollTop) + if (container._scrollTop) { container.scrollTop = container._scrollTop; - if (container._scrollLeft) + } + if (container._scrollLeft) { container.scrollLeft = container._scrollLeft; + } } } doResize() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } // No matter what notification we are in, dispatching onResize is not needed. - if (!this._inNotification()) + if (!this._inNotification()) { this._callOnVisibleChildren(this._processOnResize); + } } doLayout() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } this._notify(this.onLayout); this.doResize(); } @@ -455,11 +492,13 @@ _collectWidgetHierarchy(prefix, lines) { lines.push(prefix + '[' + this.element.className + ']' + (this._children.length ? ' {' : '')); - for (let i = 0; i < this._children.length; ++i) + for (let i = 0; i < this._children.length; ++i) { this._children[i]._collectWidgetHierarchy(prefix + ' ', lines); + } - if (this._children.length) + if (this._children.length) { lines.push(prefix + '}'); + } } /** @@ -478,13 +517,15 @@ } focus() { - if (!this.isShowing()) + if (!this.isShowing()) { return; + } const element = this._defaultFocusedElement; if (element) { - if (!element.hasFocus()) + if (!element.hasFocus()) { element.focus(); + } return; } @@ -526,10 +567,12 @@ * @return {!UI.Constraints} */ constraints() { - if (typeof this._constraints !== 'undefined') + if (typeof this._constraints !== 'undefined') { return this._constraints; - if (typeof this._cachedConstraints === 'undefined') + } + if (typeof this._cachedConstraints === 'undefined') { this._cachedConstraints = this.calculateConstraints(); + } return this._cachedConstraints; } @@ -569,8 +612,9 @@ resumeInvalidations() { --this._invalidationsSuspended; - if (!this._invalidationsSuspended && this._invalidationsRequested) + if (!this._invalidationsSuspended && this._invalidationsRequested) { this.invalidateConstraints(); + } } invalidateConstraints() { @@ -582,10 +626,11 @@ const cached = this._cachedConstraints; delete this._cachedConstraints; const actual = this.constraints(); - if (!actual.isEqual(cached) && this._parentWidget) + if (!actual.isEqual(cached) && this._parentWidget) { this._parentWidget.invalidateConstraints(); - else + } else { this.doLayout(); + } } // Excludes the widget from being tracked by its parents/ancestors via @@ -711,10 +756,12 @@ } restore() { - if (!this._widget) + if (!this._widget) { return; - if (this._widget.hasFocus() && this._previous) + } + if (this._widget.hasFocus() && this._previous) { this._previous.focus(); + } this._previous = null; this._widget = null; }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/XElement.js b/third_party/blink/renderer/devtools/front_end/ui/XElement.js index 189e9fe2..3d17e3e 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/XElement.js +++ b/third_party/blink/renderer/devtools/front_end/ui/XElement.js
@@ -27,12 +27,13 @@ */ attributeChangedCallback(attr, oldValue, newValue) { if (attr === 'flex') { - if (newValue === null) + if (newValue === null) { this.style.removeProperty('flex'); - else if (newValue === 'initial' || newValue === 'auto' || newValue === 'none' || newValue.indexOf(' ') !== -1) + } else if (newValue === 'initial' || newValue === 'auto' || newValue === 'none' || newValue.indexOf(' ') !== -1) { this.style.setProperty('flex', newValue); - else + } else { this.style.setProperty('flex', '0 0 ' + newValue); + } return; } if (newValue === null) { @@ -41,8 +42,9 @@ attr.startsWith('background-') || attr.startsWith('overflow-')) { const shorthand = attr.substring(0, attr.indexOf('-')); const shorthandValue = this.getAttribute(shorthand); - if (shorthandValue !== null) + if (shorthandValue !== null) { this.style.setProperty(shorthand, shorthandValue); + } } } else { this.style.setProperty(attr, newValue); @@ -79,10 +81,11 @@ */ attributeChangedCallback(attr, oldValue, newValue) { if (attr === 'x-start' || attr === 'x-center' || attr === 'x-stretch' || attr === 'x-baseline') { - if (newValue === null) + if (newValue === null) { this.style.removeProperty('align-items'); - else + } else { this.style.setProperty('align-items', attr === 'x-start' ? 'flex-start' : attr.substr(2)); + } return; } super.attributeChangedCallback(attr, oldValue, newValue);
diff --git a/third_party/blink/renderer/devtools/front_end/ui/XLink.js b/third_party/blink/renderer/devtools/front_end/ui/XLink.js index 880060c..6b3e001 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/XLink.js +++ b/third_party/blink/renderer/devtools/front_end/ui/XLink.js
@@ -14,8 +14,9 @@ * @return {!Element} */ static create(url, linkText, className, preventClick) { - if (!linkText) + if (!linkText) { linkText = url; + } className = className || ''; // clang-format off // TODO(dgozman): migrate css from 'devtools-link' to 'x-link'. @@ -73,10 +74,12 @@ if (attr === 'href') { let href = newValue; - if (newValue.trim().toLowerCase().startsWith('javascript:')) + if (newValue.trim().toLowerCase().startsWith('javascript:')) { href = null; - if (Common.ParsedURL.isRelativeURL(newValue)) + } + if (Common.ParsedURL.isRelativeURL(newValue)) { href = null; + } this._href = href; this.title = newValue; @@ -112,10 +115,12 @@ */ appendApplicableItems(event, contextMenu, target) { let targetNode = /** @type {!Node} */ (target); - while (targetNode && !(targetNode instanceof UI.XLink)) + while (targetNode && !(targetNode instanceof UI.XLink)) { targetNode = targetNode.parentNodeOrShadowHost(); - if (!targetNode || !targetNode._href) + } + if (!targetNode || !targetNode._href) { return; + } contextMenu.revealSection().appendItem( UI.openLinkExternallyLabel(), () => InspectorFrontendHost.openInNewTab(targetNode._href)); contextMenu.revealSection().appendItem(
diff --git a/third_party/blink/renderer/devtools/front_end/ui/XWidget.js b/third_party/blink/renderer/devtools/front_end/ui/XWidget.js index 6e33f2b8..03d6124f 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/XWidget.js +++ b/third_party/blink/renderer/devtools/front_end/ui/XWidget.js
@@ -31,8 +31,9 @@ if (!UI.XWidget._observer) { UI.XWidget._observer = new ResizeObserver(entries => { for (const entry of entries) { - if (entry.target._visible && entry.target._onResizedCallback) + if (entry.target._visible && entry.target._onResizedCallback) { entry.target._onResizedCallback.call(null); + } } }); } @@ -49,8 +50,9 @@ let widget = null; while (node) { if (node instanceof UI.XWidget) { - if (widget) + if (widget) { node._defaultFocusedElement = widget; + } widget = node; } node = node.parentNodeOrShadowHost(); @@ -96,19 +98,23 @@ * @param {!Array<!Element>} elements */ setElementsToRestoreScrollPositionsFor(elements) { - for (const element of this._elementsToRestoreScrollPositionsFor) + for (const element of this._elementsToRestoreScrollPositionsFor) { element.removeEventListener('scroll', UI.XWidget._storeScrollPosition, {passive: true, capture: false}); + } this._elementsToRestoreScrollPositionsFor = elements; - for (const element of this._elementsToRestoreScrollPositionsFor) + for (const element of this._elementsToRestoreScrollPositionsFor) { element.addEventListener('scroll', UI.XWidget._storeScrollPosition, {passive: true, capture: false}); + } } restoreScrollPositions() { for (const element of this._elementsToRestoreScrollPositionsFor) { - if (element._scrollTop) + if (element._scrollTop) { element.scrollTop = element._scrollTop; - if (element._scrollLeft) + } + if (element._scrollLeft) { element.scrollLeft = element._scrollLeft; + } } } @@ -125,8 +131,9 @@ * @param {?Element} element */ setDefaultFocusedElement(element) { - if (element && !this.isSelfOrAncestor(element)) + if (element && !this.isSelfOrAncestor(element)) { throw new Error('Default focus must be descendant'); + } this._defaultFocusedElement = element; } @@ -134,8 +141,9 @@ * @override */ focus() { - if (!this._visible) + if (!this._visible) { return; + } let element; if (this._defaultFocusedElement && this.isSelfOrAncestor(this._defaultFocusedElement)) { @@ -153,12 +161,14 @@ } } - if (!element || element.hasFocus()) + if (!element || element.hasFocus()) { return; - if (element === this) + } + if (element === this) { HTMLElement.prototype.focus.call(this); - else + } else { element.focus(); + } } /** @@ -167,8 +177,9 @@ connectedCallback() { this._visible = true; this.restoreScrollPositions(); - if (this._onShownCallback) + if (this._onShownCallback) { this._onShownCallback.call(null); + } } /** @@ -176,8 +187,9 @@ */ disconnectedCallback() { this._visible = false; - if (this._onHiddenCallback) + if (this._onHiddenCallback) { this._onHiddenCallback.call(null); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ZoomManager.js b/third_party/blink/renderer/devtools/front_end/ui/ZoomManager.js index d029538..7a3ffbdb 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/ZoomManager.js +++ b/third_party/blink/renderer/devtools/front_end/ui/ZoomManager.js
@@ -42,8 +42,9 @@ _onWindowResize() { const oldZoomFactor = this._zoomFactor; this._zoomFactor = this._frontendHost.zoomFactor(); - if (oldZoomFactor !== this._zoomFactor) + if (oldZoomFactor !== this._zoomFactor) { this.dispatchEventToListeners(UI.ZoomManager.Events.ZoomChanged, {from: oldZoomFactor, to: this._zoomFactor}); + } } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js b/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js index d95edee..bd4d4e9 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js +++ b/third_party/blink/renderer/devtools/front_end/ui/treeoutline.js
@@ -47,8 +47,9 @@ this._showSelectionOnKeyboardFocus = false; this._focusable = true; this.setFocusable(this._focusable); - if (this._focusable) + if (this._focusable) { this.contentElement.setAttribute('tabIndex', -1); + } this.element = this.contentElement; UI.ARIAUtils.markAsTree(this.element); } @@ -91,8 +92,9 @@ */ _lastDescendent() { let last = this._rootElement.lastChild(); - while (last.expanded && last.childCount()) + while (last.expanded && last.childCount()) { last = last.lastChild(); + } return last; } @@ -129,12 +131,14 @@ */ treeElementFromPoint(x, y) { const node = this.contentElement.ownerDocument.deepElementFromPoint(x, y); - if (!node) + if (!node) { return null; + } const listNode = node.enclosingNodeOrSelfWithNodeNameInArray(['ol', 'li']); - if (listNode) + if (listNode) { return listNode.parentTreeElement || listNode.treeElement; + } return null; } @@ -160,21 +164,24 @@ if (focusable) { this._focusable = true; this.contentElement.setAttribute('tabIndex', -1); - if (this.selectedTreeElement) + if (this.selectedTreeElement) { this.selectedTreeElement._setFocusable(true); + } } else { this._focusable = false; this.contentElement.removeAttribute('tabIndex'); - if (this.selectedTreeElement) + if (this.selectedTreeElement) { this.selectedTreeElement._setFocusable(false); + } } } focus() { - if (this.selectedTreeElement) + if (this.selectedTreeElement) { this.selectedTreeElement.listItemElement.focus(); - else + } else { this.contentElement.focus(); + } } useLightSelectionColor() { @@ -185,8 +192,9 @@ * @param {!UI.TreeElement} element */ _bindTreeElement(element) { - if (element.treeOutline) + if (element.treeOutline) { console.error('Binding element for the second time: ' + new Error().stack); + } element.treeOutline = this; element.onbind(); } @@ -195,8 +203,9 @@ * @param {!UI.TreeElement} element */ _unbindTreeElement(element) { - if (!element.treeOutline) + if (!element.treeOutline) { console.error('Unbinding element that was not bound: ' + new Error().stack); + } element.deselect(); element.onunbind(); @@ -208,10 +217,12 @@ */ selectPrevious() { let nextSelectedElement = this.selectedTreeElement.traversePreviousTreeElement(true); - while (nextSelectedElement && !nextSelectedElement.selectable) + while (nextSelectedElement && !nextSelectedElement.selectable) { nextSelectedElement = nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing); - if (!nextSelectedElement) + } + if (!nextSelectedElement) { return false; + } nextSelectedElement.select(false, true); return true; } @@ -221,17 +232,20 @@ */ selectNext() { let nextSelectedElement = this.selectedTreeElement.traverseNextTreeElement(true); - while (nextSelectedElement && !nextSelectedElement.selectable) + while (nextSelectedElement && !nextSelectedElement.selectable) { nextSelectedElement = nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing); - if (!nextSelectedElement) + } + if (!nextSelectedElement) { return false; + } nextSelectedElement.select(false, true); return true; } forceSelect() { - if (this.selectedTreeElement) + if (this.selectedTreeElement) { this.selectedTreeElement.deselect(); + } this._selectFirst(); } @@ -240,10 +254,12 @@ */ _selectFirst() { let first = this.firstChild(); - while (first && !first.selectable) + while (first && !first.selectable) { first = first.traverseNextTreeElement(true); - if (!first) + } + if (!first) { return false; + } first.select(false, true); return true; } @@ -253,10 +269,12 @@ */ _selectLast() { let last = this._lastDescendent(); - while (last && !last.selectable) + while (last && !last.selectable) { last = last.traversePreviousTreeElement(true); - if (!last) + } + if (!last) { return false; + } last.select(false, true); return true; } @@ -265,8 +283,9 @@ * @param {!Event} event */ _treeKeyDown(event) { - if (!this.selectedTreeElement || event.shiftKey || event.metaKey || event.ctrlKey || UI.isEditing()) + if (!this.selectedTreeElement || event.shiftKey || event.metaKey || event.ctrlKey || UI.isEditing()) { return; + } let handled = false; if (event.key === 'ArrowUp' && !event.altKey) { @@ -294,8 +313,9 @@ handled = this._selectLast(); } - if (handled) + if (handled) { event.consume(true); + } } /** @@ -303,8 +323,9 @@ * @param {boolean} center */ _deferredScrollIntoView(treeElement, center) { - if (!this._treeElementToScrollIntoView) + if (!this._treeElementToScrollIntoView) { this.element.window().requestAnimationFrame(deferredScrollIntoView.bind(this)); + } this._treeElementToScrollIntoView = treeElement; this._centerUponScrollIntoView = center; /** @@ -380,8 +401,9 @@ /** @protected */ this.titleElement = this._listItemNode.createChild('span', 'tree-element-title'); this._listItemNode.treeElement = this; - if (title) + if (title) { this.title = title; + } this._listItemNode.addEventListener('mousedown', this._handleMouseDown.bind(this), false); this._listItemNode.addEventListener('click', this._treeElementToggled.bind(this), false); this._listItemNode.addEventListener('dblclick', this._handleDoubleClick.bind(this), false); @@ -405,13 +427,15 @@ * @return {boolean} */ hasAncestor(ancestor) { - if (!ancestor) + if (!ancestor) { return false; + } let currentNode = this.parent; while (currentNode) { - if (ancestor === currentNode) + if (ancestor === currentNode) { return true; + } currentNode = currentNode.parent; } @@ -474,14 +498,16 @@ * @param {!UI.TreeElement} child */ appendChild(child) { - if (!this._children) + if (!this._children) { this._children = []; + } let insertionIndex; - if (this.treeOutline && this.treeOutline._comparator) + if (this.treeOutline && this.treeOutline._comparator) { insertionIndex = this._children.lowerBound(child, this.treeOutline._comparator); - else + } else { insertionIndex = this._children.length; + } this.insertChild(child, insertionIndex); } @@ -490,11 +516,13 @@ * @param {number} index */ insertChild(child, index) { - if (!this._children) + if (!this._children) { this._children = []; + } - if (!child) + if (!child) { throw 'child can\'t be undefined or null'; + } console.assert( !child.parent, 'Attempting to insert a child that is already in the tree, reparenting is not supported.'); @@ -520,30 +548,36 @@ this.setExpandable(true); child.parent = this; - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline._bindTreeElement(child); + } for (let current = child.firstChild(); this.treeOutline && current; - current = current.traverseNextTreeElement(false, child, true)) + current = current.traverseNextTreeElement(false, child, true)) { this.treeOutline._bindTreeElement(current); + } child.onattach(); child._ensureSelection(); - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementAttached, child); + } const nextSibling = child.nextSibling ? child.nextSibling._listItemNode : null; this._childrenListNode.insertBefore(child._listItemNode, nextSibling); this._childrenListNode.insertBefore(child._childrenListNode, nextSibling); - if (child.selected) + if (child.selected) { child.select(); - if (child.expanded) + } + if (child.expanded) { child.expand(); + } } /** * @param {number} childIndex */ removeChildAtIndex(childIndex) { - if (childIndex < 0 || childIndex >= this._children.length) + if (childIndex < 0 || childIndex >= this._children.length) { throw 'childIndex out of range'; + } const child = this._children[childIndex]; this._children.splice(childIndex, 1); @@ -551,51 +585,61 @@ const parent = child.parent; if (this.treeOutline && this.treeOutline.selectedTreeElement && this.treeOutline.selectedTreeElement.hasAncestorOrSelf(child)) { - if (child.nextSibling) + if (child.nextSibling) { child.nextSibling.select(true); - else if (child.previousSibling) + } else if (child.previousSibling) { child.previousSibling.select(true); - else if (parent) + } else if (parent) { parent.select(true); + } } - if (child.previousSibling) + if (child.previousSibling) { child.previousSibling.nextSibling = child.nextSibling; - if (child.nextSibling) + } + if (child.nextSibling) { child.nextSibling.previousSibling = child.previousSibling; + } child.parent = null; - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline._unbindTreeElement(child); + } for (let current = child.firstChild(); this.treeOutline && current; - current = current.traverseNextTreeElement(false, child, true)) + current = current.traverseNextTreeElement(false, child, true)) { this.treeOutline._unbindTreeElement(current); + } child._detach(); - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementsDetached); + } } /** * @param {!UI.TreeElement} child */ removeChild(child) { - if (!child) + if (!child) { throw 'child can\'t be undefined or null'; - if (child.parent !== this) + } + if (child.parent !== this) { return; + } const childIndex = this._children.indexOf(child); - if (childIndex === -1) + if (childIndex === -1) { throw 'child not found in this node\'s children'; + } this.removeChildAtIndex(childIndex); } removeChildren() { if (!this.root && this.treeOutline && this.treeOutline.selectedTreeElement && - this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this)) + this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this)) { this.select(true); + } for (let i = 0; this._children && i < this._children.length; ++i) { const child = this._children[i]; @@ -603,21 +647,25 @@ child.nextSibling = null; child.parent = null; - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline._unbindTreeElement(child); + } for (let current = child.firstChild(); this.treeOutline && current; - current = current.traverseNextTreeElement(false, child, true)) + current = current.traverseNextTreeElement(false, child, true)) { this.treeOutline._unbindTreeElement(current); + } child._detach(); } this._children = []; - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementsDetached); + } } get selectable() { - if (this._hidden) + if (this._hidden) { return false; + } return this._selectable; } @@ -644,8 +692,9 @@ * @param {string|!Node} x */ set title(x) { - if (this._title === x) + if (this._title === x) { return; + } this._title = x; if (typeof x === 'string') { @@ -657,11 +706,13 @@ } this._listItemNode.removeChildren(); - if (this._leadingIconsElement) + if (this._leadingIconsElement) { this._listItemNode.appendChild(this._leadingIconsElement); + } this._listItemNode.appendChild(this.titleElement); - if (this._trailingIconsElement) + if (this._trailingIconsElement) { this._listItemNode.appendChild(this._trailingIconsElement); + } this._ensureSelection(); } @@ -669,10 +720,12 @@ * @return {string} */ titleAsText() { - if (!this._title) + if (!this._title) { return ''; - if (typeof this._title === 'string') + } + if (typeof this._title === 'string') { return this._title; + } return this._title.textContent; } @@ -688,8 +741,9 @@ * @param {!Array<!UI.Icon>} icons */ setLeadingIcons(icons) { - if (!this._leadingIconsElement && !icons.length) + if (!this._leadingIconsElement && !icons.length) { return; + } if (!this._leadingIconsElement) { this._leadingIconsElement = createElementWithClass('div', 'leading-icons'); this._leadingIconsElement.classList.add('icons-container'); @@ -697,16 +751,18 @@ this._ensureSelection(); } this._leadingIconsElement.removeChildren(); - for (const icon of icons) + for (const icon of icons) { this._leadingIconsElement.appendChild(icon); + } } /** * @param {!Array<!UI.Icon>} icons */ setTrailingIcons(icons) { - if (!this._trailingIconsElement && !icons.length) + if (!this._trailingIconsElement && !icons.length) { return; + } if (!this._trailingIconsElement) { this._trailingIconsElement = createElementWithClass('div', 'trailing-icons'); this._trailingIconsElement.classList.add('icons-container'); @@ -714,8 +770,9 @@ this._ensureSelection(); } this._trailingIconsElement.removeChildren(); - for (const icon of icons) + for (const icon of icons) { this._trailingIconsElement.appendChild(icon); + } } @@ -730,8 +787,9 @@ * @param {string} x */ set tooltip(x) { - if (this._tooltip === x) + if (this._tooltip === x) { return; + } this._tooltip = x; this._listItemNode.title = x; } @@ -747,8 +805,9 @@ * @param {boolean} expandable */ setExpandable(expandable) { - if (this._expandable === expandable) + if (this._expandable === expandable) { return; + } this._expandable = expandable; @@ -765,14 +824,16 @@ * @param {boolean} collapsible */ setCollapsible(collapsible) { - if (this._collapsible === collapsible) + if (this._collapsible === collapsible) { return; + } this._collapsible = collapsible; this._listItemNode.classList.toggle('always-parent', !collapsible); - if (!collapsible) + if (!collapsible) { this.expand(); + } } get hidden() { @@ -780,8 +841,9 @@ } set hidden(x) { - if (this._hidden === x) + if (this._hidden === x) { return; + } this._hidden = x; @@ -798,10 +860,12 @@ _ensureSelection() { - if (!this.treeOutline || !this.treeOutline._renderSelection) + if (!this.treeOutline || !this.treeOutline._renderSelection) { return; - if (!this._selectionElement) + } + if (!this._selectionElement) { this._selectionElement = createElementWithClass('div', 'selection fill'); + } this._listItemNode.insertBefore(this._selectionElement, this.listItemElement.firstChild); } @@ -810,26 +874,30 @@ */ _treeElementToggled(event) { const element = event.currentTarget; - if (element.treeElement !== this || element.hasSelection()) + if (element.treeElement !== this || element.hasSelection()) { return; + } console.assert(!!this.treeOutline); const showSelectionOnKeyboardFocus = this.treeOutline ? this.treeOutline._showSelectionOnKeyboardFocus : false; const toggleOnClick = this.toggleOnClick && (showSelectionOnKeyboardFocus || !this.selectable); const isInTriangle = this.isEventWithinDisclosureTriangle(event); - if (!toggleOnClick && !isInTriangle) + if (!toggleOnClick && !isInTriangle) { return; + } if (this.expanded) { - if (event.altKey) + if (event.altKey) { this.collapseRecursively(); - else + } else { this.collapse(); + } } else { - if (event.altKey) + if (event.altKey) { this.expandRecursively(); - else + } else { this.expand(); + } } event.consume(); } @@ -839,15 +907,19 @@ */ _handleMouseDown(event) { const element = event.currentTarget; - if (!element) + if (!element) { return; - if (!this.selectable) + } + if (!this.selectable) { return; - if (element.treeElement !== this) + } + if (element.treeElement !== this) { return; + } - if (this.isEventWithinDisclosureTriangle(event)) + if (this.isEventWithinDisclosureTriangle(event)) { return; + } this.selectOnMouseDown(event); } @@ -857,14 +929,17 @@ */ _handleDoubleClick(event) { const element = event.currentTarget; - if (!element || element.treeElement !== this) + if (!element || element.treeElement !== this) { return; + } const handled = this.ondblclick(event); - if (handled) + if (handled) { return; - if (this._expandable && !this.expanded) + } + if (this._expandable && !this.expanded) { this.expand(); + } } _detach() { @@ -873,36 +948,42 @@ } collapse() { - if (!this.expanded || !this._collapsible) + if (!this.expanded || !this._collapsible) { return; + } this._listItemNode.classList.remove('expanded'); this._childrenListNode.classList.remove('expanded'); UI.ARIAUtils.setExpanded(this._listItemNode, false); this.expanded = false; this.oncollapse(); - if (this.treeOutline) + if (this.treeOutline) { this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementCollapsed, this); + } } collapseRecursively() { let item = this; while (item) { - if (item.expanded) + if (item.expanded) { item.collapse(); + } item = item.traverseNextTreeElement(false, this, true); } } collapseChildren() { - if (!this._children) + if (!this._children) { return; - for (const child of this._children) + } + for (const child of this._children) { child.collapseRecursively(); + } } expand() { - if (!this._expandable || (this.expanded && this._children)) + if (!this._expandable || (this.expanded && this._children)) { return; + } // Set this before onpopulate. Since onpopulate can add elements, this makes // sure the expanded flag is true before calling those functions. This prevents the possibility @@ -933,14 +1014,16 @@ // The Inspector uses TreeOutlines to represents object properties, so recursive expansion // in some case can be infinite, since JavaScript objects can hold circular references. // So default to a recursion cap of 3 levels, since that gives fairly good results. - if (isNaN(maxDepth)) + if (isNaN(maxDepth)) { maxDepth = 3; + } while (item) { await item._populateIfNeeded(); - if (depth < maxDepth) + if (depth < maxDepth) { item.expand(); + } item = item.traverseNextTreeElement(false, this, (depth >= maxDepth), info); depth += info.depthChange; @@ -953,15 +1036,17 @@ */ collapseOrAscend(altKey) { if (this.expanded && this._collapsible) { - if (altKey) + if (altKey) { this.collapseRecursively(); - else + } else { this.collapse(); + } return true; } - if (!this.parent || this.parent.root) + if (!this.parent || this.parent.root) { return false; + } if (!this.parent.selectable) { this.parent.collapse(); @@ -969,11 +1054,13 @@ } let nextSelectedElement = this.parent; - while (nextSelectedElement && !nextSelectedElement.selectable) + while (nextSelectedElement && !nextSelectedElement.selectable) { nextSelectedElement = nextSelectedElement.parent; + } - if (!nextSelectedElement) + if (!nextSelectedElement) { return false; + } nextSelectedElement.select(false, true); return true; } @@ -983,23 +1070,27 @@ * @return {boolean} */ descendOrExpand(altKey) { - if (!this._expandable) + if (!this._expandable) { return false; + } if (!this.expanded) { - if (altKey) + if (altKey) { this.expandRecursively(); - else + } else { this.expand(); + } return true; } let nextSelectedElement = this.firstChild(); - while (nextSelectedElement && !nextSelectedElement.selectable) + while (nextSelectedElement && !nextSelectedElement.selectable) { nextSelectedElement = nextSelectedElement.nextSibling; + } - if (!nextSelectedElement) + if (!nextSelectedElement) { return false; + } nextSelectedElement.select(false, true); return true; } @@ -1010,8 +1101,9 @@ reveal(center) { let currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) + if (!currentAncestor.expanded) { currentAncestor.expand(); + } currentAncestor = currentAncestor.parent; } @@ -1024,8 +1116,9 @@ revealed() { let currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { - if (!currentAncestor.expanded) + if (!currentAncestor.expanded) { return false; + } currentAncestor = currentAncestor.parent; } @@ -1033,8 +1126,9 @@ } selectOnMouseDown(event) { - if (this.select(false, true)) + if (this.select(false, true)) { event.consume(true); + } if (this._listItemNode.draggable && this._selectionElement) { const marginLeft = @@ -1052,8 +1146,9 @@ */ select(omitFocus, selectedByUser) { if (!this.treeOutline || !this.selectable || this.selected) { - if (!omitFocus) + if (!omitFocus) { this.listItemElement.focus(); + } return false; } // Wait to deselect this element so that focus only changes once @@ -1061,25 +1156,30 @@ this.treeOutline.selectedTreeElement = null; if (this.treeOutline._rootElement === this) { - if (lastSelected) + if (lastSelected) { lastSelected.deselect(); - if (!omitFocus) + } + if (!omitFocus) { this.listItemElement.focus(); + } return false; } this.selected = true; this.treeOutline.selectedTreeElement = this; - if (this.treeOutline._focusable) + if (this.treeOutline._focusable) { this._setFocusable(true); - if (!omitFocus || this.treeOutline.contentElement.hasFocus()) + } + if (!omitFocus || this.treeOutline.contentElement.hasFocus()) { this.listItemElement.focus(); + } this._listItemNode.classList.add('selected'); this.treeOutline.dispatchEventToListeners(UI.TreeOutline.Events.ElementSelected, this); - if (lastSelected) + if (lastSelected) { lastSelected.deselect(); + } return this.onselect(selectedByUser); } @@ -1099,17 +1199,21 @@ } _onFocus() { - if (this.treeOutline._useLightSelectionColor) + if (this.treeOutline._useLightSelectionColor) { return; - if (!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred')) + } + if (!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred')) { this._listItemNode.classList.add('force-white-icons'); + } } _onBlur() { - if (this.treeOutline._useLightSelectionColor) + if (this.treeOutline._useLightSelectionColor) { return; - if (!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred')) + } + if (!this.treeOutline.contentElement.classList.contains('hide-selection-when-blurred')) { this._listItemNode.classList.remove('force-white-icons'); + } } /** @@ -1128,8 +1232,9 @@ if (this.treeOutline && this.treeOutline.selectedTreeElement === this) { this.treeOutline.selectedTreeElement = null; - if (hadFocus) + if (hadFocus) { this.treeOutline.focus(); + } } } @@ -1210,37 +1315,44 @@ * @return {?UI.TreeElement} */ traverseNextTreeElement(skipUnrevealed, stayWithin, dontPopulate, info) { - if (!dontPopulate) + if (!dontPopulate) { this._populateIfNeeded(); + } - if (info) + if (info) { info.depthChange = 0; + } let element = skipUnrevealed ? (this.revealed() ? this.firstChild() : null) : this.firstChild(); if (element && (!skipUnrevealed || (skipUnrevealed && this.expanded))) { - if (info) + if (info) { info.depthChange = 1; + } return element; } - if (this === stayWithin) + if (this === stayWithin) { return null; + } element = skipUnrevealed ? (this.revealed() ? this.nextSibling : null) : this.nextSibling; - if (element) + if (element) { return element; + } element = this; while (element && !element.root && !(skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling) && element.parent !== stayWithin) { - if (info) + if (info) { info.depthChange -= 1; + } element = element.parent; } - if (!element || element.root) + if (!element || element.root) { return null; + } return (skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling); } @@ -1252,23 +1364,27 @@ */ traversePreviousTreeElement(skipUnrevealed, dontPopulate) { let element = skipUnrevealed ? (this.revealed() ? this.previousSibling : null) : this.previousSibling; - if (!dontPopulate && element) + if (!dontPopulate && element) { element._populateIfNeeded(); + } while (element && (skipUnrevealed ? (element.revealed() && element.expanded ? element.lastChild() : null) : element.lastChild())) { - if (!dontPopulate) + if (!dontPopulate) { element._populateIfNeeded(); + } element = (skipUnrevealed ? (element.revealed() && element.expanded ? element.lastChild() : null) : element.lastChild()); } - if (element) + if (element) { return element; + } - if (!this.parent || this.parent.root) + if (!this.parent || this.parent.root) { return null; + } return this.parent; }
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextContentBuilder.js b/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextContentBuilder.js index 9c35e34..495214e 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextContentBuilder.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextContentBuilder.js
@@ -21,8 +21,9 @@ this._addTitle(title, context.contextId); this._addEntry(ls`State`, context.contextState); this._addEntry(ls`Sample Rate`, context.sampleRate, 'Hz'); - if (context.contextType === 'realtime') + if (context.contextType === 'realtime') { this._addEntry(ls`Callback Buffer Size`, context.callbackBufferSize, 'frames'); + } this._addEntry(ls`Max Output Channels`, context.maxOutputChannelCount, 'ch'); }
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextSelector.js b/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextSelector.js index 4ccc3c7..2ae61c0 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextSelector.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/AudioContextSelector.js
@@ -38,8 +38,9 @@ this._items.insert(this._items.length, context); // Select if this is the first item. - if (this._items.length === 1) + if (this._items.length === 1) { this._dropDown.selectItem(context); + } } /** @@ -48,8 +49,9 @@ contextDestroyed(event) { const contextId = /** @type {!Protocol.WebAudio.GraphObjectId} */ (event.data); const contextIndex = this._items.findIndex(context => context.contextId === contextId); - if (contextIndex > -1) + if (contextIndex > -1) { this._items.remove(contextIndex); + } } /** @@ -64,8 +66,9 @@ // If the changed context is currently selected by user. Re-select it // because the actual element is replaced with a new one. - if (this._selectedContext && this._selectedContext.contextId === changedContext.contextId) + if (this._selectedContext && this._selectedContext.contextId === changedContext.contextId) { this._dropDown.selectItem(changedContext); + } } } @@ -86,8 +89,9 @@ * @return {?Protocol.WebAudio.BaseAudioContext} */ selectedContext() { - if (!this._selectedContext) + if (!this._selectedContext) { return null; + } return this._selectedContext; } @@ -100,10 +104,12 @@ * @param {?Element} toElement */ highlightedItemChanged(from, to, fromElement, toElement) { - if (fromElement) + if (fromElement) { fromElement.classList.remove('highlighted'); - if (toElement) + } + if (toElement) { toElement.classList.add('highlighted'); + } } /** @@ -120,12 +126,14 @@ * @param {?Protocol.WebAudio.BaseAudioContext} item */ itemSelected(item) { - if (!item) + if (!item) { return; + } // It's possible that no context is selected yet. - if (!this._selectedContext || this._selectedContext.contextId !== item.contextId) + if (!this._selectedContext || this._selectedContext.contextId !== item.contextId) { this._selectedContext = item; + } this.dispatchEventToListeners(WebAudio.AudioContextSelector.Events.ContextSelected, item); }
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioModel.js b/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioModel.js index 19a856b..66e8ca71 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioModel.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioModel.js
@@ -47,14 +47,16 @@ * @return {!Promise} */ resumeModel() { - if (!this._enabled) + if (!this._enabled) { return Promise.resolve(); + } return this._agent.enable(); } ensureEnabled() { - if (this._enabled) + if (this._enabled) { return; + } this._agent.enable(); this._enabled = true; }
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioView.js b/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioView.js index 9616596..03108d4 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioView.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/WebAudioView.js
@@ -53,16 +53,18 @@ */ wasShown() { super.wasShown(); - for (const model of SDK.targetManager.models(WebAudio.WebAudioModel)) + for (const model of SDK.targetManager.models(WebAudio.WebAudioModel)) { this._addEventListeners(model); + } } /** * @override */ willHide() { - for (const model of SDK.targetManager.models(WebAudio.WebAudioModel)) + for (const model of SDK.targetManager.models(WebAudio.WebAudioModel)) { this._removeEventListeners(model); + } } /** @@ -70,8 +72,9 @@ * @param {!WebAudio.WebAudioModel} webAudioModel */ modelAdded(webAudioModel) { - if (this.isShowing()) + if (this.isShowing()) { this._addEventListeners(webAudioModel); + } } /** @@ -167,15 +170,17 @@ */ _contextChanged(event) { const context = /** @type {!Protocol.WebAudio.BaseAudioContext} */ (event.data); - if (!this._graphManager.hasContext(context.contextId)) + if (!this._graphManager.hasContext(context.contextId)) { return; + } this._contextSelector.contextChanged(event); } _reset() { - if (this._landingPage.isShowing()) + if (this._landingPage.isShowing()) { this._landingPage.detach(); + } this._contextSelector.reset(); this._detailViewContainer.removeChildren(); this._landingPage.show(this._detailViewContainer); @@ -192,8 +197,9 @@ _audioListenerCreated(event) { const listener = /** @type {!Protocol.WebAudio.AudioListener} */ (event.data); const graph = this._graphManager.getGraph(listener.contextId); - if (!graph) + if (!graph) { return; + } graph.addNode({ nodeId: listener.listenerId, nodeType: 'Listener', @@ -208,8 +214,9 @@ _audioListenerWillBeDestroyed(event) { const {contextId, listenerId} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } graph.removeNode(listenerId); } @@ -219,8 +226,9 @@ _audioNodeCreated(event) { const node = /** @type {!Protocol.WebAudio.AudioNode} */ (event.data); const graph = this._graphManager.getGraph(node.contextId); - if (!graph) + if (!graph) { return; + } graph.addNode({ nodeId: node.nodeId, nodeType: node.nodeType, @@ -235,8 +243,9 @@ _audioNodeWillBeDestroyed(event) { const {contextId, nodeId} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } graph.removeNode(nodeId); } @@ -246,8 +255,9 @@ _audioParamCreated(event) { const param = /** @type {!Protocol.WebAudio.AudioParam} */ (event.data); const graph = this._graphManager.getGraph(param.contextId); - if (!graph) + if (!graph) { return; + } graph.addParam({ paramId: param.paramId, paramType: param.paramType, @@ -261,8 +271,9 @@ _audioParamWillBeDestroyed(event) { const {contextId, paramId} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } graph.removeParam(paramId); } @@ -272,8 +283,9 @@ _nodesConnected(event) { const {contextId, sourceId, destinationId, sourceOutputIndex, destinationInputIndex} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } graph.addNodeToNodeConnection({ sourceId, destinationId, @@ -288,8 +300,9 @@ _nodesDisconnected(event) { const {contextId, sourceId, destinationId, sourceOutputIndex, destinationInputIndex} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } graph.removeNodeToNodeConnection({ sourceId, destinationId, @@ -304,13 +317,15 @@ _nodeParamConnected(event) { const {contextId, sourceId, destinationId, sourceOutputIndex} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } // Since the destinationId is AudioParamId, we need to find the nodeId as the // real destinationId. const nodeId = graph.getNodeIdByParamId(destinationId); - if (!nodeId) + if (!nodeId) { return; + } graph.addNodeToParamConnection({ sourceId, destinationId: nodeId, @@ -325,13 +340,15 @@ _nodeParamDisconnected(event) { const {contextId, sourceId, destinationId, sourceOutputIndex} = event.data; const graph = this._graphManager.getGraph(contextId); - if (!graph) + if (!graph) { return; + } // Since the destinationId is AudioParamId, we need to find the nodeId as the // real destinationId. const nodeId = graph.getNodeIdByParamId(destinationId); - if (!nodeId) + if (!nodeId) { return; + } graph.removeNodeToParamConnection({ sourceId, destinationId: nodeId, @@ -344,8 +361,9 @@ * @param {!Protocol.WebAudio.BaseAudioContext} context */ _updateDetailView(context) { - if (this._landingPage.isShowing()) + if (this._landingPage.isShowing()) { this._landingPage.detach(); + } const detailBuilder = new WebAudio.ContextDetailBuilder(context); this._detailViewContainer.removeChildren(); this._detailViewContainer.appendChild(detailBuilder.getFragment()); @@ -376,11 +394,13 @@ for (const model of SDK.targetManager.models(WebAudio.WebAudioModel)) { // Display summary only for real-time context. if (context.contextType === 'realtime') { - if (!this._graphManager.hasContext(context.contextId)) + if (!this._graphManager.hasContext(context.contextId)) { continue; + } const realtimeData = await model.requestRealtimeData(context.contextId); - if (realtimeData) + if (realtimeData) { this._updateSummaryBar(context.contextId, realtimeData); + } } else { this._clearSummaryBar(); }
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphManager.js b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphManager.js index b184897..1ac22bf 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphManager.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphManager.js
@@ -26,8 +26,9 @@ * @param {!Protocol.WebAudio.GraphObjectId} contextId */ destroyContext(contextId) { - if (!this._graphMapByContextId.has(contextId)) + if (!this._graphMapByContextId.has(contextId)) { return; + } const graph = this._graphMapByContextId.get(contextId); graph.removeEventListener(WebAudio.GraphVisualizer.GraphView.Events.ShouldRedraw, this._notifyShouldRedraw, this);
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphView.js b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphView.js index c61d4146..24b33dc3 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphView.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/GraphView.js
@@ -166,8 +166,9 @@ _addEdge(edge) { const sourceId = edge.sourceId; // Do nothing if the edge already exists. - if (this._outboundEdgeMap.hasValue(sourceId, edge.id)) + if (this._outboundEdgeMap.hasValue(sourceId, edge.id)) { return; + } this._edges.set(edge.id, edge); this._outboundEdgeMap.set(sourceId, edge.id); @@ -183,8 +184,9 @@ */ _removeEdge(edgeId) { const edge = this._edges.get(edgeId); - if (!edge) + if (!edge) { return; + } this._outboundEdgeMap.delete(edge.sourceId, edgeId); this._inboundEdgeMap.delete(edge.destinationId, edgeId);
diff --git a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/NodeView.js b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/NodeView.js index ea10aa80..33a0a78 100644 --- a/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/NodeView.js +++ b/third_party/blink/renderer/devtools/front_end/web_audio/graph_visualizer/NodeView.js
@@ -78,8 +78,9 @@ getPortsByType(type) { const result = []; this.ports.forEach(port => { - if (port.type === type) + if (port.type === type) { result.push(port); + } }); return result; } @@ -235,8 +236,9 @@ */ generateLabel(nodeType) { // To make the label concise, remove the suffix "Node" from the nodeType. - if (nodeType.endsWith('Node')) + if (nodeType.endsWith('Node')) { nodeType = nodeType.slice(0, nodeType.length - 4); + } // Also, use an integer to replace the long UUID. this._totalNumberOfNodes += 1; @@ -252,8 +254,9 @@ * @return {number} */ WebAudio.GraphVisualizer.measureTextWidth = (text, fontStyle) => { - if (!WebAudio.GraphVisualizer._contextForFontTextMeasuring) + if (!WebAudio.GraphVisualizer._contextForFontTextMeasuring) { WebAudio.GraphVisualizer._contextForFontTextMeasuring = createElement('canvas').getContext('2d'); + } const context = WebAudio.GraphVisualizer._contextForFontTextMeasuring; context.save();
diff --git a/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js b/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js index 5cca9a54..9105900e 100644 --- a/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js +++ b/third_party/blink/renderer/devtools/front_end/worker_main/WorkerMain.js
@@ -19,12 +19,15 @@ SDK.ChildTargetManager.install(async ({target, waitingForDebugger}) => { // Only pause the new worker if debugging SW - we are going through the pause on start checkbox. - if (target.parentTarget() || target.type() !== SDK.Target.Type.ServiceWorker || !waitingForDebugger) + if (target.parentTarget() || target.type() !== SDK.Target.Type.ServiceWorker || !waitingForDebugger) { return; + } const debuggerModel = target.model(SDK.DebuggerModel); - if (!debuggerModel) + if (!debuggerModel) { return; - if (!debuggerModel.isReadyToPause()) + } + if (!debuggerModel.isReadyToPause()) { await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause); + } debuggerModel.pause(); });
diff --git a/third_party/blink/renderer/devtools/front_end/worker_service/ServiceDispatcher.js b/third_party/blink/renderer/devtools/front_end/worker_service/ServiceDispatcher.js index 7eb451f..ff6d9b5 100644 --- a/third_party/blink/renderer/devtools/front_end/worker_service/ServiceDispatcher.js +++ b/third_party/blink/renderer/devtools/front_end/worker_service/ServiceDispatcher.js
@@ -100,8 +100,9 @@ } _connectionClosed() { - for (const object of this._objects.values()) + for (const object of this._objects.values()) { object.dispose(); + } this._objects.clear(); }
diff --git a/third_party/blink/renderer/devtools/front_end/workspace/FileManager.js b/third_party/blink/renderer/devtools/front_end/workspace/FileManager.js index 21b5cbe..7155113 100644 --- a/third_party/blink/renderer/devtools/front_end/workspace/FileManager.js +++ b/third_party/blink/renderer/devtools/front_end/workspace/FileManager.js
@@ -63,8 +63,9 @@ const url = /** @type {string} */ (event.data.url); const callback = this._saveCallbacks.get(url); this._saveCallbacks.delete(url); - if (callback) + if (callback) { callback({fileSystemPath: /** @type {string} */ (event.data.fileSystemPath)}); + } } /** @@ -74,8 +75,9 @@ const url = /** @type {string} */ (event.data); const callback = this._saveCallbacks.get(url); this._saveCallbacks.delete(url); - if (callback) + if (callback) { callback(null); + } } /**
diff --git a/third_party/blink/renderer/devtools/front_end/workspace/UISourceCode.js b/third_party/blink/renderer/devtools/front_end/workspace/UISourceCode.js index 50e5b31..e5c8a0f 100644 --- a/third_party/blink/renderer/devtools/front_end/workspace/UISourceCode.js +++ b/third_party/blink/renderer/devtools/front_end/workspace/UISourceCode.js
@@ -47,8 +47,9 @@ this._origin = parsedURL.securityOrigin(); this._parentURL = this._origin + parsedURL.folderPathComponents; this._name = parsedURL.lastPathComponent; - if (parsedURL.queryParams) + if (parsedURL.queryParams) { this._name += '?' + parsedURL.queryParams; + } } else { this._origin = ''; this._parentURL = ''; @@ -132,14 +133,16 @@ * @return {string} */ displayName(skipTrim) { - if (!this._name) + if (!this._name) { return Common.UIString('(index)'); + } let name = this._name; try { - if (this.project().type() === Workspace.projectTypes.FileSystem) + if (this.project().type() === Workspace.projectTypes.FileSystem) { name = unescape(name); - else + } else { name = decodeURI(name); + } } catch (e) { } return skipTrim ? name : name.trimEndWithMaxLength(100); @@ -192,10 +195,12 @@ const oldURL = this._url; this._url = this._url.substring(0, this._url.length - this._name.length) + name; this._name = name; - if (url) + if (url) { this._url = url; - if (contentType) + } + if (contentType) { this._contentType = contentType; + } this.dispatchEventToListeners(Workspace.UISourceCode.Events.TitleChanged, this); this.project().workspace().dispatchEventToListeners( Workspace.Workspace.Events.UISourceCodeRenamed, {oldURL: oldURL, uiSourceCode: this}); @@ -238,8 +243,9 @@ * @return {!Promise<string>} */ requestContent() { - if (this._requestContentPromise) + if (this._requestContentPromise) { return this._requestContentPromise; + } if (this._contentLoaded) { this._requestContentPromise = Promise.resolve(this._content || ''); @@ -259,11 +265,13 @@ } checkContentUpdated() { - if (!this._contentLoaded && !this._forceLoadOnCheckContent) + if (!this._contentLoaded && !this._forceLoadOnCheckContent) { return; + } - if (!this._project.canSetFileContent() || this._checkingContent) + if (!this._project.canSetFileContent() || this._checkingContent) { return; + } this._checkingContent = true; this._project.requestFileContent(this, contentLoaded.bind(this)); @@ -281,8 +289,9 @@ this.setWorkingCopy(workingCopy); return; } - if (this._lastAcceptedContent === updatedContent) + if (this._lastAcceptedContent === updatedContent) { return; + } if (this._content === updatedContent) { this._lastAcceptedContent = null; @@ -301,10 +310,11 @@ const shouldUpdate = window.confirm(Common.UIString('This file was changed externally. Would you like to reload it?')); - if (shouldUpdate) + if (shouldUpdate) { this._contentCommitted(/** @type {string} */ (updatedContent), false); - else + } else { this._lastAcceptedContent = updatedContent; + } } } @@ -316,8 +326,9 @@ * @param {string} content */ _commitContent(content) { - if (this._project.canSetFileContent()) + if (this._project.canSetFileContent()) { this._project.setFileContent(this, content, false); + } this._contentCommitted(content, true); } @@ -337,8 +348,9 @@ const data = {uiSourceCode: this, content, encoded: this._contentEncoded}; this.dispatchEventToListeners(Workspace.UISourceCode.Events.WorkingCopyCommitted, data); this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommitted, data); - if (committedByUser) + if (committedByUser) { this._project.workspace().dispatchEventToListeners(Workspace.Workspace.Events.WorkingCopyCommittedByUser, data); + } } /** @@ -363,8 +375,9 @@ this._workingCopy = this._workingCopyGetter(); this._workingCopyGetter = null; } - if (this.isDirty()) + if (this.isDirty()) { return /** @type {string} */ (this._workingCopy); + } return this._content || ''; } @@ -393,8 +406,9 @@ */ setContent(content, isBase64) { this._contentEncoded = isBase64; - if (this._project.canSetFileContent()) + if (this._project.canSetFileContent()) { this._project.setFileContent(this, content, isBase64); + } this._contentCommitted(content, true); } @@ -414,15 +428,17 @@ } removeWorkingCopyGetter() { - if (!this._workingCopyGetter) + if (!this._workingCopyGetter) { return; + } this._workingCopy = this._workingCopyGetter(); this._workingCopyGetter = null; } commitWorkingCopy() { - if (this.isDirty()) + if (this.isDirty()) { this._commitContent(this.workingCopy()); + } } /** @@ -455,8 +471,9 @@ */ searchInContent(query, caseSensitive, isRegex) { const content = this.content(); - if (!content) + if (!content) { return this._project.searchInFileContent(this, query, caseSensitive, isRegex); + } return Promise.resolve(Common.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex)); } @@ -473,8 +490,9 @@ * @return {!Workspace.UILocation} */ uiLocation(lineNumber, columnNumber) { - if (typeof columnNumber === 'undefined') + if (typeof columnNumber === 'undefined') { columnNumber = 0; + } return new Workspace.UILocation(this, lineNumber, columnNumber); } @@ -505,8 +523,9 @@ */ addMessage(level, text, range) { const message = new Workspace.UISourceCode.Message(this, level, text, range); - if (!this._messages) + if (!this._messages) { this._messages = new Set(); + } this._messages.add(message); this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageAdded, message); return message; @@ -516,15 +535,18 @@ * @param {!Workspace.UISourceCode.Message} message */ removeMessage(message) { - if (this._messages && this._messages.delete(message)) + if (this._messages && this._messages.delete(message)) { this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved, message); + } } _removeAllMessages() { - if (!this._messages) + if (!this._messages) { return; - for (const message of this._messages) + } + for (const message of this._messages) { this.dispatchEventToListeners(Workspace.UISourceCode.Events.MessageRemoved, message); + } this._messages = null; } @@ -544,8 +566,9 @@ */ addDecoration(range, type, data) { const marker = new Workspace.UISourceCode.LineMarker(range, type, data); - if (!this._decorations) + if (!this._decorations) { this._decorations = new Multimap(); + } this._decorations.set(type, marker); this.dispatchEventToListeners(Workspace.UISourceCode.Events.LineDecorationAdded, marker); } @@ -554,8 +577,9 @@ * @param {string} type */ removeDecorationsForType(type) { - if (!this._decorations) + if (!this._decorations) { return; + } const markers = this._decorations.get(type); this._decorations.deleteAll(type); markers.forEach(marker => { @@ -571,8 +595,9 @@ } removeAllDecorations() { - if (!this._decorations) + if (!this._decorations) { return; + } const decorationList = this._decorations.valuesArray(); this._decorations.clear(); decorationList.forEach( @@ -620,8 +645,9 @@ */ linkText(skipTrim) { let linkText = this.uiSourceCode.displayName(skipTrim); - if (typeof this.lineNumber === 'number') + if (typeof this.lineNumber === 'number') { linkText += ':' + (this.lineNumber + 1); + } return linkText; } @@ -654,10 +680,12 @@ * @return {number} */ compareTo(other) { - if (this.uiSourceCode.url() !== other.uiSourceCode.url()) + if (this.uiSourceCode.url() !== other.uiSourceCode.url()) { return this.uiSourceCode.url() > other.uiSourceCode.url() ? 1 : -1; - if (this.lineNumber !== other.lineNumber) + } + if (this.lineNumber !== other.lineNumber) { return this.lineNumber - other.lineNumber; + } return this.columnNumber - other.columnNumber; } };
diff --git a/third_party/blink/renderer/devtools/front_end/workspace/Workspace.js b/third_party/blink/renderer/devtools/front_end/workspace/Workspace.js index 54a4c98e..c858526 100644 --- a/third_party/blink/renderer/devtools/front_end/workspace/Workspace.js +++ b/third_party/blink/renderer/devtools/front_end/workspace/Workspace.js
@@ -285,8 +285,9 @@ */ addUISourceCode(uiSourceCode) { const url = uiSourceCode.url(); - if (this.uiSourceCodeForURL(url)) + if (this.uiSourceCodeForURL(url)) { return false; + } this._uiSourceCodesMap.set(url, {uiSourceCode: uiSourceCode, index: this._uiSourceCodesList.length}); this._uiSourceCodesList.push(uiSourceCode); this._workspace.dispatchEventToListeners(Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCode); @@ -298,8 +299,9 @@ */ removeUISourceCode(url) { const uiSourceCode = this.uiSourceCodeForURL(url); - if (!uiSourceCode) + if (!uiSourceCode) { return; + } const entry = this._uiSourceCodesMap.get(url); const movedUISourceCode = this._uiSourceCodesList[this._uiSourceCodesList.length - 1]; @@ -375,8 +377,9 @@ uiSourceCodeForURL(url) { for (const project of this._projects.values()) { const uiSourceCode = project.uiSourceCodeForURL(url); - if (uiSourceCode) + if (uiSourceCode) { return uiSourceCode; + } } return null; } @@ -388,8 +391,9 @@ uiSourceCodesForProjectType(type) { let result = []; for (const project of this._projects.values()) { - if (project.type() === type) + if (project.type() === type) { result = result.concat(project.uiSourceCodes()); + } } return result; } @@ -442,8 +446,9 @@ */ uiSourceCodes() { let result = []; - for (const project of this._projects.values()) + for (const project of this._projects.values()) { result = result.concat(project.uiSourceCodes()); + } return result; }
diff --git a/third_party/blink/renderer/devtools/front_end/workspace_diff/WorkspaceDiff.js b/third_party/blink/renderer/devtools/front_end/workspace_diff/WorkspaceDiff.js index 4e05823..b50c3875 100644 --- a/third_party/blink/renderer/devtools/front_end/workspace_diff/WorkspaceDiff.js +++ b/third_party/blink/renderer/devtools/front_end/workspace_diff/WorkspaceDiff.js
@@ -71,8 +71,9 @@ * @return {!WorkspaceDiff.WorkspaceDiff.UISourceCodeDiff} */ _uiSourceCodeDiff(uiSourceCode) { - if (!this._uiSourceCodeDiffs.has(uiSourceCode)) + if (!this._uiSourceCodeDiffs.has(uiSourceCode)) { this._uiSourceCodeDiffs.set(uiSourceCode, new WorkspaceDiff.WorkspaceDiff.UISourceCodeDiff(uiSourceCode)); + } return this._uiSourceCodeDiffs.get(uiSourceCode); } @@ -105,8 +106,9 @@ */ _projectRemoved(event) { const project = /** @type {!Workspace.Project} */ (event.data); - for (const uiSourceCode of project.uiSourceCodes()) + for (const uiSourceCode of project.uiSourceCodes()) { this._removeUISourceCode(uiSourceCode); + } } /** @@ -115,8 +117,9 @@ _removeUISourceCode(uiSourceCode) { this._loadingUISourceCodes.delete(uiSourceCode); const uiSourceCodeDiff = this._uiSourceCodeDiffs.get(uiSourceCode); - if (uiSourceCodeDiff) + if (uiSourceCodeDiff) { uiSourceCodeDiff._dispose = true; + } this._markAsUnmodified(uiSourceCode); } @@ -125,8 +128,9 @@ */ _markAsUnmodified(uiSourceCode) { this._uiSourceCodeProcessedForTest(); - if (this._modifiedUISourceCodes.delete(uiSourceCode)) + if (this._modifiedUISourceCodes.delete(uiSourceCode)) { this.dispatchEventToListeners(WorkspaceDiff.Events.ModifiedStatusChanged, {uiSourceCode, isModified: false}); + } } /** @@ -134,8 +138,9 @@ */ _markAsModified(uiSourceCode) { this._uiSourceCodeProcessedForTest(); - if (this._modifiedUISourceCodes.has(uiSourceCode)) + if (this._modifiedUISourceCodes.has(uiSourceCode)) { return; + } this._modifiedUISourceCodes.add(uiSourceCode); this.dispatchEventToListeners(WorkspaceDiff.Events.ModifiedStatusChanged, {uiSourceCode, isModified: true}); } @@ -166,14 +171,16 @@ Promise.all([this.requestOriginalContentForUISourceCode(uiSourceCode), uiSourceCode.requestContent()]); this._loadingUISourceCodes.set(uiSourceCode, contentsPromise); const contents = await contentsPromise; - if (this._loadingUISourceCodes.get(uiSourceCode) !== contentsPromise) + if (this._loadingUISourceCodes.get(uiSourceCode) !== contentsPromise) { return; + } this._loadingUISourceCodes.delete(uiSourceCode); - if (contents[0] !== null && contents[1] !== null && contents[0] !== contents[1]) + if (contents[0] !== null && contents[1] !== null && contents[0] !== contents[1]) { this._markAsModified(uiSourceCode); - else + } else { this._markAsUnmodified(uiSourceCode); + } } /** @@ -193,8 +200,9 @@ * @param {?string} content */ function callback(content) { - if (typeof content !== 'string') + if (typeof content !== 'string') { return; + } uiSourceCode.addRevision(content); } @@ -233,8 +241,9 @@ * @this {WorkspaceDiff.WorkspaceDiff.UISourceCodeDiff} */ function emitDiffChanged() { - if (this._dispose) + if (this._dispose) { return; + } this.dispatchEventToListeners(WorkspaceDiff.Events.DiffChanged); this._pendingChanges = null; } @@ -244,8 +253,9 @@ * @return {!Promise<?Diff.Diff.DiffArray>} */ requestDiff() { - if (!this._requestDiffPromise) + if (!this._requestDiffPromise) { this._requestDiffPromise = this._innerRequestDiff(); + } return this._requestDiffPromise; } @@ -255,8 +265,9 @@ _originalContent() { const originalNetworkContent = Persistence.networkPersistenceManager.originalContentForUISourceCode(this._uiSourceCode); - if (originalNetworkContent) + if (originalNetworkContent) { return originalNetworkContent; + } let callback; const promise = new Promise(fulfill => callback = fulfill); @@ -268,28 +279,35 @@ * @return {!Promise<?Diff.Diff.DiffArray>} */ async _innerRequestDiff() { - if (this._dispose) + if (this._dispose) { return null; + } const baseline = await this._originalContent(); - if (baseline.length > 1024 * 1024) + if (baseline.length > 1024 * 1024) { return null; + } // ------------ ASYNC ------------ - if (this._dispose) + if (this._dispose) { return null; + } let current = this._uiSourceCode.workingCopy(); - if (!current && !this._uiSourceCode.contentLoaded()) + if (!current && !this._uiSourceCode.contentLoaded()) { current = await this._uiSourceCode.requestContent(); - if (current.length > 1024 * 1024) + } + if (current.length > 1024 * 1024) { return null; + } // ------------ ASYNC ------------ - if (this._dispose) + if (this._dispose) { return null; + } - if (current === null || baseline === null) + if (current === null || baseline === null) { return null; + } return Diff.Diff.lineDiff(baseline.split(/\r\n|\n|\r/), current.split(/\r\n|\n|\r/)); } }; @@ -306,8 +324,9 @@ * @return {!WorkspaceDiff.WorkspaceDiff} */ WorkspaceDiff.workspaceDiff = function() { - if (!WorkspaceDiff.WorkspaceDiff._instance) + if (!WorkspaceDiff.WorkspaceDiff._instance) { WorkspaceDiff.WorkspaceDiff._instance = new WorkspaceDiff.WorkspaceDiff(Workspace.workspace); + } return WorkspaceDiff.WorkspaceDiff._instance; };
diff --git a/third_party/blink/renderer/devtools/karma.conf.js b/third_party/blink/renderer/devtools/karma.conf.js index 860d9bf..916bf48 100644 --- a/third_party/blink/renderer/devtools/karma.conf.js +++ b/third_party/blink/renderer/devtools/karma.conf.js
@@ -13,15 +13,13 @@ },{ pattern: 'tests/**/*.ts', type: 'module' - }, { - pattern: 'tests/**/*.js', - type: 'module' }], - reporters: ["dots"], + reporters: ["dots", "coverage-istanbul"], preprocessors: { - './tests/**/*.ts': ['karma-typescript'] + './tests/**/*.ts': ['karma-typescript'], + './front_end/common/*.js': ['karma-coverage-istanbul-instrumenter'] }, browsers: ["ChromeHeadless"], @@ -55,9 +53,20 @@ "karma-chrome-launcher", "karma-mocha", "karma-chai", - "karma-typescript" + "karma-typescript", + require('../../../../third_party/devtools-node-modules/third_party/node_modules/karma-coverage-istanbul-instrumenter'), + require('../../../../third_party/devtools-node-modules/third_party/node_modules/karma-coverage-istanbul-reporter') ], + coverageIstanbulInstrumenter: { + esModules: true + }, + + coverageIstanbulReporter: { + reports: ["text", "html"], + dir: "karma-coverage" + }, + singleRun: true };
diff --git a/third_party/blink/renderer/devtools/scripts/lint_javascript.py b/third_party/blink/renderer/devtools/scripts/lint_javascript.py index 3d43a5c..4479e58 100755 --- a/third_party/blink/renderer/devtools/scripts/lint_javascript.py +++ b/third_party/blink/renderer/devtools/scripts/lint_javascript.py
@@ -69,6 +69,7 @@ to_platform_path_exact(eslintconfig_path), "--ignore-path", to_platform_path_exact(eslintignore_path), + "--fix", ] + files_list eslint_proc = popen(exec_command, cwd=devtools_path)
diff --git a/third_party/blink/renderer/devtools/tests/front_end/common/Trie.ts b/third_party/blink/renderer/devtools/tests/front_end/common/Trie.ts new file mode 100644 index 0000000..15298958 --- /dev/null +++ b/third_party/blink/renderer/devtools/tests/front_end/common/Trie.ts
@@ -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. + +const { assert } = chai; + +import { default as Trie } from '../../../front_end/common/Trie.js'; + +describe('Trie', () => { + let trie: Trie; + beforeEach(() => { + trie = new Trie(); + }); + + it('stores and retrieves words', () => { + trie.add('foo'); + assert.isTrue(trie.has('foo')); + assert.isFalse(trie.has('bar')); + }); + + it('removes words', () => { + trie.add('foo'); + assert.isTrue(trie.has('foo')); + trie.remove('foo'); + assert.isFalse(trie.has('foo')); + }); + + it('completes words based on prefixes', () => { + trie.add('foo'); + trie.add('food'); + trie.add('flora'); + trie.add('boat'); + trie.add('focus'); + trie.add('banana'); + assert.deepEqual(trie.words('fo'), ['foo', 'food', 'focus']); + assert.isEmpty(trie.words('cat')); + }); + + it('clears words', () => { + trie.add('foo'); + assert.isTrue(trie.has('foo')); + + trie.clear(); + assert.isFalse(trie.has('foo')); + assert.isEmpty(trie.words('foo')); + }); + + it('provides the longest prefix', () => { + trie.add('super'); + trie.add('supercar'); + + // Longest non-word prefix match. + assert.equal(trie.longestPrefix('supercalifragilisticexpialidocious', false), 'superca'); + + // Longest word prefix match. + assert.equal(trie.longestPrefix('supercalifragilisticexpialidocious', true), 'super'); + }); +});
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index b41b2d36..cb95ccb6 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -103,6 +103,7 @@ "//third_party/blink/renderer/modules/credentialmanager", "//third_party/blink/renderer/modules/crypto", "//third_party/blink/renderer/modules/csspaint", + "//third_party/blink/renderer/modules/compression", "//third_party/blink/renderer/modules/device_orientation", "//third_party/blink/renderer/modules/document_metadata", "//third_party/blink/renderer/modules/donottrack",
diff --git a/third_party/blink/renderer/modules/badging/badge.cc b/third_party/blink/renderer/modules/badging/badge.cc index f0fe9433..64e28e1 100644 --- a/third_party/blink/renderer/modules/badging/badge.cc +++ b/third_party/blink/renderer/modules/badging/badge.cc
@@ -79,7 +79,7 @@ if (!scope_url) return; - badge_service_->SetBadge(*scope_url, std::move(value)); + badge_service_->SetBadge(std::move(value)); } void Badge::ClearBadge(WTF::String scope, ExceptionState& exception_state) { @@ -87,7 +87,7 @@ if (!scope_url) return; - badge_service_->ClearBadge(*scope_url); + badge_service_->ClearBadge(); } void Badge::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/modules/cache_storage/cache.cc b/third_party/blink/renderer/modules/cache_storage/cache.cc index 849a7b8..2970003 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache.cc
@@ -7,12 +7,9 @@ #include <memory> #include <utility> -#include "base/feature_list.h" #include "base/optional.h" #include "services/network/public/mojom/fetch_api.mojom-blink.h" #include "third_party/blink/public/common/cache_storage/cache_storage_utils.h" -#include "third_party/blink/public/common/features.h" -#include "third_party/blink/public/common/service_worker/service_worker_utils.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" @@ -48,7 +45,6 @@ #include "third_party/blink/renderer/platform/network/http_parsers.h" #include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" -#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { @@ -76,38 +72,22 @@ return MIMETypeRegistry::IsSupportedJavaScriptMIMEType(mime_type); } -enum class CodeCacheGenerateTiming { - kDontGenerate, - kGenerateNow, - kGenerateWhenIdle, -}; - -CodeCacheGenerateTiming ShouldGenerateV8CodeCache(ScriptState* script_state, - const Response* response) { - EagerCodeCacheStrategy strategy = - ServiceWorkerUtils::GetEagerCodeCacheStrategy(); - if (strategy == EagerCodeCacheStrategy::kDontGenerate) - return CodeCacheGenerateTiming::kDontGenerate; - +bool ShouldGenerateV8CodeCache(ScriptState* script_state, + const Response* response) { ExecutionContext* context = ExecutionContext::From(script_state); auto* global_scope = DynamicTo<ServiceWorkerGlobalScope>(context); if (!global_scope) - return CodeCacheGenerateTiming::kDontGenerate; + return false; + + if (!global_scope->IsInstalling()) + return false; if (!HasJavascriptMimeType(response)) - return CodeCacheGenerateTiming::kDontGenerate; + return false; if (!response->InternalBodyBuffer()) - return CodeCacheGenerateTiming::kDontGenerate; - - if (global_scope->IsInstalling()) - return CodeCacheGenerateTiming::kGenerateNow; - - if (strategy == EagerCodeCacheStrategy::kOnIdleTask) { - return CodeCacheGenerateTiming::kGenerateWhenIdle; - } - - return CodeCacheGenerateTiming::kDontGenerate; + return false; + return true; } } // namespace @@ -406,27 +386,19 @@ public: CodeCacheHandleCallbackForPut(ScriptState* script_state, - Cache* cache, wtf_size_t index, BarrierCallbackForPut* barrier_callback, Request* request, Response* response, - CodeCacheGenerateTiming timing, int64_t trace_id) : script_state_(script_state), - cache_(cache), index_(index), barrier_callback_(barrier_callback), mime_type_(response->InternalMIMEType()), - timing_(timing), trace_id_(trace_id) { fetch_api_request_ = request->CreateFetchAPIRequest(); fetch_api_response_ = response->PopulateFetchAPIResponse(); url_ = fetch_api_request_->url; - opaque_mode_ = fetch_api_response_->response_type == - network::mojom::FetchResponseType::kOpaque - ? V8CodeCache::OpaqueMode::kOpaque - : V8CodeCache::OpaqueMode::kNotOpaque; } ~CodeCacheHandleCallbackForPut() override = default; @@ -437,7 +409,6 @@ TRACE_ID_GLOBAL(trace_id_), TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "url", CacheStorageTracedValue(url_.GetString())); - base::Time response_time = fetch_api_response_->response_time; mojom::blink::BatchOperationPtr batch_operation = mojom::blink::BatchOperation::New(); batch_operation->operation_type = mojom::blink::OperationType::kPut; @@ -450,33 +421,17 @@ batch_operation->response->blob = BlobDataHandle::Create( std::move(blob_data), array_buffer->ByteLength()); - if (timing_ == CodeCacheGenerateTiming::kGenerateNow) { - scoped_refptr<CachedMetadata> cached_metadata = - GenerateFullCodeCache(array_buffer); - if (cached_metadata) { - base::span<const uint8_t> serialized_data = - cached_metadata->SerializedData(); - auto side_data_blob_data = std::make_unique<BlobData>(); - side_data_blob_data->AppendBytes(serialized_data.data(), - serialized_data.size()); + scoped_refptr<CachedMetadata> cached_metadata = + GenerateFullCodeCache(array_buffer); + if (cached_metadata) { + base::span<const uint8_t> serialized_data = + cached_metadata->SerializedData(); + auto side_data_blob_data = std::make_unique<BlobData>(); + side_data_blob_data->AppendBytes(serialized_data.data(), + serialized_data.size()); - batch_operation->response->side_data_blob = BlobDataHandle::Create( - std::move(side_data_blob_data), serialized_data.size()); - } - } else { - // Schedule an idle task to generate code cache later. - ServiceWorkerGlobalScope* global_scope = GetServiceWorkerGlobalScope(); - if (global_scope) { - auto* thread_scheduler = - global_scope->GetScheduler()->GetWorkerThreadScheduler(); - DCHECK(thread_scheduler); - int task_id = global_scope->WillStartTask(); - thread_scheduler->IdleTaskRunner()->PostIdleTask( - FROM_HERE, WTF::Bind(&Cache::CodeCacheHandleCallbackForPut:: - GenerateCodeCacheOnIdleTask, - WrapPersistent(this), task_id, - WrapPersistent(array_buffer), response_time)); - } + batch_operation->response->side_data_blob = BlobDataHandle::Create( + std::move(side_data_blob_data), serialized_data.size()); } barrier_callback_->OnSuccess(index_, std::move(batch_operation)); @@ -490,7 +445,6 @@ void Trace(blink::Visitor* visitor) override { visitor->Trace(script_state_); - visitor->Trace(cache_); visitor->Trace(barrier_callback_); FetchDataLoader::Client::Trace(visitor); } @@ -528,45 +482,12 @@ url_, text_decoder->Encoding(), opaque_mode_); } - void GenerateCodeCacheOnIdleTask(int task_id, - DOMArrayBuffer* array_buffer, - base::Time response_time, - base::TimeTicks) { - TRACE_EVENT_WITH_FLOW1( - "CacheStorage", - "Cache::CodeCacheHandleCallbackForPut::GenerateCodeCacheOnIdleTask", - TRACE_ID_GLOBAL(trace_id_), - TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "url", - CacheStorageTracedValue(url_.GetString())); - - ServiceWorkerGlobalScope* global_scope = GetServiceWorkerGlobalScope(); - if (!global_scope) - return; - - scoped_refptr<CachedMetadata> cached_metadata = - GenerateFullCodeCache(array_buffer); - if (!cached_metadata) { - global_scope->DidEndTask(task_id); - return; - } - cache_->cache_remote_->SetSideData( - url_, response_time, cached_metadata->SerializedData(), trace_id_, - WTF::Bind( - [](ServiceWorkerGlobalScope* global_scope, int task_id, - mojom::blink::CacheStorageError error) { - global_scope->DidEndTask(task_id); - }, - WrapPersistent(global_scope), task_id)); - } - const Member<ScriptState> script_state_; - const Member<Cache> cache_; const wtf_size_t index_; Member<BarrierCallbackForPut> barrier_callback_; const String mime_type_; KURL url_; V8CodeCache::OpaqueMode opaque_mode_; - CodeCacheGenerateTiming timing_; const int64_t trace_id_; mojom::blink::FetchAPIRequestPtr fetch_api_request_; @@ -1014,16 +935,13 @@ BodyStreamBuffer* buffer = responses[i]->InternalBodyBuffer(); - CodeCacheGenerateTiming cache_generate_timing = - ShouldGenerateV8CodeCache(script_state, responses[i]); - if (cache_generate_timing != CodeCacheGenerateTiming::kDontGenerate) { + if (ShouldGenerateV8CodeCache(script_state, responses[i])) { FetchDataLoader* loader = FetchDataLoader::CreateLoaderAsArrayBuffer(); - buffer->StartLoading( - loader, - MakeGarbageCollected<CodeCacheHandleCallbackForPut>( - script_state, this, i, barrier_callback, requests[i], - responses[i], cache_generate_timing, trace_id), - exception_state); + buffer->StartLoading(loader, + MakeGarbageCollected<CodeCacheHandleCallbackForPut>( + script_state, i, barrier_callback, requests[i], + responses[i], trace_id), + exception_state); if (exception_state.HadException()) { barrier_callback->OnError("Could not inspect response body state"); return promise;
diff --git a/third_party/blink/renderer/modules/cache_storage/cache_test.cc b/third_party/blink/renderer/modules/cache_storage/cache_test.cc index 6395810..016dbac 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache_test.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache_test.cc
@@ -184,14 +184,6 @@ CheckBatchOperationsIfProvided(batch_operations); std::move(callback).Run(CacheStorageVerboseError::New(error_, String())); } - void SetSideData(const KURL& url, - base::Time response_time, - base::span<const uint8_t> side_data, - int64_t trace_id, - SetSideDataCallback callback) override { - std::move(callback).Run( - blink::mojom::CacheStorageError::kErrorNotImplemented); - } protected: void CheckUrlIfProvided(const KURL& url) {
diff --git a/third_party/blink/renderer/modules/compression/BUILD.gn b/third_party/blink/renderer/modules/compression/BUILD.gn new file mode 100644 index 0000000..0f8e7b1 --- /dev/null +++ b/third_party/blink/renderer/modules/compression/BUILD.gn
@@ -0,0 +1,10 @@ +import("//third_party/blink/renderer/modules/modules.gni") + +blink_modules_sources("compression") { + sources = [ + "decompression_stream.cc", + "decompression_stream.h", + "inflate_transformer.cc", + "inflate_transformer.h", + ] +}
diff --git a/third_party/blink/renderer/modules/compression/README.md b/third_party/blink/renderer/modules/compression/README.md new file mode 100644 index 0000000..3a65da92 --- /dev/null +++ b/third_party/blink/renderer/modules/compression/README.md
@@ -0,0 +1,8 @@ +# CompressionStreams API + +This directory contains the implementation of CompressionStream and +DecompressionStream. + +## Design docs + +See [DecompressionStream Design Docs](https://docs.google.com/document/d/1TovyqqeC3HoO0A4UUBKiCyhZlQSl7jM_F7KbWjK2Gcs/edit).
diff --git a/third_party/blink/renderer/modules/compression/decompression_stream.cc b/third_party/blink/renderer/modules/compression/decompression_stream.cc new file mode 100644 index 0000000..e0b77a2 --- /dev/null +++ b/third_party/blink/renderer/modules/compression/decompression_stream.cc
@@ -0,0 +1,46 @@ +#include "third_party/blink/renderer/modules/compression/decompression_stream.h" +#include "third_party/blink/renderer/modules/compression/inflate_transformer.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" + +namespace blink { + +DecompressionStream* DecompressionStream::Create( + ScriptState* script_state, + const AtomicString& format, + ExceptionState& exception_state) { + return MakeGarbageCollected<DecompressionStream>(script_state, format, + exception_state); +} + +ReadableStream* DecompressionStream::readable() const { + return transform_->Readable(); +} + +WritableStream* DecompressionStream::writable() const { + return transform_->Writable(); +} + +void DecompressionStream::Trace(Visitor* visitor) { + visitor->Trace(transform_); + ScriptWrappable::Trace(visitor); +} + +DecompressionStream::DecompressionStream(ScriptState* script_state, + const AtomicString& format, + ExceptionState& exception_state) + : transform_(MakeGarbageCollected<TransformStream>()) { + InflateTransformer::Algorithm algorithm = + InflateTransformer::Algorithm::kDeflate; + if (format == "gzip") { + algorithm = InflateTransformer::Algorithm::kGzip; + } else if (format != "deflate") { + exception_state.ThrowTypeError("Unsupported format"); + return; + } + + transform_->Init( + MakeGarbageCollected<InflateTransformer>(script_state, algorithm), + script_state, exception_state); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/compression/decompression_stream.h b/third_party/blink/renderer/modules/compression/decompression_stream.h new file mode 100644 index 0000000..3e2495f --- /dev/null +++ b/third_party/blink/renderer/modules/compression/decompression_stream.h
@@ -0,0 +1,32 @@ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_DECOMPRESSION_STREAM_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_DECOMPRESSION_STREAM_H_ + +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/core/streams/transform_stream.h" +#include "third_party/blink/renderer/platform/bindings/script_wrappable.h" + +namespace blink { + +class DecompressionStream final : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + static DecompressionStream* Create(ScriptState*, + const AtomicString&, + ExceptionState&); + DecompressionStream(ScriptState*, const AtomicString&, ExceptionState&); + + ReadableStream* readable() const; + WritableStream* writable() const; + + void Trace(Visitor* visitor) override; + + private: + const Member<TransformStream> transform_; + + DISALLOW_COPY_AND_ASSIGN(DecompressionStream); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_DECOMPRESSION_STREAM_H_
diff --git a/third_party/blink/renderer/modules/compression/decompression_stream.idl b/third_party/blink/renderer/modules/compression/decompression_stream.idl new file mode 100644 index 0000000..a49b5a0 --- /dev/null +++ b/third_party/blink/renderer/modules/compression/decompression_stream.idl
@@ -0,0 +1,10 @@ +[ + Exposed=(Window,Worker), + Constructor(DOMString format), + ConstructorCallWith=ScriptState, + RaisesException=Constructor, + RuntimeEnabled=CompressionStreams +] interface DecompressionStream { + readonly attribute ReadableStream readable; + readonly attribute WritableStream writable; +};
diff --git a/third_party/blink/renderer/modules/compression/inflate_transformer.cc b/third_party/blink/renderer/modules/compression/inflate_transformer.cc new file mode 100644 index 0000000..ea6b1cf --- /dev/null +++ b/third_party/blink/renderer/modules/compression/inflate_transformer.cc
@@ -0,0 +1,111 @@ +#include "third_party/blink/renderer/modules/compression/inflate_transformer.h" + +#include <string.h> +#include <algorithm> +#include <limits> + +#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_uint8_array.h" +#include "third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h" +#include "third_party/blink/renderer/core/streams/transform_stream_transformer.h" +#include "third_party/blink/renderer/core/typed_arrays/array_buffer_view_helpers.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/bindings/to_v8.h" + +#include "v8/include/v8.h" + +namespace blink { + +InflateTransformer::InflateTransformer(ScriptState* script_state, + Algorithm algorithm) + : script_state_(script_state), out_buffer_(kBufferSize) { + memset(&stream_, 0, sizeof(z_stream)); + int err; + constexpr int kWindowBits = 15; + constexpr int kUseGzip = 16; + switch (algorithm) { + case Algorithm::kDeflate: + err = inflateInit2(&stream_, kWindowBits); + break; + case Algorithm::kGzip: + err = inflateInit2(&stream_, kWindowBits + kUseGzip); + break; + } + DCHECK_EQ(Z_OK, err); +} + +InflateTransformer::~InflateTransformer() { + if (!was_flush_called_) { + inflateEnd(&stream_); + } +} + +void InflateTransformer::Transform( + v8::Local<v8::Value> chunk, + TransformStreamDefaultControllerInterface* controller, + ExceptionState& exception_state) { + // TODO(canonmukai): Change to MaybeShared<DOMUint8Array> + // when we are ready to support SharedArrayBuffer. + NotShared<DOMUint8Array> chunk_data = ToNotShared<NotShared<DOMUint8Array>>( + script_state_->GetIsolate(), chunk, exception_state); + if (exception_state.HadException()) { + return; + } + if (!chunk_data) { + exception_state.ThrowTypeError("chunk is not of type Uint8Array."); + return; + } + + Inflate(chunk_data.View(), IsFinished(false), controller, exception_state); +} + +void InflateTransformer::Flush( + TransformStreamDefaultControllerInterface* controller, + ExceptionState& exception_state) { + DCHECK(!was_flush_called_); + Inflate(nullptr, IsFinished(true), controller, exception_state); + inflateEnd(&stream_); + was_flush_called_ = true; +} + +void InflateTransformer::Inflate( + const DOMUint8Array* data, + IsFinished finished, + TransformStreamDefaultControllerInterface* controller, + ExceptionState& exception_state) { + unsigned int out_buffer_size = static_cast<unsigned int>(kBufferSize); + if (data) { + stream_.avail_in = data->length(); + stream_.next_in = data->DataMaybeShared(); + } else { + stream_.avail_in = 0; + stream_.next_in = nullptr; + } + + do { + stream_.avail_out = out_buffer_size; + stream_.next_out = out_buffer_.data(); + int err = inflate(&stream_, finished ? Z_FINISH : Z_NO_FLUSH); + if (err != Z_OK && err != Z_STREAM_END && err != Z_BUF_ERROR) { + exception_state.ThrowTypeError("The compressed data was not valid."); + return; + } + + wtf_size_t bytes = out_buffer_size - stream_.avail_out; + if (bytes) { + controller->Enqueue( + ToV8(DOMUint8Array::Create(out_buffer_.data(), bytes), script_state_), + exception_state); + if (exception_state.HadException()) { + return; + } + } + } while (stream_.avail_out == 0); +} + +void InflateTransformer::Trace(Visitor* visitor) { + visitor->Trace(script_state_); + TransformStreamTransformer::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/compression/inflate_transformer.h b/third_party/blink/renderer/modules/compression/inflate_transformer.h new file mode 100644 index 0000000..4a44efd --- /dev/null +++ b/third_party/blink/renderer/modules/compression/inflate_transformer.h
@@ -0,0 +1,54 @@ +#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_INFLATE_TRANSFORMER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_INFLATE_TRANSFORMER_H_ + +#include "base/util/type_safety/strong_alias.h" + +#include "third_party/blink/renderer/core/streams/transform_stream_transformer.h" +#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h" +#include "third_party/blink/renderer/platform/wtf/vector.h" +#include "third_party/zlib/zlib.h" + +namespace blink { + +class InflateTransformer final : public TransformStreamTransformer { + public: + enum class Algorithm { kDeflate, kGzip }; + + InflateTransformer(ScriptState*, Algorithm algorithm); + ~InflateTransformer() override; + + void Transform(v8::Local<v8::Value> chunk, + TransformStreamDefaultControllerInterface*, + ExceptionState&) override; + + void Flush(TransformStreamDefaultControllerInterface*, + ExceptionState&) override; + + ScriptState* GetScriptState() override { return script_state_; } + + void Trace(Visitor*) override; + + private: + using IsFinished = util::StrongAlias<class IsFinishedTag, bool>; + + void Inflate(const DOMUint8Array* data, + IsFinished, + TransformStreamDefaultControllerInterface*, + ExceptionState&); + + Member<ScriptState> script_state_; + + z_stream stream_; + + Vector<Bytef> out_buffer_; + + bool was_flush_called_ = false; + + static constexpr wtf_size_t kBufferSize = 65536; + + DISALLOW_COPY_AND_ASSIGN(InflateTransformer); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_COMPRESSION_INFLATE_TRANSFORMER_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 f0cd0a6..ec10ba8 100644 --- a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc +++ b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.cc
@@ -12,7 +12,7 @@ #include "media/base/supported_types.h" #include "media/filters/stream_parser_factory.h" #include "media/mojo/mojom/media_types.mojom-blink.h" -#include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h" #include "third_party/blink/public/platform/task_type.h" @@ -775,14 +775,14 @@ if (decode_history_service_) return true; - if (!execution_context || !execution_context->GetInterfaceProvider()) + if (!execution_context) return false; scoped_refptr<base::SingleThreadTaskRunner> task_runner = execution_context->GetTaskRunner(TaskType::kMediaElementEvent); - execution_context->GetInterfaceProvider()->GetInterface( - mojo::MakeRequest(&decode_history_service_, task_runner)); + execution_context->GetBrowserInterfaceBroker().GetInterface( + decode_history_service_.BindNewPipeAndPassReceiver(task_runner)); return true; }
diff --git a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h index a052fd0..100e5b0 100644 --- a/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h +++ b/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h
@@ -7,6 +7,7 @@ #include "media/base/video_codecs.h" // for media::VideoCodecProfile #include "media/mojo/mojom/video_decode_perf_history.mojom-blink.h" +#include "mojo/public/cpp/bindings/remote.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/visitor.h" @@ -52,7 +53,8 @@ bool is_smooth, bool is_power_efficient); - media::mojom::blink::VideoDecodePerfHistoryPtr decode_history_service_; + mojo::Remote<media::mojom::blink::VideoDecodePerfHistory> + decode_history_service_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index 85399269..1b94e1b 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -99,6 +99,7 @@ "canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.idl", "clipboard/clipboard.idl", "clipboard/clipboard_item.idl", + "compression/decompression_stream.idl", "contacts_picker/contacts_manager.idl", "content_index/content_index.idl", "content_index/content_index_event.idl",
diff --git a/third_party/blink/renderer/modules/payments/payment_request.cc b/third_party/blink/renderer/modules/payments/payment_request.cc index 4795bd55..56e4baa 100644 --- a/third_party/blink/renderer/modules/payments/payment_request.cc +++ b/third_party/blink/renderer/modules/payments/payment_request.cc
@@ -11,8 +11,7 @@ #include "base/location.h" #include "base/stl_util.h" #include "build/build_config.h" -#include "mojo/public/cpp/bindings/interface_request.h" -#include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h" #include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h" @@ -1163,9 +1162,9 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner = execution_context->GetTaskRunner(TaskType::kUserInteraction); - GetFrame()->GetInterfaceProvider().GetInterface( - mojo::MakeRequest(&payment_provider_, task_runner)); - payment_provider_.set_connection_error_handler( + GetFrame()->GetBrowserInterfaceBroker().GetInterface( + payment_provider_.BindNewPipeAndPassReceiver(task_runner)); + payment_provider_.set_disconnect_handler( WTF::Bind(&PaymentRequest::OnConnectionError, WrapWeakPersistent(this))); UseCounter::Count(execution_context, WebFeature::kPaymentRequestInitialized);
diff --git a/third_party/blink/renderer/modules/payments/payment_request.h b/third_party/blink/renderer/modules/payments/payment_request.h index d8f2a2c1..62101861 100644 --- a/third_party/blink/renderer/modules/payments/payment_request.h +++ b/third_party/blink/renderer/modules/payments/payment_request.h
@@ -9,6 +9,7 @@ #include "base/memory/scoped_refptr.h" #include "components/payments/mojom/payment_request_data.mojom-blink.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" @@ -165,7 +166,7 @@ Member<ScriptPromiseResolver> abort_resolver_; Member<ScriptPromiseResolver> can_make_payment_resolver_; Member<ScriptPromiseResolver> has_enrolled_instrument_resolver_; - payments::mojom::blink::PaymentRequestPtr payment_provider_; + mojo::Remote<payments::mojom::blink::PaymentRequest> payment_provider_; mojo::Receiver<payments::mojom::blink::PaymentRequestClient> client_receiver_{ this}; TaskRunnerTimer<PaymentRequest> complete_timer_;
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc index da7d8f1b..c10d33b5 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc +++ b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.cc
@@ -1259,23 +1259,6 @@ return service_worker_host_.get(); } -int ServiceWorkerGlobalScope::WillStartTask() { - DCHECK(IsContextThread()); - DCHECK(timeout_timer_); - return timeout_timer_->StartEvent(base::DoNothing()); -} - -void ServiceWorkerGlobalScope::DidEndTask(int task_id) { - DCHECK(IsContextThread()); - DCHECK(timeout_timer_); - // Check if the task is still alive, since the timeout timer might have - // already timed it out (which calls the abort callback passed to StartEvent() - // but that does nothing, since we just check HasEvent() here instead of - // maintaining our own set of started events). - if (timeout_timer_->HasEvent(task_id)) - timeout_timer_->EndEvent(task_id); -} - void ServiceWorkerGlobalScope::OnIdleTimeout() { DCHECK(IsContextThread()); // RequestedTermination() returns true if ServiceWorkerTimeoutTimer agrees
diff --git a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h index 884002a..c2471ae6 100644 --- a/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h +++ b/third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h
@@ -275,15 +275,6 @@ mojom::blink::ServiceWorkerHost* GetServiceWorkerHost(); - // Called when a task is going to be scheduled on the service worker. - // The service worker shouldn't request to be terminated until the task is - // finished. Returns an id for the task. The caller must call DidEndTask() - // with the returned id to notify that the task is finished. - int WillStartTask(); - // Called when a task is finished. |task_id| must be a return value of - // WillStartTask(). - void DidEndTask(int task_id); - DEFINE_ATTRIBUTE_EVENT_LISTENER(install, kInstall) DEFINE_ATTRIBUTE_EVENT_LISTENER(activate, kActivate) DEFINE_ATTRIBUTE_EVENT_LISTENER(fetch, kFetch)
diff --git a/third_party/blink/renderer/modules/wake_lock/wake_lock_controller_test.cc b/third_party/blink/renderer/modules/wake_lock/wake_lock_controller_test.cc index 32d40ff0..1d14f44fe 100644 --- a/third_party/blink/renderer/modules/wake_lock/wake_lock_controller_test.cc +++ b/third_party/blink/renderer/modules/wake_lock/wake_lock_controller_test.cc
@@ -276,13 +276,13 @@ // First, acquire a handful of locks of different types. auto* screen_resolver1 = MakeGarbageCollected<ScriptPromiseResolver>(context.GetScriptState()); - ScriptPromise screen_promise1 = screen_resolver1->Promise(); + screen_resolver1->Promise(); auto* screen_resolver2 = MakeGarbageCollected<ScriptPromiseResolver>(context.GetScriptState()); - ScriptPromise screen_promise2 = screen_resolver2->Promise(); + screen_resolver2->Promise(); auto* system_resolver1 = MakeGarbageCollected<ScriptPromiseResolver>(context.GetScriptState()); - ScriptPromise system_promise1 = system_resolver1->Promise(); + system_resolver1->Promise(); controller.RequestWakeLock(WakeLockType::kScreen, screen_resolver1, /*signal=*/nullptr); controller.RequestWakeLock(WakeLockType::kScreen, screen_resolver2,
diff --git a/third_party/blink/renderer/modules/webgpu/dawn_conversions.cc b/third_party/blink/renderer/modules/webgpu/dawn_conversions.cc index b776225..66b9acf 100644 --- a/third_party/blink/renderer/modules/webgpu/dawn_conversions.cc +++ b/third_party/blink/renderer/modules/webgpu/dawn_conversions.cc
@@ -32,6 +32,9 @@ if (webgpu_enum == "sampled-texture") { return DAWN_BINDING_TYPE_SAMPLED_TEXTURE; } + if (webgpu_enum == "storage-texture") { + return DAWN_BINDING_TYPE_STORAGE_TEXTURE; + } NOTREACHED(); return DAWN_BINDING_TYPE_FORCE32; }
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout_binding.idl b/third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout_binding.idl index c13851c3..141823e5 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout_binding.idl +++ b/third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout_binding.idl
@@ -20,6 +20,7 @@ "readonly-storage-buffer", "sampler", "sampled-texture", + "storage-texture", }; enum GPUTextureComponentType {
diff --git a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc index d708722..e32ba35e 100644 --- a/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc +++ b/third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder_test.cc
@@ -42,7 +42,6 @@ #include "third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.h" #include "third_party/blink/renderer/platform/testing/histogram_tester.h" #include "third_party/blink/renderer/platform/wtf/shared_buffer.h" -#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h" namespace blink { @@ -122,12 +121,13 @@ row_bytes[1] = decoder->DecodedYUVWidthBytes(1); row_bytes[2] = decoder->DecodedYUVWidthBytes(2); - scoped_refptr<ArrayBuffer> buffer(ArrayBuffer::Create( - row_bytes[0] * y_size.Height() + row_bytes[1] * u_size.Height() + - row_bytes[2] * v_size.Height(), - 1)); + size_t planes_data_size = row_bytes[0] * y_size.Height() + + row_bytes[1] * u_size.Height() + + row_bytes[2] * v_size.Height(); + std::unique_ptr<char[]> planes_data(new char[planes_data_size]); + void* planes[3]; - planes[0] = buffer->Data(); + planes[0] = reinterpret_cast<void*>(planes_data.get()); planes[1] = ((char*)planes[0]) + row_bytes[0] * y_size.Height(); planes[2] = ((char*)planes[1]) + row_bytes[1] * u_size.Height();
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index ee86fde..3f9fa32 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -304,6 +304,10 @@ status: "test", }, { + name: "CompressionStreams", + status: "experimental", + }, + { name: "ComputedAccessibilityInfo", status: "experimental", }, @@ -394,9 +398,6 @@ status: "experimental", }, { - name: "CSSFontFeatureValues" - }, - { name: "CSSFontSizeAdjust", status: "experimental", },
diff --git a/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader b/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader index 294938b..d721178 100644 --- a/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader +++ b/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader
@@ -1,9 +1,6 @@ # Test consistently hitting default timeout. Bug(none) css3/filters/effect-reference-subregion.html [ Skip ] -# Times out. -crbug.com/994331 compositing/lots-of-img-layers.html [ Skip ] - # Not rendering the rightmost frame. crbug.com/1001616 media/alpha-video-playback.html [ Skip ]
diff --git a/third_party/blink/web_tests/SlowTests b/third_party/blink/web_tests/SlowTests index eb14621..5afe36f 100644 --- a/third_party/blink/web_tests/SlowTests +++ b/third_party/blink/web_tests/SlowTests
@@ -665,3 +665,6 @@ crbug.com/984003 http/tests/virtual-scroller/find-element-66-10px.html [ Slow ] crbug.com/1003715 [ Win10 ] http/tests/notifications/serviceworker-notification-properties.html [ Slow ] + +# Slow when using Vulkan. +crbug.com/994331 compositing/lots-of-img-layers.html [ Slow ]
diff --git a/third_party/blink/web_tests/animations/composition/backdrop-filter-composition-expected.txt b/third_party/blink/web_tests/animations/composition/backdrop-filter-composition-expected.txt new file mode 100644 index 0000000..2fcece0 --- /dev/null +++ b/third_party/blink/web_tests/animations/composition/backdrop-filter-composition-expected.txt
@@ -0,0 +1,186 @@ +This is a testharness.js-based test. +PASS This test uses interpolation-test.js. +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (-0.5) is [blur(10px) blur(15px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (0) is [blur(10px) blur(40px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (0.25) is [blur(10px) blur(52.5px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (0.5) is [blur(10px) blur(65px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (0.75) is [blur(10px) blur(77.5px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (1) is [blur(10px) blur(90px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [blur(40px)] to add [blur(90px)] at (1.5) is [blur(10px) blur(115px)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (-0.5) is [sepia(0.25) sepia(0.75)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (0) is [sepia(0.5) sepia(0.5)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (0.25) is [sepia(0.625) sepia(0.375)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (0.5) is [sepia(0.75) sepia(0.25)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (0.75) is [sepia(0.875) sepia(0.125)] +FAIL Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (1) is [sepia(1)] assert_equals: expected "sepia ( 1 ) sepia ( 0 ) " but got "sepia ( 1 ) " +PASS Compositing: property <backdrop-filter> underlying [sepia(0.5)] from add [sepia(0.5)] to replace [sepia(1)] at (1.5) is [sepia(1) sepia(0)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (-0.5) is [brightness(0.75) brightness(0.75)] +FAIL Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (0) is [brightness(0.5)] assert_equals: expected "brightness ( 0.5 ) brightness ( 1 ) " but got "brightness ( 0.5 ) " +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (0.25) is [brightness(0.375) brightness(1.125)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (0.5) is [brightness(0.25) brightness(1.25)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (0.75) is [brightness(0.125) brightness(1.375)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (1) is [brightness(0) brightness(1.5)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0)] from replace [brightness(0.5)] to add [brightness(1.5)] at (1.5) is [brightness(0) brightness(1.75)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (-0.5) is [invert(0.5) saturate(1.5)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (0) is [invert(0.5) saturate(2)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (0.25) is [invert(0.5) saturate(2.25)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (0.5) is [invert(0.5) saturate(2.5)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (0.75) is [invert(0.5) saturate(2.75)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (1) is [invert(0.5) saturate(3)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [saturate(2)] to add [saturate(3)] at (1.5) is [invert(0.5) saturate(3.5)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (-0.5) is [invert(0.25) saturate(0)] +FAIL Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (0) is [invert(0.5)] assert_equals: expected "invert ( 0.5 ) saturate ( 1 ) " but got "invert ( 0.5 ) " +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (0.25) is [invert(0.625) saturate(1.5)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (0.5) is [invert(0.75) saturate(2)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (0.75) is [invert(0.875) saturate(2.5)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (1) is [invert(1) saturate(3)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.5)] from add [none] to replace [invert(1) saturate(3)] at (1.5) is [invert(1) saturate(4)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (-0.5) is [grayscale(0.25) blur(10px) brightness(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (0) is [grayscale(0.25) blur(10px) brightness(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (0.25) is [grayscale(0.25) blur(10px) brightness(0.25)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (0.5) is [grayscale(0.25) blur(10px) brightness(0.5)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (0.75) is [grayscale(0.25) blur(10px) brightness(0.75)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (1) is [grayscale(0.25) blur(10px) brightness(1)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(25%) blur(10px)] from add [brightness(0)] to add [brightness(1)] at (1.5) is [grayscale(0.25) blur(10px) brightness(1.5)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (-0.5) is [blur(10px) grayscale(0.625) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (0) is [blur(10px) grayscale(0.5) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (0.25) is [blur(10px) grayscale(0.4375) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (0.5) is [blur(10px) grayscale(0.375) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (0.75) is [blur(10px) grayscale(0.3125) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (1) is [blur(10px) grayscale(0.25) blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from add [grayscale(50%) blur(10px)] to add [grayscale(25%) blur(10px)] at (1.5) is [blur(10px) grayscale(0.125) blur(10px)] +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (-0.5) is [grayscale(0.5) blur(30px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.5 ) blur ( 30px ) " but got "grayscale ( 0.5 ) blur ( 30px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (0) is [grayscale(0.5) blur(30px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.5 ) blur ( 30px ) " but got "grayscale ( 0.5 ) blur ( 30px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (0.25) is [grayscale(0.5) blur(30px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.5 ) blur ( 30px ) " but got "grayscale ( 0.5 ) blur ( 30px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (0.5) is [grayscale(0.25) blur(40px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.25 ) blur ( 40px ) " but got "grayscale ( 0.25 ) blur ( 40px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (0.75) is [grayscale(0.25) blur(40px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.25 ) blur ( 40px ) " but got "grayscale ( 0.25 ) blur ( 40px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (1) is [grayscale(0.25) blur(40px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.25 ) blur ( 40px ) " but got "grayscale ( 0.25 ) blur ( 40px ) " +FAIL Compositing: property <backdrop-filter> underlying [url(#a)] from add [grayscale(50%) blur(30px)] to add [grayscale(25%) blur(40px)] at (1.5) is [grayscale(0.25) blur(40px)] assert_equals: expected "url ( \" # a \" ) grayscale ( 0.25 ) blur ( 40px ) " but got "grayscale ( 0.25 ) blur ( 40px ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (-0.5) is [url("#a") brightness(1)] assert_equals: expected "blur ( 10px ) url ( \" # a \" ) brightness ( 1 ) " but got "url ( \" # a \" ) brightness ( 1 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (0) is [url("#a") brightness(1)] assert_equals: expected "blur ( 10px ) url ( \" # a \" ) brightness ( 1 ) " but got "url ( \" # a \" ) brightness ( 1 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (0.25) is [url("#a") brightness(1)] assert_equals: expected "blur ( 10px ) url ( \" # a \" ) brightness ( 1 ) " but got "url ( \" # a \" ) brightness ( 1 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (0.5) is [url("#b") brightness(0)] assert_equals: expected "blur ( 10px ) url ( \" # b \" ) brightness ( 0 ) " but got "url ( \" # b \" ) brightness ( 0 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (0.75) is [url("#b") brightness(0)] assert_equals: expected "blur ( 10px ) url ( \" # b \" ) brightness ( 0 ) " but got "url ( \" # b \" ) brightness ( 0 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (1) is [url("#b") brightness(0)] assert_equals: expected "blur ( 10px ) url ( \" # b \" ) brightness ( 0 ) " but got "url ( \" # b \" ) brightness ( 0 ) " +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from add [url(#a) brightness(1)] to add [url(#b) brightness(0)] at (1.5) is [url("#b") brightness(0)] assert_equals: expected "blur ( 10px ) url ( \" # b \" ) brightness ( 0 ) " but got "url ( \" # b \" ) brightness ( 0 ) " +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (-0.5) is [blur(25px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0) is [blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.25) is [blur(62.5px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.5) is [blur(75px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.75) is [blur(87.5px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (1) is [blur(100px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (1.5) is [blur(125px)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (-0.5) is [brightness(0)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (0) is [brightness(0)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (0.25) is [brightness(0)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (0.5) is [brightness(0.25)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (0.75) is [brightness(0.5)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (1) is [brightness(0.75)] +PASS Compositing: property <backdrop-filter> underlying [brightness(0.25)] from accumulate [brightness(0.5)] to accumulate [brightness(1.5)] at (1.5) is [brightness(1.25)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (-0.5) is [contrast(0)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (0) is [contrast(0)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (0.25) is [contrast(0)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (0.5) is [contrast(0.25)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (0.75) is [contrast(0.5)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (1) is [contrast(0.75)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.25)] from accumulate [contrast(0.5)] to accumulate [contrast(1.5)] at (1.5) is [contrast(1.25)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (-0.5) is [drop-shadow(rgb(255, 255, 0) -15px 5px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (0) is [drop-shadow(rgb(255, 255, 0) 10px 15px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (0.25) is [drop-shadow(rgb(255, 191, 64) 22.5px 20px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (0.5) is [drop-shadow(rgb(255, 128, 128) 35px 25px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (0.75) is [drop-shadow(rgb(255, 64, 191) 47.5px 30px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (1) is [drop-shadow(rgb(255, 0, 255) 60px 35px 10px)] +PASS Compositing: property <backdrop-filter> underlying [drop-shadow(10px 5px 0px rgb(255, 0, 0))] from accumulate [drop-shadow(0px 10px 10px rgb(0, 255, 0))] to accumulate [drop-shadow(50px 30px 10px rgb(0, 0, 255))] at (1.5) is [drop-shadow(rgb(255, 0, 255) 85px 45px 10px)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (-0.5) is [grayscale(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (0) is [grayscale(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (0.25) is [grayscale(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (0.5) is [grayscale(0)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (0.75) is [grayscale(0.125)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (1) is [grayscale(0.25)] +PASS Compositing: property <backdrop-filter> underlying [grayscale(0.25)] from accumulate [grayscale(0.5)] to accumulate [grayscale(1.5)] at (1.5) is [grayscale(0.5)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (-0.5) is [hue-rotate(55deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (0) is [hue-rotate(185deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (0.25) is [hue-rotate(250deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (0.5) is [hue-rotate(315deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (0.75) is [hue-rotate(380deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (1) is [hue-rotate(445deg)] +PASS Compositing: property <backdrop-filter> underlying [hue-rotate(45deg)] from accumulate [hue-rotate(140deg)] to accumulate [hue-rotate(400deg)] at (1.5) is [hue-rotate(575deg)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (-0.5) is [invert(0)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (0) is [invert(0)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (0.25) is [invert(0)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (0.5) is [invert(0)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (0.75) is [invert(0.125)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (1) is [invert(0.25)] +PASS Compositing: property <backdrop-filter> underlying [invert(0.25)] from accumulate [invert(0.5)] to accumulate [invert(1.5)] at (1.5) is [invert(0.5)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (-0.5) is [opacity(0)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (0) is [opacity(0)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (0.25) is [opacity(0)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (0.5) is [opacity(0)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (0.75) is [opacity(0.125)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (1) is [opacity(0.25)] +PASS Compositing: property <backdrop-filter> underlying [opacity(0.25)] from accumulate [opacity(0.5)] to accumulate [opacity(1.5)] at (1.5) is [opacity(0.5)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (-0.5) is [saturate(0)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (0) is [saturate(0)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (0.25) is [saturate(0)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (0.5) is [saturate(0.25)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (0.75) is [saturate(0.5)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (1) is [saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [saturate(0.25)] from accumulate [saturate(0.5)] to accumulate [saturate(1.5)] at (1.5) is [saturate(1.25)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (-0.5) is [sepia(0)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (0) is [sepia(0)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (0.25) is [sepia(0)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (0.5) is [sepia(0)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (0.75) is [sepia(0.125)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (1) is [sepia(0.25)] +PASS Compositing: property <backdrop-filter> underlying [sepia(0.25)] from accumulate [sepia(0.5)] to accumulate [sepia(1.5)] at (1.5) is [sepia(0.5)] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (-0.5) is [url("#b")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (0) is [url("#b")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (0.25) is [url("#b")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (0.5) is [url("#c")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (0.75) is [url("#c")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (1) is [url("#c")] +PASS Compositing: property <backdrop-filter> underlying [url(#a)] from accumulate [url(#b)] to accumulate [url(#c)] at (1.5) is [url("#c")] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (-0.5) is [blur(25px) saturate(1.5)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (0) is [blur(50px) saturate(1)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (0.25) is [blur(62.5px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (0.5) is [blur(75px) saturate(0.5)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (0.75) is [blur(87.5px) saturate(0.25)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (1) is [blur(100px) saturate(0)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px) saturate(1)] to accumulate [blur(90px) saturate(0)] at (1.5) is [blur(125px) saturate(0)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (-0.5) is [blur(25px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0) is [blur(50px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.25) is [blur(62.5px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.5) is [blur(75px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (0.75) is [blur(87.5px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (1) is [blur(100px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px) saturate(0.75)] from accumulate [blur(40px)] to accumulate [blur(90px)] at (1.5) is [blur(125px) saturate(0.75)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (-0.5) is [blur(20px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (0) is [blur(40px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (0.25) is [blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (0.5) is [blur(60px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (0.75) is [blur(70px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (1) is [blur(80px)] +PASS Compositing: property <backdrop-filter> underlying [contrast(0.75)] from accumulate [blur(40px)] to accumulate [blur(80px)] at (1.5) is [blur(100px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (-0.5) is [blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (0) is [blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (0.25) is [blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (0.5) is [saturate(1)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (0.75) is [saturate(1)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (1) is [saturate(1)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to accumulate [saturate(1)] at (1.5) is [saturate(1)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (-0.5) is [blur(10px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (0) is [blur(40px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (0.25) is [blur(55px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (0.5) is [blur(70px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (0.75) is [blur(85px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (1) is [blur(100px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(30px)] to replace [blur(100px)] at (1.5) is [blur(130px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (-0.5) is [blur(70px) blur(0px)] +FAIL Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (0) is [blur(50px)] assert_equals: expected "blur ( 50px ) blur ( 0px ) " but got "blur ( 50px ) " +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (0.25) is [blur(40px) blur(25px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (0.5) is [blur(30px) blur(50px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (0.75) is [blur(20px) blur(75px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (1) is [blur(10px) blur(100px)] +PASS Compositing: property <backdrop-filter> underlying [blur(10px)] from accumulate [blur(40px)] to add [blur(100px)] at (1.5) is [blur(0px) blur(150px)] +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/animations/composition/backdrop-filter-composition.html b/third_party/blink/web_tests/animations/composition/backdrop-filter-composition.html index 5956f6e..6eaf0b5 100644 --- a/third_party/blink/web_tests/animations/composition/backdrop-filter-composition.html +++ b/third_party/blink/web_tests/animations/composition/backdrop-filter-composition.html
@@ -3,12 +3,172 @@ <body> <script src="../interpolation/resources/interpolation-test.js"></script> <script> +// Basic additive composition; the lists should be concatenated. assertComposition({ property: 'backdrop-filter', underlying: 'blur(10px)', addFrom: 'blur(40px)', addTo: 'blur(90px)', }, [ + {at: -0.5, is: 'blur(10px) blur(15px)'}, + {at: 0, is: 'blur(10px) blur(40px)'}, + {at: 0.25, is: 'blur(10px) blur(52.5px)'}, + {at: 0.5, is: 'blur(10px) blur(65px)'}, + {at: 0.75, is: 'blur(10px) blur(77.5px)'}, + {at: 1, is: 'blur(10px) blur(90px)'}, + {at: 1.5, is: 'blur(10px) blur(115px)'}, +]); + +// Here we have add-from and replace-to, so the list will be have mismatched +// lengths and the replace-to list will have to be extended to interpolate as +// per https://drafts.fxtf.org/filter-effects-1/#interpolation-of-filters +// +// That is, this becomes an interpolation of the form: +// sepia(0.5) sepia(0.5) --> sepia(1) sepia(0) +assertComposition({ + property: 'backdrop-filter', + underlying: 'sepia(0.5)', + addFrom: 'sepia(0.5)', + replaceTo: 'sepia(1)', +}, [ + {at: -0.5, is: 'sepia(0.25) sepia(0.75)'}, + {at: 0, is: 'sepia(0.5) sepia(0.5)'}, + {at: 0.25, is: 'sepia(0.625) sepia(0.375)'}, + {at: 0.5, is: 'sepia(0.75) sepia(0.25)'}, + {at: 0.75, is: 'sepia(0.875) sepia(0.125)'}, + {at: 1, is: 'sepia(1) sepia(0)'}, + {at: 1.5, is: 'sepia(1) sepia(0)'}, +]); + +// In this case we have replace-from and add-to, so similar extending behavior +// takes place. Note that brightness has an initial value of 1. +// +// That is, this becomes an interpolation of the form: +// brightness(0.5) brightness(1) --> brightness(0) brightness(1.5) +assertComposition({ + property: 'backdrop-filter', + underlying: 'brightness(0)', + replaceFrom: 'brightness(0.5)', + addTo: 'brightness(1.5)', +}, [ + {at: -0.5, is: 'brightness(0.75) brightness(0.75)'}, + {at: 0, is: 'brightness(0.5) brightness(1)'}, + {at: 0.25, is: 'brightness(0.375) brightness(1.125)'}, + {at: 0.5, is: 'brightness(0.25) brightness(1.25)'}, + {at: 0.75, is: 'brightness(0.125) brightness(1.375)'}, + {at: 1, is: 'brightness(0) brightness(1.5)'}, + {at: 1.5, is: 'brightness(0) brightness(1.75)'}, +]); + +// Test mixing properties. +assertComposition({ + property: 'backdrop-filter', + underlying: 'invert(0.5)', + addFrom: 'saturate(2)', + addTo: 'saturate(3)', +}, [ + {at: -0.5, is: 'invert(0.5) saturate(1.5)'}, + {at: 0, is: 'invert(0.5) saturate(2)'}, + {at: 0.25, is: 'invert(0.5) saturate(2.25)'}, + {at: 0.5, is: 'invert(0.5) saturate(2.5)'}, + {at: 0.75, is: 'invert(0.5) saturate(2.75)'}, + {at: 1, is: 'invert(0.5) saturate(3)'}, + {at: 1.5, is: 'invert(0.5) saturate(3.5)'}, +]); + +// Test the 'none' behavior; composition happens before interpolation, so this +// is actually an interpolation of: +// invert(0.5) saturate(1) --> invert(1) saturate(3) +assertComposition({ + property: 'backdrop-filter', + underlying: 'invert(0.5)', + addFrom: 'none', + replaceTo: 'invert(1) saturate(3)', +}, [ + {at: -0.5, is: 'invert(0.25) saturate(0)'}, + {at: 0, is: 'invert(0.5) saturate(1)'}, + {at: 0.25, is: 'invert(0.625) saturate(1.5)'}, + {at: 0.5, is: 'invert(0.75) saturate(2)'}, + {at: 0.75, is: 'invert(0.875) saturate(2.5)'}, + {at: 1, is: 'invert(1) saturate(3)'}, + {at: 1.5, is: 'invert(1.25) saturate(4)'}, +]); + +// Test having multiple underlying values +assertComposition({ + property: 'backdrop-filter', + underlying: 'grayscale(25%) blur(10px)', + addFrom: 'brightness(0)', + addTo: 'brightness(1)', +}, [ + {at: -0.5, is: 'grayscale(25%) blur(10px) brightness(0)'}, + {at: 0, is: 'grayscale(25%) blur(10px) brightness(0)'}, + {at: 0.25, is: 'grayscale(25%) blur(10px) brightness(0.25)'}, + {at: 0.5, is: 'grayscale(25%) blur(10px) brightness(0.5)'}, + {at: 0.75, is: 'grayscale(25%) blur(10px) brightness(0.75)'}, + {at: 1, is: 'grayscale(25%) blur(10px) brightness(1)'}, + {at: 1.5, is: 'grayscale(25%) blur(10px) brightness(1.5)'}, +]); + +// Make sure that a matching underlying value is still prefixed. +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + addFrom: 'grayscale(50%) blur(10px)', + addTo: 'grayscale(25%) blur(10px)', +}, [ + {at: -0.5, is: 'blur(10px) grayscale(0.625) blur(10px)'}, + {at: 0, is: 'blur(10px) grayscale(0.5) blur(10px)'}, + {at: 0.25, is: 'blur(10px) grayscale(0.4375) blur(10px)'}, + {at: 0.5, is: 'blur(10px) grayscale(0.375) blur(10px)'}, + {at: 0.75, is: 'blur(10px) grayscale(0.3125) blur(10px)'}, + {at: 1, is: 'blur(10px) grayscale(0.25) blur(10px)'}, + {at: 1.5, is: 'blur(10px) grayscale(0.125) blur(10px)'}, +]); + +// Check the case where composition causes a url() to be included; the animation +// should change to discrete. +assertComposition({ + property: 'backdrop-filter', + underlying: 'url(#a)', + addFrom: 'grayscale(50%) blur(30px)', + addTo: 'grayscale(25%) blur(40px)', +}, [ + {at: -0.5, is: 'url("#a") grayscale(0.5) blur(30px)'}, + {at: 0, is: 'url("#a") grayscale(0.5) blur(30px)'}, + {at: 0.25, is: 'url("#a") grayscale(0.5) blur(30px)'}, + {at: 0.5, is: 'url("#a") grayscale(0.25) blur(40px)'}, + {at: 0.75, is: 'url("#a") grayscale(0.25) blur(40px)'}, + {at: 1, is: 'url("#a") grayscale(0.25) blur(40px)'}, + {at: 1.5, is: 'url("#a") grayscale(0.25) blur(40px)'}, +]); + +// And check the inverse; nothing fancy here but it should be a discrete +// animation with blur prepended. +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + addFrom: 'url(#a) brightness(1)', + addTo: 'url(#b) brightness(0)', +}, [ + {at: -0.5, is: 'blur(10px) url(#a) brightness(1)'}, + {at: 0, is: 'blur(10px) url(#a) brightness(1)'}, + {at: 0.25, is: 'blur(10px) url(#a) brightness(1)'}, + {at: 0.5, is: 'blur(10px) url(#b) brightness(0)'}, + {at: 0.75, is: 'blur(10px) url(#b) brightness(0)'}, + {at: 1, is: 'blur(10px) url(#b) brightness(0)'}, + {at: 1.5, is: 'blur(10px) url(#b) brightness(0)'}, +]); + +// --------------- Accumulation tests. --------------------- + +// blur; simple addition. +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + accumulateFrom: 'blur(40px)', + accumulateTo: 'blur(90px)', +}, [ {at: -0.5, is: 'blur(25px)'}, {at: 0, is: 'blur(50px)'}, {at: 0.25, is: 'blur(62.5px)'}, @@ -18,154 +178,265 @@ {at: 1.5, is: 'blur(125px)'}, ]); -assertComposition({ - property: 'backdrop-filter', - underlying: 'sepia(0.5)', - addFrom: 'sepia(0.5)', - replaceTo: 'sepia(0)', -}, [ - {at: -0.5, is: 'sepia(1)'}, - {at: 0, is: 'sepia(1)'}, - {at: 0.25, is: 'sepia(0.75)'}, - {at: 0.5, is: 'sepia(0.5)'}, - {at: 0.75, is: 'sepia(0.25)'}, - {at: 1, is: 'sepia(0)'}, - {at: 1.5, is: 'sepia(0)'}, -]); - +// brightness; 1-based addition. assertComposition({ property: 'backdrop-filter', underlying: 'brightness(0.25)', - replaceFrom: 'brightness(0.5)', - addTo: 'brightness(1.25)', + accumulateFrom: 'brightness(0.5)', + accumulateTo: 'brightness(1.5)', }, [ {at: -0.5, is: 'brightness(0)'}, - {at: 0, is: 'brightness(0.5)'}, - {at: 0.25, is: 'brightness(0.75)'}, - {at: 0.5, is: 'brightness(1)'}, - {at: 0.75, is: 'brightness(1.25)'}, - {at: 1, is: 'brightness(1.5)'}, - {at: 1.5, is: 'brightness(2)'}, + {at: 0, is: 'brightness(0)'}, + {at: 0.25, is: 'brightness(0)'}, + {at: 0.5, is: 'brightness(0.25)'}, + {at: 0.75, is: 'brightness(0.5)'}, + {at: 1, is: 'brightness(0.75)'}, + {at: 1.5, is: 'brightness(1.25)'}, ]); +// contrast; 1-based addition. assertComposition({ property: 'backdrop-filter', - underlying: 'invert(0.5) saturate(1)', - addFrom: 'invert(1) saturate(2)', - addTo: 'invert(25%) saturate(3)', + underlying: 'contrast(0.25)', + accumulateFrom: 'contrast(0.5)', + accumulateTo: 'contrast(1.5)', }, [ - {at: -0.5, is: 'invert(1) saturate(2.5)'}, - {at: 0, is: 'invert(1) saturate(3)'}, - {at: 0.25, is: 'invert(1) saturate(3.25)'}, - {at: 0.5, is: 'invert(1) saturate(3.5)'}, - {at: 0.75, is: 'invert(0.9375) saturate(3.75)'}, - {at: 1, is: 'invert(0.75) saturate(4)'}, - {at: 1.5, is: 'invert(0.375) saturate(4.5)'}, + {at: -0.5, is: 'contrast(0)'}, + {at: 0, is: 'contrast(0)'}, + {at: 0.25, is: 'contrast(0)'}, + {at: 0.5, is: 'contrast(0.25)'}, + {at: 0.75, is: 'contrast(0.5)'}, + {at: 1, is: 'contrast(0.75)'}, + {at: 1.5, is: 'contrast(1.25)'}, ]); +// drop-shadow; addition of lengths plus color addition assertComposition({ property: 'backdrop-filter', - underlying: 'invert(0.5)', - addFrom: 'invert(1) saturate(200%)', - addTo: 'invert(25%) saturate(3) contrast(50%)', + underlying: 'drop-shadow(10px 5px 0px rgb(255, 0, 0))', + accumulateFrom: 'drop-shadow(0px 10px 10px rgb(0, 255, 0))', + accumulateTo: 'drop-shadow(50px 30px 10px rgb(0, 0, 255))', }, [ - {at: -0.5, is: 'invert(1) saturate(1.5) contrast(1.25)'}, - {at: 0, is: 'invert(1) saturate(2)'}, - {at: 0.25, is: 'invert(1) saturate(2.25) contrast(0.875)'}, - {at: 0.5, is: 'invert(1) saturate(2.5) contrast(0.75)'}, - {at: 0.75, is: 'invert(0.9375) saturate(2.75) contrast(0.625)'}, - {at: 1, is: 'invert(0.75) saturate(3) contrast(0.5)'}, - {at: 1.5, is: 'invert(0.375) saturate(3.5) contrast(0.25)'}, + {at: -0.5, is: 'drop-shadow(-15px 5px 10px rgb(255, 255, 0))'}, + {at: 0, is: 'drop-shadow(10px 15px 10px rgb(255, 255, 0))'}, + {at: 0.25, is: 'drop-shadow(22.5px 20px 10px rgb(255, 191, 64))'}, + {at: 0.5, is: 'drop-shadow(35px 25px 10px rgb(255, 128, 128))'}, + {at: 0.75, is: 'drop-shadow(47.5px 30px 10px rgb(255, 64, 191))'}, + {at: 1, is: 'drop-shadow(60px 35px 10px rgb(255, 0, 255))'}, + {at: 1.5, is: 'drop-shadow(85px 45px 10px rgb(255, 0, 255))'}, ]); +// grayscale; 1-based addition. assertComposition({ property: 'backdrop-filter', - underlying: 'invert(0.5)', - addFrom: 'none', - addTo: 'invert(25%) saturate(3) contrast(50%)', + underlying: 'grayscale(0.25)', + accumulateFrom: 'grayscale(0.5)', + accumulateTo: 'grayscale(1.5)', // clamped to 1 }, [ - {at: -0.5, is: 'invert(0.375) saturate(0) contrast(1.25)'}, - {at: 0, is: 'invert(0.5)'}, - {at: 0.25, is: 'invert(0.5625) saturate(1.5) contrast(0.875)'}, - {at: 0.5, is: 'invert(0.625) saturate(2) contrast(0.75)'}, - {at: 0.75, is: 'invert(0.6875) saturate(2.5) contrast(0.625)'}, - {at: 1, is: 'invert(0.75) saturate(3) contrast(0.5)'}, - {at: 1.5, is: 'invert(0.875) saturate(4) contrast(0.25)'}, + {at: -0.5, is: 'grayscale(0)'}, + {at: 0, is: 'grayscale(0)'}, + {at: 0.25, is: 'grayscale(0)'}, + {at: 0.5, is: 'grayscale(0)'}, + {at: 0.75, is: 'grayscale(0.125)'}, + {at: 1, is: 'grayscale(0.25)'}, + {at: 1.5, is: 'grayscale(0.5)'}, ]); +// hue-rotate; simple addition assertComposition({ property: 'backdrop-filter', - underlying: 'invert(0.5)', - addFrom: 'invert(1) saturate(200%)', - addTo: 'none', + underlying: 'hue-rotate(45deg)', + accumulateFrom: 'hue-rotate(140deg)', + accumulateTo: 'hue-rotate(400deg)', }, [ - {at: -0.5, is: 'invert(1) saturate(2.5)'}, - {at: 0, is: 'invert(1) saturate(2)'}, - {at: 0.25, is: 'invert(1) saturate(1.75)'}, - {at: 0.5, is: 'invert(1) saturate(1.5)'}, - {at: 0.75, is: 'invert(0.75) saturate(1.25)'}, - {at: 1, is: 'invert(0.5)'}, - {at: 1.5, is: 'invert(0) saturate(0.5)'}, + {at: -0.5, is: 'hue-rotate(55deg)'}, + {at: 0, is: 'hue-rotate(185deg)'}, + {at: 0.25, is: 'hue-rotate(250deg)'}, + {at: 0.5, is: 'hue-rotate(315deg)'}, + {at: 0.75, is: 'hue-rotate(380deg)'}, + {at: 1, is: 'hue-rotate(445deg)'}, + {at: 1.5, is: 'hue-rotate(575deg)'}, ]); +// invert; 1-based addition. assertComposition({ property: 'backdrop-filter', - underlying: 'none', - addFrom: 'invert(1) saturate(200%)', - addTo: 'invert(25%) saturate(3) contrast(50%)', + underlying: 'invert(0.25)', + accumulateFrom: 'invert(0.5)', + accumulateTo: 'invert(1.5)', // clamped to 1 }, [ - {at: -0.5, is: 'invert(1) saturate(1.5) contrast(1.25)'}, - {at: 0, is: 'invert(1) saturate(2)'}, - {at: 0.25, is: 'invert(0.8125) saturate(2.25) contrast(0.875)'}, - {at: 0.5, is: 'invert(0.625) saturate(2.5) contrast(0.75)'}, - {at: 0.75, is: 'invert(0.4375) saturate(2.75) contrast(0.625)'}, - {at: 1, is: 'invert(0.25) saturate(3) contrast(0.5)'}, - {at: 1.5, is: 'invert(0) saturate(3.5) contrast(0.25)'}, + {at: -0.5, is: 'invert(0)'}, + {at: 0, is: 'invert(0)'}, + {at: 0.25, is: 'invert(0)'}, + {at: 0.5, is: 'invert(0)'}, + {at: 0.75, is: 'invert(0.125)'}, + {at: 1, is: 'invert(0.25)'}, + {at: 1.5, is: 'invert(0.5)'}, ]); +// opacity; 1-based addition assertComposition({ property: 'backdrop-filter', - underlying: 'grayscale(25%) blur(10px)', - addFrom: 'grayscale(50%) blur(10px)', - addTo: 'blur(10px)', + underlying: 'opacity(0.25)', + accumulateFrom: 'opacity(0.5)', + accumulateTo: 'opacity(1.5)', // clamped to 1 }, [ - {at: -0.5, is: 'grayscale(0.75) blur(20px)'}, - {at: 0, is: 'grayscale(0.75) blur(20px)'}, - {at: 0.25, is: 'grayscale(0.75) blur(20px)'}, - {at: 0.5, is: 'blur(10px)'}, - {at: 0.75, is: 'blur(10px)'}, - {at: 1, is: 'blur(10px)'}, - {at: 1.5, is: 'blur(10px)'}, + {at: -0.5, is: 'opacity(0)'}, + {at: 0, is: 'opacity(0)'}, + {at: 0.25, is: 'opacity(0)'}, + {at: 0.5, is: 'opacity(0)'}, + {at: 0.75, is: 'opacity(0.125)'}, + {at: 1, is: 'opacity(0.25)'}, + {at: 1.5, is: 'opacity(0.5)'}, ]); +// saturate; 1-based addition +assertComposition({ + property: 'backdrop-filter', + underlying: 'saturate(0.25)', + accumulateFrom: 'saturate(0.5)', + accumulateTo: 'saturate(1.5)', +}, [ + {at: -0.5, is: 'saturate(0)'}, + {at: 0, is: 'saturate(0)'}, + {at: 0.25, is: 'saturate(0)'}, + {at: 0.5, is: 'saturate(0.25)'}, + {at: 0.75, is: 'saturate(0.5)'}, + {at: 1, is: 'saturate(0.75)'}, + {at: 1.5, is: 'saturate(1.25)'}, +]); + +// sepia; 1-based addition +assertComposition({ + property: 'backdrop-filter', + underlying: 'sepia(0.25)', + accumulateFrom: 'sepia(0.5)', + accumulateTo: 'sepia(1.5)', // clamped to 1 +}, [ + {at: -0.5, is: 'sepia(0)'}, + {at: 0, is: 'sepia(0)'}, + {at: 0.25, is: 'sepia(0)'}, + {at: 0.5, is: 'sepia(0)'}, + {at: 0.75, is: 'sepia(0.125)'}, + {at: 1, is: 'sepia(0.25)'}, + {at: 1.5, is: 'sepia(0.5)'}, +]); + +// url; cannot be accumulated +assertComposition({ + property: 'backdrop-filter', + underlying: 'url(#a)', + accumulateFrom: 'url(#b)', + accumulateTo: 'url(#c)', +}, [ + {at: -0.5, is: 'url(#b)'}, + {at: 0, is: 'url(#b)'}, + {at: 0.25, is: 'url(#b)'}, + {at: 0.5, is: 'url(#c)'}, + {at: 0.75, is: 'url(#c)'}, + {at: 1, is: 'url(#c)'}, + {at: 1.5, is: 'url(#c)'}, +]); + +// Test auto-extension of the underlying list. assertComposition({ property: 'backdrop-filter', underlying: 'blur(10px)', - addFrom: 'grayscale(50%) blur(10px)', - addTo: 'grayscale(25%) blur(10px)', + accumulateFrom: 'blur(40px) saturate(1)', + accumulateTo: 'blur(90px) saturate(0)', }, [ - {at: -0.5, is: 'grayscale(0.625) blur(10px)'}, - {at: 0, is: 'grayscale(0.5) blur(10px)'}, - {at: 0.25, is: 'grayscale(0.4375) blur(10px)'}, - {at: 0.5, is: 'grayscale(0.375) blur(10px)'}, - {at: 0.75, is: 'grayscale(0.3125) blur(10px)'}, - {at: 1, is: 'grayscale(0.25) blur(10px)'}, - {at: 1.5, is: 'grayscale(0.125) blur(10px)'}, + {at: -0.5, is: 'blur(25px) saturate(1.5)'}, + {at: 0, is: 'blur(50px) saturate(1)'}, + {at: 0.25, is: 'blur(62.5px) saturate(0.75)'}, + {at: 0.5, is: 'blur(75px) saturate(0.5)'}, + {at: 0.75, is: 'blur(87.5px) saturate(0.25)'}, + {at: 1, is: 'blur(100px) saturate(0)'}, + {at: 1.5, is: 'blur(125px) saturate(0)'}, ]); +// Test auto-extension of the composited-onto list. assertComposition({ property: 'backdrop-filter', - underlying: 'url(#a) grayscale(50%) blur(20px)', - addFrom: 'url(#a) grayscale(50%) blur(30px)', - addTo: 'url(#a) grayscale(25%) blur(40px)', + underlying: 'blur(10px) saturate(0.75)', + accumulateFrom: 'blur(40px)', + accumulateTo: 'blur(90px)', }, [ - {at: -0.5, is: 'url("#a") grayscale(0.5) blur(30px)'}, - {at: 0, is: 'url("#a") grayscale(0.5) blur(30px)'}, - {at: 0.25, is: 'url("#a") grayscale(0.5) blur(30px)'}, - {at: 0.5, is: 'url("#a") grayscale(0.25) blur(40px)'}, - {at: 0.75, is: 'url("#a") grayscale(0.25) blur(40px)'}, - {at: 1, is: 'url("#a") grayscale(0.25) blur(40px)'}, - {at: 1.5, is: 'url("#a") grayscale(0.25) blur(40px)'}, + {at: -0.5, is: 'blur(25px) saturate(0.75)'}, + {at: 0, is: 'blur(50px) saturate(0.75)'}, + {at: 0.25, is: 'blur(62.5px) saturate(0.75)'}, + {at: 0.5, is: 'blur(75px) saturate(0.75)'}, + {at: 0.75, is: 'blur(87.5px) saturate(0.75)'}, + {at: 1, is: 'blur(100px) saturate(0.75)'}, + {at: 1.5, is: 'blur(125px) saturate(0.75)'}, +]); + +// Mismatching type for underlying; it just gets replaced. +assertComposition({ + property: 'backdrop-filter', + underlying: 'contrast(0.75)', + accumulateFrom: 'blur(40px)', + accumulateTo: 'blur(80px)', +}, [ + {at: -0.5, is: 'blur(20px)'}, + {at: 0, is: 'blur(40px)'}, + {at: 0.25, is: 'blur(50px)'}, + {at: 0.5, is: 'blur(60px)'}, + {at: 0.75, is: 'blur(70px)'}, + {at: 1, is: 'blur(80px)'}, + {at: 1.5, is: 'blur(100px)'}, +]); + +// Underlying only type-matches one side of the interpolation; it should be +// accumulated onto that side, but the entire animation will be discrete due to +// the mis-matching types. +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + accumulateFrom: 'blur(40px)', + accumulateTo: 'saturate(1)', +}, [ + {at: -0.5, is: 'blur(50px)'}, + {at: 0, is: 'blur(50px)'}, + {at: 0.25, is: 'blur(50px)'}, + {at: 0.5, is: 'saturate(1)'}, + {at: 0.75, is: 'saturate(1)'}, + {at: 1, is: 'saturate(1)'}, + {at: 1.5, is: 'saturate(1)'}, +]); + +// Test a case where only one side is accumulative and the other is replace. +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + accumulateFrom: 'blur(30px)', + replaceTo: 'blur(100px)', +}, [ + {at: -0.5, is: 'blur(10px)'}, + {at: 0, is: 'blur(40px)'}, + {at: 0.25, is: 'blur(55px)'}, + {at: 0.5, is: 'blur(70px)'}, + {at: 0.75, is: 'blur(85px)'}, + {at: 1, is: 'blur(100px)'}, + {at: 1.5, is: 'blur(130px)'}, +]); + +// Test a case where only one side is accumulative and the other is add. +// This basically looks like: +// accumulateSide = blur(Apx) neutral-blur +// addSide = blur(10px) blur(Bpx) +assertComposition({ + property: 'backdrop-filter', + underlying: 'blur(10px)', + accumulateFrom: 'blur(40px)', + addTo: 'blur(100px)', +}, [ + {at: -0.5, is: 'blur(70px) blur(0px)'}, + {at: 0, is: 'blur(50px) blur(0px)'}, + {at: 0.25, is: 'blur(40px) blur(25px)'}, + {at: 0.5, is: 'blur(30px) blur(50px)'}, + {at: 0.75, is: 'blur(20px) blur(75px)'}, + {at: 1, is: 'blur(10px) blur(100px)'}, + {at: 1.5, is: 'blur(0px) blur(150px)'}, ]); </script> </body>
diff --git a/third_party/blink/web_tests/animations/interpolation/border-spacing-interpolation.html b/third_party/blink/web_tests/animations/interpolation/border-spacing-interpolation.html index b159a35..ecde603 100644 --- a/third_party/blink/web_tests/animations/interpolation/border-spacing-interpolation.html +++ b/third_party/blink/web_tests/animations/interpolation/border-spacing-interpolation.html
@@ -37,66 +37,6 @@ <script src="resources/interpolation-test.js"></script> <script> assertInterpolation({ - property: 'border-spacing', - from: neutralKeyframe, - to: '20px', -}, [ - {at: -0.3, is: '7px 7px'}, - {at: 0, is: '10px 10px'}, - {at: 0.3, is: '13px 13px'}, - {at: 0.6, is: '16px 16px'}, - {at: 1, is: '20px 20px'}, - {at: 1.5, is: '25px 25px'}, -]); -assertInterpolation({ - property: 'border-spacing', - from: 'initial', - to: '20px', -}, [ - {at: -0.3, is: '0px 0px'}, - {at: 0, is: '0px 0px'}, - {at: 0.3, is: '6px 6px'}, - {at: 0.6, is: '12px 12px'}, - {at: 1, is: '20px 20px'}, - {at: 1.5, is: '30px 30px'}, -]); -assertInterpolation({ - property: 'border-spacing', - from: 'inherit', - to: '20px', -}, [ - {at: -0.3, is: '33px 33px'}, - {at: 0, is: '30px 30px'}, - {at: 0.3, is: '27px 27px'}, - {at: 0.6, is: '24px 24px'}, - {at: 1, is: '20px 20px'}, - {at: 1.5, is: '15px 15px'}, -]); -assertInterpolation({ - property: 'border-spacing', - from: 'unset', - to: '20px', -}, [ - {at: -0.3, is: '33px 33px'}, - {at: 0, is: '30px 30px'}, - {at: 0.3, is: '27px 27px'}, - {at: 0.6, is: '24px 24px'}, - {at: 1, is: '20px 20px'}, - {at: 1.5, is: '15px 15px'}, -]); -assertInterpolation({ - property: 'border-spacing', - from: '0px', - to: '10px' -}, [ - {at: -0.3, is: '0px 0px'}, // Can't be negative. - {at: 0, is: '0px 0px'}, - {at: 0.3, is: '3px 3px'}, - {at: 0.6, is: '6px 6px'}, - {at: 1, is: '10px 10px'}, - {at: 1.5, is: '15px 15px'} -]); -assertInterpolation({ property: '-webkit-border-horizontal-spacing', from: '0px', to: '10px'
diff --git a/third_party/blink/web_tests/animations/interpolation/clip-path-interpolation.html b/third_party/blink/web_tests/animations/interpolation/clip-path-interpolation.html index b91dbf3..5af39a9 100644 --- a/third_party/blink/web_tests/animations/interpolation/clip-path-interpolation.html +++ b/third_party/blink/web_tests/animations/interpolation/clip-path-interpolation.html
@@ -1,130 +1,8 @@ <!DOCTYPE html> <meta charset="UTF-8"> -<style> -.parent { - clip-path: circle(80% at 30% 10%); -} -.target { - clip-path: circle(60% at 10% 30%); -} -</style> <body> <script src="resources/interpolation-test.js"></script> <script> -/* TODO: add inset test once blend() works for it */ - -assertInterpolation({ - property: 'clip-path', - from: neutralKeyframe, - to: 'circle(40% at 20% 20%)', -}, [ - {at: -0.3, is: 'circle(66% at 7% 33%)'}, - {at: 0, is: 'circle(60% at 10% 30%)'}, - {at: 0.3, is: 'circle(54% at 13% 27%)'}, - {at: 0.6, is: 'circle(48% at 16% 24%)'}, - {at: 1, is: 'circle(40% at 20% 20%)'}, - {at: 1.5, is: 'circle(30% at 25% 15%)'}, -]); - -assertNoInterpolation({ - property: 'clip-path', - from: 'initial', - to: 'circle(40% at 20% 20%)', -}); - -assertInterpolation({ - property: 'clip-path', - from: 'inherit', - to: 'circle(40% at 20% 20%)', -}, [ - {at: -0.3, is: 'circle(92% at 33% 7%)'}, - {at: 0, is: 'circle(80% at 30% 10%)'}, - {at: 0.3, is: 'circle(68% at 27% 13%)'}, - {at: 0.6, is: 'circle(56% at 24% 16%)'}, - {at: 1, is: 'circle(40% at 20% 20%)'}, - {at: 1.5, is: 'circle(20% at 15% 25%)'}, -]); - -assertNoInterpolation({ - property: 'clip-path', - from: 'unset', - to: 'circle(40% at 20% 20%)', -}); - -assertInterpolation({ - property: 'clip-path', - from: 'circle(100% at 0% 0%)', - to: 'circle(50% at 25% 25%)', -}, [ - {at: -0.3, is: 'circle(115% at -7.5% -7.5%)'}, - {at: 0, is: 'circle(100% at 0% 0%)'}, - {at: 0.3, is: 'circle(85% at 7.5% 7.5%)'}, - {at: 0.6, is: 'circle(70% at 15% 15%)'}, - {at: 1, is: 'circle(50% at 25% 25%)'}, - {at: 1.5, is: 'circle(25% at 37.5% 37.5%)'} -]); - -assertInterpolation({ - property: 'clip-path', - from: 'ellipse(100% 100% at 0% 0%)', - to: 'ellipse(50% 50% at 25% 25%)', -}, [ - {at: -0.3, is: 'ellipse(115% 115% at -7.5% -7.5%)'}, - {at: 0, is: 'ellipse(100% 100% at 0% 0%)'}, - {at: 0.3, is: 'ellipse(85% 85% at 7.5% 7.5%)'}, - {at: 0.6, is: 'ellipse(70% 70% at 15% 15%)'}, - {at: 1, is: 'ellipse(50% 50% at 25% 25%)'}, - {at: 1.5, is: 'ellipse(25% 25% at 37.5% 37.5%)'} -]); - -assertInterpolation({ - property: 'clip-path', - from: 'polygon(nonzero, 0px 0px, 25px 25px, 50px 50px)', - to: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)', -}, [ - {at: -0.3, is: 'polygon(nonzero, -7.5px -7.5px, 17.5px 17.5px, 42.5px 42.5px)'}, - {at: 0, is: 'polygon(nonzero, 0px 0px, 25px 25px, 50px 50px)'}, - {at: 0.3, is: 'polygon(nonzero, 7.5px 7.5px, 32.5px 32.5px, 57.5px 57.5px)'}, - {at: 0.6, is: 'polygon(nonzero, 15px 15px, 40px 40px, 65px 65px)'}, - {at: 1, is: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)'}, - {at: 1.5, is: 'polygon(nonzero, 37.5px 37.5px, 62.5px 62.5px, 87.5px 87.5px)'} -]); - -assertNoInterpolation({ - property: 'clip-path', - from: 'polygon(evenodd, 0px 0px, 25px 25px, 50px 50px)', - to: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)', -}); - -assertInterpolation({ - property: 'clip-path', - from: 'inset(100%)', - to: 'inset(120%)', -}, [ - {at: -0.3, is: 'inset(94%)'}, - {at: 0, is: 'inset(100%)'}, - {at: 0.3, is: 'inset(106%)'}, - {at: 0.6, is: 'inset(112%)'}, - {at: 1, is: 'inset(120%)'}, - {at: 1.5, is: 'inset(130%)'}, -]); - -assertNoInterpolation({ - property: 'clip-path', - from: 'none', - to: 'ellipse(100% 100% at 0% 0%)', -}); - -assertInterpolation({ - property: 'clip-path', - from: 'circle(25% at right 5% bottom 15px)', - to: 'circle(45% at right 25% bottom 35px)', -}, [ - {at: 0.25, is: 'circle(30% at 90% calc(-20px + 100%))'}, - {at: 0.5, is: 'circle(35% at 85% calc(-25px + 100%))'}, - {at: 0.75, is: 'circle(40% at 80% calc(-30px + 100%))'}, -]); - // Regression test for crbug.com/920122. assertInterpolation({ property: 'clip-path', @@ -134,13 +12,6 @@ {at: 3.40282e+38, is: 'inset(calc(3.40282e+38% + -3.40282e+38px))'}, ]); - -assertNoInterpolation({ - property: 'clip-path', - from: 'url("/clip-source")', - to: 'ellipse(100% 100% at 0% 0%)', -}); - // clip-path <geometry-box> support is not yet implemented in Blink. // crbug.com/694218
diff --git a/third_party/blink/web_tests/animations/interpolation/color-option-interpolation.html b/third_party/blink/web_tests/animations/interpolation/color-option-interpolation.html deleted file mode 100644 index d93d475..0000000 --- a/third_party/blink/web_tests/animations/interpolation/color-option-interpolation.html +++ /dev/null
@@ -1,89 +0,0 @@ -<!DOCTYPE html> -<meta charset="UTF-8"> -<style> -.parent { - color: blue; -} -.target { - display: inline-block; - font-size: 60pt; - color: yellow; -} -.expected { - margin-right: 15px; -} -</style> -<body alink="red" link="blue"> -<template id="target-template"> - <select> - <option class="target" selected>opt</option> - </select> -</template> -<script src="resources/interpolation-test.js"></script> -<script> -assertInterpolation({ - property: 'color', - from: neutralKeyframe, - to: 'green', -}, [ - {at: -0.3, is: 'rgb(255, 255, 0)'}, - {at: 0, is: 'rgb(255, 255, 0)'}, - {at: 0.3, is: 'rgb(179, 217, 0)'}, - {at: 0.6, is: 'rgb(102, 179, 0)'}, - {at: 1, is: 'rgb(0, 128, 0)'}, - {at: 1.5, is: 'rgb(0, 65, 0)'}, -]); - -assertInterpolation({ - property: 'color', - from: 'initial', - to: 'green', -}, [ - {at: -0.3, is: 'rgb(0, 0, 0)'}, - {at: 0, is: 'rgb(0, 0, 0)'}, - {at: 0.3, is: 'rgb(0, 38, 0)'}, - {at: 0.6, is: 'rgb(0, 77, 0)'}, - {at: 1, is: 'rgb(0, 128, 0)'}, - {at: 1.5, is: 'rgb(0, 192, 0)'}, -]); - -assertInterpolation({ - property: 'color', - from: 'black', - to: 'orange', -}, [ - {at: -0.3, is: 'rgb(0, 0, 0)'}, - {at: 0, is: 'rgb(0, 0, 0)'}, - {at: 0.3, is: 'rgb(77, 50, 0)'}, - {at: 0.6, is: 'rgb(153, 99, 0)'}, - {at: 1, is: 'rgb(255, 165, 0)'}, - {at: 1.5, is: 'rgb(255, 248, 0)'}, -]); - -assertInterpolation({ - property: 'color', - from: '-webkit-activelink', - to: 'green', -}, [ - {at: -0.3, is: 'rgb(255, 0, 0)'}, - {at: 0, is: 'rgb(255, 0, 0)'}, - {at: 0.3, is: 'rgb(179, 38, 0)'}, - {at: 0.6, is: 'rgb(102, 77, 0)'}, - {at: 1, is: 'rgb(0, 128, 0)'}, - {at: 1.5, is: 'rgb(0, 192, 0)'}, -]); - -assertInterpolation({ - property: 'color', - from: '-webkit-link', - to: 'green', -}, [ - {at: -0.3, is: 'rgb(0, 0, 255)'}, - {at: 0, is: 'rgb(0, 0, 255)'}, - {at: 0.3, is: 'rgb(0, 38, 179)'}, - {at: 0.6, is: 'rgb(0, 77, 102)'}, - {at: 1, is: 'rgb(0, 128, 0)'}, - {at: 1.5, is: 'rgb(0, 192, 0)'}, -]); -</script> -</body>
diff --git a/third_party/blink/web_tests/animations/interpolation/margin-interpolation.html b/third_party/blink/web_tests/animations/interpolation/margin-interpolation.html deleted file mode 100644 index bbd849e..0000000 --- a/third_party/blink/web_tests/animations/interpolation/margin-interpolation.html +++ /dev/null
@@ -1,107 +0,0 @@ -<!DOCTYPE html> -<meta charset="UTF-8"> -<style> -.parent { - margin: 10px; - border: solid; - display: inline-block; -} -.target { - width: 40px; - height: 40px; - background-color: black; - display: inline-block; - margin: 30px; - opacity: 0.5; -} -.expected { - background-color: green; -} -</style> -<body> -<template id="target-template"> - <div> - <div class="target"></div> - </div> -</template> -<script src="resources/interpolation-test.js"></script> -<script> -assertInterpolation({ - property: 'margin', - from: neutralKeyframe, - to: '20px', -}, [ - {at: -0.3, is: '33px'}, - {at: 0, is: '30px'}, - {at: 0.3, is: '27px'}, - {at: 0.6, is: '24px'}, - {at: 1, is: '20px'}, - {at: 1.5, is: '15px'}, -]); - -assertInterpolation({ - property: 'margin', - from: 'initial', - to: '20px', -}, [ - {at: -0.3, is: '-6px'}, - {at: 0, is: '0px'}, - {at: 0.3, is: '6px'}, - {at: 0.6, is: '12px'}, - {at: 1, is: '20px'}, - {at: 1.5, is: '30px'}, -]); - -assertInterpolation({ - property: 'margin', - from: 'inherit', - to: '20px', -}, [ - {at: -0.3, is: '7px'}, - {at: 0, is: '10px'}, - {at: 0.3, is: '13px'}, - {at: 0.6, is: '16px'}, - {at: 1, is: '20px'}, - {at: 1.5, is: '25px'}, -]); - -assertInterpolation({ - property: 'margin', - from: 'unset', - to: '20px', -}, [ - {at: -0.3, is: '-6px'}, - {at: 0, is: '0px'}, - {at: 0.3, is: '6px'}, - {at: 0.6, is: '12px'}, - {at: 1, is: '20px'}, - {at: 1.5, is: '30px'}, -]); - -assertInterpolation({ - property: 'margin', - from: '0px', - to: '10px' -}, [ - {at: -0.3, is: '-3px'}, - {at: 0, is: '0px'}, - {at: 0.3, is: '3px'}, - {at: 0.6, is: '6px'}, - {at: 1, is: '10px'}, - {at: 1.5, is: '15px'} -]); - -assertInterpolation({ - property: 'margin', - from: '20px 40px 60px 80px', - to: '30px 50px 70px 90px' -}, [ - {at: -0.3, is: '17px 37px 57px 77px'}, - {at: 0, is: '20px 40px 60px 80px'}, - {at: 0.3, is: '23px 43px 63px 83px'}, - {at: 0.6, is: '26px 46px 66px 86px'}, - {at: 1, is: '30px 50px 70px 90px'}, - {at: 1.5, is: '35px 55px 75px 95px'} -]); -</script> -</body>
diff --git a/third_party/blink/web_tests/animations/interpolation/resources/interpolation-test.js b/third_party/blink/web_tests/animations/interpolation/resources/interpolation-test.js index 43227df5..cfd875f 100644 --- a/third_party/blink/web_tests/animations/interpolation/resources/interpolation-test.js +++ b/third_party/blink/web_tests/animations/interpolation/resources/interpolation-test.js
@@ -42,12 +42,15 @@ * This works in the same way as assertInterpolation with expectations auto * generated according to each interpolation method's handling of values * that don't interpolate. - * - assertComposition({property, underlying, [addFrom], [addTo], [replaceFrom], [replaceTo]}, [{at: fraction, is: value}]) + * - assertComposition( + * { property, underlying, [accumulateFrom], [accumulateTo], + * [addFrom], [addTo], [replaceFrom], [replaceTo] }, + * [{at: fraction, is: value}]) * Similar to assertInterpolation() instead using only the Web Animations API - * to animate composite specified keyframes (add or replace) on top of - * an underlying value. - * Exactly one of (addFrom, replaceFrom) must be specified. - * Exactly one of (addTo, replaceTo) must be specified. + * to animate composite specified keyframes (accumulate, add or replace) on + * top of an underlying value. + * Exactly one of (accumulateFrom, addFrom, replaceFrom) must be specified. + * Exactly one of (accumulateTo, addTo, replaceTo) must be specified. * - afterTest(callback) * Calls callback after all the tests have executed. * @@ -372,16 +375,19 @@ var options = compositionTest.options; var property = options.property; var underlying = options.underlying; - var from = options.addFrom || options.replaceFrom; - var to = options.addTo || options.replaceTo; - var fromComposite = 'addFrom' in options ? 'add' : 'replace'; - var toComposite = 'addTo' in options ? 'add' : 'replace'; - if ('addFrom' in options === 'replaceFrom' in options - || 'addTo' in options === 'replaceTo' in options) { + var from = options.accumulateFrom || options.addFrom || options.replaceFrom; + var to = options.accumulateTo || options.addTo || options.replaceTo; + var fromComposite = 'accumulateFrom' in options ? 'accumulate' : 'addFrom' in options ? 'add' : 'replace'; + var toComposite = 'accumulateTo' in options ? 'accumulate' : 'addTo' in options ? 'add' : 'replace'; + const invalidFrom = 'addFrom' in options === 'replaceFrom' in options + && 'addFrom' in options === 'accumulateFrom' in options; + const invalidTo = 'addTo' in options === 'replaceTo' in options + && 'addTo' in options === 'accumulateTo' in options; + if (invalidFrom || invalidTo) { test(function() { - assert_true('addFrom' in options !== 'replaceFrom' in options, 'addFrom xor replaceFrom must be specified'); - assert_true('addTo' in options !== 'replaceTo' in options, 'addTo xor replaceTo must be specified'); - }, `Composition tests must use addFrom xor replaceFrom, and addTo xor replaceTo`); + assert_false(invalidFrom, 'Exactly one of accumulateFrom, addFrom, or replaceFrom must be specified'); + assert_false(invalidTo, 'Exactly one of accumulateTo, addTo, or replaceTo must be specified'); + }, `Composition tests must have valid setup`); } validateTestInputs(property, from, to, underlying);
diff --git a/third_party/blink/web_tests/badging/badge-error.html b/third_party/blink/web_tests/badging/badge-error.html index 4f19696..62ccb5d 100644 --- a/third_party/blink/web_tests/badging/badge-error.html +++ b/third_party/blink/web_tests/badging/badge-error.html
@@ -12,36 +12,21 @@ <script> // Negative value not allowed. -badge_test(() => { ExperimentalBadge.set(-1); }, undefined, undefined, - 'TypeError'); +badge_test(() => { ExperimentalBadge.set(-1); }, undefined, 'TypeError'); // Value too large (2^53). -badge_test(() => { ExperimentalBadge.set(9007199254740992); }, undefined, - undefined, 'TypeError'); +badge_test(() => { ExperimentalBadge.set(9007199254740992); }, + undefined, + 'TypeError'); // Illegal numeric values. -badge_test(() => { ExperimentalBadge.set(Infinity); }, undefined, undefined, - 'TypeError'); -badge_test(() => { ExperimentalBadge.set(-Infinity); }, undefined, undefined, - 'TypeError'); -badge_test(() => { ExperimentalBadge.set(NaN); }, undefined, undefined, - 'TypeError'); +badge_test(() => { ExperimentalBadge.set(Infinity); }, undefined, 'TypeError'); +badge_test(() => { ExperimentalBadge.set(-Infinity); }, undefined, 'TypeError'); +badge_test(() => { ExperimentalBadge.set(NaN); }, undefined, 'TypeError'); // Other values that can't convert to a long. -badge_test(() => { ExperimentalBadge.set("Foo"); }, undefined, undefined, - 'TypeError'); -badge_test(() => { ExperimentalBadge.set({}); }, undefined, undefined, - 'TypeError'); - -// Wrong origin. -badge_test(() => { - ExperimentalBadge.set(1, {scope: 'https://wrongorigin.com/scope'}); -}, undefined, undefined, 'SecurityError'); - -// Invalid URL. -badge_test(() => { - ExperimentalBadge.set(1, {scope: 'https://example.com:99999'}); -}, undefined, undefined, 'TypeError'); +badge_test(() => { ExperimentalBadge.set("Foo"); }, undefined, 'TypeError'); +badge_test(() => { ExperimentalBadge.set({}); }, undefined, 'TypeError'); </script> </body>
diff --git a/third_party/blink/web_tests/badging/badge-success.html b/third_party/blink/web_tests/badging/badge-success.html index 1174ecc..403833c 100644 --- a/third_party/blink/web_tests/badging/badge-success.html +++ b/third_party/blink/web_tests/badging/badge-success.html
@@ -11,51 +11,29 @@ <body> <script> -// The default scope URL is the current origin. -const defaultScope = new URL('/', location).href; +badge_test(() => { ExperimentalBadge.set(); }, 'flag'); -badge_test(() => { ExperimentalBadge.set(); }, 'flag', defaultScope); +badge_test(() => { ExperimentalBadge.set(undefined); }, 'flag'); -badge_test(() => { ExperimentalBadge.set(undefined); }, 'flag', defaultScope); - -badge_test(() => { ExperimentalBadge.set(1); }, 'number:1', defaultScope); +badge_test(() => { ExperimentalBadge.set(1); }, 'number:1'); // Non-whole number should round down to nearest integer. -badge_test(() => { ExperimentalBadge.set(10.6); }, 'number:10', defaultScope); +badge_test(() => { ExperimentalBadge.set(10.6); }, 'number:10'); // Maximum allowed value (2^53 - 1). badge_test(() => { ExperimentalBadge.set(9007199254740991); }, - 'number:9007199254740991', defaultScope); + 'number:9007199254740991'); // Setting the Badge to 0 should be equivalent to clearing the badge. -badge_test(() => { ExperimentalBadge.set(0); }, 'clear', defaultScope); +badge_test(() => { ExperimentalBadge.set(0); }, 'clear'); -badge_test(() => { ExperimentalBadge.clear(); }, 'clear', defaultScope); +badge_test(() => { ExperimentalBadge.clear(); }, 'clear'); // Non-numeric values that convert to integer. -badge_test(() => { ExperimentalBadge.set(null); }, 'clear', defaultScope); -badge_test(() => { ExperimentalBadge.set(false); }, 'clear', defaultScope); -badge_test(() => { ExperimentalBadge.set(true); }, 'number:1', defaultScope); -badge_test(() => { ExperimentalBadge.set('3'); }, 'number:3', defaultScope); - -// Test options dictionary. - -badge_test(() => { ExperimentalBadge.set(1, {}); }, 'number:1', defaultScope); -badge_test(() => { ExperimentalBadge.set(1, {foo: 4}); }, 'number:1', - defaultScope); - -badge_test(() => { - ExperimentalBadge.set(1, {scope: new URL('/scope', location).href}); -}, 'number:1', new URL('/scope', location).href); -// Scope URL resolved against document. -badge_test(() => { ExperimentalBadge.set(1, {scope: '/scope'}); }, - 'number:1', new URL('/scope', location).href); - -// Explicit undefined to set a flag with a scope. -// TODO(mgiuca): Currently fails with TypeError. https://crbug.com/1001411 -// badge_test(() => { -// ExperimentalBadge.set(undefined, {scope: 'https://example.com/scope'}); -// }, 'number:1', 'https://example.com/scope'); +badge_test(() => { ExperimentalBadge.set(null); }, 'clear'); +badge_test(() => { ExperimentalBadge.set(false); }, 'clear'); +badge_test(() => { ExperimentalBadge.set(true); }, 'number:1'); +badge_test(() => { ExperimentalBadge.set('3'); }, 'number:3'); </script> </body>
diff --git a/third_party/blink/web_tests/badging/resources/mock-badge-service.js b/third_party/blink/web_tests/badging/resources/mock-badge-service.js index 28708a5..8012aee 100644 --- a/third_party/blink/web_tests/badging/resources/mock-badge-service.js +++ b/third_party/blink/web_tests/badging/resources/mock-badge-service.js
@@ -10,16 +10,15 @@ this.interceptor_.start(); } - init_(expectedAction, expectedScope) { + init_(expectedAction) { this.expectedAction = expectedAction; - this.expectedScope = expectedScope; return new Promise((resolve, reject) => { this.reject_ = reject; this.resolve_ = resolve; }); } - setBadge(scope, value) { + setBadge(value) { // Accessing number when the union is a flag will throw, so read the // value in a try catch. let number; @@ -32,17 +31,15 @@ try { const action = number === undefined ? 'flag' : 'number:' + number; assert_equals(action, this.expectedAction); - assert_equals(scope.url, this.expectedScope); this.resolve_(); } catch (error) { this.reject_(error); } } - clearBadge(scope) { + clearBadge() { try { assert_equals('clear', this.expectedAction); - assert_equals(scope.url, this.expectedScope); this.resolve_(); } catch (error) { this.reject_(error); @@ -67,9 +64,9 @@ }); } -function badge_test(func, expectedAction, expectedScope, expectedError) { +function badge_test(func, expectedAction, expectedError) { promise_test(() => { - let mockPromise = mockBadgeService.init_(expectedAction, expectedScope); + let mockPromise = mockBadgeService.init_(expectedAction); return Promise.race( [callAndObserveErrors(func, expectedError), mockPromise]); });
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 7f30bd1..6f1e902a 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
@@ -174592,6 +174592,12 @@ "upgrade-insecure-requests/OWNERS": [ [] ], + "upgrade-insecure-requests/generic/test-case.sub.js": [ + [] + ], + "upgrade-insecure-requests/generic/tools/generate.py": [ + [] + ], "upgrade-insecure-requests/link-upgrade/basic-link-no-upgrade.sub.html": [ [] ], @@ -174664,7 +174670,10 @@ "upgrade-insecure-requests/shared-worker-upgrade.https-expected.txt": [ [] ], - "upgrade-insecure-requests/support/generate.py": [ + "upgrade-insecure-requests/spec.src.json": [ + [] + ], + "upgrade-insecure-requests/spec_json.js": [ [] ], "upgrade-insecure-requests/support/redirect-cors.py": [ @@ -197532,6 +197541,144 @@ {} ] ], + "compression/decompression-bad-chunks.any.js": [ + [ + "compression/decompression-bad-chunks.any.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-bad-chunks.any.serviceworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-bad-chunks.any.sharedworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-bad-chunks.any.worker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ] + ], + "compression/decompression-constructor-error.any.js": [ + [ + "compression/decompression-constructor-error.any.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-constructor-error.any.serviceworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-constructor-error.any.sharedworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-constructor-error.any.worker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ] + ], + "compression/decompression-correct-input.any.js": [ + [ + "compression/decompression-correct-input.any.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-correct-input.any.serviceworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-correct-input.any.sharedworker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ], + [ + "compression/decompression-correct-input.any.worker.html", + { + "script_metadata": [ + [ + "global", + "worker" + ] + ] + } + ] + ], "console/console-is-a-namespace.any.js": [ [ "console/console-is-a-namespace.any.html", @@ -283596,6 +283743,12 @@ {} ] ], + "resource-timing/resource_hash.htm": [ + [ + "resource-timing/resource_hash.htm", + {} + ] + ], "resource-timing/resource_ignore_data_url.html": [ [ "resource-timing/resource_ignore_data_url.html", @@ -328095,7 +328248,7 @@ "testharness" ], "animation-worklet/idlharness.any.worker-expected.txt": [ - "190d29155cf1677662da92d196566ca17f8c27d9", + "df764b287d58bbce24c8be311fc79b7578c3f071", "support" ], "animation-worklet/inactive-timeline.https.html": [ @@ -330055,11 +330208,11 @@ "support" ], "common/security-features/tools/format_spec_src_json.py": [ - "1276c78f9fb71f98971476000c082ab3511787e6", + "b4549bb710cd119e87ca4a41d65d7980b6b40406", "support" ], "common/security-features/tools/generate.py": [ - "0cf7fab42ec199b5f93926a5133ff149bff93c8c", + "fa36d8c63d6d84a1c5eafd3160b879f7f3c94310", "support" ], "common/security-features/tools/spec_validator.py": [ @@ -330254,6 +330407,18 @@ "1d3965fca6769c70bc02308a4c70b4e58c8990e5", "reftest" ], + "compression/decompression-bad-chunks.any.js": [ + "8f44ffd902f0838cecf72be50245ab4c683fc09c", + "testharness" + ], + "compression/decompression-constructor-error.any.js": [ + "9ffdb08ce2ff365f70af8121f82e5856c6de9533", + "testharness" + ], + "compression/decompression-correct-input.any.js": [ + "11d8736cb225d6ce575677dcdb70b0a19dd4f65f", + "testharness" + ], "console/META.yml": [ "60c95d0d579c57eee3c2c0b47004b371c24d2e56", "support" @@ -428131,7 +428296,7 @@ "support" ], "fetch/api/resources/preflight.py": [ - "d2249606db624892dab96fc9484a9e274947b859", + "a2552c2565ad9be6d17dea1cb6a90ff9eb211190", "support" ], "fetch/api/resources/redirect-empty-location.py": [ @@ -452219,7 +452384,7 @@ "support" ], "interfaces/css-animation-worklet.idl": [ - "4aca84e5a024efdc2d3e674540bf2091758551c9", + "2c46cc7c94c65d6928db9f4e90a57c6188815d8e", "support" ], "interfaces/css-animations.idl": [ @@ -452355,7 +452520,7 @@ "support" ], "interfaces/gyroscope.idl": [ - "24cd82c643159d680004937d12a17a38c06ece1b", + "3754fd81e6bf605a308794e5b759ecd8784a6a15", "support" ], "interfaces/hr-time.idl": [ @@ -478926,6 +479091,10 @@ "de3c3d015d1db068868b54b924a358018fb49e84", "testharness" ], + "resource-timing/resource_hash.htm": [ + "a44c1c9065967682261346051f5e4391d81f1667", + "testharness" + ], "resource-timing/resource_ignore_data_url.html": [ "f8ca2f1187e934fc9b07b5dbc31769f887528b51", "testharness" @@ -494234,6 +494403,14 @@ "704bba994088a6e2197142a7ddbd71bc89eea7d8", "testharness" ], + "upgrade-insecure-requests/generic/test-case.sub.js": [ + "cde228dbad89f7b707a6332dc8ed3b41e0474555", + "support" + ], + "upgrade-insecure-requests/generic/tools/generate.py": [ + "cde29893f5fbd35ff0ccf00f7ee323fbb3194c8b", + "support" + ], "upgrade-insecure-requests/iframe-redirect-upgrade.https.html": [ "7d0a310cf43e6144d3fc2d13f81d3f8912569e3f", "testharness" @@ -494394,8 +494571,12 @@ "cf1d3c382e4b139db42e807ab1db166cb0d4fbbb", "testharness" ], - "upgrade-insecure-requests/support/generate.py": [ - "e3f5aaf3ddf858989f83bcba1743ef73978162e1", + "upgrade-insecure-requests/spec.src.json": [ + "6aee9a280b0ff5001c77e2d8a688618c049dc226", + "support" + ], + "upgrade-insecure-requests/spec_json.js": [ + "9122ce38e31e1a2c2c2c3f4caa291ae24e91a8cb", "support" ], "upgrade-insecure-requests/support/redirect-cors.py": [ @@ -495451,7 +495632,7 @@ "support" ], "web-animations/animation-model/animation-types/accumulation-per-property-expected.txt": [ - "21f5bd82c5df91569054b3c3c9f8f182f8877f5f", + "f556eb3ac384b07d47bbdb3d9a775401934f3dd6", "support" ], "web-animations/animation-model/animation-types/accumulation-per-property.html": [ @@ -495459,7 +495640,7 @@ "testharness" ], "web-animations/animation-model/animation-types/addition-per-property-expected.txt": [ - "d8f9003384fd8716a822d945161c17ebe86677a7", + "b435eccd16a1d969a2d43942c3478e745ac5b6d4", "support" ], "web-animations/animation-model/animation-types/addition-per-property.html": [ @@ -498191,7 +498372,7 @@ "wdspec" ], "webdriver/tests/take_element_screenshot/user_prompts.py": [ - "221eaa9363528d3fa102f9506d81bca89546e9f5", + "5d1b497ff2c4dcda6b1d5d14d9fd99c4c282809c", "wdspec" ], "webdriver/tests/take_screenshot/__init__.py": [ @@ -498207,7 +498388,7 @@ "wdspec" ], "webdriver/tests/take_screenshot/user_prompts.py": [ - "902463f22c8165628ce5fccffafdc70481300f20", + "ad9e3695148d63153db8aacbe3b8444a814d5ba3", "wdspec" ], "webgpu/OWNERS": [
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/idlharness.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/animation-worklet/idlharness.any.worker-expected.txt index 190d2915..df764b2 100644 --- a/third_party/blink/web_tests/external/wpt/animation-worklet/idlharness.any.worker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/idlharness.any.worker-expected.txt
@@ -9,6 +9,7 @@ PASS WorkletAnimation interface: existence and properties of interface object FAIL WorkletAnimation must be primary interface of new WorkletAnimation("name") assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: WorkletAnimation is not defined" FAIL Stringification of new WorkletAnimation("name") assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: WorkletAnimation is not defined" +FAIL WorkletAnimation interface: new WorkletAnimation("name") must not have property "undefined" assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: WorkletAnimation is not defined" FAIL WorkletAnimation interface: new WorkletAnimation("name") must not have property "animatorName" assert_equals: Unexpected exception when evaluating object expected null but got object "ReferenceError: WorkletAnimation is not defined" PASS WorkletGroupEffect interface: existence and properties of interface object PASS WorkletGlobalScope interface: existence and properties of interface object
diff --git a/third_party/blink/web_tests/external/wpt/common/security-features/tools/format_spec_src_json.py b/third_party/blink/web_tests/external/wpt/common/security-features/tools/format_spec_src_json.py index 1276c78..b4549bb 100644 --- a/third_party/blink/web_tests/external/wpt/common/security-features/tools/format_spec_src_json.py +++ b/third_party/blink/web_tests/external/wpt/common/security-features/tools/format_spec_src_json.py
@@ -6,7 +6,9 @@ def main(): '''Formats spec.src.json.''' script_directory = os.path.dirname(os.path.abspath(__file__)) - for dir in ['mixed-content', 'referrer-policy']: + for dir in [ + 'mixed-content', 'referrer-policy', 'upgrade-insecure-requests' + ]: filename = os.path.join(script_directory, '..', '..', '..', dir, 'spec.src.json') spec = json.load(
diff --git a/third_party/blink/web_tests/external/wpt/common/security-features/tools/generate.py b/third_party/blink/web_tests/external/wpt/common/security-features/tools/generate.py index 0cf7fab..fa36d8c 100644 --- a/third_party/blink/web_tests/external/wpt/common/security-features/tools/generate.py +++ b/third_party/blink/web_tests/external/wpt/common/security-features/tools/generate.py
@@ -110,6 +110,18 @@ else: raise Exception( 'Invalid delivery_type: %s' % delivery.delivery_type) + elif delivery.key == 'upgradeInsecureRequests': + # https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery + assert (delivery.value == 'upgrade') + if delivery.delivery_type == 'meta': + meta += '<meta http-equiv="Content-Security-Policy" ' + \ + 'content="upgrade-insecure-requests">' + elif delivery.delivery_type == 'http-rp': + headers[ + 'Content-Security-Policy'] = 'upgrade-insecure-requests' + else: + raise Exception( + 'Invalid delivery_type: %s' % delivery.delivery_type) else: raise Exception('Invalid delivery_key: %s' % delivery.key) return {"meta": meta, "headers": headers}
diff --git a/third_party/blink/web_tests/external/wpt/compression/decompression-bad-chunks.any.js b/third_party/blink/web_tests/external/wpt/compression/decompression-bad-chunks.any.js new file mode 100644 index 0000000..8f44ffd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compression/decompression-bad-chunks.any.js
@@ -0,0 +1,74 @@ +// META: global=worker + +'use strict'; + +const badChunks = [ + { + name: 'undefined', + value: undefined + }, + { + name: 'null', + value: null + }, + { + name: 'numeric', + value: 3.14 + }, + { + name: 'object, not BufferSource', + value: {} + }, + { + name: 'array', + value: [65] + }, + { + name: 'SharedArrayBuffer', + // Use a getter to postpone construction so that all tests don't fail where + // SharedArrayBuffer is not yet implemented. + get value() { + return new SharedArrayBuffer(); + } + }, + { + name: 'shared Uint8Array', + get value() { + new Uint8Array(new SharedArrayBuffer()) + } + }, + { + name: 'invalid deflate bytes', + get value() { + new Uint8Array([0, 156, 75, 173, 40, 72, 77, 46, 73, 77, 81, 200, 47, 45, 41, 40, 45, 1, 0, 48, 173, 6, 36]) + } + }, + { + name: 'invalid gzip bytes', + get value() { + new Uint8Array([0, 139, 8, 0, 0, 0, 0, 0, 0, 3, 75, 173, 40, 72, 77, 46, 73, 77, 81, 200, 47, 45, 41, 40, 45, 1, 0, 176, 1, 57, 179, 15, 0, 0, 0]) + } + }, +]; + +for (const chunk of badChunks) { + promise_test(async t => { + const ds = new DecompressionStream('gzip'); + const reader = ds.readable.getReader(); + const writer = ds.writable.getWriter(); + const writePromise = writer.write(chunk.value); + const readPromise = reader.read(); + await promise_rejects(t, new TypeError(), writePromise, 'write should reject'); + await promise_rejects(t, new TypeError(), readPromise, 'read should reject'); + }, `chunk of type ${chunk.name} should error the stream for gzip`); + + promise_test(async t => { + const ds = new DecompressionStream('deflate'); + const reader = ds.readable.getReader(); + const writer = ds.writable.getWriter(); + const writePromise = writer.write(chunk.value); + const readPromise = reader.read(); + await promise_rejects(t, new TypeError(), writePromise, 'write should reject'); + await promise_rejects(t, new TypeError(), readPromise, 'read should reject'); + }, `chunk of type ${chunk.name} should error the stream for deflate`); +}
diff --git a/third_party/blink/web_tests/external/wpt/compression/decompression-constructor-error.any.js b/third_party/blink/web_tests/external/wpt/compression/decompression-constructor-error.any.js new file mode 100644 index 0000000..9ffdb08c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compression/decompression-constructor-error.any.js
@@ -0,0 +1,15 @@ +// META: global=worker + +'use strict'; + +test(t => { + assert_throws(new TypeError(), () => new DecompressionStream('a'), 'constructor should throw'); +}, '"a" should cause the constructor to throw'); + +test(t => { + assert_throws(new TypeError(), () => new DecompressionStream(), 'constructor should throw'); +}, 'no input should cause the constructor to throw'); + +test(t => { + assert_throws(new Error(), () => new DecompressionStream({ toString() { throw Error(); } }), 'constructor should throw'); +}, 'non-string input should cause the constructor to throw');
diff --git a/third_party/blink/web_tests/external/wpt/compression/decompression-correct-input.any.js b/third_party/blink/web_tests/external/wpt/compression/decompression-correct-input.any.js new file mode 100644 index 0000000..11d8736 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/compression/decompression-correct-input.any.js
@@ -0,0 +1,26 @@ +// META: global=worker + +'use strict'; + +const deflateChunkValue = new Uint8Array([120, 156, 75, 173, 40, 72, 77, 46, 73, 77, 81, 200, 47, 45, 41, 40, 45, 1, 0, 48, 173, 6, 36]); +const gzipChunkValue = new Uint8Array([31, 139, 8, 0, 0, 0, 0, 0, 0, 3, 75, 173, 40, 72, 77, 46, 73, 77, 81, 200, 47, 45, 41, 40, 45, 1, 0, 176, 1, 57, 179, 15, 0, 0, 0]); +const trueChunkValue = new TextEncoder().encode('expected output'); + +promise_test(async t => { + const ds = new DecompressionStream('deflate'); + const reader = ds.readable.getReader(); + const writer = ds.writable.getWriter(); + const writePromise = writer.write(deflateChunkValue); + const { done, value } = await reader.read(); + assert_array_equals(Array.from(value), trueChunkValue, "value should match"); +}, 'decompressing deflated input should work'); + + +promise_test(async t => { + const ds = new DecompressionStream('gzip'); + const reader = ds.readable.getReader(); + const writer = ds.writable.getWriter(); + const writePromise = writer.write(gzipChunkValue); + const { done, value } = await reader.read(); + assert_array_equals(Array.from(value), trueChunkValue, "value should match"); +}, 'decompressing gzip input should work');
diff --git a/third_party/blink/web_tests/external/wpt/css/css-box/animation/margin-interpolation.html b/third_party/blink/web_tests/external/wpt/css/css-box/animation/margin-interpolation.html new file mode 100644 index 0000000..088836cb --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-box/animation/margin-interpolation.html
@@ -0,0 +1,118 @@ +<!DOCTYPE html> +<meta charset="UTF-8"> +<title>margin interpolation</title> +<link rel="help" href="https://www.w3.org/TR/CSS2/box.html#margin-properties"> +<meta name="assert" content="margin supports animation"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/interpolation-testcommon.js"></script> + +<style> +.parent { + margin: 10px; + border: solid; + display: inline-block; +} + +.target { + width: 40px; + height: 40px; + background-color: black; + display: inline-block; + margin: 30px; + opacity: 0.5; +} + +.expected { + background-color: green; +} +</style> + +<body> +<template id="target-template"> + <div> + <div class="target"></div> + </div> +</template> + +<script> +test_interpolation({ + property: 'margin', + from: neutralKeyframe, + to: '20px', +}, [ + {at: -0.3, expect: '33px'}, + {at: 0, expect: '30px'}, + {at: 0.3, expect: '27px'}, + {at: 0.6, expect: '24px'}, + {at: 1, expect: '20px'}, + {at: 1.5, expect: '15px'}, +]); + +test_interpolation({ + property: 'margin', + from: 'initial', + to: '20px', +}, [ + {at: -0.3, expect: '-6px'}, + {at: 0, expect: '0px'}, + {at: 0.3, expect: '6px'}, + {at: 0.6, expect: '12px'}, + {at: 1, expect: '20px'}, + {at: 1.5, expect: '30px'}, +]); + +test_interpolation({ + property: 'margin', + from: 'inherit', + to: '20px', +}, [ + {at: -0.3, expect: '7px'}, + {at: 0, expect: '10px'}, + {at: 0.3, expect: '13px'}, + {at: 0.6, expect: '16px'}, + {at: 1, expect: '20px'}, + {at: 1.5, expect: '25px'}, +]); + +test_interpolation({ + property: 'margin', + from: 'unset', + to: '20px', +}, [ + {at: -0.3, expect: '-6px'}, + {at: 0, expect: '0px'}, + {at: 0.3, expect: '6px'}, + {at: 0.6, expect: '12px'}, + {at: 1, expect: '20px'}, + {at: 1.5, expect: '30px'}, +]); + +test_interpolation({ + property: 'margin', + from: '0px', + to: '10px' +}, [ + {at: -0.3, expect: '-3px'}, + {at: 0, expect: '0px'}, + {at: 0.3, expect: '3px'}, + {at: 0.6, expect: '6px'}, + {at: 1, expect: '10px'}, + {at: 1.5, expect: '15px'} +]); + +test_interpolation({ + property: 'margin', + from: '20px 40px 60px 80px', + to: '30px 50px 70px 90px' +}, [ + {at: -0.3, expect: '17px 37px 57px 77px'}, + {at: 0, expect: '20px 40px 60px 80px'}, + {at: 0.3, expect: '23px 43px 63px 83px'}, + {at: 0.6, expect: '26px 46px 66px 86px'}, + {at: 1, expect: '30px 50px 70px 90px'}, + {at: 1.5, expect: '35px 55px 75px 95px'} +]); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-masking/animations/clip-path-interpolation.html b/third_party/blink/web_tests/external/wpt/css/css-masking/animations/clip-path-interpolation.html new file mode 100644 index 0000000..21c34f1f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-masking/animations/clip-path-interpolation.html
@@ -0,0 +1,141 @@ +<!DOCTYPE html> +<meta charset="UTF-8"> +<title>clip-path interpolation</title> +<link rel="help" href="https://drafts.fxtf.org/css-masking-1/#the-clip-path"> +<meta name="assert" content="clip-path supports animation"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/interpolation-testcommon.js"></script> + +<style> +.parent { + clip-path: circle(80% at 30% 10%); +} + +.target { + clip-path: circle(60% at 10% 30%); +} +</style> +<body> +<script> +test_interpolation({ + property: 'clip-path', + from: neutralKeyframe, + to: 'circle(40% at 20% 20%)', +}, [ + {at: -0.3, expect: 'circle(66% at 7% 33%)'}, + {at: 0, expect: 'circle(60% at 10% 30%)'}, + {at: 0.3, expect: 'circle(54% at 13% 27%)'}, + {at: 0.6, expect: 'circle(48% at 16% 24%)'}, + {at: 1, expect: 'circle(40% at 20% 20%)'}, + {at: 1.5, expect: 'circle(30% at 25% 15%)'}, +]); + +test_no_interpolation({ + property: 'clip-path', + from: 'initial', + to: 'circle(40% at 20% 20%)', +}); + +test_interpolation({ + property: 'clip-path', + from: 'inherit', + to: 'circle(40% at 20% 20%)', +}, [ + {at: -0.3, expect: 'circle(92% at 33% 7%)'}, + {at: 0, expect: 'circle(80% at 30% 10%)'}, + {at: 0.3, expect: 'circle(68% at 27% 13%)'}, + {at: 0.6, expect: 'circle(56% at 24% 16%)'}, + {at: 1, expect: 'circle(40% at 20% 20%)'}, + {at: 1.5, expect: 'circle(20% at 15% 25%)'}, +]); + +test_no_interpolation({ + property: 'clip-path', + from: 'unset', + to: 'circle(40% at 20% 20%)', +}); + +test_interpolation({ + property: 'clip-path', + from: 'circle(100% at 0% 0%)', + to: 'circle(50% at 25% 25%)', +}, [ + {at: -0.3, expect: 'circle(115% at -7.5% -7.5%)'}, + {at: 0, expect: 'circle(100% at 0% 0%)'}, + {at: 0.3, expect: 'circle(85% at 7.5% 7.5%)'}, + {at: 0.6, expect: 'circle(70% at 15% 15%)'}, + {at: 1, expect: 'circle(50% at 25% 25%)'}, + {at: 1.5, expect: 'circle(25% at 37.5% 37.5%)'} +]); + +test_interpolation({ + property: 'clip-path', + from: 'ellipse(100% 100% at 0% 0%)', + to: 'ellipse(50% 50% at 25% 25%)', +}, [ + {at: -0.3, expect: 'ellipse(115% 115% at -7.5% -7.5%)'}, + {at: 0, expect: 'ellipse(100% 100% at 0% 0%)'}, + {at: 0.3, expect: 'ellipse(85% 85% at 7.5% 7.5%)'}, + {at: 0.6, expect: 'ellipse(70% 70% at 15% 15%)'}, + {at: 1, expect: 'ellipse(50% 50% at 25% 25%)'}, + {at: 1.5, expect: 'ellipse(25% 25% at 37.5% 37.5%)'} +]); + +test_interpolation({ + property: 'clip-path', + from: 'polygon(nonzero, 0px 0px, 25px 25px, 50px 50px)', + to: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)', +}, [ + {at: -0.3, expect: 'polygon(nonzero, -7.5px -7.5px, 17.5px 17.5px, 42.5px 42.5px)'}, + {at: 0, expect: 'polygon(nonzero, 0px 0px, 25px 25px, 50px 50px)'}, + {at: 0.3, expect: 'polygon(nonzero, 7.5px 7.5px, 32.5px 32.5px, 57.5px 57.5px)'}, + {at: 0.6, expect: 'polygon(nonzero, 15px 15px, 40px 40px, 65px 65px)'}, + {at: 1, expect: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)'}, + {at: 1.5, expect: 'polygon(nonzero, 37.5px 37.5px, 62.5px 62.5px, 87.5px 87.5px)'} +]); + +test_no_interpolation({ + property: 'clip-path', + from: 'polygon(evenodd, 0px 0px, 25px 25px, 50px 50px)', + to: 'polygon(nonzero, 25px 25px, 50px 50px, 75px 75px)', +}); + +test_interpolation({ + property: 'clip-path', + from: 'inset(100%)', + to: 'inset(120%)', +}, [ + {at: -0.3, expect: 'inset(94%)'}, + {at: 0, expect: 'inset(100%)'}, + {at: 0.3, expect: 'inset(106%)'}, + {at: 0.6, expect: 'inset(112%)'}, + {at: 1, expect: 'inset(120%)'}, + {at: 1.5, expect: 'inset(130%)'}, +]); + +test_no_interpolation({ + property: 'clip-path', + from: 'none', + to: 'ellipse(100% 100% at 0% 0%)', +}); + +test_interpolation({ + property: 'clip-path', + from: 'circle(25% at right 5% bottom 15px)', + to: 'circle(45% at right 25% bottom 35px)', +}, [ + {at: 0.25, expect: 'circle(30% at 90% calc(-20px + 100%))'}, + {at: 0.5, expect: 'circle(35% at 85% calc(-25px + 100%))'}, + {at: 0.75, expect: 'circle(40% at 80% calc(-30px + 100%))'}, +]); + +test_no_interpolation({ + property: 'clip-path', + from: 'url("/clip-source")', + to: 'ellipse(100% 100% at 0% 0%)', +}); + +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-tables/animations/border-spacing-interpolation.html b/third_party/blink/web_tests/external/wpt/css/css-tables/animations/border-spacing-interpolation.html new file mode 100644 index 0000000..02e1cc6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-tables/animations/border-spacing-interpolation.html
@@ -0,0 +1,116 @@ +<!DOCTYPE html> +<meta charset="UTF-8"> +<title>boder-spacing interpolation</title> +<link rel="help" href="https://www.w3.org/TR/CSS2/tables.html#separated-borders"> +<meta name="assert" content="border-spacing supports animation"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/css/support/interpolation-testcommon.js"></script> + +<style> +.parent { + border-spacing: 30px; +} + +.target { + width: 50px; + height: 50px; + background-color: black; + display: inline-block; + margin: 18px; + border-collapse: separate; + border-spacing: 10px; +} + +.target td { + background-color: white; + border: 1px solid orange; + width: 10px; + height: 10px; +} + +.expected { + background-color: green; +} +</style> + +<body> +<template id="target-template"> + <table> + <tbody> + <tr> + <td></td> + <td></td> + </tr> + </tbody> + </table> +</template> + +<script> +test_interpolation({ + property: 'border-spacing', + from: neutralKeyframe, + to: '20px', +}, [ + {at: -0.3, expect: '7px 7px'}, + {at: 0, expect: '10px 10px'}, + {at: 0.3, expect: '13px 13px'}, + {at: 0.6, expect: '16px 16px'}, + {at: 1, expect: '20px 20px'}, + {at: 1.5, expect: '25px 25px'}, +]); + +test_interpolation({ + property: 'border-spacing', + from: 'initial', + to: '20px', +}, [ + {at: -0.3, expect: '0px 0px'}, + {at: 0, expect: '0px 0px'}, + {at: 0.3, expect: '6px 6px'}, + {at: 0.6, expect: '12px 12px'}, + {at: 1, expect: '20px 20px'}, + {at: 1.5, expect: '30px 30px'}, +]); + +test_interpolation({ + property: 'border-spacing', + from: 'inherit', + to: '20px', +}, [ + {at: -0.3, expect: '33px 33px'}, + {at: 0, expect: '30px 30px'}, + {at: 0.3, expect: '27px 27px'}, + {at: 0.6, expect: '24px 24px'}, + {at: 1, expect: '20px 20px'}, + {at: 1.5, expect: '15px 15px'}, +]); + +test_interpolation({ + property: 'border-spacing', + from: 'unset', + to: '20px', +}, [ + {at: -0.3, expect: '33px 33px'}, + {at: 0, expect: '30px 30px'}, + {at: 0.3, expect: '27px 27px'}, + {at: 0.6, expect: '24px 24px'}, + {at: 1, expect: '20px 20px'}, + {at: 1.5, expect: '15px 15px'}, +]); + +test_interpolation({ + property: 'border-spacing', + from: '0px', + to: '10px' +}, [ + {at: -0.3, expect: '0px 0px'}, // Can't be negative. + {at: 0, expect: '0px 0px'}, + {at: 0.3, expect: '3px 3px'}, + {at: 0.6, expect: '6px 6px'}, + {at: 1, expect: '10px 10px'}, + {at: 1.5, expect: '15px 15px'} +]); +</script> +</body>
diff --git a/third_party/blink/web_tests/external/wpt/fetch/api/resources/preflight.py b/third_party/blink/web_tests/external/wpt/fetch/api/resources/preflight.py index d224960..a2552c2 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/api/resources/preflight.py +++ b/third_party/blink/web_tests/external/wpt/fetch/api/resources/preflight.py
@@ -26,7 +26,6 @@ response.set_error(400, "No Access-Control-Request-Method header") return "ERROR: No access-control-request-method in preflight!" - # https://github.com/whatwg/fetch/issues/922 if request.headers.get("Accept", "") != "*/*": response.set_error(400, "Request does not have 'Accept: */*' header") return "ERROR: Invalid access in preflight!"
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/css-animation-worklet.idl b/third_party/blink/web_tests/external/wpt/interfaces/css-animation-worklet.idl index 4aca84e..2c46cc7c 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/css-animation-worklet.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/css-animation-worklet.idl
@@ -22,12 +22,12 @@ attribute double? localTime; }; -[Exposed=Window, - Constructor (DOMString animatorName, +[Exposed=Window] +interface WorkletAnimation : Animation { + constructor(DOMString animatorName, optional (AnimationEffect or sequence<AnimationEffect>)? effects = null, optional AnimationTimeline? timeline, - optional any options)] -interface WorkletAnimation : Animation { + optional any options); readonly attribute DOMString animatorName; };
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/gyroscope.idl b/third_party/blink/web_tests/external/wpt/interfaces/gyroscope.idl index 24cd82c6..3754fd81 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/gyroscope.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/gyroscope.idl
@@ -3,8 +3,9 @@ // (https://github.com/tidoust/reffy-reports) // Source: Gyroscope (https://w3c.github.io/gyroscope/) -[Constructor(optional GyroscopeSensorOptions sensorOptions), SecureContext, Exposed=Window] +[SecureContext, Exposed=Window] interface Gyroscope : Sensor { + constructor(optional GyroscopeSensorOptions sensorOptions = {}); readonly attribute double? x; readonly attribute double? y; readonly attribute double? z;
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resource_hash.htm b/third_party/blink/web_tests/external/wpt/resource-timing/resource_hash.htm new file mode 100644 index 0000000..a44c1c90 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/resource-timing/resource_hash.htm
@@ -0,0 +1,44 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="utf-8" /> +<title>Resource Timing: image with a hash</title> +<link rel="help" href="http://www.w3.org/TR/resource-timing/#dom-performanceresourcetiming-initiatortype"/> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/webperftestharness.js"></script> +<script src="resources/webperftestharnessextension.js"></script> +<script> +setup({explicit_done: true}); + +// explicitly test the namespace before we start testing +test_namespace("getEntriesByType"); + +function onload_test() { + if (window.performance.getEntriesByType === undefined) { + done(); + return; + } + + const url = "resources/fake_responses.py?tag=" + Math.random() + '#hash=1'; + const image = new Image(); + image.onload = image.onerror = () => { + const entries = window.performance.getEntriesByType('resource').filter(r => r.initiatorType === 'img'); + test_equals(entries.length, 1, "There should be one entry"); + if (entries.length === 1) { + test_true(entries[0].name.indexOf('#hash=1') > -1, "There should be a hash in the resource name"); + } + done(); + + } + image.src = url; +} +window.onload = onload_test; +</script> +</head> +<body> +<h1>Description</h1> +<p>This test validates that a hash in an image URL is preserved in resource timing API results.</p> +<div id="log"></div> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/trusted-types/trusted-types-reporting.tentative.https.html b/third_party/blink/web_tests/external/wpt/trusted-types/trusted-types-reporting.tentative.https.html index 11ef305..0104ba3 100644 --- a/third_party/blink/web_tests/external/wpt/trusted-types/trusted-types-reporting.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/trusted-types/trusted-types-reporting.tentative.https.html
@@ -68,7 +68,7 @@ function expect_blocked_uri(s) { return e => { assert_true(e.blockedURI === s, - `expected "${e.blockedUri}" to be "${s}".`); + `expected "${e.blockedURI}" to be "${s}".`); return e; } } @@ -154,6 +154,7 @@ promise_test(t => { let p = Promise.resolve() .then(promise_violation("trusted-types two")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("Element.innerHTML")) .then(expect_sample("abc")); expect_throws(_ => { document.getElementById("div").innerHTML = "abc" }); @@ -163,6 +164,7 @@ promise_test(t => { let p = Promise.resolve() .then(promise_violation("trusted-types two")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("HTMLAnchorElement.href")); expect_throws(_ => { document.getElementById("anchor").href = "" }); return p; @@ -171,6 +173,7 @@ promise_test(t => { let p = Promise.resolve() .then(promise_violation("trusted-types two")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("HTMLElement.innerText")) .then(expect_sample("2+2;")); expect_throws(_ => document.getElementById("script").innerText = "2+2;"); @@ -180,6 +183,7 @@ promise_test(t => { let p = Promise.resolve() .then(promise_violation("trusted-types one")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("eval")) .then(expect_sample("2+2")) .then(promise_flush()); @@ -193,6 +197,7 @@ // start of the value, but it should not be excessively long. let p = Promise.resolve() .then(promise_violation("trusted-types two")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("HTMLElement.innerText")) .then(expect_sample("abbb")) .then(e => assert_less_than(e.sample.length, 150)); @@ -211,6 +216,7 @@ promise_test(t => { let p = Promise.resolve() .then(promise_violation("trusted-types one")) + .then(expect_blocked_uri("trusted-types-sink")) .then(expect_sample("HTMLAnchorElement.href")) .then(expect_sample("abc")); expect_throws(_ => document.getElementById("customlink").href = "abc");
diff --git a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/test-case.sub.js b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/test-case.sub.js new file mode 100644 index 0000000..cde228d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/test-case.sub.js
@@ -0,0 +1,37 @@ +// TODO(hiroshige): Document the type of `scenario`. +function TestCase(scenario, description) { + const urls = getRequestURLs(scenario.subresource, + scenario.origin, + scenario.redirection); + const checkResult = _ => { + // Send request to check if the key has been torn down. + return xhrRequest(urls.assertUrl) + .then(assertResult => { + // Now check if the value has been torn down. If it's still there, + // we have blocked the request to mixed-content. + assert_equals(assertResult.status, scenario.expectation, + "The resource request should be '" + scenario.expectation + "'."); + }); + }; + + function runTest() { + /** @type {Subresource} */ + const subresource = { + subresourceType: scenario.subresource, + url: urls.testUrl, + policyDeliveries: scenario.subresource_policy_deliveries, + }; + + promise_test(() => { + return xhrRequest(urls.announceUrl) + // Send out the real resource request. + // This should tear down the key if it's not blocked. + .then(_ => invokeRequest(subresource, scenario.source_context_list)) + // We check the key state, regardless of whether the main request + // succeeded or failed. + .then(checkResult, checkResult); + }, description); + } // runTest + + return {start: runTest}; +}
diff --git a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/tools/generate.py b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/tools/generate.py new file mode 100755 index 0000000..cde2989 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/generic/tools/generate.py
@@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import os +import sys + +sys.path.insert( + 0, + os.path.join( + os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', 'common', + 'security-features', 'tools')) +import generate + + +class UpgradeInsecureRequestsConfig(object): + def __init__(self): + self.selection_pattern = \ + '%(source_context_list)s.%(delivery_type)s/' + \ + '%(delivery_value)s/' + \ + '%(subresource)s/' + \ + '%(origin)s.%(redirection)s.%(source_scheme)s' + + self.test_file_path_pattern = 'gen/' + self.selection_pattern + '.html' + + self.test_description_template = 'Upgrade-Insecure-Requests: Expects %(expectation)s for %(subresource)s to %(origin)s origin and %(redirection)s redirection from %(source_scheme)s context.' + + self.test_page_title_template = 'Upgrade-Insecure-Requests: %s' + + self.helper_js = '/upgrade-insecure-requests/generic/test-case.sub.js' + + # For debug target only. + self.sanity_checker_js = '/upgrade-insecure-requests/generic/sanity-checker.js' + self.spec_json_js = '/upgrade-insecure-requests/spec_json.js' + + self.test_case_name = 'TestCase' + + script_directory = os.path.dirname(os.path.abspath(__file__)) + self.spec_directory = os.path.abspath( + os.path.join(script_directory, '..', '..')) + + +if __name__ == '__main__': + generate.main(UpgradeInsecureRequestsConfig())
diff --git a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec.src.json b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec.src.json new file mode 100644 index 0000000..6aee9a2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec.src.json
@@ -0,0 +1,376 @@ +{ + "specification": [ + { + "name": "No upgrade-insecure-request", + "title": "No upgrade-insecure-request", + "description": "No upgrade-insecure-request", + "specification_url": "https://w3c.github.io/webappsec-upgrade-insecure-requests/", + "test_expansion": [ + { + "name": "Without upgrade-insecure-request, all requests are blocked ...", + "expansion": "default", + "source_scheme": "https", + "source_context_list": "*", + "delivery_type": "meta", + "delivery_value": null, + "redirection": "*", + "subresource": "*", + "origin": "*", + "expectation": "blocked" + }, + { + "name": "... except for the secure requests listed here", + "expansion": "override", + "source_scheme": "https", + "source_context_list": "*", + "delivery_type": "meta", + "delivery_value": null, + "redirection": "no-redirect", + "subresource": "*", + "origin": [ + "same-https", + "cross-https", + "same-wss", + "cross-wss" + ], + "expectation": "allowed" + } + ] + }, + { + "name": "With upgrade-insecure-request", + "title": "With upgrade-insecure-request", + "description": "With upgrade-insecure-request", + "specification_url": "https://w3c.github.io/webappsec-upgrade-insecure-requests/", + "test_expansion": [ + { + "name": "With upgrade-insecure-request, all insecure requests are upgraded and allowed.", + "expansion": "default", + "source_scheme": "https", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "upgrade", + "redirection": "*", + "subresource": "*", + "origin": "*", + "expectation": "allowed" + } + ] + } + ], + "delivery_key": "upgradeInsecureRequests", + "excluded_tests": [ + { + "name": "Omit secure requests", + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "no-redirect", + "subresource": "*", + "origin": [ + "same-https", + "cross-https", + "same-wss", + "cross-wss" + ], + "expectation": "allowed" + }, + { + "name": "For inheriting tests skip http-rp because we already have <meta> tests", + "expansion": "*", + "source_scheme": "*", + "source_context_list": [ + "srcdoc-inherit", + "iframe-blank-inherit", + "worker-classic-data" + ], + "delivery_type": "http-rp", + "delivery_value": "*", + "redirection": "*", + "subresource": "*", + "origin": "*", + "expectation": "*" + }, + { + "name": "Workers are same-origin only", + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": [ + "worker-classic", + "worker-module", + "sharedworker-classic" + ], + "origin": [ + "cross-https", + "cross-http-downgrade", + "cross-wss", + "cross-ws-downgrade" + ], + "expectation": "*" + }, + { + "name": "Websockets are ws/wss-only", + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": "websocket", + "origin": [ + "same-https", + "same-http-downgrade", + "cross-https", + "cross-http-downgrade" + ], + "expectation": "*" + }, + { + "name": "Websockets is no-redirect only", + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": [ + "downgrade" + ], + "subresource": "websocket", + "origin": "*", + "expectation": "*" + }, + { + "name": "ws/wss are websocket-only", + "expansion": "*", + "source_scheme": "*", + "source_context_list": "*", + "delivery_type": "*", + "delivery_value": "*", + "redirection": "*", + "subresource": [ + "iframe-tag", + "img-tag", + "xhr", + "fetch", + "worker-classic", + "worker-module", + "worker-import-data", + "sharedworker-classic", + "worklet-animation", + "worklet-audio", + "worklet-layout", + "worklet-paint", + "worklet-animation-import-data", + "worklet-audio-import-data", + "worklet-layout-import-data", + "worklet-paint-import-data" + ], + "origin": [ + "same-wss", + "same-ws-downgrade", + "cross-wss", + "cross-ws-downgrade" + ], + "expectation": "*" + } + ], + "source_context_schema": { + "supported_delivery_type": { + "top": [ + "http-rp", + "meta" + ], + "iframe": [ + "http-rp", + "meta" + ], + "iframe-blank": [ + "meta" + ], + "srcdoc": [ + "meta" + ], + "worker-classic": [ + "http-rp" + ], + "worker-module": [ + "http-rp" + ], + "worker-classic-data": [], + "worker-module-data": [] + }, + "supported_subresource": { + "top": "*", + "iframe": "*", + "iframe-blank": "*", + "srcdoc": "*", + "worker-classic": [ + "xhr", + "fetch", + "websocket" + ], + "worker-module": [ + "xhr", + "fetch", + "websocket" + ], + "worker-classic-data": [ + "xhr", + "fetch", + "websocket" + ], + "worker-module-data": [ + "xhr", + "fetch", + "websocket" + ] + } + }, + "subresource_schema": { + "supported_delivery_type": { + "xhr": [], + "worker-classic": [], + "worker-module": [], + "worker-import-data": [], + "sharedworker-classic": [], + "worklet-animation": [], + "worklet-audio": [], + "worklet-layout": [], + "worklet-paint": [], + "worklet-animation-import-data": [], + "worklet-audio-import-data": [], + "worklet-layout-import-data": [], + "worklet-paint-import-data": [], + "fetch": [], + "websocket": [], + "img-tag": [], + "iframe-tag": [] + } + }, + "source_context_list_schema": { + "top": { + "description": "CSP set by the top-level Document", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + } + ], + "subresourcePolicyDeliveries": [] + }, + "srcdoc-inherit": { + "description": "srcdoc iframe should inherit parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "srcdoc" + } + ], + "subresourcePolicyDeliveries": [] + }, + "iframe-blank-inherit": { + "description": "blank iframe should inherit parent Document's policy", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "iframe-blank" + } + ], + "subresourcePolicyDeliveries": [] + }, + "worker-classic-data": { + "description": "CSP set by the top-level Document is inherited to dedicated workers", + "sourceContextList": [ + { + "sourceContextType": "top", + "policyDeliveries": [ + "policy" + ] + }, + { + "sourceContextType": "worker-classic-data", + "policyDeliveries": [] + } + ], + "subresourcePolicyDeliveries": [] + } + }, + "test_expansion_schema": { + "expansion": [ + "default", + "override" + ], + "source_scheme": [ + "https" + ], + "delivery_type": [ + "http-rp", + "meta" + ], + "delivery_value": [ + null, + "upgrade" + ], + "source_context_list": [ + "top", + "srcdoc-inherit", + "iframe-blank-inherit", + "worker-classic-data" + ], + "redirection": [ + "no-redirect", + "downgrade" + ], + "origin": [ + "same-https", + "same-http-downgrade", + "cross-https", + "cross-http-downgrade", + "same-wss", + "same-ws-downgrade", + "cross-wss", + "cross-ws-downgrade" + ], + "subresource": [ + "iframe-tag", + "img-tag", + "xhr", + "fetch", + "websocket", + "worker-classic", + "worker-module", + "worker-import-data", + "sharedworker-classic", + "worklet-animation", + "worklet-audio", + "worklet-layout", + "worklet-paint", + "worklet-animation-import-data", + "worklet-audio-import-data", + "worklet-layout-import-data", + "worklet-paint-import-data" + ], + "expectation": [ + "allowed", + "blocked" + ] + } +}
diff --git a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec_json.js b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec_json.js new file mode 100644 index 0000000..9122ce3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/spec_json.js
@@ -0,0 +1 @@ +var SPEC_JSON = {"subresource_schema": {"supported_delivery_type": {"worklet-layout": [], "worklet-paint": [], "worker-module": [], "sharedworker-classic": [], "worklet-paint-import-data": [], "worklet-animation-import-data": [], "fetch": [], "xhr": [], "worker-classic": [], "worklet-layout-import-data": [], "worklet-audio-import-data": [], "worklet-animation": [], "worker-import-data": [], "websocket": [], "worklet-audio": [], "iframe-tag": [], "img-tag": []}}, "excluded_tests": [{"delivery_value": "*", "origin": ["same-https", "cross-https", "same-wss", "cross-wss"], "delivery_type": "*", "name": "Omit secure requests", "expectation": "allowed", "expansion": "*", "redirection": "no-redirect", "source_context_list": "*", "source_scheme": "*", "subresource": "*"}, {"delivery_value": "*", "origin": "*", "delivery_type": "http-rp", "name": "For inheriting tests skip http-rp because we already have <meta> tests", "expectation": "*", "expansion": "*", "redirection": "*", "source_context_list": ["srcdoc-inherit", "iframe-blank-inherit", "worker-classic-data"], "source_scheme": "*", "subresource": "*"}, {"delivery_value": "*", "origin": ["cross-https", "cross-http-downgrade", "cross-wss", "cross-ws-downgrade"], "delivery_type": "*", "name": "Workers are same-origin only", "expectation": "*", "expansion": "*", "redirection": "*", "source_context_list": "*", "source_scheme": "*", "subresource": ["worker-classic", "worker-module", "sharedworker-classic"]}, {"delivery_value": "*", "origin": ["same-https", "same-http-downgrade", "cross-https", "cross-http-downgrade"], "delivery_type": "*", "name": "Websockets are ws/wss-only", "expectation": "*", "expansion": "*", "redirection": "*", "source_context_list": "*", "source_scheme": "*", "subresource": "websocket"}, {"delivery_value": "*", "origin": "*", "delivery_type": "*", "name": "Websockets is no-redirect only", "expectation": "*", "expansion": "*", "redirection": ["downgrade"], "source_context_list": "*", "source_scheme": "*", "subresource": "websocket"}, {"delivery_value": "*", "origin": ["same-wss", "same-ws-downgrade", "cross-wss", "cross-ws-downgrade"], "delivery_type": "*", "name": "ws/wss are websocket-only", "expectation": "*", "expansion": "*", "redirection": "*", "source_context_list": "*", "source_scheme": "*", "subresource": ["iframe-tag", "img-tag", "xhr", "fetch", "worker-classic", "worker-module", "worker-import-data", "sharedworker-classic", "worklet-animation", "worklet-audio", "worklet-layout", "worklet-paint", "worklet-animation-import-data", "worklet-audio-import-data", "worklet-layout-import-data", "worklet-paint-import-data"]}], "specification": [{"test_expansion": [{"delivery_value": null, "origin": "*", "delivery_type": "meta", "name": "Without upgrade-insecure-request, all requests are blocked ...", "expectation": "blocked", "expansion": "default", "redirection": "*", "source_context_list": "*", "source_scheme": "https", "subresource": "*"}, {"delivery_value": null, "origin": ["same-https", "cross-https", "same-wss", "cross-wss"], "delivery_type": "meta", "name": "... except for the secure requests listed here", "expectation": "allowed", "expansion": "override", "redirection": "no-redirect", "source_context_list": "*", "source_scheme": "https", "subresource": "*"}], "description": "No upgrade-insecure-request", "specification_url": "https://w3c.github.io/webappsec-upgrade-insecure-requests/", "name": "No upgrade-insecure-request", "title": "No upgrade-insecure-request"}, {"test_expansion": [{"delivery_value": "upgrade", "origin": "*", "delivery_type": "*", "name": "With upgrade-insecure-request, all insecure requests are upgraded and allowed.", "expectation": "allowed", "expansion": "default", "redirection": "*", "source_context_list": "*", "source_scheme": "https", "subresource": "*"}], "description": "With upgrade-insecure-request", "specification_url": "https://w3c.github.io/webappsec-upgrade-insecure-requests/", "name": "With upgrade-insecure-request", "title": "With upgrade-insecure-request"}], "test_expansion_schema": {"delivery_value": [null, "upgrade"], "origin": ["same-https", "same-http-downgrade", "cross-https", "cross-http-downgrade", "same-wss", "same-ws-downgrade", "cross-wss", "cross-ws-downgrade"], "delivery_type": ["http-rp", "meta"], "subresource": ["iframe-tag", "img-tag", "xhr", "fetch", "websocket", "worker-classic", "worker-module", "worker-import-data", "sharedworker-classic", "worklet-animation", "worklet-audio", "worklet-layout", "worklet-paint", "worklet-animation-import-data", "worklet-audio-import-data", "worklet-layout-import-data", "worklet-paint-import-data"], "expectation": ["allowed", "blocked"], "expansion": ["default", "override"], "redirection": ["no-redirect", "downgrade"], "source_context_list": ["top", "srcdoc-inherit", "iframe-blank-inherit", "worker-classic-data"], "source_scheme": ["https"]}, "source_context_list_schema": {"worker-classic-data": {"subresourcePolicyDeliveries": [], "description": "CSP set by the top-level Document is inherited to dedicated workers", "sourceContextList": [{"sourceContextType": "top", "policyDeliveries": ["policy"]}, {"sourceContextType": "worker-classic-data", "policyDeliveries": []}]}, "top": {"subresourcePolicyDeliveries": [], "description": "CSP set by the top-level Document", "sourceContextList": [{"sourceContextType": "top", "policyDeliveries": ["policy"]}]}, "srcdoc-inherit": {"subresourcePolicyDeliveries": [], "description": "srcdoc iframe should inherit parent Document's policy", "sourceContextList": [{"sourceContextType": "top", "policyDeliveries": ["policy"]}, {"sourceContextType": "srcdoc"}]}, "iframe-blank-inherit": {"subresourcePolicyDeliveries": [], "description": "blank iframe should inherit parent Document's policy", "sourceContextList": [{"sourceContextType": "top", "policyDeliveries": ["policy"]}, {"sourceContextType": "iframe-blank"}]}}, "delivery_key": "upgradeInsecureRequests", "source_context_schema": {"supported_delivery_type": {"iframe": ["http-rp", "meta"], "worker-module-data": [], "worker-classic-data": [], "top": ["http-rp", "meta"], "worker-classic": ["http-rp"], "iframe-blank": ["meta"], "worker-module": ["http-rp"], "srcdoc": ["meta"]}, "supported_subresource": {"iframe": "*", "worker-module-data": ["xhr", "fetch", "websocket"], "worker-classic-data": ["xhr", "fetch", "websocket"], "top": "*", "worker-classic": ["xhr", "fetch", "websocket"], "iframe-blank": "*", "worker-module": ["xhr", "fetch", "websocket"], "srcdoc": "*"}}};
diff --git a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/support/generate.py b/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/support/generate.py deleted file mode 100644 index e3f5aaf..0000000 --- a/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/support/generate.py +++ /dev/null
@@ -1,64 +0,0 @@ -# Usage: execute -# $ python support/generate.py -# at wpt/upgrade-insecure-requests/. -# -# Note: Some tests (link-upgrade.sub.https.html and -# websocket-upgrade.https.html) are not covered by this generator script. - -template = '''<!DOCTYPE html> -<html> -<head> -<!-- Generated by wpt/upgrade-insecure-requests/support/generate.py -->%(additionalMeta)s -<title>Upgrade Insecure Requests: %(name)s.</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="./support/testharness-helper.sub.js"></script> -<script src="/common/security-features/resources/common.sub.js"></script> - -<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> -</head> -<body> -<script> -const tests = %(generatorName)s(ResourceType.%(resourceType)s, %(sameOriginOnly)s); -tests.forEach(test => testMap['%(name)s'](test)); -</script> -</body> -</html> -''' - -def getLong(file): - testsThatNeedMoreTime = [ "worker-subresource-fetch-redirect-upgrade.https.html" ] - if any(file in item for item in testsThatNeedMoreTime ): - return '\n<meta name="timeout" content="long">' - return "" - -# resourceType is |ResourceType| in testharness-helper.sub.js. -for name, resourceType in [ - ('image', 'IMAGE'), ('iframe', 'FRAME'), - ('animation-worklet', 'WORKLET'), ('audio-worklet', 'WORKLET'), - ('layout-worklet', 'WORKLET'), ('paint-worklet', 'WORKLET'), - ('worker', 'WORKER'), - ('module-worker', 'WORKER'), - ('worker-subresource-xhr', 'FETCH'), - ('worker-subresource-fetch', 'FETCH'), - ('shared-worker', 'SHARED_WORKER')]: - # TODO(https://crbug.com/989399): Add tests for subresource requests on shared - # workers, and main/subresource requests on service workers. - - sameOriginOnly = 'false' - if resourceType == 'WORKER' or resourceType == 'SHARED_WORKER': - sameOriginOnly = 'true' - - types = [('', 'generateTests'), ('-redirect', 'generateRedirectTests')] - if name == 'module-worker' or resourceType == 'WORKLET': - types.append(('-import', 'generateModuleImportTests')) - - for typeName, generatorName in types: - filename = '%s%s-upgrade.https.html' % (name, typeName) - with open(filename, 'w') as html_file: - html_file.write(template % { - 'name': name, - 'additionalMeta': getLong(filename), - 'resourceType': resourceType, - 'generatorName': generatorName, - 'sameOriginOnly': sameOriginOnly})
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-expected.txt index 21f5bd8..f556eb3 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/accumulation-per-property-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 563 tests; 531 PASS, 32 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 563 tests; 532 PASS, 31 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS align-content (type: discrete) has testAccumulation function PASS align-content: "flex-end" onto "flex-start" @@ -201,7 +201,7 @@ PASS fill-rule: "nonzero" onto "evenodd" PASS fill-rule: "evenodd" onto "nonzero" PASS filter (type: filterList) has testAccumulation function -FAIL filter: same ordered filter functions assert_equals: The value should be blur(30px) brightness(0) at 0ms expected "blur(30px) brightness(0)" but got "blur(30px) brightness(0.4)" +PASS filter: same ordered filter functions PASS filter: mismatched ordered filter functions PASS flex-basis (type: lengthPercentageOrCalc) has testAccumulation function PASS flex-basis: length
diff --git a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt index d8f90033..b435ecc 100644 --- a/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt +++ b/third_party/blink/web_tests/external/wpt/web-animations/animation-model/animation-types/addition-per-property-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 559 tests; 538 PASS, 21 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 559 tests; 540 PASS, 19 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Setup PASS align-content (type: discrete) has testAddition function PASS align-content: "flex-end" onto "flex-start" @@ -201,8 +201,8 @@ PASS fill-rule: "nonzero" onto "evenodd" PASS fill-rule: "evenodd" onto "nonzero" PASS filter (type: filterList) has testAddition function -FAIL filter: blur on blur assert_equals: The value should be blur(10px) blur(20px) at 0ms expected "blur(10px) blur(20px)" but got "blur(30px)" -FAIL filter: different filter functions assert_equals: The value should be blur(10px) brightness(0.8) at 0ms expected "blur(10px) brightness(0.8)" but got "brightness(0.8)" +PASS filter: blur on blur +PASS filter: different filter functions PASS flex-basis (type: lengthPercentageOrCalc) has testAddition function PASS flex-basis: length PASS flex-basis: length of rem
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/take_element_screenshot/user_prompts.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/take_element_screenshot/user_prompts.py index 221eaa9..5d1b497f 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/take_element_screenshot/user_prompts.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/take_element_screenshot/user_prompts.py
@@ -2,7 +2,7 @@ import pytest -from tests.support.asserts import assert_png, assert_success +from tests.support.asserts import assert_dialog_handled, assert_error, assert_png, assert_success from tests.support.inline import inline @@ -17,8 +17,8 @@ @pytest.fixture -def check_user_prompt_not_closed_without_exception(session, create_dialog): - def check_user_prompt_not_closed_without_exception(dialog_type): +def check_user_prompt_closed_without_exception(session, create_dialog): + def check_user_prompt_closed_without_exception(dialog_type, retval): session.url = inline("<input/>") element = session.find.css("input", all=False) @@ -27,44 +27,96 @@ response = take_element_screenshot(session, element.id) value = assert_success(response) + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + assert_png(value) + return check_user_prompt_closed_without_exception + + +@pytest.fixture +def check_user_prompt_closed_with_exception(session, create_dialog): + def check_user_prompt_closed_with_exception(dialog_type, retval): + session.url = inline("<input/>") + element = session.find.css("input", all=False) + + create_dialog(dialog_type, text=dialog_type) + + response = take_element_screenshot(session, element.id) + assert_error(response, "unexpected alert open") + + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + + return check_user_prompt_closed_with_exception + + +@pytest.fixture +def check_user_prompt_not_closed_but_exception(session, create_dialog): + def check_user_prompt_not_closed_but_exception(dialog_type): + session.url = inline("<input/>") + element = session.find.css("input", all=False) + + create_dialog(dialog_type, text=dialog_type) + + response = take_element_screenshot(session, element.id) + assert_error(response, "unexpected alert open") + assert session.alert.text == dialog_type session.alert.dismiss() - return check_user_prompt_not_closed_without_exception + return check_user_prompt_not_closed_but_exception @pytest.mark.capabilities({"unhandledPromptBehavior": "accept"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_accept(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "accept and notify"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_accept_and_notify(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_dismiss(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss and notify"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_dismiss_and_notify(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "ignore"}) @pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_ignore(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +def test_ignore(check_user_prompt_not_closed_but_exception, dialog_type): + check_user_prompt_not_closed_but_exception(dialog_type) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_default(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_default(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval)
diff --git a/third_party/blink/web_tests/external/wpt/webdriver/tests/take_screenshot/user_prompts.py b/third_party/blink/web_tests/external/wpt/webdriver/tests/take_screenshot/user_prompts.py index 902463f..ad9e369 100644 --- a/third_party/blink/web_tests/external/wpt/webdriver/tests/take_screenshot/user_prompts.py +++ b/third_party/blink/web_tests/external/wpt/webdriver/tests/take_screenshot/user_prompts.py
@@ -2,7 +2,7 @@ import pytest -from tests.support.asserts import assert_png, assert_success +from tests.support.asserts import assert_dialog_handled, assert_error, assert_png, assert_success from tests.support.inline import inline @@ -12,8 +12,8 @@ @pytest.fixture -def check_user_prompt_not_closed_without_exception(session, create_dialog): - def check_user_prompt_not_closed_without_exception(dialog_type): +def check_user_prompt_closed_without_exception(session, create_dialog): + def check_user_prompt_closed_without_exception(dialog_type, retval): session.url = inline("<input/>") create_dialog(dialog_type, text=dialog_type) @@ -21,44 +21,94 @@ response = take_screenshot(session) value = assert_success(response) + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + assert_png(value) + return check_user_prompt_closed_without_exception + + +@pytest.fixture +def check_user_prompt_closed_with_exception(session, create_dialog): + def check_user_prompt_closed_with_exception(dialog_type, retval): + session.url = inline("<input/>") + + create_dialog(dialog_type, text=dialog_type) + + response = take_screenshot(session) + assert_error(response, "unexpected alert open") + + assert_dialog_handled(session, expected_text=dialog_type, expected_retval=retval) + + return check_user_prompt_closed_with_exception + + +@pytest.fixture +def check_user_prompt_not_closed_but_exception(session, create_dialog): + def check_user_prompt_not_closed_but_exception(dialog_type): + session.url = inline("<input/>") + + create_dialog(dialog_type, text=dialog_type) + + response = take_screenshot(session) + assert_error(response, "unexpected alert open") + assert session.alert.text == dialog_type session.alert.dismiss() - return check_user_prompt_not_closed_without_exception + return check_user_prompt_not_closed_but_exception @pytest.mark.capabilities({"unhandledPromptBehavior": "accept"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_accept(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "accept and notify"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_accept_and_notify(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", True), + ("prompt", ""), +]) +def test_accept_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_dismiss(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss(check_user_prompt_closed_without_exception, dialog_type, retval): + check_user_prompt_closed_without_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "dismiss and notify"}) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_dismiss_and_notify(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_dismiss_and_notify(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval) @pytest.mark.capabilities({"unhandledPromptBehavior": "ignore"}) @pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_ignore(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +def test_ignore(check_user_prompt_not_closed_but_exception, dialog_type): + check_user_prompt_not_closed_but_exception(dialog_type) -@pytest.mark.parametrize("dialog_type", ["alert", "confirm", "prompt"]) -def test_default(check_user_prompt_not_closed_without_exception, dialog_type): - check_user_prompt_not_closed_without_exception(dialog_type) +@pytest.mark.parametrize("dialog_type, retval", [ + ("alert", None), + ("confirm", False), + ("prompt", None), +]) +def test_default(check_user_prompt_closed_with_exception, dialog_type, retval): + check_user_prompt_closed_with_exception(dialog_type, retval)
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index a8f015f..5eda7169 100644 --- a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -384,6 +384,11 @@ method constructor method contains method item +interface DecompressionStream + attribute @@toStringTag + getter readable + getter writable + method constructor interface DetectedBarcode attribute @@toStringTag getter boundingBox
diff --git a/third_party/blink/web_tests/http/tests/websocket/multiple-connections-throttled-expected.txt b/third_party/blink/web_tests/http/tests/websocket/multiple-connections-throttled-expected.txt index d7ae331..eb59b99 100644 --- a/third_party/blink/web_tests/http/tests/websocket/multiple-connections-throttled-expected.txt +++ b/third_party/blink/web_tests/http/tests/websocket/multiple-connections-throttled-expected.txt
@@ -1,53 +1,8 @@ -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason -CONSOLE ERROR: line 24: WebSocket connection to 'ws://127.0.0.1:8880/echo' failed: Unknown reason Test that WebSocket connections are throttled. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS openedCount is 255 +FAIL openedCount should be 255. Was 300. PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt new file mode 100644 index 0000000..d305e9b1 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt
@@ -0,0 +1,24 @@ +Tests that CSS media features can be overridden. +matchMedia("(prefers-color-scheme: __invalid__)").matches: false +matchMedia("(prefers-color-scheme: __invalid__)").matches applied: 2px x 2px +matchMedia("(prefers-color-scheme: no-preference)").matches: true +matchMedia("(prefers-color-scheme: no-preference)").matches applied: 2px x 2px +matchMedia("(prefers-color-scheme: light)").matches: true +matchMedia("(prefers-color-scheme: light)").matches applied: 3px x 2px +matchMedia("(prefers-color-scheme: dark)").matches: true +matchMedia("(prefers-color-scheme: dark)").matches applied: 4px x 2px +matchMedia("(prefers-color-scheme: __invalid__)").matches: false +matchMedia("(prefers-color-scheme: __invalid__)").matches applied: 2px x 2px +matchMedia("(prefers-reduced-motion: __invalid__)").matches: false +matchMedia("(prefers-reduced-motion: __invalid__)").matches applied: 2px x 2px +matchMedia("(prefers-reduced-motion: no-preference)").matches: true +matchMedia("(prefers-reduced-motion: no-preference)").matches applied: 2px x 2px +matchMedia("(prefers-reduced-motion: reduce)").matches: true +matchMedia("(prefers-reduced-motion: reduce)").matches applied: 2px x 3px +matchMedia("(prefers-reduced-motion: __invalid__)").matches: false +matchMedia("(prefers-reduced-motion: __invalid__)").matches applied: 2px x 2px +matchMedia("(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)").matches: true +matchMedia("(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)").matches applied: 999px x 999px +matchMedia("(prefers-color-scheme: __invalid__)").matches: false +matchMedia("(prefers-color-scheme: __invalid__)").matches applied: 2px x 2px +
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js new file mode 100644 index 0000000..7fddf17 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js
@@ -0,0 +1,68 @@ +(async function(testRunner) { + const {page, session, dp} = await testRunner.startBlank( + 'Tests that CSS media features can be overridden.'); + + await session.navigate('../resources/css-media-features.html'); + + async function setEmulatedMediaFeature(feature, value) { + await dp.Emulation.setEmulatedMedia({ + features: [ + { + name: feature, + value: value, + }, + ], + }); + const mediaQuery = `(${feature}: ${value})`; + const code = `matchMedia(${JSON.stringify(mediaQuery)}).matches`; + const result = await session.evaluate(code); + testRunner.log(`${code}: ${result}`); + const width = await session.evaluate('getComputedStyle(p).width'); + const height = await session.evaluate('getComputedStyle(p).height'); + testRunner.log(`${code} applied: ${width} x ${height}`); + } + + async function setEmulatedMediaFeatures({ features, mediaQuery }) { + await dp.Emulation.setEmulatedMedia({ + features, + }); + const code = `matchMedia(${JSON.stringify(mediaQuery)}).matches`; + const result = await session.evaluate(code); + testRunner.log(`${code}: ${result}`); + const width = await session.evaluate('getComputedStyle(p).width'); + const height = await session.evaluate('getComputedStyle(p).height'); + testRunner.log(`${code} applied: ${width} x ${height}`); + } + + // Test `prefers-color-scheme`. + // https://drafts.csswg.org/mediaqueries-5/#prefers-color-scheme + await setEmulatedMediaFeature('prefers-color-scheme', '__invalid__'); + await setEmulatedMediaFeature('prefers-color-scheme', 'no-preference'); + await setEmulatedMediaFeature('prefers-color-scheme', 'light'); + await setEmulatedMediaFeature('prefers-color-scheme', 'dark'); + await setEmulatedMediaFeature('prefers-color-scheme', '__invalid__'); + + // Test `prefers-reduced-motion`. + // https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-motion + await setEmulatedMediaFeature('prefers-reduced-motion', '__invalid__'); + await setEmulatedMediaFeature('prefers-reduced-motion', 'no-preference'); + await setEmulatedMediaFeature('prefers-reduced-motion', 'reduce'); + await setEmulatedMediaFeature('prefers-reduced-motion', '__invalid__'); + + // Test combinations. + await setEmulatedMediaFeatures({ + features: [ + { name: 'prefers-color-scheme', value: 'dark' }, + { name: 'prefers-reduced-motion', value: 'reduce' }, + ], + mediaQuery: '(prefers-color-scheme: dark) and (prefers-reduced-motion: reduce)', + }); + await setEmulatedMediaFeatures({ + features: [ + { name: 'prefers-color-scheme', value: '__invalid__' }, + ], + mediaQuery: '(prefers-color-scheme: __invalid__)', + }); + + testRunner.completeTest(); +});
diff --git a/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html b/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html new file mode 100644 index 0000000..2c38e8d9 --- /dev/null +++ b/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<style> + p { width: 1px; height: 1px; } + @media (prefers-color-scheme: no-preference) { p { width: 2px; } } + @media (prefers-color-scheme: light) { p { width: 3px; } } + @media (prefers-color-scheme: dark) { p { width: 4px; } } + @media (prefers-reduced-motion: no-preference) { p { height: 2px; } } + @media (prefers-reduced-motion: reduce) { p { height: 3px; } } + @media (prefers-color-scheme: dark) and (prefers-reduced-motion: reduce) { p { width: 999px; height: 999px; } } +</style> +<p id="p">
diff --git a/third_party/blink/web_tests/payments/resources/payment-request-mock.js b/third_party/blink/web_tests/payments/resources/payment-request-mock.js index 8f33c2b..4d6755c 100644 --- a/third_party/blink/web_tests/payments/resources/payment-request-mock.js +++ b/third_party/blink/web_tests/payments/resources/payment-request-mock.js
@@ -10,7 +10,7 @@ this.bindings_ = new mojo.BindingSet(payments.mojom.PaymentRequest); this.interceptor_ = new MojoInterfaceInterceptor( - payments.mojom.PaymentRequest.name); + payments.mojom.PaymentRequest.name, "context", true); this.interceptor_.oninterfacerequest = e => this.bindings_.addBinding(this, e.handle); this.interceptor_.start();
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt index c6d8be8..e9e5199b 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -340,6 +340,11 @@ [Worker] method constructor [Worker] method contains [Worker] method item +[Worker] interface DecompressionStream +[Worker] attribute @@toStringTag +[Worker] getter readable +[Worker] getter writable +[Worker] method constructor [Worker] interface DedicatedWorkerGlobalScope : WorkerGlobalScope [Worker] attribute @@toStringTag [Worker] attribute PERSISTENT
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 07098809..ae50334e 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -1499,6 +1499,11 @@ method clear method constructor method remove +interface DecompressionStream + attribute @@toStringTag + getter readable + getter writable + method constructor interface DelayNode : AudioNode attribute @@toStringTag getter delayTime
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt index 7eaaf64..bc49892 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -340,6 +340,11 @@ [Worker] method constructor [Worker] method contains [Worker] method item +[Worker] interface DecompressionStream +[Worker] attribute @@toStringTag +[Worker] getter readable +[Worker] getter writable +[Worker] method constructor [Worker] interface DetectedBarcode [Worker] attribute @@toStringTag [Worker] getter boundingBox
diff --git a/tools/json_to_struct/json_to_struct.py b/tools/json_to_struct/json_to_struct.py index 46cfd4a..ec332a5 100755 --- a/tools/json_to_struct/json_to_struct.py +++ b/tools/json_to_struct/json_to_struct.py
@@ -136,6 +136,13 @@ for element_name, element in description['elements'].items(): f.write('extern const %s %s;\n' % (schema['type_name'], element_name)) + if 'generate_array' in description: + f.write('\n') + f.write('extern const %s* const %s[];\n' % (schema['type_name'], + description['generate_array']['array_name'])) + f.write('extern const size_t %s;\n' % + (description['generate_array']['array_name'] + 'Length')) + if namespace: f.write('\n') f.write('} // namespace %s\n' % namespace) @@ -171,6 +178,17 @@ f.write(element_generator.GenerateElements(schema['type_name'], schema['schema'], description)) + if 'generate_array' in description: + f.write('\n') + f.write('const %s* const %s[] = {\n' % (schema['type_name'], + description['generate_array']['array_name'])) + for element_name, _ in description['elements'].items(): + f.write('\t&%s,\n' % element_name) + f.write('};\n') + f.write('const size_t %s = base::size(%s);\n' % + (description['generate_array']['array_name'] + 'Length', + description['generate_array']['array_name'])) + if namespace: f.write('\n') f.write('} // namespace %s\n' % namespace)
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 8eee741..344a774b 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -3608,6 +3608,13 @@ <int value="20" label="Installing the feature module failed"/> </enum> +<enum name="AutofillAssistantFeatureModuleInstallation"> + <int value="0" label="Background installation requested"/> + <int value="1" label="Foreground installation succeeded"/> + <int value="2" label="Foreground installation failed"/> + <int value="3" label="Already installed"/> +</enum> + <enum name="AutofillAssistantOnBoarding"> <int value="0" label="Shown"/> <int value="1" label="Not shown (returning user)"/> @@ -18134,6 +18141,7 @@ <int value="614" label="DeviceLoginScreenCaretHighlightEnabled"/> <int value="615" label="DeviceLoginScreenMonoAudioEnabled"/> <int value="616" label="TotalMemoryLimitMb"/> + <int value="617" label="DeviceLoginScreenAutoclickEnabled"/> </enum> <enum name="EnterprisePolicyInvalidations"> @@ -24758,6 +24766,11 @@ <int value="3036" label="XRIsSessionSupported"/> <int value="3037" label="ScrollbarUseScrollbarButtonReversedDirection"/> <int value="3038" label="CSSSelectorPseudoScrollbarButtonReversedDirection"/> + <int value="3039" label="FragmentHasTildeAmpersandTilde"/> + <int value="3040" label="FragmentHasColonTildeColon"/> + <int value="3041" label="FragmentHasTildeAtTilde"/> + <int value="3042" label="FragmentHasAmpersandDelimiterQuestion"/> + <int value="3043" label="InvalidFragmentDirective"/> </enum> <enum name="FeaturePolicyAllowlistType"> @@ -50463,6 +50476,7 @@ <int value="13" label="Switch to another profile button"/> <int value="14" label="Cookies cleared on exit link"/> <int value="15" label="Add new profile button"/> + <int value="16" label="Sync settings(sync on) button"/> </enum> <enum name="ProfileNetUserCount">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 2aca350..953bb0f 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -17864,6 +17864,35 @@ </summary> </histogram> +<histogram name="Bookmarks.AddedPerProfileType" enum="BrowserProfileType" + expires_after="M85"> + <owner>rhalavati@chromium.org</owner> + <owner>chrome-privacy-core@google.com</owner> + <summary> + This histogram records when a bookmark is added sliced on profile type. + </summary> +</histogram> + +<histogram name="Bookmarks.BookmarkAllTabsWithTabsCount.Incognito" units="tabs" + expires_after="M85"> + <owner>rhalavati@chromium.org</owner> + <owner>chrome-privacy-core@google.com</owner> + <summary> + This histogram records the count of tabs when a user bookmarks all open + tabs, in incognito mode. + </summary> +</histogram> + +<histogram name="Bookmarks.BookmarkAllTabsWithTabsCount.Regular" units="tabs" + expires_after="M85"> + <owner>rhalavati@chromium.org</owner> + <owner>chrome-privacy-core@google.com</owner> + <summary> + This histogram records the count of tabs when a user bookmarks all open + tabs, in regular mode. + </summary> +</histogram> + <histogram name="Bookmarks.BookmarksInFolder" units="bookmarks"> <owner>calamity@chromium.org</owner> <summary> @@ -134786,7 +134815,7 @@ </histogram> <histogram name="SiteIsolatedCodeCache.JS.Behaviour" - enum="SiteIsolatedCodeCacheJSBehaviour" expires_after="2019-10-30"> + enum="SiteIsolatedCodeCacheJSBehaviour" expires_after="2020-03-31"> <owner>mythria@chromium.org</owner> <summary> The behaviour of site isolated javascript code cache recorded for each cache @@ -147540,6 +147569,10 @@ </histogram> <histogram name="TileManager.TilesGPUMemoryUsage" units="KB"> + <obsolete> + Replaced by TileManager.TilesGPUMemoryUsage2 which records on all devices + instead of just devices with less than 512MB of memory. + </obsolete> <owner>xidachen@chromium.org</owner> <owner>ericrk@chromium.org</owner> <summary> @@ -147549,6 +147582,16 @@ </summary> </histogram> +<histogram name="TileManager.TilesGPUMemoryUsage2" units="KB" + expires_after="never"> + <owner>pdr@chromium.org</owner> + <owner>ericrk@chromium.org</owner> + <summary> + The amount of GPU memory used for tiles, in kilobytes. Recorded when the + tile manager had sufficient memory to schedule all visible tiles. + </summary> +</histogram> + <histogram name="TimeZone.TimeZoneRequest.Event" enum="TimeZoneRequestEvent" expires_after="never"> <!-- expires-never: This reports external time zone provider health status and
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 013d199..bcfd818 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -191,21 +191,6 @@ return toplevel_document; } -bool EmitsAtkTextEvents(AtkObject* atk_object) { - // If this node is not a static text node, it supports the full AtkText - // interface. - AtkRole role = atk_object_get_role(atk_object); - if (role != ATK_ROLE_TEXT) - return true; - - // If this node is not a static text leaf node, it supports the full AtkText - // interface. - if (atk_object_get_n_accessible_children(atk_object)) - return true; - - return false; -} - bool IsFrameAncestorOfAtkObject(AtkObject* frame, AtkObject* atk_object) { AtkObject* current_frame = FindAtkObjectParentFrame(atk_object); while (current_frame) { @@ -353,10 +338,6 @@ return nullptr; } -bool SelectionOffsetsIndicateSelection(const std::pair<int, int>& offsets) { - return offsets.first >= 0 && offsets.second >= 0 && - offsets.first != offsets.second; -} void PrependTextAttributeToSet(const AtkTextAttribute attribute, const std::string& value, @@ -2286,7 +2267,7 @@ AtkUtilAuraLinux::GetInstance()->InitializeAsync(); } -AtkRole AXPlatformNodeAuraLinux::GetAtkRole() { +AtkRole AXPlatformNodeAuraLinux::GetAtkRole() const { switch (GetData().role) { case ax::mojom::Role::kAlert: return ATK_ROLE_ALERT; @@ -3224,35 +3205,139 @@ return false; } -void AXPlatformNodeAuraLinux::OnTextSelectionChanged() { - AtkObject* atk_object = GetOrCreateAtkObject(); - if (!EmitsAtkTextEvents(atk_object)) { - if (auto* parent = AtkObjectToAXPlatformNodeAuraLinux(GetParent())) - parent->OnTextSelectionChanged(); +bool AXPlatformNodeAuraLinux::EmitsAtkTextEvents() const { + // If this node is not a static text node, it supports the full AtkText + // interface. + if (GetAtkRole() != ATK_ROLE_TEXT) + return true; + + // If this node has children it is not a static text leaf node and supports + // the full AtkText interface. + if (GetChildCount()) + return true; + + return false; +} + +void AXPlatformNodeAuraLinux::GetFullSelection(int32_t* anchor_node_id, + int* anchor_offset, + int32_t* focus_node_id, + int* focus_offset) { + DCHECK(anchor_node_id); + DCHECK(anchor_offset); + DCHECK(focus_node_id); + DCHECK(focus_offset); + + if (IsPlainTextField() && + GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, anchor_offset) && + GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, focus_offset)) { + int32_t node_id = GetData().id != -1 ? GetData().id : GetUniqueId(); + *anchor_node_id = *focus_node_id = node_id; return; } - DCHECK(ATK_IS_TEXT(atk_object)); + ui::AXTree::Selection selection = GetDelegate()->GetUnignoredSelection(); + *anchor_node_id = selection.anchor_object_id; + *anchor_offset = selection.anchor_offset; + *focus_node_id = selection.focus_object_id; + *focus_offset = selection.focus_offset; +} - std::pair<int, int> new_selection; - GetSelectionOffsets(&new_selection.first, &new_selection.second); - std::pair<int, int> old_selection = text_selection_; - text_selection_ = new_selection; +AXPlatformNodeAuraLinux& AXPlatformNodeAuraLinux::FindEditableRootOrDocument() { + if (GetAtkRole() == ATK_ROLE_DOCUMENT_WEB) + return *this; + if (GetData().GetBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot)) + return *this; + if (auto* parent = AtkObjectToAXPlatformNodeAuraLinux(GetParent())) + return parent->FindEditableRootOrDocument(); + return *this; +} + +AXPlatformNodeAuraLinux* AXPlatformNodeAuraLinux::FindCommonAncestor( + AXPlatformNodeAuraLinux* other) { + if (this == other || other->IsDescendantOf(this)) + return this; + if (auto* parent = AtkObjectToAXPlatformNodeAuraLinux(GetParent())) + return parent->FindCommonAncestor(other); + return nullptr; +} + +void AXPlatformNodeAuraLinux::UpdateSelectionInformation(int32_t anchor_node_id, + int anchor_offset, + int32_t focus_node_id, + int focus_offset) { + had_nonzero_width_selection = + focus_node_id != anchor_node_id || focus_offset != anchor_offset; + current_caret_ = std::make_pair(focus_node_id, focus_offset); +} + +void AXPlatformNodeAuraLinux::EmitSelectionChangedSignal(bool had_selection) { + if (!EmitsAtkTextEvents()) { + if (auto* parent = AtkObjectToAXPlatformNodeAuraLinux(GetParent())) + parent->EmitSelectionChangedSignal(had_selection); + return; + } + + AtkObject* atk_object = GetOrCreateAtkObject(); + DCHECK(ATK_IS_TEXT(atk_object)); + std::pair<int, int> selection; + GetSelectionOffsets(&selection.first, &selection.second); // ATK does not consider a collapsed selection a selection, so // when the collapsed selection changes (caret movement), we should // avoid sending text-selection-changed events. - bool has_selection = SelectionOffsetsIndicateSelection(new_selection); - bool had_selection = SelectionOffsetsIndicateSelection(old_selection); - if (has_selection != had_selection || - (has_selection && new_selection != old_selection)) { + if (HasSelection() || had_selection) g_signal_emit_by_name(atk_object, "text-selection-changed"); +} + +void AXPlatformNodeAuraLinux::EmitCaretChangedSignal() { + if (!EmitsAtkTextEvents()) { + if (auto* parent = AtkObjectToAXPlatformNodeAuraLinux(GetParent())) + parent->EmitCaretChangedSignal(); + return; } - if (HasCaret() && new_selection.second != old_selection.second) { - g_signal_emit_by_name(atk_object, "text-caret-moved", - UTF16ToUnicodeOffsetInText(new_selection.second)); + DCHECK(HasCaret()); + std::pair<int, int> selection; + GetSelectionOffsets(&selection.first, &selection.second); + + AtkObject* atk_object = GetOrCreateAtkObject(); + DCHECK(ATK_IS_TEXT(atk_object)); + g_signal_emit_by_name(atk_object, "text-caret-moved", + UTF16ToUnicodeOffsetInText(selection.second)); +} + +void AXPlatformNodeAuraLinux::OnTextSelectionChanged() { + int32_t anchor_node_id, focus_node_id; + int anchor_offset, focus_offset; + GetFullSelection(&anchor_node_id, &anchor_offset, &focus_node_id, + &focus_offset); + + auto* anchor_node = static_cast<AXPlatformNodeAuraLinux*>( + GetDelegate()->GetFromNodeID(anchor_node_id)); + auto* focus_node = static_cast<AXPlatformNodeAuraLinux*>( + GetDelegate()->GetFromNodeID(focus_node_id)); + if (!anchor_node || !focus_node) + return; + + AXPlatformNodeAuraLinux& editable_root = FindEditableRootOrDocument(); + AXPlatformNodeAuraLinux* common_ancestor = + focus_node->FindCommonAncestor(anchor_node); + if (common_ancestor) { + common_ancestor->EmitSelectionChangedSignal( + editable_root.HadNonZeroWidthSelection()); } + + // It's possible for the selection to change and for the caret to stay in + // place. This might happen if the selection is totally reset with a + // different anchor node, but the same focus node. We should avoid sending a + // caret changed signal in that case. + std::pair<int32_t, int> prev_caret = editable_root.GetCurrentCaret(); + if (prev_caret.first != focus_node_id || prev_caret.second != focus_offset) + focus_node->EmitCaretChangedSignal(); + + editable_root.UpdateSelectionInformation(anchor_node_id, anchor_offset, + focus_node_id, focus_offset); } bool AXPlatformNodeAuraLinux::SupportsSelectionWithAtkSelection() { @@ -3485,7 +3570,7 @@ AtkObject* atk_object = GetOrCreateAtkObject(); DCHECK(ATK_IS_TEXT(atk_object)); - if (!EmitsAtkTextEvents(atk_object)) + if (!EmitsAtkTextEvents()) return; if (old_len > 0) { @@ -3902,7 +3987,6 @@ if (!SetHypertextSelection(offset, offset)) return false; - OnTextSelectionChanged(); return true; } @@ -3932,14 +4016,14 @@ if (!SetHypertextSelection(start_offset, end_offset)) return false; - OnTextSelectionChanged(); return true; } bool AXPlatformNodeAuraLinux::HasSelection() { std::pair<int, int> selection; GetSelectionOffsets(&selection.first, &selection.second); - return SelectionOffsetsIndicateSelection(selection); + return selection.first >= 0 && selection.second >= 0 && + selection.first != selection.second; } void AXPlatformNodeAuraLinux::GetSelectionExtents(int* start_offset, @@ -4169,7 +4253,7 @@ AtkObject* atk_object = GetOrCreateAtkObject(); DCHECK(ATK_IS_TEXT(atk_object)); - if (!EmitsAtkTextEvents(atk_object)) { + if (!EmitsAtkTextEvents()) { ActivateFindInPageInParent(start_offset, end_offset); return; }
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.h b/ui/accessibility/platform/ax_platform_node_auralinux.h index 9ae304c..71a3c91 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.h +++ b/ui/accessibility/platform/ax_platform_node_auralinux.h
@@ -106,7 +106,7 @@ void EnsureAtkObjectIsValid(); void Destroy() override; - AtkRole GetAtkRole(); + AtkRole GetAtkRole() const; void GetAtkState(AtkStateSet* state_set); AtkRelationSet* GetAtkRelations(); void GetExtents(gint* x, gint* y, gint* width, gint* height, @@ -197,6 +197,7 @@ bool SetCaretOffset(int offset); bool SetTextSelectionForAtkText(int start_offset, int end_offset); bool HasSelection(); + void GetSelectionExtents(int* start_offset, int* end_offset); gchar* GetSelectionWithText(int* start_offset, int* end_offset); @@ -289,6 +290,41 @@ // Find the first child which is a document containing web content. AtkObject* FindFirstWebContentDocument(); + // If a selection that intersects this node get the full selection + // including start and end node ids. + void GetFullSelection(int32_t* anchor_node_id, + int* anchor_offset, + int32_t* focus_node_id, + int* focus_offset); + + // Returns true if this node's AtkObject is suitable for emitting AtkText + // signals. ATs don't expect static text objects to emit AtkText signals. + bool EmitsAtkTextEvents() const; + + // Find the first ancestor which is an editable root or a document. This node + // will be one which contains a single selection. + AXPlatformNodeAuraLinux& FindEditableRootOrDocument(); + + // Find the first common ancestor between this node and a given node. + AXPlatformNodeAuraLinux* FindCommonAncestor(AXPlatformNodeAuraLinux* other); + + // Update the selection information stored in this node. This should be + // called on the editable root, the root node of the accessibility tree, or + // the document (ie the node returned by FindEditableRootOrDocument()). + void UpdateSelectionInformation(int32_t anchor_node_id, + int anchor_offset, + int32_t focus_node_id, + int focus_offset); + + // Emit a GObject signal indicating a selection change. + void EmitSelectionChangedSignal(bool had_selection); + + // Emit a GObject signal indicating that the caret has moved. + void EmitCaretChangedSignal(); + + bool HadNonZeroWidthSelection() const { return had_nonzero_width_selection; } + std::pair<int32_t, int> GetCurrentCaret() const { return current_caret_; } + // If the given argument can be found as a child of this node, return its // hypertext extents, otherwise return base::nullopt; base::Optional<std::pair<int, int>> GetHypertextExtentsOfChild( @@ -312,10 +348,17 @@ // minimized the last time it's visibility changed. bool was_minimized_ = false; - // The previously observed text selection for this node. We store - // this in order to avoid sending duplicate text-selection-changed - // and text-caret-moved events. - std::pair<int, int> text_selection_ = std::make_pair(-1, -1); + // Information about the selection meant to be stored on the return value of + // FindEditableRootOrDocument(). + // + // Whether or not we previously had a selection where the anchor and focus + // were not equal. This is what ATK consider a "selection." + bool had_nonzero_width_selection = false; + + // Information about the current caret location (a node id and an offset). + // This is used to track when the caret actually moves during a selection + // change. + std::pair<int32_t, int> current_caret_ = {-1, -1}; // A map which converts between an offset in the node's hypertext and the // ATK text attributes at that offset.
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc index 44973634..75908ed 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux_unittest.cc
@@ -1399,34 +1399,52 @@ &caret_position_from_event); atk_text_set_caret_offset(atk_text, 4); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), 4); ASSERT_EQ(caret_position_from_event, 4); // Setting the same position should not trigger another event. caret_position_from_event = -1; atk_text_set_caret_offset(atk_text, 4); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), 4); ASSERT_EQ(caret_position_from_event, -1); int character_count = atk_text_get_character_count(atk_text); atk_text_set_caret_offset(atk_text, -1); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), character_count); ASSERT_EQ(caret_position_from_event, character_count); + atk_text_set_caret_offset(atk_text, 0); // Reset position. + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); caret_position_from_event = -1; atk_text_set_caret_offset(atk_text, -1000); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), character_count); ASSERT_EQ(caret_position_from_event, character_count); + atk_text_set_caret_offset(atk_text, 0); // Reset position. + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); caret_position_from_event = -1; atk_text_set_caret_offset(atk_text, 1000); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), character_count); ASSERT_EQ(caret_position_from_event, character_count); caret_position_from_event = -1; atk_text_set_caret_offset(atk_text, character_count - 1); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); ASSERT_EQ(atk_text_get_caret_offset(atk_text), character_count - 1); ASSERT_EQ(caret_position_from_event, character_count - 1); @@ -2096,6 +2114,8 @@ int selection_start, selection_end; EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, 1)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_TRUE(saw_selection_change); g_free(atk_text_get_selection(atk_text, 0, &selection_start, &selection_end)); EXPECT_EQ(selection_start, 0); @@ -2103,25 +2123,22 @@ // Reset position. EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, 0)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); saw_selection_change = false; EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 1, 0)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_TRUE(saw_selection_change); g_free(atk_text_get_selection(atk_text, 0, &selection_start, &selection_end)); EXPECT_EQ(selection_start, 0); EXPECT_EQ(selection_end, 1); - // Setting the selection to the same location should not trigger - // another event. - saw_selection_change = false; - EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 1, 0)); - EXPECT_FALSE(saw_selection_change); - g_free(atk_text_get_selection(atk_text, 0, &selection_start, &selection_end)); - EXPECT_EQ(selection_start, 0); - EXPECT_EQ(selection_end, 1); - saw_selection_change = false; EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 2, 4)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_TRUE(saw_selection_change); g_free(atk_text_get_selection(atk_text, 0, &selection_start, &selection_end)); EXPECT_EQ(selection_start, 2); @@ -2136,11 +2153,12 @@ saw_selection_change = false; EXPECT_FALSE(atk_text_set_selection(atk_text, 0, 0, 50)); - EXPECT_FALSE(saw_selection_change); saw_selection_change = false; int n_characters = atk_text_get_character_count(atk_text); EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, -1)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_TRUE(saw_selection_change); g_free(atk_text_get_selection(atk_text, 0, &selection_start, &selection_end)); EXPECT_EQ(selection_start, 0); @@ -2148,6 +2166,8 @@ saw_selection_change = false; EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, 1)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_EQ(1, atk_text_get_n_selections(atk_text)); EXPECT_TRUE(atk_text_remove_selection(atk_text, 0)); EXPECT_TRUE(saw_selection_change); @@ -2155,9 +2175,13 @@ // Reset position. EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, 0)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); saw_selection_change = false; EXPECT_TRUE(atk_text_set_selection(atk_text, 0, 0, 1)); + GetRootPlatformNode()->NotifyAccessibilityEvent( + ax::mojom::Event::kTextSelectionChanged); EXPECT_EQ(1, atk_text_get_n_selections(atk_text)); EXPECT_FALSE(atk_text_remove_selection(atk_text, 1)); EXPECT_TRUE(saw_selection_change);
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc index 1f905100..488e6e49 100644 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ b/ui/accessibility/platform/ax_platform_node_base.cc
@@ -1776,6 +1776,10 @@ // We assume that there are 96 pixels per inch on a standard display. // TODO(nektar): Figure out the current value of pixels per inch. float points = font_size * 72.0 / 96.0; + + // Round to the nearest 0.5 points. + points = std::round(points * 2.0) / 2.0; + attributes.push_back( std::make_pair("font-size", base::NumberToString(points) + "pt")); }
diff --git a/ui/events/blink/blink_features.cc b/ui/events/blink/blink_features.cc index 9c533b6..b173f77 100644 --- a/ui/events/blink/blink_features.cc +++ b/ui/events/blink/blink_features.cc
@@ -7,7 +7,7 @@ namespace features { const base::Feature kResamplingScrollEvents{"ResamplingScrollEvents", - base::FEATURE_ENABLED_BY_DEFAULT}; + base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kFilteringScrollPrediction{ "FilteringScrollPrediction", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js index 6677c83..47fe7830 100644 --- a/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js +++ b/ui/file_manager/file_manager/foreground/elements/xf_panel_item.js
@@ -30,6 +30,9 @@ /** @private {number} */ this.panelType_ = this.panelTypeDefault; + /** @private @type {?function(Event)} */ + this.onclick = this.onClicked_.bind(this); + /** @public {?DisplayPanel} */ this.parent = null; @@ -204,7 +207,7 @@ this.setAttribute('indicator', 'progress'); secondaryButton = document.createElement('xf-button'); secondaryButton.id = 'secondary-action'; - secondaryButton.onclick = this.onclick; + secondaryButton.onclick = assert(this.onclick); secondaryButton.dataset.category = 'cancel'; secondaryButton.setAttribute('aria-label', '$i18n{CANCEL_LABEL}'); buttonSpacer.insertAdjacentElement('afterend', secondaryButton); @@ -223,7 +226,7 @@ this.setAttribute('status', 'success'); primaryButton = document.createElement('xf-button'); primaryButton.id = 'primary-action'; - primaryButton.onclick = this.onclick; + primaryButton.onclick = assert(this.onclick); primaryButton.dataset.category = 'dismiss'; buttonSpacer.insertAdjacentElement('afterend', primaryButton); break; @@ -232,7 +235,7 @@ this.setAttribute('status', 'failure'); secondaryButton = document.createElement('xf-button'); secondaryButton.id = 'secondary-action'; - secondaryButton.onclick = this.onclick; + secondaryButton.onclick = assert(this.onclick); secondaryButton.dataset.category = 'dismiss'; buttonSpacer.insertAdjacentElement('afterend', secondaryButton); break;
diff --git a/ui/message_center/message_center_impl.cc b/ui/message_center/message_center_impl.cc index 6d71ab2..f5343d6 100644 --- a/ui/message_center/message_center_impl.cc +++ b/ui/message_center/message_center_impl.cc
@@ -460,11 +460,9 @@ observer.OnQuietModeChanged(true); quiet_mode_timer_ = std::make_unique<base::OneShotTimer>(); - quiet_mode_timer_->Start( - FROM_HERE, - expires_in, - base::Bind( - &MessageCenterImpl::SetQuietMode, base::Unretained(this), false)); + quiet_mode_timer_->Start(FROM_HERE, expires_in, + base::BindOnce(&MessageCenterImpl::SetQuietMode, + base::Unretained(this), false)); } }
diff --git a/ui/message_center/message_center_impl_unittest.cc b/ui/message_center/message_center_impl_unittest.cc index f9bfc75a..b647e99 100644 --- a/ui/message_center/message_center_impl_unittest.cc +++ b/ui/message_center/message_center_impl_unittest.cc
@@ -166,7 +166,7 @@ } base::RunLoop* run_loop() const { return run_loop_.get(); } - base::Closure closure() const { return closure_; } + base::RepeatingClosure closure() const { return closure_; } protected: std::unique_ptr<Notification> CreateSimpleNotification( @@ -217,7 +217,7 @@ MessageCenter* message_center_; std::unique_ptr<base::MessageLoop> loop_; std::unique_ptr<base::RunLoop> run_loop_; - base::Closure closure_; + base::RepeatingClosure closure_; DISALLOW_COPY_AND_ASSIGN(MessageCenterImplTest); }; @@ -316,7 +316,7 @@ class MockPopupTimersController : public PopupTimersController { public: MockPopupTimersController(MessageCenter* message_center, - base::Closure quit_closure) + base::RepeatingClosure quit_closure) : PopupTimersController(message_center), timer_finished_(0), quit_closure_(quit_closure) {} @@ -334,7 +334,7 @@ private: int timer_finished_; std::string last_id_; - base::Closure quit_closure_; + base::RepeatingClosure quit_closure_; }; TEST_F(MessageCenterImplTest, PopupTimersEmptyController) {
diff --git a/ui/message_center/popup_timer.cc b/ui/message_center/popup_timer.cc index 6c09453..e99b5ef 100644 --- a/ui/message_center/popup_timer.cc +++ b/ui/message_center/popup_timer.cc
@@ -30,9 +30,8 @@ timeout_ <= passed_ ? base::TimeDelta() : timeout_ - passed_; start_time_ = base::Time::Now(); - timer_->Start( - FROM_HERE, timeout_to_close, - base::Bind(&Delegate::TimerFinished, timer_delegate_, id_)); + timer_->Start(FROM_HERE, timeout_to_close, + base::BindOnce(&Delegate::TimerFinished, timer_delegate_, id_)); } void PopupTimer::Pause() {
diff --git a/ui/message_center/public/cpp/notification_delegate_unittest.cc b/ui/message_center/public/cpp/notification_delegate_unittest.cc index bd600a7ee..376b89a 100644 --- a/ui/message_center/public/cpp/notification_delegate_unittest.cc +++ b/ui/message_center/public/cpp/notification_delegate_unittest.cc
@@ -34,16 +34,16 @@ TEST_F(NotificationDelegateTest, ClickDelegate) { auto delegate = base::MakeRefCounted<HandleNotificationClickDelegate>( - base::Bind(&NotificationDelegateTest::BodyClickCallback, - base::Unretained(this))); + base::BindRepeating(&NotificationDelegateTest::BodyClickCallback, + base::Unretained(this))); delegate->Click(base::nullopt, base::nullopt); EXPECT_EQ(1, callback_count_); } TEST_F(NotificationDelegateTest, NullClickDelegate) { - auto delegate = - base::MakeRefCounted<HandleNotificationClickDelegate>(base::Closure()); + auto delegate = base::MakeRefCounted<HandleNotificationClickDelegate>( + base::RepeatingClosure()); delegate->Click(base::nullopt, base::nullopt); EXPECT_EQ(0, callback_count_); @@ -51,8 +51,8 @@ TEST_F(NotificationDelegateTest, ButtonClickDelegate) { auto delegate = base::MakeRefCounted<HandleNotificationClickDelegate>( - base::Bind(&NotificationDelegateTest::ButtonClickCallback, - base::Unretained(this))); + base::BindRepeating(&NotificationDelegateTest::ButtonClickCallback, + base::Unretained(this))); delegate->Click(base::nullopt, base::nullopt); EXPECT_EQ(1, callback_count_);
diff --git a/ui/message_center/views/message_view_factory.h b/ui/message_center/views/message_view_factory.h index f4d48b8..301dc6fa 100644 --- a/ui/message_center/views/message_view_factory.h +++ b/ui/message_center/views/message_view_factory.h
@@ -25,8 +25,9 @@ public: // A function that creates MessageView for a NOTIFICATION_TYPE_CUSTOM // notification. - typedef base::Callback<std::unique_ptr<MessageView>(const Notification&)> - CustomMessageViewFactoryFunction; + using CustomMessageViewFactoryFunction = + base::RepeatingCallback<std::unique_ptr<MessageView>( + const Notification&)>; static MessageView* Create(const Notification& notification);
diff --git a/ui/snapshot/screenshot_grabber.cc b/ui/snapshot/screenshot_grabber.cc index 476bbe2..2145955e 100644 --- a/ui/snapshot/screenshot_grabber.cc +++ b/ui/snapshot/screenshot_grabber.cc
@@ -90,9 +90,9 @@ #endif ui::GrabWindowSnapshotAsyncPNG( window, rect, - base::Bind(&ScreenshotGrabber::GrabWindowSnapshotAsyncCallback, - factory_.GetWeakPtr(), window_identifier, is_partial, - base::Passed(&callback))); + base::BindOnce(&ScreenshotGrabber::GrabWindowSnapshotAsyncCallback, + factory_.GetWeakPtr(), window_identifier, is_partial, + std::move(callback))); } bool ScreenshotGrabber::CanTakeScreenshot() {
diff --git a/ui/snapshot/snapshot.cc b/ui/snapshot/snapshot.cc index 4e276d1..e3a0c8c 100644 --- a/ui/snapshot/snapshot.cc +++ b/ui/snapshot/snapshot.cc
@@ -39,33 +39,33 @@ void EncodeImageAndScheduleCallback( scoped_refptr<base::RefCountedMemory> (*encode_func)(const gfx::Image&), - const base::Callback<void(scoped_refptr<base::RefCountedMemory> data)>& + base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)> callback, gfx::Image image) { base::PostTaskAndReplyWithResult( FROM_HERE, {base::ThreadPool(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::Bind(encode_func, std::move(image)), callback); + base::BindOnce(encode_func, std::move(image)), std::move(callback)); } } // namespace -void GrabWindowSnapshotAsyncPNG( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncPNGCallback& callback) { +void GrabWindowSnapshotAsyncPNG(gfx::NativeWindow window, + const gfx::Rect& source_rect, + GrabWindowSnapshotAsyncPNGCallback callback) { GrabWindowSnapshotAsync( window, source_rect, - base::Bind(EncodeImageAndScheduleCallback, &EncodeImageAsPNG, callback)); + base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsPNG, + std::move(callback))); } -void GrabWindowSnapshotAsyncJPEG( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncJPEGCallback& callback) { +void GrabWindowSnapshotAsyncJPEG(gfx::NativeWindow window, + const gfx::Rect& source_rect, + GrabWindowSnapshotAsyncJPEGCallback callback) { GrabWindowSnapshotAsync( window, source_rect, - base::Bind(EncodeImageAndScheduleCallback, &EncodeImageAsJPEG, callback)); + base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsJPEG, + std::move(callback))); } } // namespace ui
diff --git a/ui/snapshot/snapshot.h b/ui/snapshot/snapshot.h index f6fd6d3..9fbb3b6 100644 --- a/ui/snapshot/snapshot.h +++ b/ui/snapshot/snapshot.h
@@ -38,37 +38,40 @@ // These functions take a snapshot of |source_rect|, specified in layer space // coordinates (DIP for desktop, physical pixels for Android), and scale the // snapshot to |target_size| (in physical pixels), asynchronously. -typedef base::Callback<void(gfx::Image snapshot)> - GrabWindowSnapshotAsyncCallback; +using GrabWindowSnapshotAsyncCallback = + base::OnceCallback<void(gfx::Image snapshot)>; + SNAPSHOT_EXPORT void GrabWindowSnapshotAndScaleAsync( gfx::NativeWindow window, const gfx::Rect& source_rect, const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); SNAPSHOT_EXPORT void GrabWindowSnapshotAsync( gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); SNAPSHOT_EXPORT void GrabViewSnapshotAsync( gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); using GrabWindowSnapshotAsyncPNGCallback = - base::Callback<void(scoped_refptr<base::RefCountedMemory> data)>; + base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>; + SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncPNG( gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncPNGCallback& callback); + GrabWindowSnapshotAsyncPNGCallback callback); using GrabWindowSnapshotAsyncJPEGCallback = - base::Callback<void(scoped_refptr<base::RefCountedMemory> data)>; + base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>; + SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncJPEG( gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncJPEGCallback& callback); + GrabWindowSnapshotAsyncJPEGCallback callback); } // namespace ui
diff --git a/ui/snapshot/snapshot_android.cc b/ui/snapshot/snapshot_android.cc index 92f3525..b6596a1 100644 --- a/ui/snapshot/snapshot_android.cc +++ b/ui/snapshot/snapshot_android.cc
@@ -57,37 +57,36 @@ std::move(copy_request)); } -void GrabWindowSnapshotAndScaleAsync( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback) { +void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window, + const gfx::Rect& source_rect, + const gfx::Size& target_size, + GrabWindowSnapshotAsyncCallback callback) { MakeAsyncCopyRequest( window, source_rect, CreateCopyRequest(window, source_rect, base::BindOnce(&SnapshotAsync::ScaleCopyOutputResult, - callback, target_size))); + std::move(callback), target_size))); } void GrabWindowSnapshotAsync(gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { MakeAsyncCopyRequest( window, source_rect, CreateCopyRequest( window, source_rect, base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult, - callback))); + std::move(callback)))); } void GrabViewSnapshotAsync(gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { std::unique_ptr<viz::CopyOutputRequest> copy_request = view->MaybeRequestCopyOfView(CreateCopyRequest( view, source_rect, base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult, - callback))); + std::move(callback)))); if (!copy_request) return;
diff --git a/ui/snapshot/snapshot_async.cc b/ui/snapshot/snapshot_async.cc index ffb65ab..275458c7b 100644 --- a/ui/snapshot/snapshot_async.cc +++ b/ui/snapshot/snapshot_async.cc
@@ -18,9 +18,9 @@ namespace { -void OnFrameScalingFinished(const GrabWindowSnapshotAsyncCallback& callback, +void OnFrameScalingFinished(GrabWindowSnapshotAsyncCallback callback, const SkBitmap& scaled_bitmap) { - callback.Run(gfx::Image::CreateFrom1xBitmap(scaled_bitmap)); + std::move(callback).Run(gfx::Image::CreateFrom1xBitmap(scaled_bitmap)); } SkBitmap ScaleBitmap(const SkBitmap& input_bitmap, @@ -35,12 +35,12 @@ } // namespace void SnapshotAsync::ScaleCopyOutputResult( - const GrabWindowSnapshotAsyncCallback& callback, + GrabWindowSnapshotAsyncCallback callback, const gfx::Size& target_size, std::unique_ptr<viz::CopyOutputResult> result) { const SkBitmap bitmap = result->AsSkBitmap(); if (!bitmap.readyToDraw()) { - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); return; } @@ -51,19 +51,19 @@ base::PostTaskAndReplyWithResult( FROM_HERE, {base::ThreadPool(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, - base::Bind(ScaleBitmap, bitmap, target_size), - base::Bind(&OnFrameScalingFinished, callback)); + base::BindOnce(ScaleBitmap, bitmap, target_size), + base::BindOnce(&OnFrameScalingFinished, std::move(callback))); } void SnapshotAsync::RunCallbackWithCopyOutputResult( - const GrabWindowSnapshotAsyncCallback& callback, + GrabWindowSnapshotAsyncCallback callback, std::unique_ptr<viz::CopyOutputResult> result) { const SkBitmap bitmap = result->AsSkBitmap(); if (!bitmap.readyToDraw()) { - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); return; } - callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap)); + std::move(callback).Run(gfx::Image::CreateFrom1xBitmap(bitmap)); } } // namespace ui
diff --git a/ui/snapshot/snapshot_async.h b/ui/snapshot/snapshot_async.h index d45d102..951055a4 100644 --- a/ui/snapshot/snapshot_async.h +++ b/ui/snapshot/snapshot_async.h
@@ -22,12 +22,12 @@ class SnapshotAsync { public: static void ScaleCopyOutputResult( - const GrabWindowSnapshotAsyncCallback& callback, + GrabWindowSnapshotAsyncCallback callback, const gfx::Size& target_size, std::unique_ptr<viz::CopyOutputResult> result); static void RunCallbackWithCopyOutputResult( - const GrabWindowSnapshotAsyncCallback& callback, + GrabWindowSnapshotAsyncCallback callback, std::unique_ptr<viz::CopyOutputResult> result); private:
diff --git a/ui/snapshot/snapshot_aura.cc b/ui/snapshot/snapshot_aura.cc index a5b80a03..38d18b2 100644 --- a/ui/snapshot/snapshot_aura.cc +++ b/ui/snapshot/snapshot_aura.cc
@@ -82,21 +82,20 @@ aura::Window* window, const gfx::Rect& source_rect, const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { MakeInitialAsyncCopyRequest( window, source_rect, - base::BindOnce(&SnapshotAsync::ScaleCopyOutputResult, callback, + base::BindOnce(&SnapshotAsync::ScaleCopyOutputResult, std::move(callback), target_size)); } -void GrabWindowSnapshotAsyncAura( - aura::Window* window, - const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { +void GrabWindowSnapshotAsyncAura(aura::Window* window, + const gfx::Rect& source_rect, + GrabWindowSnapshotAsyncCallback callback) { MakeInitialAsyncCopyRequest( window, source_rect, base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult, - callback)); + std::move(callback))); } #if !defined(OS_WIN) @@ -113,34 +112,33 @@ return GrabWindowSnapshot(view, snapshot_bounds, image); } -void GrabWindowSnapshotAndScaleAsync( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback) { +void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window, + const gfx::Rect& source_rect, + const gfx::Size& target_size, + GrabWindowSnapshotAsyncCallback callback) { GrabWindowSnapshotAndScaleAsyncAura(window, source_rect, target_size, - callback); + std::move(callback)); } void GrabWindowSnapshotAsync(gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { - GrabWindowSnapshotAsyncAura(window, source_rect, callback); + GrabWindowSnapshotAsyncCallback callback) { + GrabWindowSnapshotAsyncAura(window, source_rect, std::move(callback)); } void GrabViewSnapshotAsync(gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { - GrabWindowSnapshotAsyncAura(view, source_rect, callback); + GrabWindowSnapshotAsyncCallback callback) { + GrabWindowSnapshotAsyncAura(view, source_rect, std::move(callback)); } void GrabLayerSnapshotAsync(ui::Layer* layer, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { MakeAsyncCopyRequest( layer, source_rect, base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult, - callback)); + std::move(callback))); } #endif
diff --git a/ui/snapshot/snapshot_aura.h b/ui/snapshot/snapshot_aura.h index 8a388a8..e5cfcef 100644 --- a/ui/snapshot/snapshot_aura.h +++ b/ui/snapshot/snapshot_aura.h
@@ -19,19 +19,19 @@ aura::Window* window, const gfx::Rect& source_rect, const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncAura( aura::Window* window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); // Grabs a snapshot of a |layer| and all its descendants. // |source_rect| is the bounds of the snapshot content relative to |layer|. SNAPSHOT_EXPORT void GrabLayerSnapshotAsync( Layer* layer, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback); + GrabWindowSnapshotAsyncCallback callback); } // namespace ui
diff --git a/ui/snapshot/snapshot_aura_unittest.cc b/ui/snapshot/snapshot_aura_unittest.cc index 143e2d7..93afad6 100644 --- a/ui/snapshot/snapshot_aura_unittest.cc +++ b/ui/snapshot/snapshot_aura_unittest.cc
@@ -152,7 +152,7 @@ scoped_refptr<SnapshotHolder> holder(new SnapshotHolder); ui::GrabWindowSnapshotAsync( root_window(), source_rect, - base::Bind(&SnapshotHolder::SnapshotCallback, holder)); + base::BindOnce(&SnapshotHolder::SnapshotCallback, holder)); holder->WaitForSnapshot(); DCHECK(holder->completed());
diff --git a/ui/snapshot/snapshot_ios.mm b/ui/snapshot/snapshot_ios.mm index b0c57e8..1ff4e657 100644 --- a/ui/snapshot/snapshot_ios.mm +++ b/ui/snapshot/snapshot_ios.mm
@@ -29,19 +29,19 @@ const gfx::Rect& snapshot_bounds, const gfx::Size& target_size, GrabWindowSnapshotAsyncCallback callback) { - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); } void GrabViewSnapshotAsync(gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { - callback.Run(gfx::Image()); + GrabWindowSnapshotAsyncCallback callback) { + std::move(callback).Run(gfx::Image()); } void GrabWindowSnapshotAsync(gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { - callback.Run(gfx::Image()); + GrabWindowSnapshotAsyncCallback callback) { + std::move(callback).Run(gfx::Image()); } } // namespace ui
diff --git a/ui/snapshot/snapshot_mac.mm b/ui/snapshot/snapshot_mac.mm index 5eb36bc..805b4ed 100644 --- a/ui/snapshot/snapshot_mac.mm +++ b/ui/snapshot/snapshot_mac.mm
@@ -71,21 +71,21 @@ const gfx::Rect& snapshot_bounds, const gfx::Size& target_size, GrabWindowSnapshotAsyncCallback callback) { - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); } void GrabViewSnapshotAsync(gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { - callback.Run(gfx::Image()); + GrabWindowSnapshotAsyncCallback callback) { + std::move(callback).Run(gfx::Image()); } void GrabWindowSnapshotAsync(gfx::NativeWindow native_window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { NSWindow* window = native_window.GetNativeNSWindow(); return GrabViewSnapshotAsync([[window contentView] superview], source_rect, - callback); + std::move(callback)); } } // namespace ui
diff --git a/ui/snapshot/snapshot_win.cc b/ui/snapshot/snapshot_win.cc index 57fcf1d..27d99532 100644 --- a/ui/snapshot/snapshot_win.cc +++ b/ui/snapshot/snapshot_win.cc
@@ -125,39 +125,38 @@ void GrabWindowSnapshotAsync(gfx::NativeWindow window, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { if (UseAuraSnapshot()) { - GrabWindowSnapshotAsyncAura(window, source_rect, callback); + GrabWindowSnapshotAsyncAura(window, source_rect, std::move(callback)); return; } gfx::Image image; GrabWindowSnapshot(window, source_rect, &image); - callback.Run(image); + std::move(callback).Run(image); } void GrabViewSnapshotAsync(gfx::NativeView view, const gfx::Rect& source_rect, - const GrabWindowSnapshotAsyncCallback& callback) { + GrabWindowSnapshotAsyncCallback callback) { if (UseAuraSnapshot()) { - GrabWindowSnapshotAsyncAura(view, source_rect, callback); + GrabWindowSnapshotAsyncAura(view, source_rect, std::move(callback)); return; } NOTIMPLEMENTED(); - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); } -void GrabWindowSnapshotAndScaleAsync( - gfx::NativeWindow window, - const gfx::Rect& source_rect, - const gfx::Size& target_size, - const GrabWindowSnapshotAsyncCallback& callback) { +void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window, + const gfx::Rect& source_rect, + const gfx::Size& target_size, + GrabWindowSnapshotAsyncCallback callback) { if (UseAuraSnapshot()) { GrabWindowSnapshotAndScaleAsyncAura(window, source_rect, target_size, - callback); + std::move(callback)); return; } NOTIMPLEMENTED(); - callback.Run(gfx::Image()); + std::move(callback).Run(gfx::Image()); } } // namespace ui
diff --git a/ui/snapshot/test/run_all_unittests.cc b/ui/snapshot/test/run_all_unittests.cc index 9c1aceb..eb5575e 100644 --- a/ui/snapshot/test/run_all_unittests.cc +++ b/ui/snapshot/test/run_all_unittests.cc
@@ -22,6 +22,6 @@ base::TestSuite test_suite(argc, argv); return base::LaunchUnitTests( argc, argv, - base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); + base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); #endif }
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java index 587f599d..05ddedf 100644 --- a/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java +++ b/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java
@@ -6,17 +6,14 @@ import android.content.Context; import android.os.IBinder; -import android.util.AndroidRuntimeException; import android.webkit.ValueCallback; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; -import org.chromium.base.Log; import org.chromium.base.PathUtils; import org.chromium.base.annotations.UsedByReflection; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; -import org.chromium.base.library_loader.ProcessInitException; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.ChildProcessCreationParams; import org.chromium.content_public.browser.DeviceUtils; @@ -66,45 +63,29 @@ DeviceUtils.addDeviceSpecificUserAgentSwitch(); - try { - LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_WEBLAYER); - } catch (ProcessInitException e) { - Log.e(TAG, "ContentView initialization failed.", e); - throw new AndroidRuntimeException(e); - } + LibraryLoader.getInstance().ensureInitialized(LibraryProcessType.PROCESS_WEBLAYER); - try { - final ValueCallback<Boolean> loadedCallback = - (ValueCallback<Boolean>) ObjectWrapper.unwrap( - loadedCallbackWrapper, ValueCallback.class); - BrowserStartupController.get(LibraryProcessType.PROCESS_WEBLAYER) - .startBrowserProcessesAsync(/* startGpu */ false, - /* startServiceManagerOnly */ false, - new BrowserStartupController.StartupCallback() { - @Override - public void onSuccess() { - loadedCallback.onReceiveValue(true); - } - @Override - public void onFailure() { - loadedCallback.onReceiveValue(false); - } - }); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - throw new AndroidRuntimeException(e); - } + final ValueCallback<Boolean> loadedCallback = (ValueCallback<Boolean>) ObjectWrapper.unwrap( + loadedCallbackWrapper, ValueCallback.class); + BrowserStartupController.get(LibraryProcessType.PROCESS_WEBLAYER) + .startBrowserProcessesAsync(/* startGpu */ false, + /* startServiceManagerOnly */ false, + new BrowserStartupController.StartupCallback() { + @Override + public void onSuccess() { + loadedCallback.onReceiveValue(true); + } + @Override + public void onFailure() { + loadedCallback.onReceiveValue(false); + } + }); } @Override public void loadSync() { - try { - BrowserStartupController.get(LibraryProcessType.PROCESS_WEBLAYER) - .startBrowserProcessesSync( - /* singleProcess*/ false); - } catch (ProcessInitException e) { - Log.e(TAG, "Unable to load native library.", e); - throw new AndroidRuntimeException(e); - } + BrowserStartupController.get(LibraryProcessType.PROCESS_WEBLAYER) + .startBrowserProcessesSync( + /* singleProcess*/ false); } }