File: core_tab_helper.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (565 lines) | stat: -rw-r--r-- 22,191 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/tab_contents/core_tab_helper.h"

#include <string>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/bind_post_task.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser_command_controller.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/common/chrome_render_frame.mojom.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/generated_resources.h"
#include "components/lens/buildflags.h"
#include "components/lens/lens_constants.h"
#include "components/lens/lens_entrypoints.h"
#include "components/lens/lens_features.h"
#include "components/lens/lens_url_utils.h"
#include "components/search/search.h"
#include "components/search_engines/template_url.h"
#include "components/search_engines/template_url_service.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "extensions/buildflags/buildflags.h"
#include "net/base/load_states.h"
#include "net/http/http_request_headers.h"
#include "skia/ext/image_operations.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/codec/webp_codec.h"
#include "ui/gfx/image/image_util.h"

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#endif

using content::WebContents;

namespace {

constexpr int kImageSearchThumbnailMinSize = 300 * 300;
constexpr int kImageSearchThumbnailMaxWidth = 600;
constexpr int kImageSearchThumbnailMaxHeight = 600;
constexpr int kEncodingQualityJpeg = 40;
constexpr int kEncodingQualityWebp = 45;

bool NeedsDownscale(gfx::Image image) {
  return (image.Height() * image.Width() > lens::kMaxAreaForImageSearch) &&
         (image.Width() > lens::kMaxPixelsForImageSearch ||
          image.Height() > lens::kMaxPixelsForImageSearch);
}

gfx::Image DownscaleImage(const gfx::Image& image) {
  return gfx::ResizedImageForMaxDimensions(
      image, lens::kMaxPixelsForImageSearch, lens::kMaxPixelsForImageSearch,
      lens::kMaxAreaForImageSearch);
}

}  // namespace

