// 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 #include #include #include #include #include "Internals/CefSharpApp.h" #include "Internals/CookieVisitor.h" #include "Internals/CompletionHandler.h" #include "Internals/StringUtils.h" #include "Internals/PluginVisitor.h" #include "ManagedCefBrowserAdapter.h" #include "CefSettings.h" #include "ResourceHandlerWrapper.h" #include "SchemeHandlerFactoryWrapper.h" #include "Internals/CefTaskScheduler.h" #include "CookieAsyncWrapper.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); } } /// Initializes CefSharp with the default settings. /// true if successful; otherwise, false. static bool Initialize() { auto cefSettings = gcnew CefSettings(); return Initialize(cefSettings); } /// Initializes CefSharp with user-provided settings. /// CefSharp configuration settings. /// true if successful; otherwise, false. static bool Initialize(CefSettings^ cefSettings) { return Initialize(cefSettings, true, false); } /// Initializes CefSharp with user-provided settings. /// 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) { bool success = false; // NOTE: Can only initialize Cef once, so subsiquent calls are ignored. if (!IsInitialized) { 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)); 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; } /// 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(); } /// 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. static bool VisitAllCookies(ICookieVisitor^ visitor) { CefRefPtr manager = CefCookieManager::GetGlobalManager(); if (manager == nullptr) { return false; } CefRefPtr cookieVisitor = new CookieVisitor(visitor); return manager->VisitAllCookies(cookieVisitor); } /// Visits a subset of the cookies. The results are filtered by the given url scheme, host, domain and path. /// If is true, HTTP-only cookies will also be included in the results. The returned cookies /// are sorted by longest path, then by earliest creation date. /// The URL to use for filtering a subset of the cookies available. /// A flag that determines whether HTTP-only cookies will be shown in results. /// A user-provided Cookie Visitor implementation. /// Returns false if the CookieManager is not available; otherwise, true. static bool VisitUrlCookies(String^ url, bool includeHttpOnly, ICookieVisitor^ visitor) { CefRefPtr manager = CefCookieManager::GetGlobalManager(); if (manager == nullptr) { return false; } CefRefPtr cookieVisitor = new CookieVisitor(visitor); return manager->VisitUrlCookies(StringUtils::ToNative(url), includeHttpOnly, cookieVisitor); } /// Sets a CefSharp Cookie. This function expects each attribute to be well-formed. It will check for disallowed /// 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 name /// The cookie value /// The cookie domain /// The cookie path /// A flag that determines whether the cookie will be marked as "secure" (i.e. its scope is limited to secure channels, typically HTTPS). /// A flag that determines whether the cookie will be marked as HTTP Only (i.e. the cookie is inaccessible to client-side scripts). /// A flag that determines whether the cookie has an expiration date. Must be set to true when the "expires" parameter is provided. /// The DateTime when the cookie will be treated as expired. Will only be taken into account if the "has_expires" is set to true. /// false if the cookie cannot be set (e.g. if illegal charecters such as ';' are used); otherwise true. static bool SetCookie(String^ url, String^ name, String^ value, String^ domain, String^ path, bool secure, bool httponly, bool has_expires, DateTime expires) { auto cookieInvoker = gcnew CookieAsyncWrapper(url, name, value, domain, path, secure, httponly, has_expires, expires); if (CefCurrentlyOn(TID_IO)) { return cookieInvoker->SetCookie(); } auto task = Cef::IOThreadTaskFactory->StartNew(gcnew Func(cookieInvoker, &CookieAsyncWrapper::SetCookie)); task->Wait(); return task->Result; } /// Sets a cookie using mostly default parameters. This function expects each attribute to be well-formed. It will check for disallowed /// 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 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) { return SetCookie(url, name, value, domain, "/", false, false, true, expires); } /// Deletes all cookies that matches all the provided parameters. If both and are empty, all cookies will be deleted. /// The cookie URL. If an empty string is provided, any URL will be matched. /// The name of the cookie. If an empty string is provided, any URL will be matched. /// false if a non-empty invalid URL is specified, or if cookies cannot be accessed; otherwise, true. static bool DeleteCookies(String^ url, String^ name) { auto cookieInvoker = gcnew CookieAsyncWrapper(url, name); if (CefCurrentlyOn(TID_IO)) { return cookieInvoker->DeleteCookies(); } auto task = Cef::IOThreadTaskFactory->StartNew(gcnew Func(cookieInvoker, &CookieAsyncWrapper::DeleteCookies)); task->Wait(); return task->Result; } /// Sets the directory path that will be used for storing cookie data. If is empty data will be stored in /// memory only. Otherwise, data will be stored at the specified path. To persist session cookies (cookies without an expiry /// date or validity interval) set to true. Session cookies are generally intended to be transient and /// most Web browsers do not persist them. /// The file path to write cookies to. /// A flag that determines whether session cookies will be persisted or not. /// false if a non-empty invalid URL is specified, or if the CookieManager is not available; otherwise, true. static bool SetCookiePath(String^ path, bool persistSessionCookies) { CefRefPtr manager = CefCookieManager::GetGlobalManager(); if (manager == nullptr) { return false; } return manager->SetStoragePath(StringUtils::ToNative(path), persistSessionCookies); } /// Flush the backing store (if any) to disk and execute the specified |handler| on the IO thread when done. Returns /// A user-provided ICompletionHandler implementation. /// Returns false if cookies cannot be accessed. static bool FlushStore(ICompletionHandler^ handler) { CefRefPtr manager = CefCookieManager::GetGlobalManager(); if (manager == nullptr) { return false; } CefRefPtr wrapper = new CompletionHandler(handler); return manager->FlushStore(wrapper); } /// 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). /// 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) /// WARNING In the very unlikely event of no plugins being found the Task may never complete /// /// 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)); } }; }