// Copyright © 2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Threading.Tasks;
using CefSharp.DevTools.Page;
using CefSharp.Enums;
using CefSharp.Internals;
using CefSharp.Structs;
using CefSharp.Web;
using Point = System.Drawing.Point;
using Range = CefSharp.Structs.Range;
using Size = System.Drawing.Size;
namespace CefSharp.OffScreen
{
///
/// An offscreen instance of Chromium that you can use to take
/// snapshots or evaluate JavaScript.
///
public partial class ChromiumWebBrowser : IRenderWebBrowser
{
///
/// The managed cef browser adapter
///
private IBrowserAdapter managedCefBrowserAdapter;
///
/// Size of the Chromium viewport.
/// This must be set to something other than 0x0 otherwise Chromium will not render,
/// and the ScreenshotAsync task will deadlock.
///
private Size size = new Size(1366, 768);
///
/// Flag to guard the creation of the underlying offscreen browser - only one instance can be created
///
private bool browserCreated;
///
/// Action which is called immediately before the event after the
/// uderlying Chromium Embedded Framework (CEF) browser has been created.
///
private Action onAfterBrowserCreatedDelegate;
private float deviceScaleFactor = 1.0f;
///
/// Gets a value indicating whether this instance is disposed.
///
/// if this instance is disposed; otherwise, .
public bool IsDisposed
{
get
{
return Interlocked.CompareExchange(ref disposeSignaled, 1, 1) == 1;
}
}
///
/// A flag that indicates whether the WebBrowser is initialized (true) or not (false).
///
/// true if this instance is browser initialized; otherwise, false.
public bool IsBrowserInitialized
{
get { return InternalIsBrowserInitialized(); }
}
///
/// A flag that indicates whether the control is currently loading one or more web pages (true) or not (false).
///
/// true if this instance is loading; otherwise, false.
/// In the WPF control, this property is implemented as a Dependency Property and fully supports data
/// binding.
public bool IsLoading { get; private set; }
///
/// The text that will be displayed as a ToolTip
///
/// The tooltip text.
public string TooltipText { get; private set; }
///
/// The address (URL) which the browser control is currently displaying.
/// Will automatically be updated as the user navigates to another page (e.g. by clicking on a link).
///
/// The address.
/// In the WPF control, this property is implemented as a Dependency Property and fully supports data
/// binding.
public string Address { get; private set; }
///
/// A flag that indicates whether the state of the control current supports the GoBack action (true) or not (false).
///
/// true if this instance can go back; otherwise, false.
/// In the WPF control, this property is implemented as a Dependency Property and fully supports data
/// binding.
public bool CanGoBack { get; private set; }
///
/// A flag that indicates whether the state of the control currently supports the GoForward action (true) or not (false).
///
/// true if this instance can go forward; otherwise, false.
/// In the WPF control, this property is implemented as a Dependency Property and fully supports data
/// binding.
public bool CanGoForward { get; private set; }
///
/// Gets the request context.
///
/// The request context.
public IRequestContext RequestContext { get; private set; }
///
/// Implement and assign to handle events related to browser rendering.
///
/// The render handler.
public IRenderHandler RenderHandler { get; set; }
///
/// Implement to handle events related to accessibility.
///
/// The accessibility handler.
public IAccessibilityHandler AccessibilityHandler { get; set; }
///
/// Event called after the underlying CEF browser instance has been created.
/// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI
/// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// (The exception to this is when you're running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread).
///
public event EventHandler BrowserInitialized;
///
/// Occurs when the browser address changed.
/// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI
/// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// (The exception to this is when you're running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread).
///
public event EventHandler AddressChanged;
///
/// Occurs when [title changed].
/// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI
/// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang..
/// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread.
/// (The exception to this is when you're running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread).
///
public event EventHandler TitleChanged;
///
/// Fired on the CEF UI thread, which by default is not the same as your application main thread.
/// Called when an element should be painted. Pixel values passed to this method are scaled relative to view coordinates
/// based on the value of ScreenInfo.DeviceScaleFactor returned from GetScreenInfo.
///
public event EventHandler Paint;
///
/// Used by as the
/// event happens before the bitmap buffer is updated. We do this to allow users to mark
/// to true and stop the buffer from being updated.
///
private event EventHandler AfterPaint;
///
/// Create a new OffScreen Chromium Browser. If you use = true then you must
/// set to false and call after the objects are registered.
/// The underlying Chromium Embedded Framework(CEF) Browser is created asynchronouly, to subscribe to the event it is recommended
/// that you set to false, subscribe to the event and then call
/// to ensure you are subscribe to the event before it's fired (Issue https://github.com/cefsharp/CefSharp/issues/3552).
///
/// html string to be initially loaded in the browser.
/// The browser settings to use. If null, the default settings are used.
/// See for more details. Defaults to null
/// automatically create the underlying Browser
///
/// Use as an alternative to the event. If the underlying Chromium Embedded Framework (CEF) browser is created successfully,
/// this action is guranteed to be called after the browser created where as the event may be called before
/// you have a chance to subscribe to the event as the CEF Browser is created async. (Issue https://github.com/cefsharp/CefSharp/issues/3552).
///
/// Cef::Initialize() failed
public ChromiumWebBrowser(HtmlString html, IBrowserSettings browserSettings = null,
IRequestContext requestContext = null, bool automaticallyCreateBrowser = true,
Action onAfterBrowserCreated = null) : this(html.ToDataUriString(), browserSettings, requestContext, automaticallyCreateBrowser, onAfterBrowserCreated)
{
}
///
/// Create a new OffScreen Chromium Browser. If you use = true then you must
/// set to false and call after the objects are registered.
/// The underlying Chromium Embedded Framework(CEF) Browser is created asynchronouly, to subscribe to the event it is recommended
/// that you set to false, subscribe to the event and then call
/// to ensure you are subscribe to the event before it's fired (Issue https://github.com/cefsharp/CefSharp/issues/3552).
///
/// Initial address (url) to load
/// The browser settings to use. If null, the default settings are used.
/// See for more details. Defaults to null
/// automatically create the underlying Browser
///
/// Use as an alternative to the event. If the underlying Chromium Embedded Framework (CEF) browser is created successfully,
/// this action is guranteed to be called after the browser created where as the event may be called before
/// you have a chance to subscribe to the event as the CEF Browser is created async. (Issue https://github.com/cefsharp/CefSharp/issues/3552).
///
/// Cef::Initialize() failed
public ChromiumWebBrowser(string address = "", IBrowserSettings browserSettings = null,
IRequestContext requestContext = null, bool automaticallyCreateBrowser = true,
Action onAfterBrowserCreated = null)
{
if (!Cef.IsInitialized)
{
var settings = new CefSettings();
if (!Cef.Initialize(settings))
{
throw new InvalidOperationException(CefInitializeFailedErrorMessage);
}
}
RequestContext = requestContext;
Cef.AddDisposable(this);
Address = address;
onAfterBrowserCreatedDelegate = onAfterBrowserCreated;
managedCefBrowserAdapter = ManagedCefBrowserAdapter.Create(this, true);
if (automaticallyCreateBrowser)
{
CreateBrowser(null, browserSettings);
}
RenderHandler = new DefaultRenderHandler(this);
}
///
/// Finalizes an instance of the class.
///
~ChromiumWebBrowser()
{
Dispose(false);
}
///
/// Releases all resources used by the object
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Releases unmanaged and - optionally - managed resources for the
///
/// to release both managed and unmanaged resources; to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
// Attempt to move the disposeSignaled state from 0 to 1. If successful, we can be assured that
// this thread is the first thread to do so, and can safely dispose of the object.
if (Interlocked.CompareExchange(ref disposeSignaled, 1, 0) != 0)
{
return;
}
if (disposing)
{
CanExecuteJavascriptInMainFrame = false;
Interlocked.Exchange(ref browserInitialized, 0);
//Stop rendering immediately so later on when we dispose of the
//RenderHandler no further OnPaint calls take place
//Check browser not null as it's possible to call Dispose before it's created
browser?.GetHost().WasHidden(true);
// Don't reference event listeners any longer:
AddressChanged = null;
BrowserInitialized = null;
ConsoleMessage = null;
FrameLoadEnd = null;
FrameLoadStart = null;
LoadError = null;
LoadingStateChanged = null;
Paint = null;
AfterPaint = null;
StatusMessage = null;
TitleChanged = null;
JavascriptMessageReceived = null;
// Release reference to handlers, except LifeSpanHandler which is done after Disposing
// ManagedCefBrowserAdapter otherwise the ILifeSpanHandler.DoClose will not be invoked.
// We also leave FocusHandler and override with a NoFocusHandler implementation as
// it so we can block taking Focus (we're dispoing afterall). Issue #3715
FreeHandlersExceptLifeSpanAndFocus();
FocusHandler = new NoFocusHandler();
browser = null;
BrowserCore = null;
if (managedCefBrowserAdapter != null)
{
managedCefBrowserAdapter.Dispose();
managedCefBrowserAdapter = null;
}
// LifeSpanHandler is set to null after managedCefBrowserAdapter.Dispose so ILifeSpanHandler.DoClose
// is called.
LifeSpanHandler = null;
//Take a copy of the RenderHandler then set to property to null
//Before we dispose, reduces the changes of any OnPaint calls
//using the RenderHandler after Dispose
var renderHandler = RenderHandler;
RenderHandler = null;
renderHandler?.Dispose();
}
Cef.RemoveDisposable(this);
}
///
/// Create the underlying browser. The instance address, browser settings and request context will be used.
///
/// Window information used when creating the browser
/// Browser initialization settings
/// An instance of the underlying offscreen browser has already been created, this method can only be called once.
public void CreateBrowser(IWindowInfo windowInfo = null, IBrowserSettings browserSettings = null)
{
if (browserCreated)
{
throw new Exception("An instance of the underlying offscreen browser has already been created, this method can only be called once.");
}
browserCreated = true;
if (browserSettings == null)
{
browserSettings = Core.ObjectFactory.CreateBrowserSettings(autoDispose: true);
}
if (windowInfo == null)
{
windowInfo = Core.ObjectFactory.CreateWindowInfo();
windowInfo.SetAsWindowless(IntPtr.Zero);
}
//TODO: We need some sort of timeout and
//if we use the same approach for WPF/WinForms then
//we need to move the common code into the partial class
GlobalContextInitialized.ExecuteOrEnqueue((success) =>
{
if(!success)
{
return;
}
managedCefBrowserAdapter.CreateBrowser(windowInfo, browserSettings, RequestContext, Address);
//Dispose of BrowserSettings if we created it, if user created then they're responsible
if (browserSettings.AutoDispose)
{
browserSettings.Dispose();
}
browserSettings = null;
});
}
///
/// Create the underlying CEF browser. The address and request context passed into the constructor
/// will be used. If a delegate was passed
/// into the constructor it will not be called as this method overrides that value internally.
///
/// Window information used when creating the browser
/// Browser initialization settings
/// An instance of the underlying offscreen browser has already been created, this method can only be called once.
///
/// A that represents the creation of the underlying CEF browser ( instance.
/// When the task completes then the CEF Browser will have been created and you can start performing basic tasks.
/// Note that the control's event will be invoked after this task completes.
///
public Task CreateBrowserAsync(IWindowInfo windowInfo = null, IBrowserSettings browserSettings = null)
{
var tcs = new TaskCompletionSource();
onAfterBrowserCreatedDelegate += new Action(b =>
{
tcs.TrySetResultAsync(b);
});
try
{
CreateBrowser(windowInfo, browserSettings);
}
catch(Exception ex)
{
tcs.TrySetExceptionAsync(ex);
}
return tcs.Task;
}
///
/// Get/set the size of the Chromium viewport, in pixels.
/// This also changes the size of the next rendered bitmap.
///
/// The size.
public Size Size
{
get { return size; }
set
{
if (size != value)
{
size = value;
if (IsBrowserInitialized)
{
browser.GetHost().WasResized();
}
}
}
}
///
/// Device scale factor. Specifies the ratio between physical and logical pixels.
///
public float DeviceScaleFactor
{
get { return deviceScaleFactor; }
set
{
deviceScaleFactor = value;
if (IsBrowserInitialized)
{
browser.GetHost().NotifyScreenInfoChanged();
}
}
}
///
/// Immediately returns a copy of the last rendering from Chrome,
/// or null if no rendering has occurred yet.
/// Chrome also renders the page loading, so if you want to see a complete rendering,
/// only start this task once your page is loaded (which you can detect via FrameLoadEnd
/// or your own heuristics based on evaluating JavaScript).
/// It is your responsibility to dispose the returned Bitmap.
/// The bitmap size is determined by the Size property set earlier.
///
/// Choose which bitmap to retrieve, choose for a merged bitmap.
/// Bitmap.
public Bitmap ScreenshotOrNull(PopupBlending blend = PopupBlending.Main)
{
if (RenderHandler == null)
{
throw new NullReferenceException("RenderHandler cannot be null. Use DefaultRenderHandler unless implementing your own");
}
var renderHandler = RenderHandler as DefaultRenderHandler;
if (renderHandler == null)
{
throw new Exception("ScreenshotOrNull and ScreenshotAsync can only be used in combination with the DefaultRenderHandler");
}
lock (renderHandler.BitmapLock)
{
if (blend == PopupBlending.Main)
{
return renderHandler.BitmapBuffer.CreateBitmap();
}
if (blend == PopupBlending.Popup)
{
return renderHandler.PopupOpen ? renderHandler.PopupBuffer.CreateBitmap() : null;
}
var bitmap = renderHandler.BitmapBuffer.CreateBitmap();
if (renderHandler.PopupOpen && bitmap != null)
{
var popup = renderHandler.PopupBuffer.CreateBitmap();
if (popup == null)
{
return bitmap;
}
return MergeBitmaps(bitmap, popup, renderHandler.PopupPosition);
}
return bitmap;
}
}
///
/// Starts a task that waits for the next rendering from Chrome.
/// Chrome also renders the page loading, so if you want to see a complete rendering,
/// only start this task once your page is loaded (which you can detect via FrameLoadEnd
/// or your own heuristics based on evaluating JavaScript).
/// It is your responsibility to dispose the returned Bitmap.
/// The bitmap size is determined by the Size property set earlier.
///
/// Ignore existing bitmap (if any) and return the next available bitmap
/// Choose which bitmap to retrieve, choose for a merged bitmap.
/// Task<Bitmap>.
[Obsolete("Use CaptureScreenshotAsync instead.")]
public Task ScreenshotAsync(bool ignoreExistingScreenshot = false, PopupBlending blend = PopupBlending.Main)
{
ThrowExceptionIfDisposed();
// Try our luck and see if there is already a screenshot, to save us creating a new thread for nothing.
var screenshot = ScreenshotOrNull(blend);
var completionSource = new TaskCompletionSource();
if (screenshot == null || ignoreExistingScreenshot)
{
EventHandler afterPaint = null; // otherwise we cannot reference ourselves in the anonymous method below
afterPaint = (sender, e) =>
{
// Chromium has rendered. Tell the task about it.
AfterPaint -= afterPaint;
//If the user handled the Paint event then we'll throw an exception here
//as it's not possible to use ScreenShotAsync as the buffer wasn't updated.
if (e.Handled)
{
completionSource.TrySetException(new InvalidOperationException("OnPaintEventArgs.Handled = true, unable to process request. The buffer has not been updated"));
}
else
{
completionSource.TrySetResultAsync(ScreenshotOrNull(blend));
}
};
AfterPaint += afterPaint;
}
else
{
completionSource.TrySetResultAsync(screenshot);
}
return completionSource.Task;
}
///
/// Capture page screenshot.
///
/// Image compression format (defaults to png).
/// Compression quality from range [0..100] (jpeg only).
/// view port to capture, if not null the browser will be resized if the requested width/height
/// are larger than the current browser .
/// A task that can be awaited to obtain the screenshot as a byte[].
public async Task CaptureScreenshotAsync(CaptureScreenshotFormat? format = null, int? quality = null, Viewport viewport = null)
{
ThrowExceptionIfDisposed();
ThrowExceptionIfBrowserNotInitialized();
using (var devToolsClient = browser.GetDevToolsClient())
{
if (viewport == null)
{
var screenShot = await devToolsClient.Page.CaptureScreenshotAsync(format, quality, fromSurface: true).ConfigureAwait(continueOnCapturedContext: false);
return screenShot.Data;
}
if (viewport.Scale <= 0)
{
throw new ArgumentException($"{nameof(viewport)}.{nameof(viewport.Scale)} must be greater than 0.");
}
//https://bitbucket.org/chromiumembedded/cef/issues/3103/offscreen-capture-screenshot-with-devtools
//CEF OSR mode doesn't set the size internally when CaptureScreenShot is called with a clip param specified, so
//we must manually resize our view if size is greater
var newWidth = viewport.Width + viewport.X;
if (newWidth < size.Width)
{
newWidth = size.Width;
}
var newHeight = viewport.Height + viewport.Y;
if (newHeight < size.Height)
{
newHeight = size.Height;
}
if ((int)newWidth > size.Width || (int)newHeight > size.Height || viewport.Scale != deviceScaleFactor)
{
await ResizeAsync((int)newWidth, (int)newHeight, (float)viewport.Scale).ConfigureAwait(continueOnCapturedContext:false);
}
//Create a copy instead of modifying users object as we need to set Scale to 1
//as CEF doesn't support passing custom scale for OSR.
var clip = new Viewport
{
Height = viewport.Height,
Width = viewport.Width,
X = viewport.X,
Y = viewport.Y,
Scale = 1
};
var response = await devToolsClient.Page.CaptureScreenshotAsync(format, quality, clip: clip, fromSurface: true).ConfigureAwait(continueOnCapturedContext: false);
return response.Data;
}
}
///
/// Resize the browser
///
/// width
/// height
/// device scale factor
/// A task that can be awaited and will resolve when the desired size is achieved.
///
/// The current implementation is fairly symplistic, it simply resizes the browser
/// and resolves the task when the browser starts painting at the desired size.
///
public Task ResizeAsync(int width, int height, float? deviceScaleFactor = null)
{
ThrowExceptionIfDisposed();
ThrowExceptionIfBrowserNotInitialized();
if (size.Width == width && size.Height == height && (deviceScaleFactor == null || deviceScaleFactor == DeviceScaleFactor))
{
return Task.FromResult(true);
}
var scaledWidth = (int)(width * DeviceScaleFactor);
var scaledHeight = (int)(height * DeviceScaleFactor);
var tcs = new TaskCompletionSource();
EventHandler handler = null;
handler = (s, e) =>
{
if (e.Width == scaledWidth && e.Height == scaledHeight)
{
AfterPaint -= handler;
tcs.TrySetResultAsync(true);
}
};
AfterPaint += handler;
//Only set the value if not null otherwise
//a call to NotifyScreenInfoChanged will be made.
if (deviceScaleFactor.HasValue)
{
scaledWidth = (int)(width * deviceScaleFactor.Value);
scaledHeight = (int)(height * deviceScaleFactor.Value);
DeviceScaleFactor = deviceScaleFactor.Value;
}
Size = new Size(width, height);
return tcs.Task;
}
///
public void Load(string url)
{
if (IsDisposed)
{
return;
}
//There's a small window here between CreateBrowser
//and OnAfterBrowserCreated where the Address prop
//will be updated, though LoadUrl won't be called.
if (IsBrowserInitialized)
{
using (var frame = this.GetMainFrame())
{
frame.LoadUrl(url);
}
}
else
{
Address = url;
}
}
#if NETCOREAPP || NET462
///
/// Waits for the page rendering to be idle for .
/// Rendering is considered to be idle when no events have occured
/// for .
/// This is useful for scenarios like taking a screen shot.
///
/// optional idleTime in miliseconds, default to 500ms
/// optional timeout, if not specified defaults to thirty(30) seconds.
/// optional CancellationToken
/// Task that resolves when page rendering has been idle for
public async Task WaitForRenderIdleAsync(int idleTimeInMs = 500, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
{
var renderIdleTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var idleTimer = new System.Timers.Timer
{
Interval = idleTimeInMs,
AutoReset = false
};
EventHandler handler = null;
idleTimer.Elapsed += (sender, args) =>
{
Paint -= handler;
idleTimer.Stop();
idleTimer.Dispose();
renderIdleTcs.TrySetResult(true);
};
//Every time Paint is called we reset our timer
handler = (s, args) =>
{
idleTimer.Stop();
idleTimer.Start();
};
idleTimer.Start();
Paint += handler;
try
{
await TaskTimeoutExtensions.WaitAsync(renderIdleTcs.Task, timeout ?? TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false);
}
catch(Exception)
{
Paint -= handler;
idleTimer?.Stop();
idleTimer?.Dispose();
throw;
}
}
#endif
///
/// The javascript object repository, one repository per ChromiumWebBrowser instance.
///
public IJavascriptObjectRepository JavascriptObjectRepository
{
get { return managedCefBrowserAdapter?.JavascriptObjectRepository; }
}
///
/// Has Focus - Always False
///
/// returns false
bool IChromiumWebBrowserBase.Focus()
{
// no control to focus for offscreen browser
return false;
}
///
/// Returns the current CEF Browser Instance
///
/// browser instance or null
public IBrowser GetBrowser()
{
ThrowExceptionIfDisposed();
ThrowExceptionIfBrowserNotInitialized();
return browser;
}
///
/// Gets the screen information (scale factor).
///
/// ScreenInfo.
ScreenInfo? IRenderWebBrowser.GetScreenInfo()
{
return GetScreenInfo();
}
///
/// Gets the screen information (scale factor).
///
/// ScreenInfo.
protected virtual ScreenInfo? GetScreenInfo()
{
var renderHandler = RenderHandler;
if(renderHandler == null)
{
var screenInfo = new ScreenInfo { DeviceScaleFactor = DeviceScaleFactor };
return screenInfo;
}
return renderHandler.GetScreenInfo();
}
///
/// Gets the view rect (width, height)
///
/// ViewRect.
Rect IRenderWebBrowser.GetViewRect()
{
return GetViewRect();
}
///
/// Gets the view rect (width, height)
///
/// ViewRect.
protected virtual Rect GetViewRect()
{
var renderHandler = RenderHandler;
if (renderHandler == null)
{
var size = Size;
var viewRect = new Rect(0, 0, size.Width, size.Height);
return viewRect;
}
return renderHandler.GetViewRect();
}
///
/// Called to retrieve the translation from view coordinates to actual screen coordinates.
///
/// x
/// y
/// screen x
/// screen y
/// Return true if the screen coordinates were provided.
bool IRenderWebBrowser.GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY)
{
return GetScreenPoint(viewX, viewY, out screenX, out screenY);
}
///
/// Called to retrieve the translation from view coordinates to actual screen coordinates.
///
/// x
/// y
/// screen x
/// screen y
/// Return true if the screen coordinates were provided.
protected virtual bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY)
{
screenX = 0;
screenY = 0;
return RenderHandler?.GetScreenPoint(viewX, viewY, out screenX, out screenY) ?? false;
}
///
/// Called when an element has been rendered to the shared texture handle.
/// This method is only called when is set to true
///
/// indicates whether the element is the view or the popup widget.
/// contains the set of rectangles in pixel coordinates that need to be repainted
/// is the handle for a D3D11 Texture2D that can be accessed via ID3D11Device using the OpenSharedResource method.
void IRenderWebBrowser.OnAcceleratedPaint(PaintElementType type, Rect dirtyRect, IntPtr sharedHandle)
{
RenderHandler?.OnAcceleratedPaint(type, dirtyRect, sharedHandle);
}
///
/// Called when an element should be painted. (Invoked from CefRenderHandler.OnPaint)
///
/// indicates whether the element is the view or the popup widget.
/// contains the set of rectangles in pixel coordinates that need to be repainted
/// The bitmap will be will be width * height *4 bytes in size and represents a BGRA image with an upper-left origin
/// width
/// height
void IRenderWebBrowser.OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height)
{
var handled = false;
var args = new OnPaintEventArgs(type == PaintElementType.Popup, dirtyRect, buffer, width, height);
var handler = Paint;
if (handler != null)
{
handler(this, args);
handled = args.Handled;
}
if (!handled)
{
RenderHandler?.OnPaint(type, dirtyRect, buffer, width, height);
}
var afterHandler = AfterPaint;
if (afterHandler != null)
{
afterHandler(this, args);
}
}
///
/// Called when the browser's cursor has changed. .
///
/// If type is Custom then customCursorInfo will be populated with the custom cursor information
/// cursor type
/// custom cursor Information
void IRenderWebBrowser.OnCursorChange(IntPtr cursor, CursorType type, CursorInfo customCursorInfo)
{
RenderHandler?.OnCursorChange(cursor, type, customCursorInfo);
}
///
/// Starts dragging.
///
/// The drag data.
/// The mask.
/// The x.
/// The y.
/// true if XXXX, false otherwise.
bool IRenderWebBrowser.StartDragging(IDragData dragData, DragOperationsMask mask, int x, int y)
{
return RenderHandler?.StartDragging(dragData, mask, x, y) ?? false;
}
void IRenderWebBrowser.UpdateDragCursor(DragOperationsMask operation)
{
RenderHandler?.UpdateDragCursor(operation);
}
///
/// Sets the popup is open.
///
/// if set to true [show].
void IRenderWebBrowser.OnPopupShow(bool show)
{
RenderHandler?.OnPopupShow(show);
}
///
/// Called when the browser wants to move or resize the popup widget.
///
/// contains the new location and size in view coordinates.
void IRenderWebBrowser.OnPopupSize(Rect rect)
{
RenderHandler?.OnPopupSize(rect);
}
void IRenderWebBrowser.OnImeCompositionRangeChanged(Range selectedRange, Rect[] characterBounds)
{
RenderHandler?.OnImeCompositionRangeChanged(selectedRange, characterBounds);
}
void IRenderWebBrowser.OnVirtualKeyboardRequested(IBrowser browser, TextInputMode inputMode)
{
RenderHandler?.OnVirtualKeyboardRequested(browser, inputMode);
}
///
/// Called when [after browser created].
///
/// The browser.
partial void OnAfterBrowserCreated(IBrowser browser)
{
onAfterBrowserCreatedDelegate?.Invoke(browser);
BrowserInitialized?.Invoke(this, EventArgs.Empty);
}
///
/// Sets the address.
///
/// The instance containing the event data.
void IWebBrowserInternal.SetAddress(AddressChangedEventArgs args)
{
Address = args.Address;
AddressChanged?.Invoke(this, args);
}
///
/// Sets the loading state change.
///
/// The instance containing the event data.
partial void SetLoadingStateChange(LoadingStateChangedEventArgs args)
{
CanGoBack = args.CanGoBack;
CanGoForward = args.CanGoForward;
IsLoading = args.IsLoading;
}
///
/// Sets the title.
///
/// The instance containing the event data.
void IWebBrowserInternal.SetTitle(TitleChangedEventArgs args)
{
TitleChanged?.Invoke(this, args);
}
///
/// Sets the tooltip text.
///
/// The tooltip text.
void IWebBrowserInternal.SetTooltipText(string tooltipText)
{
TooltipText = tooltipText;
}
///
/// Creates a new bitmap with the dimensions of firstBitmap, then
/// draws the firstBitmap, then overlays the secondBitmap
///
/// First bitmap, this will be the first image drawn
/// Second bitmap, this image will be drawn on the first
/// Position of the second bitmap
/// The merged bitmap, size of firstBitmap
private Bitmap MergeBitmaps(Bitmap firstBitmap, Bitmap secondBitmap, Point secondBitmapPosition)
{
var mergedBitmap = new Bitmap(firstBitmap.Width, firstBitmap.Height, PixelFormat.Format32bppPArgb);
using (var g = Graphics.FromImage(mergedBitmap))
{
g.DrawImage(firstBitmap, new Rectangle(0, 0, firstBitmap.Width, firstBitmap.Height));
g.DrawImage(secondBitmap, new Rectangle(secondBitmapPosition.X, secondBitmapPosition.Y, secondBitmap.Width, secondBitmap.Height));
}
return mergedBitmap;
}
}
}