diff --git a/CefSharp.OffScreen.Example/Program.cs b/CefSharp.OffScreen.Example/Program.cs index 534bb6e95..c67b321b0 100644 --- a/CefSharp.OffScreen.Example/Program.cs +++ b/CefSharp.OffScreen.Example/Program.cs @@ -4,9 +4,9 @@ using System; using System.Diagnostics; -using System.Drawing; using System.IO; using System.Threading.Tasks; +using CefSharp.DevTools.Page; namespace CefSharp.OffScreen.Example { @@ -14,6 +14,8 @@ namespace CefSharp.OffScreen.Example { private const string TestUrlOne = "https://www.google.com/"; private const string TestUrlTwo = "https://github.com/"; + private const string TestUrlThree = "https://www.google.com/doodles"; + private const string TestUrlFour = "https://microsoft.com/"; public static int Main(string[] args) { @@ -22,7 +24,7 @@ namespace CefSharp.OffScreen.Example Console.WriteLine(); //Console app doesn't have a message loop which we need as Cef.Initialize/Cef.Shutdown must be called on the same - //thread. We use a super simple implementation from + //thread. We use a super simple SynchronizationContext implementation from //https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/ //Continuations will happen on the main thread //The Nito.AsyncEx.Context Nuget package has a more advanced implementation @@ -39,14 +41,16 @@ namespace CefSharp.OffScreen.Example return; } - var t1 = MainAsync(TestUrlOne, "cache\\path1", 1.0); + var t1 = MainAsync(TestUrlOne, TestUrlTwo, "cache\\path1", 1.0); //Demo showing Zoom Level of 2.0 //Using seperate request contexts allows the urls from the same domain to have independent zoom levels //otherwise they would be the same - default behaviour of Chromium - var t2 = MainAsync(TestUrlTwo, "cache\\path2", 2.0); + var t2 = MainAsync(TestUrlThree, TestUrlFour, "cache\\path2", 2.0); await Task.WhenAll(t1, t2); + Console.WriteLine("Image viewer launched. Press any key to exit."); + // Wait for user input Console.ReadKey(); @@ -64,7 +68,7 @@ namespace CefSharp.OffScreen.Example return 0; } - private static async Task MainAsync(string url, string cachePath, double zoomLevel) + private static async Task MainAsync(string url, string secondUrl, string cachePath, double zoomLevel) { var browserSettings = new BrowserSettings { @@ -125,54 +129,74 @@ namespace CefSharp.OffScreen.Example ////Give the browser a little time to finish drawing our SendKeyEvent input //await Task.Delay(100); + var contentSize = await browser.GetContentSizeAsync(); + + var viewport = new Viewport + { + Height = contentSize.Height, + Width = contentSize.Width, + Scale = 1.0 + }; + // Wait for the screenshot to be taken, // if one exists ignore it, wait for a new one to make sure we have the most up to date - var bitmap = await browser.ScreenshotAsync(true); + var bitmap = await browser.CaptureScreenshotAsync(viewport:viewport); - DisplayBitmap(bitmap); + // Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png) + var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png"); - //await browser.LoadUrlAsync("http://github.com"); + Console.WriteLine(); + Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath); + + File.WriteAllBytes(screenshotPath, bitmap); + + Console.WriteLine("Screenshot saved. Launching your default image viewer..."); + + // Tell Windows to launch the saved image. + Process.Start(new ProcessStartInfo(screenshotPath) + { + // UseShellExecute is false by default on .NET Core. + UseShellExecute = true + }); + + await browser.LoadUrlAsync(secondUrl); // Gets a warpper around the CefBrowserHost instance // You can perform a lot of low level browser operations using this interface - //var cefbrowserHost = browser.GetBrowserHost(); + var cefbrowserHost = browser.GetBrowserHost(); //You can call Invalidate to redraw/refresh the image - //cefbrowserHost.Invalidate(PaintElementType.View); + cefbrowserHost.Invalidate(PaintElementType.View); - // Wait for the screenshot to be taken. - //bitmap = await browser.ScreenshotAsync(true); + contentSize = await browser.GetContentSizeAsync(); - //DisplayBitmap(bitmap); + viewport = new Viewport + { + Height = contentSize.Height, + Width = contentSize.Width, + Scale = 1.0 + }; + + // Wait for the screenshot to be taken, + // if one exists ignore it, wait for a new one to make sure we have the most up to date + bitmap = await browser.CaptureScreenshotAsync(viewport: viewport); + + screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png"); + + Console.WriteLine(); + Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath); + + File.WriteAllBytes(screenshotPath, bitmap); + + Console.WriteLine("Screenshot saved. Launching your default image viewer..."); + + // Tell Windows to launch the saved image. + Process.Start(new ProcessStartInfo(screenshotPath) + { + // UseShellExecute is false by default on .NET Core. + UseShellExecute = true + }); } } - - private static void DisplayBitmap(Bitmap bitmap) - { - // Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png) - var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot" + DateTime.Now.Ticks + ".png"); - - Console.WriteLine(); - Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath); - - // Save the Bitmap to the path. - // The image type is auto-detected via the ".png" extension. - bitmap.Save(screenshotPath); - - // We no longer need the Bitmap. - // Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications. - bitmap.Dispose(); - - Console.WriteLine("Screenshot saved. Launching your default image viewer..."); - - // Tell Windows to launch the saved image. - Process.Start(new ProcessStartInfo(screenshotPath) - { - // UseShellExecute is false by default on .NET Core. - UseShellExecute = true - }); - - Console.WriteLine("Image viewer launched. Press any key to exit."); - } } } diff --git a/CefSharp.OffScreen/ChromiumWebBrowser.cs b/CefSharp.OffScreen/ChromiumWebBrowser.cs index 801b428d7..f50a5f1a5 100644 --- a/CefSharp.OffScreen/ChromiumWebBrowser.cs +++ b/CefSharp.OffScreen/ChromiumWebBrowser.cs @@ -7,6 +7,7 @@ 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; @@ -45,6 +46,7 @@ namespace CefSharp.OffScreen /// 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. @@ -402,6 +404,23 @@ namespace CefSharp.OffScreen } } + /// + /// 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. @@ -467,8 +486,11 @@ namespace CefSharp.OffScreen /// 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); @@ -505,6 +527,99 @@ namespace CefSharp.OffScreen 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 to match the width/height. + /// 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) + { + await ResizeAsync((int)viewport.Width, (int)viewport.Height, (float)viewport.Scale).ConfigureAwait(continueOnCapturedContext:false); + } + + //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. + var response = await devToolsClient.Page.CaptureScreenshotAsync(format, quality, 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) + { + return Task.FromResult(true); + } + + var tcs = new TaskCompletionSource(); + EventHandler handler = null; + + handler = (s, e) => + { + if (e.Width == width && e.Height == height) + { + 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) + { + DeviceScaleFactor = deviceScaleFactor.Value; + } + Size = new Size(width, height); + + return tcs.Task; + } + + /// + /// Size of scrollable area in CSS pixels + /// + /// A task that can be awaited to get the size of the scrollable area in CSS pixels. + public async Task GetContentSizeAsync() + { + ThrowExceptionIfDisposed(); + ThrowExceptionIfBrowserNotInitialized(); + + using (var devToolsClient = browser.GetDevToolsClient()) + { + //Get the content size + var layoutMetricsResponse = await devToolsClient.Page.GetLayoutMetricsAsync().ConfigureAwait(continueOnCapturedContext:false); + + return layoutMetricsResponse.CssContentSize; + } + } + /// public void Load(string url) { diff --git a/CefSharp.OffScreen/DefaultRenderHandler.cs b/CefSharp.OffScreen/DefaultRenderHandler.cs index e595904c6..0de95d32a 100644 --- a/CefSharp.OffScreen/DefaultRenderHandler.cs +++ b/CefSharp.OffScreen/DefaultRenderHandler.cs @@ -98,7 +98,7 @@ namespace CefSharp.OffScreen /// Return null if no screenInfo structure is provided. public virtual ScreenInfo? GetScreenInfo() { - var screenInfo = new ScreenInfo { DeviceScaleFactor = 1.0F }; + var screenInfo = new ScreenInfo { DeviceScaleFactor = browser.DeviceScaleFactor }; return screenInfo; }