CoreTabHelper::CoreTabHelper(WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      content::WebContentsUserData<CoreTabHelper>(*web_contents) {}

CoreTabHelper::~CoreTabHelper() = default;

// static
std::u16string CoreTabHelper::GetDefaultTitle() {
  return l10n_util::GetStringUTF16(IDS_DEFAULT_TAB_TITLE);
}

std::u16string CoreTabHelper::GetStatusText() const {
  std::u16string status_text;
  GetStatusTextForWebContents(&status_text, web_contents());
  return status_text;
}

void CoreTabHelper::UpdateContentRestrictions(int content_restrictions) {
  content_restrictions_ = content_restrictions;
#if !BUILDFLAG(IS_ANDROID)
  Browser* browser = chrome::FindBrowserWithTab(web_contents());
  if (!browser) {
    return;
  }

  browser->command_controller()->ContentRestrictionsChanged();
#endif
}

std::vector<unsigned char> CoreTabHelper::EncodeImage(
    const gfx::Image& image,
    std::string& content_type,
    lens::mojom::ImageFormat& image_format) {
  std::optional<std::vector<uint8_t>> data =
      gfx::JPEGCodec::Encode(image.AsBitmap(), kEncodingQualityJpeg);

  if (data) {
    content_type = "image/jpeg";
    image_format = lens::mojom::ImageFormat::JPEG;
    return data.value();
  }

  // Get the front and end of the image bytes in order to store them in the
  // search_args to be sent as part of the PostContent in the request
  content_type = "image/png";
  image_format = lens::mojom::ImageFormat::PNG;
  auto bytes = image.As1xPNGBytes();
  return {bytes->begin(), bytes->end()};
}

// static
void CoreTabHelper::DownscaleAndEncodeBitmap(
    const SkBitmap& bitmap,
    int thumbnail_min_area,
    int thumbnail_max_width,
    int thumbnail_max_height,
    DownscaleAndEncodeBitmapCallback callback) {
  gfx::Size original_size;
  std::string content_type;
  gfx::Size downscaled_size;
  std::vector<lens::mojom::LatencyLogPtr> log_data;
  std::vector<unsigned char> thumbnail_data;

  if (bitmap.isNull()) {
    return std::move(callback).Run(thumbnail_data, content_type, original_size,
                                   downscaled_size, std::move(log_data));
  }

  original_size = gfx::Size(bitmap.width(), bitmap.height());
  gfx::SizeF scaled_size = gfx::SizeF(original_size);
  bool needs_downscale = false;

  if (original_size.GetArea() > thumbnail_min_area) {
    if (scaled_size.width() > thumbnail_max_width) {
      needs_downscale = true;
      scaled_size.Scale(thumbnail_max_width / scaled_size.width());
    }

    if (scaled_size.height() > thumbnail_max_height) {
      needs_downscale = true;
      scaled_size.Scale(thumbnail_max_height / scaled_size.height());
    }
  }

  SkBitmap thumbnail;
  if (needs_downscale) {
    log_data.push_back(lens::mojom::LatencyLog::New(
        lens::mojom::Phase::DOWNSCALE_START, original_size, gfx::Size(),
        lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
        /*encoded_size_bytes=*/0));
    thumbnail = skia::ImageOperations::Resize(
        bitmap, skia::ImageOperations::RESIZE_GOOD,
        static_cast<int>(scaled_size.width()),
        static_cast<int>(scaled_size.height()));
    downscaled_size = gfx::Size(thumbnail.width(), thumbnail.height());
    log_data.push_back(lens::mojom::LatencyLog::New(
        lens::mojom::Phase::DOWNSCALE_END, original_size, downscaled_size,
        lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
        /*encoded_size_bytes=*/0));
  } else {
    thumbnail = std::move(bitmap);
    downscaled_size = gfx::Size(original_size);
  }

  lens::mojom::ImageFormat encode_target_format;
  std::optional<std::vector<uint8_t>> encoded_data;
  log_data.push_back(lens::mojom::LatencyLog::New(
      lens::mojom::Phase::ENCODE_START, original_size, downscaled_size,
      lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
      /*encoded_size_bytes=*/0));
  if (thumbnail.isOpaque() && (encoded_data = gfx::JPEGCodec::Encode(
                                   thumbnail, kEncodingQualityJpeg))) {
    thumbnail_data.swap(encoded_data.value());
    content_type = "image/jpeg";
    encode_target_format = lens::mojom::ImageFormat::JPEG;
  } else if ((encoded_data =
                  gfx::WebpCodec::Encode(thumbnail, kEncodingQualityWebp))) {
    thumbnail_data.swap(encoded_data.value());
    content_type = "image/webp";
    encode_target_format = lens::mojom::ImageFormat::WEBP;
  }
  log_data.push_back(lens::mojom::LatencyLog::New(
      lens::mojom::Phase::ENCODE_END, original_size, downscaled_size,
      encode_target_format, base::Time::Now(),
      /*encoded_size_bytes=*/sizeof(unsigned char) * thumbnail_data.size()));
  return std::move(callback).Run(thumbnail_data, content_type, original_size,
                                 downscaled_size, std::move(log_data));
}

// static
lens::mojom::ImageFormat CoreTabHelper::EncodeImageIntoSearchArgs(
    const gfx::Image& image,
    size_t& encoded_size_bytes,
    TemplateURLRef::SearchTermsArgs& search_args) {
  lens::mojom::ImageFormat image_format;
  std::string content_type;
  std::vector<uint8_t> data = EncodeImage(image, content_type, image_format);
  encoded_size_bytes = sizeof(unsigned char) * data.size();
  search_args.image_thumbnail_content.assign(data.begin(), data.end());
  search_args.image_thumbnail_content_type = content_type;
  return image_format;
}

void CoreTabHelper::SearchWithLens(content::RenderFrameHost* render_frame_host,
                                   const GURL& src_url,
                                   lens::EntryPoint entry_point) {
  SearchByImageImpl(render_frame_host, src_url, kImageSearchThumbnailMinSize,
                    lens::kMaxPixelsForImageSearch,
                    lens::kMaxPixelsForImageSearch,
                    lens::GetQueryParametersForLensRequest(entry_point));
}

void CoreTabHelper::SearchWithLens(const gfx::Image& image,
                                   lens::EntryPoint entry_point) {
  auto lens_query_params = lens::GetQueryParametersForLensRequest(entry_point);

  SearchByImageImpl(image, lens_query_params);
}

void CoreTabHelper::SearchByImage(content::RenderFrameHost* render_frame_host,
                                  const GURL& src_url) {
  SearchByImageImpl(render_frame_host, src_url, kImageSearchThumbnailMinSize,
                    kImageSearchThumbnailMaxWidth,
                    kImageSearchThumbnailMaxHeight, std::string());
}

void CoreTabHelper::SearchByImage(const gfx::Image& image) {
  SearchByImageImpl(image,
                    /*additional_query_params=*/std::string());
}

void CoreTabHelper::SearchByImageImpl(
    const gfx::Image& original_image,
    const std::string& additional_query_params) {
  std::vector<lens::mojom::LatencyLogPtr> log_data;
  log_data.push_back(lens::mojom::LatencyLog::New(
      lens::mojom::Phase::OVERALL_START, gfx::Size(), gfx::Size(),
      lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
      /*encoded_size_bytes=*/0));

  // Downscale the `original_image` if needed.
  gfx::Image image = original_image;
  if (NeedsDownscale(original_image)) {
    log_data.push_back(lens::mojom::LatencyLog::New(
        lens::mojom::Phase::DOWNSCALE_START, original_image.Size(), gfx::Size(),
        lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
        /*encoded_size_bytes=*/0));

    image = DownscaleImage(original_image);

    log_data.push_back(lens::mojom::LatencyLog::New(
        lens::mojom::Phase::DOWNSCALE_END, original_image.Size(), image.Size(),
        lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
        /*encoded_size_bytes=*/0));
  }

  TemplateURLService* template_url_service = GetTemplateURLService();
  const TemplateURL* const default_provider =
      template_url_service->GetDefaultSearchProvider();
  DCHECK(default_provider);
  TemplateURLRef::SearchTermsArgs search_args =
      TemplateURLRef::SearchTermsArgs(std::u16string());

  log_data.push_back(lens::mojom::LatencyLog::New(
      lens::mojom::Phase::ENCODE_START, original_image.Size(), gfx::Size(),
      lens::mojom::ImageFormat::ORIGINAL, base::Time::Now(),
      /*encoded_size_bytes=*/0));

  size_t encoded_size_bytes;
  std::string content_type;
  std::vector<unsigned char> encoded_image_bytes;
  lens::mojom::ImageFormat image_format;
  image_format =
      EncodeImageIntoSearchArgs(image, encoded_size_bytes, search_args);
  log_data.push_back(lens::mojom::LatencyLog::New(
      lens::mojom::Phase::ENCODE_END, original_image.Size(), gfx::Size(),
      image_format, base::Time::Now(), encoded_size_bytes));

  std::string additional_query_params_modified = additional_query_params;
  if (base::FeatureList::IsEnabled(lens::features::kLensStandalone) &&
      search::DefaultSearchProviderIsGoogle(template_url_service)) {
    lens::AppendLogsQueryParam(&additional_query_params_modified,
                               std::move(log_data));
  }

  if (search::DefaultSearchProviderIsGoogle(template_url_service)) {
    search_args.processed_image_dimensions =
        base::NumberToString(image.Size().width()) + "," +
        base::NumberToString(image.Size().height());
  }

  search_args.image_original_size = original_image.Size();
  search_args.additional_query_params = additional_query_params_modified;
  TemplateURLRef::PostContent post_content;
  GURL search_url(default_provider->image_url_ref().ReplaceSearchTerms(
      search_args, template_url_service->search_terms_data(), &post_content));
  PostContentToURL(post_content, search_url);
}

void CoreTabHelper::SearchByImageImpl(
    content::RenderFrameHost* render_frame_host,
    const GURL& src_url,
    int thumbnail_min_area,
    int thumbnail_max_width,
    int thumbnail_max_height,
    const std::string& additional_query_params) {
  mojo::AssociatedRemote<chrome::mojom::ChromeRenderFrame> chrome_render_frame;
  render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(
      &chrome_render_frame);
  // Bind the InterfacePtr into the callback so that it's kept alive until
  // there's either a connection error or a response.
  auto* thumbnail_capturer_proxy = chrome_render_frame.get();
  thumbnail_capturer_proxy->RequestBitmapForContextNode(base::BindOnce(
      &CoreTabHelper::DoSearchByImageWithBitmap, weak_factory_.GetWeakPtr(),
      std::move(chrome_render_frame), src_url, additional_query_params,
      thumbnail_min_area, thumbnail_max_width, thumbnail_max_height));
}

// static
bool CoreTabHelper::GetStatusTextForWebContents(std::u16string* status_text,
                                                content::WebContents* source) {
#if BUILDFLAG(IS_ANDROID)
  NOTREACHED() << "If this ends up being used on Android update "
               << "ChromeContentBrowserClient::OverrideURLLoaderFactoryParams.";
#else
  if (!source->IsLoading() ||
      source->GetLoadState().state == net::LOAD_STATE_IDLE) {
    return false;
  }

  switch (source->GetLoadState().state) {
    case net::LOAD_STATE_WAITING_FOR_STALLED_SOCKET_POOL:
    case net::LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_WAITING_FOR_SOCKET_SLOT);
      return true;
    case net::LOAD_STATE_WAITING_FOR_DELEGATE:
      if (!source->GetLoadState().param.empty()) {
        *status_text = l10n_util::GetStringFUTF16(
            IDS_LOAD_STATE_WAITING_FOR_DELEGATE, source->GetLoadState().param);
        return true;
      } else {
        *status_text = l10n_util::GetStringUTF16(
            IDS_LOAD_STATE_WAITING_FOR_DELEGATE_GENERIC);
        return true;
      }
    case net::LOAD_STATE_WAITING_FOR_CACHE:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_WAITING_FOR_CACHE);
      return true;
    case net::LOAD_STATE_ESTABLISHING_PROXY_TUNNEL:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_ESTABLISHING_PROXY_TUNNEL);
      return true;
    case net::LOAD_STATE_DOWNLOADING_PAC_FILE:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_DOWNLOADING_PAC_FILE);
      return true;
    case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
      return true;
    case net::LOAD_STATE_RESOLVING_HOST_IN_PAC_FILE:
      *status_text =
          l10n_util::GetStringUTF16(IDS_LOAD_STATE_RESOLVING_HOST_IN_PAC_FILE);
      return true;
    case net::LOAD_STATE_RESOLVING_HOST:
      *status_text = l10n_util::GetStringUTF16(IDS_LOAD_STATE_RESOLVING_HOST);
      return true;
    case net::LOAD_STATE_CONNECTING:
      *status_text = l10n_util::GetStringUTF16(IDS_LOAD_STATE_CONNECTING);
      return true;
    case net::LOAD_STATE_SSL_HANDSHAKE:
      *status_text = l10n_util::GetStringUTF16(IDS_LOAD_STATE_SSL_HANDSHAKE);
      return true;
    case net::LOAD_STATE_SENDING_REQUEST:
      if (source->GetUploadSize()) {
        *status_text = l10n_util::GetStringFUTF16Int(
            IDS_LOAD_STATE_SENDING_REQUEST_WITH_PROGRESS,
            static_cast<int>((100 * source->GetUploadPosition()) /
                             source->GetUploadSize()));
        return true;
      } else {
        *status_text =
            l10n_util::GetStringUTF16(IDS_LOAD_STATE_SENDING_REQUEST);
        return true;
      }
    case net::LOAD_STATE_WAITING_FOR_RESPONSE:
      *status_text = l10n_util::GetStringFUTF16(
          IDS_LOAD_STATE_WAITING_FOR_RESPONSE, source->GetLoadStateHost());
      return true;
    // Ignore net::LOAD_STATE_READING_RESPONSE, net::LOAD_STATE_IDLE and
    // net::LOAD_STATE_OBSOLETE_WAITING_FOR_APPCACHE
    case net::LOAD_STATE_IDLE:
    case net::LOAD_STATE_READING_RESPONSE:
    case net::LOAD_STATE_OBSOLETE_WAITING_FOR_APPCACHE:
      break;
  }
  return false;
