refactor: use gin_helper::Dictionary::ValueOrDefault() (#46982)

* refactor: use ValueOrDefault() in electron_api_web_contents.cc

* refactor: use ValueOrDefault() in electron_api_url_loader.cc

* refactor: use ValueOrDefault() in electron_download_manager_delegate.cc

* refactor: use ValueOrDefault() in electron_touch_bar.mm

* refactor: use ValueOrDefault() in electron_url_loader_factory.cc

* refactor: use ValueOrDefault() in electron_browser_context.cc

* refactor: use ValueOrDefault() in electron_touch_bar.mm

* refactor: use ValueOrDefault() in blink_converter.cc

* feat: add ValueOrDefault() to PersistentDictionary

* empty commit

* refactor: use ValueOrDefault() in blink_converter.cc

* refactor: inline the rectangle base::Value::Dict

* refactor: remove has_scroll temporary

---------

Co-authored-by: Deepak Mohan <hop2deep@gmail.com>
This commit is contained in:
Charles Kerr 2025-05-08 14:17:22 -05:00 committed by GitHub
commit 2cbd968da5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 76 additions and 114 deletions

View file

@ -822,8 +822,7 @@ WebContents::WebContents(v8::Isolate* isolate,
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
bool initially_shown = true;
options.Get(options::kShow, &initially_shown);
const bool initially_shown = options.ValueOrDefault(options::kShow, true);
// Obtain the session.
std::string partition;
@ -2332,9 +2331,7 @@ void WebContents::LoadURL(const GURL& url,
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
if (options.ValueOrDefault("reloadIgnoringCache", false)) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
@ -3011,13 +3008,10 @@ void WebContents::Print(gin::Arguments* args) {
}
// Set optional silent printing.
bool silent = false;
options.Get("silent", &silent);
settings.Set("silent", silent);
settings.Set("silent", options.ValueOrDefault("silent", false));
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds,
options.ValueOrDefault("printBackground", false));
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
@ -3028,20 +3022,16 @@ void WebContents::Print(gin::Arguments* args) {
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
settings.Set(printing::kSettingMarginsCustom,
base::Value::Dict{}
.Set(printing::kSettingMarginTop,
margins.ValueOrDefault("top", 0))
.Set(printing::kSettingMarginBottom,
margins.ValueOrDefault("bottom", 0))
.Set(printing::kSettingMarginLeft,
margins.ValueOrDefault("left", 0))
.Set(printing::kSettingMarginRight,
margins.ValueOrDefault("right", 0)));
}
} else {
settings.Set(
@ -3050,46 +3040,37 @@ void WebContents::Print(gin::Arguments* args) {
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
settings.Set(printing::kSettingColor,
static_cast<int>(options.ValueOrDefault("color", true)
? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
settings.Set(printing::kSettingLandscape,
options.ValueOrDefault("landscape", false));
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
const auto device_name =
options.ValueOrDefault("deviceName", std::u16string{});
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
settings.Set(printing::kSettingScaleFactor,
options.ValueOrDefault("scaleFactor", 100));
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet,
options.ValueOrDefault("pagesPerSheet", 1));
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
settings.Set(printing::kSettingCollate,
options.ValueOrDefault("collate", true));
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
settings.Set(printing::kSettingCopies, options.ValueOrDefault("copies", 1));
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
const auto header = options.ValueOrDefault("header", std::string{});
const auto footer = options.ValueOrDefault("footer", std::string{});
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
@ -3128,9 +3109,8 @@ void WebContents::Print(gin::Arguments* args) {
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
const auto duplex_mode = options.ValueOrDefault(
"duplexMode", printing::mojom::DuplexMode::kSimplex);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
base::Value::Dict media_size;
@ -3150,14 +3130,11 @@ void WebContents::Print(gin::Arguments* args) {
}
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
if (gin_helper::Dictionary dpi; options.Get("dpi", &dpi)) {
settings.Set(printing::kSettingDpiHorizontal,
dpi.ValueOrDefault("horizontal", 72));
settings.Set(printing::kSettingDpiVertical,
dpi.ValueOrDefault("vertical", 72));
}
print_task_runner_->PostTaskAndReplyWithResult(

View file

@ -758,9 +758,9 @@ void ElectronBrowserContext::DisplayMediaDeviceChosen(
GetAudioDesktopMediaId(request.requested_audio_device_ids));
devices.audio_device = audio_device;
} else if (result_dict.Get("audio", &rfh)) {
bool enable_local_echo = false;
result_dict.Get("enableLocalEcho", &enable_local_echo);
bool disable_local_echo = !enable_local_echo;
const bool enable_local_echo =
result_dict.ValueOrDefault("enableLocalEcho", false);
const bool disable_local_echo = !enable_local_echo;
auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
blink::MediaStreamDevice audio_device(
request.audio_type,

View file

@ -294,8 +294,7 @@ void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone(
if (!item)
return;
bool canceled = true;
result.Get("canceled", &canceled);
const bool canceled = result.ValueOrDefault("canceled", true);
base::FilePath path;

View file

@ -124,8 +124,8 @@ network::mojom::URLResponseHeadPtr ToResponseHead(
return head;
}
int status_code = net::HTTP_OK;
dict.Get("statusCode", &status_code);
const int status_code =
dict.ValueOrDefault("statusCode", static_cast<int>(net::HTTP_OK));
head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(
absl::StrFormat("HTTP/1.1 %d %s", status_code,
net::GetHttpReasonPhrase(

View file

@ -398,8 +398,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
}
bool enabled = true;
settings.Get("enabled", &enabled);
const bool enabled = settings.ValueOrDefault("enabled", true);
[button setEnabled:enabled];
}
@ -501,16 +500,9 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
settings.Get("label", &label);
item.label = base::SysUTF8ToNSString(label);
int maxValue = 100;
int minValue = 0;
int value = 50;
settings.Get("minValue", &minValue);
settings.Get("maxValue", &maxValue);
settings.Get("value", &value);
item.slider.minValue = minValue;
item.slider.maxValue = maxValue;
item.slider.doubleValue = value;
item.slider.minValue = settings.ValueOrDefault("minValue", 0);
item.slider.maxValue = settings.ValueOrDefault("maxValue", 100);
item.slider.doubleValue = settings.ValueOrDefault("value", 50);
}
- (NSTouchBarItem*)makePopoverForID:(NSString*)id
@ -540,9 +532,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
item.collapsedRepresentationImage = image.AsNSImage();
}
bool showCloseButton = true;
settings.Get("showCloseButton", &showCloseButton);
item.showsCloseButton = showCloseButton;
item.showsCloseButton = settings.ValueOrDefault("showCloseButton", true);
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
@ -670,8 +660,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
for (size_t i = 0; i < segments.size(); ++i) {
std::string label;
gfx::Image image;
bool enabled = true;
segments[i].Get("enabled", &enabled);
const bool enabled = segments[i].ValueOrDefault("enabled", true);
if (segments[i].Get("label", &label)) {
[control setLabel:base::SysUTF8ToNSString(label) forSegment:i];
} else {
@ -686,8 +675,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
[control setEnabled:enabled forSegment:i];
}
int selectedIndex = 0;
settings.Get("selectedIndex", &selectedIndex);
const int selectedIndex = settings.ValueOrDefault("selectedIndex", 0);
if (selectedIndex >= 0 && selectedIndex < control.segmentCount)
control.selectedSegment = selectedIndex;
}
@ -726,8 +714,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
withSettings:(const gin_helper::PersistentDictionary&)settings {
NSScrubber* scrubber = item.view;
bool showsArrowButtons = false;
settings.Get("showArrowButtons", &showsArrowButtons);
const bool showsArrowButtons =
settings.ValueOrDefault("showArrowButtons", false);
// The scrubber will crash if the user tries to scroll
// and there are no items.
if ([self numberOfItemsForScrubber:scrubber] > 0)
@ -766,9 +754,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
scrubber.mode = NSScrubberModeFree;
}
bool continuous = true;
settings.Get("continuous", &continuous);
scrubber.continuous = continuous;
scrubber.continuous = settings.ValueOrDefault("continuous", true);
[scrubber reloadData];
}

View file

@ -609,9 +609,8 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
}
}
blink::mojom::FetchCacheMode cache_mode =
blink::mojom::FetchCacheMode::kDefault;
opts.Get("cache", &cache_mode);
const auto cache_mode =
opts.ValueOrDefault("cache", blink::mojom::FetchCacheMode::kDefault);
switch (cache_mode) {
case blink::mojom::FetchCacheMode::kNoStore:
request->load_flags |= net::LOAD_DISABLE_CACHE;
@ -639,8 +638,8 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
break;
}
bool use_session_cookies = false;
opts.Get("useSessionCookies", &use_session_cookies);
const bool use_session_cookies =
opts.ValueOrDefault("useSessionCookies", false);
int options = network::mojom::kURLLoadOptionSniffMimeType;
if (!credentials_specified && !use_session_cookies) {
// This is the default case, as well as the case when credentials is not
@ -650,9 +649,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
options |= network::mojom::kURLLoadOptionBlockAllCookies;
}
bool bypass_custom_protocol_handlers = false;
opts.Get("bypassCustomProtocolHandlers", &bypass_custom_protocol_handlers);
if (bypass_custom_protocol_handlers)
if (opts.ValueOrDefault("bypassCustomProtocolHandlers", false))
options |= kBypassCustomProtocolHandlers;
v8::Local<v8::Value> body;

View file

@ -369,10 +369,8 @@ bool Converter<blink::WebMouseEvent>::FromV8(v8::Isolate* isolate,
if (!dict.Get("button", &out->button))
out->button = blink::WebMouseEvent::Button::kLeft;
float global_x = 0.f;
float global_y = 0.f;
dict.Get("globalX", &global_x);
dict.Get("globalY", &global_y);
const float global_x = dict.ValueOrDefault("globalX", 0.F);
const float global_y = dict.ValueOrDefault("globalY", 0.F);
out->SetPositionInScreen(global_x, global_y);
dict.Get("movementX", &out->movement_x);
@ -397,23 +395,19 @@ bool Converter<blink::WebMouseWheelEvent>::FromV8(
dict.Get("accelerationRatioX", &out->acceleration_ratio_x);
dict.Get("accelerationRatioY", &out->acceleration_ratio_y);
bool has_precise_scrolling_deltas = false;
dict.Get("hasPreciseScrollingDeltas", &has_precise_scrolling_deltas);
if (has_precise_scrolling_deltas) {
out->delta_units = ui::ScrollGranularity::kScrollByPrecisePixel;
} else {
out->delta_units = ui::ScrollGranularity::kScrollByPixel;
}
const bool precise = dict.ValueOrDefault("hasPreciseScrollingDeltas", false);
out->delta_units = precise ? ui::ScrollGranularity::kScrollByPrecisePixel
: ui::ScrollGranularity::kScrollByPixel;
#if defined(USE_AURA)
// Matches the behavior of ui/events/blink/web_input_event_traits.cc:
bool can_scroll = true;
if (dict.Get("canScroll", &can_scroll) && !can_scroll) {
if (!dict.ValueOrDefault("canScroll", true)) {
out->delta_units = ui::ScrollGranularity::kScrollByPage;
out->SetModifiers(out->GetModifiers() &
~blink::WebInputEvent::Modifiers::kControlKey);
}
#endif
return true;
}

View file

@ -41,6 +41,15 @@ class PersistentDictionary {
gin::ConvertFromV8(isolate_, value, out);
}
// Convenience function for using a default value if the
// specified key isn't present in the dictionary.
template <typename T>
T ValueOrDefault(const std::string_view key, T default_value) const {
if (auto value = T{}; Get(key, &value))
return value;
return default_value;
}
private:
raw_ptr<v8::Isolate> isolate_ = nullptr;
v8::Global<v8::Object> handle_;