chore: migrate base::StringPiece to std::string_view (#40915)

* chore: migrate from base::StringPiece to std::string_view in keyboard_util.cc

* chore: migrate from base::StringPiece to std::string_view in error_thrower.cc

* chore: migrate from base::StringPiece to std::string_view in electron_api_web_contents.cc

* chore: migrate from base::StringPiece to std::string_view in gin_helper/dictionary.h

* chore: migrate from base::StringPiece to std::string_view in electron_api_url_loader.cc

* chore: phase out internal use of base:::StringPiece

`base::StringPiece` is being phased out upstream. Its code has been
removed upstream and it's just a typedef for `std::string_view`.

They haven't removed the typedef yet, so this PR tries to get ahead
of future breakage by migrating "internal" use (i.e. leaving alone the
places where the `base::StringPiece` name is coming from an upstream
method that we override).

Xref: https://bugs.chromium.org/p/chromium/issues/detail?id=691162

Xref: https://chromium-review.googlesource.com/c/chromium/src/+/4294483

Xref: https://docs.google.com/document/d/1d4RnD1uAE2t4iANR0nXy82ASIPGsPuw2mpO6v6T7JKs
This commit is contained in:
Charles Kerr 2024-01-10 19:00:37 -06:00 committed by GitHub
parent 892c9d78a3
commit f36ceae024
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
45 changed files with 223 additions and 174 deletions

View file

@ -5,6 +5,7 @@
#include "shell/app/electron_content_client.h" #include "shell/app/electron_content_client.h"
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -106,12 +107,12 @@ bool IsWidevineAvailable(
} }
#endif // BUILDFLAG(ENABLE_WIDEVINE) #endif // BUILDFLAG(ENABLE_WIDEVINE)
void AppendDelimitedSwitchToVector(const base::StringPiece cmd_switch, void AppendDelimitedSwitchToVector(const std::string_view cmd_switch,
std::vector<std::string>* append_me) { std::vector<std::string>* append_me) {
auto* command_line = base::CommandLine::ForCurrentProcess(); auto* command_line = base::CommandLine::ForCurrentProcess();
auto switch_value = command_line->GetSwitchValueASCII(cmd_switch); auto switch_value = command_line->GetSwitchValueASCII(cmd_switch);
if (!switch_value.empty()) { if (!switch_value.empty()) {
constexpr base::StringPiece delimiter(",", 1); constexpr std::string_view delimiter{",", 1};
auto tokens = auto tokens =
base::SplitString(switch_value, delimiter, base::TRIM_WHITESPACE, base::SplitString(switch_value, delimiter, base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY); base::SPLIT_WANT_NONEMPTY);

View file

@ -7,6 +7,7 @@
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include "base/apple/bundle_locations.h" #include "base/apple/bundle_locations.h"
@ -80,9 +81,9 @@ namespace {
const char kRelauncherProcess[] = "relauncher"; const char kRelauncherProcess[] = "relauncher";
constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX"); constexpr std::string_view kElectronDisableSandbox{"ELECTRON_DISABLE_SANDBOX"};
constexpr base::StringPiece kElectronEnableStackDumping( constexpr std::string_view kElectronEnableStackDumping{
"ELECTRON_ENABLE_STACK_DUMPING"); "ELECTRON_ENABLE_STACK_DUMPING"};
// Returns true if this subprocess type needs the ResourceBundle initialized // Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded. // and resources loaded.

View file

@ -7,6 +7,7 @@
#include <map> #include <map>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -60,7 +61,7 @@ namespace {
// See https://nodejs.org/api/cli.html#cli_options // See https://nodejs.org/api/cli.html#cli_options
void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) { void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
// Options that are unilaterally disallowed. // Options that are unilaterally disallowed.
static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({
"--enable-fips", "--enable-fips",
"--force-fips", "--force-fips",
"--openssl-config", "--openssl-config",
@ -69,7 +70,7 @@ void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
}); });
for (const auto& arg : argv) { for (const auto& arg : argv) {
const auto key = base::StringPiece(arg).substr(0, arg.find('=')); const auto key = std::string_view{arg}.substr(0, arg.find('='));
if (disallowed.contains(key)) { if (disallowed.contains(key)) {
LOG(ERROR) << "The Node.js cli flag " << key LOG(ERROR) << "The Node.js cli flag " << key
<< " is not supported in Electron"; << " is not supported in Electron";

View file

@ -7,6 +7,7 @@
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -157,7 +158,7 @@ struct Converter<JumpListItem::Type> {
private: private:
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, JumpListItem::Type>({ base::MakeFixedFlatMap<std::string_view, JumpListItem::Type>({
{"file", JumpListItem::Type::kFile}, {"file", JumpListItem::Type::kFile},
{"separator", JumpListItem::Type::kSeparator}, {"separator", JumpListItem::Type::kSeparator},
{"task", JumpListItem::Type::kTask}, {"task", JumpListItem::Type::kTask},
@ -248,7 +249,7 @@ struct Converter<JumpListCategory::Type> {
private: private:
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, JumpListCategory::Type>({ base::MakeFixedFlatMap<std::string_view, JumpListCategory::Type>({
{"custom", JumpListCategory::Type::kCustom}, {"custom", JumpListCategory::Type::kCustom},
{"frequent", JumpListCategory::Type::kFrequent}, {"frequent", JumpListCategory::Type::kFrequent},
{"recent", JumpListCategory::Type::kRecent}, {"recent", JumpListCategory::Type::kRecent},
@ -414,7 +415,7 @@ struct Converter<net::SecureDnsMode> {
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
net::SecureDnsMode* out) { net::SecureDnsMode* out) {
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, net::SecureDnsMode>({ base::MakeFixedFlatMap<std::string_view, net::SecureDnsMode>({
{"automatic", net::SecureDnsMode::kAutomatic}, {"automatic", net::SecureDnsMode::kAutomatic},
{"off", net::SecureDnsMode::kOff}, {"off", net::SecureDnsMode::kOff},
{"secure", net::SecureDnsMode::kSecure}, {"secure", net::SecureDnsMode::kSecure},
@ -440,9 +441,9 @@ IconLoader::IconSize GetIconSizeByString(const std::string& size) {
} }
// Return the path constant from string. // Return the path constant from string.
int GetPathConstant(base::StringPiece name) { int GetPathConstant(std::string_view name) {
// clang-format off // clang-format off
constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, int>({ constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({
{"appData", DIR_APP_DATA}, {"appData", DIR_APP_DATA},
#if BUILDFLAG(IS_POSIX) #if BUILDFLAG(IS_POSIX)
{"cache", base::DIR_CACHE}, {"cache", base::DIR_CACHE},

View file

@ -9,6 +9,7 @@
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view>
#include <vector> #include <vector>
#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_task_traits.h"
@ -249,7 +250,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
void RemoveFromParentChildWindows(); void RemoveFromParentChildWindows();
template <typename... Args> template <typename... Args>
void EmitEventSoon(base::StringPiece eventName) { void EmitEventSoon(std::string_view eventName) {
content::GetUIThreadTaskRunner({})->PostTask( content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, FROM_HERE,
base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>),

View file

@ -4,6 +4,8 @@
#include "shell/browser/api/electron_api_cookies.h" #include "shell/browser/api/electron_api_cookies.h"
#include <string>
#include <string_view>
#include <utility> #include <utility>
#include "base/time/time.h" #include "base/time/time.h"
@ -169,7 +171,7 @@ base::Time ParseTimeProperty(const std::optional<double>& value) {
return base::Time::FromSecondsSinceUnixEpoch(*value); return base::Time::FromSecondsSinceUnixEpoch(*value);
} }
base::StringPiece InclusionStatusToString(net::CookieInclusionStatus status) { std::string_view InclusionStatusToString(net::CookieInclusionStatus status) {
if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY)) if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY))
return "Failed to create httponly cookie"; return "Failed to create httponly cookie";
if (status.HasExclusionReason( if (status.HasExclusionReason(

View file

@ -4,6 +4,7 @@
#include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_protocol.h"
#include <string_view>
#include <vector> #include <vector>
#include "base/command_line.h" #include "base/command_line.h"
@ -193,7 +194,7 @@ const char* const kBuiltinSchemes[] = {
}; };
// Convert error code to string. // Convert error code to string.
constexpr base::StringPiece ErrorCodeToString(ProtocolError error) { constexpr std::string_view ErrorCodeToString(ProtocolError error) {
switch (error) { switch (error) {
case ProtocolError::kRegistered: case ProtocolError::kRegistered:
return "The scheme has been registered"; return "The scheme has been registered";

View file

@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_screen.h" #include "shell/browser/api/electron_api_screen.h"
#include <string> #include <string>
#include <string_view>
#include "base/functional/bind.h" #include "base/functional/bind.h"
#include "gin/dictionary.h" #include "gin/dictionary.h"
@ -49,13 +50,13 @@ std::vector<std::string> MetricsToArray(uint32_t metrics) {
} }
void DelayEmit(Screen* screen, void DelayEmit(Screen* screen,
base::StringPiece name, const std::string_view name,
const display::Display& display) { const display::Display& display) {
screen->Emit(name, display); screen->Emit(name, display);
} }
void DelayEmitWithMetrics(Screen* screen, void DelayEmitWithMetrics(Screen* screen,
base::StringPiece name, const std::string_view name,
const display::Display& display, const display::Display& display,
const std::vector<std::string>& metrics) { const std::vector<std::string>& metrics) {
screen->Emit(name, display, metrics); screen->Emit(name, display, metrics);

View file

@ -4,6 +4,7 @@
#include "shell/browser/api/electron_api_service_worker_context.h" #include "shell/browser/api/electron_api_service_worker_context.h"
#include <string_view>
#include <utility> #include <utility>
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
@ -24,7 +25,7 @@ namespace electron::api {
namespace { namespace {
constexpr base::StringPiece MessageSourceToString( constexpr std::string_view MessageSourceToString(
const blink::mojom::ConsoleMessageSource source) { const blink::mojom::ConsoleMessageSource source) {
switch (source) { switch (source) {
case blink::mojom::ConsoleMessageSource::kXml: case blink::mojom::ConsoleMessageSource::kXml:

View file

@ -2,10 +2,12 @@
// Use of this source code is governed by the MIT license that can be // Use of this source code is governed by the MIT license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include <iomanip>
#include <string_view>
#include <dwmapi.h> #include <dwmapi.h>
#include <windows.devices.enumeration.h> #include <windows.devices.enumeration.h>
#include <wrl/client.h> #include <wrl/client.h>
#include <iomanip>
#include "shell/browser/api/electron_api_system_preferences.h" #include "shell/browser/api/electron_api_system_preferences.h"
@ -98,39 +100,38 @@ std::string SystemPreferences::GetAccentColor() {
std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower, std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower,
const std::string& color) { const std::string& color) {
static constexpr auto Lookup = static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({
base::MakeFixedFlatMap<base::StringPiece, int>({ {"3d-dark-shadow", COLOR_3DDKSHADOW},
{"3d-dark-shadow", COLOR_3DDKSHADOW}, {"3d-face", COLOR_3DFACE},
{"3d-face", COLOR_3DFACE}, {"3d-highlight", COLOR_3DHIGHLIGHT},
{"3d-highlight", COLOR_3DHIGHLIGHT}, {"3d-light", COLOR_3DLIGHT},
{"3d-light", COLOR_3DLIGHT}, {"3d-shadow", COLOR_3DSHADOW},
{"3d-shadow", COLOR_3DSHADOW}, {"active-border", COLOR_ACTIVEBORDER},
{"active-border", COLOR_ACTIVEBORDER}, {"active-caption", COLOR_ACTIVECAPTION},
{"active-caption", COLOR_ACTIVECAPTION}, {"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION},
{"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION}, {"app-workspace", COLOR_APPWORKSPACE},
{"app-workspace", COLOR_APPWORKSPACE}, {"button-text", COLOR_BTNTEXT},
{"button-text", COLOR_BTNTEXT}, {"caption-text", COLOR_CAPTIONTEXT},
{"caption-text", COLOR_CAPTIONTEXT}, {"desktop", COLOR_DESKTOP},
{"desktop", COLOR_DESKTOP}, {"disabled-text", COLOR_GRAYTEXT},
{"disabled-text", COLOR_GRAYTEXT}, {"highlight", COLOR_HIGHLIGHT},
{"highlight", COLOR_HIGHLIGHT}, {"highlight-text", COLOR_HIGHLIGHTTEXT},
{"highlight-text", COLOR_HIGHLIGHTTEXT}, {"hotlight", COLOR_HOTLIGHT},
{"hotlight", COLOR_HOTLIGHT}, {"inactive-border", COLOR_INACTIVEBORDER},
{"inactive-border", COLOR_INACTIVEBORDER}, {"inactive-caption", COLOR_INACTIVECAPTION},
{"inactive-caption", COLOR_INACTIVECAPTION}, {"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION},
{"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION}, {"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT},
{"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT}, {"info-background", COLOR_INFOBK},
{"info-background", COLOR_INFOBK}, {"info-text", COLOR_INFOTEXT},
{"info-text", COLOR_INFOTEXT}, {"menu", COLOR_MENU},
{"menu", COLOR_MENU}, {"menu-highlight", COLOR_MENUHILIGHT},
{"menu-highlight", COLOR_MENUHILIGHT}, {"menu-text", COLOR_MENUTEXT},
{"menu-text", COLOR_MENUTEXT}, {"menubar", COLOR_MENUBAR},
{"menubar", COLOR_MENUBAR}, {"scrollbar", COLOR_SCROLLBAR},
{"scrollbar", COLOR_SCROLLBAR}, {"window", COLOR_WINDOW},
{"window", COLOR_WINDOW}, {"window-frame", COLOR_WINDOWFRAME},
{"window-frame", COLOR_WINDOWFRAME}, {"window-text", COLOR_WINDOWTEXT},
{"window-text", COLOR_WINDOWTEXT}, });
});
if (const auto* iter = Lookup.find(color); iter != Lookup.end()) if (const auto* iter = Lookup.find(color); iter != Lookup.end())
return ToRGBAHex(color_utils::GetSysSkColor(iter->second)); return ToRGBAHex(color_utils::GetSysSkColor(iter->second));

View file

@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_tray.h" #include "shell/browser/api/electron_api_tray.h"
#include <string> #include <string>
#include <string_view>
#include "base/containers/fixed_flat_map.h" #include "base/containers/fixed_flat_map.h"
#include "gin/dictionary.h" #include "gin/dictionary.h"
@ -32,7 +33,7 @@ struct Converter<electron::TrayIcon::IconType> {
electron::TrayIcon::IconType* out) { electron::TrayIcon::IconType* out) {
using Val = electron::TrayIcon::IconType; using Val = electron::TrayIcon::IconType;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"custom", Val::kCustom}, {"custom", Val::kCustom},
{"error", Val::kError}, {"error", Val::kError},
{"info", Val::kInfo}, {"info", Val::kInfo},

View file

@ -9,6 +9,7 @@
#include <optional> #include <optional>
#include <set> #include <set>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -205,7 +206,7 @@ struct Converter<printing::mojom::MarginType> {
printing::mojom::MarginType* out) { printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType; using Val = printing::mojom::MarginType;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"custom", Val::kCustomMargins}, {"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins}, {"default", Val::kDefaultMargins},
{"none", Val::kNoMargins}, {"none", Val::kNoMargins},
@ -222,7 +223,7 @@ struct Converter<printing::mojom::DuplexMode> {
printing::mojom::DuplexMode* out) { printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode; using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"longEdge", Val::kLongEdge}, {"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge}, {"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex}, {"simplex", Val::kSimplex},
@ -284,7 +285,7 @@ struct Converter<content::SavePageType> {
content::SavePageType* out) { content::SavePageType* out) {
using Val = content::SavePageType; using Val = content::SavePageType;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML}, {"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML}, {"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML}, {"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
@ -329,7 +330,7 @@ struct Converter<electron::api::WebContents::Type> {
electron::api::WebContents::Type* out) { electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type; using Val = electron::api::WebContents::Type;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"backgroundPage", Val::kBackgroundPage}, {"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView}, {"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen}, {"offscreen", Val::kOffScreen},
@ -357,7 +358,7 @@ namespace electron::api {
namespace { namespace {
constexpr base::StringPiece CursorTypeToString( constexpr std::string_view CursorTypeToString(
ui::mojom::CursorType cursor_type) { ui::mojom::CursorType cursor_type) {
switch (cursor_type) { switch (cursor_type) {
case ui::mojom::CursorType::kPointer: case ui::mojom::CursorType::kPointer:

View file

@ -9,6 +9,7 @@
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -371,7 +372,7 @@ class WebContents : public ExclusiveAccessContext,
// this.emit(name, new Event(sender, message), args...); // this.emit(name, new Event(sender, message), args...);
template <typename... Args> template <typename... Args>
bool EmitWithSender(base::StringPiece name, bool EmitWithSender(const std::string_view name,
content::RenderFrameHost* frame, content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback, electron::mojom::ElectronApiIPC::InvokeCallback callback,
Args&&... args) { Args&&... args) {

View file

@ -6,6 +6,7 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include "base/containers/contains.h" #include "base/containers/contains.h"
@ -33,7 +34,7 @@
#include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/dictionary.h"
static constexpr auto ResourceTypes = static constexpr auto ResourceTypes =
base::MakeFixedFlatMap<base::StringPiece, base::MakeFixedFlatMap<std::string_view,
extensions::WebRequestResourceType>({ extensions::WebRequestResourceType>({
{"cspReport", extensions::WebRequestResourceType::CSP_REPORT}, {"cspReport", extensions::WebRequestResourceType::CSP_REPORT},
{"font", extensions::WebRequestResourceType::FONT}, {"font", extensions::WebRequestResourceType::FONT},
@ -77,7 +78,7 @@ struct UserData : public base::SupportsUserData::Data {
raw_ptr<WebRequest> data; raw_ptr<WebRequest> data;
}; };
extensions::WebRequestResourceType ParseResourceType(base::StringPiece value) { extensions::WebRequestResourceType ParseResourceType(std::string_view value) {
if (const auto* iter = ResourceTypes.find(value); iter != ResourceTypes.end()) if (const auto* iter = ResourceTypes.find(value); iter != ResourceTypes.end())
return iter->second; return iter->second;

View file

@ -4,6 +4,8 @@
#include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_browser_main_parts.h"
#include <string_view>
#include "base/command_line.h" #include "base/command_line.h"
#include "base/environment.h" #include "base/environment.h"
#include "ui/base/ozone_buildflags.h" #include "ui/base/ozone_buildflags.h"
@ -16,8 +18,8 @@
#include "shell/common/thread_restrictions.h" #include "shell/common/thread_restrictions.h"
#endif #endif
constexpr base::StringPiece kElectronOzonePlatformHint( constexpr std::string_view kElectronOzonePlatformHint{
"ELECTRON_OZONE_PLATFORM_HINT"); "ELECTRON_OZONE_PLATFORM_HINT"};
#if BUILDFLAG(IS_OZONE_WAYLAND) #if BUILDFLAG(IS_OZONE_WAYLAND)

View file

@ -5,6 +5,7 @@
#ifndef ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_ #ifndef ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_
#define ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_ #define ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_
#include <string_view>
#include <utility> #include <utility>
#include "gin/handle.h" #include "gin/handle.h"
@ -25,7 +26,7 @@ class EventEmitterMixin {
// this.emit(name, new Event(), args...); // this.emit(name, new Event(), args...);
// Returns true if event.preventDefault() was called during processing. // Returns true if event.preventDefault() was called during processing.
template <typename... Args> template <typename... Args>
bool Emit(base::StringPiece name, Args&&... args) { bool Emit(const std::string_view name, Args&&... args) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate); v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper; v8::Local<v8::Object> wrapper;
@ -39,7 +40,7 @@ class EventEmitterMixin {
// this.emit(name, args...); // this.emit(name, args...);
template <typename... Args> template <typename... Args>
void EmitWithoutEvent(base::StringPiece name, Args&&... args) { void EmitWithoutEvent(const std::string_view name, Args&&... args) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate); v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper; v8::Local<v8::Object> wrapper;

View file

@ -6,6 +6,7 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include "base/files/file_path.h" #include "base/files/file_path.h"
@ -93,7 +94,7 @@ void ElectronExtensionSystem::InitForRegularProfile(bool extensions_enabled) {
} }
std::unique_ptr<base::Value::Dict> ParseManifest( std::unique_ptr<base::Value::Dict> ParseManifest(
base::StringPiece manifest_contents) { const std::string_view manifest_contents) {
JSONStringValueDeserializer deserializer(manifest_contents); JSONStringValueDeserializer deserializer(manifest_contents);
std::unique_ptr<base::Value> manifest = std::unique_ptr<base::Value> manifest =
deserializer.Deserialize(nullptr, nullptr); deserializer.Deserialize(nullptr, nullptr);

View file

@ -6,6 +6,10 @@
#include <utility> #include <utility>
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include <string_view>
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/command_line.h" #include "base/command_line.h"
#include "base/containers/contains.h" #include "base/containers/contains.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
@ -33,7 +37,6 @@
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/containers/fixed_flat_set.h" #include "base/containers/fixed_flat_set.h"
#include "base/strings/string_piece.h"
#include "extensions/common/constants.h" #include "extensions/common/constants.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
@ -189,7 +192,7 @@ bool HidChooserContext::HasDevicePermission(
bool HidChooserContext::IsFidoAllowedForOrigin(const url::Origin& origin) { bool HidChooserContext::IsFidoAllowedForOrigin(const url::Origin& origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
static constexpr auto kPrivilegedExtensionIds = static constexpr auto kPrivilegedExtensionIds =
base::MakeFixedFlatSet<base::StringPiece>({ base::MakeFixedFlatSet<std::string_view>({
"ckcendljdlmgnhghiaomidhiiclmapok", // gnubbyd-v3 dev "ckcendljdlmgnhghiaomidhiiclmapok", // gnubbyd-v3 dev
"lfboplenmmjcmpbkeemecobbadnmpfhi", // gnubbyd-v3 prod "lfboplenmmjcmpbkeemecobbadnmpfhi", // gnubbyd-v3 prod
}); });

View file

@ -7,6 +7,7 @@
#include <list> #include <list>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include "base/containers/fixed_flat_map.h" #include "base/containers/fixed_flat_map.h"
@ -48,7 +49,7 @@ struct Converter<electron::ProtocolType> {
electron::ProtocolType* out) { electron::ProtocolType* out) {
using Val = electron::ProtocolType; using Val = electron::ProtocolType;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
// note "free" is internal type, not allowed to be passed from user // note "free" is internal type, not allowed to be passed from user
{"buffer", Val::kBuffer}, {"buffer", Val::kBuffer},
{"file", Val::kFile}, {"file", Val::kFile},

View file

@ -4,6 +4,7 @@
#include "shell/browser/net/node_stream_loader.h" #include "shell/browser/net/node_stream_loader.h"
#include <string_view>
#include <utility> #include <utility>
#include "mojo/public/cpp/system/string_data_source.h" #include "mojo/public/cpp/system/string_data_source.h"
@ -135,8 +136,8 @@ void NodeStreamLoader::ReadMore() {
is_reading_ = false; is_reading_ = false;
is_writing_ = true; is_writing_ = true;
producer_->Write(std::make_unique<mojo::StringDataSource>( producer_->Write(std::make_unique<mojo::StringDataSource>(
base::StringPiece(node::Buffer::Data(buffer), std::string_view{node::Buffer::Data(buffer),
node::Buffer::Length(buffer)), node::Buffer::Length(buffer)},
mojo::StringDataSource::AsyncWritingMode:: mojo::StringDataSource::AsyncWritingMode::
STRING_STAYS_VALID_UNTIL_COMPLETION), STRING_STAYS_VALID_UNTIL_COMPLETION),
base::BindOnce(&NodeStreamLoader::DidWrite, weak)); base::BindOnce(&NodeStreamLoader::DidWrite, weak));

View file

@ -5,6 +5,7 @@
#include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/file_dialog.h"
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -441,7 +442,7 @@ void SaveDialogCompletion(int chosen,
dict.Set("canceled", true); dict.Set("canceled", true);
dict.Set("filePath", base::FilePath()); dict.Set("filePath", base::FilePath());
#if IS_MAS_BUILD() #if IS_MAS_BUILD()
dict.Set("bookmark", base::StringPiece()); dict.Set("bookmark", std::string_view{});
#endif #endif
} else { } else {
std::string path = base::SysNSStringToUTF8([[dialog URL] path]); std::string path = base::SysNSStringToUTF8([[dialog URL] path]);

View file

@ -6,6 +6,7 @@
#include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents.h"
#include <memory> #include <memory>
#include <string_view>
#include <utility> #include <utility>
#include "base/base64.h" #include "base/base64.h"
@ -959,8 +960,8 @@ void InspectableWebContents::DispatchProtocolMessage(
if (!frontend_loaded_) if (!frontend_loaded_)
return; return;
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), const std::string_view str_message{
message.size()); reinterpret_cast<const char*>(message.data()), message.size()};
if (str_message.length() < kMaxMessageChunkSize) { if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage", CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message))); base::Value(std::string(str_message)));

View file

@ -4,6 +4,7 @@
#include "shell/browser/usb/electron_usb_delegate.h" #include "shell/browser/usb/electron_usb_delegate.h"
#include <string_view>
#include <utility> #include <utility>
#include "base/containers/contains.h" #include "base/containers/contains.h"
@ -45,7 +46,7 @@ electron::UsbChooserContext* GetChooserContext(
// These extensions can claim the smart card USB class and automatically gain // These extensions can claim the smart card USB class and automatically gain
// permissions for devices that have an interface with this class. // permissions for devices that have an interface with this class.
constexpr auto kSmartCardPrivilegedExtensionIds = constexpr auto kSmartCardPrivilegedExtensionIds =
base::MakeFixedFlatSet<base::StringPiece>({ base::MakeFixedFlatSet<std::string_view>({
// Smart Card Connector Extension and its Beta version, see // Smart Card Connector Extension and its Beta version, see
// crbug.com/1233881. // crbug.com/1233881.
"khpfeaanjngmcnplbdlpegiifgpfgdco", "khpfeaanjngmcnplbdlpegiifgpfgdco",

View file

@ -4,6 +4,7 @@
#include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_permission_helper.h"
#include <string_view>
#include <utility> #include <utility>
#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_context.h"
@ -17,7 +18,7 @@
namespace { namespace {
constexpr base::StringPiece MediaStreamTypeToString( constexpr std::string_view MediaStreamTypeToString(
blink::mojom::MediaStreamType type) { blink::mojom::MediaStreamType type) {
switch (type) { switch (type) {
case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE: case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE:

View file

@ -6,6 +6,7 @@
#include <algorithm> #include <algorithm>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -46,7 +47,7 @@ struct Converter<blink::mojom::AutoplayPolicy> {
blink::mojom::AutoplayPolicy* out) { blink::mojom::AutoplayPolicy* out) {
using Val = blink::mojom::AutoplayPolicy; using Val = blink::mojom::AutoplayPolicy;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"document-user-activation-required", {"document-user-activation-required",
Val::kDocumentUserActivationRequired}, Val::kDocumentUserActivationRequired},
{"no-user-gesture-required", Val::kNoUserGestureRequired}, {"no-user-gesture-required", Val::kNoUserGestureRequired},
@ -63,7 +64,7 @@ struct Converter<blink::mojom::V8CacheOptions> {
blink::mojom::V8CacheOptions* out) { blink::mojom::V8CacheOptions* out) {
using Val = blink::mojom::V8CacheOptions; using Val = blink::mojom::V8CacheOptions;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"bypassHeatCheck", Val::kCodeWithoutHeatCheck}, {"bypassHeatCheck", Val::kCodeWithoutHeatCheck},
{"bypassHeatCheckAndEagerCompile", Val::kFullCodeWithoutHeatCheck}, {"bypassHeatCheckAndEagerCompile", Val::kFullCodeWithoutHeatCheck},
{"code", Val::kCode}, {"code", Val::kCode},

View file

@ -7,6 +7,7 @@
#include <algorithm> #include <algorithm>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -68,7 +69,7 @@ struct Converter<network::mojom::CredentialsMode> {
network::mojom::CredentialsMode* out) { network::mojom::CredentialsMode* out) {
using Val = network::mojom::CredentialsMode; using Val = network::mojom::CredentialsMode;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"include", Val::kInclude}, {"include", Val::kInclude},
{"omit", Val::kOmit}, {"omit", Val::kOmit},
// Note: This only makes sense if the request // Note: This only makes sense if the request
@ -86,7 +87,7 @@ struct Converter<blink::mojom::FetchCacheMode> {
blink::mojom::FetchCacheMode* out) { blink::mojom::FetchCacheMode* out) {
using Val = blink::mojom::FetchCacheMode; using Val = blink::mojom::FetchCacheMode;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"default", Val::kDefault}, {"default", Val::kDefault},
{"force-cache", Val::kForceCache}, {"force-cache", Val::kForceCache},
{"no-cache", Val::kValidateCache}, {"no-cache", Val::kValidateCache},
@ -106,7 +107,7 @@ struct Converter<net::ReferrerPolicy> {
using Val = net::ReferrerPolicy; using Val = net::ReferrerPolicy;
// clang-format off // clang-format off
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN}, {"", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN},
{"no-referrer", Val::NO_REFERRER}, {"no-referrer", Val::NO_REFERRER},
{"no-referrer-when-downgrade", Val::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE}, {"no-referrer-when-downgrade", Val::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE},
@ -546,7 +547,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
if (std::string mode; opts.Get("mode", &mode)) { if (std::string mode; opts.Get("mode", &mode)) {
using Val = network::mojom::RequestMode; using Val = network::mojom::RequestMode;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"cors", Val::kCors}, {"cors", Val::kCors},
{"navigate", Val::kNavigate}, {"navigate", Val::kNavigate},
{"no-cors", Val::kNoCors}, {"no-cors", Val::kNoCors},
@ -559,7 +560,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
if (std::string destination; opts.Get("destination", &destination)) { if (std::string destination; opts.Get("destination", &destination)) {
using Val = network::mojom::RequestDestination; using Val = network::mojom::RequestDestination;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"audio", Val::kAudio}, {"audio", Val::kAudio},
{"audioworklet", Val::kAudioWorklet}, {"audioworklet", Val::kAudioWorklet},
{"document", Val::kDocument}, {"document", Val::kDocument},
@ -694,7 +695,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
return ret; return ret;
} }
void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece, void SimpleURLLoaderWrapper::OnDataReceived(std::string_view string_piece,
base::OnceClosure resume) { base::OnceClosure resume) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();

View file

@ -5,6 +5,7 @@
#include "shell/common/asar/archive.h" #include "shell/common/asar/archive.h"
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -105,7 +106,7 @@ bool FillFileInfoWithNode(Archive::FileInfo* info,
const std::string* offset = node->FindString("offset"); const std::string* offset = node->FindString("offset");
if (offset && if (offset &&
base::StringToUint64(base::StringPiece(*offset), &info->offset)) { base::StringToUint64(std::string_view{*offset}, &info->offset)) {
info->offset += header_size; info->offset += header_size;
} else { } else {
return false; return false;

View file

@ -6,6 +6,7 @@
#include <algorithm> #include <algorithm>
#include <string> #include <string>
#include <string_view>
#include <vector> #include <vector>
#include "base/containers/fixed_flat_map.h" #include "base/containers/fixed_flat_map.h"
@ -135,7 +136,7 @@ struct Converter<blink::WebMouseEvent::Button> {
blink::WebMouseEvent::Button* out) { blink::WebMouseEvent::Button* out) {
using Val = blink::WebMouseEvent::Button; using Val = blink::WebMouseEvent::Button;
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, Val>({ base::MakeFixedFlatMap<std::string_view, Val>({
{"left", Val::kLeft}, {"left", Val::kLeft},
{"middle", Val::kMiddle}, {"middle", Val::kMiddle},
{"right", Val::kRight}, {"right", Val::kRight},
@ -148,7 +149,7 @@ struct Converter<blink::WebMouseEvent::Button> {
// these are the modifier names we both accept and return // these are the modifier names we both accept and return
static constexpr auto Modifiers = static constexpr auto Modifiers =
base::MakeFixedFlatMap<base::StringPiece, blink::WebInputEvent::Modifiers>({ base::MakeFixedFlatMap<std::string_view, blink::WebInputEvent::Modifiers>({
{"alt", blink::WebInputEvent::Modifiers::kAltKey}, {"alt", blink::WebInputEvent::Modifiers::kAltKey},
{"capslock", blink::WebInputEvent::Modifiers::kCapsLockOn}, {"capslock", blink::WebInputEvent::Modifiers::kCapsLockOn},
{"control", blink::WebInputEvent::Modifiers::kControlKey}, {"control", blink::WebInputEvent::Modifiers::kControlKey},
@ -167,14 +168,14 @@ static constexpr auto Modifiers =
// these are the modifier names we accept but do not return // these are the modifier names we accept but do not return
static constexpr auto ModifierAliases = static constexpr auto ModifierAliases =
base::MakeFixedFlatMap<base::StringPiece, blink::WebInputEvent::Modifiers>({ base::MakeFixedFlatMap<std::string_view, blink::WebInputEvent::Modifiers>({
{"cmd", blink::WebInputEvent::Modifiers::kMetaKey}, {"cmd", blink::WebInputEvent::Modifiers::kMetaKey},
{"command", blink::WebInputEvent::Modifiers::kMetaKey}, {"command", blink::WebInputEvent::Modifiers::kMetaKey},
{"ctrl", blink::WebInputEvent::Modifiers::kControlKey}, {"ctrl", blink::WebInputEvent::Modifiers::kControlKey},
}); });
static constexpr auto ReferrerPolicies = static constexpr auto ReferrerPolicies =
base::MakeFixedFlatMap<base::StringPiece, network::mojom::ReferrerPolicy>({ base::MakeFixedFlatMap<std::string_view, network::mojom::ReferrerPolicy>({
{"default", network::mojom::ReferrerPolicy::kDefault}, {"default", network::mojom::ReferrerPolicy::kDefault},
{"no-referrer", network::mojom::ReferrerPolicy::kNever}, {"no-referrer", network::mojom::ReferrerPolicy::kNever},
{"no-referrer-when-downgrade", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade}, {"no-referrer-when-downgrade", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade},
@ -197,8 +198,8 @@ struct Converter<blink::WebInputEvent::Modifiers> {
} }
}; };
std::vector<base::StringPiece> ModifiersToArray(int modifiers) { std::vector<std::string_view> ModifiersToArray(int modifiers) {
std::vector<base::StringPiece> modifier_strings; std::vector<std::string_view> modifier_strings;
for (const auto& [name, mask] : Modifiers) for (const auto& [name, mask] : Modifiers)
if (mask & modifiers) if (mask & modifiers)
@ -463,7 +464,7 @@ v8::Local<v8::Value>
Converter<std::optional<blink::mojom::FormControlType>>::ToV8( Converter<std::optional<blink::mojom::FormControlType>>::ToV8(
v8::Isolate* isolate, v8::Isolate* isolate,
const std::optional<blink::mojom::FormControlType>& in) { const std::optional<blink::mojom::FormControlType>& in) {
base::StringPiece str{"none"}; std::string_view str{"none"};
if (in.has_value()) { if (in.has_value()) {
switch (*in) { switch (*in) {
case blink::mojom::FormControlType::kButtonButton: case blink::mojom::FormControlType::kButtonButton:

View file

@ -5,6 +5,7 @@
#include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/content_converter.h"
#include <string> #include <string>
#include <string_view>
#include "base/containers/fixed_flat_map.h" #include "base/containers/fixed_flat_map.h"
#include "content/public/browser/context_menu_params.h" #include "content/public/browser/context_menu_params.h"
@ -24,7 +25,7 @@
namespace { namespace {
[[nodiscard]] constexpr base::StringPiece FormControlToInputFieldTypeString( [[nodiscard]] constexpr std::string_view FormControlToInputFieldTypeString(
const std::optional<blink::mojom::FormControlType> form_control_type) { const std::optional<blink::mojom::FormControlType> form_control_type) {
if (!form_control_type) if (!form_control_type)
return "none"; return "none";
@ -70,7 +71,7 @@ namespace {
namespace gin { namespace gin {
static constexpr auto MenuSourceTypes = static constexpr auto MenuSourceTypes =
base::MakeFixedFlatMap<base::StringPiece, ui::MenuSourceType>({ base::MakeFixedFlatMap<std::string_view, ui::MenuSourceType>({
{"adjustSelection", ui::MENU_SOURCE_ADJUST_SELECTION}, {"adjustSelection", ui::MENU_SOURCE_ADJUST_SELECTION},
{"adjustSelectionReset", ui::MENU_SOURCE_ADJUST_SELECTION_RESET}, {"adjustSelectionReset", ui::MENU_SOURCE_ADJUST_SELECTION_RESET},
{"keyboard", ui::MENU_SOURCE_KEYBOARD}, {"keyboard", ui::MENU_SOURCE_KEYBOARD},
@ -285,12 +286,11 @@ bool Converter<content::StopFindAction>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
content::StopFindAction* out) { content::StopFindAction* out) {
using Val = content::StopFindAction; using Val = content::StopFindAction;
static constexpr auto Lookup = static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({
base::MakeFixedFlatMap<base::StringPiece, Val>({ {"activateSelection", Val::STOP_FIND_ACTION_ACTIVATE_SELECTION},
{"activateSelection", Val::STOP_FIND_ACTION_ACTIVATE_SELECTION}, {"clearSelection", Val::STOP_FIND_ACTION_CLEAR_SELECTION},
{"clearSelection", Val::STOP_FIND_ACTION_CLEAR_SELECTION}, {"keepSelection", Val::STOP_FIND_ACTION_KEEP_SELECTION},
{"keepSelection", Val::STOP_FIND_ACTION_KEEP_SELECTION}, });
});
return FromV8WithLookup(isolate, val, Lookup, out); return FromV8WithLookup(isolate, val, Lookup, out);
} }

View file

@ -5,6 +5,7 @@
#include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/net_converter.h"
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -691,7 +692,7 @@ bool Converter<net::DnsQueryType>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
net::DnsQueryType* out) { net::DnsQueryType* out) {
static constexpr auto Lookup = static constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, net::DnsQueryType>({ base::MakeFixedFlatMap<std::string_view, net::DnsQueryType>({
{"A", net::DnsQueryType::A}, {"A", net::DnsQueryType::A},
{"AAAA", net::DnsQueryType::AAAA}, {"AAAA", net::DnsQueryType::AAAA},
}); });
@ -703,14 +704,13 @@ bool Converter<net::HostResolverSource>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
net::HostResolverSource* out) { net::HostResolverSource* out) {
using Val = net::HostResolverSource; using Val = net::HostResolverSource;
static constexpr auto Lookup = static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({
base::MakeFixedFlatMap<base::StringPiece, Val>({ {"any", Val::ANY},
{"any", Val::ANY}, {"dns", Val::DNS},
{"dns", Val::DNS}, {"localOnly", Val::LOCAL_ONLY},
{"localOnly", Val::LOCAL_ONLY}, {"mdns", Val::MULTICAST_DNS},
{"mdns", Val::MULTICAST_DNS}, {"system", Val::SYSTEM},
{"system", Val::SYSTEM}, });
});
return FromV8WithLookup(isolate, val, Lookup, out); return FromV8WithLookup(isolate, val, Lookup, out);
} }
@ -720,12 +720,11 @@ bool Converter<network::mojom::ResolveHostParameters::CacheUsage>::FromV8(
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
network::mojom::ResolveHostParameters::CacheUsage* out) { network::mojom::ResolveHostParameters::CacheUsage* out) {
using Val = network::mojom::ResolveHostParameters::CacheUsage; using Val = network::mojom::ResolveHostParameters::CacheUsage;
static constexpr auto Lookup = static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({
base::MakeFixedFlatMap<base::StringPiece, Val>({ {"allowed", Val::ALLOWED},
{"allowed", Val::ALLOWED}, {"disallowed", Val::DISALLOWED},
{"disallowed", Val::DISALLOWED}, {"staleAllowed", Val::STALE_ALLOWED},
{"staleAllowed", Val::STALE_ALLOWED}, });
});
return FromV8WithLookup(isolate, val, Lookup, out); return FromV8WithLookup(isolate, val, Lookup, out);
} }
@ -735,11 +734,10 @@ bool Converter<network::mojom::SecureDnsPolicy>::FromV8(
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
network::mojom::SecureDnsPolicy* out) { network::mojom::SecureDnsPolicy* out) {
using Val = network::mojom::SecureDnsPolicy; using Val = network::mojom::SecureDnsPolicy;
static constexpr auto Lookup = static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({
base::MakeFixedFlatMap<base::StringPiece, Val>({ {"allow", Val::ALLOW},
{"allow", Val::ALLOW}, {"disable", Val::DISABLE},
{"disable", Val::DISABLE}, });
});
return FromV8WithLookup(isolate, val, Lookup, out); return FromV8WithLookup(isolate, val, Lookup, out);
} }

View file

@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.chromium file. // found in the LICENSE.chromium file.
#include <string_view>
#include "shell/common/gin_helper/arguments.h" #include "shell/common/gin_helper/arguments.h"
#include "v8/include/v8-exception.h" #include "v8/include/v8-exception.h"
@ -15,7 +17,7 @@ void Arguments::ThrowError() const {
gin::Arguments::ThrowError(); gin::Arguments::ThrowError();
} }
void Arguments::ThrowError(base::StringPiece message) const { void Arguments::ThrowError(const std::string_view message) const {
isolate()->ThrowException( isolate()->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate(), message))); v8::Exception::Error(gin::StringToV8(isolate(), message)));
} }

View file

@ -5,6 +5,8 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_
#include <string_view>
#include "gin/arguments.h" #include "gin/arguments.h"
namespace gin_helper { namespace gin_helper {
@ -40,7 +42,7 @@ class Arguments : public gin::Arguments {
// Throw error with custom error message. // Throw error with custom error message.
void ThrowError() const; void ThrowError() const;
void ThrowError(base::StringPiece message) const; void ThrowError(std::string_view message) const;
private: private:
// MUST NOT ADD ANY DATA MEMBER. // MUST NOT ADD ANY DATA MEMBER.

View file

@ -6,6 +6,7 @@
#define ELECTRON_SHELL_COMMON_GIN_HELPER_DICTIONARY_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_DICTIONARY_H_
#include <optional> #include <optional>
#include <string_view>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
@ -68,7 +69,7 @@ class Dictionary : public gin::Dictionary {
// Like normal Get but put result in an std::optional. // Like normal Get but put result in an std::optional.
template <typename T> template <typename T>
bool GetOptional(base::StringPiece key, std::optional<T>* out) const { bool GetOptional(const std::string_view key, std::optional<T>* out) const {
T ret; T ret;
if (Get(key, &ret)) { if (Get(key, &ret)) {
out->emplace(std::move(ret)); out->emplace(std::move(ret));
@ -79,7 +80,7 @@ class Dictionary : public gin::Dictionary {
} }
template <typename T> template <typename T>
bool GetHidden(base::StringPiece key, T* out) const { bool GetHidden(std::string_view key, T* out) const {
v8::Local<v8::Context> context = isolate()->GetCurrentContext(); v8::Local<v8::Context> context = isolate()->GetCurrentContext();
v8::Local<v8::Private> privateKey = v8::Local<v8::Private> privateKey =
v8::Private::ForApi(isolate(), gin::StringToV8(isolate(), key)); v8::Private::ForApi(isolate(), gin::StringToV8(isolate(), key));
@ -92,7 +93,7 @@ class Dictionary : public gin::Dictionary {
} }
template <typename T> template <typename T>
bool SetHidden(base::StringPiece key, T val) { bool SetHidden(std::string_view key, T val) {
v8::Local<v8::Value> v8_value; v8::Local<v8::Value> v8_value;
if (!gin::TryConvertToV8(isolate(), val, &v8_value)) if (!gin::TryConvertToV8(isolate(), val, &v8_value))
return false; return false;
@ -105,7 +106,7 @@ class Dictionary : public gin::Dictionary {
} }
template <typename T> template <typename T>
bool SetMethod(base::StringPiece key, const T& callback) { bool SetMethod(std::string_view key, const T& callback) {
auto context = isolate()->GetCurrentContext(); auto context = isolate()->GetCurrentContext();
auto templ = CallbackTraits<T>::CreateTemplate(isolate(), callback); auto templ = CallbackTraits<T>::CreateTemplate(isolate(), callback);
return GetHandle() return GetHandle()
@ -147,7 +148,7 @@ class Dictionary : public gin::Dictionary {
} }
template <typename T> template <typename T>
bool SetReadOnly(base::StringPiece key, const T& val) { bool SetReadOnly(std::string_view key, const T& val) {
v8::Local<v8::Value> v8_value; v8::Local<v8::Value> v8_value;
if (!gin::TryConvertToV8(isolate(), val, &v8_value)) if (!gin::TryConvertToV8(isolate(), val, &v8_value))
return false; return false;
@ -160,7 +161,7 @@ class Dictionary : public gin::Dictionary {
// Note: If we plan to add more Set methods, consider adding an option instead // Note: If we plan to add more Set methods, consider adding an option instead
// of copying code. // of copying code.
template <typename T> template <typename T>
bool SetReadOnlyNonConfigurable(base::StringPiece key, T val) { bool SetReadOnlyNonConfigurable(std::string_view key, T val) {
v8::Local<v8::Value> v8_value; v8::Local<v8::Value> v8_value;
if (!gin::TryConvertToV8(isolate(), val, &v8_value)) if (!gin::TryConvertToV8(isolate(), val, &v8_value))
return false; return false;
@ -171,13 +172,13 @@ class Dictionary : public gin::Dictionary {
return !result.IsNothing() && result.FromJust(); return !result.IsNothing() && result.FromJust();
} }
bool Has(base::StringPiece key) const { bool Has(std::string_view key) const {
v8::Maybe<bool> result = GetHandle()->Has(isolate()->GetCurrentContext(), v8::Maybe<bool> result = GetHandle()->Has(isolate()->GetCurrentContext(),
gin::StringToV8(isolate(), key)); gin::StringToV8(isolate(), key));
return !result.IsNothing() && result.FromJust(); return !result.IsNothing() && result.FromJust();
} }
bool Delete(base::StringPiece key) { bool Delete(std::string_view key) {
v8::Maybe<bool> result = GetHandle()->Delete( v8::Maybe<bool> result = GetHandle()->Delete(
isolate()->GetCurrentContext(), gin::StringToV8(isolate(), key)); isolate()->GetCurrentContext(), gin::StringToV8(isolate(), key));
return !result.IsNothing() && result.FromJust(); return !result.IsNothing() && result.FromJust();

View file

@ -2,6 +2,8 @@
// Use of this source code is governed by the MIT license that can be // Use of this source code is governed by the MIT license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include <string_view>
#include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/error_thrower.h"
#include "gin/converter.h" #include "gin/converter.h"
@ -15,27 +17,28 @@ ErrorThrower::ErrorThrower(v8::Isolate* isolate) : isolate_(isolate) {}
// costly to invoke // costly to invoke
ErrorThrower::ErrorThrower() : isolate_(v8::Isolate::GetCurrent()) {} ErrorThrower::ErrorThrower() : isolate_(v8::Isolate::GetCurrent()) {}
void ErrorThrower::ThrowError(base::StringPiece err_msg) const { void ErrorThrower::ThrowError(const std::string_view err_msg) const {
Throw(v8::Exception::Error, err_msg); Throw(v8::Exception::Error, err_msg);
} }
void ErrorThrower::ThrowTypeError(base::StringPiece err_msg) const { void ErrorThrower::ThrowTypeError(const std::string_view err_msg) const {
Throw(v8::Exception::TypeError, err_msg); Throw(v8::Exception::TypeError, err_msg);
} }
void ErrorThrower::ThrowRangeError(base::StringPiece err_msg) const { void ErrorThrower::ThrowRangeError(const std::string_view err_msg) const {
Throw(v8::Exception::RangeError, err_msg); Throw(v8::Exception::RangeError, err_msg);
} }
void ErrorThrower::ThrowReferenceError(base::StringPiece err_msg) const { void ErrorThrower::ThrowReferenceError(const std::string_view err_msg) const {
Throw(v8::Exception::ReferenceError, err_msg); Throw(v8::Exception::ReferenceError, err_msg);
} }
void ErrorThrower::ThrowSyntaxError(base::StringPiece err_msg) const { void ErrorThrower::ThrowSyntaxError(const std::string_view err_msg) const {
Throw(v8::Exception::SyntaxError, err_msg); Throw(v8::Exception::SyntaxError, err_msg);
} }
void ErrorThrower::Throw(ErrorGenerator gen, base::StringPiece err_msg) const { void ErrorThrower::Throw(ErrorGenerator gen,
const std::string_view err_msg) const {
v8::Local<v8::Value> exception = gen(gin::StringToV8(isolate_, err_msg), {}); v8::Local<v8::Value> exception = gen(gin::StringToV8(isolate_, err_msg), {});
if (!isolate_->IsExecutionTerminating()) if (!isolate_->IsExecutionTerminating())
isolate_->ThrowException(exception); isolate_->ThrowException(exception);

View file

@ -5,8 +5,9 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_
#include <string_view>
#include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr.h"
#include "base/strings/string_piece.h"
#include "v8/include/v8.h" #include "v8/include/v8.h"
namespace gin_helper { namespace gin_helper {
@ -17,18 +18,18 @@ class ErrorThrower {
ErrorThrower(); ErrorThrower();
~ErrorThrower() = default; ~ErrorThrower() = default;
void ThrowError(base::StringPiece err_msg) const; void ThrowError(std::string_view err_msg) const;
void ThrowTypeError(base::StringPiece err_msg) const; void ThrowTypeError(std::string_view err_msg) const;
void ThrowRangeError(base::StringPiece err_msg) const; void ThrowRangeError(std::string_view err_msg) const;
void ThrowReferenceError(base::StringPiece err_msg) const; void ThrowReferenceError(std::string_view err_msg) const;
void ThrowSyntaxError(base::StringPiece err_msg) const; void ThrowSyntaxError(std::string_view err_msg) const;
v8::Isolate* isolate() const { return isolate_; } v8::Isolate* isolate() const { return isolate_; }
private: private:
using ErrorGenerator = v8::Local<v8::Value> (*)(v8::Local<v8::String> err_msg, using ErrorGenerator = v8::Local<v8::Value> (*)(v8::Local<v8::String> err_msg,
v8::Local<v8::Value> options); v8::Local<v8::Value> options);
void Throw(ErrorGenerator gen, base::StringPiece err_msg) const; void Throw(ErrorGenerator gen, std::string_view err_msg) const;
raw_ptr<v8::Isolate> isolate_; raw_ptr<v8::Isolate> isolate_;
}; };

View file

@ -5,6 +5,7 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -38,7 +39,7 @@ class EventEmitter : public gin_helper::Wrappable<T> {
// this.emit(name, new Event(), args...); // this.emit(name, new Event(), args...);
template <typename... Args> template <typename... Args>
bool Emit(base::StringPiece name, Args&&... args) { bool Emit(const std::string_view name, Args&&... args) {
v8::HandleScope handle_scope(isolate()); v8::HandleScope handle_scope(isolate());
v8::Local<v8::Object> wrapper = GetWrapper(); v8::Local<v8::Object> wrapper = GetWrapper();
if (wrapper.IsEmpty()) if (wrapper.IsEmpty())
@ -58,7 +59,7 @@ class EventEmitter : public gin_helper::Wrappable<T> {
private: private:
// this.emit(name, event, args...); // this.emit(name, event, args...);
template <typename... Args> template <typename... Args>
bool EmitWithEvent(base::StringPiece name, bool EmitWithEvent(const std::string_view name,
gin::Handle<gin_helper::internal::Event> event, gin::Handle<gin_helper::internal::Event> event,
Args&&... args) { Args&&... args) {
// It's possible that |this| will be deleted by EmitEvent, so save anything // It's possible that |this| will be deleted by EmitEvent, so save anything

View file

@ -12,14 +12,14 @@ ObjectTemplateBuilder::ObjectTemplateBuilder(
: isolate_(isolate), template_(templ) {} : isolate_(isolate), template_(templ) {}
ObjectTemplateBuilder& ObjectTemplateBuilder::SetImpl( ObjectTemplateBuilder& ObjectTemplateBuilder::SetImpl(
const base::StringPiece& name, const std::string_view name,
v8::Local<v8::Data> val) { v8::Local<v8::Data> val) {
template_->Set(gin::StringToSymbol(isolate_, name), val); template_->Set(gin::StringToSymbol(isolate_, name), val);
return *this; return *this;
} }
ObjectTemplateBuilder& ObjectTemplateBuilder::SetPropertyImpl( ObjectTemplateBuilder& ObjectTemplateBuilder::SetPropertyImpl(
const base::StringPiece& name, const std::string_view name,
v8::Local<v8::FunctionTemplate> getter, v8::Local<v8::FunctionTemplate> getter,
v8::Local<v8::FunctionTemplate> setter) { v8::Local<v8::FunctionTemplate> setter) {
template_->SetAccessorProperty(gin::StringToSymbol(isolate_, name), getter, template_->SetAccessorProperty(gin::StringToSymbol(isolate_, name), getter,

View file

@ -5,6 +5,8 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_
#include <string_view>
#include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr.h"
#include "shell/common/gin_helper/function_template.h" #include "shell/common/gin_helper/function_template.h"
@ -28,7 +30,7 @@ class ObjectTemplateBuilder {
// poetic license here in order that all calls to Set() can be via the '.' // poetic license here in order that all calls to Set() can be via the '.'
// operator and line up nicely. // operator and line up nicely.
template <typename T> template <typename T>
ObjectTemplateBuilder& SetValue(const base::StringPiece& name, T val) { ObjectTemplateBuilder& SetValue(const std::string_view name, T val) {
return SetImpl(name, ConvertToV8(isolate_, val)); return SetImpl(name, ConvertToV8(isolate_, val));
} }
@ -37,19 +39,19 @@ class ObjectTemplateBuilder {
// will want to use one of the first two options. Also see // will want to use one of the first two options. Also see
// gin::CreateFunctionTemplate() for creating raw function templates. // gin::CreateFunctionTemplate() for creating raw function templates.
template <typename T> template <typename T>
ObjectTemplateBuilder& SetMethod(const base::StringPiece& name, ObjectTemplateBuilder& SetMethod(const std::string_view name,
const T& callback) { const T& callback) {
return SetImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, callback)); return SetImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, callback));
} }
template <typename T> template <typename T>
ObjectTemplateBuilder& SetProperty(const base::StringPiece& name, ObjectTemplateBuilder& SetProperty(const std::string_view name,
const T& getter) { const T& getter) {
return SetPropertyImpl(name, return SetPropertyImpl(name,
CallbackTraits<T>::CreateTemplate(isolate_, getter), CallbackTraits<T>::CreateTemplate(isolate_, getter),
v8::Local<v8::FunctionTemplate>()); v8::Local<v8::FunctionTemplate>());
} }
template <typename T, typename U> template <typename T, typename U>
ObjectTemplateBuilder& SetProperty(const base::StringPiece& name, ObjectTemplateBuilder& SetProperty(const std::string_view name,
const T& getter, const T& getter,
const U& setter) { const U& setter) {
return SetPropertyImpl(name, return SetPropertyImpl(name,
@ -60,10 +62,10 @@ class ObjectTemplateBuilder {
v8::Local<v8::ObjectTemplate> Build(); v8::Local<v8::ObjectTemplate> Build();
private: private:
ObjectTemplateBuilder& SetImpl(const base::StringPiece& name, ObjectTemplateBuilder& SetImpl(const std::string_view name,
v8::Local<v8::Data> val); v8::Local<v8::Data> val);
ObjectTemplateBuilder& SetPropertyImpl( ObjectTemplateBuilder& SetPropertyImpl(
const base::StringPiece& name, const std::string_view name,
v8::Local<v8::FunctionTemplate> getter, v8::Local<v8::FunctionTemplate> getter,
v8::Local<v8::FunctionTemplate> setter); v8::Local<v8::FunctionTemplate> setter);

View file

@ -2,6 +2,8 @@
// Use of this source code is governed by the MIT license that can be // Use of this source code is governed by the MIT license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include <string_view>
#include "shell/common/gin_helper/promise.h" #include "shell/common/gin_helper/promise.h"
namespace gin_helper { namespace gin_helper {
@ -43,7 +45,8 @@ v8::Maybe<bool> PromiseBase::Reject(v8::Local<v8::Value> except) {
return GetInner()->Reject(GetContext(), except); return GetInner()->Reject(GetContext(), except);
} }
v8::Maybe<bool> PromiseBase::RejectWithErrorMessage(base::StringPiece message) { v8::Maybe<bool> PromiseBase::RejectWithErrorMessage(
const std::string_view message) {
v8::HandleScope handle_scope(isolate()); v8::HandleScope handle_scope(isolate());
gin_helper::MicrotasksScope microtasks_scope( gin_helper::MicrotasksScope microtasks_scope(
isolate(), GetContext()->GetMicrotaskQueue()); isolate(), GetContext()->GetMicrotaskQueue());

View file

@ -6,12 +6,12 @@
#define ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_
#include <string> #include <string>
#include <string_view>
#include <tuple> #include <tuple>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr.h"
#include "base/strings/string_piece.h"
#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "shell/common/gin_converters/std_converter.h" #include "shell/common/gin_converters/std_converter.h"
@ -47,19 +47,20 @@ class PromiseBase {
// //
// Note: The parameter type is PromiseBase&& so it can take the instances of // Note: The parameter type is PromiseBase&& so it can take the instances of
// Promise<T> type. // Promise<T> type.
static void RejectPromise(PromiseBase&& promise, base::StringPiece errmsg) { static void RejectPromise(PromiseBase&& promise,
const std::string_view errmsg) {
if (electron::IsBrowserProcess() && if (electron::IsBrowserProcess() &&
!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
content::GetUIThreadTaskRunner({})->PostTask( content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, FROM_HERE,
base::BindOnce( base::BindOnce(
// Note that this callback can not take StringPiece, // Note that this callback can not take std::string_view,
// as StringPiece only references string internally and // as StringPiece only references string internally and
// will blow when a temporary string is passed. // will blow when a temporary string is passed.
[](PromiseBase&& promise, std::string str) { [](PromiseBase&& promise, std::string str) {
promise.RejectWithErrorMessage(str); promise.RejectWithErrorMessage(str);
}, },
std::move(promise), std::string(errmsg.data(), errmsg.size()))); std::move(promise), std::string{errmsg}));
} else { } else {
promise.RejectWithErrorMessage(errmsg); promise.RejectWithErrorMessage(errmsg);
} }
@ -67,7 +68,7 @@ class PromiseBase {
v8::Maybe<bool> Reject(); v8::Maybe<bool> Reject();
v8::Maybe<bool> Reject(v8::Local<v8::Value> except); v8::Maybe<bool> Reject(v8::Local<v8::Value> except);
v8::Maybe<bool> RejectWithErrorMessage(base::StringPiece message); v8::Maybe<bool> RejectWithErrorMessage(std::string_view message);
v8::Local<v8::Context> GetContext() const; v8::Local<v8::Context> GetContext() const;
v8::Local<v8::Promise> GetHandle() const; v8::Local<v8::Promise> GetHandle() const;

View file

@ -18,7 +18,7 @@ namespace {
using CodeAndShiftedChar = std::pair<ui::KeyboardCode, std::optional<char16_t>>; using CodeAndShiftedChar = std::pair<ui::KeyboardCode, std::optional<char16_t>>;
constexpr CodeAndShiftedChar KeyboardCodeFromKeyIdentifier( constexpr CodeAndShiftedChar KeyboardCodeFromKeyIdentifier(
base::StringPiece str) { const std::string_view str) {
#if BUILDFLAG(IS_MAC) #if BUILDFLAG(IS_MAC)
constexpr auto CommandOrControl = ui::VKEY_COMMAND; constexpr auto CommandOrControl = ui::VKEY_COMMAND;
#else #else
@ -26,7 +26,7 @@ constexpr CodeAndShiftedChar KeyboardCodeFromKeyIdentifier(
#endif #endif
constexpr auto Lookup = constexpr auto Lookup =
base::MakeFixedFlatMap<base::StringPiece, CodeAndShiftedChar>({ base::MakeFixedFlatMap<std::string_view, CodeAndShiftedChar>({
{"alt", {ui::VKEY_MENU, {}}}, {"alt", {ui::VKEY_MENU, {}}},
{"altgr", {ui::VKEY_ALTGR, {}}}, {"altgr", {ui::VKEY_ALTGR, {}}},
{"backspace", {ui::VKEY_BACK, {}}}, {"backspace", {ui::VKEY_BACK, {}}},
@ -272,7 +272,7 @@ constexpr CodeAndShiftedChar KeyboardCodeFromCharCode(char16_t c) {
} // namespace } // namespace
ui::KeyboardCode KeyboardCodeFromStr(base::StringPiece str, ui::KeyboardCode KeyboardCodeFromStr(const std::string_view str,
std::optional<char16_t>* shifted_char) { std::optional<char16_t>* shifted_char) {
auto const [code, shifted] = auto const [code, shifted] =
str.size() == 1 ? KeyboardCodeFromCharCode(base::ToLowerASCII(str[0])) str.size() == 1 ? KeyboardCodeFromCharCode(base::ToLowerASCII(str[0]))

View file

@ -6,8 +6,8 @@
#define ELECTRON_SHELL_COMMON_KEYBOARD_UTIL_H_ #define ELECTRON_SHELL_COMMON_KEYBOARD_UTIL_H_
#include <optional> #include <optional>
#include <string_view>
#include "base/strings/string_piece.h"
#include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/keycodes/keyboard_codes.h"
namespace electron { namespace electron {
@ -15,7 +15,7 @@ namespace electron {
// Return key code of the |str|, if the original key is a shifted character, // Return key code of the |str|, if the original key is a shifted character,
// for example + and /, set it in |shifted_char|. // for example + and /, set it in |shifted_char|.
// pressed. // pressed.
ui::KeyboardCode KeyboardCodeFromStr(base::StringPiece str, ui::KeyboardCode KeyboardCodeFromStr(std::string_view str,
std::optional<char16_t>* shifted_char); std::optional<char16_t>* shifted_char);
} // namespace electron } // namespace electron

View file

@ -5,6 +5,7 @@
#include "shell/common/logging.h" #include "shell/common/logging.h"
#include <string> #include <string>
#include <string_view>
#include "base/base_switches.h" #include "base/base_switches.h"
#include "base/command_line.h" #include "base/command_line.h"
@ -19,8 +20,8 @@
namespace logging { namespace logging {
constexpr base::StringPiece kLogFileName("ELECTRON_LOG_FILE"); constexpr std::string_view kLogFileName{"ELECTRON_LOG_FILE"};
constexpr base::StringPiece kElectronEnableLogging("ELECTRON_ENABLE_LOGGING"); constexpr std::string_view kElectronEnableLogging{"ELECTRON_ENABLE_LOGGING"};
base::FilePath GetLogFileName(const base::CommandLine& command_line) { base::FilePath GetLogFileName(const base::CommandLine& command_line) {
std::string filename = command_line.GetSwitchValueASCII(switches::kLogFile); std::string filename = command_line.GetSwitchValueASCII(switches::kLogFile);

View file

@ -6,6 +6,7 @@
#include <algorithm> #include <algorithm>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -293,9 +294,9 @@ void ErrorMessageListener(v8::Local<v8::Message> message,
// Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode. // Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode.
// If node CLI inspect support is disabled, allow no debug options. // If node CLI inspect support is disabled, allow no debug options.
bool IsAllowedOption(base::StringPiece option) { bool IsAllowedOption(const std::string_view option) {
static constexpr auto debug_options = static constexpr auto debug_options =
base::MakeFixedFlatSet<base::StringPiece>({ base::MakeFixedFlatSet<std::string_view>({
"--debug", "--debug",
"--debug-brk", "--debug-brk",
"--debug-port", "--debug-port",
@ -307,7 +308,7 @@ bool IsAllowedOption(base::StringPiece option) {
}); });
// This should be aligned with what's possible to set via the process object. // This should be aligned with what's possible to set via the process object.
static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ static constexpr auto options = base::MakeFixedFlatSet<std::string_view>({
"--dns-result-order", "--dns-result-order",
"--no-deprecation", "--no-deprecation",
"--throw-deprecation", "--throw-deprecation",
@ -325,7 +326,7 @@ bool IsAllowedOption(base::StringPiece option) {
// See https://nodejs.org/api/cli.html#cli_node_options_options // See https://nodejs.org/api/cli.html#cli_node_options_options
void SetNodeOptions(base::Environment* env) { void SetNodeOptions(base::Environment* env) {
// Options that are unilaterally disallowed // Options that are unilaterally disallowed
static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({
"--enable-fips", "--enable-fips",
"--experimental-policy", "--experimental-policy",
"--force-fips", "--force-fips",
@ -334,7 +335,7 @@ void SetNodeOptions(base::Environment* env) {
"--use-openssl-ca", "--use-openssl-ca",
}); });
static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ static constexpr auto pkg_opts = base::MakeFixedFlatSet<std::string_view>({
"--http-parser", "--http-parser",
"--max-http-header-size", "--max-http-header-size",
}); });
@ -475,7 +476,7 @@ std::vector<std::string> NodeBindings::ParseNodeCliFlags() {
#else #else
const auto& option = arg; const auto& option = arg;
#endif #endif
const auto stripped = base::StringPiece(option).substr(0, option.find('=')); const auto stripped = std::string_view{option}.substr(0, option.find('='));
// Only allow no-op or a small set of debug/trace related options. // Only allow no-op or a small set of debug/trace related options.
if (IsAllowedOption(stripped) || stripped == "--") if (IsAllowedOption(stripped) || stripped == "--")
args.push_back(option); args.push_back(option);

View file

@ -5,6 +5,7 @@
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -397,7 +398,7 @@ class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>,
private: private:
bool MaybeGetRenderFrame(v8::Isolate* isolate, bool MaybeGetRenderFrame(v8::Isolate* isolate,
const base::StringPiece method_name, const std::string_view method_name,
content::RenderFrame** render_frame_ptr) { content::RenderFrame** render_frame_ptr) {
std::string error_msg; std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, method_name, render_frame_ptr)) { if (!MaybeGetRenderFrame(&error_msg, method_name, render_frame_ptr)) {
@ -408,7 +409,7 @@ class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>,
} }
bool MaybeGetRenderFrame(std::string* error_msg, bool MaybeGetRenderFrame(std::string* error_msg,
const base::StringPiece method_name, const std::string_view method_name,
content::RenderFrame** render_frame_ptr) { content::RenderFrame** render_frame_ptr) {
auto* frame = render_frame(); auto* frame = render_frame();
if (!frame) { if (!frame) {