#endif  // BUILDFLAG(IS_ANDROID)
}

////////////////////////////////////////////////////////////////////////////////
// WebContentsObserver overrides

void CoreTabHelper::DidStartLoading() {
  UpdateContentRestrictions(0);
}

// Update back/forward buttons for web_contents that are active.
void CoreTabHelper::NavigationEntriesDeleted() {
#if !BUILDFLAG(IS_ANDROID)
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (web_contents() == browser->tab_strip_model()->GetActiveWebContents()) {
      browser->command_controller()->TabStateChanged();
    }
  }
#endif
}

// Notify browser commands that depend on whether focus is in the
// web contents or not.
void CoreTabHelper::OnWebContentsFocused(
    content::RenderWidgetHost* render_widget_host) {
#if !BUILDFLAG(IS_ANDROID)
  Browser* browser = chrome::FindBrowserWithTab(web_contents());
  if (browser) {
    browser->command_controller()->WebContentsFocusChanged();
  }
#endif  // BUILDFLAG(IS_ANDROID)
}

void CoreTabHelper::OnWebContentsLostFocus(
    content::RenderWidgetHost* render_widget_host) {
#if !BUILDFLAG(IS_ANDROID)
  Browser* browser = chrome::FindBrowserWithTab(web_contents());
  if (browser) {
    browser->command_controller()->WebContentsFocusChanged();
  }
#endif  // BUILDFLAG(IS_ANDROID)
}

