diff --git a/Build.bat b/Build.bat new file mode 100644 index 000000000..b1edbcf23 --- /dev/null +++ b/Build.bat @@ -0,0 +1,3 @@ +SET ThisScriptsDirectory=%~dp0 +SET PowerShellScriptPath=%ThisScriptsDirectory%Build.ps1 +PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}"; \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 95dcba95d..0eefda7fa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ Thanks for your interest in contributing to the project! Please follow these sim `CefSharp` simply takes the building blocks provided by `Cef` and attempts to provide a usable '.Net' implementation. The upstream [`CEF` forum](http://magpcss.org/ceforum/) is a valuable resource, if your issues seems fairly low level, then please conduct some research before posting. -It maybe helpful to run the `cefclient` application and compare output with `CefSharp`. The `WinForms` and `WPF` versions use two different rendering modes, `WPF` uses Offscreen Rendering (`OSR`). +It maybe helpful to run the `cefclient` application and compare output with `CefSharp`. The `WinForms` and `WPF` versions use two different rendering modes, `WPF` uses Offscreen Rendering (`OSR`). `OffScreen` also uses `OSR` mode. - Download **Test App** from http://cefbuilds.com - To compare with WPF run `cefclient --multi-threaded-message-loop --off-screen-rendering-enabled` @@ -44,6 +44,7 @@ Your bug report should **always follow this template**: - **What is the expected output? What do you see instead?** - **What steps will reproduce the problem?** +- **Are you using `WinForms`, `WPF` or `OffScreen`?** - **What version of the product are you using? On what operating system? x86 or x64?** - What version are you using? Nuget? CI Nuget? build from a branch? If so which branch? - Win7, Win 8, etc? @@ -84,4 +85,4 @@ Pull requests are **awesome**. If you're looking to raise a PR for something whi - Max number of columns are 132, please format your code accordingly - Please don't add #Regions to the code - When adding new files, please prepend the standard license disclaimer (just copy and paste from another source file) -- Do your best to follow these guidelines but don't be afraid to make mistakes when trying to apply them. We are all novices in the beginning. \ No newline at end of file +- Do your best to follow these guidelines but don't be afraid to make mistakes when trying to apply them. We are all novices in the beginning. diff --git a/CefSharp.BrowserSubprocess.Core/CefSharp.BrowserSubprocess.Core.vcxproj b/CefSharp.BrowserSubprocess.Core/CefSharp.BrowserSubprocess.Core.vcxproj index d8142b3f9..e5c528b23 100644 --- a/CefSharp.BrowserSubprocess.Core/CefSharp.BrowserSubprocess.Core.vcxproj +++ b/CefSharp.BrowserSubprocess.Core/CefSharp.BrowserSubprocess.Core.vcxproj @@ -1,6 +1,6 @@  - + Debug @@ -66,7 +66,7 @@ - 03744085 + 4664bbc5 true @@ -198,6 +198,6 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - + \ No newline at end of file diff --git a/CefSharp.BrowserSubprocess.Core/packages.config b/CefSharp.BrowserSubprocess.Core/packages.config index faf0feb53..337c7a6c1 100644 --- a/CefSharp.BrowserSubprocess.Core/packages.config +++ b/CefSharp.BrowserSubprocess.Core/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/CefSharp.Core/BrowserSettings.h b/CefSharp.Core/BrowserSettings.h index dc9964d9c..9b9060e77 100644 --- a/CefSharp.Core/BrowserSettings.h +++ b/CefSharp.Core/BrowserSettings.h @@ -71,13 +71,15 @@ namespace CefSharp public ref class BrowserSettings { + private: + bool _isFinalized; internal: CefBrowserSettings* _browserSettings; public: - BrowserSettings() : _browserSettings(new CefBrowserSettings()) { } - !BrowserSettings() { delete _browserSettings; } - ~BrowserSettings() { delete _browserSettings; } + BrowserSettings() : _browserSettings(new CefBrowserSettings()), _isFinalized(false) { } + !BrowserSettings() { delete _browserSettings; _isFinalized = true; } + ~BrowserSettings() { if (!_isFinalized) this->!BrowserSettings(); } // CefBrowserSettings is private causing whole field to be private // exposing void* as a workaround diff --git a/CefSharp.Core/Cef.h b/CefSharp.Core/Cef.h index c8f2c6bda..d5ff05a07 100644 --- a/CefSharp.Core/Cef.h +++ b/CefSharp.Core/Cef.h @@ -7,6 +7,7 @@ #include #include #include +#include #include "Internals/CefSharpApp.h" #include "Internals/CookieVisitor.h" @@ -168,6 +169,94 @@ namespace CefSharp return success; } + /// Add an entry to the cross-origin whitelist. + /// The origin allowed to be accessed by the target protocol/domain. + /// The target protocol allowed to access the source origin. + /// The optional target domain allowed to access the source origin. + /// If set to true would allow a blah.example.com if the + /// URL (like http://www.example.com) will be allowed access to + /// all resources hosted on the specified and . + /// If is non-empty and if false only + /// exact domain matches will be allowed. If contains a top- + /// level domain component (like "example.com") and is + /// true sub-domain matches will be allowed. If is empty and + /// "/> if true all domains and IP addresses will be + /// allowed. + // + /// This method cannot be used to bypass the restrictions on local or display + /// isolated schemes. See the comments on for more + /// information. + /// + /// This function may be called on any thread. Returns false if + /// is invalid or the whitelist cannot be accessed. + /// + static bool AddCrossOriginWhitelistEntry( + String^ sourceOrigin, + String^ targetProtocol, + String^ targetDomain, + bool allowTargetSubdomains) + { + return CefAddCrossOriginWhitelistEntry( + StringUtils::ToNative(sourceOrigin), + StringUtils::ToNative(targetProtocol), + StringUtils::ToNative(targetDomain), + allowTargetSubdomains); + } + + /// Remove entry from cross-origin whitelist + /// The origin allowed to be accessed by the target protocol/domain. + /// The target protocol allowed to access the source origin. + /// The optional target domain allowed to access the source origin. + /// If set to true would allow a blah.example.com if the + /// is invalid or the whitelist cannot be accessed. + /// + static bool RemoveCrossOriginWhitelistEntry(String^ sourceOrigin, + String^ targetProtocol, + String^ targetDomain, + bool allowTargetSubdomains) + + { + return CefRemoveCrossOriginWhitelistEntry( + StringUtils::ToNative(sourceOrigin), + StringUtils::ToNative(targetProtocol), + StringUtils::ToNative(targetDomain), + allowTargetSubdomains); + } + + /// Remove all entries from the cross-origin access whitelist. + /// + /// Remove all entries from the cross-origin access whitelist. Returns false if + /// the whitelist cannot be accessed. + /// + static bool ClearCrossOriginWhitelist() + { + return CefClearCrossOriginWhitelist(); + } + /// Visits all cookies using the provided Cookie Visitor. The returned cookies are sorted by longest path, then by earliest creation date. /// A user-provided Cookie Visitor implementation. /// Returns false if the CookieManager is not available; otherwise, true. @@ -258,9 +347,9 @@ namespace CefSharp /// characters (e.g. the ';' character is disallowed within the cookie value attribute) and will return false without setting /// the cookie if such characters are found. /// The cookie URL + /// The cookie domain. /// The cookie name. /// The cookie value. - /// The cookie domain. /// The DateTime when the cookie will be treated as expired. /// false if the cookie cannot be set (e.g. if illegal charecters such as ';' are used); otherwise true. static bool SetCookie(String^ url, String^ domain, String^ name, String^ value, DateTime expires) @@ -348,5 +437,14 @@ namespace CefSharp IsInitialized = false; } } + + /// + /// Clear all registered scheme handler factories. + /// + /// Returns false on error. + static bool ClearSchemeHandlerFactories() + { + return CefClearSchemeHandlerFactories(); + } }; } diff --git a/CefSharp.Core/CefSharp.Core.vcxproj b/CefSharp.Core/CefSharp.Core.vcxproj index eb86525a6..6f10b405c 100644 --- a/CefSharp.Core/CefSharp.Core.vcxproj +++ b/CefSharp.Core/CefSharp.Core.vcxproj @@ -1,6 +1,6 @@  - + Debug @@ -66,7 +66,7 @@ <_ProjectFileVersion>11.0.51106.1 - 6edfce21 + 84bd8e6a bin\$(Configuration)\ @@ -225,6 +225,7 @@ + @@ -257,6 +258,7 @@ + @@ -283,6 +285,6 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - + \ No newline at end of file diff --git a/CefSharp.Core/CefSharp.Core.vcxproj.filters b/CefSharp.Core/CefSharp.Core.vcxproj.filters index 89770fcb7..65c5e8ad7 100644 --- a/CefSharp.Core/CefSharp.Core.vcxproj.filters +++ b/CefSharp.Core/CefSharp.Core.vcxproj.filters @@ -53,6 +53,9 @@ Source Files + + Source Files + @@ -133,6 +136,9 @@ Header Files + + Header Files + diff --git a/CefSharp.Core/Internals/CefDragDataWrapper.h b/CefSharp.Core/Internals/CefDragDataWrapper.h index 4a4f6d402..b94730e4e 100644 --- a/CefSharp.Core/Internals/CefDragDataWrapper.h +++ b/CefSharp.Core/Internals/CefDragDataWrapper.h @@ -41,6 +41,24 @@ namespace CefSharp virtual property bool IsFragment; virtual property bool IsLink; + /// + // Create a new CefDragData object. + /// + /*--cef()--*/ + static CefDragDataWrapper^ Create() + { + CefRefPtr cefDragData = CefDragData::Create(); + return gcnew CefDragDataWrapper(cefDragData); + } + + virtual property CefRefPtr* InternalDragData + { + CefRefPtr* get() + { + return new CefRefPtr(_wrappedDragData.get()); + } + } + //TODO: Vector is a pointer, so can potentially be updated (items may be possibly removed) virtual property IList^ FileNames { diff --git a/CefSharp.Core/Internals/CefSharpApp.h b/CefSharp.Core/Internals/CefSharpApp.h index bd675a223..1237a1941 100644 --- a/CefSharp.Core/Internals/CefSharpApp.h +++ b/CefSharp.Core/Internals/CefSharpApp.h @@ -7,6 +7,7 @@ #include "include/cef_app.h" #include "CefSettings.h" #include "SchemeHandlerWrapper.h" +#include "SchemeHandlerFactoryWrapper.h" namespace CefSharp { @@ -56,7 +57,7 @@ namespace CefSharp // when the process is shutting down. // TOOD: Consider adding error handling here. But where do we report any errors that may have occurred? - registrar->AddCustomScheme(StringUtils::ToNative(cefCustomScheme->SchemeName), cefCustomScheme->IsStandard, false, false); + registrar->AddCustomScheme(StringUtils::ToNative(cefCustomScheme->SchemeName), cefCustomScheme->IsStandard, cefCustomScheme->IsLocal, cefCustomScheme->IsDisplayIsolated); } }; diff --git a/CefSharp.Core/Internals/ClientAdapter.cpp b/CefSharp.Core/Internals/ClientAdapter.cpp index 860ca3683..5c3df65cd 100644 --- a/CefSharp.Core/Internals/ClientAdapter.cpp +++ b/CefSharp.Core/Internals/ClientAdapter.cpp @@ -569,5 +569,32 @@ namespace CefSharp return handler->OnDragEnter(_browserControl, dragDataWrapper, (CefSharp::DragOperationsMask)mask); } + + bool ClientAdapter::OnRequestGeolocationPermission(CefRefPtr browser, const CefString& requesting_url, int request_id, CefRefPtr callback) + { + IGeolocationHandler^ handler = _browserControl->GeolocationHandler; + if (handler == nullptr) + { + // Default deny, as CEF does. + return false; + } + + if (handler->OnRequestGeolocationPermission(_browserControl, StringUtils::ToClr(requesting_url), request_id)) + { + callback->Continue(true); + return true; + } + + return false; + } + + void ClientAdapter::OnCancelGeolocationPermission(CefRefPtr browser, const CefString& requesting_url, int request_id) + { + IGeolocationHandler^ handler = _browserControl->GeolocationHandler; + if (handler != nullptr) + { + handler->OnCancelGeolocationPermission(_browserControl, StringUtils::ToClr(requesting_url), request_id); + } + } } } diff --git a/CefSharp.Core/Internals/ClientAdapter.h b/CefSharp.Core/Internals/ClientAdapter.h index d4356a238..25d022180 100644 --- a/CefSharp.Core/Internals/ClientAdapter.h +++ b/CefSharp.Core/Internals/ClientAdapter.h @@ -15,8 +15,6 @@ using namespace System; namespace CefSharp { - ref class ManagedCefBrowserAdapter; - namespace Internals { private class ClientAdapter : public CefClient, @@ -29,7 +27,8 @@ namespace CefSharp public CefKeyboardHandler, public CefJSDialogHandler, public CefDialogHandler, - public CefDragHandler + public CefDragHandler, + public CefGeolocationHandler { private: CriticalSection _syncRoot; @@ -75,6 +74,7 @@ namespace CefSharp virtual CefRefPtr GetJSDialogHandler() OVERRIDE{ return this; } virtual CefRefPtr GetDialogHandler() OVERRIDE{ return this; } virtual CefRefPtr GetDragHandler() OVERRIDE{ return this; } + virtual CefRefPtr GetGeolocationHandler() OVERRIDE{ return this; } // CefLifeSpanHandler virtual DECL bool OnBeforePopup(CefRefPtr browser, CefRefPtr frame, @@ -136,6 +136,11 @@ namespace CefSharp //CefDragHandler virtual DECL bool OnDragEnter(CefRefPtr browser, CefRefPtr dragData, DragOperationsMask mask) OVERRIDE; + //CefGeolocationHandler + virtual DECL bool OnRequestGeolocationPermission(CefRefPtr browser, const CefString& requesting_url, int request_id, + CefRefPtr callback) OVERRIDE; + virtual DECL void OnCancelGeolocationPermission(CefRefPtr browser, const CefString& requesting_url, int request_id) OVERRIDE; + IMPLEMENT_REFCOUNTING(ClientAdapter); }; } diff --git a/CefSharp.Core/Internals/RenderClientAdapter.h b/CefSharp.Core/Internals/RenderClientAdapter.h index 79ed98c4e..a031b8b97 100644 --- a/CefSharp.Core/Internals/RenderClientAdapter.h +++ b/CefSharp.Core/Internals/RenderClientAdapter.h @@ -39,12 +39,12 @@ namespace CefSharp _renderWebBrowser = nullptr; _webBrowserInternal = nullptr; - DisposeBitmapInfo(_mainBitmapInfo); + ReleaseBitmapHandlers(_mainBitmapInfo); delete _mainBitmapInfo; _mainBitmapInfo = nullptr; - DisposeBitmapInfo(_popupBitmapInfo); + ReleaseBitmapHandlers(_popupBitmapInfo); delete _popupBitmapInfo; _popupBitmapInfo = nullptr; @@ -92,14 +92,54 @@ namespace CefSharp lock l(bitmapInfo->BitmapLock); - auto fileMappingHandle = (HANDLE)bitmapInfo->FileMappingHandle; + if(bitmapInfo->DirtyRectSupport) + { + //NOTE: According to https://bitbucket.org/chromiumembedded/branches-2171-cef3/commits/ce984ddff3268a50cf9967487327e1257015b98c + // 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 = CefDirtyRect(r.x, r.y, r.width, r.height); + } + auto backBufferHandle = (HANDLE)bitmapInfo->BackBufferHandle; - SetBufferHelper(bitmapInfo, width, height, &fileMappingHandle, - &backBufferHandle, buffer); + if (backBufferHandle == NULL || bitmapInfo->Width != width || bitmapInfo->Height != height) + { + int pixels = width * height; + int numberOfBytes = pixels * bitmapInfo->BytesPerPixel; + auto fileMappingHandle = (HANDLE)bitmapInfo->FileMappingHandle; - bitmapInfo->FileMappingHandle = (IntPtr)fileMappingHandle; - bitmapInfo->BackBufferHandle = (IntPtr)backBufferHandle; + //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->InvokeRenderAsync(bitmapInfo); }; @@ -111,67 +151,24 @@ namespace CefSharp }; private: - void SetBufferHelper(BitmapInfo^ bitmapInfo, int newWidth, int newHeight, - HANDLE* fileMappingHandle, HANDLE* backBufferHandle, const void* buffer) - { - int pixels = newWidth * newHeight; - int numberOfBytes = pixels * bitmapInfo->BytesPerPixel; - - if (*backBufferHandle == NULL || - bitmapInfo->Width != newWidth || - bitmapInfo->Height != newHeight) - { - //Clear the reference to Bitmap so a new one is created by InvokeRenderAsync - bitmapInfo->ClearBitmap(); - - //Release the current handles (if not null) - ReleaseBitmapHandlers(backBufferHandle, fileMappingHandle); - - // 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->Width = newWidth; - bitmapInfo->Height = newHeight; - - CopyMemory(*backBufferHandle, (void*)buffer, numberOfBytes); - }; - - void ReleaseBitmapHandlers(HANDLE* backBufferHandle, HANDLE* fileMappingHandle) - { - if (*backBufferHandle != NULL) - { - UnmapViewOfFile(*backBufferHandle); - *backBufferHandle = NULL; - } - - if (*fileMappingHandle != NULL) - { - CloseHandle(*fileMappingHandle); - *fileMappingHandle = NULL; - } - } - - void DisposeBitmapInfo(BitmapInfo^ bitmapInfo) + void ReleaseBitmapHandlers(BitmapInfo^ bitmapInfo) { auto backBufferHandle = (HANDLE)bitmapInfo->BackBufferHandle; auto fileMappingHandle = (HANDLE)bitmapInfo->FileMappingHandle; - ReleaseBitmapHandlers(&backBufferHandle, &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/Internals/StreamAdapter.cpp b/CefSharp.Core/Internals/StreamAdapter.cpp index 291d40e7e..9791afe1f 100644 --- a/CefSharp.Core/Internals/StreamAdapter.cpp +++ b/CefSharp.Core/Internals/StreamAdapter.cpp @@ -11,7 +11,7 @@ namespace CefSharp { StreamAdapter::~StreamAdapter() { - _stream->Close(); + //Remove the reference to the stream, must be kept open as it might be reused for subsiquent requests (e.g. refresh). _stream = nullptr; } diff --git a/CefSharp.Core/Internals/StreamAdapter.h b/CefSharp.Core/Internals/StreamAdapter.h index 9d8d73454..5b1162ac9 100644 --- a/CefSharp.Core/Internals/StreamAdapter.h +++ b/CefSharp.Core/Internals/StreamAdapter.h @@ -20,7 +20,11 @@ namespace CefSharp public: virtual ~StreamAdapter(); - StreamAdapter(Stream^ stream) : _stream(stream) { } + StreamAdapter(Stream^ stream) : _stream(stream) + { + //Reset stream position + stream->Position = 0; + } virtual size_t Read(void* ptr, size_t size, size_t n); virtual int Seek(int64 offset, int whence); diff --git a/CefSharp.Core/ManagedCefBrowserAdapter.h b/CefSharp.Core/ManagedCefBrowserAdapter.h index 83ad0bf7b..60d124a77 100644 --- a/CefSharp.Core/ManagedCefBrowserAdapter.h +++ b/CefSharp.Core/ManagedCefBrowserAdapter.h @@ -9,6 +9,7 @@ #include "MouseButtonType.h" #include "PaintElementType.h" #include "Internals/ClientAdapter.h" +#include "Internals/CefDragDataWrapper.h" #include "Internals/RenderClientAdapter.h" #include "Internals/MCefRefPtr.h" #include "Internals/StringVisitor.h" @@ -34,7 +35,9 @@ namespace CefSharp Close(true); _clientAdapter = nullptr; - if (_browserProcessServiceHost != nullptr) + + // Guard managed only member derefs by isDisposing: + if (isDisposing && _browserProcessServiceHost != nullptr) { _browserProcessServiceHost->Close(); _browserProcessServiceHost = nullptr; @@ -669,5 +672,55 @@ namespace CefSharp browser->GetHost()->AddWordToDictionary(wordNative); } } + + CefMouseEvent GetCefMouseEvent(MouseEvent^ mouseEvent) + { + CefMouseEvent cefMouseEvent; + cefMouseEvent.x = mouseEvent->X; + cefMouseEvent.y = mouseEvent->Y; + cefMouseEvent.modifiers = (uint32)mouseEvent->Modifiers; + return cefMouseEvent; + } + + void OnDragTargetDragEnter(CefDragDataWrapper^ dragData, MouseEvent^ mouseEvent, DragOperationsMask allowedOperations) + { + auto browser = _clientAdapter->GetCefBrowser(); + + if (browser != nullptr) + { + dragData->ResetFileContents(); // Recommended by documentation to reset before calling DragEnter + browser->GetHost()->DragTargetDragEnter(*dragData->InternalDragData, GetCefMouseEvent(mouseEvent), (CefBrowserHost::DragOperationsMask) allowedOperations); + } + } + + void OnDragTargetDragOver(MouseEvent^ mouseEvent, DragOperationsMask allowedOperations) + { + auto browser = _clientAdapter->GetCefBrowser(); + + if (browser != nullptr) + { + browser->GetHost()->DragTargetDragOver(GetCefMouseEvent(mouseEvent), (CefBrowserHost::DragOperationsMask) allowedOperations); + } + } + + void OnDragTargetDragLeave() + { + auto browser = _clientAdapter->GetCefBrowser(); + + if (browser != nullptr) + { + browser->GetHost()->DragTargetDragLeave(); + } + } + + void OnDragTargetDragDrop(MouseEvent^ mouseEvent) + { + auto browser = _clientAdapter->GetCefBrowser(); + + if (browser != nullptr) + { + browser->GetHost()->DragTargetDrop(GetCefMouseEvent(mouseEvent)); + } + } }; } diff --git a/CefSharp.Core/SchemeHandlerFactoryWrapper.cpp b/CefSharp.Core/SchemeHandlerFactoryWrapper.cpp new file mode 100644 index 000000000..33685451f --- /dev/null +++ b/CefSharp.Core/SchemeHandlerFactoryWrapper.cpp @@ -0,0 +1,23 @@ +// Copyright © 2010-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. + +#include "Stdafx.h" +#include "SchemeHandlerFactoryWrapper.h" + +using namespace System::Runtime::InteropServices; +using namespace System::IO; + +namespace CefSharp +{ + CefRefPtr SchemeHandlerFactoryWrapper::Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) + { + ISchemeHandler^ handler = _factory->Create(); + CefRefPtr wrapper = new SchemeHandlerWrapper(handler); + return static_cast>(wrapper); + } +} \ No newline at end of file diff --git a/CefSharp.Core/SchemeHandlerFactoryWrapper.h b/CefSharp.Core/SchemeHandlerFactoryWrapper.h new file mode 100644 index 000000000..90823f2e1 --- /dev/null +++ b/CefSharp.Core/SchemeHandlerFactoryWrapper.h @@ -0,0 +1,29 @@ +// Copyright © 2010-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. + +#pragma once + +#include "Stdafx.h" +#include "include/cef_scheme.h" +#include "Internals/AutoLock.h" + +using namespace System; +using namespace System::IO; +using namespace System::Collections::Specialized; + +namespace CefSharp +{ + class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory + { + gcroot _factory; + + public: + SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) + : _factory(factory) {} + + virtual CefRefPtr Create(CefRefPtr browser, CefRefPtr frame, const CefString& scheme_name, CefRefPtr request); + + IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); + }; +} \ No newline at end of file diff --git a/CefSharp.Core/SchemeHandlerWrapper.cpp b/CefSharp.Core/SchemeHandlerWrapper.cpp index 43619b1bd..7adab6a07 100644 --- a/CefSharp.Core/SchemeHandlerWrapper.cpp +++ b/CefSharp.Core/SchemeHandlerWrapper.cpp @@ -142,15 +142,4 @@ namespace CefSharp } return -1; } - - CefRefPtr SchemeHandlerFactoryWrapper::Create( - CefRefPtr browser, - CefRefPtr frame, - const CefString& scheme_name, - CefRefPtr request) - { - ISchemeHandler^ handler = _factory->Create(); - CefRefPtr wrapper = new SchemeHandlerWrapper(handler); - return static_cast>(wrapper); - } } \ No newline at end of file diff --git a/CefSharp.Core/SchemeHandlerWrapper.h b/CefSharp.Core/SchemeHandlerWrapper.h index e84a48b4b..ac00b8545 100644 --- a/CefSharp.Core/SchemeHandlerWrapper.h +++ b/CefSharp.Core/SchemeHandlerWrapper.h @@ -49,17 +49,4 @@ namespace CefSharp IMPLEMENT_REFCOUNTING(SchemeHandlerWrapper); }; - - class SchemeHandlerFactoryWrapper : public CefSchemeHandlerFactory - { - gcroot _factory; - - public: - SchemeHandlerFactoryWrapper(ISchemeHandlerFactory^ factory) - : _factory(factory) {} - - virtual CefRefPtr Create(CefRefPtr browser, CefRefPtr frame, const CefString& scheme_name, CefRefPtr request); - - IMPLEMENT_REFCOUNTING(SchemeHandlerFactoryWrapper); - }; } \ No newline at end of file diff --git a/CefSharp.Core/packages.config b/CefSharp.Core/packages.config index faf0feb53..337c7a6c1 100644 --- a/CefSharp.Core/packages.config +++ b/CefSharp.Core/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/CefSharp.Example/CefExample.cs b/CefSharp.Example/CefExample.cs index 26dd99280..103aecea1 100644 --- a/CefSharp.Example/CefExample.cs +++ b/CefSharp.Example/CefExample.cs @@ -15,12 +15,28 @@ namespace CefSharp.Example public static void Init() { + // Set Google API keys, used for Geolocation requests sans GPS. See http://www.chromium.org/developers/how-tos/api-keys + // Environment.SetEnvironmentVariable("GOOGLE_API_KEY", ""); + // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_ID", ""); + // Environment.SetEnvironmentVariable("GOOGLE_DEFAULT_CLIENT_SECRET", ""); + + //Chromium Command Line args + //http://peter.sh/experiments/chromium-command-line-switches/ + //NOTE: Note all relevant in relation to `CefSharp`, use for reference purposes only. + var settings = new CefSettings(); settings.RemoteDebuggingPort = 8088; //settings.CefCommandLineArgs.Add("renderer-process-limit", "1"); //settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog"); //settings.CefCommandLineArgs.Add("disable-gpu", "1"); //settings.CefCommandLineArgs.Add("disable-gpu-vsync", "1"); + //settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //Enable WebRTC + //settings.CefCommandLineArgs.Add("no-proxy-server", "1"); //Don't use a proxy server, always make direct connections. Overrides any other proxy server flags that are passed. + + //Disables the DirectWrite font rendering system on windows. + //Possibly useful when experiencing blury fonts. + //settings.CefCommandLineArgs.Add("disable-direct-write", "1"); + settings.LogSeverity = LogSeverity.Verbose; if (DebuggingSubProcess) diff --git a/CefSharp.Example/Resources/TooltipTest.html b/CefSharp.Example/Resources/TooltipTest.html index 6de4139d7..0295225b4 100644 --- a/CefSharp.Example/Resources/TooltipTest.html +++ b/CefSharp.Example/Resources/TooltipTest.html @@ -14,6 +14,11 @@ + \ No newline at end of file diff --git a/CefSharp.OffScreen.Example/CefSharp.OffScreen.Example.csproj b/CefSharp.OffScreen.Example/CefSharp.OffScreen.Example.csproj index da7299ff2..17738e3da 100644 --- a/CefSharp.OffScreen.Example/CefSharp.OffScreen.Example.csproj +++ b/CefSharp.OffScreen.Example/CefSharp.OffScreen.Example.csproj @@ -13,7 +13,7 @@ 512 - 320b0b24 + 793b99d4 true @@ -94,9 +94,9 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + - - + + \ No newline at end of file diff --git a/CefSharp.OffScreen.Example/Program.cs b/CefSharp.OffScreen.Example/Program.cs index ae6fd9531..95ed2425e 100644 --- a/CefSharp.OffScreen.Example/Program.cs +++ b/CefSharp.OffScreen.Example/Program.cs @@ -29,22 +29,24 @@ namespace CefSharp.OffScreen.Example CefExample.Init(); // Create the offscreen Chromium browser. - browser = new ChromiumWebBrowser(testUrl); - - // An event that is fired when the first page is finished loading. - // This returns to us from another thread. - if (captureFirstRenderedImage) + using (browser = new ChromiumWebBrowser(testUrl)) { - browser.ResourceHandler.RegisterHandler(testUrl, ResourceHandler.FromString("

