// Copyright © 2010-2015 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 #include #include #include #include "Internals/CefSharpApp.h" #include "Internals/CookieManager.h" #include "Internals/PluginVisitor.h" #include "CefSettings.h" #include "SchemeHandlerFactoryWrapper.h" #include "Internals/CefTaskScheduler.h" #include "Internals/CefGetGeolocationCallbackWrapper.h" using namespace System::Collections::Generic; using namespace System::Linq; using namespace System::Reflection; namespace CefSharp { public ref class Cef sealed { private: static Object^ _sync; static bool _initialized = false; static HashSet^ _disposables; static Cef() { _sync = gcnew Object(); _disposables = gcnew HashSet(); } static void ParentProcessExitHandler(Object^ sender, EventArgs^ e) { if (Cef::IsInitialized) { Cef::Shutdown(); } } public: /// /// Called on the browser process UI thread immediately after the CEF context has been initialized. /// static property Action^ OnContextInitialized; static property TaskFactory^ UIThreadTaskFactory; static property TaskFactory^ IOThreadTaskFactory; static property TaskFactory^ FileThreadTaskFactory; static void AddDisposable(IDisposable^ item) { msclr::lock l(_sync); _disposables->Add(item); } static void RemoveDisposable(IDisposable^ item) { msclr::lock l(_sync); _disposables->Remove(item); } /// Gets a value that indicates whether CefSharp is initialized. /// true if CefSharp is initialized; otherwise, false. static property bool IsInitialized { bool get() { return _initialized; } private: void set(bool value) { _initialized = value; } } /// Gets a value that indicates the version of CefSharp currently being used. /// The CefSharp version. static property String^ CefSharpVersion { String^ get() { Assembly^ assembly = Assembly::GetAssembly(Cef::typeid); return assembly->GetName()->Version->ToString(); } } /// Gets a value that indicates the CEF version currently being used. /// The CEF Version static property String^ CefVersion { String^ get() { return String::Format("r{0}", CEF_VERSION); } } /// Gets a value that indicates the Chromium version currently being used. /// The Chromium version. static property String^ ChromiumVersion { String^ get() { // Need explicit cast here to avoid C4965 warning when the minor version is zero. return String::Format("{0}.{1}.{2}.{3}", CHROME_VERSION_MAJOR, (Object^) CHROME_VERSION_MINOR, CHROME_VERSION_BUILD, CHROME_VERSION_PATCH); } } /// /// Gets a value that indicates the Git Hash for CEF version currently being used. /// /// The Git Commit Hash static property String^ CefCommitHash { String^ get() { return CEF_COMMIT_HASH; } } /// /// Initializes CefSharp with the default settings. /// This function should be called on the main application thread to initialize the CEF browser process. /// /// true if successful; otherwise, false. static bool Initialize() { auto cefSettings = gcnew CefSettings(); return Initialize(cefSettings); } /// /// Initializes CefSharp with user-provided settings. /// This function should be called on the main application thread to initialize the CEF browser process. /// /// CefSharp configuration settings. /// true if successful; otherwise, false. static bool Initialize(CefSettings^ cefSettings) { return Initialize(cefSettings, true, false); } /// /// Initializes CefSharp with user-provided settings. /// This function should be called on the main application thread to initialize the CEF browser process. /// /// CefSharp configuration settings. /// When the Current AppDomain (relative to the thread called on) /// Exits(ProcessExit event) then Shudown will be called. /// Check that all relevant dependencies avaliable, throws exception if any are missing /// true if successful; otherwise, false. static bool Initialize(CefSettings^ cefSettings, bool shutdownOnProcessExit, bool performDependencyCheck) { if (IsInitialized) { // NOTE: Can only initialize Cef once, to make this explicitly clear throw exception on subsiquent attempts throw gcnew Exception("Cef can only be initialized once. Use Cef.IsInitialized to guard against this exception."); } if (cefSettings->BrowserSubprocessPath == nullptr) { throw gcnew Exception("CefSettings BrowserSubprocessPath cannot be null."); } if(performDependencyCheck) { DependencyChecker::AssertAllDependenciesPresent(cefSettings->Locale, cefSettings->LocalesDirPath, cefSettings->ResourcesDirPath, cefSettings->PackLoadingDisabled, cefSettings->BrowserSubprocessPath); } UIThreadTaskFactory = gcnew TaskFactory(gcnew CefTaskScheduler(TID_UI)); IOThreadTaskFactory = gcnew TaskFactory(gcnew CefTaskScheduler(TID_IO)); FileThreadTaskFactory = gcnew TaskFactory(gcnew CefTaskScheduler(TID_FILE)); CefMainArgs main_args; CefRefPtr app(new CefSharpApp(cefSettings, OnContextInitialized)); auto success = CefInitialize(main_args, *(cefSettings->_cefSettings), app.get(), NULL); //Register SchemeHandlerFactories - must be called after CefInitialize for each (CefCustomScheme^ cefCustomScheme in cefSettings->CefCustomSchemes) { auto domainName = cefCustomScheme->DomainName ? cefCustomScheme->DomainName : String::Empty; CefRefPtr wrapper = new SchemeHandlerFactoryWrapper(cefCustomScheme->SchemeHandlerFactory); CefRegisterSchemeHandlerFactory(StringUtils::ToNative(cefCustomScheme->SchemeName), StringUtils::ToNative(domainName), wrapper); } _initialized = success; if (_initialized && shutdownOnProcessExit) { AppDomain::CurrentDomain->ProcessExit += gcnew EventHandler(ParentProcessExitHandler); } return success; } /// Perform a single iteration of CEF message loop processing. This function is /// used to integrate the CEF message loop into an existing application message /// loop. Care must be taken to balance performance against excessive CPU usage. /// This function should only be called on the main application thread and only /// if CefInitialize() is called with a CefSettings.multi_threaded_message_loop /// value of false. This function will not block. static void DoMessageLoopWork() { CefDoMessageLoopWork(); } /// 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 /// was set to example.com /// /// /// The same-origin policy restricts how scripts hosted from different origins /// (scheme + domain + port) can communicate. By default, scripts can only access /// resources with the same origin. Scripts hosted on the HTTP and HTTPS schemes /// (but no other schemes) can use the "Access-Control-Allow-Origin" header to /// allow cross-origin requests. For example, https://source.example.com can make /// XMLHttpRequest requests on http://target.example.com if the /// http://target.example.com request returns an "Access-Control-Allow-Origin: /// https://source.example.com" response header. // /// Scripts in separate frames or iframes and hosted from the same protocol and /// domain suffix can execute cross-origin JavaScript if both pages set the /// document.domain value to the same domain suffix. For example, /// scheme://foo.example.com and scheme://bar.example.com can communicate using /// JavaScript if both domains set document.domain="example.com". // /// This method is used to allow access to origins that would otherwise violate /// the same-origin policy. Scripts hosted underneath the fully qualified /// 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 /// was set to example.com /// /// /// Remove an entry from the cross-origin access whitelist. Returns false if /// 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(); } /// /// Returns the global cookie manager. /// static ICookieManager^ GetGlobalCookieManager() { auto cookieManager = CefCookieManager::GetGlobalManager(NULL); return gcnew CookieManager(cookieManager); } /// /// Shuts down CefSharp and the underlying CEF infrastructure. This method is safe to call multiple times; it will only /// shut down CEF on the first call (all subsequent calls will be ignored). /// This function should be called on the main application thread to shut down the CEF browser process before the application exits. /// static void Shutdown() { if (IsInitialized) { OnContextInitialized = nullptr; msclr::lock l(_sync); UIThreadTaskFactory = nullptr; IOThreadTaskFactory = nullptr; FileThreadTaskFactory = nullptr; for each(IDisposable^ diposable in Enumerable::ToList(_disposables)) { delete diposable; } GC::Collect(); GC::WaitForPendingFinalizers(); CefShutdown(); IsInitialized = false; } } /// /// Clear all registered scheme handler factories. /// /// Returns false on error. static bool ClearSchemeHandlerFactories() { return CefClearSchemeHandlerFactories(); } /// /// Async returns a list containing Plugin Information /// (Wrapper around CefVisitWebPluginInfo) /// The Task will be cancelled and a TaskCanceledException throw /// if the Task does not complete within 2000ms /// Documentation for CefWebPluginInfoVisitor.Visit states /// `This method may never be called if no plugins are found.` /// hence the Task cancelled timeout /// /// Returns List of structs. static Task^>^ GetPlugins() { CefRefPtr visitor = new PluginVisitor(); CefVisitWebPluginInfo(visitor); return visitor->GetTask(); } /// /// Add a plugin path (directory + file). This change may not take affect until after RefreshWebPlugins() is called. /// /// Path (directory + file). static void AddWebPluginPath(String^ path) { CefAddWebPluginPath(StringUtils::ToNative(path)); } /// /// Add a plugin directory. This change may not take affect until after CefRefreshWebPlugins() is called. /// /// Directory. static void AddWebPluginDirectory(String^ directory) { CefAddWebPluginDirectory(StringUtils::ToNative(directory)); } /// /// Cause the plugin list to refresh the next time it is accessed regardless of whether it has already been loaded. /// static void RefreshWebPlugins() { CefRefreshWebPlugins(); } /// /// Remove a plugin path (directory + file). This change may not take affect until after RefreshWebPlugins() is called. /// /// Path (directory + file). static void RemoveWebPluginPath(String^ path) { CefRemoveWebPluginPath(StringUtils::ToNative(path)); } /// /// Unregister an internal plugin. This may be undone the next time RefreshWebPlugins() is called. /// /// Path (directory + file). static void UnregisterInternalWebPlugin(String^ path) { CefUnregisterInternalWebPlugin(StringUtils::ToNative(path)); } /// /// Force a plugin to shutdown. /// /// Path (directory + file). static void ForceWebPluginShutdown(String^ path) { CefForceWebPluginShutdown(StringUtils::ToNative(path)); } /// /// Call during process startup to enable High-DPI support on Windows 7 or newer. /// Older versions of Windows should be left DPI-unaware because they do not /// support DirectWrite and GDI fonts are kerned very badly. /// static void EnableHighDPISupport() { CefEnableHighDPISupport(); } /// /// Request a one-time geolocation update. /// This function bypasses any user permission checks so should only be /// used by code that is allowed to access location information. /// /// Returns 'best available' location info or, if the location update failed, with error info. static Task^ GetGeolocationAsync() { auto callback = new CefGetGeolocationCallbackWrapper(); CefGetGeolocation(callback); return callback->GetTask(); } }; }