• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
2 // reserved. Use of this source code is governed by a BSD-style license that
3 // can be found in the LICENSE file.
4 
5 #include "tests/cefclient/browser/client_handler.h"
6 
7 #include <stdio.h>
8 #include <algorithm>
9 #include <iomanip>
10 #include <sstream>
11 #include <string>
12 
13 #include "include/base/cef_bind.h"
14 #include "include/cef_browser.h"
15 #include "include/cef_frame.h"
16 #include "include/cef_parser.h"
17 #include "include/cef_ssl_status.h"
18 #include "include/cef_x509_certificate.h"
19 #include "include/wrapper/cef_closure_task.h"
20 #include "tests/cefclient/browser/main_context.h"
21 #include "tests/cefclient/browser/root_window_manager.h"
22 #include "tests/cefclient/browser/test_runner.h"
23 #include "tests/shared/browser/extension_util.h"
24 #include "tests/shared/browser/resource_util.h"
25 #include "tests/shared/common/client_switches.h"
26 
27 namespace client {
28 
29 #if defined(OS_WIN)
30 #define NEWLINE "\r\n"
31 #else
32 #define NEWLINE "\n"
33 #endif
34 
35 namespace {
36 
37 // Custom menu command Ids.
38 enum client_menu_ids {
39   CLIENT_ID_SHOW_DEVTOOLS = MENU_ID_USER_FIRST,
40   CLIENT_ID_CLOSE_DEVTOOLS,
41   CLIENT_ID_INSPECT_ELEMENT,
42   CLIENT_ID_SHOW_SSL_INFO,
43   CLIENT_ID_CURSOR_CHANGE_DISABLED,
44   CLIENT_ID_OFFLINE,
45   CLIENT_ID_TESTMENU_SUBMENU,
46   CLIENT_ID_TESTMENU_CHECKITEM,
47   CLIENT_ID_TESTMENU_RADIOITEM1,
48   CLIENT_ID_TESTMENU_RADIOITEM2,
49   CLIENT_ID_TESTMENU_RADIOITEM3,
50 };
51 
52 // Musr match the value in client_renderer.cc.
53 const char kFocusedNodeChangedMessage[] = "ClientRenderer.FocusedNodeChanged";
54 
GetTimeString(const CefTime & value)55 std::string GetTimeString(const CefTime& value) {
56   if (value.GetTimeT() == 0)
57     return "Unspecified";
58 
59   static const char* kMonths[] = {
60       "January", "February", "March",     "April",   "May",      "June",
61       "July",    "August",   "September", "October", "November", "December"};
62   std::string month;
63   if (value.month >= 1 && value.month <= 12)
64     month = kMonths[value.month - 1];
65   else
66     month = "Invalid";
67 
68   std::stringstream ss;
69   ss << month << " " << value.day_of_month << ", " << value.year << " "
70      << std::setfill('0') << std::setw(2) << value.hour << ":"
71      << std::setfill('0') << std::setw(2) << value.minute << ":"
72      << std::setfill('0') << std::setw(2) << value.second;
73   return ss.str();
74 }
75 
GetBinaryString(CefRefPtr<CefBinaryValue> value)76 std::string GetBinaryString(CefRefPtr<CefBinaryValue> value) {
77   if (!value.get())
78     return "&nbsp;";
79 
80   // Retrieve the value.
81   const size_t size = value->GetSize();
82   std::string src;
83   src.resize(size);
84   value->GetData(const_cast<char*>(src.data()), size, 0);
85 
86   // Encode the value.
87   return CefBase64Encode(src.data(), src.size());
88 }
89 
90 #define FLAG(flag)                          \
91   if (status & flag) {                      \
92     result += std::string(#flag) + "<br/>"; \
93   }
94 
95 #define VALUE(val, def)       \
96   if (val == def) {           \
97     return std::string(#def); \
98   }
99 
GetCertStatusString(cef_cert_status_t status)100 std::string GetCertStatusString(cef_cert_status_t status) {
101   std::string result;
102 
103   FLAG(CERT_STATUS_COMMON_NAME_INVALID);
104   FLAG(CERT_STATUS_DATE_INVALID);
105   FLAG(CERT_STATUS_AUTHORITY_INVALID);
106   FLAG(CERT_STATUS_NO_REVOCATION_MECHANISM);
107   FLAG(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
108   FLAG(CERT_STATUS_REVOKED);
109   FLAG(CERT_STATUS_INVALID);
110   FLAG(CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
111   FLAG(CERT_STATUS_NON_UNIQUE_NAME);
112   FLAG(CERT_STATUS_WEAK_KEY);
113   FLAG(CERT_STATUS_PINNED_KEY_MISSING);
114   FLAG(CERT_STATUS_NAME_CONSTRAINT_VIOLATION);
115   FLAG(CERT_STATUS_VALIDITY_TOO_LONG);
116   FLAG(CERT_STATUS_IS_EV);
117   FLAG(CERT_STATUS_REV_CHECKING_ENABLED);
118   FLAG(CERT_STATUS_SHA1_SIGNATURE_PRESENT);
119   FLAG(CERT_STATUS_CT_COMPLIANCE_FAILED);
120 
121   if (result.empty())
122     return "&nbsp;";
123   return result;
124 }
125 
GetSSLVersionString(cef_ssl_version_t version)126 std::string GetSSLVersionString(cef_ssl_version_t version) {
127   VALUE(version, SSL_CONNECTION_VERSION_UNKNOWN);
128   VALUE(version, SSL_CONNECTION_VERSION_SSL2);
129   VALUE(version, SSL_CONNECTION_VERSION_SSL3);
130   VALUE(version, SSL_CONNECTION_VERSION_TLS1);
131   VALUE(version, SSL_CONNECTION_VERSION_TLS1_1);
132   VALUE(version, SSL_CONNECTION_VERSION_TLS1_2);
133   VALUE(version, SSL_CONNECTION_VERSION_TLS1_3);
134   VALUE(version, SSL_CONNECTION_VERSION_QUIC);
135   return std::string();
136 }
137 
GetContentStatusString(cef_ssl_content_status_t status)138 std::string GetContentStatusString(cef_ssl_content_status_t status) {
139   std::string result;
140 
141   VALUE(status, SSL_CONTENT_NORMAL_CONTENT);
142   FLAG(SSL_CONTENT_DISPLAYED_INSECURE_CONTENT);
143   FLAG(SSL_CONTENT_RAN_INSECURE_CONTENT);
144 
145   if (result.empty())
146     return "&nbsp;";
147   return result;
148 }
149 
150 // Load a data: URI containing the error message.
LoadErrorPage(CefRefPtr<CefFrame> frame,const std::string & failed_url,cef_errorcode_t error_code,const std::string & other_info)151 void LoadErrorPage(CefRefPtr<CefFrame> frame,
152                    const std::string& failed_url,
153                    cef_errorcode_t error_code,
154                    const std::string& other_info) {
155   std::stringstream ss;
156   ss << "<html><head><title>Page failed to load</title></head>"
157         "<body bgcolor=\"white\">"
158         "<h3>Page failed to load.</h3>"
159         "URL: <a href=\""
160      << failed_url << "\">" << failed_url
161      << "</a><br/>Error: " << test_runner::GetErrorString(error_code) << " ("
162      << error_code << ")";
163 
164   if (!other_info.empty())
165     ss << "<br/>" << other_info;
166 
167   ss << "</body></html>";
168   frame->LoadURL(test_runner::GetDataURI(ss.str(), "text/html"));
169 }
170 
171 // Return HTML string with information about a certificate.
GetCertificateInformation(CefRefPtr<CefX509Certificate> cert,cef_cert_status_t certstatus)172 std::string GetCertificateInformation(CefRefPtr<CefX509Certificate> cert,
173                                       cef_cert_status_t certstatus) {
174   CefRefPtr<CefX509CertPrincipal> subject = cert->GetSubject();
175   CefRefPtr<CefX509CertPrincipal> issuer = cert->GetIssuer();
176 
177   // Build a table showing certificate information. Various types of invalid
178   // certificates can be tested using https://badssl.com/.
179   std::stringstream ss;
180   ss << "<h3>X.509 Certificate Information:</h3>"
181         "<table border=1><tr><th>Field</th><th>Value</th></tr>";
182 
183   if (certstatus != CERT_STATUS_NONE) {
184     ss << "<tr><td>Status</td><td>" << GetCertStatusString(certstatus)
185        << "</td></tr>";
186   }
187 
188   ss << "<tr><td>Subject</td><td>"
189      << (subject.get() ? subject->GetDisplayName().ToString() : "&nbsp;")
190      << "</td></tr>"
191         "<tr><td>Issuer</td><td>"
192      << (issuer.get() ? issuer->GetDisplayName().ToString() : "&nbsp;")
193      << "</td></tr>"
194         "<tr><td>Serial #*</td><td>"
195      << GetBinaryString(cert->GetSerialNumber()) << "</td></tr>"
196      << "<tr><td>Valid Start</td><td>" << GetTimeString(cert->GetValidStart())
197      << "</td></tr>"
198         "<tr><td>Valid Expiry</td><td>"
199      << GetTimeString(cert->GetValidExpiry()) << "</td></tr>";
200 
201   CefX509Certificate::IssuerChainBinaryList der_chain_list;
202   CefX509Certificate::IssuerChainBinaryList pem_chain_list;
203   cert->GetDEREncodedIssuerChain(der_chain_list);
204   cert->GetPEMEncodedIssuerChain(pem_chain_list);
205   DCHECK_EQ(der_chain_list.size(), pem_chain_list.size());
206 
207   der_chain_list.insert(der_chain_list.begin(), cert->GetDEREncoded());
208   pem_chain_list.insert(pem_chain_list.begin(), cert->GetPEMEncoded());
209 
210   for (size_t i = 0U; i < der_chain_list.size(); ++i) {
211     ss << "<tr><td>DER Encoded*</td>"
212           "<td style=\"max-width:800px;overflow:scroll;\">"
213        << GetBinaryString(der_chain_list[i])
214        << "</td></tr>"
215           "<tr><td>PEM Encoded*</td>"
216           "<td style=\"max-width:800px;overflow:scroll;\">"
217        << GetBinaryString(pem_chain_list[i]) << "</td></tr>";
218   }
219 
220   ss << "</table> * Displayed value is base64 encoded.";
221   return ss.str();
222 }
223 
224 }  // namespace
225 
226 class ClientDownloadImageCallback : public CefDownloadImageCallback {
227  public:
ClientDownloadImageCallback(CefRefPtr<ClientHandler> client_handler)228   explicit ClientDownloadImageCallback(CefRefPtr<ClientHandler> client_handler)
229       : client_handler_(client_handler) {}
230 
OnDownloadImageFinished(const CefString & image_url,int http_status_code,CefRefPtr<CefImage> image)231   void OnDownloadImageFinished(const CefString& image_url,
232                                int http_status_code,
233                                CefRefPtr<CefImage> image) OVERRIDE {
234     if (image)
235       client_handler_->NotifyFavicon(image);
236   }
237 
238  private:
239   CefRefPtr<ClientHandler> client_handler_;
240 
241   IMPLEMENT_REFCOUNTING(ClientDownloadImageCallback);
242   DISALLOW_COPY_AND_ASSIGN(ClientDownloadImageCallback);
243 };
244 
ClientHandler(Delegate * delegate,bool is_osr,const std::string & startup_url)245 ClientHandler::ClientHandler(Delegate* delegate,
246                              bool is_osr,
247                              const std::string& startup_url)
248     : is_osr_(is_osr),
249       startup_url_(startup_url),
250       download_favicon_images_(false),
251       delegate_(delegate),
252       browser_count_(0),
253       console_log_file_(MainContext::Get()->GetConsoleLogPath()),
254       first_console_message_(true),
255       focus_on_editable_field_(false),
256       initial_navigation_(true) {
257   DCHECK(!console_log_file_.empty());
258 
259 #if defined(OS_LINUX)
260   // Provide the GTK-based dialog implementation on Linux.
261   dialog_handler_ = new ClientDialogHandlerGtk();
262   print_handler_ = new ClientPrintHandlerGtk();
263 #endif
264 
265   resource_manager_ = new CefResourceManager();
266   test_runner::SetupResourceManager(resource_manager_, &string_resource_map_);
267 
268   // Read command line settings.
269   CefRefPtr<CefCommandLine> command_line =
270       CefCommandLine::GetGlobalCommandLine();
271   mouse_cursor_change_disabled_ =
272       command_line->HasSwitch(switches::kMouseCursorChangeDisabled);
273   offline_ = command_line->HasSwitch(switches::kOffline);
274 }
275 
DetachDelegate()276 void ClientHandler::DetachDelegate() {
277   if (!CURRENTLY_ON_MAIN_THREAD()) {
278     // Execute this method on the main thread.
279     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::DetachDelegate, this));
280     return;
281   }
282 
283   DCHECK(delegate_);
284   delegate_ = nullptr;
285 }
286 
OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefProcessId source_process,CefRefPtr<CefProcessMessage> message)287 bool ClientHandler::OnProcessMessageReceived(
288     CefRefPtr<CefBrowser> browser,
289     CefRefPtr<CefFrame> frame,
290     CefProcessId source_process,
291     CefRefPtr<CefProcessMessage> message) {
292   CEF_REQUIRE_UI_THREAD();
293 
294   if (message_router_->OnProcessMessageReceived(browser, frame, source_process,
295                                                 message)) {
296     return true;
297   }
298 
299   // Check for messages from the client renderer.
300   std::string message_name = message->GetName();
301   if (message_name == kFocusedNodeChangedMessage) {
302     // A message is sent from ClientRenderDelegate to tell us whether the
303     // currently focused DOM node is editable. Use of |focus_on_editable_field_|
304     // is redundant with CefKeyEvent.focus_on_editable_field in OnPreKeyEvent
305     // but is useful for demonstration purposes.
306     focus_on_editable_field_ = message->GetArgumentList()->GetBool(0);
307     return true;
308   }
309 
310   return false;
311 }
312 
OnBeforeContextMenu(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefContextMenuParams> params,CefRefPtr<CefMenuModel> model)313 void ClientHandler::OnBeforeContextMenu(CefRefPtr<CefBrowser> browser,
314                                         CefRefPtr<CefFrame> frame,
315                                         CefRefPtr<CefContextMenuParams> params,
316                                         CefRefPtr<CefMenuModel> model) {
317   CEF_REQUIRE_UI_THREAD();
318 
319   if ((params->GetTypeFlags() & (CM_TYPEFLAG_PAGE | CM_TYPEFLAG_FRAME)) != 0) {
320     // Add a separator if the menu already has items.
321     if (model->GetCount() > 0)
322       model->AddSeparator();
323 
324     const bool use_chrome_runtime = MainContext::Get()->UseChromeRuntime();
325     if (!use_chrome_runtime) {
326       // TODO(chrome-runtime): Add support for this.
327       // Add DevTools items to all context menus.
328       model->AddItem(CLIENT_ID_SHOW_DEVTOOLS, "&Show DevTools");
329       model->AddItem(CLIENT_ID_CLOSE_DEVTOOLS, "Close DevTools");
330       model->AddSeparator();
331       model->AddItem(CLIENT_ID_INSPECT_ELEMENT, "Inspect Element");
332     }
333 
334     if (HasSSLInformation(browser)) {
335       model->AddSeparator();
336       model->AddItem(CLIENT_ID_SHOW_SSL_INFO, "Show SSL information");
337     }
338 
339     if (!use_chrome_runtime) {
340       // TODO(chrome-runtime): Add support for this.
341       model->AddSeparator();
342       model->AddCheckItem(CLIENT_ID_CURSOR_CHANGE_DISABLED,
343                           "Cursor change disabled");
344       if (mouse_cursor_change_disabled_)
345         model->SetChecked(CLIENT_ID_CURSOR_CHANGE_DISABLED, true);
346     }
347 
348     model->AddSeparator();
349     model->AddCheckItem(CLIENT_ID_OFFLINE, "Offline mode");
350     if (offline_)
351       model->SetChecked(CLIENT_ID_OFFLINE, true);
352 
353     // Test context menu features.
354     BuildTestMenu(model);
355   }
356 
357   if (delegate_)
358     delegate_->OnBeforeContextMenu(model);
359 }
360 
OnContextMenuCommand(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefContextMenuParams> params,int command_id,EventFlags event_flags)361 bool ClientHandler::OnContextMenuCommand(CefRefPtr<CefBrowser> browser,
362                                          CefRefPtr<CefFrame> frame,
363                                          CefRefPtr<CefContextMenuParams> params,
364                                          int command_id,
365                                          EventFlags event_flags) {
366   CEF_REQUIRE_UI_THREAD();
367 
368   switch (command_id) {
369     case CLIENT_ID_SHOW_DEVTOOLS:
370       ShowDevTools(browser, CefPoint());
371       return true;
372     case CLIENT_ID_CLOSE_DEVTOOLS:
373       CloseDevTools(browser);
374       return true;
375     case CLIENT_ID_INSPECT_ELEMENT:
376       ShowDevTools(browser, CefPoint(params->GetXCoord(), params->GetYCoord()));
377       return true;
378     case CLIENT_ID_SHOW_SSL_INFO:
379       ShowSSLInformation(browser);
380       return true;
381     case CLIENT_ID_CURSOR_CHANGE_DISABLED:
382       mouse_cursor_change_disabled_ = !mouse_cursor_change_disabled_;
383       return true;
384     case CLIENT_ID_OFFLINE:
385       offline_ = !offline_;
386       SetOfflineState(browser, offline_);
387       return true;
388     default:  // Allow default handling, if any.
389       return ExecuteTestMenu(command_id);
390   }
391 }
392 
OnAddressChange(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,const CefString & url)393 void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
394                                     CefRefPtr<CefFrame> frame,
395                                     const CefString& url) {
396   CEF_REQUIRE_UI_THREAD();
397 
398   // Only update the address for the main (top-level) frame.
399   if (frame->IsMain())
400     NotifyAddress(url);
401 }
402 
OnTitleChange(CefRefPtr<CefBrowser> browser,const CefString & title)403 void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
404                                   const CefString& title) {
405   CEF_REQUIRE_UI_THREAD();
406 
407   NotifyTitle(title);
408 }
409 
OnFaviconURLChange(CefRefPtr<CefBrowser> browser,const std::vector<CefString> & icon_urls)410 void ClientHandler::OnFaviconURLChange(
411     CefRefPtr<CefBrowser> browser,
412     const std::vector<CefString>& icon_urls) {
413   CEF_REQUIRE_UI_THREAD();
414 
415   if (!icon_urls.empty() && download_favicon_images_) {
416     browser->GetHost()->DownloadImage(icon_urls[0], true, 16, false,
417                                       new ClientDownloadImageCallback(this));
418   }
419 }
420 
OnFullscreenModeChange(CefRefPtr<CefBrowser> browser,bool fullscreen)421 void ClientHandler::OnFullscreenModeChange(CefRefPtr<CefBrowser> browser,
422                                            bool fullscreen) {
423   CEF_REQUIRE_UI_THREAD();
424 
425   NotifyFullscreen(fullscreen);
426 }
427 
OnConsoleMessage(CefRefPtr<CefBrowser> browser,cef_log_severity_t level,const CefString & message,const CefString & source,int line)428 bool ClientHandler::OnConsoleMessage(CefRefPtr<CefBrowser> browser,
429                                      cef_log_severity_t level,
430                                      const CefString& message,
431                                      const CefString& source,
432                                      int line) {
433   CEF_REQUIRE_UI_THREAD();
434 
435   FILE* file = fopen(console_log_file_.c_str(), "a");
436   if (file) {
437     std::stringstream ss;
438     ss << "Level: ";
439     switch (level) {
440       case LOGSEVERITY_DEBUG:
441         ss << "Debug" << NEWLINE;
442         break;
443       case LOGSEVERITY_INFO:
444         ss << "Info" << NEWLINE;
445         break;
446       case LOGSEVERITY_WARNING:
447         ss << "Warn" << NEWLINE;
448         break;
449       case LOGSEVERITY_ERROR:
450         ss << "Error" << NEWLINE;
451         break;
452       default:
453         NOTREACHED();
454         break;
455     }
456     ss << "Message: " << message.ToString() << NEWLINE
457        << "Source: " << source.ToString() << NEWLINE << "Line: " << line
458        << NEWLINE << "-----------------------" << NEWLINE;
459     fputs(ss.str().c_str(), file);
460     fclose(file);
461 
462     if (first_console_message_) {
463       test_runner::Alert(
464           browser, "Console messages written to \"" + console_log_file_ + "\"");
465       first_console_message_ = false;
466     }
467   }
468 
469   return false;
470 }
471 
OnAutoResize(CefRefPtr<CefBrowser> browser,const CefSize & new_size)472 bool ClientHandler::OnAutoResize(CefRefPtr<CefBrowser> browser,
473                                  const CefSize& new_size) {
474   CEF_REQUIRE_UI_THREAD();
475 
476   NotifyAutoResize(new_size);
477   return true;
478 }
479 
OnCursorChange(CefRefPtr<CefBrowser> browser,CefCursorHandle cursor,cef_cursor_type_t type,const CefCursorInfo & custom_cursor_info)480 bool ClientHandler::OnCursorChange(CefRefPtr<CefBrowser> browser,
481                                    CefCursorHandle cursor,
482                                    cef_cursor_type_t type,
483                                    const CefCursorInfo& custom_cursor_info) {
484   CEF_REQUIRE_UI_THREAD();
485 
486   // Return true to disable default handling of cursor changes.
487   return mouse_cursor_change_disabled_;
488 }
489 
OnBeforeDownload(CefRefPtr<CefBrowser> browser,CefRefPtr<CefDownloadItem> download_item,const CefString & suggested_name,CefRefPtr<CefBeforeDownloadCallback> callback)490 void ClientHandler::OnBeforeDownload(
491     CefRefPtr<CefBrowser> browser,
492     CefRefPtr<CefDownloadItem> download_item,
493     const CefString& suggested_name,
494     CefRefPtr<CefBeforeDownloadCallback> callback) {
495   CEF_REQUIRE_UI_THREAD();
496 
497   // Continue the download and show the "Save As" dialog.
498   callback->Continue(MainContext::Get()->GetDownloadPath(suggested_name), true);
499 }
500 
OnDownloadUpdated(CefRefPtr<CefBrowser> browser,CefRefPtr<CefDownloadItem> download_item,CefRefPtr<CefDownloadItemCallback> callback)501 void ClientHandler::OnDownloadUpdated(
502     CefRefPtr<CefBrowser> browser,
503     CefRefPtr<CefDownloadItem> download_item,
504     CefRefPtr<CefDownloadItemCallback> callback) {
505   CEF_REQUIRE_UI_THREAD();
506 
507   if (download_item->IsComplete()) {
508     test_runner::Alert(browser, "File \"" +
509                                     download_item->GetFullPath().ToString() +
510                                     "\" downloaded successfully.");
511   }
512 }
513 
OnDragEnter(CefRefPtr<CefBrowser> browser,CefRefPtr<CefDragData> dragData,CefDragHandler::DragOperationsMask mask)514 bool ClientHandler::OnDragEnter(CefRefPtr<CefBrowser> browser,
515                                 CefRefPtr<CefDragData> dragData,
516                                 CefDragHandler::DragOperationsMask mask) {
517   CEF_REQUIRE_UI_THREAD();
518 
519   // Forbid dragging of URLs and files.
520   if ((mask & DRAG_OPERATION_LINK) && !dragData->IsFragment()) {
521     test_runner::Alert(browser, "cefclient blocks dragging of URLs and files");
522     return true;
523   }
524 
525   return false;
526 }
527 
OnDraggableRegionsChanged(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,const std::vector<CefDraggableRegion> & regions)528 void ClientHandler::OnDraggableRegionsChanged(
529     CefRefPtr<CefBrowser> browser,
530     CefRefPtr<CefFrame> frame,
531     const std::vector<CefDraggableRegion>& regions) {
532   CEF_REQUIRE_UI_THREAD();
533 
534   NotifyDraggableRegions(regions);
535 }
536 
OnTakeFocus(CefRefPtr<CefBrowser> browser,bool next)537 void ClientHandler::OnTakeFocus(CefRefPtr<CefBrowser> browser, bool next) {
538   CEF_REQUIRE_UI_THREAD();
539 
540   NotifyTakeFocus(next);
541 }
542 
OnSetFocus(CefRefPtr<CefBrowser> browser,FocusSource source)543 bool ClientHandler::OnSetFocus(CefRefPtr<CefBrowser> browser,
544                                FocusSource source) {
545   CEF_REQUIRE_UI_THREAD();
546 
547   if (initial_navigation_) {
548     CefRefPtr<CefCommandLine> command_line =
549         CefCommandLine::GetGlobalCommandLine();
550     if (command_line->HasSwitch(switches::kNoActivate)) {
551       // Don't give focus to the browser on creation.
552       return true;
553     }
554   }
555 
556   return false;
557 }
558 
OnPreKeyEvent(CefRefPtr<CefBrowser> browser,const CefKeyEvent & event,CefEventHandle os_event,bool * is_keyboard_shortcut)559 bool ClientHandler::OnPreKeyEvent(CefRefPtr<CefBrowser> browser,
560                                   const CefKeyEvent& event,
561                                   CefEventHandle os_event,
562                                   bool* is_keyboard_shortcut) {
563   CEF_REQUIRE_UI_THREAD();
564 
565   if (!event.focus_on_editable_field && event.windows_key_code == 0x20) {
566     // Special handling for the space character when an input element does not
567     // have focus. Handling the event in OnPreKeyEvent() keeps the event from
568     // being processed in the renderer. If we instead handled the event in the
569     // OnKeyEvent() method the space key would cause the window to scroll in
570     // addition to showing the alert box.
571     if (event.type == KEYEVENT_RAWKEYDOWN)
572       test_runner::Alert(browser, "You pressed the space bar!");
573     return true;
574   }
575 
576   return false;
577 }
578 
OnBeforePopup(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,const CefString & target_url,const CefString & target_frame_name,CefLifeSpanHandler::WindowOpenDisposition target_disposition,bool user_gesture,const CefPopupFeatures & popupFeatures,CefWindowInfo & windowInfo,CefRefPtr<CefClient> & client,CefBrowserSettings & settings,CefRefPtr<CefDictionaryValue> & extra_info,bool * no_javascript_access)579 bool ClientHandler::OnBeforePopup(
580     CefRefPtr<CefBrowser> browser,
581     CefRefPtr<CefFrame> frame,
582     const CefString& target_url,
583     const CefString& target_frame_name,
584     CefLifeSpanHandler::WindowOpenDisposition target_disposition,
585     bool user_gesture,
586     const CefPopupFeatures& popupFeatures,
587     CefWindowInfo& windowInfo,
588     CefRefPtr<CefClient>& client,
589     CefBrowserSettings& settings,
590     CefRefPtr<CefDictionaryValue>& extra_info,
591     bool* no_javascript_access) {
592   CEF_REQUIRE_UI_THREAD();
593 
594   // Return true to cancel the popup window.
595   return !CreatePopupWindow(browser, false, popupFeatures, windowInfo, client,
596                             settings);
597 }
598 
OnAfterCreated(CefRefPtr<CefBrowser> browser)599 void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
600   CEF_REQUIRE_UI_THREAD();
601 
602   browser_count_++;
603 
604   if (!message_router_) {
605     // Create the browser-side router for query handling.
606     CefMessageRouterConfig config;
607     message_router_ = CefMessageRouterBrowserSide::Create(config);
608 
609     // Register handlers with the router.
610     test_runner::CreateMessageHandlers(message_handler_set_);
611     MessageHandlerSet::const_iterator it = message_handler_set_.begin();
612     for (; it != message_handler_set_.end(); ++it)
613       message_router_->AddHandler(*(it), false);
614   }
615 
616   // Set offline mode if requested via the command-line flag.
617   if (offline_)
618     SetOfflineState(browser, true);
619 
620   if (browser->GetHost()->GetExtension()) {
621     // Browsers hosting extension apps should auto-resize.
622     browser->GetHost()->SetAutoResizeEnabled(true, CefSize(20, 20),
623                                              CefSize(1000, 1000));
624 
625     CefRefPtr<CefExtension> extension = browser->GetHost()->GetExtension();
626     if (extension_util::IsInternalExtension(extension->GetPath())) {
627       // Register the internal handler for extension resources.
628       extension_util::AddInternalExtensionToResourceManager(extension,
629                                                             resource_manager_);
630     }
631   }
632 
633   NotifyBrowserCreated(browser);
634 }
635 
DoClose(CefRefPtr<CefBrowser> browser)636 bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
637   CEF_REQUIRE_UI_THREAD();
638 
639   NotifyBrowserClosing(browser);
640 
641   // Allow the close. For windowed browsers this will result in the OS close
642   // event being sent.
643   return false;
644 }
645 
OnBeforeClose(CefRefPtr<CefBrowser> browser)646 void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
647   CEF_REQUIRE_UI_THREAD();
648 
649   if (--browser_count_ == 0) {
650     // Remove and delete message router handlers.
651     MessageHandlerSet::const_iterator it = message_handler_set_.begin();
652     for (; it != message_handler_set_.end(); ++it) {
653       message_router_->RemoveHandler(*(it));
654       delete *(it);
655     }
656     message_handler_set_.clear();
657     message_router_ = nullptr;
658   }
659 
660   NotifyBrowserClosed(browser);
661 }
662 
OnLoadingStateChange(CefRefPtr<CefBrowser> browser,bool isLoading,bool canGoBack,bool canGoForward)663 void ClientHandler::OnLoadingStateChange(CefRefPtr<CefBrowser> browser,
664                                          bool isLoading,
665                                          bool canGoBack,
666                                          bool canGoForward) {
667   CEF_REQUIRE_UI_THREAD();
668 
669   if (!isLoading && initial_navigation_) {
670     initial_navigation_ = false;
671   }
672 
673   NotifyLoadingState(isLoading, canGoBack, canGoForward);
674 }
675 
OnLoadError(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,ErrorCode errorCode,const CefString & errorText,const CefString & failedUrl)676 void ClientHandler::OnLoadError(CefRefPtr<CefBrowser> browser,
677                                 CefRefPtr<CefFrame> frame,
678                                 ErrorCode errorCode,
679                                 const CefString& errorText,
680                                 const CefString& failedUrl) {
681   CEF_REQUIRE_UI_THREAD();
682 
683   // Don't display an error for downloaded files.
684   if (errorCode == ERR_ABORTED)
685     return;
686 
687   // Don't display an error for external protocols that we allow the OS to
688   // handle. See OnProtocolExecution().
689   if (errorCode == ERR_UNKNOWN_URL_SCHEME) {
690     std::string urlStr = frame->GetURL();
691     if (urlStr.find("spotify:") == 0)
692       return;
693   }
694 
695   // Load the error page.
696   LoadErrorPage(frame, failedUrl, errorCode, errorText);
697 }
698 
OnBeforeBrowse(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,bool user_gesture,bool is_redirect)699 bool ClientHandler::OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
700                                    CefRefPtr<CefFrame> frame,
701                                    CefRefPtr<CefRequest> request,
702                                    bool user_gesture,
703                                    bool is_redirect) {
704   CEF_REQUIRE_UI_THREAD();
705 
706   message_router_->OnBeforeBrowse(browser, frame);
707   return false;
708 }
709 
OnOpenURLFromTab(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,const CefString & target_url,CefRequestHandler::WindowOpenDisposition target_disposition,bool user_gesture)710 bool ClientHandler::OnOpenURLFromTab(
711     CefRefPtr<CefBrowser> browser,
712     CefRefPtr<CefFrame> frame,
713     const CefString& target_url,
714     CefRequestHandler::WindowOpenDisposition target_disposition,
715     bool user_gesture) {
716   if (target_disposition == WOD_NEW_BACKGROUND_TAB ||
717       target_disposition == WOD_NEW_FOREGROUND_TAB) {
718     // Handle middle-click and ctrl + left-click by opening the URL in a new
719     // browser window.
720     RootWindowConfig config;
721     config.with_controls = true;
722     config.with_osr = is_osr();
723     config.url = target_url;
724     MainContext::Get()->GetRootWindowManager()->CreateRootWindow(config);
725     return true;
726   }
727 
728   // Open the URL in the current browser window.
729   return false;
730 }
731 
GetResourceRequestHandler(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,bool is_navigation,bool is_download,const CefString & request_initiator,bool & disable_default_handling)732 CefRefPtr<CefResourceRequestHandler> ClientHandler::GetResourceRequestHandler(
733     CefRefPtr<CefBrowser> browser,
734     CefRefPtr<CefFrame> frame,
735     CefRefPtr<CefRequest> request,
736     bool is_navigation,
737     bool is_download,
738     const CefString& request_initiator,
739     bool& disable_default_handling) {
740   CEF_REQUIRE_IO_THREAD();
741   return this;
742 }
743 
GetAuthCredentials(CefRefPtr<CefBrowser> browser,const CefString & origin_url,bool isProxy,const CefString & host,int port,const CefString & realm,const CefString & scheme,CefRefPtr<CefAuthCallback> callback)744 bool ClientHandler::GetAuthCredentials(CefRefPtr<CefBrowser> browser,
745                                        const CefString& origin_url,
746                                        bool isProxy,
747                                        const CefString& host,
748                                        int port,
749                                        const CefString& realm,
750                                        const CefString& scheme,
751                                        CefRefPtr<CefAuthCallback> callback) {
752   CEF_REQUIRE_IO_THREAD();
753 
754   // Used for testing authentication with a proxy server.
755   // For example, CCProxy on Windows.
756   if (isProxy) {
757     callback->Continue("guest", "guest");
758     return true;
759   }
760 
761   // Used for testing authentication with https://jigsaw.w3.org/HTTP/.
762   if (host == "jigsaw.w3.org") {
763     callback->Continue("guest", "guest");
764     return true;
765   }
766 
767   return false;
768 }
769 
OnQuotaRequest(CefRefPtr<CefBrowser> browser,const CefString & origin_url,int64 new_size,CefRefPtr<CefRequestCallback> callback)770 bool ClientHandler::OnQuotaRequest(CefRefPtr<CefBrowser> browser,
771                                    const CefString& origin_url,
772                                    int64 new_size,
773                                    CefRefPtr<CefRequestCallback> callback) {
774   CEF_REQUIRE_IO_THREAD();
775 
776   static const int64 max_size = 1024 * 1024 * 20;  // 20mb.
777 
778   // Grant the quota request if the size is reasonable.
779   callback->Continue(new_size <= max_size);
780   return true;
781 }
782 
OnCertificateError(CefRefPtr<CefBrowser> browser,ErrorCode cert_error,const CefString & request_url,CefRefPtr<CefSSLInfo> ssl_info,CefRefPtr<CefRequestCallback> callback)783 bool ClientHandler::OnCertificateError(CefRefPtr<CefBrowser> browser,
784                                        ErrorCode cert_error,
785                                        const CefString& request_url,
786                                        CefRefPtr<CefSSLInfo> ssl_info,
787                                        CefRefPtr<CefRequestCallback> callback) {
788   CEF_REQUIRE_UI_THREAD();
789 
790   if (cert_error == ERR_CERT_AUTHORITY_INVALID &&
791       request_url.ToString().find("https://www.magpcss.org/") == 0U) {
792     // Allow the CEF Forum to load. It has a self-signed certificate.
793     callback->Continue(true);
794     return true;
795   }
796 
797   CefRefPtr<CefX509Certificate> cert = ssl_info->GetX509Certificate();
798   if (cert.get()) {
799     // Load the error page.
800     LoadErrorPage(browser->GetMainFrame(), request_url, cert_error,
801                   GetCertificateInformation(cert, ssl_info->GetCertStatus()));
802   }
803 
804   return false;  // Cancel the request.
805 }
806 
OnSelectClientCertificate(CefRefPtr<CefBrowser> browser,bool isProxy,const CefString & host,int port,const X509CertificateList & certificates,CefRefPtr<CefSelectClientCertificateCallback> callback)807 bool ClientHandler::OnSelectClientCertificate(
808     CefRefPtr<CefBrowser> browser,
809     bool isProxy,
810     const CefString& host,
811     int port,
812     const X509CertificateList& certificates,
813     CefRefPtr<CefSelectClientCertificateCallback> callback) {
814   CEF_REQUIRE_UI_THREAD();
815 
816   CefRefPtr<CefCommandLine> command_line =
817       CefCommandLine::GetGlobalCommandLine();
818   if (!command_line->HasSwitch(switches::kSslClientCertificate)) {
819     return false;
820   }
821 
822   const std::string& cert_name =
823       command_line->GetSwitchValue(switches::kSslClientCertificate);
824 
825   if (cert_name.empty()) {
826     callback->Select(nullptr);
827     return true;
828   }
829 
830   std::vector<CefRefPtr<CefX509Certificate>>::const_iterator it =
831       certificates.begin();
832   for (; it != certificates.end(); ++it) {
833     CefString subject((*it)->GetSubject()->GetDisplayName());
834     if (subject == cert_name) {
835       callback->Select(*it);
836       return true;
837     }
838   }
839 
840   return true;
841 }
842 
OnRenderProcessTerminated(CefRefPtr<CefBrowser> browser,TerminationStatus status)843 void ClientHandler::OnRenderProcessTerminated(CefRefPtr<CefBrowser> browser,
844                                               TerminationStatus status) {
845   CEF_REQUIRE_UI_THREAD();
846 
847   message_router_->OnRenderProcessTerminated(browser);
848 
849   // Don't reload if there's no start URL, or if the crash URL was specified.
850   if (startup_url_.empty() || startup_url_ == "chrome://crash")
851     return;
852 
853   CefRefPtr<CefFrame> frame = browser->GetMainFrame();
854   std::string url = frame->GetURL();
855 
856   // Don't reload if the termination occurred before any URL had successfully
857   // loaded.
858   if (url.empty())
859     return;
860 
861   std::string start_url = startup_url_;
862 
863   // Convert URLs to lowercase for easier comparison.
864   std::transform(url.begin(), url.end(), url.begin(), tolower);
865   std::transform(start_url.begin(), start_url.end(), start_url.begin(),
866                  tolower);
867 
868   // Don't reload the URL that just resulted in termination.
869   if (url.find(start_url) == 0)
870     return;
871 
872   frame->LoadURL(startup_url_);
873 }
874 
OnDocumentAvailableInMainFrame(CefRefPtr<CefBrowser> browser)875 void ClientHandler::OnDocumentAvailableInMainFrame(
876     CefRefPtr<CefBrowser> browser) {
877   CEF_REQUIRE_UI_THREAD();
878 
879   // Restore offline mode after main frame navigation. Otherwise, offline state
880   // (e.g. `navigator.onLine`) might be wrong in the renderer process.
881   if (offline_)
882     SetOfflineState(browser, true);
883 }
884 
OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,CefRefPtr<CefRequestCallback> callback)885 cef_return_value_t ClientHandler::OnBeforeResourceLoad(
886     CefRefPtr<CefBrowser> browser,
887     CefRefPtr<CefFrame> frame,
888     CefRefPtr<CefRequest> request,
889     CefRefPtr<CefRequestCallback> callback) {
890   CEF_REQUIRE_IO_THREAD();
891 
892   return resource_manager_->OnBeforeResourceLoad(browser, frame, request,
893                                                  callback);
894 }
895 
GetResourceHandler(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request)896 CefRefPtr<CefResourceHandler> ClientHandler::GetResourceHandler(
897     CefRefPtr<CefBrowser> browser,
898     CefRefPtr<CefFrame> frame,
899     CefRefPtr<CefRequest> request) {
900   CEF_REQUIRE_IO_THREAD();
901 
902   return resource_manager_->GetResourceHandler(browser, frame, request);
903 }
904 
GetResourceResponseFilter(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,CefRefPtr<CefResponse> response)905 CefRefPtr<CefResponseFilter> ClientHandler::GetResourceResponseFilter(
906     CefRefPtr<CefBrowser> browser,
907     CefRefPtr<CefFrame> frame,
908     CefRefPtr<CefRequest> request,
909     CefRefPtr<CefResponse> response) {
910   CEF_REQUIRE_IO_THREAD();
911 
912   return test_runner::GetResourceResponseFilter(browser, frame, request,
913                                                 response);
914 }
915 
OnProtocolExecution(CefRefPtr<CefBrowser> browser,CefRefPtr<CefFrame> frame,CefRefPtr<CefRequest> request,bool & allow_os_execution)916 void ClientHandler::OnProtocolExecution(CefRefPtr<CefBrowser> browser,
917                                         CefRefPtr<CefFrame> frame,
918                                         CefRefPtr<CefRequest> request,
919                                         bool& allow_os_execution) {
920   CEF_REQUIRE_IO_THREAD();
921 
922   std::string urlStr = request->GetURL();
923 
924   // Allow OS execution of Spotify URIs.
925   if (urlStr.find("spotify:") == 0)
926     allow_os_execution = true;
927 }
928 
GetBrowserCount() const929 int ClientHandler::GetBrowserCount() const {
930   CEF_REQUIRE_UI_THREAD();
931   return browser_count_;
932 }
933 
ShowDevTools(CefRefPtr<CefBrowser> browser,const CefPoint & inspect_element_at)934 void ClientHandler::ShowDevTools(CefRefPtr<CefBrowser> browser,
935                                  const CefPoint& inspect_element_at) {
936   if (!CefCurrentlyOn(TID_UI)) {
937     // Execute this method on the UI thread.
938     CefPostTask(TID_UI, base::Bind(&ClientHandler::ShowDevTools, this, browser,
939                                    inspect_element_at));
940     return;
941   }
942 
943   CefWindowInfo windowInfo;
944   CefRefPtr<CefClient> client;
945   CefBrowserSettings settings;
946 
947   MainContext::Get()->PopulateBrowserSettings(&settings);
948 
949   CefRefPtr<CefBrowserHost> host = browser->GetHost();
950 
951   // Test if the DevTools browser already exists.
952   bool has_devtools = host->HasDevTools();
953   if (!has_devtools) {
954     // Create a new RootWindow for the DevTools browser that will be created
955     // by ShowDevTools().
956     has_devtools = CreatePopupWindow(browser, true, CefPopupFeatures(),
957                                      windowInfo, client, settings);
958   }
959 
960   if (has_devtools) {
961     // Create the DevTools browser if it doesn't already exist.
962     // Otherwise, focus the existing DevTools browser and inspect the element
963     // at |inspect_element_at| if non-empty.
964     host->ShowDevTools(windowInfo, client, settings, inspect_element_at);
965   }
966 }
967 
CloseDevTools(CefRefPtr<CefBrowser> browser)968 void ClientHandler::CloseDevTools(CefRefPtr<CefBrowser> browser) {
969   browser->GetHost()->CloseDevTools();
970 }
971 
HasSSLInformation(CefRefPtr<CefBrowser> browser)972 bool ClientHandler::HasSSLInformation(CefRefPtr<CefBrowser> browser) {
973   CefRefPtr<CefNavigationEntry> nav =
974       browser->GetHost()->GetVisibleNavigationEntry();
975 
976   return (nav && nav->GetSSLStatus() &&
977           nav->GetSSLStatus()->IsSecureConnection());
978 }
979 
ShowSSLInformation(CefRefPtr<CefBrowser> browser)980 void ClientHandler::ShowSSLInformation(CefRefPtr<CefBrowser> browser) {
981   std::stringstream ss;
982   CefRefPtr<CefNavigationEntry> nav =
983       browser->GetHost()->GetVisibleNavigationEntry();
984   if (!nav)
985     return;
986 
987   CefRefPtr<CefSSLStatus> ssl = nav->GetSSLStatus();
988   if (!ssl)
989     return;
990 
991   ss << "<html><head><title>SSL Information</title></head>"
992         "<body bgcolor=\"white\">"
993         "<h3>SSL Connection</h3>"
994      << "<table border=1><tr><th>Field</th><th>Value</th></tr>";
995 
996   CefURLParts urlparts;
997   if (CefParseURL(nav->GetURL(), urlparts)) {
998     CefString port(&urlparts.port);
999     ss << "<tr><td>Server</td><td>" << CefString(&urlparts.host).ToString();
1000     if (!port.empty())
1001       ss << ":" << port.ToString();
1002     ss << "</td></tr>";
1003   }
1004 
1005   ss << "<tr><td>SSL Version</td><td>"
1006      << GetSSLVersionString(ssl->GetSSLVersion()) << "</td></tr>";
1007   ss << "<tr><td>Content Status</td><td>"
1008      << GetContentStatusString(ssl->GetContentStatus()) << "</td></tr>";
1009 
1010   ss << "</table>";
1011 
1012   CefRefPtr<CefX509Certificate> cert = ssl->GetX509Certificate();
1013   if (cert.get())
1014     ss << GetCertificateInformation(cert, ssl->GetCertStatus());
1015 
1016   ss << "</body></html>";
1017 
1018   RootWindowConfig config;
1019   config.with_controls = false;
1020   config.with_osr = is_osr();
1021   config.url = test_runner::GetDataURI(ss.str(), "text/html");
1022   MainContext::Get()->GetRootWindowManager()->CreateRootWindow(config);
1023 }
1024 
SetStringResource(const std::string & page,const std::string & data)1025 void ClientHandler::SetStringResource(const std::string& page,
1026                                       const std::string& data) {
1027   if (!CefCurrentlyOn(TID_IO)) {
1028     CefPostTask(TID_IO, base::Bind(&ClientHandler::SetStringResource, this,
1029                                    page, data));
1030     return;
1031   }
1032 
1033   string_resource_map_[page] = data;
1034 }
1035 
CreatePopupWindow(CefRefPtr<CefBrowser> browser,bool is_devtools,const CefPopupFeatures & popupFeatures,CefWindowInfo & windowInfo,CefRefPtr<CefClient> & client,CefBrowserSettings & settings)1036 bool ClientHandler::CreatePopupWindow(CefRefPtr<CefBrowser> browser,
1037                                       bool is_devtools,
1038                                       const CefPopupFeatures& popupFeatures,
1039                                       CefWindowInfo& windowInfo,
1040                                       CefRefPtr<CefClient>& client,
1041                                       CefBrowserSettings& settings) {
1042   CEF_REQUIRE_UI_THREAD();
1043 
1044   // The popup browser will be parented to a new native window.
1045   // Don't show URL bar and navigation buttons on DevTools windows.
1046   MainContext::Get()->GetRootWindowManager()->CreateRootWindowAsPopup(
1047       !is_devtools, is_osr(), popupFeatures, windowInfo, client, settings);
1048 
1049   return true;
1050 }
1051 
NotifyBrowserCreated(CefRefPtr<CefBrowser> browser)1052 void ClientHandler::NotifyBrowserCreated(CefRefPtr<CefBrowser> browser) {
1053   if (!CURRENTLY_ON_MAIN_THREAD()) {
1054     // Execute this method on the main thread.
1055     MAIN_POST_CLOSURE(
1056         base::Bind(&ClientHandler::NotifyBrowserCreated, this, browser));
1057     return;
1058   }
1059 
1060   if (delegate_)
1061     delegate_->OnBrowserCreated(browser);
1062 }
1063 
NotifyBrowserClosing(CefRefPtr<CefBrowser> browser)1064 void ClientHandler::NotifyBrowserClosing(CefRefPtr<CefBrowser> browser) {
1065   if (!CURRENTLY_ON_MAIN_THREAD()) {
1066     // Execute this method on the main thread.
1067     MAIN_POST_CLOSURE(
1068         base::Bind(&ClientHandler::NotifyBrowserClosing, this, browser));
1069     return;
1070   }
1071 
1072   if (delegate_)
1073     delegate_->OnBrowserClosing(browser);
1074 }
1075 
NotifyBrowserClosed(CefRefPtr<CefBrowser> browser)1076 void ClientHandler::NotifyBrowserClosed(CefRefPtr<CefBrowser> browser) {
1077   if (!CURRENTLY_ON_MAIN_THREAD()) {
1078     // Execute this method on the main thread.
1079     MAIN_POST_CLOSURE(
1080         base::Bind(&ClientHandler::NotifyBrowserClosed, this, browser));
1081     return;
1082   }
1083 
1084   if (delegate_)
1085     delegate_->OnBrowserClosed(browser);
1086 }
1087 
NotifyAddress(const CefString & url)1088 void ClientHandler::NotifyAddress(const CefString& url) {
1089   if (!CURRENTLY_ON_MAIN_THREAD()) {
1090     // Execute this method on the main thread.
1091     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::NotifyAddress, this, url));
1092     return;
1093   }
1094 
1095   if (delegate_)
1096     delegate_->OnSetAddress(url);
1097 }
1098 
NotifyTitle(const CefString & title)1099 void ClientHandler::NotifyTitle(const CefString& title) {
1100   if (!CURRENTLY_ON_MAIN_THREAD()) {
1101     // Execute this method on the main thread.
1102     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::NotifyTitle, this, title));
1103     return;
1104   }
1105 
1106   if (delegate_)
1107     delegate_->OnSetTitle(title);
1108 }
1109 
NotifyFavicon(CefRefPtr<CefImage> image)1110 void ClientHandler::NotifyFavicon(CefRefPtr<CefImage> image) {
1111   if (!CURRENTLY_ON_MAIN_THREAD()) {
1112     // Execute this method on the main thread.
1113     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::NotifyFavicon, this, image));
1114     return;
1115   }
1116 
1117   if (delegate_)
1118     delegate_->OnSetFavicon(image);
1119 }
1120 
NotifyFullscreen(bool fullscreen)1121 void ClientHandler::NotifyFullscreen(bool fullscreen) {
1122   if (!CURRENTLY_ON_MAIN_THREAD()) {
1123     // Execute this method on the main thread.
1124     MAIN_POST_CLOSURE(
1125         base::Bind(&ClientHandler::NotifyFullscreen, this, fullscreen));
1126     return;
1127   }
1128 
1129   if (delegate_)
1130     delegate_->OnSetFullscreen(fullscreen);
1131 }
1132 
NotifyAutoResize(const CefSize & new_size)1133 void ClientHandler::NotifyAutoResize(const CefSize& new_size) {
1134   if (!CURRENTLY_ON_MAIN_THREAD()) {
1135     // Execute this method on the main thread.
1136     MAIN_POST_CLOSURE(
1137         base::Bind(&ClientHandler::NotifyAutoResize, this, new_size));
1138     return;
1139   }
1140 
1141   if (delegate_)
1142     delegate_->OnAutoResize(new_size);
1143 }
1144 
NotifyLoadingState(bool isLoading,bool canGoBack,bool canGoForward)1145 void ClientHandler::NotifyLoadingState(bool isLoading,
1146                                        bool canGoBack,
1147                                        bool canGoForward) {
1148   if (!CURRENTLY_ON_MAIN_THREAD()) {
1149     // Execute this method on the main thread.
1150     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::NotifyLoadingState, this,
1151                                  isLoading, canGoBack, canGoForward));
1152     return;
1153   }
1154 
1155   if (delegate_)
1156     delegate_->OnSetLoadingState(isLoading, canGoBack, canGoForward);
1157 }
1158 
NotifyDraggableRegions(const std::vector<CefDraggableRegion> & regions)1159 void ClientHandler::NotifyDraggableRegions(
1160     const std::vector<CefDraggableRegion>& regions) {
1161   if (!CURRENTLY_ON_MAIN_THREAD()) {
1162     // Execute this method on the main thread.
1163     MAIN_POST_CLOSURE(
1164         base::Bind(&ClientHandler::NotifyDraggableRegions, this, regions));
1165     return;
1166   }
1167 
1168   if (delegate_)
1169     delegate_->OnSetDraggableRegions(regions);
1170 }
1171 
NotifyTakeFocus(bool next)1172 void ClientHandler::NotifyTakeFocus(bool next) {
1173   if (!CURRENTLY_ON_MAIN_THREAD()) {
1174     // Execute this method on the main thread.
1175     MAIN_POST_CLOSURE(base::Bind(&ClientHandler::NotifyTakeFocus, this, next));
1176     return;
1177   }
1178 
1179   if (delegate_)
1180     delegate_->OnTakeFocus(next);
1181 }
1182 
BuildTestMenu(CefRefPtr<CefMenuModel> model)1183 void ClientHandler::BuildTestMenu(CefRefPtr<CefMenuModel> model) {
1184   if (model->GetCount() > 0)
1185     model->AddSeparator();
1186 
1187   // Build the sub menu.
1188   CefRefPtr<CefMenuModel> submenu =
1189       model->AddSubMenu(CLIENT_ID_TESTMENU_SUBMENU, "Context Menu Test");
1190   submenu->AddCheckItem(CLIENT_ID_TESTMENU_CHECKITEM, "Check Item");
1191   submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM1, "Radio Item 1", 0);
1192   submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM2, "Radio Item 2", 0);
1193   submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM3, "Radio Item 3", 0);
1194 
1195   // Check the check item.
1196   if (test_menu_state_.check_item)
1197     submenu->SetChecked(CLIENT_ID_TESTMENU_CHECKITEM, true);
1198 
1199   // Check the selected radio item.
1200   submenu->SetChecked(
1201       CLIENT_ID_TESTMENU_RADIOITEM1 + test_menu_state_.radio_item, true);
1202 }
1203 
ExecuteTestMenu(int command_id)1204 bool ClientHandler::ExecuteTestMenu(int command_id) {
1205   if (command_id == CLIENT_ID_TESTMENU_CHECKITEM) {
1206     // Toggle the check item.
1207     test_menu_state_.check_item ^= 1;
1208     return true;
1209   } else if (command_id >= CLIENT_ID_TESTMENU_RADIOITEM1 &&
1210              command_id <= CLIENT_ID_TESTMENU_RADIOITEM3) {
1211     // Store the selected radio item.
1212     test_menu_state_.radio_item = (command_id - CLIENT_ID_TESTMENU_RADIOITEM1);
1213     return true;
1214   }
1215 
1216   // Allow default handling to proceed.
1217   return false;
1218 }
1219 
SetOfflineState(CefRefPtr<CefBrowser> browser,bool offline)1220 void ClientHandler::SetOfflineState(CefRefPtr<CefBrowser> browser,
1221                                     bool offline) {
1222   // See DevTools protocol docs for message format specification.
1223   CefRefPtr<CefDictionaryValue> params = CefDictionaryValue::Create();
1224   params->SetBool("offline", offline);
1225   params->SetDouble("latency", 0);
1226   params->SetDouble("downloadThroughput", 0);
1227   params->SetDouble("uploadThroughput", 0);
1228   browser->GetHost()->ExecuteDevToolsMethod(
1229       /*message_id=*/0, "Network.emulateNetworkConditions", params);
1230 }
1231 
1232 }  // namespace client
1233