| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366 |
- using System;
- using UnityEngine;
- using UnityEngine.UI;
- [DisallowMultipleComponent]
- public sealed class ActivityWebViewController : MonoBehaviour
- {
- const float RestoredBackdropAlpha = 0.68f;
- const float MaximizedBackdropAlpha = 1.0f;
- static ActivityWebViewController instance;
- static bool shownDuringLoadingThisSession;
- static bool shownThisSession;
- UniWebView webView;
- Image backdrop;
- float initialScale = 0.8f;
- bool maximized;
- bool closing;
- bool pageLoaded;
- Rect lastSafeArea;
- int lastScreenWidth;
- int lastScreenHeight;
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
- static void ResetStatics()
- {
- instance = null;
- shownDuringLoadingThisSession = false;
- shownThisSession = false;
- }
- public static void ShowDuringLoading()
- {
- if (shownDuringLoadingThisSession)
- return;
- ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
- if (settings == null)
- {
- Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources.");
- return;
- }
- if (!settings.showOnLaunch)
- return;
- if (EnsureInstance())
- {
- shownDuringLoadingThisSession = true;
- Debug.Log("[Activity] Activity page opened during loading.");
- }
- }
- public static void ShowOnLaunch()
- {
- if (shownThisSession)
- return;
- ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
- if (settings == null)
- {
- Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources.");
- return;
- }
- if (!settings.showOnLaunch)
- return;
- if (Show())
- shownThisSession = true;
- }
- public static bool Show()
- {
- return EnsureInstance();
- }
- static bool EnsureInstance()
- {
- if (instance != null)
- {
- instance.ApplyCurrentFrame();
- if (instance.webView != null && instance.pageLoaded)
- instance.webView.Show();
- return true;
- }
- ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
- string url = settings != null ? settings.activityUrl : ActivityWebViewSettings.DefaultActivityUrl;
- url = string.IsNullOrWhiteSpace(url) ? ActivityWebViewSettings.DefaultActivityUrl : url.Trim();
- if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri) ||
- (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
- {
- Debug.LogWarning("[Activity] Activity URL must be an absolute HTTP(S) URL: " + url);
- return false;
- }
- if (!UniWebView.IsWebViewSupported)
- {
- Debug.LogWarning("[Activity] UniWebView is not supported on this platform.");
- return false;
- }
- var root = new GameObject("ActivityWebView");
- DontDestroyOnLoad(root);
- var controller = root.AddComponent<ActivityWebViewController>();
- controller.Initialize(url, settings != null ? settings.initialScale : 0.8f);
- return true;
- }
- public static void CloseCurrent()
- {
- if (instance != null)
- instance.Close();
- }
- void Initialize(string url, float scale)
- {
- instance = this;
- initialScale = Mathf.Clamp(scale, 0.1f, 1f);
- CreateBackdrop();
- CreateWebView();
- lastSafeArea = Screen.safeArea;
- lastScreenWidth = Screen.width;
- lastScreenHeight = Screen.height;
- ApplyCurrentFrame();
- webView.Load(url);
- }
- void Update()
- {
- if (webView == null)
- return;
- Rect safeArea = Screen.safeArea;
- if (safeArea != lastSafeArea ||
- lastScreenWidth != Screen.width ||
- lastScreenHeight != Screen.height)
- {
- lastSafeArea = safeArea;
- lastScreenWidth = Screen.width;
- lastScreenHeight = Screen.height;
- ApplyCurrentFrame();
- }
- }
- void OnDestroy()
- {
- if (webView != null)
- {
- webView.OnShouldClose -= HandleShouldClose;
- webView.OnPageFinished -= HandlePageFinished;
- webView.OnLoadingErrorReceived -= HandleLoadingError;
- webView.OnChannelMessageReceived -= HandleChannelMessage;
- webView.OnMessageReceived -= HandleUrlMessage;
- }
- if (instance == this)
- instance = null;
- }
- void CreateBackdrop()
- {
- var canvasObject = new GameObject(
- "Backdrop",
- typeof(RectTransform),
- typeof(Canvas),
- typeof(GraphicRaycaster));
- canvasObject.transform.SetParent(transform, false);
- var canvas = canvasObject.GetComponent<Canvas>();
- canvas.renderMode = RenderMode.ScreenSpaceOverlay;
- canvas.sortingOrder = short.MaxValue;
- var imageObject = new GameObject("Dim", typeof(RectTransform), typeof(Image));
- imageObject.transform.SetParent(canvasObject.transform, false);
- var rect = imageObject.GetComponent<RectTransform>();
- rect.anchorMin = Vector2.zero;
- rect.anchorMax = Vector2.one;
- rect.offsetMin = Vector2.zero;
- rect.offsetMax = Vector2.zero;
- backdrop = imageObject.GetComponent<Image>();
- backdrop.color = new Color(0f, 0f, 0f, RestoredBackdropAlpha);
- backdrop.raycastTarget = true;
- }
- void CreateWebView()
- {
- UniWebView.SetAllowAutoPlay(true);
- UniWebView.SetJavaScriptEnabled(true);
- webView = gameObject.AddComponent<UniWebView>();
- webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
- webView.BackgroundColor = Color.black;
- webView.SetBackButtonEnabled(true);
- webView.OnShouldClose += HandleShouldClose;
- webView.OnPageFinished += HandlePageFinished;
- webView.OnLoadingErrorReceived += HandleLoadingError;
- webView.OnChannelMessageReceived += HandleChannelMessage;
- webView.OnMessageReceived += HandleUrlMessage;
- }
- bool HandleShouldClose(UniWebView view)
- {
- Close();
- return false;
- }
- void HandlePageFinished(UniWebView view, int statusCode, string url)
- {
- pageLoaded = true;
- Debug.Log("[Activity] Activity page loaded: " + url);
- ApplyCurrentFrame();
- view.Show();
- }
- void HandleLoadingError(UniWebView view, int errorCode, string errorMessage, UniWebViewNativeResultPayload payload)
- {
- if (pageLoaded)
- {
- Debug.LogWarning($"[Activity] Resource loading error {errorCode}: {errorMessage}");
- return;
- }
- Debug.LogWarning($"[Activity] Failed to load the activity page {errorCode}: {errorMessage}");
- Close();
- }
- UniWebViewChannelMessageResponse HandleChannelMessage(UniWebView view, UniWebViewChannelMessage message)
- {
- HandleAction(message.action, message.data);
- return null;
- }
- void HandleUrlMessage(UniWebView view, UniWebViewMessage message)
- {
- if (!string.Equals(message.Scheme, "uniwebview", StringComparison.OrdinalIgnoreCase))
- return;
- string payload = null;
- if (message.Args != null)
- message.Args.TryGetValue("payload", out payload);
- HandleAction(message.Path, payload);
- }
- void HandleAction(string action, string data)
- {
- if (string.IsNullOrWhiteSpace(action))
- return;
- switch (action.Trim().ToLowerInvariant())
- {
- case "close":
- Close();
- break;
- case "maximize":
- SetMaximized(true);
- break;
- case "restore":
- SetMaximized(false);
- break;
- case "facebook_config":
- ActivityFacebookService.ApplyConfig(ParseFacebookConfig(data));
- break;
- case "openwindow":
- OpenWindow(data);
- break;
- default:
- ActivityFacebookService.LogEvent(action, data);
- break;
- }
- }
- void SetMaximized(bool value)
- {
- maximized = value;
- ApplyCurrentFrame();
- }
- void ApplyCurrentFrame()
- {
- if (webView != null)
- webView.Frame = CalculateFrame();
- if (backdrop != null)
- backdrop.color = new Color(0f, 0f, 0f, maximized ? MaximizedBackdropAlpha : RestoredBackdropAlpha);
- }
- Rect CalculateFrame()
- {
- Rect safeArea = Screen.safeArea;
- float safeTop = Screen.height - safeArea.yMax;
- if (maximized)
- return new Rect(safeArea.xMin, safeTop, safeArea.width, safeArea.height);
- float width = safeArea.width * initialScale;
- float height = safeArea.height * initialScale;
- float x = safeArea.xMin + (safeArea.width - width) * 0.5f;
- float y = safeTop + (safeArea.height - height) * 0.5f;
- return new Rect(x, y, width, height);
- }
- void OpenWindow(string data)
- {
- if (string.IsNullOrWhiteSpace(data))
- return;
- try
- {
- var payload = JsonUtility.FromJson<ActivityOpenWindowPayload>(data);
- if (payload != null && !string.IsNullOrWhiteSpace(payload.url))
- Application.OpenURL(payload.url);
- }
- catch (Exception exception)
- {
- Debug.LogWarning("[Activity] Invalid openWindow payload: " + exception.Message);
- }
- }
- static ActivityFacebookConfig ParseFacebookConfig(string data)
- {
- if (string.IsNullOrWhiteSpace(data))
- return null;
- try
- {
- return JsonUtility.FromJson<ActivityFacebookConfig>(data);
- }
- catch (Exception exception)
- {
- Debug.LogWarning("[Activity] Invalid Facebook config: " + exception.Message);
- return null;
- }
- }
- void Close()
- {
- if (closing)
- return;
- closing = true;
- if (instance == this)
- instance = null;
- Destroy(gameObject);
- }
- #pragma warning disable 0649
- [Serializable]
- sealed class ActivityOpenWindowPayload
- {
- public string url;
- }
- #pragma warning restore 0649
- }
|