void CoreTabHelper::DoSearchByImageWithBitmap(
    mojo::AssociatedRemote<chrome::mojom::ChromeRenderFrame>
        chrome_render_frame,
    const GURL& src_url,
    const std::string& additional_query_params,
    int thumbnail_min_area,
    int thumbnail_max_width,
    int thumbnail_max_height,
    const SkBitmap& bitmap) {
  base::ThreadPool::PostTask(base::BindOnce(
      &CoreTabHelper::DownscaleAndEncodeBitmap, bitmap, thumbnail_min_area,
      thumbnail_max_width, thumbnail_max_height,
      base::BindPostTask(base::SequencedTaskRunner::GetCurrentDefault(),
                         base::BindOnce(&CoreTabHelper::DoSearchByImage,
                                        weak_factory_.GetWeakPtr(), src_url,
                                        additional_query_params))));
}

void CoreTabHelper::DoSearchByImage(
    const GURL& src_url,
    const std::string& additional_query_params,
    const std::vector<unsigned char>& thumbnail_data,
    const std::string& content_type,
    const gfx::Size& original_size,
    const gfx::Size& downscaled_size,
    const std::vector<lens::mojom::LatencyLogPtr> log_data) {
  if (thumbnail_data.empty()) {
    return;
  }

  TemplateURLService* template_url_service = GetTemplateURLService();
  const TemplateURL* const default_provider =
      template_url_service->GetDefaultSearchProvider();
  DCHECK(default_provider);

  std::string additional_query_params_modified = additional_query_params;
  if (base::FeatureList::IsEnabled(lens::features::kLensStandalone) &&
      search::DefaultSearchProviderIsGoogle(template_url_service)) {
    lens::AppendLogsQueryParam(&additional_query_params_modified,
                               std::move(log_data));
  }

  TemplateURLRef::SearchTermsArgs search_args =
      TemplateURLRef::SearchTermsArgs(std::u16string());
  if (search::DefaultSearchProviderIsGoogle(template_url_service)) {
    search_args.processed_image_dimensions =
        base::NumberToString(downscaled_size.width()) + "," +
        base::NumberToString(downscaled_size.height());
  }

  search_args.image_thumbnail_content.assign(thumbnail_data.begin(),
                                             thumbnail_data.end());
  search_args.image_thumbnail_content_type = content_type;
  search_args.image_url = src_url;
  search_args.image_original_size = original_size;
  search_args.additional_query_params = additional_query_params_modified;
  TemplateURLRef::PostContent post_content;
  const TemplateURLRef& template_url = default_provider->image_url_ref();
  GURL search_url(template_url.ReplaceSearchTerms(
      search_args, template_url_service->search_terms_data(), &post_content));

  PostContentToURL(post_content, search_url);
}

TemplateURLService* CoreTabHelper::GetTemplateURLService() {
  Profile* profile =
      Profile::FromBrowserContext(web_contents()->GetBrowserContext());
  DCHECK(profile);
  TemplateURLService* template_url_service =
      TemplateURLServiceFactory::GetForProfile(profile);
  DCHECK(template_url_service);
  return template_url_service;
}

void CoreTabHelper::PostContentToURL(TemplateURLRef::PostContent post_content,
                                     GURL url) {
  if (!url.is_valid()) {
    return;
  }
  content::OpenURLParams open_url_params(
      url, content::Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui::PAGE_TRANSITION_LINK, false);
  const std::string& content_type = post_content.first;
  const std::string& post_data = post_content.second;
  if (!post_data.empty()) {
    DCHECK(!content_type.empty());
    open_url_params.post_data =
        network::ResourceRequestBody::CreateFromCopyOfBytes(
            base::as_byte_span(post_data));
    open_url_params.extra_headers +=
        base::StringPrintf("%s: %s\r\n", net::HttpRequestHeaders::kContentType,
                           content_type.c_str());
  }

  web_contents()->OpenURL(open_url_params, /*navigation_handle_callback=*/{});
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(CoreTabHelper);