123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940 |
- #include "WebInterfaceBrowserSingleton.h"
- #include "Misc/Paths.h"
- #include "GenericPlatform/GenericPlatformFile.h"
- #include "Misc/CommandLine.h"
- #include "Misc/ConfigCacheIni.h"
- #include "Internationalization/Culture.h"
- #include "Misc/App.h"
- #include "WebInterfaceBrowserModule.h"
- #include "Misc/EngineVersion.h"
- #include "Framework/Application/SlateApplication.h"
- #include "IWebInterfaceBrowserCookieManager.h"
- #include "WebInterfaceBrowserLog.h"
- #if PLATFORM_WINDOWS
- #include "Windows/WindowsHWrapper.h"
- #endif
- #if WITH_CEF3
- #include "Misc/ScopeLock.h"
- #include "Async/Async.h"
- #include "HAL/PlatformApplicationMisc.h"
- #include "CEF/CEFInterfaceBrowserApp.h"
- #include "CEF/CEFInterfaceBrowserHandler.h"
- #include "CEF/CEFWebInterfaceBrowserWindow.h"
- #include "CEF/CEFInterfaceSchemeHandler.h"
- #include "CEF/CEFInterfaceResourceContextHandler.h"
- #include "CEF/CEFInterfaceBrowserClosureTask.h"
- # if PLATFORM_WINDOWS
- # include "Windows/AllowWindowsPlatformTypes.h"
- # endif
- # pragma push_macro("OVERRIDE")
- # undef OVERRIDE
- THIRD_PARTY_INCLUDES_START
- #if PLATFORM_APPLE
- PRAGMA_DISABLE_DEPRECATION_WARNINGS
- #endif
- # include "include/cef_app.h"
- # include "include/cef_version.h"
- #if PLATFORM_APPLE
- PRAGMA_ENABLE_DEPRECATION_WARNINGS
- #endif
- THIRD_PARTY_INCLUDES_END
- # pragma pop_macro("OVERRIDE")
- # if PLATFORM_WINDOWS
- # include "Windows/HideWindowsPlatformTypes.h"
- # endif
- #endif
- #if BUILD_EMBEDDED_APP
- # include "Native/NativeWebInterfaceBrowserProxy.h"
- #endif
- #if WITH_CEF3
- # define CEF3_BIN_DIR TEXT("Binaries/ThirdParty/CEF3")
- # if PLATFORM_WINDOWS && PLATFORM_64BITS
- # define CEF3_RESOURCES_DIR CEF3_BIN_DIR TEXT("/Win64/Resources")
- # define CEF3_SUBPROCES_EXE TEXT("Binaries/Win64/EpicWebHelper.exe")
- # elif PLATFORM_WINDOWS && PLATFORM_32BITS
- # define CEF3_RESOURCES_DIR CEF3_BIN_DIR TEXT("/Win32/Resources")
- # define CEF3_SUBPROCES_EXE TEXT("Binaries/Win32/EpicWebHelper.exe")
- # elif PLATFORM_MAC
- # if PLATFORM_MAC_ARM64
- # define CEF3_FRAMEWORK_DIR CEF3_BIN_DIR TEXT("/Mac/Chromium Embedded Framework arm64.framework")
- # else
- # define CEF3_FRAMEWORK_DIR CEF3_BIN_DIR TEXT("/Mac/Chromium Embedded Framework x86.framework")
- # endif
- # define CEF3_RESOURCES_DIR CEF3_FRAMEWORK_DIR TEXT("/Resources")
- # define CEF3_SUBPROCES_EXE TEXT("Binaries/Mac/EpicWebHelper.app/Contents/MacOS/EpicWebHelper")
- # elif PLATFORM_LINUX
- # define CEF3_RESOURCES_DIR CEF3_BIN_DIR TEXT("/Linux/Resources")
- # define CEF3_SUBPROCES_EXE TEXT("Binaries/Linux/EpicWebHelper")
- # endif
-
- # ifndef CEF3_DEFAULT_CACHE
- # define CEF3_DEFAULT_CACHE 1
- # endif
- #endif
- FString FWebInterfaceBrowserSingleton::ApplicationCacheDir() const
- {
- #if PLATFORM_MAC
-
- static TCHAR Result[MAC_MAX_PATH] = TEXT("");
- if (!Result[0])
- {
- SCOPED_AUTORELEASE_POOL;
- NSString *CacheBaseDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
- NSString* BundleID = [[NSBundle mainBundle] bundleIdentifier];
- if(!BundleID)
- {
- BundleID = [[NSProcessInfo processInfo] processName];
- }
- check(BundleID);
- NSString* AppCacheDir = [CacheBaseDir stringByAppendingPathComponent: BundleID];
- FPlatformString::CFStringToTCHAR((CFStringRef)AppCacheDir, Result);
- }
- return FString(Result);
- #else
-
- return FPaths::ProjectSavedDir();
- #endif
- }
- class FWebInterfaceBrowserWindowFactory
- : public IWebInterfaceBrowserWindowFactory
- {
- public:
- virtual ~FWebInterfaceBrowserWindowFactory()
- { }
- virtual TSharedPtr<IWebInterfaceBrowserWindow> Create(
- TSharedPtr<FCEFWebInterfaceBrowserWindow>& BrowserWindowParent,
- TSharedPtr<FWebInterfaceBrowserWindowInfo>& BrowserWindowInfo) override
- {
- return IWebInterfaceBrowserModule::Get().GetSingleton()->CreateBrowserWindow(
- BrowserWindowParent,
- BrowserWindowInfo);
- }
- virtual TSharedPtr<IWebInterfaceBrowserWindow> Create(
- void* OSWindowHandle,
- FString InitialURL,
- bool bUseTransparency,
- bool bThumbMouseButtonNavigation,
- bool bInterceptLoadRequests = false,
- TOptional<FString> ContentsToLoad = TOptional<FString>(),
- bool ShowErrorMessage = true,
- FColor BackgroundColor = FColor(255, 255, 255, 255)) override
- {
- FCreateInterfaceBrowserWindowSettings Settings;
- Settings.OSWindowHandle = OSWindowHandle;
- Settings.InitialURL = MoveTemp(InitialURL);
- Settings.bUseTransparency = bUseTransparency;
- Settings.bThumbMouseButtonNavigation = bThumbMouseButtonNavigation;
- Settings.ContentsToLoad = MoveTemp(ContentsToLoad);
- Settings.bShowErrorMessage = ShowErrorMessage;
- Settings.BackgroundColor = BackgroundColor;
- Settings.bInterceptLoadRequests = bInterceptLoadRequests;
- return IWebInterfaceBrowserModule::Get().GetSingleton()->CreateBrowserWindow(Settings);
- }
- };
- class FNoWebInterfaceBrowserWindowFactory
- : public IWebInterfaceBrowserWindowFactory
- {
- public:
- virtual ~FNoWebInterfaceBrowserWindowFactory()
- { }
- virtual TSharedPtr<IWebInterfaceBrowserWindow> Create(
- TSharedPtr<FCEFWebInterfaceBrowserWindow>& BrowserWindowParent,
- TSharedPtr<FWebInterfaceBrowserWindowInfo>& BrowserWindowInfo) override
- {
- return nullptr;
- }
- virtual TSharedPtr<IWebInterfaceBrowserWindow> Create(
- void* OSWindowHandle,
- FString InitialURL,
- bool bUseTransparency,
- bool bThumbMouseButtonNavigation,
- bool bInterceptLoadRequests = false,
- TOptional<FString> ContentsToLoad = TOptional<FString>(),
- bool ShowErrorMessage = true,
- FColor BackgroundColor = FColor(255, 255, 255, 255)) override
- {
- return nullptr;
- }
- };
- #if WITH_CEF3
- #if PLATFORM_MAC || PLATFORM_LINUX
- class FInterfacePosixSignalPreserver
- {
- public:
- FInterfacePosixSignalPreserver()
- {
- struct sigaction Sigact;
- for (uint32 i = 0; i < UE_ARRAY_COUNT(PreserveSignals); ++i)
- {
- FMemory::Memset(&Sigact, 0, sizeof(Sigact));
- if (sigaction(PreserveSignals[i], nullptr, &Sigact) != 0)
- {
- UE_LOG(LogWebInterfaceBrowser, Warning, TEXT("Failed to backup signal handler for %i."), PreserveSignals[i]);
- }
- OriginalSignalHandlers[i] = Sigact;
- }
- }
- ~FInterfacePosixSignalPreserver()
- {
- for (uint32 i = 0; i < UE_ARRAY_COUNT(PreserveSignals); ++i)
- {
- if(sigaction(PreserveSignals[i], &OriginalSignalHandlers[i], nullptr) != 0)
- {
- UE_LOG(LogWebInterfaceBrowser, Warning, TEXT("Failed to restore signal handler for %i."), PreserveSignals[i]);
- }
- }
- }
- private:
-
-
- const int PreserveSignals[13] = {SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT,
- SIGFPE, SIGSEGV, SIGALRM, SIGTERM, SIGCHLD, SIGBUS, SIGTRAP, SIGPIPE};
- struct sigaction OriginalSignalHandlers[UE_ARRAY_COUNT(PreserveSignals)];
- };
- #endif
- #endif
- FWebInterfaceBrowserSingleton::FWebInterfaceBrowserSingleton(const FWebInterfaceBrowserInitSettings& WebBrowserInitSettings)
- #if WITH_CEF3
- : WebBrowserWindowFactory(MakeShareable(new FWebInterfaceBrowserWindowFactory()))
- #else
- : WebBrowserWindowFactory(MakeShareable(new FNoWebInterfaceBrowserWindowFactory()))
- #endif
- , bDevToolsShortcutEnabled(UE_BUILD_DEVELOPMENT || UE_BUILD_DEBUG)
- , bJSBindingsToLoweringEnabled(true)
- , bAppIsFocused(false)
- #if WITH_CEF3
- , bCEFInitialized(false)
- #endif
- , DefaultMaterial(nullptr)
- , DefaultTranslucentMaterial(nullptr)
- {
- #if WITH_CEF3
-
-
- bAllowCEF = (!IsRunningCommandlet() || (IsAllowCommandletRendering() && FParse::Param(FCommandLine::Get(), TEXT("AllowCommandletCEF")))) &&
- FApp::CanEverRender() && !FParse::Param(FCommandLine::Get(), TEXT("nocef"));
- if (bAllowCEF)
- {
-
- check(IsInGameThread());
-
- #if PLATFORM_WINDOWS
- CefMainArgs MainArgs(hInstance);
- #else
- CefMainArgs MainArgs;
- #endif
-
-
- CefEnableHighDPISupport();
- bool bWebGL = FParse::Param(FCommandLine::Get(), TEXT("webgl"));
- bool bVerboseLogging = FParse::Param(FCommandLine::Get(), TEXT("cefverbose")) || FParse::Param(FCommandLine::Get(), TEXT("debuglog"));
-
- CEFBrowserApp = new FCEFInterfaceBrowserApp(bWebGL);
-
- CefSettings Settings;
- Settings.no_sandbox = true;
- Settings.command_line_args_disabled = true;
- Settings.external_message_pump = true;
-
- Settings.multi_threaded_message_loop = false;
-
-
- Settings.background_color = CefColorSetARGB(255, 0, 0, 0);
- #if PLATFORM_LINUX
- Settings.windowless_rendering_enabled = true;
- #endif
- FString CefLogFile(FPaths::Combine(*FPaths::ProjectLogDir(), TEXT("cef3.log")));
- CefLogFile = FPaths::ConvertRelativePathToFull(CefLogFile);
- CefString(&Settings.log_file) = TCHAR_TO_WCHAR(*CefLogFile);
- Settings.log_severity = bVerboseLogging ? LOGSEVERITY_VERBOSE : LOGSEVERITY_WARNING;
- uint16 DebugPort;
- if(FParse::Value(FCommandLine::Get(), TEXT("cefdebug="), DebugPort))
- {
- Settings.remote_debugging_port = DebugPort;
- }
-
- FString LocaleCode = GetCurrentLocaleCode();
- CefString(&Settings.locale) = TCHAR_TO_WCHAR(*LocaleCode);
-
- CefString(&Settings.user_agent_product) = TCHAR_TO_WCHAR(*WebBrowserInitSettings.ProductVersion);
- #if CEF3_DEFAULT_CACHE
-
- FString CachePath(FPaths::Combine(ApplicationCacheDir(), TEXT("webcache")));
- CachePath = FPaths::ConvertRelativePathToFull(GenerateWebCacheFolderName(CachePath));
- CefString(&Settings.cache_path) = TCHAR_TO_WCHAR(*CachePath);
- #endif
-
- FString ResourcesPath(FPaths::Combine(*FPaths::EngineDir(), CEF3_RESOURCES_DIR));
- ResourcesPath = FPaths::ConvertRelativePathToFull(ResourcesPath);
- if (!FPaths::DirectoryExists(ResourcesPath))
- {
- UE_LOG(LogWebInterfaceBrowser, Error, TEXT("Chromium Resources information not found at: %s."), *ResourcesPath);
- }
- CefString(&Settings.resources_dir_path) = TCHAR_TO_WCHAR(*ResourcesPath);
- #if !PLATFORM_MAC
-
- FString LocalesPath(FPaths::Combine(*ResourcesPath, TEXT("locales")));
- LocalesPath = FPaths::ConvertRelativePathToFull(LocalesPath);
- if (!FPaths::DirectoryExists(LocalesPath))
- {
- UE_LOG(LogWebInterfaceBrowser, Error, TEXT("Chromium Locales information not found at: %s."), *LocalesPath);
- }
- CefString(&Settings.locales_dir_path) = TCHAR_TO_WCHAR(*LocalesPath);
- #else
-
-
- FString LocalePakPath = ResourcesPath + TEXT("/") + LocaleCode.Replace(TEXT("-"), TEXT("_")) + TEXT(".lproj/locale.pak");
- if (!FPaths::FileExists(LocalePakPath))
- {
- FCultureRef Culture = FInternationalization::Get().GetCurrentCulture();
- LocaleCode = Culture->GetTwoLetterISOLanguageName();
- LocalePakPath = ResourcesPath + TEXT("/") + LocaleCode + TEXT(".lproj/locale.pak");
- if (FPaths::FileExists(LocalePakPath))
- {
- CefString(&Settings.locale) = TCHAR_TO_WCHAR(*LocaleCode);
- }
- }
-
- FString CefFrameworkPath(FPaths::Combine(*FPaths::EngineDir(), CEF3_FRAMEWORK_DIR));
- CefFrameworkPath = FPaths::ConvertRelativePathToFull(CefFrameworkPath);
- CefString(&Settings.framework_dir_path) = TCHAR_TO_WCHAR(*CefFrameworkPath);
- CefString(&Settings.main_bundle_path) = TCHAR_TO_WCHAR(*CefFrameworkPath);
- #endif
-
- FString SubProcessPath(FPaths::Combine(*FPaths::EngineDir(), CEF3_SUBPROCES_EXE));
- SubProcessPath = FPaths::ConvertRelativePathToFull(SubProcessPath);
- if (!IPlatformFile::GetPlatformPhysical().FileExists(*SubProcessPath))
- {
- UE_LOG(LogWebInterfaceBrowser, Error, TEXT("EpicWebHelper.exe not found, check that this program has been built and is placed in: %s."), *SubProcessPath);
- }
- CefString(&Settings.browser_subprocess_path) = TCHAR_TO_WCHAR(*SubProcessPath);
- #if PLATFORM_MAC || PLATFORM_LINUX
-
- FInterfacePosixSignalPreserver PosixSignalPreserver;
- #endif
-
- bCEFInitialized = CefInitialize(MainArgs, Settings, CEFBrowserApp.get(), nullptr);
- check(bCEFInitialized);
-
- FPlatformProcess::SetThreadName(*FName(NAME_GameThread).GetPlainNameString());
- DefaultCookieManager = FCefWebInterfaceCookieManagerFactory::Create(CefCookieManager::GetGlobalManager(nullptr));
- }
- #endif
- }
- #if WITH_CEF3
- void FWebInterfaceBrowserSingleton::WaitForTaskQueueFlush()
- {
-
- bTaskFinished = false;
- CefPostTask(TID_UI, new FCEFInterfaceBrowserClosureTask(nullptr, [=]()
- {
- bTaskFinished = true;
- }));
- const double StartWaitAppTime = FPlatformTime::Seconds();
- while (!bTaskFinished)
- {
- FPlatformProcess::Sleep(0.01);
-
- if (FSlateApplication::IsInitialized())
- {
- FSlateApplication::Get().PumpMessages();
- }
- CefDoMessageLoopWork();
-
- if (FPlatformTime::Seconds() - StartWaitAppTime > 1.0f)
- {
- break;
- }
- }
- }
- #endif
- FWebInterfaceBrowserSingleton::~FWebInterfaceBrowserSingleton()
- {
- #if WITH_CEF3
- if (!bCEFInitialized)
- return;
- if (bAllowCEF)
- {
- {
- FScopeLock Lock(&WindowInterfacesCS);
-
- for (int32 Index = 0; Index < WindowInterfaces.Num(); ++Index)
- {
- auto BrowserWindow = WindowInterfaces[Index].Pin();
- if (BrowserWindow.IsValid() && BrowserWindow->IsValid())
- {
-
- BrowserWindow->InternalCefBrowser->GetHost()->CloseBrowser(true);
- }
- }
-
- WindowInterfaces.Reset();
- }
-
- CefClearSchemeHandlerFactories();
- for (const TPair<FString, CefRefPtr<CefRequestContext>>& RequestContextPair : RequestContexts)
- {
- RequestContextPair.Value->ClearSchemeHandlerFactories();
- }
-
- RequestContexts.Reset();
-
- for (const TPair <FString,CefRefPtr<FCEFInterfaceResourceContextHandler>>& HandlerPair : RequestResourceHandlers)
- {
- HandlerPair.Value->OnBeforeLoad().Unbind();
- }
-
- RequestResourceHandlers.Reset();
-
- CEFBrowserApp = nullptr;
- WaitForTaskQueueFlush();
-
- CefShutdown();
- }
- bCEFInitialized = false;
- #endif
- }
- TSharedRef<IWebInterfaceBrowserWindowFactory> FWebInterfaceBrowserSingleton::GetWebBrowserWindowFactory() const
- {
- return WebBrowserWindowFactory;
- }
- TSharedPtr<IWebInterfaceBrowserWindow> FWebInterfaceBrowserSingleton::CreateBrowserWindow(
- TSharedPtr<FCEFWebInterfaceBrowserWindow>& BrowserWindowParent,
- TSharedPtr<FWebInterfaceBrowserWindowInfo>& BrowserWindowInfo
- )
- {
- #if WITH_CEF3
- if (bAllowCEF)
- {
- TOptional<FString> ContentsToLoad;
- bool bShowErrorMessage = BrowserWindowParent->IsShowingErrorMessages();
- bool bThumbMouseButtonNavigation = BrowserWindowParent->IsThumbMouseButtonNavigationEnabled();
- bool bUseTransparency = BrowserWindowParent->UseTransparency();
- bool bUsingAcceleratedPaint = BrowserWindowParent->UsingAcceleratedPaint();
- bool bUseNativeCursors = BrowserWindowParent->UseNativeCursors();
- FString InitialURL = WCHAR_TO_TCHAR(BrowserWindowInfo->Browser->GetMainFrame()->GetURL().ToWString().c_str());
- TSharedPtr<FCEFWebInterfaceBrowserWindow> NewBrowserWindow(new FCEFWebInterfaceBrowserWindow(BrowserWindowInfo->Browser, BrowserWindowInfo->Handler, InitialURL, ContentsToLoad, bShowErrorMessage, bThumbMouseButtonNavigation, bUseTransparency, bUseNativeCursors, bJSBindingsToLoweringEnabled, bUsingAcceleratedPaint));
- BrowserWindowInfo->Handler->SetBrowserWindow(NewBrowserWindow);
- {
- FScopeLock Lock(&WindowInterfacesCS);
- WindowInterfaces.Add(NewBrowserWindow);
- }
- NewBrowserWindow->GetCefBrowser()->GetHost()->SetWindowlessFrameRate(BrowserWindowParent->GetCefBrowser()->GetHost()->GetWindowlessFrameRate());
- return NewBrowserWindow;
- }
- #endif
- return nullptr;
- }
- TSharedPtr<IWebInterfaceBrowserWindow> FWebInterfaceBrowserSingleton::CreateBrowserWindow(const FCreateInterfaceBrowserWindowSettings& WindowSettings)
- {
- bool bBrowserEnabled = true;
- GConfig->GetBool(TEXT("Browser"), TEXT("bEnabled"), bBrowserEnabled, GEngineIni);
- if (!bBrowserEnabled || !FApp::CanEverRender())
- {
- return nullptr;
- }
- #if WITH_CEF3
- if (bAllowCEF)
- {
-
- CefWindowInfo WindowInfo;
-
- CefBrowserSettings BrowserSettings;
-
-
-
-
- BrowserSettings.background_color = CefColorSetARGB(WindowSettings.bUseTransparency ? 0 : WindowSettings.BackgroundColor.A, WindowSettings.BackgroundColor.R, WindowSettings.BackgroundColor.G, WindowSettings.BackgroundColor.B);
-
- BrowserSettings.plugins = STATE_DISABLED;
- #if PLATFORM_WINDOWS
-
- if (WindowSettings.OSWindowHandle != nullptr)
- {
- RECT ClientRect = { 0, 0, 0, 0 };
- if (!GetClientRect((HWND)WindowSettings.OSWindowHandle, &ClientRect))
- {
- UE_LOG(LogWebInterfaceBrowser, Error, TEXT("Failed to get client rect"));
- }
- WindowInfo.SetAsChild((CefWindowHandle)WindowSettings.OSWindowHandle, ClientRect);
- }
- else
- #endif
- {
-
- WindowInfo.SetAsWindowless(kNullWindowHandle);
- WindowInfo.shared_texture_enabled = WindowSettings.bAcceleratedPaint && FCEFWebInterfaceBrowserWindow::CanSupportAcceleratedPaint() ? 1 : 0;
- BrowserSettings.windowless_frame_rate = WindowSettings.BrowserFrameRate;
- }
-
- TArray<FString> AuthorizationHeaderAllowListURLS;
- GConfig->GetArray(TEXT("Browser"), TEXT("AuthorizationHeaderAllowListURLS"), AuthorizationHeaderAllowListURLS, GEngineIni);
-
- CefRefPtr<FCEFInterfaceBrowserHandler> NewHandler(new FCEFInterfaceBrowserHandler(WindowSettings.bUseTransparency, WindowSettings.bInterceptLoadRequests ,WindowSettings.AltRetryDomains, AuthorizationHeaderAllowListURLS));
- CefRefPtr<CefRequestContext> RequestContext = nullptr;
- if (WindowSettings.Context.IsSet())
- {
- const FInterfaceBrowserContextSettings Context = WindowSettings.Context.GetValue();
- const CefRefPtr<CefRequestContext>* ExistingRequestContext = RequestContexts.Find(Context.Id);
- if (ExistingRequestContext == nullptr)
- {
- CefRequestContextSettings RequestContextSettings;
- CefString(&RequestContextSettings.accept_language_list) = Context.AcceptLanguageList.IsEmpty() ? TCHAR_TO_WCHAR(*GetCurrentLocaleCode()) : TCHAR_TO_WCHAR(*Context.AcceptLanguageList);
- CefString(&RequestContextSettings.cache_path) = TCHAR_TO_WCHAR(*GenerateWebCacheFolderName(Context.CookieStorageLocation));
- RequestContextSettings.persist_session_cookies = Context.bPersistSessionCookies;
- RequestContextSettings.ignore_certificate_errors = Context.bIgnoreCertificateErrors;
- CefRefPtr<FCEFInterfaceResourceContextHandler> ResourceContextHandler = new FCEFInterfaceResourceContextHandler(this);
- ResourceContextHandler->OnBeforeLoad() = Context.OnBeforeContextResourceLoad;
- RequestResourceHandlers.Add(Context.Id, ResourceContextHandler);
-
- RequestContext = CefRequestContext::CreateContext(RequestContextSettings, ResourceContextHandler);
- RequestContexts.Add(Context.Id, RequestContext);
- }
- else
- {
- RequestContext = *ExistingRequestContext;
- }
- SchemeHandlerFactories.RegisterFactoriesWith(RequestContext);
- UE_LOG(LogWebInterfaceBrowser, Log, TEXT("Creating browser for ContextId=%s."), *WindowSettings.Context.GetValue().Id);
- }
- if (RequestContext == nullptr)
- {
-
- RequestContext = CefRequestContext::GetGlobalContext();
- }
-
- CefRefPtr<CefBrowser> Browser = CefBrowserHost::CreateBrowserSync(WindowInfo, NewHandler.get(), TCHAR_TO_WCHAR(*WindowSettings.InitialURL), BrowserSettings, nullptr, RequestContext);
- if (Browser.get())
- {
-
- TSharedPtr<FCEFWebInterfaceBrowserWindow> NewBrowserWindow = MakeShareable(new FCEFWebInterfaceBrowserWindow(
- Browser,
- NewHandler,
- WindowSettings.InitialURL,
- WindowSettings.ContentsToLoad,
- WindowSettings.bShowErrorMessage,
- WindowSettings.bThumbMouseButtonNavigation,
- WindowSettings.bUseTransparency,
- WindowSettings.bUseNativeCursors,
- bJSBindingsToLoweringEnabled,
- WindowInfo.shared_texture_enabled == 1 ? true : false));
- NewHandler->SetBrowserWindow(NewBrowserWindow);
- {
- FScopeLock Lock(&WindowInterfacesCS);
- WindowInterfaces.Add(NewBrowserWindow);
- }
- return NewBrowserWindow;
- }
- }
- #endif
- return nullptr;
- }
- #if BUILD_EMBEDDED_APP
- TSharedPtr<IWebInterfaceBrowserWindow> FWebInterfaceBrowserSingleton::CreateNativeBrowserProxy()
- {
- TSharedPtr<FNativeWebInterfaceBrowserProxy> NewBrowserWindow = MakeShareable(new FNativeWebInterfaceBrowserProxy(
- bJSBindingsToLoweringEnabled
- ));
- NewBrowserWindow->Initialize();
- return NewBrowserWindow;
- }
- #endif
- bool FWebInterfaceBrowserSingleton::Tick(float DeltaTime)
- {
- QUICK_SCOPE_CYCLE_COUNTER(STAT_FWebInterfaceBrowserSingleton_Tick);
- #if WITH_CEF3
- if (bAllowCEF)
- {
- {
- FScopeLock Lock(&WindowInterfacesCS);
- bool bIsSlateAwake = FSlateApplication::IsInitialized() && !FSlateApplication::Get().IsSlateAsleep();
-
- for (int32 Index = WindowInterfaces.Num() - 1; Index >= 0; --Index)
- {
- if (!WindowInterfaces[Index].IsValid())
- {
- WindowInterfaces.RemoveAt(Index);
- }
- else if (bIsSlateAwake)
- {
- TSharedPtr<FCEFWebInterfaceBrowserWindow> BrowserWindow = WindowInterfaces[Index].Pin();
- if(BrowserWindow.IsValid())
- {
-
- BrowserWindow->CheckTickActivity();
- }
- }
- }
- }
-
- if (CEFBrowserApp != nullptr)
- {
- bool bForceMessageLoop = false;
- GConfig->GetBool(TEXT("Browser"), TEXT("bForceMessageLoop"), bForceMessageLoop, GEngineIni);
-
- static const int MaxFrameRateClamp = 60;
- int32 MinMessageLoopHz = 1;
- GConfig->GetInt(TEXT("Browser"), TEXT("MinMessageLoopHertz"), MinMessageLoopHz, GEngineIni);
- MinMessageLoopHz = FMath::Clamp(MinMessageLoopHz, 1, 60);
-
- int32 MaxForcedMessageLoopHz = 15;
- GConfig->GetInt(TEXT("Browser"), TEXT("MaxForcedMessageLoopHertz"), MaxForcedMessageLoopHz, GEngineIni);
- MaxForcedMessageLoopHz = FMath::Clamp(MaxForcedMessageLoopHz, MinMessageLoopHz, 60);
-
-
-
-
- float MinMessageLoopSeconds = 1.0f / MinMessageLoopHz;
- float MaxForcedMessageLoopSeconds = 1.0f / MaxForcedMessageLoopHz;
- static float SecondsSinceLastPump = 0;
- static float SecondsSinceLastAppFocusCheck = MaxForcedMessageLoopSeconds;
- static float SecondsToNextForcedPump = MaxForcedMessageLoopSeconds;
-
- SecondsSinceLastPump += DeltaTime;
- SecondsSinceLastAppFocusCheck += DeltaTime;
-
- SecondsToNextForcedPump -= DeltaTime;
- bool bWantForce = bForceMessageLoop;
- bool bCanForce = SecondsToNextForcedPump <= 0;
- bool bMustForce = SecondsSinceLastPump >= MinMessageLoopSeconds;
- if (SecondsSinceLastAppFocusCheck > MinMessageLoopSeconds && WindowInterfaces.Num() > 0)
- {
- SecondsSinceLastAppFocusCheck = 0;
-
- bAppIsFocused = FPlatformApplicationMisc::IsThisApplicationForeground();
- }
-
- bool bAppIsFocusedAndWebWindows = WindowInterfaces.Num() > 0 && bAppIsFocused;
-
- if (bWantForce == false && bMustForce == false && bAppIsFocusedAndWebWindows == true )
- {
- for (int32 Index = 0; Index < WindowInterfaces.Num(); Index++)
- {
- if (WindowInterfaces[Index].IsValid())
- {
- TSharedPtr<FCEFWebInterfaceBrowserWindow> BrowserWindow = WindowInterfaces[Index].Pin();
- if (BrowserWindow->GetParentWindow().IsValid())
- {
- TSharedPtr<SWindow> BrowserParentWindow = BrowserWindow->GetParentWindow();
- if (!BrowserParentWindow->IsWindowMinimized())
- {
- bWantForce = true;
- }
- }
- }
- }
- }
-
- if (CEFBrowserApp->TickMessagePump(DeltaTime, (bWantForce && bCanForce) || bMustForce))
- {
- SecondsSinceLastPump = 0;
- SecondsToNextForcedPump = MaxForcedMessageLoopSeconds;
- }
- }
-
- for (int32 Index = 0; Index < WindowInterfaces.Num(); Index++)
- {
- if (WindowInterfaces[Index].IsValid())
- {
- TSharedPtr<FCEFWebInterfaceBrowserWindow> BrowserWindow = WindowInterfaces[Index].Pin();
- if (BrowserWindow.IsValid())
- {
- BrowserWindow->UpdateVideoBuffering();
- }
- }
- }
- }
- #endif
- return true;
- }
- FString FWebInterfaceBrowserSingleton::GetCurrentLocaleCode()
- {
- FCultureRef Culture = FInternationalization::Get().GetCurrentCulture();
- FString LocaleCode = Culture->GetTwoLetterISOLanguageName();
- FString Country = Culture->GetRegion();
- if (!Country.IsEmpty())
- {
- LocaleCode = LocaleCode + TEXT("-") + Country;
- }
- return LocaleCode;
- }
- TSharedPtr<IWebInterfaceBrowserCookieManager> FWebInterfaceBrowserSingleton::GetCookieManager(TOptional<FString> ContextId) const
- {
- if (ContextId.IsSet())
- {
- #if WITH_CEF3
- if (bAllowCEF)
- {
- const CefRefPtr<CefRequestContext>* ExistingContext = RequestContexts.Find(ContextId.GetValue());
- if (ExistingContext && ExistingContext->get())
- {
-
- return FCefWebInterfaceCookieManagerFactory::Create((*ExistingContext)->GetCookieManager(nullptr));
- }
- else
- {
- UE_LOG(LogWebInterfaceBrowser, Log, TEXT("No cookie manager for ContextId=%s. Using default cookie manager"), *ContextId.GetValue());
- }
- }
- #endif
- }
-
- return DefaultCookieManager;
- }
- #if WITH_CEF3
- bool FWebInterfaceBrowserSingleton::URLRequestAllowsCredentials(const FString& URL)
- {
- FScopeLock Lock(&WindowInterfacesCS);
-
-
- for (int32 Index = WindowInterfaces.Num() - 1; Index >= 0; --Index)
- {
- TSharedPtr<FCEFWebInterfaceBrowserWindow> BrowserWindow = WindowInterfaces[Index].Pin();
- if (BrowserWindow.IsValid() && BrowserWindow->URLRequestAllowsCredentials(URL))
- {
- return true;
- }
- }
- return false;
- }
- FString FWebInterfaceBrowserSingleton::GenerateWebCacheFolderName(const FString& InputPath)
- {
- if (InputPath.IsEmpty())
- return InputPath;
-
-
- return InputPath + "_" + MAKE_STRING(CHROME_VERSION_BUILD);
- }
- #endif
- void FWebInterfaceBrowserSingleton::ClearOldCacheFolders(const FString &CachePathRoot, const FString &CachePrefix)
- {
- #if WITH_CEF3
-
- struct FDirectoryVisitor : public IPlatformFile::FDirectoryVisitor
- {
- const FString CachePrefix;
- const FString CurrentCachePath;
- FDirectoryVisitor(const FString &InCachePrefix, const FString &InCurrentCachePath)
- : CachePrefix(InCachePrefix),
- CurrentCachePath(InCurrentCachePath)
- {
- }
- virtual bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory) override
- {
- static const FString CachePrefixSearch = "/" + CachePrefix;
- if (bIsDirectory)
- {
- FString DirName(FilenameOrDirectory);
- if (DirName.Contains(CachePrefixSearch) && DirName.Equals(CurrentCachePath)==false)
- {
- UE_LOG(LogWebInterfaceBrowser, Log, TEXT("Old Cache folder found=%s, deleting"), *DirName);
-
-
-
- }
- }
-
- return true;
- }
- };
-
- FDirectoryVisitor Visitor(CachePrefix, GenerateWebCacheFolderName(FPaths::Combine(CachePathRoot, CachePrefix)));
- IPlatformFile::GetPlatformPhysical().IterateDirectory(*CachePathRoot, Visitor);
- #endif
- }
- bool FWebInterfaceBrowserSingleton::RegisterContext(const FInterfaceBrowserContextSettings& Settings)
- {
- #if WITH_CEF3
- if (bAllowCEF)
- {
- const CefRefPtr<CefRequestContext>* ExistingContext = RequestContexts.Find(Settings.Id);
- if (ExistingContext != nullptr)
- {
-
-
- return false;
- }
- CefRequestContextSettings RequestContextSettings;
- CefString(&RequestContextSettings.accept_language_list) = Settings.AcceptLanguageList.IsEmpty() ? TCHAR_TO_WCHAR(*GetCurrentLocaleCode()) : TCHAR_TO_WCHAR(*Settings.AcceptLanguageList);
- CefString(&RequestContextSettings.cache_path) = TCHAR_TO_WCHAR(*GenerateWebCacheFolderName(Settings.CookieStorageLocation));
- RequestContextSettings.persist_session_cookies = Settings.bPersistSessionCookies;
- RequestContextSettings.ignore_certificate_errors = Settings.bIgnoreCertificateErrors;
-
- CefRefPtr<FCEFInterfaceResourceContextHandler> ResourceContextHandler = new FCEFInterfaceResourceContextHandler(this);
- ResourceContextHandler->OnBeforeLoad() = Settings.OnBeforeContextResourceLoad;
- RequestResourceHandlers.Add(Settings.Id, ResourceContextHandler);
- CefRefPtr<CefRequestContext> RequestContext = CefRequestContext::CreateContext(RequestContextSettings, ResourceContextHandler);
- RequestContexts.Add(Settings.Id, RequestContext);
- SchemeHandlerFactories.RegisterFactoriesWith(RequestContext);
- UE_LOG(LogWebInterfaceBrowser, Log, TEXT("Registering ContextId=%s."), *Settings.Id);
- return true;
- }
- #endif
- return false;
- }
- bool FWebInterfaceBrowserSingleton::UnregisterContext(const FString& ContextId)
- {
- #if WITH_CEF3
- bool bFoundContext = false;
- if (bAllowCEF)
- {
- UE_LOG(LogWebInterfaceBrowser, Log, TEXT("Unregistering ContextId=%s."), *ContextId);
- WaitForTaskQueueFlush();
- CefRefPtr<CefRequestContext> Context;
- if (RequestContexts.RemoveAndCopyValue(ContextId, Context))
- {
- bFoundContext = true;
- Context->ClearSchemeHandlerFactories();
- }
- CefRefPtr<FCEFInterfaceResourceContextHandler> ResourceHandler;
- if (RequestResourceHandlers.RemoveAndCopyValue(ContextId, ResourceHandler))
- {
- ResourceHandler->OnBeforeLoad().Unbind();
- }
- }
- return bFoundContext;
- #else
- return false;
- #endif
- }
- bool FWebInterfaceBrowserSingleton::RegisterSchemeHandlerFactory(FString Scheme, FString Domain, IWebInterfaceBrowserSchemeHandlerFactory* WebBrowserSchemeHandlerFactory)
- {
- #if WITH_CEF3
- if (bAllowCEF)
- {
- SchemeHandlerFactories.AddSchemeHandlerFactory(MoveTemp(Scheme), MoveTemp(Domain), WebBrowserSchemeHandlerFactory);
- return true;
- }
- #endif
- return false;
- }
- bool FWebInterfaceBrowserSingleton::UnregisterSchemeHandlerFactory(IWebInterfaceBrowserSchemeHandlerFactory* WebBrowserSchemeHandlerFactory)
- {
- #if WITH_CEF3
- if (bAllowCEF)
- {
- SchemeHandlerFactories.RemoveSchemeHandlerFactory(WebBrowserSchemeHandlerFactory);
- return true;
- }
- #endif
- return false;
- }
- #undef CEF3_BIN_DIR
- #undef CEF3_FRAMEWORK_DIR
- #undef CEF3_RESOURCES_DIR
- #undef CEF3_SUBPROCES_EXE
|