CefBrowserHost.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. namespace Xilium.CefGlue
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using Xilium.CefGlue.Interop;
  8. /// <summary>
  9. /// Class used to represent the browser process aspects of a browser window. The
  10. /// methods of this class can only be called in the browser process. They may be
  11. /// called on any thread in that process unless otherwise indicated in the
  12. /// comments.
  13. /// </summary>
  14. public sealed unsafe partial class CefBrowserHost
  15. {
  16. /// <summary>
  17. /// Create a new browser window using the window parameters specified by
  18. /// |windowInfo|. All values will be copied internally and the actual window
  19. /// will be created on the UI thread. If |request_context| is empty the
  20. /// global request context will be used. This method can be called on any
  21. /// browser process thread and will not block. The optional |extra_info|
  22. /// parameter provides an opportunity to specify extra information specific
  23. /// to the created browser that will be passed to
  24. /// CefRenderProcessHandler::OnBrowserCreated() in the render process.
  25. /// </summary>
  26. public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url, CefDictionaryValue extraInfo = null, CefRequestContext requestContext = null)
  27. {
  28. if (windowInfo == null) throw new ArgumentNullException("windowInfo");
  29. if (client == null) throw new ArgumentNullException("client");
  30. if (settings == null) throw new ArgumentNullException("settings");
  31. // TODO: [ApiUsage] if windowInfo.WindowRenderingDisabled && client doesn't provide RenderHandler implementation -> throw exception
  32. var n_windowInfo = windowInfo.GetNativePointer();
  33. var n_client = client.ToNative();
  34. var n_settings = settings.ToNative();
  35. var n_extraInfo = extraInfo != null ? extraInfo.ToNative() : null;
  36. var n_requestContext = requestContext != null ? requestContext.ToNative() : null;
  37. fixed (char* url_ptr = url)
  38. {
  39. cef_string_t n_url = new cef_string_t(url_ptr, url != null ? url.Length : 0);
  40. var n_success = cef_browser_host_t.create_browser(n_windowInfo, n_client, &n_url, n_settings, n_extraInfo, n_requestContext);
  41. if (n_success != 1) throw ExceptionBuilder.FailedToCreateBrowser(n_success);
  42. }
  43. }
  44. /// <summary>
  45. /// Create a new browser window using the window parameters specified by
  46. /// |windowInfo|. If |request_context| is empty the global request context
  47. /// will be used. This method can only be called on the browser process UI
  48. /// thread. The optional |extra_info| parameter provides an opportunity to
  49. /// specify extra information specific to the created browser that will be
  50. /// passed to CefRenderProcessHandler::OnBrowserCreated() in the render
  51. /// process.
  52. /// </summary>
  53. public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url, CefDictionaryValue extraInfo = null, CefRequestContext requestContext = null)
  54. {
  55. if (windowInfo == null) throw new ArgumentNullException("windowInfo");
  56. if (client == null) throw new ArgumentNullException("client");
  57. if (settings == null) throw new ArgumentNullException("settings");
  58. // TODO: [ApiUsage] if windowInfo.WindowRenderingDisabled && client doesn't provide RenderHandler implementation -> throw exception
  59. var n_windowInfo = windowInfo.GetNativePointer();
  60. var n_client = client.ToNative();
  61. var n_settings = settings.ToNative();
  62. var n_extraInfo = extraInfo != null ? extraInfo.ToNative() : null;
  63. var n_requestContext = requestContext != null ? requestContext.ToNative() : null;
  64. fixed (char* url_ptr = url)
  65. {
  66. cef_string_t n_url = new cef_string_t(url_ptr, url != null ? url.Length : 0);
  67. var n_browser = cef_browser_host_t.create_browser_sync(n_windowInfo, n_client, &n_url, n_settings, n_extraInfo, n_requestContext);
  68. return CefBrowser.FromNative(n_browser);
  69. }
  70. }
  71. /// <summary>
  72. /// Returns the hosted browser object.
  73. /// </summary>
  74. public CefBrowser GetBrowser()
  75. {
  76. return CefBrowser.FromNative(cef_browser_host_t.get_browser(_self));
  77. }
  78. /// <summary>
  79. /// Request that the browser close. The JavaScript 'onbeforeunload' event will
  80. /// be fired. If |force_close| is false the event handler, if any, will be
  81. /// allowed to prompt the user and the user can optionally cancel the close.
  82. /// If |force_close| is true the prompt will not be displayed and the close
  83. /// will proceed. Results in a call to CefLifeSpanHandler::DoClose() if the
  84. /// event handler allows the close or if |force_close| is true. See
  85. /// CefLifeSpanHandler::DoClose() documentation for additional usage
  86. /// information.
  87. /// </summary>
  88. public void CloseBrowser(bool forceClose = false)
  89. {
  90. cef_browser_host_t.close_browser(_self, forceClose ? 1 : 0);
  91. }
  92. /// <summary>
  93. /// Helper for closing a browser. Call this method from the top-level window
  94. /// close handler. Internally this calls CloseBrowser(false) if the close has
  95. /// not yet been initiated. This method returns false while the close is
  96. /// pending and true after the close has completed. See CloseBrowser() and
  97. /// CefLifeSpanHandler::DoClose() documentation for additional usage
  98. /// information. This method must be called on the browser process UI thread.
  99. /// </summary>
  100. public bool TryCloseBrowser()
  101. {
  102. return cef_browser_host_t.try_close_browser(_self) != 0;
  103. }
  104. /// <summary>
  105. /// Set whether the browser is focused.
  106. /// </summary>
  107. public void SetFocus(bool focus)
  108. {
  109. cef_browser_host_t.set_focus(_self, focus ? 1 : 0);
  110. }
  111. /// <summary>
  112. /// Retrieve the window handle for this browser. If this browser is wrapped in
  113. /// a CefBrowserView this method should be called on the browser process UI
  114. /// thread and it will return the handle for the top-level native window.
  115. /// </summary>
  116. public IntPtr GetWindowHandle()
  117. {
  118. return cef_browser_host_t.get_window_handle(_self);
  119. }
  120. /// <summary>
  121. /// Retrieve the window handle of the browser that opened this browser. Will
  122. /// return NULL for non-popup windows or if this browser is wrapped in a
  123. /// CefBrowserView. This method can be used in combination with custom handling
  124. /// of modal windows.
  125. /// </summary>
  126. public IntPtr GetOpenerWindowHandle()
  127. {
  128. return cef_browser_host_t.get_opener_window_handle(_self);
  129. }
  130. /// <summary>
  131. /// Returns true if this browser is wrapped in a CefBrowserView.
  132. /// </summary>
  133. public bool HasView
  134. {
  135. get { return cef_browser_host_t.has_view(_self) != 0; }
  136. }
  137. /// <summary>
  138. /// Returns the client for this browser.
  139. /// </summary>
  140. public CefClient GetClient()
  141. {
  142. return CefClient.FromNative(
  143. cef_browser_host_t.get_client(_self)
  144. );
  145. }
  146. /// <summary>
  147. /// Returns the request context for this browser.
  148. /// </summary>
  149. public CefRequestContext GetRequestContext()
  150. {
  151. return CefRequestContext.FromNative(
  152. cef_browser_host_t.get_request_context(_self)
  153. );
  154. }
  155. /// <summary>
  156. /// Get the current zoom level. The default zoom level is 0.0. This method can
  157. /// only be called on the UI thread.
  158. /// </summary>
  159. public double GetZoomLevel()
  160. {
  161. return cef_browser_host_t.get_zoom_level(_self);
  162. }
  163. /// <summary>
  164. /// Change the zoom level to the specified value. Specify 0.0 to reset the
  165. /// zoom level. If called on the UI thread the change will be applied
  166. /// immediately. Otherwise, the change will be applied asynchronously on the
  167. /// UI thread.
  168. /// </summary>
  169. public void SetZoomLevel(double value)
  170. {
  171. cef_browser_host_t.set_zoom_level(_self, value);
  172. }
  173. /// <summary>
  174. /// Call to run a file chooser dialog. Only a single file chooser dialog may be
  175. /// pending at any given time. |mode| represents the type of dialog to display.
  176. /// |title| to the title to be used for the dialog and may be empty to show the
  177. /// default title ("Open" or "Save" depending on the mode). |default_file_path|
  178. /// is the path with optional directory and/or file name component that will be
  179. /// initially selected in the dialog. |accept_filters| are used to restrict the
  180. /// selectable file types and may any combination of (a) valid lower-cased MIME
  181. /// types (e.g. "text/*" or "image/*"), (b) individual file extensions (e.g.
  182. /// ".txt" or ".png"), or (c) combined description and file extension delimited
  183. /// using "|" and ";" (e.g. "Image Types|.png;.gif;.jpg").
  184. /// |selected_accept_filter| is the 0-based index of the filter that will be
  185. /// selected by default. |callback| will be executed after the dialog is
  186. /// dismissed or immediately if another dialog is already pending. The dialog
  187. /// will be initiated asynchronously on the UI thread.
  188. /// </summary>
  189. public void RunFileDialog(CefFileDialogMode mode, string title, string defaultFilePath, string[] acceptFilters, int selectedAcceptFilter, CefRunFileDialogCallback callback)
  190. {
  191. if (callback == null) throw new ArgumentNullException("callback");
  192. fixed (char* title_ptr = title)
  193. fixed (char* defaultFilePath_ptr = defaultFilePath)
  194. {
  195. var n_title = new cef_string_t(title_ptr, title != null ? title.Length : 0);
  196. var n_defaultFilePath = new cef_string_t(defaultFilePath_ptr, defaultFilePath != null ? defaultFilePath.Length : 0);
  197. var n_acceptFilters = cef_string_list.From(acceptFilters);
  198. cef_browser_host_t.run_file_dialog(_self, mode, &n_title, &n_defaultFilePath, n_acceptFilters, selectedAcceptFilter, callback.ToNative());
  199. libcef.string_list_free(n_acceptFilters);
  200. }
  201. }
  202. /// <summary>
  203. /// Download the file at |url| using CefDownloadHandler.
  204. /// </summary>
  205. public void StartDownload(string url)
  206. {
  207. if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
  208. fixed (char* url_ptr = url)
  209. {
  210. var n_url = new cef_string_t(url_ptr, url.Length);
  211. cef_browser_host_t.start_download(_self, &n_url);
  212. }
  213. }
  214. /// <summary>
  215. /// Download |image_url| and execute |callback| on completion with the images
  216. /// received from the renderer. If |is_favicon| is true then cookies are not
  217. /// sent and not accepted during download. Images with density independent
  218. /// pixel (DIP) sizes larger than |max_image_size| are filtered out from the
  219. /// image results. Versions of the image at different scale factors may be
  220. /// downloaded up to the maximum scale factor supported by the system. If there
  221. /// are no image results &lt;= |max_image_size| then the smallest image is resized
  222. /// to |max_image_size| and is the only result. A |max_image_size| of 0 means
  223. /// unlimited. If |bypass_cache| is true then |image_url| is requested from the
  224. /// server even if it is present in the browser cache.
  225. /// </summary>
  226. public void DownloadImage(string imageUrl, bool isFavIcon, uint maxImageSize, bool bypassCache, CefDownloadImageCallback callback)
  227. {
  228. if (string.IsNullOrEmpty(imageUrl)) throw new ArgumentNullException("imageUrl");
  229. fixed (char* imageUrl_ptr = imageUrl)
  230. {
  231. var n_imageUrl = new cef_string_t(imageUrl_ptr, imageUrl.Length);
  232. var n_callback = callback.ToNative();
  233. cef_browser_host_t.download_image(_self, &n_imageUrl, isFavIcon ? 1 : 0, maxImageSize, bypassCache ? 1 : 0, n_callback);
  234. }
  235. }
  236. /// <summary>
  237. /// Print the current browser contents.
  238. /// </summary>
  239. public void Print()
  240. {
  241. cef_browser_host_t.print(_self);
  242. }
  243. /// <summary>
  244. /// Print the current browser contents to the PDF file specified by |path| and
  245. /// execute |callback| on completion. The caller is responsible for deleting
  246. /// |path| when done. For PDF printing to work on Linux you must implement the
  247. /// CefPrintHandler::GetPdfPaperSize method.
  248. /// </summary>
  249. public void PrintToPdf(string path, CefPdfPrintSettings settings, CefPdfPrintCallback callback)
  250. {
  251. fixed (char* path_ptr = path)
  252. {
  253. var n_path = new cef_string_t(path_ptr, path.Length);
  254. var n_settings = settings.ToNative();
  255. cef_browser_host_t.print_to_pdf(_self,
  256. &n_path,
  257. n_settings,
  258. callback.ToNative()
  259. );
  260. cef_pdf_print_settings_t.Clear(n_settings);
  261. cef_pdf_print_settings_t.Free(n_settings);
  262. }
  263. }
  264. /// <summary>
  265. /// Search for |searchText|. |identifier| must be a unique ID and these IDs
  266. /// must strictly increase so that newer requests always have greater IDs than
  267. /// older requests. If |identifier| is zero or less than the previous ID value
  268. /// then it will be automatically assigned a new valid ID. |forward| indicates
  269. /// whether to search forward or backward within the page. |matchCase|
  270. /// indicates whether the search should be case-sensitive. |findNext| indicates
  271. /// whether this is the first request or a follow-up. The CefFindHandler
  272. /// instance, if any, returned via CefClient::GetFindHandler will be called to
  273. /// report find results.
  274. /// </summary>
  275. public void Find(int identifier, string searchText, bool forward, bool matchCase, bool findNext)
  276. {
  277. fixed (char* searchText_ptr = searchText)
  278. {
  279. var n_searchText = new cef_string_t(searchText_ptr, searchText.Length);
  280. cef_browser_host_t.find(_self, identifier, &n_searchText, forward ? 1 : 0, matchCase ? 1 : 0, findNext ? 1 : 0);
  281. }
  282. }
  283. /// <summary>
  284. /// Cancel all searches that are currently going on.
  285. /// </summary>
  286. public void StopFinding(bool clearSelection)
  287. {
  288. cef_browser_host_t.stop_finding(_self, clearSelection ? 1 : 0);
  289. }
  290. /// <summary>
  291. /// Open developer tools (DevTools) in its own browser. The DevTools browser
  292. /// will remain associated with this browser. If the DevTools browser is
  293. /// already open then it will be focused, in which case the |windowInfo|,
  294. /// |client| and |settings| parameters will be ignored. If |inspect_element_at|
  295. /// is non-empty then the element at the specified (x,y) location will be
  296. /// inspected. The |windowInfo| parameter will be ignored if this browser is
  297. /// wrapped in a CefBrowserView.
  298. /// </summary>
  299. public void ShowDevTools(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings browserSettings, CefPoint inspectElementAt)
  300. {
  301. var n_inspectElementAt = new cef_point_t(inspectElementAt.X, inspectElementAt.Y);
  302. cef_browser_host_t.show_dev_tools(_self, windowInfo.ToNative(), client.ToNative(), browserSettings.ToNative(),
  303. &n_inspectElementAt);
  304. }
  305. /// <summary>
  306. /// Explicitly close the associated DevTools browser, if any.
  307. /// </summary>
  308. public void CloseDevTools()
  309. {
  310. cef_browser_host_t.close_dev_tools(_self);
  311. }
  312. /// <summary>
  313. /// Returns true if this browser currently has an associated DevTools browser.
  314. /// Must be called on the browser process UI thread.
  315. /// </summary>
  316. public bool HasDevTools
  317. {
  318. get
  319. {
  320. return cef_browser_host_t.has_dev_tools(_self) != 0;
  321. }
  322. }
  323. /// <summary>
  324. /// Send a method call message over the DevTools protocol. |message| must be a
  325. /// UTF8-encoded JSON dictionary that contains "id" (int), "method" (string)
  326. /// and "params" (dictionary, optional) values. See the DevTools protocol
  327. /// documentation at https://chromedevtools.github.io/devtools-protocol/ for
  328. /// details of supported methods and the expected "params" dictionary contents.
  329. /// |message| will be copied if necessary. This method will return true if
  330. /// called on the UI thread and the message was successfully submitted for
  331. /// validation, otherwise false. Validation will be applied asynchronously and
  332. /// any messages that fail due to formatting errors or missing parameters may
  333. /// be discarded without notification. Prefer ExecuteDevToolsMethod if a more
  334. /// structured approach to message formatting is desired.
  335. /// Every valid method call will result in an asynchronous method result or
  336. /// error message that references the sent message "id". Event messages are
  337. /// received while notifications are enabled (for example, between method calls
  338. /// for "Page.enable" and "Page.disable"). All received messages will be
  339. /// delivered to the observer(s) registered with AddDevToolsMessageObserver.
  340. /// See CefDevToolsMessageObserver::OnDevToolsMessage documentation for details
  341. /// of received message contents.
  342. /// Usage of the SendDevToolsMessage, ExecuteDevToolsMethod and
  343. /// AddDevToolsMessageObserver methods does not require an active DevTools
  344. /// front-end or remote-debugging session. Other active DevTools sessions will
  345. /// continue to function independently. However, any modification of global
  346. /// browser state by one session may not be reflected in the UI of other
  347. /// sessions.
  348. /// Communication with the DevTools front-end (when displayed) can be logged
  349. /// for development purposes by passing the
  350. /// `--devtools-protocol-log-file=&lt;path&gt;` command-line flag.
  351. /// </summary>
  352. public bool SendDevToolsMessage(IntPtr message, int messageSize)
  353. {
  354. return cef_browser_host_t.send_dev_tools_message(
  355. _self, (void*)message, checked((UIntPtr)messageSize)) != 0;
  356. }
  357. /// <summary>
  358. /// Execute a method call over the DevTools protocol. This is a more structured
  359. /// version of SendDevToolsMessage. |message_id| is an incremental number that
  360. /// uniquely identifies the message (pass 0 to have the next number assigned
  361. /// automatically based on previous values). |method| is the method name.
  362. /// |params| are the method parameters, which may be empty. See the DevTools
  363. /// protocol documentation (linked above) for details of supported methods and
  364. /// the expected |params| dictionary contents. This method will return the
  365. /// assigned message ID if called on the UI thread and the message was
  366. /// successfully submitted for validation, otherwise 0. See the
  367. /// SendDevToolsMessage documentation for additional usage information.
  368. /// </summary>
  369. public int ExecuteDevToolsMethod(int messageId, string method, CefDictionaryValue parameters)
  370. {
  371. fixed (char* method_str = method)
  372. {
  373. var n_method = new cef_string_t(method_str, method != null ? method.Length : 0);
  374. return cef_browser_host_t.execute_dev_tools_method(
  375. _self, messageId, &n_method, parameters.ToNative());
  376. }
  377. }
  378. /// <summary>
  379. /// Add an observer for DevTools protocol messages (method results and events).
  380. /// The observer will remain registered until the returned Registration object
  381. /// is destroyed. See the SendDevToolsMessage documentation for additional
  382. /// usage information.
  383. /// </summary>
  384. public CefRegistration AddDevToolsMessageObserver(CefDevToolsMessageObserver observer)
  385. {
  386. if (observer == null) throw new ArgumentNullException(nameof(observer));
  387. var n_registration = cef_browser_host_t.add_dev_tools_message_observer(_self,
  388. observer.ToNative());
  389. return CefRegistration.FromNativeOrNull(n_registration);
  390. }
  391. /// <summary>
  392. /// Retrieve a snapshot of current navigation entries as values sent to the
  393. /// specified visitor. If |current_only| is true only the current navigation
  394. /// entry will be sent, otherwise all navigation entries will be sent.
  395. /// </summary>
  396. public void GetNavigationEntries(CefNavigationEntryVisitor visitor, bool currentOnly)
  397. {
  398. cef_browser_host_t.get_navigation_entries(_self, visitor.ToNative(), currentOnly ? 1 : 0);
  399. }
  400. /// <summary>
  401. /// If a misspelled word is currently selected in an editable node calling
  402. /// this method will replace it with the specified |word|.
  403. /// </summary>
  404. public void ReplaceMisspelling(string word)
  405. {
  406. fixed (char* word_str = word)
  407. {
  408. var n_word = new cef_string_t(word_str, word != null ? word.Length : 0);
  409. cef_browser_host_t.replace_misspelling(_self, &n_word);
  410. }
  411. }
  412. /// <summary>
  413. /// Add the specified |word| to the spelling dictionary.
  414. /// </summary>
  415. public void AddWordToDictionary(string word)
  416. {
  417. fixed (char* word_str = word)
  418. {
  419. var n_word = new cef_string_t(word_str, word != null ? word.Length : 0);
  420. cef_browser_host_t.add_word_to_dictionary(_self, &n_word);
  421. }
  422. }
  423. /// <summary>
  424. /// Returns true if window rendering is disabled.
  425. /// </summary>
  426. public bool IsWindowRenderingDisabled
  427. {
  428. get
  429. {
  430. return cef_browser_host_t.is_window_rendering_disabled(_self) != 0;
  431. }
  432. }
  433. /// <summary>
  434. /// Notify the browser that the widget has been resized. The browser will first
  435. /// call CefRenderHandler::GetViewRect to get the new size and then call
  436. /// CefRenderHandler::OnPaint asynchronously with the updated regions. This
  437. /// method is only used when window rendering is disabled.
  438. /// </summary>
  439. public void WasResized()
  440. {
  441. cef_browser_host_t.was_resized(_self);
  442. }
  443. /// <summary>
  444. /// Notify the browser that it has been hidden or shown. Layouting and
  445. /// CefRenderHandler::OnPaint notification will stop when the browser is
  446. /// hidden. This method is only used when window rendering is disabled.
  447. /// </summary>
  448. public void WasHidden(bool hidden)
  449. {
  450. cef_browser_host_t.was_hidden(_self, hidden ? 1 : 0);
  451. }
  452. /// <summary>
  453. /// Send a notification to the browser that the screen info has changed. The
  454. /// browser will then call CefRenderHandler::GetScreenInfo to update the
  455. /// screen information with the new values. This simulates moving the webview
  456. /// window from one display to another, or changing the properties of the
  457. /// current display. This method is only used when window rendering is
  458. /// disabled.
  459. /// </summary>
  460. public void NotifyScreenInfoChanged()
  461. {
  462. cef_browser_host_t.notify_screen_info_changed(_self);
  463. }
  464. /// <summary>
  465. /// Invalidate the view. The browser will call CefRenderHandler::OnPaint
  466. /// asynchronously. This method is only used when window rendering is
  467. /// disabled.
  468. /// </summary>
  469. public void Invalidate(CefPaintElementType type)
  470. {
  471. cef_browser_host_t.invalidate(_self, type);
  472. }
  473. /// <summary>
  474. /// Issue a BeginFrame request to Chromium. Only valid when
  475. /// CefWindowInfo::external_begin_frame_enabled is set to true.
  476. /// </summary>
  477. public void SendExternalBeginFrame()
  478. {
  479. cef_browser_host_t.send_external_begin_frame(_self);
  480. }
  481. /// <summary>
  482. /// Send a key event to the browser.
  483. /// </summary>
  484. public void SendKeyEvent(CefKeyEvent keyEvent)
  485. {
  486. if (keyEvent == null) throw new ArgumentNullException("keyEvent");
  487. var n_event = new cef_key_event_t();
  488. keyEvent.ToNative(&n_event);
  489. cef_browser_host_t.send_key_event(_self, &n_event);
  490. }
  491. /// <summary>
  492. /// Send a mouse click event to the browser. The |x| and |y| coordinates are
  493. /// relative to the upper-left corner of the view.
  494. /// </summary>
  495. public void SendMouseClickEvent(CefMouseEvent @event, CefMouseButtonType type, bool mouseUp, int clickCount)
  496. {
  497. var n_event = @event.ToNative();
  498. cef_browser_host_t.send_mouse_click_event(_self, &n_event, type, mouseUp ? 1 : 0, clickCount);
  499. }
  500. /// <summary>
  501. /// Send a mouse move event to the browser. The |x| and |y| coordinates are
  502. /// relative to the upper-left corner of the view.
  503. /// </summary>
  504. public void SendMouseMoveEvent(CefMouseEvent @event, bool mouseLeave)
  505. {
  506. var n_event = @event.ToNative();
  507. cef_browser_host_t.send_mouse_move_event(_self, &n_event, mouseLeave ? 1 : 0);
  508. }
  509. /// <summary>
  510. /// Send a mouse wheel event to the browser. The |x| and |y| coordinates are
  511. /// relative to the upper-left corner of the view. The |deltaX| and |deltaY|
  512. /// values represent the movement delta in the X and Y directions respectively.
  513. /// In order to scroll inside select popups with window rendering disabled
  514. /// CefRenderHandler::GetScreenPoint should be implemented properly.
  515. /// </summary>
  516. public void SendMouseWheelEvent(CefMouseEvent @event, int deltaX, int deltaY)
  517. {
  518. var n_event = @event.ToNative();
  519. cef_browser_host_t.send_mouse_wheel_event(_self, &n_event, deltaX, deltaY);
  520. }
  521. /// <summary>
  522. /// Send a touch event to the browser for a windowless browser.
  523. /// </summary>
  524. public void SendTouchEvent(CefTouchEvent @event)
  525. {
  526. cef_touch_event_t n_event;
  527. @event.ToNative(out n_event);
  528. cef_browser_host_t.send_touch_event(_self, &n_event);
  529. }
  530. /// <summary>
  531. /// Send a focus event to the browser.
  532. /// </summary>
  533. public void SendFocusEvent(bool setFocus)
  534. {
  535. cef_browser_host_t.send_focus_event(_self, setFocus ? 1 : 0);
  536. }
  537. /// <summary>
  538. /// Send a capture lost event to the browser.
  539. /// </summary>
  540. public void SendCaptureLostEvent()
  541. {
  542. cef_browser_host_t.send_capture_lost_event(_self);
  543. }
  544. /// <summary>
  545. /// Notify the browser that the window hosting it is about to be moved or
  546. /// resized. This method is only used on Windows and Linux.
  547. /// </summary>
  548. public void NotifyMoveOrResizeStarted()
  549. {
  550. cef_browser_host_t.notify_move_or_resize_started(_self);
  551. }
  552. /// <summary>
  553. /// Returns the maximum rate in frames per second (fps) that CefRenderHandler::
  554. /// OnPaint will be called for a windowless browser. The actual fps may be
  555. /// lower if the browser cannot generate frames at the requested rate. The
  556. /// minimum value is 1 and the maximum value is 60 (default 30). This method
  557. /// can only be called on the UI thread.
  558. /// </summary>
  559. public int GetWindowlessFrameRate()
  560. {
  561. return cef_browser_host_t.get_windowless_frame_rate(_self);
  562. }
  563. /// <summary>
  564. /// Set the maximum rate in frames per second (fps) that CefRenderHandler::
  565. /// OnPaint will be called for a windowless browser. The actual fps may be
  566. /// lower if the browser cannot generate frames at the requested rate. The
  567. /// minimum value is 1 and the maximum value is 60 (default 30). Can also be
  568. /// set at browser creation via CefBrowserSettings.windowless_frame_rate.
  569. /// </summary>
  570. public void SetWindowlessFrameRate(int frameRate)
  571. {
  572. cef_browser_host_t.set_windowless_frame_rate(_self, frameRate);
  573. }
  574. /// <summary>
  575. /// Begins a new composition or updates the existing composition. Blink has a
  576. /// special node (a composition node) that allows the input method to change
  577. /// text without affecting other DOM nodes. |text| is the optional text that
  578. /// will be inserted into the composition node. |underlines| is an optional set
  579. /// of ranges that will be underlined in the resulting text.
  580. /// |replacement_range| is an optional range of the existing text that will be
  581. /// replaced. |selection_range| is an optional range of the resulting text that
  582. /// will be selected after insertion or replacement. The |replacement_range|
  583. /// value is only used on OS X.
  584. /// This method may be called multiple times as the composition changes. When
  585. /// the client is done making changes the composition should either be canceled
  586. /// or completed. To cancel the composition call ImeCancelComposition. To
  587. /// complete the composition call either ImeCommitText or
  588. /// ImeFinishComposingText. Completion is usually signaled when:
  589. /// A. The client receives a WM_IME_COMPOSITION message with a GCS_RESULTSTR
  590. /// flag (on Windows), or;
  591. /// B. The client receives a "commit" signal of GtkIMContext (on Linux), or;
  592. /// C. insertText of NSTextInput is called (on Mac).
  593. /// This method is only used when window rendering is disabled.
  594. /// </summary>
  595. public void ImeSetComposition(string text,
  596. int underlinesCount,
  597. CefCompositionUnderline underlines,
  598. CefRange replacementRange,
  599. CefRange selectionRange)
  600. {
  601. fixed (char* text_ptr = text)
  602. {
  603. cef_string_t n_text = new cef_string_t(text_ptr, text != null ? text.Length : 0);
  604. UIntPtr n_underlinesCount = checked((UIntPtr)underlinesCount);
  605. var n_underlines = underlines.ToNative();
  606. cef_range_t n_replacementRange = new cef_range_t(replacementRange.From, replacementRange.To);
  607. cef_range_t n_selectionRange = new cef_range_t(selectionRange.From, selectionRange.To);
  608. cef_browser_host_t.ime_set_composition(_self, &n_text, n_underlinesCount, &n_underlines, &n_replacementRange, &n_selectionRange);
  609. }
  610. }
  611. /// <summary>
  612. /// Completes the existing composition by optionally inserting the specified
  613. /// |text| into the composition node. |replacement_range| is an optional range
  614. /// of the existing text that will be replaced. |relative_cursor_pos| is where
  615. /// the cursor will be positioned relative to the current cursor position. See
  616. /// comments on ImeSetComposition for usage. The |replacement_range| and
  617. /// |relative_cursor_pos| values are only used on OS X.
  618. /// This method is only used when window rendering is disabled.
  619. /// </summary>
  620. public void ImeCommitText(string text, CefRange replacementRange, int relativeCursorPos)
  621. {
  622. fixed (char* text_ptr = text)
  623. {
  624. cef_string_t n_text = new cef_string_t(text_ptr, text != null ? text.Length : 0);
  625. var n_replacementRange = new cef_range_t(replacementRange.From, replacementRange.To);
  626. cef_browser_host_t.ime_commit_text(_self, &n_text, &n_replacementRange, relativeCursorPos);
  627. }
  628. }
  629. /// <summary>
  630. /// Completes the existing composition by applying the current composition node
  631. /// contents. If |keep_selection| is false the current selection, if any, will
  632. /// be discarded. See comments on ImeSetComposition for usage.
  633. /// This method is only used when window rendering is disabled.
  634. /// </summary>
  635. public void ImeFinishComposingText(bool keepSelection)
  636. {
  637. cef_browser_host_t.ime_finish_composing_text(_self, keepSelection ? 1 : 0);
  638. }
  639. /// <summary>
  640. /// Cancels the existing composition and discards the composition node
  641. /// contents without applying them. See comments on ImeSetComposition for
  642. /// usage.
  643. /// This method is only used when window rendering is disabled.
  644. /// </summary>
  645. public void ImeCancelComposition()
  646. {
  647. cef_browser_host_t.ime_cancel_composition(_self);
  648. }
  649. /// <summary>
  650. /// Call this method when the user drags the mouse into the web view (before
  651. /// calling DragTargetDragOver/DragTargetLeave/DragTargetDrop).
  652. /// |drag_data| should not contain file contents as this type of data is not
  653. /// allowed to be dragged into the web view. File contents can be removed using
  654. /// CefDragData::ResetFileContents (for example, if |drag_data| comes from
  655. /// CefRenderHandler::StartDragging).
  656. /// This method is only used when window rendering is disabled.
  657. /// </summary>
  658. public void DragTargetDragEnter(CefDragData dragData, CefMouseEvent mouseEvent, CefDragOperationsMask allowedOps)
  659. {
  660. var n_mouseEvent = mouseEvent.ToNative();
  661. cef_browser_host_t.drag_target_drag_enter(_self,
  662. dragData.ToNative(),
  663. &n_mouseEvent,
  664. allowedOps);
  665. }
  666. /// <summary>
  667. /// Call this method each time the mouse is moved across the web view during
  668. /// a drag operation (after calling DragTargetDragEnter and before calling
  669. /// DragTargetDragLeave/DragTargetDrop).
  670. /// This method is only used when window rendering is disabled.
  671. /// </summary>
  672. public void DragTargetDragOver(CefMouseEvent mouseEvent, CefDragOperationsMask allowedOps)
  673. {
  674. var n_mouseEvent = mouseEvent.ToNative();
  675. cef_browser_host_t.drag_target_drag_over(_self, &n_mouseEvent, allowedOps);
  676. }
  677. /// <summary>
  678. /// Call this method when the user drags the mouse out of the web view (after
  679. /// calling DragTargetDragEnter).
  680. /// This method is only used when window rendering is disabled.
  681. /// </summary>
  682. public void DragTargetDragLeave()
  683. {
  684. cef_browser_host_t.drag_target_drag_leave(_self);
  685. }
  686. /// <summary>
  687. /// Call this method when the user completes the drag operation by dropping
  688. /// the object onto the web view (after calling DragTargetDragEnter).
  689. /// The object being dropped is |drag_data|, given as an argument to
  690. /// the previous DragTargetDragEnter call.
  691. /// This method is only used when window rendering is disabled.
  692. /// </summary>
  693. public void DragTargetDrop(CefMouseEvent mouseEvent)
  694. {
  695. var n_mouseEvent = mouseEvent.ToNative();
  696. cef_browser_host_t.drag_target_drop(_self, &n_mouseEvent);
  697. }
  698. /// <summary>
  699. /// Call this method when the drag operation started by a
  700. /// CefRenderHandler::StartDragging call has ended either in a drop or
  701. /// by being cancelled. |x| and |y| are mouse coordinates relative to the
  702. /// upper-left corner of the view. If the web view is both the drag source
  703. /// and the drag target then all DragTarget* methods should be called before
  704. /// DragSource* mthods.
  705. /// This method is only used when window rendering is disabled.
  706. /// </summary>
  707. public void DragSourceEndedAt(int x, int y, CefDragOperationsMask op)
  708. {
  709. cef_browser_host_t.drag_source_ended_at(_self, x, y, op);
  710. }
  711. /// <summary>
  712. /// Call this method when the drag operation started by a
  713. /// CefRenderHandler::StartDragging call has completed. This method may be
  714. /// called immediately without first calling DragSourceEndedAt to cancel a
  715. /// drag operation. If the web view is both the drag source and the drag
  716. /// target then all DragTarget* methods should be called before DragSource*
  717. /// mthods.
  718. /// This method is only used when window rendering is disabled.
  719. /// </summary>
  720. public void DragSourceSystemDragEnded()
  721. {
  722. cef_browser_host_t.drag_source_system_drag_ended(_self);
  723. }
  724. /// <summary>
  725. /// Returns the current visible navigation entry for this browser. This method
  726. /// can only be called on the UI thread.
  727. /// </summary>
  728. public CefNavigationEntry GetVisibleNavigationEntry()
  729. {
  730. return CefNavigationEntry.FromNativeOrNull(
  731. cef_browser_host_t.get_visible_navigation_entry(_self)
  732. );
  733. }
  734. /// <summary>
  735. /// Set accessibility state for all frames. |accessibility_state| may be
  736. /// default, enabled or disabled. If |accessibility_state| is STATE_DEFAULT
  737. /// then accessibility will be disabled by default and the state may be further
  738. /// controlled with the "force-renderer-accessibility" and
  739. /// "disable-renderer-accessibility" command-line switches. If
  740. /// |accessibility_state| is STATE_ENABLED then accessibility will be enabled.
  741. /// If |accessibility_state| is STATE_DISABLED then accessibility will be
  742. /// completely disabled.
  743. /// For windowed browsers accessibility will be enabled in Complete mode (which
  744. /// corresponds to kAccessibilityModeComplete in Chromium). In this mode all
  745. /// platform accessibility objects will be created and managed by Chromium's
  746. /// internal implementation. The client needs only to detect the screen reader
  747. /// and call this method appropriately. For example, on macOS the client can
  748. /// handle the @"AXEnhancedUserInterface" accessibility attribute to detect
  749. /// VoiceOver state changes and on Windows the client can handle WM_GETOBJECT
  750. /// with OBJID_CLIENT to detect accessibility readers.
  751. /// For windowless browsers accessibility will be enabled in TreeOnly mode
  752. /// (which corresponds to kAccessibilityModeWebContentsOnly in Chromium). In
  753. /// this mode renderer accessibility is enabled, the full tree is computed, and
  754. /// events are passed to CefAccessibiltyHandler, but platform accessibility
  755. /// objects are not created. The client may implement platform accessibility
  756. /// objects using CefAccessibiltyHandler callbacks if desired.
  757. /// </summary>
  758. public void SetAccessibilityState(CefState accessibilityState)
  759. {
  760. cef_browser_host_t.set_accessibility_state(_self, accessibilityState);
  761. }
  762. /// <summary>
  763. /// Enable notifications of auto resize via CefDisplayHandler::OnAutoResize.
  764. /// Notifications are disabled by default. |min_size| and |max_size| define the
  765. /// range of allowed sizes.
  766. /// </summary>
  767. public void SetAutoResizeEnabled(bool enabled, CefSize minSize, CefSize maxSize)
  768. {
  769. var nMinSize = new cef_size_t(minSize.Width, minSize.Height);
  770. var nMaxSize = new cef_size_t(maxSize.Width, maxSize.Height);
  771. cef_browser_host_t.set_auto_resize_enabled(_self, enabled ? 1 : 0, &nMinSize, &nMaxSize);
  772. }
  773. /// <summary>
  774. /// Returns the extension hosted in this browser or NULL if no extension is
  775. /// hosted. See CefRequestContext::LoadExtension for details.
  776. /// </summary>
  777. public CefExtension GetExtension()
  778. {
  779. var nExtension = cef_browser_host_t.get_extension(_self);
  780. return CefExtension.FromNativeOrNull(nExtension);
  781. }
  782. /// <summary>
  783. /// Returns true if this browser is hosting an extension background script.
  784. /// Background hosts do not have a window and are not displayable. See
  785. /// CefRequestContext::LoadExtension for details.
  786. /// </summary>
  787. public bool IsBackgroundHost
  788. {
  789. get
  790. {
  791. return cef_browser_host_t.is_background_host(_self) != 0;
  792. }
  793. }
  794. /// <summary>
  795. /// Set whether the browser's audio is muted.
  796. /// </summary>
  797. public void SetAudioMuted(bool value)
  798. {
  799. cef_browser_host_t.set_audio_muted(_self, value ? 1 : 0);
  800. }
  801. /// <summary>
  802. /// Returns true if the browser's audio is muted. This method can only be
  803. /// called on the UI thread.
  804. /// </summary>
  805. public bool IsAudioMuted
  806. {
  807. get
  808. {
  809. return cef_browser_host_t.is_audio_muted(_self) != 0;
  810. }
  811. }
  812. }
  813. }