diff --git a/CefSharp.Core/Internals/ClientAdapter.cpp b/CefSharp.Core/Internals/ClientAdapter.cpp index 65a6db25d..a7ebc51e0 100644 --- a/CefSharp.Core/Internals/ClientAdapter.cpp +++ b/CefSharp.Core/Internals/ClientAdapter.cpp @@ -147,12 +147,6 @@ namespace CefSharp if (browserAdapter != nullptr) { client = browserAdapter->GetClientAdapter().get(); - - auto renderClientAdapter = dynamic_cast(client.get()); - if (renderClientAdapter != nullptr) - { - renderClientAdapter->CreateBitmapInfo(); - } } } } diff --git a/CefSharp.Core/Internals/RenderClientAdapter.h b/CefSharp.Core/Internals/RenderClientAdapter.h index c6dd07c13..44d8ca04a 100644 --- a/CefSharp.Core/Internals/RenderClientAdapter.h +++ b/CefSharp.Core/Internals/RenderClientAdapter.h @@ -19,15 +19,11 @@ namespace CefSharp public CefRenderHandler { private: - gcroot _webBrowserInternal; gcroot _renderWebBrowser; - gcroot _mainBitmapInfo; - gcroot _popupBitmapInfo; public: RenderClientAdapter(IWebBrowserInternal^ webBrowserInternal, IBrowserAdapter^ browserAdapter): - ClientAdapter(webBrowserInternal, browserAdapter), - _webBrowserInternal(webBrowserInternal) + ClientAdapter(webBrowserInternal, browserAdapter) { _renderWebBrowser = dynamic_cast(webBrowserInternal); } @@ -35,23 +31,6 @@ namespace CefSharp ~RenderClientAdapter() { _renderWebBrowser = nullptr; - _webBrowserInternal = nullptr; - - ReleaseBitmapHandlers(_mainBitmapInfo); - - delete _mainBitmapInfo; - _mainBitmapInfo = nullptr; - - ReleaseBitmapHandlers(_popupBitmapInfo); - - delete _popupBitmapInfo; - _popupBitmapInfo = nullptr; - } - - void CreateBitmapInfo() - { - _mainBitmapInfo = _renderWebBrowser->CreateBitmapInfo(false); - _popupBitmapInfo = _renderWebBrowser->CreateBitmapInfo(true); } // CefClient @@ -126,60 +105,8 @@ namespace CefSharp virtual DECL void OnPaint(CefRefPtr browser, PaintElementType type, const RectList& dirtyRects, const void* buffer, int width, int height) OVERRIDE { - auto bitmapInfo = type == PET_VIEW ? _mainBitmapInfo : _popupBitmapInfo; - - lock l(bitmapInfo->BitmapLock); - - if(bitmapInfo->DirtyRectSupport) - { - //NOTE: According to https://bitbucket.org/chromiumembedded/cef/commits/1ddb0ba41d7052eaad50b8d9de959f3b5e05ff21?at=master - // There is only one rect now that's a union of all dirty regions. API Still passes in a vector - - CefRect r = dirtyRects.front(); - bitmapInfo->DirtyRect = Rect(r.x, r.y, r.width, r.height); - } - - auto backBufferHandle = (HANDLE)bitmapInfo->BackBufferHandle; - - if (backBufferHandle == NULL || bitmapInfo->Width != width || bitmapInfo->Height != height) - { - int pixels = width * height; - int numberOfBytes = pixels * bitmapInfo->BytesPerPixel; - auto fileMappingHandle = (HANDLE)bitmapInfo->FileMappingHandle; - - //Clear the reference to Bitmap so a new one is created by InvokeRenderAsync - bitmapInfo->ClearBitmap(); - - //Release the current handles (if not null) - ReleaseBitmapHandlers(bitmapInfo); - - // Create new fileMappingHandle - fileMappingHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, numberOfBytes, NULL); - if (fileMappingHandle == NULL) - { - // TODO: Consider doing something more sensible here, since the browser will be very badly broken if this - // TODO: method call fails. - return; - } - - backBufferHandle = MapViewOfFile(fileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, numberOfBytes); - if (backBufferHandle == NULL) - { - // TODO: Consider doing something more sensible here, since the browser will be very badly broken if this - // TODO: method call fails. - return; - } - - bitmapInfo->FileMappingHandle = (IntPtr)fileMappingHandle; - bitmapInfo->BackBufferHandle = (IntPtr)backBufferHandle; - bitmapInfo->Width = width; - bitmapInfo->Height = height; - bitmapInfo->NumberOfBytes = numberOfBytes; - } - - CopyMemory(backBufferHandle, (void*)buffer, bitmapInfo->NumberOfBytes); - - _renderWebBrowser->OnPaint(bitmapInfo); + CefRect r = dirtyRects.front(); + _renderWebBrowser->OnPaint((CefSharp::PaintElementType)type, Rect(r.x, r.y, r.width, r.height), IntPtr((void *)buffer), width, height); }; virtual DECL void OnCursorChange(CefRefPtr browser, CefCursorHandle cursor, CursorType type, @@ -225,30 +152,6 @@ namespace CefSharp _renderWebBrowser->OnImeCompositionRangeChanged(Range(selectedRange.from, selectedRange.to), charBounds); } - private: - void ReleaseBitmapHandlers(BitmapInfo^ bitmapInfo) - { - if(bitmapInfo) - { - auto backBufferHandle = (HANDLE)bitmapInfo->BackBufferHandle; - auto fileMappingHandle = (HANDLE)bitmapInfo->FileMappingHandle; - - if (backBufferHandle != NULL) - { - UnmapViewOfFile(backBufferHandle); - backBufferHandle = NULL; - bitmapInfo->BackBufferHandle = IntPtr::Zero; - } - - if (fileMappingHandle != NULL) - { - CloseHandle(fileMappingHandle); - fileMappingHandle = NULL; - bitmapInfo->FileMappingHandle = IntPtr::Zero; - } - } - } - IMPLEMENT_REFCOUNTING(RenderClientAdapter) }; } diff --git a/CefSharp.Core/ManagedCefBrowserAdapter.cpp b/CefSharp.Core/ManagedCefBrowserAdapter.cpp index e3a4c218e..cd3c3f5f6 100644 --- a/CefSharp.Core/ManagedCefBrowserAdapter.cpp +++ b/CefSharp.Core/ManagedCefBrowserAdapter.cpp @@ -18,10 +18,6 @@ bool ManagedCefBrowserAdapter::IsDisposed::get() void ManagedCefBrowserAdapter::CreateOffscreenBrowser(IntPtr windowHandle, BrowserSettings^ browserSettings, RequestContext^ requestContext, String^ address) { - //Create the required BitmapInfo classes before the offscreen browser is initialized - auto renderClientAdapter = dynamic_cast(_clientAdapter.get()); - renderClientAdapter->CreateBitmapInfo(); - auto hwnd = static_cast(windowHandle.ToPointer()); CefWindowInfo window; diff --git a/CefSharp.OffScreen/BitmapBuffer.cs b/CefSharp.OffScreen/BitmapBuffer.cs new file mode 100644 index 000000000..f3dd9cedf --- /dev/null +++ b/CefSharp.OffScreen/BitmapBuffer.cs @@ -0,0 +1,102 @@ +// Copyright © 2010-2017 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.Runtime.InteropServices; + +namespace CefSharp.OffScreen +{ + public class BitmapBuffer + { + private const int BytesPerPixel = 4; + private const PixelFormat Format = PixelFormat.Format32bppPArgb; + + private byte[] buffer; + + /// + /// Number of bytes + /// + public int NumberOfBytes { get; private set; } + /// + /// Width + /// + public int Width { get; private set; } + /// + /// Height + /// + public int Height { get; private set; } + /// + /// Dirty Rect - unified region containing th + /// + public Rect DirtyRect { get; private set; } + + public object BitmapLock { get; private set; } + + public BitmapBuffer(object bitmapLock) + { + BitmapLock = bitmapLock; + } + + public byte[] Buffer + { + get { return buffer; } + } + + //TODO: May need to Pin the buffer in memory using GCHandle.Alloc(this.buffer, GCHandleType.Pinned); + private void ResizeBuffer(int width, int height) + { + if (buffer == null) + { + //No of Pixels (width * height) * BytesPerPixel + NumberOfBytes = width * height * BytesPerPixel; + + buffer = new byte[NumberOfBytes]; + + Width = width; + Height = height; + } + else if (width != Width || height != Height) + { + //No of Pixels (width * height) * BytesPerPixel + NumberOfBytes = width * height * BytesPerPixel; + + Array.Resize(ref buffer, NumberOfBytes); + Width = width; + Height = height; + } + } + + public void UpdateBuffer(int width, int height, IntPtr buffer, Rect dirtyRect) + { + lock (BitmapLock) + { + DirtyRect = dirtyRect; + ResizeBuffer(width, height); + Marshal.Copy(buffer, this.buffer, 0, NumberOfBytes); + } + } + + public Bitmap CreateBitmap() + { + lock (BitmapLock) + { + if (Width == 0 || Height == 0 || buffer.Length == 0) + { + return null; + } + + var stride = Width * BytesPerPixel; + + var pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); + + var bitmap = new Bitmap(Width, Height, stride, Format, pointer); + + return bitmap; + } + } + } +} diff --git a/CefSharp.OffScreen/BitmapFactory.cs b/CefSharp.OffScreen/BitmapFactory.cs deleted file mode 100644 index fdfce2584..000000000 --- a/CefSharp.OffScreen/BitmapFactory.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2010-2017 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 CefSharp.Internals; - -namespace CefSharp.OffScreen -{ - /// - /// BitmapFactory. - /// - /// - public class BitmapFactory : IBitmapFactory - { - /// - /// The bitmap lock - /// - private readonly object bitmapLock; - - /// - /// Initializes a new instance of the class. - /// - /// The lock object. - public BitmapFactory(object lockObject) - { - bitmapLock = lockObject; - } - - /// - /// Create an instance of BitmapInfo based on the params - /// - /// create bitmap info for a popup (typically just a bool flag used internally) - /// DPI scale - /// newly created BitmapInfo - BitmapInfo IBitmapFactory.CreateBitmap(bool isPopup, double dpiScale) - { - //The bitmap buffer is 32 BPP - return new GdiBitmapInfo { IsPopup = isPopup, BitmapLock = bitmapLock }; - } - } -} diff --git a/CefSharp.OffScreen/CefSharp.OffScreen.csproj b/CefSharp.OffScreen/CefSharp.OffScreen.csproj index 6f8cd436c..2acc67161 100644 --- a/CefSharp.OffScreen/CefSharp.OffScreen.csproj +++ b/CefSharp.OffScreen/CefSharp.OffScreen.csproj @@ -72,9 +72,8 @@ - + - diff --git a/CefSharp.OffScreen/ChromiumWebBrowser.cs b/CefSharp.OffScreen/ChromiumWebBrowser.cs index 94e723c9f..bb3e8a0bc 100644 --- a/CefSharp.OffScreen/ChromiumWebBrowser.cs +++ b/CefSharp.OffScreen/ChromiumWebBrowser.cs @@ -24,15 +24,12 @@ namespace CefSharp.OffScreen private ManagedCefBrowserAdapter managedCefBrowserAdapter; /// - /// Contains the last rendering from Chromium. Direct access - /// to the underlying Bitmap - there is no locking when trying - /// to access directly, use where appropriate. - /// A new bitmap is only created when it's size changes, otherwise - /// the back buffer for the bitmap is constantly updated. - /// Read the doco for more info. + /// Contains the last bitmap buffer. Direct access + /// to the underlying buffer - there is no locking when trying + /// to access directly, use where appropriate. /// /// The bitmap. - public Bitmap Bitmap { get; protected set; } + public BitmapBuffer BitmapBuffer { get; protected set; } /// /// Need a lock because the caller may be asking for the bitmap @@ -182,11 +179,6 @@ namespace CefSharp.OffScreen /// The geolocation handler. public IGeolocationHandler GeolocationHandler { get; set; } /// - /// Gets or sets the bitmap factory. - /// - /// The bitmap factory. - public IBitmapFactory BitmapFactory { get; set; } - /// /// Implement and assign to handle messages from the render process. /// /// The render process message handler. @@ -276,13 +268,6 @@ namespace CefSharp.OffScreen /// public event EventHandler TitleChanged; - /// - /// Fired by a separate thread when Chrome has re-rendered. - /// This means that a Bitmap will be returned by ScreenshotOrNull(). - /// - [Obsolete("Subscribe to OnPaint instead as this event will be removed in future versions.")] - public event EventHandler NewScreenshot; - /// /// 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 @@ -291,7 +276,7 @@ namespace CefSharp.OffScreen /// of rectangles in pixel coordinates that need to be repainted. |buffer| will be |width|*|height|*4 bytes in size and /// represents a BGRA image with an upper-left origin. /// - public event EventHandler OnPaint; + public event EventHandler Paint; /// /// A flag that indicates if you can execute javascript in the main frame. @@ -313,7 +298,7 @@ namespace CefSharp.OffScreen /// /// The popup Bitmap. /// - public Bitmap Popup { get; protected set; } + public BitmapBuffer PopupBuffer { get; protected set; } /// /// Create a new OffScreen Chromium Browser @@ -331,8 +316,6 @@ namespace CefSharp.OffScreen throw new InvalidOperationException("Cef::Initialize() failed"); } - BitmapFactory = new BitmapFactory(BitmapLock); - ResourceHandlerFactory = new DefaultResourceHandlerFactory(); BrowserSettings = browserSettings ?? new BrowserSettings(); RequestContext = requestContext; @@ -347,6 +330,8 @@ namespace CefSharp.OffScreen CreateBrowser(IntPtr.Zero); } + BitmapBuffer = new BitmapBuffer(BitmapLock); + PopupBuffer = new BitmapBuffer(BitmapLock); popupPosition = new Point(); popupSize = new Size(); } @@ -391,12 +376,6 @@ namespace CefSharp.OffScreen browser = null; IsBrowserInitialized = false; - if (Bitmap != null) - { - Bitmap.Dispose(); - Bitmap = null; - } - if (BrowserSettings != null) { BrowserSettings.Dispose(); @@ -479,38 +458,41 @@ namespace CefSharp.OffScreen /// 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 LoadingStateChanged/FrameLoadEnd + /// 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 property set earlier. + /// The bitmap size is determined by the Size property set earlier. /// /// Choose which bitmap to retrieve, choose for a merged bitmap. /// Bitmap. - [Obsolete("Use ScreenshotAsync as this method will be removed in future versions.")] public Bitmap ScreenshotOrNull(PopupBlending blend = PopupBlending.Main) { lock (BitmapLock) { - if (blend == PopupBlending.Blend) + if (blend == PopupBlending.Main) { - if (PopupOpen && Bitmap != null && Popup != null) - { - return MergeBitmaps(Bitmap, Popup); - } - - return Bitmap == null ? null : new Bitmap(Bitmap); - } - else if(blend == PopupBlending.Popup) - { - if (PopupOpen) - { - return Popup == null ? null : new Bitmap(Popup); - } - - return null; + return BitmapBuffer.CreateBitmap(); } - return Bitmap == null ? null : new Bitmap(Bitmap); + if (blend == PopupBlending.Popup) + { + return PopupOpen ? PopupBuffer.CreateBitmap() : null; + } + + + var bitmap = BitmapBuffer.CreateBitmap(); + + if (PopupOpen && bitmap != null) + { + var popup = PopupBuffer.CreateBitmap(); + if (popup == null) + { + return bitmap; + } + return MergeBitmaps(bitmap, popup); + } + + return bitmap; } } @@ -534,17 +516,17 @@ namespace CefSharp.OffScreen if (screenshot == null || ignoreExistingScreenshot) { - EventHandler onPaint = null; // otherwise we cannot reference ourselves in the anonymous method below + EventHandler paint = null; // otherwise we cannot reference ourselves in the anonymous method below - onPaint = (sender, e) => + paint = (sender, e) => { - // Chromium has rendered. Tell the task about it. - OnPaint -= onPaint; + // Chromium has rendered. Tell the task about it. + Paint -= paint; completionSource.TrySetResultAsync(ScreenshotOrNull()); }; - OnPaint += onPaint; + Paint += paint; } else { @@ -703,89 +685,46 @@ namespace CefSharp.OffScreen } /// - /// Creates the bitmap information. + /// Called when an element should be painted. (Invoked from CefRenderHandler.OnPaint) /// - /// if set to true [is popup]. - /// BitmapInfo. - /// BitmapFactory cannot be null - BitmapInfo IRenderWebBrowser.CreateBitmapInfo(bool isPopup) - { - if (BitmapFactory == null) - { - throw new Exception("BitmapFactory cannot be null"); - } - return BitmapFactory.CreateBitmap(isPopup, 1.0F); - } - - /// - /// Invoked from CefRenderHandler.OnPaint - /// A new is only created when - /// is true, otherwise the new buffer is simply copied into the backBuffer of the existing - /// for efficiency. Locking provided by OnPaint as this method is called - /// in it's lock scope. - /// - /// information about the bitmap to be rendered - void IRenderWebBrowser.OnPaint(BitmapInfo bitmapInfo) + /// 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 handler = OnPaint; + var handler = Paint; if (handler != null) { - var args = new OnPaintEventArgs(bitmapInfo.IsPopup, bitmapInfo.DirtyRect, bitmapInfo.BackBufferHandle, - bitmapInfo.Width, bitmapInfo.Height, bitmapInfo.BytesPerPixel, bitmapInfo.NumberOfBytes); + var args = new OnPaintEventArgs(type == PaintElementType.Popup, dirtyRect, buffer, width, height); handler(this, args); - handled = args.Handled; } if(!handled) { - var newScreenshotHandler = NewScreenshot; - if (newScreenshotHandler != null) - { - newScreenshotHandler(this, EventArgs.Empty); - } - - InvokeRenderAsync(bitmapInfo); + OnPaint(type, dirtyRect, buffer, width, height); } } /// - /// Invoked from CefRenderHandler.OnPaint - /// A new is only created when - /// is true, otherwise the new buffer is simply copied into the backBuffer of the existing - /// for efficiency. Locking provided by OnPaint as this method is called - /// in it's lock scope. + /// Called when an element should be painted. (Invoked from CefRenderHandler.OnPaint) /// - /// information about the bitmap to be rendered - protected virtual void InvokeRenderAsync(BitmapInfo bitmapInfo) + /// 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 + protected virtual void OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height) { - var gdiBitmapInfo = (GdiBitmapInfo)bitmapInfo; + var isPopup = type == PaintElementType.Popup; - if (bitmapInfo.CreateNewBitmap) - { - if (gdiBitmapInfo.IsPopup) - { - if (Popup != null) - { - Popup.Dispose(); - Popup = null; - } + var bitmapBuffer = isPopup ? PopupBuffer : BitmapBuffer; - Popup = gdiBitmapInfo.CreateBitmap(); - } - else - { - if (Bitmap != null) - { - Bitmap.Dispose(); - Bitmap = null; - } - - Bitmap = gdiBitmapInfo.CreateBitmap(); - } - } + bitmapBuffer.UpdateBuffer(width, height, buffer, dirtyRect); } /// @@ -855,13 +794,6 @@ namespace CefSharp.OffScreen protected virtual void SetPopupIsOpen(bool show) { PopupOpen = show; - - //Cleanup the old popup now that's it's not open - if (!PopupOpen && Popup != null) - { - Popup.Dispose(); - Popup = null; - } } /// diff --git a/CefSharp.OffScreen/GdiBitmapInfo.cs b/CefSharp.OffScreen/GdiBitmapInfo.cs deleted file mode 100644 index 8e6e57774..000000000 --- a/CefSharp.OffScreen/GdiBitmapInfo.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright © 2010-2017 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 CefSharp.Internals; - -namespace CefSharp.OffScreen -{ - /// - /// Uses GdiBitmap to render the backbuffer. - /// - /// - public class GdiBitmapInfo : BitmapInfo - { - /// - /// The bitmap - /// - private Bitmap bitmap; - - /// - /// The create new bitmap - /// - private bool createNewBitmap; - - /// - /// Initializes a new instance of the class. - /// - public GdiBitmapInfo() - { - BytesPerPixel = 4; - } - - /// - /// Gets a value indicating whether [create new bitmap]. - /// - /// true if [create new bitmap]; otherwise, false. - public override bool CreateNewBitmap - { - get { return createNewBitmap; } - } - - /// - /// Clears the bitmap. - /// - public override void ClearBitmap() - { - createNewBitmap = true; - } - - /// - /// Creates the bitmap. - /// - /// Bitmap. - public virtual Bitmap CreateBitmap() - { - if(BackBufferHandle == IntPtr.Zero) - { - return null; - } - - var stride = Width * BytesPerPixel; - - bitmap = new Bitmap(Width, Height, stride, PixelFormat.Format32bppPArgb, BackBufferHandle); - - createNewBitmap = false; - - return bitmap; - } - } -} diff --git a/CefSharp.OffScreen/OnPaintEventArgs.cs b/CefSharp.OffScreen/OnPaintEventArgs.cs index 4b2c90555..64f435be3 100644 --- a/CefSharp.OffScreen/OnPaintEventArgs.cs +++ b/CefSharp.OffScreen/OnPaintEventArgs.cs @@ -16,8 +16,6 @@ namespace CefSharp public int Width { get; private set; } public int Height { get; private set; } public IntPtr BufferHandle { get; private set; } - public int BytesPerPixel { get; private set; } - public int NumberOfBytes { get; set; } public Rect DirtyRect { get; private set; } /// @@ -30,15 +28,13 @@ namespace CefSharp /// height /// bytes per pixel /// number of bytes in the buffer - public OnPaintEventArgs(bool isPopup, Rect dirtyRect, IntPtr bufferHandle, int width, int height, int bytesPerPixel, int numberOfBytes) + public OnPaintEventArgs(bool isPopup, Rect dirtyRect, IntPtr bufferHandle, int width, int height) { IsPopup = isPopup; DirtyRect = dirtyRect; BufferHandle = bufferHandle; Width = width; Height = height; - BytesPerPixel = bytesPerPixel; - NumberOfBytes = numberOfBytes; } } } diff --git a/CefSharp.Wpf.Example/Controls/ChromiumWebBrowserWithScreenshotSupport.cs b/CefSharp.Wpf.Example/Controls/ChromiumWebBrowserWithScreenshotSupport.cs index cda38a8df..c54aa9bc0 100644 --- a/CefSharp.Wpf.Example/Controls/ChromiumWebBrowserWithScreenshotSupport.cs +++ b/CefSharp.Wpf.Example/Controls/ChromiumWebBrowserWithScreenshotSupport.cs @@ -6,6 +6,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.IO.MemoryMappedFiles; +using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; @@ -23,6 +25,12 @@ namespace CefSharp.Wpf.Example.Controls /// public class ChromiumWebBrowserWithScreenshotSupport : ChromiumWebBrowser { + [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] + private static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); + + private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; + private static int BytesPerPixel = PixelFormat.BitsPerPixel / 8; + private volatile bool isTakingScreenshot = false; private Size? screenshotSize; private int oldFrameRate; @@ -93,7 +101,7 @@ namespace CefSharp.Wpf.Example.Controls return base.GetViewRect(); } - protected override void OnPaint(BitmapInfo bitmapInfo) + protected override void OnPaint(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height) { if(isTakingScreenshot) { @@ -105,34 +113,51 @@ namespace CefSharp.Wpf.Example.Controls } //Wait until we have a frame that matches the updated size we requested - if (screenshotSize.HasValue && screenshotSize.Value.Width == bitmapInfo.Width && screenshotSize.Value.Height == bitmapInfo.Height) - { + if (screenshotSize.HasValue && screenshotSize.Value.Width == width && screenshotSize.Value.Height == height) + { + var stride = width * BytesPerPixel; + var numberOfBytes = stride * height; + + //Create out own memory mapped view for the screenshot and copy the buffer into it. + //If we were going to create a lot of screenshots then it would be better to allocate a large buffer + //and reuse it. + var mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); + var viewAccessor = mappedFile.CreateViewAccessor(); + + CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes); + //Bitmaps need to be created on the UI thread Dispatcher.BeginInvoke((Action)(() => { - var stride = bitmapInfo.Width * bitmapInfo.BytesPerPixel; + var backBuffer = mappedFile.SafeMemoryMappedFileHandle.DangerousGetHandle(); + //NOTE: Interopbitmap is not capable of supporting DPI scaling + var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBuffer, + width, height, PixelFormats.Bgra32, stride, 0); + //Using TaskExtensions.TrySetResultAsync extension method so continuation runs on Threadpool + screenshotTaskCompletionSource.TrySetResultAsync(bitmap); - lock (bitmapInfo.BitmapLock) + isTakingScreenshot = false; + var browserHost = GetBrowser().GetHost(); + //Return the framerate to the previous value + browserHost.WindowlessFrameRate = oldFrameRate; + //Let the browser know the size changes so normal rendering can continue + browserHost.WasResized(); + + if(viewAccessor != null) { - //NOTE: Interopbitmap is not capable of supporting DPI scaling - var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, - bitmapInfo.Width, bitmapInfo.Height, PixelFormats.Bgra32, stride, 0); - //Using TaskExtensions.TrySetResultAsync extension method so continuation runs on Threadpool - screenshotTaskCompletionSource.TrySetResultAsync(bitmap); + viewAccessor.Dispose(); + } - isTakingScreenshot = false; - var browserHost = GetBrowser().GetHost(); - //Return the framerate to the previous value - browserHost.WindowlessFrameRate = oldFrameRate; - //Let the browser know the size changes so normal rendering can continue - browserHost.WasResized(); + if(mappedFile != null) + { + mappedFile.Dispose(); } })); } } else { - base.OnPaint(bitmapInfo); + base.OnPaint(isPopup, dirtyRect, buffer, width, height); } } diff --git a/CefSharp.Wpf/CefSharp.Wpf.csproj b/CefSharp.Wpf/CefSharp.Wpf.csproj index abe045d23..99fecfbc0 100644 --- a/CefSharp.Wpf/CefSharp.Wpf.csproj +++ b/CefSharp.Wpf/CefSharp.Wpf.csproj @@ -79,19 +79,18 @@ + - Code - - + + + - - diff --git a/CefSharp.Wpf/ChromiumWebBrowser.cs b/CefSharp.Wpf/ChromiumWebBrowser.cs index 1dc1b7ae3..42ffdd00f 100644 --- a/CefSharp.Wpf/ChromiumWebBrowser.cs +++ b/CefSharp.Wpf/ChromiumWebBrowser.cs @@ -4,7 +4,6 @@ using CefSharp.Internals; using CefSharp.Wpf.Internals; -using CefSharp.Wpf.Rendering; using Microsoft.Win32.SafeHandles; using System; using System.Threading; @@ -17,8 +16,8 @@ using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Threading; -using CefSharp.ModelBinding; using System.Runtime.CompilerServices; +using CefSharp.Wpf.Rendering; namespace CefSharp.Wpf { @@ -270,9 +269,12 @@ namespace CefSharp.Wpf public event EventHandler LoadingStateChanged; /// - /// Raised before each render cycle, and allows you to adjust the bitmap before it's rendered/applied + /// Raised every time is called. You can access the underlying buffer, though it's + /// preferable to either override or implement your own as there is no outwardly + /// accessible locking (locking is done within the default implementations). + /// 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 /// - public event EventHandler Rendering; + public event EventHandler Paint; /// /// Navigates to the previous page in the browser history. Will automatically be enabled/disabled depending on the @@ -415,9 +417,7 @@ namespace CefSharp.Wpf { throw new InvalidOperationException("Cef::Initialize() failed"); } - - BitmapFactory = new BitmapFactory(); - + //Add this ChromiumWebBrowser instance to a list of IDisposable objects // that if still alive at the time Cef.Shutdown is called will be disposed of // It's important all browser instances be freed before Cef.Shutdown is called. @@ -468,6 +468,7 @@ namespace CefSharp.Wpf ResourceHandlerFactory = new DefaultResourceHandlerFactory(); BrowserSettings = new BrowserSettings(); + BitmapFactory = new InteropBitmapFactory(); PresentationSource.AddSourceChangedHandler(this, PresentationSourceChangedHandler); @@ -516,7 +517,7 @@ namespace CefSharp.Wpf FrameLoadEnd = null; LoadError = null; LoadingStateChanged = null; - Rendering = null; + Paint = null; if (isDisposing) { @@ -651,34 +652,6 @@ namespace CefSharp.Wpf return true; } - /// - /// Creates the BitmapInfo instance used for rendering. Two instances - /// will be created, one will be used for the popup - /// - /// if set to true [is popup]. - /// BitmapInfo. - /// BitmapFactory cannot be null - BitmapInfo IRenderWebBrowser.CreateBitmapInfo(bool isPopup) - { - return CreateBitmapInfo(isPopup); - } - - /// - /// Creates the BitmapInfo instance used for rendering. Two instances - /// will be created, one will be used for the popup - /// - /// if set to true [is popup]. - /// BitmapInfo. - /// BitmapFactory cannot be null - protected virtual BitmapInfo CreateBitmapInfo(bool isPopup) - { - if (BitmapFactory == null) - { - throw new Exception("BitmapFactory cannot be null"); - } - return BitmapFactory.CreateBitmap(isPopup, DpiScaleFactor); - } - /// /// Starts the dragging. /// @@ -726,52 +699,46 @@ namespace CefSharp.Wpf /// /// 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. bitmapInfo.IsPopup indicates whether the element is the view - /// or the popup widget. BitmapInfo.DirtyRect 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. - /// The underlying buffer is copied into the back buffer and is accessible via BackBufferHandle /// - /// information about the bitmap to be rendered - void IRenderWebBrowser.OnPaint(BitmapInfo bitmapInfo) + /// 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) { - OnPaint(bitmapInfo); + OnPaint(type == PaintElementType.Popup, dirtyRect, buffer, width, height); } /// - /// 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. bitmapInfo.IsPopup indicates whether the element is the view - /// or the popup widget. BitmapInfo.DirtyRect 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. - /// The underlying buffer is copied into the back buffer and is accessible via BackBufferHandle + /// Called when an element should be painted. Pixel values passed to this method are scaled relative to view coordinates based on the + /// value of returned from . To override the default behaviour + /// override this method or implement your own and assign to + /// Called on the CEF UI Thread /// - /// information about the bitmap to be rendered - protected virtual void OnPaint(BitmapInfo bitmapInfo) + /// 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 + protected virtual void OnPaint(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height) { - UiThreadRunAsync(delegate + var paint = Paint; + if (paint != null) { - lock (bitmapInfo.BitmapLock) + var args = new PaintEventArgs(isPopup, dirtyRect, buffer, width, height); + + paint(this, args); + + if(args.Handled) { - var wpfBitmapInfo = (WpfBitmapInfo)bitmapInfo; - // Inform parents that the browser rendering is updating - OnRendering(this, wpfBitmapInfo); - - // Now update the WPF image - if (wpfBitmapInfo.CreateNewBitmap) - { - var img = bitmapInfo.IsPopup ? popupImage : image; - - img.Source = null; - GC.Collect(1); - - img.Source = wpfBitmapInfo.CreateBitmap(); - } - - wpfBitmapInfo.Invalidate(); + return; } - }, - DispatcherPriority.Render); + } + + var img = isPopup ? popupImage : image; + + BitmapFactory.CreateOrUpdateBitmap(isPopup, buffer, dirtyRect, width, height, img); } /// @@ -1571,6 +1538,22 @@ namespace CefSharp.Wpf browser.GetHost().NotifyScreenInfoChanged(); } + //Ignore this for custom bitmap factories + if (BitmapFactory.GetType() == typeof(WritableBitmapFactory) || BitmapFactory.GetType() == typeof(InteropBitmap)) + { + if (DpiScaleFactor > 1.0 && BitmapFactory.GetType() != typeof(WritableBitmapFactory)) + { + const int DefaultDpi = 96; + var scale = DefaultDpi * DpiScaleFactor; + + BitmapFactory = new WritableBitmapFactory(scale, scale); + } + else if (DpiScaleFactor == 1.0 && BitmapFactory.GetType() != typeof(InteropBitmapFactory)) + { + BitmapFactory = new InteropBitmapFactory(); + } + } + var window = source.RootVisual as Window; if(window != null) { @@ -2297,20 +2280,6 @@ namespace CefSharp.Wpf managedCefBrowserAdapter.RegisterAsyncJsObject(name, objectToBind, options); } - /// - /// Raises Rendering event - /// - /// The sender. - /// The bitmap information. - protected virtual void OnRendering(object sender, WpfBitmapInfo bitmapInfo) - { - var rendering = Rendering; - if (rendering != null) - { - rendering(sender, new RenderingEventArgs(bitmapInfo)); - } - } - /// /// Returns the current IBrowser Instance /// diff --git a/CefSharp.Wpf/IBitmapFactory.cs b/CefSharp.Wpf/IBitmapFactory.cs new file mode 100644 index 000000000..1cc4bae14 --- /dev/null +++ b/CefSharp.Wpf/IBitmapFactory.cs @@ -0,0 +1,19 @@ +// Copyright © 2010-2017 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.Windows.Controls; + +namespace CefSharp.Wpf +{ + /// + /// Factory class used to generate a BitmapInfo object for OSR rendering (WPF and OffScreen projects) + /// Implement this interface if you wish to render the underlying Bitmap to a custom type + /// e.g. a GDI Bitmap in the WPF Control + /// + public interface IBitmapFactory : IDisposable + { + void CreateOrUpdateBitmap(bool isPopup, IntPtr buffer, Rect dirtyRect, int width, int height, Image image); + } +} \ No newline at end of file diff --git a/CefSharp.Wpf/PaintEventArgs.cs b/CefSharp.Wpf/PaintEventArgs.cs new file mode 100644 index 000000000..790f7120e --- /dev/null +++ b/CefSharp.Wpf/PaintEventArgs.cs @@ -0,0 +1,58 @@ +// Copyright © 2010-2017 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; + +namespace CefSharp.Wpf +{ + /// + /// Event arguments for the Paint event handler. + /// + /// + public class PaintEventArgs : EventArgs + { + /// + /// Is the OnPaint call for a Popup or the Main View + /// + public bool IsPopup { get; private set; } + + /// + /// contains the set of rectangles in pixel coordinates that need to be repainted + /// + public Rect DirtyRect { get; private set; } + + /// + /// Buffer + /// + public IntPtr Buffer { get; private set; } + + /// + /// Width + /// + public int Width { get; private set; } + + /// + /// Height + /// + public int Height { get; private set; } + + /// + /// Gets or sets a value indicating whether the event is handled. + /// + public bool Handled { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The bitmap information. + public PaintEventArgs(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height) + { + IsPopup = isPopup; + DirtyRect = dirtyRect; + Buffer = buffer; + Width = width; + Height = height; + } + } +} diff --git a/CefSharp.Wpf/Rendering/BitmapFactory.cs b/CefSharp.Wpf/Rendering/BitmapFactory.cs deleted file mode 100644 index 342eb8bfd..000000000 --- a/CefSharp.Wpf/Rendering/BitmapFactory.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2010-2017 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 CefSharp.Internals; - -namespace CefSharp.Wpf.Rendering -{ - /// - /// BitmapFactory. - /// - /// - public class BitmapFactory : IBitmapFactory - { - /// - /// The default dpi - /// - public const int DefaultDpi = 96; - - /// - /// Create an instance of BitmapInfo based on the params - /// - /// create bitmap info for a popup (typically just a bool flag used internally) - /// DPI scale - /// newly created BitmapInfo - public BitmapInfo CreateBitmap(bool isPopup, double dpiScale) - { - if (dpiScale > 1.0) - { - return new WritableBitmapInfo(DefaultDpi * dpiScale, DefaultDpi * dpiScale) - { - IsPopup = isPopup - }; - } - - return new InteropBitmapInfo { IsPopup = isPopup }; - } - } -} diff --git a/CefSharp.Wpf/Rendering/InteropBitmapFactory.cs b/CefSharp.Wpf/Rendering/InteropBitmapFactory.cs new file mode 100644 index 000000000..164b3f298 --- /dev/null +++ b/CefSharp.Wpf/Rendering/InteropBitmapFactory.cs @@ -0,0 +1,143 @@ +// Copyright © 2010-2017 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.IO.MemoryMappedFiles; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; +using System.Runtime.InteropServices; +using System.Windows.Threading; + +namespace CefSharp.Wpf.Rendering +{ + /// + /// InteropBitmapFactory - creates/updates an InteropBitmap + /// Uses a MemoryMappedFile for double buffering when the size matches + /// or creates a new InteropBitmap when required + /// + /// + public class InteropBitmapFactory : IBitmapFactory + { + [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] + private static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); + + /// + /// The pixel format + /// + private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; + private static int BytesPerPixel = PixelFormat.BitsPerPixel / 8; + + private object lockObject = new object(); + + private Size viewSize; + private Size popupSize; + + private MemoryMappedFile viewMemoryMappedFile; + private MemoryMappedFile popupMemoryMappedFile; + private MemoryMappedViewAccessor viewMemoryMappedViewAccessor; + private MemoryMappedViewAccessor popupMemoryMappedViewAccessor; + + public void Dispose() + { + ReleaseMemoryMappedView(ref popupMemoryMappedFile, ref popupMemoryMappedViewAccessor); + ReleaseMemoryMappedView(ref viewMemoryMappedFile, ref viewMemoryMappedViewAccessor); + } + + void IBitmapFactory.CreateOrUpdateBitmap(bool isPopup, IntPtr buffer, Rect dirtyRect, int width, int height, Image image) + { + if (isPopup) + { + CreateOrUpdateBitmap(isPopup, buffer, dirtyRect, width, height, image, ref popupSize, ref popupMemoryMappedFile, ref popupMemoryMappedViewAccessor); + } + else + { + CreateOrUpdateBitmap(isPopup, buffer, dirtyRect, width, height, image, ref viewSize, ref viewMemoryMappedFile, ref viewMemoryMappedViewAccessor); + } + } + + private void CreateOrUpdateBitmap(bool isPopup, IntPtr buffer, Rect dirtyRect, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor) + { + if (image.Dispatcher.HasShutdownStarted) + { + return; + } + + var createNewBitmap = false; + + lock (lockObject) + { + int pixels = width * height; + int numberOfBytes = pixels * BytesPerPixel; + + createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width; + + if (createNewBitmap) + { + //If the MemoryMappedFile is smaller than we need then create a larger one + //If it's larger then we need then rather than going through the costly expense of + //allocating a new one we'll just use the old one and only access the number of bytes we require. + if (viewAccessor == null || viewAccessor.Capacity < numberOfBytes) + { + ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor); + + mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); + + viewAccessor = mappedFile.CreateViewAccessor(); + } + + currentSize.Height = height; + currentSize.Width = width; + } + + //TODO: Performance analysis to determine which is the fastest memory copy function + //NativeMethodWrapper.CopyMemoryUsingHandle(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes); + CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes); + } + + image.Dispatcher.BeginInvoke((Action)(() => + { + lock (lockObject) + { + if (createNewBitmap) + { + if (image.Source != null) + { + image.Source = null; + GC.Collect(1); + } + + var backBufferHandle = isPopup ? popupMemoryMappedFile.SafeMemoryMappedFileHandle : viewMemoryMappedFile.SafeMemoryMappedFileHandle; + + var stride = width * BytesPerPixel; + var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBufferHandle.DangerousGetHandle(), width, height, PixelFormat, stride, 0); + image.Source = bitmap; + } + else + { + var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); + var bitmap = (InteropBitmap)image.Source; + bitmap.Invalidate(sourceRect); + } + } + }), DispatcherPriority.Render); + } + + private void ReleaseMemoryMappedView(ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor stream) + { + if (stream != null) + { + stream.Dispose(); + stream = null; + } + + if (mappedFile != null) + { + mappedFile.Dispose(); + mappedFile = null; + } + } + } +} diff --git a/CefSharp.Wpf/Rendering/InteropBitmapInfo.cs b/CefSharp.Wpf/Rendering/InteropBitmapInfo.cs deleted file mode 100644 index 165fb0f8a..000000000 --- a/CefSharp.Wpf/Rendering/InteropBitmapInfo.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright © 2010-2017 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.Windows; -using System.Windows.Interop; -using System.Windows.Media; -using System.Windows.Media.Imaging; - -namespace CefSharp.Wpf.Rendering -{ - /// - /// InteropBitmapInfo. - /// - /// - public class InteropBitmapInfo : WpfBitmapInfo - { - /// - /// The pixel format - /// - private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; - - /// - /// Gets the bitmap. - /// - /// The bitmap. - public InteropBitmap Bitmap { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - public InteropBitmapInfo() - { - BytesPerPixel = PixelFormat.BitsPerPixel / 8; - DirtyRectSupport = true; - } - - /// - /// Gets a value indicating whether [create new bitmap]. - /// - /// true if [create new bitmap]; otherwise, false. - public override bool CreateNewBitmap - { - get { return Bitmap == null; } - } - - /// - /// Clears the bitmap. - /// - public override void ClearBitmap() - { - Bitmap = null; - } - - /// - /// Invalidates this instance. - /// - public override void Invalidate() - { - if (Bitmap != null) - { - var sourceRect = new Int32Rect(DirtyRect.X, DirtyRect.Y, DirtyRect.Width, DirtyRect.Height); - Bitmap.Invalidate(sourceRect); - } - } - - /// - /// Creates the bitmap. - /// - /// BitmapSource. - public override BitmapSource CreateBitmap() - { - // Unable to create bitmap without valid File Handle (Most likely control is being disposed) - if (FileMappingHandle == IntPtr.Zero) - { - return null; - } - - var stride = Width * BytesPerPixel; - - Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0); - - return Bitmap; - } - } -} diff --git a/CefSharp.Wpf/Rendering/WpfBitmapInfo.cs b/CefSharp.Wpf/Rendering/WpfBitmapInfo.cs deleted file mode 100644 index 0fc7b750b..000000000 --- a/CefSharp.Wpf/Rendering/WpfBitmapInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright © 2010-2017 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.Windows.Media.Imaging; -using CefSharp.Internals; - -namespace CefSharp.Wpf.Rendering -{ - /// - /// WpfBitmapInfo. - /// - /// - public abstract class WpfBitmapInfo : BitmapInfo - { - /// - /// Invalidates this instance. - /// - public abstract void Invalidate(); - /// - /// Creates the bitmap. - /// - /// BitmapSource. - public abstract BitmapSource CreateBitmap(); - } -} diff --git a/CefSharp.Wpf/Rendering/WritableBitmapFactory.cs b/CefSharp.Wpf/Rendering/WritableBitmapFactory.cs new file mode 100644 index 000000000..ce023209d --- /dev/null +++ b/CefSharp.Wpf/Rendering/WritableBitmapFactory.cs @@ -0,0 +1,152 @@ +// Copyright © 2010-2017 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.IO.MemoryMappedFiles; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; + +namespace CefSharp.Wpf.Rendering +{ + /// + /// BitmapFactory. + /// + /// + public class WritableBitmapFactory : IBitmapFactory + { + /// + /// The pixel format + /// + private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; + private static int BytesPerPixel = PixelFormat.BitsPerPixel / 8; + + private object lockObject = new object(); + + private Size viewSize; + private Size popupSize; + + private MemoryMappedFile viewMemoryMappedFile; + private MemoryMappedFile popupMemoryMappedFile; + private MemoryMappedViewAccessor viewMemoryMappedViewAccessor; + private MemoryMappedViewAccessor popupMemoryMappedViewAccessor; + + /// + /// Gets the dpi x. + /// + /// The dpi x. + public double DpiX { get; private set; } + /// + /// Gets the dpi y. + /// + /// The dpi y. + public double DpiY { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The dpi x. + /// The dpi y. + public WritableBitmapFactory(double dpiX, double dpiY) + { + DpiX = dpiX; + DpiY = dpiY; + } + + public void Dispose() + { + ReleaseMemoryMappedView(ref popupMemoryMappedFile, ref popupMemoryMappedViewAccessor); + ReleaseMemoryMappedView(ref viewMemoryMappedFile, ref viewMemoryMappedViewAccessor); + } + + void IBitmapFactory.CreateOrUpdateBitmap(bool isPopup, IntPtr buffer, Rect dirtyRect, int width, int height, Image image) + { + if (isPopup) + { + CreateOrUpdateBitmap(isPopup, buffer, dirtyRect, width, height, image, ref popupSize, ref popupMemoryMappedFile, ref popupMemoryMappedViewAccessor); + } + else + { + CreateOrUpdateBitmap(isPopup, buffer, dirtyRect, width, height, image, ref viewSize, ref viewMemoryMappedFile, ref viewMemoryMappedViewAccessor); + } + } + + private void CreateOrUpdateBitmap(bool isPopup, IntPtr buffer, Rect dirtyRect, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor) + { + bool createNewBitmap = false; + + if (image.Dispatcher.HasShutdownStarted) + { + return; + } + + lock (lockObject) + { + + int pixels = width * height; + int numberOfBytes = pixels * BytesPerPixel; + + createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width; + + if (createNewBitmap) + { + ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor); + + mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); + + viewAccessor = mappedFile.CreateViewAccessor(); + + currentSize.Height = height; + currentSize.Width = width; + } + + NativeMethodWrapper.CopyMemoryUsingHandle(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes); + } + + image.Dispatcher.BeginInvoke((Action)(() => + { + lock (lockObject) + { + if (createNewBitmap) + { + if (image.Source != null) + { + image.Source = null; + GC.Collect(1); + } + + image.Source = new WriteableBitmap(width, height, DpiX, DpiY, PixelFormat, null); + } + + var backBufferHandle = isPopup ? popupMemoryMappedFile.SafeMemoryMappedFileHandle : viewMemoryMappedFile.SafeMemoryMappedFileHandle; + + var stride = width * BytesPerPixel; + var noOfBytes = stride * height; + + // Update the dirty region + var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); + var bitmap = (WriteableBitmap)image.Source; + bitmap.WritePixels(sourceRect, backBufferHandle.DangerousGetHandle(), noOfBytes, stride, dirtyRect.X, dirtyRect.Y); + } + }), DispatcherPriority.Render); + } + + private void ReleaseMemoryMappedView(ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor stream) + { + if (stream != null) + { + stream.Dispose(); + stream = null; + } + + if (mappedFile != null) + { + mappedFile.Dispose(); + mappedFile = null; + } + } + } +} diff --git a/CefSharp.Wpf/Rendering/WritableBitmapInfo.cs b/CefSharp.Wpf/Rendering/WritableBitmapInfo.cs deleted file mode 100644 index 5c24c5c35..000000000 --- a/CefSharp.Wpf/Rendering/WritableBitmapInfo.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright © 2010-2017 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.Windows; -using System.Windows.Media; -using System.Windows.Media.Imaging; - -namespace CefSharp.Wpf.Rendering -{ - /// - /// Uses WriteableBitmap to create a bitmap from the backbuffer - /// - /// - public class WritableBitmapInfo : WpfBitmapInfo - { - /// - /// The pixel format - /// - private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; - - /// - /// Gets the bitmap. - /// - /// The bitmap. - public WriteableBitmap Bitmap { get; private set; } - /// - /// Gets the dpi x. - /// - /// The dpi x. - public double DpiX { get; private set; } - /// - /// Gets the dpi y. - /// - /// The dpi y. - public double DpiY { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - public WritableBitmapInfo() - : this(BitmapFactory.DefaultDpi, BitmapFactory.DefaultDpi) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The dpi x. - /// The dpi y. - public WritableBitmapInfo(double dpiX, double dpiY) - { - DpiX = dpiX; - DpiY = dpiY; - - BytesPerPixel = PixelFormat.BitsPerPixel / 8; - DirtyRectSupport = true; - } - - /// - /// Gets a value indicating whether [create new bitmap]. - /// - /// true if [create new bitmap]; otherwise, false. - public override bool CreateNewBitmap - { - get { return Bitmap == null; } - } - - /// - /// Clears the bitmap. - /// - public override void ClearBitmap() - { - Bitmap = null; - } - - /// - /// Invalidates this instance. - /// - public override void Invalidate() - { - if (BackBufferHandle == IntPtr.Zero || Width == 0 || Height == 0 || DirtyRect.Width == 0 || DirtyRect.Height == 0) - { - return; - } - - var stride = Width * BytesPerPixel; - var sourceBufferSize = stride * Height; - - // Update the dirty region - var sourceRect = new Int32Rect(DirtyRect.X, DirtyRect.Y, DirtyRect.Width, DirtyRect.Height); - Bitmap.WritePixels(sourceRect, BackBufferHandle, sourceBufferSize, stride, DirtyRect.X, DirtyRect.Y); - } - - /// - /// Creates the bitmap. - /// - /// BitmapSource. - public override BitmapSource CreateBitmap() - { - Bitmap = new WriteableBitmap(Width, Height, DpiX, DpiY, PixelFormat, null); - - return Bitmap; - } - } -} diff --git a/CefSharp.Wpf/RenderingEventArgs.cs b/CefSharp.Wpf/RenderingEventArgs.cs deleted file mode 100644 index 1e3c5818f..000000000 --- a/CefSharp.Wpf/RenderingEventArgs.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright © 2010-2017 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 CefSharp.Wpf.Rendering; - -namespace CefSharp.Wpf -{ - /// - /// Event arguments to the Rendering event handler set up in IWebBrowser. - /// - /// - public class RenderingEventArgs : EventArgs - { - /// - /// Initializes a new instance of the class. - /// - /// The bitmap information. - public RenderingEventArgs(WpfBitmapInfo bitmapInfo) - { - BitmapInfo = bitmapInfo; - } - - /// - /// The bitmap info being rendered. - /// - /// The bitmap information. - public WpfBitmapInfo BitmapInfo { get; private set; } - } -} diff --git a/CefSharp/CefSharp.csproj b/CefSharp/CefSharp.csproj index a7896f873..f6ee912fb 100644 --- a/CefSharp/CefSharp.csproj +++ b/CefSharp/CefSharp.csproj @@ -237,7 +237,6 @@ - @@ -259,7 +258,6 @@ - diff --git a/CefSharp/IBitmapFactory.cs b/CefSharp/IBitmapFactory.cs deleted file mode 100644 index 227c6776c..000000000 --- a/CefSharp/IBitmapFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright © 2010-2017 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 CefSharp.Internals; - -namespace CefSharp -{ - /// - /// Factory class used to generate a BitmapInfo object for OSR rendering (WPF and OffScreen projects) - /// Implement this interface if you wish to render the underlying Bitmap to a custom type - /// e.g. a GDI Bitmap in the WPF Control - /// - public interface IBitmapFactory - { - /// - /// Create an instance of BitmapInfo based on the params - /// - /// create bitmap info for a popup (typically just a bool flag used internally) - /// DPI scale - /// newly created BitmapInfo - BitmapInfo CreateBitmap(bool isPopup, double dpiScale); - } -} diff --git a/CefSharp/Internals/BitmapInfo.cs b/CefSharp/Internals/BitmapInfo.cs deleted file mode 100644 index b92bc2ef2..000000000 --- a/CefSharp/Internals/BitmapInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2010-2017 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; - -namespace CefSharp.Internals -{ - /// - /// Information about the bitmap that should be rendered - /// - public abstract class BitmapInfo - { - public object BitmapLock; - public IntPtr BackBufferHandle; - - public bool IsPopup { get; set; } - public int Width { get; set; } - public int Height { get; set; } - - public IntPtr FileMappingHandle { get; set; } - - public int BytesPerPixel { get; protected set; } - public bool DirtyRectSupport { get; protected set; } - public int NumberOfBytes { get; set; } - - public abstract bool CreateNewBitmap { get; } - public abstract void ClearBitmap(); - - public Rect DirtyRect { get; set; } - - protected BitmapInfo() - { - BitmapLock = new object(); - } - } -} diff --git a/CefSharp/Internals/IRenderWebBrowser.cs b/CefSharp/Internals/IRenderWebBrowser.cs index 6ea01f6c3..5b24c905a 100644 --- a/CefSharp/Internals/IRenderWebBrowser.cs +++ b/CefSharp/Internals/IRenderWebBrowser.cs @@ -20,18 +20,17 @@ namespace CefSharp.Internals /// Return true if the screen coordinates were provided. bool GetScreenPoint(int viewX, int viewY, out int screenX, out int screenY); - BitmapInfo CreateBitmapInfo(bool isPopup); - /// - /// 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. bitmapInfo.IsPopup indicates whether the element is the view - /// or the popup widget. BitmapInfo.DirtyRect 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. - /// The underlying buffer is copied into the back buffer and is accessible via BackBufferHandle + /// Called when an element should be painted. Pixel values passed to this method are scaled relative to view coordinates based on the + /// value of returned from . + /// Called on the CEF UI Thread /// - /// information about the bitmap to be rendered - void OnPaint(BitmapInfo bitmapInfo); + /// 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 OnPaint(PaintElementType type, Rect dirtyRect, IntPtr buffer, int width, int height); void SetCursor(IntPtr cursor, CursorType type);