CefSharp OffScreen

")); - browser.ScreenshotAsync().ContinueWith(DisplayBitmap); - } - else - { - browser.FrameLoadEnd += BrowserFrameLoadEnd; - } - // We have to wait for something, otherwise the process will exit too soon. - Console.ReadKey(); + // An event that is fired when the first page is finished loading. + // This returns to us from another thread. + if (captureFirstRenderedImage) + { + browser.ResourceHandler.RegisterHandler(testUrl, ResourceHandler.FromString("

CefSharp OffScreen

")); + browser.ScreenshotAsync().ContinueWith(DisplayBitmap); + } + else + { + browser.FrameLoadEnd += BrowserFrameLoadEnd; + } + + // We have to wait for something, otherwise the process will exit too soon. + Console.ReadKey(); + } // Clean up Chromium objects. You need to call this in your application otherwise // you will get a crash when closing. diff --git a/CefSharp.OffScreen.Example/packages.config b/CefSharp.OffScreen.Example/packages.config index 86e5afd80..468defc7a 100644 --- a/CefSharp.OffScreen.Example/packages.config +++ b/CefSharp.OffScreen.Example/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/CefSharp.OffScreen/ChromiumWebBrowser.cs b/CefSharp.OffScreen/ChromiumWebBrowser.cs index b047d4125..50b7a3000 100644 --- a/CefSharp.OffScreen/ChromiumWebBrowser.cs +++ b/CefSharp.OffScreen/ChromiumWebBrowser.cs @@ -44,34 +44,74 @@ namespace CefSharp.OffScreen /// The browser settings to use. If null, the default settings are used. public ChromiumWebBrowser(string address, BrowserSettings browserSettings = null) { + if (!Cef.IsInitialized && !Cef.Initialize()) + { + throw new InvalidOperationException("Cef::Initialize() failed"); + } + ResourceHandler = new DefaultResourceHandler(); Cef.AddDisposable(this); + Address = address; managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, true); managedCefBrowserAdapter.CreateOffscreenBrowser(IntPtr.Zero, browserSettings ?? new BrowserSettings(), address); } + ~ChromiumWebBrowser() + { + Dispose(false); + } + public void Dispose() { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + // Don't reference handlers any longer: ResourceHandler = null; + JsDialogHandler = null; + DialogHandler = null; + DownloadHandler = null; + KeyboardHandler = null; + LifeSpanHandler = null; + MenuHandler = null; + FocusHandler = null; + RequestHandler = null; + DragHandler = null; + GeolocationHandler = null; + + // Don't reference event listeners any longer: + LoadError = null; + FrameLoadStart = null; + FrameLoadEnd = null; + ConsoleMessage = null; + BrowserInitialized = null; + StatusMessage = null; + NavStateChanged = null; Cef.RemoveDisposable(this); - if (bitmap != null) + if (disposing) { - bitmap.Dispose(); - bitmap = null; - } + if (bitmap != null) + { + bitmap.Dispose(); + bitmap = null; + } - if (managedCefBrowserAdapter != null) - { - if (!managedCefBrowserAdapter.IsDisposed) - managedCefBrowserAdapter.Dispose(); - managedCefBrowserAdapter = null; + if (managedCefBrowserAdapter != null) + { + if (!managedCefBrowserAdapter.IsDisposed) + { + managedCefBrowserAdapter.Dispose(); + } + managedCefBrowserAdapter = null; + } } - - GC.SuppressFinalize(this); } /// @@ -168,6 +208,7 @@ namespace CefSharp.OffScreen public IRequestHandler RequestHandler { get; set; } public IDragHandler DragHandler { get; set; } public IResourceHandler ResourceHandler { get; set; } + public IGeolocationHandler GeolocationHandler { get; set; } public event EventHandler LoadError; public event EventHandler FrameLoadStart; @@ -197,7 +238,7 @@ namespace CefSharp.OffScreen managedCefBrowserAdapter.AddWordToDictionary(word); } - public string Address { get; set; } + public string Address { get; private set; } public bool CanGoBack { get; private set; } @@ -343,7 +384,7 @@ namespace CefSharp.OffScreen public BitmapInfo CreateBitmapInfo(bool isPopup) { //The bitmap buffer is 32 BPP - return new GdiBitmapInfo { IsPopup = isPopup, BytesPerPixel = 4, BitmapLock = bitmapLock }; + return new GdiBitmapInfo { IsPopup = isPopup, BitmapLock = bitmapLock }; } void IRenderWebBrowser.InvokeRenderAsync(BitmapInfo bitmapInfo) diff --git a/CefSharp.OffScreen/GdiBitmapInfo.cs b/CefSharp.OffScreen/GdiBitmapInfo.cs index a6d49e7f7..dadb1b73a 100644 --- a/CefSharp.OffScreen/GdiBitmapInfo.cs +++ b/CefSharp.OffScreen/GdiBitmapInfo.cs @@ -8,7 +8,17 @@ namespace CefSharp.OffScreen { public class GdiBitmapInfo : BitmapInfo { - public bool IsCleared { get; set; } + public bool IsCleared { get; private set; } + + public GdiBitmapInfo() + { + BytesPerPixel = 4; + } + + public override bool CreateNewBitmap + { + get { return IsCleared; } + } public override void ClearBitmap() { diff --git a/CefSharp.Test/CefSharp.Test.csproj b/CefSharp.Test/CefSharp.Test.csproj index deffb5acb..7475b999d 100644 --- a/CefSharp.Test/CefSharp.Test.csproj +++ b/CefSharp.Test/CefSharp.Test.csproj @@ -19,7 +19,7 @@ 3.5 Client - 85aa022d + 578e8d6c true @@ -142,9 +142,9 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + - - + + \ No newline at end of file diff --git a/CefSharp.Test/packages.config b/CefSharp.Test/packages.config index 664576fbb..e4bd01f61 100644 --- a/CefSharp.Test/packages.config +++ b/CefSharp.Test/packages.config @@ -2,8 +2,8 @@ - - + + \ No newline at end of file diff --git a/CefSharp.WinForms.Example/BrowserTabUserControl.cs b/CefSharp.WinForms.Example/BrowserTabUserControl.cs index 88e8638aa..968fa8005 100644 --- a/CefSharp.WinForms.Example/BrowserTabUserControl.cs +++ b/CefSharp.WinForms.Example/BrowserTabUserControl.cs @@ -1,8 +1,7 @@ -using System.Threading.Tasks; -using CefSharp.Example; -using CefSharp.WinForms.Example.Controls; +using CefSharp.Example; using System; using System.Windows.Forms; +using CefSharp.WinForms.Internals; namespace CefSharp.WinForms.Example { @@ -26,6 +25,8 @@ namespace CefSharp.WinForms.Example browser.MenuHandler = new MenuHandler(); browser.RequestHandler = new RequestHandler(); browser.JsDialogHandler = new JsDialogHandler(); + browser.GeolocationHandler = new GeolocationHandler(); + browser.DownloadHandler = new DownloadHandler(); //browser.FocusHandler = new FocusHandler(browser, urlTextBox); browser.NavStateChanged += OnBrowserNavStateChanged; browser.ConsoleMessage += OnBrowserConsoleMessage; @@ -41,24 +42,6 @@ namespace CefSharp.WinForms.Example var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion); DisplayOutput(version); - - Disposed += BrowserTabUserControlDisposed; - } - - private void BrowserTabUserControlDisposed(object sender, EventArgs e) - { - var browser = (ChromiumWebBrowser)Browser; - Disposed -= BrowserTabUserControlDisposed; - - browser.NavStateChanged -= OnBrowserNavStateChanged; - browser.ConsoleMessage -= OnBrowserConsoleMessage; - browser.TitleChanged -= OnBrowserTitleChanged; - browser.AddressChanged -= OnBrowserAddressChanged; - browser.StatusMessage -= OnBrowserStatusMessage; - browser.IsBrowserInitializedChanged -= OnIsBrowserInitializedChanged; - browser.IsLoadingChanged -= OnIsLoadingChanged; - - browser.Dispose(); } private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args) diff --git a/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj b/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj index 25d83d5a3..0d4172d5e 100644 --- a/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj +++ b/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj @@ -21,7 +21,7 @@ 3.5 Client - e79ac826 + 386a1560 x64 @@ -70,7 +70,6 @@ BrowserForm.cs - UserControl @@ -78,6 +77,7 @@ BrowserTabUserControl.cs + Form @@ -85,6 +85,12 @@ SimpleBrowserForm.cs + + Form + + + TabulationDemoForm.cs + @@ -110,6 +116,9 @@ SimpleBrowserForm.cs + + TabulationDemoForm.cs + ResXFileCodeGenerator Resources.Designer.cs @@ -159,9 +168,9 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + - - + + \ No newline at end of file diff --git a/CefSharp.WinForms.Example/Controls/ControlExtensions.cs b/CefSharp.WinForms.Example/Controls/ControlExtensions.cs deleted file mode 100644 index f0bde242a..000000000 --- a/CefSharp.WinForms.Example/Controls/ControlExtensions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2010-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.Windows.Forms; - -namespace CefSharp.WinForms.Example.Controls -{ - public static class ControlExtensions - { - /// - /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread. - /// - /// the control for which the update is required - /// action to be performed on the control - public static void InvokeOnUiThreadIfRequired(this Control control, Action action) - { - if (control.InvokeRequired) - { - control.BeginInvoke(action); - } - else - { - action.Invoke(); - } - } - } -} diff --git a/CefSharp.WinForms.Example/GeolocationHandler.cs b/CefSharp.WinForms.Example/GeolocationHandler.cs new file mode 100644 index 000000000..4fd1382a4 --- /dev/null +++ b/CefSharp.WinForms.Example/GeolocationHandler.cs @@ -0,0 +1,22 @@ +// Copyright © 2010-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.Windows.Forms; + +namespace CefSharp.WinForms.Example +{ + internal class GeolocationHandler : IGeolocationHandler + { + public bool OnRequestGeolocationPermission(IWebBrowser browser, string requestingUrl, int requestId) + { + var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButtons.YesNo); + return result == DialogResult.Yes; + } + + public void OnCancelGeolocationPermission(IWebBrowser browser, string requestingUrl, int requestId) + { + } + } +} diff --git a/CefSharp.WinForms.Example/Minimal/SimpleBrowserForm.cs b/CefSharp.WinForms.Example/Minimal/SimpleBrowserForm.cs index 22125e216..2ad7a9b25 100644 --- a/CefSharp.WinForms.Example/Minimal/SimpleBrowserForm.cs +++ b/CefSharp.WinForms.Example/Minimal/SimpleBrowserForm.cs @@ -5,7 +5,7 @@ using System; using System.Windows.Forms; using CefSharp.Example; -using CefSharp.WinForms.Example.Controls; +using CefSharp.WinForms.Internals; namespace CefSharp.WinForms.Example.Minimal { diff --git a/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.Designer.cs b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.Designer.cs new file mode 100644 index 000000000..e5897925c --- /dev/null +++ b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.Designer.cs @@ -0,0 +1,105 @@ +namespace CefSharp.WinForms.Example.Minimal +{ + partial class TabulationDemoForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.txtURL = new System.Windows.Forms.TextBox(); + this.btnGO = new System.Windows.Forms.Button(); + this.grpBrowser = new System.Windows.Forms.GroupBox(); + this.txtDummy = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // txtURL + // + this.txtURL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.txtURL.Location = new System.Drawing.Point(8, 11); + this.txtURL.Name = "txtURL"; + this.txtURL.Size = new System.Drawing.Size(774, 20); + this.txtURL.TabIndex = 0; + this.txtURL.Text = "http://www.google.com"; + this.txtURL.Enter += new System.EventHandler(this.TxtUrlEnter); + this.txtURL.Leave += new System.EventHandler(this.TxtUrlLeave); + // + // btnGO + // + this.btnGO.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.btnGO.Location = new System.Drawing.Point(782, 9); + this.btnGO.Name = "btnGO"; + this.btnGO.Size = new System.Drawing.Size(33, 23); + this.btnGO.TabIndex = 1; + this.btnGO.Text = "GO"; + this.btnGO.UseVisualStyleBackColor = true; + this.btnGO.Click += new System.EventHandler(this.BtnGoClick); + // + // grpBrowser + // + this.grpBrowser.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.grpBrowser.Location = new System.Drawing.Point(8, 37); + this.grpBrowser.Name = "grpBrowser"; + this.grpBrowser.Size = new System.Drawing.Size(807, 568); + this.grpBrowser.TabIndex = 2; + this.grpBrowser.TabStop = false; + this.grpBrowser.Text = "Browser"; + // + // txtDummy + // + this.txtDummy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.txtDummy.Location = new System.Drawing.Point(8, 612); + this.txtDummy.Name = "txtDummy"; + this.txtDummy.Size = new System.Drawing.Size(807, 20); + this.txtDummy.TabIndex = 3; + this.txtDummy.Text = "Dummy Text"; + // + // TabulationDemoForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(827, 642); + this.Controls.Add(this.txtDummy); + this.Controls.Add(this.grpBrowser); + this.Controls.Add(this.btnGO); + this.Controls.Add(this.txtURL); + this.Name = "TabulationDemoForm"; + this.Text = "Tabulation Demo"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox txtURL; + private System.Windows.Forms.Button btnGO; + private System.Windows.Forms.GroupBox grpBrowser; + private System.Windows.Forms.TextBox txtDummy; + } +} \ No newline at end of file diff --git a/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.cs b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.cs new file mode 100644 index 000000000..87bc42bd9 --- /dev/null +++ b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.cs @@ -0,0 +1,39 @@ +// Copyright © 2010-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.Windows.Forms; + +namespace CefSharp.WinForms.Example.Minimal +{ + public partial class TabulationDemoForm : Form + { + private readonly ChromiumWebBrowser chromiumWebBrowser; + + public TabulationDemoForm() + { + InitializeComponent(); + chromiumWebBrowser = new ChromiumWebBrowser(txtURL.Text) { Dock = DockStyle.Fill }; + var userControl = new UserControl { Dock = DockStyle.Fill }; + userControl.Controls.Add(chromiumWebBrowser); + grpBrowser.Controls.Add(userControl); + } + + private void BtnGoClick(object sender, EventArgs e) + { + chromiumWebBrowser.Load(txtURL.Text); + } + + private void TxtUrlLeave(object sender, EventArgs e) + { + txtURL.BackColor = Color.White; + } + + private void TxtUrlEnter(object sender, EventArgs e) + { + txtURL.BackColor = Color.Yellow; + } + } +} diff --git a/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.resx b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/CefSharp.WinForms.Example/Minimal/TabulationDemoForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CefSharp.WinForms.Example/Program.cs b/CefSharp.WinForms.Example/Program.cs index 57002ad9e..1e6ea6b47 100644 --- a/CefSharp.WinForms.Example/Program.cs +++ b/CefSharp.WinForms.Example/Program.cs @@ -18,6 +18,7 @@ namespace CefSharp.WinForms.Example var browser = new BrowserForm(); //var browser = new SimpleBrowserForm(); + //var browser = new TabulationDemoForm(); Application.Run(browser); } } diff --git a/CefSharp.WinForms.Example/app.manifest b/CefSharp.WinForms.Example/app.manifest index 399e0d2eb..12bd81018 100644 --- a/CefSharp.WinForms.Example/app.manifest +++ b/CefSharp.WinForms.Example/app.manifest @@ -8,7 +8,14 @@ xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - + + + + + + + + diff --git a/CefSharp.WinForms.Example/packages.config b/CefSharp.WinForms.Example/packages.config index 86e5afd80..468defc7a 100644 --- a/CefSharp.WinForms.Example/packages.config +++ b/CefSharp.WinForms.Example/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/CefSharp.WinForms/CefSharp.WinForms.csproj b/CefSharp.WinForms/CefSharp.WinForms.csproj index 708d642ed..c17b5eee6 100644 --- a/CefSharp.WinForms/CefSharp.WinForms.csproj +++ b/CefSharp.WinForms/CefSharp.WinForms.csproj @@ -43,6 +43,7 @@ + @@ -52,6 +53,9 @@ + + + Component diff --git a/CefSharp.WinForms/ChromiumWebBrowser.cs b/CefSharp.WinForms/ChromiumWebBrowser.cs index ea2fdc618..a5115036d 100644 --- a/CefSharp.WinForms/ChromiumWebBrowser.cs +++ b/CefSharp.WinForms/ChromiumWebBrowser.cs @@ -14,6 +14,7 @@ namespace CefSharp.WinForms public class ChromiumWebBrowser : Control, IWebBrowserInternal, IWinFormsWebBrowser { private ManagedCefBrowserAdapter managedCefBrowserAdapter; + private ParentFormMessageInterceptor parentFormMessageInterceptor; public BrowserSettings BrowserSettings { get; set; } public string Title { get; set; } @@ -31,6 +32,7 @@ namespace CefSharp.WinForms public IFocusHandler FocusHandler { get; set; } public IDragHandler DragHandler { get; set; } public IResourceHandler ResourceHandler { get; set; } + public IGeolocationHandler GeolocationHandler { get; set; } public bool CanGoForward { get; private set; } public bool CanGoBack { get; private set; } @@ -55,6 +57,11 @@ namespace CefSharp.WinForms public ChromiumWebBrowser(string address) { + if (!Cef.IsInitialized && !Cef.Initialize()) + { + throw new InvalidOperationException("Cef::Initialize() failed"); + } + Cef.AddDisposable(this); Address = address; @@ -62,12 +69,23 @@ namespace CefSharp.WinForms FocusHandler = new DefaultFocusHandler(this); ResourceHandler = new DefaultResourceHandler(); + BrowserSettings = new BrowserSettings(); managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, false); } protected override void Dispose(bool disposing) { + // Don't utilize any of the handlers anymore: + DialogHandler = null; + JsDialogHandler = null; + KeyboardHandler = null; + RequestHandler = null; + DownloadHandler = null; + LifeSpanHandler = null; + MenuHandler = null; + DragHandler = null; + GeolocationHandler = null; FocusHandler = null; ResourceHandler = null; @@ -75,11 +93,37 @@ namespace CefSharp.WinForms if (disposing) { + IsBrowserInitialized = false; + + if (BrowserSettings != null) + { + BrowserSettings.Dispose(); + BrowserSettings = null; + } + + if (parentFormMessageInterceptor != null) + { + parentFormMessageInterceptor.Dispose(); + parentFormMessageInterceptor = null; + } + if (managedCefBrowserAdapter != null) { managedCefBrowserAdapter.Dispose(); managedCefBrowserAdapter = null; } + + // Don't maintain a reference to event listeners anylonger: + LoadError = null; + FrameLoadStart = null; + FrameLoadEnd = null; + NavStateChanged = null; + ConsoleMessage = null; + StatusMessage = null; + AddressChanged = null; + TitleChanged = null; + IsBrowserInitializedChanged = null; + IsLoadingChanged = null; } base.Dispose(disposing); } @@ -88,6 +132,15 @@ namespace CefSharp.WinForms { IsBrowserInitialized = true; + // By the time this callback gets called, this control + // is most likely hooked into a browser Form of some sort. + // (Which is what ParentFormMessageInterceptor relies on.) + // Ensure the ParentFormMessageInterceptor construction occurs on the WinForms UI thread: + this.InvokeOnUiThreadIfRequired(() => + { + parentFormMessageInterceptor = new ParentFormMessageInterceptor(this); + }); + ResizeBrowser(); var handler = IsBrowserInitializedChanged; @@ -159,7 +212,7 @@ namespace CefSharp.WinForms protected override void OnHandleCreated(EventArgs e) { - managedCefBrowserAdapter.CreateBrowser(BrowserSettings ?? new BrowserSettings(), Handle, Address); + managedCefBrowserAdapter.CreateBrowser(BrowserSettings, Handle, Address); base.OnHandleCreated(e); } @@ -388,14 +441,6 @@ namespace CefSharp.WinForms } } - /// - /// Set whether the browser is focused. - /// - public void SetFocus(bool isFocused) - { - managedCefBrowserAdapter.SetFocus(isFocused); - } - protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); @@ -405,7 +450,7 @@ namespace CefSharp.WinForms private void ResizeBrowser() { - if (IsBrowserInitialized && managedCefBrowserAdapter != null) + if (IsBrowserInitialized) { managedCefBrowserAdapter.Resize(Width, Height); } @@ -413,7 +458,7 @@ namespace CefSharp.WinForms public void NotifyMoveOrResizeStarted() { - if (IsBrowserInitialized && managedCefBrowserAdapter != null) + if (IsBrowserInitialized) { managedCefBrowserAdapter.NotifyMoveOrResizeStarted(); } @@ -428,5 +473,30 @@ namespace CefSharp.WinForms { managedCefBrowserAdapter.AddWordToDictionary(word); } + + protected override void OnEnter(EventArgs e) + { + SetFocus(true); + + base.OnEnter(e); + } + + protected override void OnLeave(EventArgs e) + { + SetFocus(false); + + base.OnLeave(e); + } + + /// + /// Set whether the browser is focused. + /// + public void SetFocus(bool isFocused) + { + if (IsBrowserInitialized) + { + managedCefBrowserAdapter.SetFocus(isFocused); + } + } } } diff --git a/CefSharp.WinForms/Internals/ControlExtensions.cs b/CefSharp.WinForms/Internals/ControlExtensions.cs new file mode 100644 index 000000000..0fba09a4f --- /dev/null +++ b/CefSharp.WinForms/Internals/ControlExtensions.cs @@ -0,0 +1,66 @@ +// Copyright © 2010-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.Windows.Forms; + +namespace CefSharp.WinForms.Internals +{ + public static class ControlExtensions + { + /// + /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread. + /// + /// the control for which the update is required + /// action to be performed on the control + public static void InvokeOnUiThreadIfRequired(this Control control, Action action) + { + if (control.InvokeRequired) + { + control.BeginInvoke(action); + } + else + { + action.Invoke(); + } + } + + public static void Activate(this Control control) + { + // Notify WinForms world that inner browser window got focus. This will trigger Leave event to previous focused control + var containerControl = control.GetContainerControl(); + if (containerControl != null) + { + containerControl.ActivateControl(control); + } + } + + public static void SelectNextControl(this Control control, bool next) + { + var containerControl = control.GetContainerControl(); + + while (containerControl != null) + { + var containerControlAsControl = containerControl as Control; + if (containerControlAsControl == null) + { + break; + } + + var activeControl = containerControl.ActiveControl; + if (containerControlAsControl.SelectNextControl(activeControl, next, true, true, false)) + { + break; + } + + if (containerControlAsControl.Parent == null) + { + break; + } + + containerControl = containerControlAsControl.Parent.GetContainerControl(); + } + } + } +} diff --git a/CefSharp.WinForms/Internals/DefaultFocusHandler.cs b/CefSharp.WinForms/Internals/DefaultFocusHandler.cs index c8f76d71c..0ea2b6be0 100644 --- a/CefSharp.WinForms/Internals/DefaultFocusHandler.cs +++ b/CefSharp.WinForms/Internals/DefaultFocusHandler.cs @@ -2,31 +2,32 @@ // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. -using System.Windows.Forms; - namespace CefSharp.WinForms.Internals { - internal class DefaultFocusHandler : IFocusHandler - { - private readonly ChromiumWebBrowser browser; + internal class DefaultFocusHandler : IFocusHandler + { + private readonly ChromiumWebBrowser browser; - public DefaultFocusHandler(ChromiumWebBrowser browser) - { - this.browser = browser; - } + public DefaultFocusHandler(ChromiumWebBrowser browser) + { + this.browser = browser; + } - public void OnGotFocus() - { - } + public virtual void OnGotFocus() + { + browser.InvokeOnUiThreadIfRequired(browser.Activate); + } - public bool OnSetFocus(CefFocusSource source) - { - return false; - } + public virtual bool OnSetFocus(CefFocusSource source) + { + // Do not let the browser take focus when a Load method has been called + return source == CefFocusSource.FocusSourceNavigation; + } - public void OnTakeFocus(bool next) - { - browser.BeginInvoke(new MethodInvoker(() => browser.SelectNextControl(browser, next, true, true, true))); - } - } + public virtual void OnTakeFocus(bool next) + { + // NOTE: OnTakeFocus means leaving focus / not taking focus + browser.InvokeOnUiThreadIfRequired(() => browser.SelectNextControl(next)); + } + } } diff --git a/CefSharp.WinForms/Internals/NativeMethods.cs b/CefSharp.WinForms/Internals/NativeMethods.cs new file mode 100644 index 000000000..3710be351 --- /dev/null +++ b/CefSharp.WinForms/Internals/NativeMethods.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace CefSharp.WinForms.Internals +{ + internal static class NativeMethods + { + public const int WM_MOVE = 0x3; + public const int WM_MOVING = 0x216; + } +} diff --git a/CefSharp.WinForms/Internals/ParentFormMessageInterceptor.cs b/CefSharp.WinForms/Internals/ParentFormMessageInterceptor.cs new file mode 100644 index 000000000..25bb2a3db --- /dev/null +++ b/CefSharp.WinForms/Internals/ParentFormMessageInterceptor.cs @@ -0,0 +1,212 @@ +// 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.Runtime.InteropServices; +using System.Windows.Forms; + +namespace CefSharp.WinForms.Internals +{ + internal class ParentFormMessageInterceptor : NativeWindow, IDisposable + { + /// + /// Keep track of whether a move is in progress. + /// + private bool isMoving; + + /// + /// Used to determine the coordinates involved in the move + /// + private Rectangle movingRectangle; + + private ChromiumWebBrowser Browser { get; set; } + + private Form ParentForm { get; set; } + + public ParentFormMessageInterceptor(ChromiumWebBrowser browser) + { + Browser = browser; + // Get notified if our browser window parent changes: + Browser.ParentChanged += ParentParentChanged; + // Find the browser form to subclass to monitor WM_MOVE/WM_MOVING + RefindParentForm(); + } + + /// + /// Call to force refinding of the parent Form. + /// (i.e. top level window that owns the ChromiumWebBrowserControl) + /// + public void RefindParentForm() + { + ParentParentChanged(Browser, null); + } + + /// + /// Adjust the form to listen to if the ChromiumWebBrowserControl's parent changes. + /// + /// The ChromiumWebBrowser whose parent has changed. + /// + private void ParentParentChanged(object sender, EventArgs e) + { + var control = (Control)sender; + var oldForm = ParentForm; + var newForm = control.FindForm(); + + if (oldForm == null || newForm == null || oldForm.Handle != newForm.Handle) + { + if (Handle != IntPtr.Zero) + { + ReleaseHandle(); + } + if (oldForm != null) + { + oldForm.HandleCreated -= OnHandleCreated; + oldForm.HandleDestroyed -= OnHandleDestroyed; + } + ParentForm = newForm; + if (newForm != null) + { + newForm.HandleCreated += OnHandleCreated; + newForm.HandleDestroyed += OnHandleDestroyed; + // If newForm's Handle has been created already, + // our event listener won't be called, so call it now. + if (newForm.IsHandleCreated) + { + OnHandleCreated(newForm, null); + } + } + } + } + + private void OnHandleCreated(object sender, EventArgs e) + { + AssignHandle(((Form)sender).Handle); + } + + private void OnHandleDestroyed(object sender, EventArgs e) + { + ReleaseHandle(); + } + + protected override void WndProc(ref Message m) + { + var isMovingMessage = false; + + // Negative initial values keeps the compiler quiet and to + // ensure we have actual window movement to notify CEF about. + const int invalidMoveCoordinate = -1; + var x = invalidMoveCoordinate; + var y = invalidMoveCoordinate; + + // Listen for operating system messages + switch (m.Msg) + { + case NativeMethods.WM_MOVING: + { + movingRectangle = (Rectangle)Marshal.PtrToStructure(m.LParam, typeof(Rectangle)); + x = movingRectangle.Left; + y = movingRectangle.Top; + isMovingMessage = true; + break; + } + case NativeMethods.WM_MOVE: + { + x = (m.LParam.ToInt32() & 0xffff); + y = ((m.LParam.ToInt32() >> 16) & 0xffff); + isMovingMessage = true; + break; + } + } + + // Only notify about movement if: + // * Browser Handle Created + // NOTE: This is checked for paranoia. + // This WndProc can't be called unless ParentForm has + // its handle created, but that doesn't necessarily mean + // Browser has had its handle created. + // WinForm controls don't usually get eagerly created Handles + // in their constructors. + // * ParentForm Actually moved + // * Not currently moving (on the UI thread only of course) + // * The current WindowState is Normal. + // This check is to simplify the effort here. + // Other logic already handles the maximize/minimize + // cases just fine. + // You might consider checking Browser.Visible and + // not notifying our browser control if the browser control isn't visible. + // However, if you do that, the non-Visible CEF tab will still + // have any SELECT drop downs rendering where they shouldn't. + if (isMovingMessage + && Browser.IsHandleCreated + && ParentForm.WindowState == FormWindowState.Normal + && (ParentForm.Left != x || ParentForm.Top != y) + && !isMoving) + { + // ParentForm.Left & .Right are negative when the window + // is transitioning from maximized to normal. + // If we are transitioning, the form will also receive + // a WM_SIZE which can deal with the move/size combo itself. + if (ParentForm.Left >= 0 && ParentForm.Right >= 0) + { + OnMoving(); + } + } + DefWndProc(ref m); + } + + protected virtual void OnMoving() + { + isMoving = true; + + if (Browser.IsBrowserInitialized) + { + Browser.NotifyMoveOrResizeStarted(); + } + + isMoving = false; + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (ParentForm != null) + { + ParentForm.HandleCreated -= OnHandleCreated; + ParentForm.HandleDestroyed -= OnHandleDestroyed; + ParentForm = null; + } + + // Unmanaged resource, but release here anyway. + // NativeWindow has its own finalization logic + // that should be run if this instance isn't disposed + // properly before arriving at the finalization thread. + // See: http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/NativeWindow.cs,147 + // for the gruesome details. + if (Handle != IntPtr.Zero) + { + ReleaseHandle(); + } + + if (Browser != null) + { + Browser.ParentChanged -= ParentParentChanged; + Browser = null; + } + } + } + + protected override void OnThreadException(Exception e) + { + // TODO: Do something more interesting here, logging, whatever, something. + base.OnThreadException(e); + } + } +} diff --git a/CefSharp.Wpf.Example/CefSharp.Wpf.Example.csproj b/CefSharp.Wpf.Example/CefSharp.Wpf.Example.csproj index 342c3db2e..8d7fafa6f 100644 --- a/CefSharp.Wpf.Example/CefSharp.Wpf.Example.csproj +++ b/CefSharp.Wpf.Example/CefSharp.Wpf.Example.csproj @@ -21,7 +21,7 @@ 3.5 Client - eef213f7 + 1dae910e true @@ -105,6 +105,7 @@ Designer + @@ -172,9 +173,9 @@ This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + - - + + \ No newline at end of file diff --git a/CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs b/CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs new file mode 100644 index 000000000..690f3547f --- /dev/null +++ b/CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs @@ -0,0 +1,22 @@ +// Copyright © 2010-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.Windows; + +namespace CefSharp.Wpf.Example.Handlers +{ + internal class GeolocationHandler : IGeolocationHandler + { + public bool OnRequestGeolocationPermission(IWebBrowser browser, string requestingUrl, int requestId) + { + var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo); + return result == MessageBoxResult.Yes; + } + + public void OnCancelGeolocationPermission(IWebBrowser browser, string requestingUrl, int requestId) + { + } + } +} diff --git a/CefSharp.Wpf.Example/Views/BrowserTabView.xaml b/CefSharp.Wpf.Example/Views/BrowserTabView.xaml index e98473ed0..06735aee4 100644 --- a/CefSharp.Wpf.Example/Views/BrowserTabView.xaml +++ b/CefSharp.Wpf.Example/Views/BrowserTabView.xaml @@ -175,6 +175,7 @@ Opacity="{Binding ElementName=opacitySlider, Path=Value}" Address="{Binding Address, Mode=TwoWay}" Title="{Binding Title, Mode=OneWayToSource}" + AllowDrop="True" WebBrowser="{Binding WebBrowser, Mode=OneWayToSource}"> diff --git a/CefSharp.Wpf.Example/Views/BrowserTabView.xaml.cs b/CefSharp.Wpf.Example/Views/BrowserTabView.xaml.cs index 5d13a1d09..916fcac4f 100644 --- a/CefSharp.Wpf.Example/Views/BrowserTabView.xaml.cs +++ b/CefSharp.Wpf.Example/Views/BrowserTabView.xaml.cs @@ -2,7 +2,6 @@ // // 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; using System.Windows.Input; using CefSharp.Example; @@ -19,6 +18,8 @@ namespace CefSharp.Wpf.Example.Views browser.RegisterJsObject("bound", new BoundObject()); browser.MenuHandler = new Handlers.MenuHandler(); + browser.GeolocationHandler = new Handlers.GeolocationHandler(); + browser.DownloadHandler = new DownloadHandler(); CefExample.RegisterTestResources(browser); } diff --git a/CefSharp.Wpf.Example/packages.config b/CefSharp.Wpf.Example/packages.config index 86e5afd80..468defc7a 100644 --- a/CefSharp.Wpf.Example/packages.config +++ b/CefSharp.Wpf.Example/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/CefSharp.Wpf/CefSharp.Wpf.csproj b/CefSharp.Wpf/CefSharp.Wpf.csproj index 0c7fa1711..ebc386349 100644 --- a/CefSharp.Wpf/CefSharp.Wpf.csproj +++ b/CefSharp.Wpf/CefSharp.Wpf.csproj @@ -93,7 +93,7 @@ - + Code @@ -101,7 +101,10 @@ + + + @@ -113,6 +116,7 @@ CefSharp +