AppSettingsWindow.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEditorInternal;
  5. using UnityEngine;
  6. public sealed class AppSettingsWindow : EditorWindow
  7. {
  8. private AppSettings settings;
  9. private SerializedObject facebook;
  10. private int appIndex;
  11. private string appName, appId, clientToken;
  12. private string appAddress, appChannel, privacyUrl, downloadUrl, gameSceneName;
  13. private AssemblyDefinitionAsset hotPatchAssembly;
  14. private string addressError;
  15. private Vector2 scrollPosition;
  16. private bool showTestUrlHelp = false;
  17. private bool showUsageHelp = true;
  18. private bool showS3Settings;
  19. [NonSerialized] private string s3Bucket, s3Region, s3AccessKey, s3SecretKey, s3SessionToken;
  20. private const string TestUrlExample = @"<key>TestUserID</key>
  21. <string>https://example.com/test/</string>";
  22. [MenuItem("AppSettings/Open Settings")]
  23. public static void Open()
  24. {
  25. var window = GetWindow<AppSettingsWindow>("AppSettings");
  26. window.minSize = new Vector2(560, 420);
  27. window.LoadSettings();
  28. window.Show();
  29. }
  30. private void OnEnable()
  31. {
  32. showUsageHelp = true;
  33. LoadSettings();
  34. }
  35. private void LoadSettings()
  36. {
  37. settings = AppHelpProjectSettings.LoadOrCreateAppSettings();
  38. addressError = null;
  39. try
  40. {
  41. appAddress = string.IsNullOrEmpty(settings.AppAddress)
  42. ? string.Empty : ClientCrypto.DecryptString(settings.AppAddress);
  43. }
  44. catch (Exception)
  45. {
  46. appAddress = string.Empty;
  47. addressError = "Failed to decrypt AppAddress. Enter the plain-text address again and save.";
  48. }
  49. appChannel = settings.AppChannel;
  50. privacyUrl = settings.PrivacyUrl;
  51. downloadUrl = settings.DownloadUrl;
  52. gameSceneName = settings.GameSceneName;
  53. hotPatchAssembly = HotPatchAssemblySelection.Find(settings.HotPatchAssemblyName);
  54. var facebookAsset = AppHelpProjectSettings.LoadOrCreateFacebookSettings();
  55. facebook = facebookAsset != null ? new SerializedObject(facebookAsset) : null;
  56. appName = appId = clientToken = string.Empty;
  57. if (facebook == null) return;
  58. facebook.Update();
  59. appIndex = Mathf.Max(0, facebook.FindProperty("selectedAppIndex").intValue);
  60. appName = ReadFacebookValue("appLabels");
  61. appId = ReadFacebookValue("appIds");
  62. clientToken = ReadFacebookValue("clientTokens");
  63. }
  64. private string ReadFacebookValue(string name)
  65. {
  66. var property = facebook.FindProperty(name);
  67. return appIndex < property.arraySize
  68. ? property.GetArrayElementAtIndex(appIndex).stringValue : string.Empty;
  69. }
  70. private void WriteFacebookValue(string name, string value)
  71. {
  72. var property = facebook.FindProperty(name);
  73. while (property.arraySize <= appIndex)
  74. {
  75. var index = property.arraySize;
  76. property.arraySize++;
  77. property.GetArrayElementAtIndex(index).stringValue = string.Empty;
  78. }
  79. property.GetArrayElementAtIndex(appIndex).stringValue = value;
  80. }
  81. private void OnGUI()
  82. {
  83. using (new FontSizeScope(2))
  84. DrawWindow();
  85. }
  86. private void DrawWindow()
  87. {
  88. scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
  89. EditorGUILayout.LabelField("Facebook", EditorStyles.boldLabel);
  90. if (facebook == null)
  91. EditorGUILayout.HelpBox("FacebookSettings.asset was not found in Resources.", MessageType.Error);
  92. using (new EditorGUI.DisabledScope(facebook == null))
  93. {
  94. appName = EditorGUILayout.TextField("Facebook AppName", appName);
  95. appId = EditorGUILayout.TextField("Facebook AppID", appId);
  96. clientToken = EditorGUILayout.TextField("Client Token", clientToken);
  97. }
  98. EditorGUILayout.Space();
  99. EditorGUILayout.LabelField("App", EditorStyles.boldLabel);
  100. EditorGUI.BeginChangeCheck();
  101. appAddress = EditorGUILayout.TextField(new GUIContent("AppAddress", "Enter a plain-text address. It is encrypted when saved."), appAddress);
  102. if (EditorGUI.EndChangeCheck()) addressError = null;
  103. if (!string.IsNullOrEmpty(addressError))
  104. EditorGUILayout.HelpBox(addressError, MessageType.Error);
  105. appChannel = EditorGUILayout.TextField("AppChannel", appChannel);
  106. privacyUrl = EditorGUILayout.TextField("PrivacyUrl", privacyUrl);
  107. downloadUrl = EditorGUILayout.TextField(new GUIContent("Hot Patch DownloadUrl", "HTTP(S) resource directory or full manifest.json URL. Use 资源构建/一键打包资源 to export the DLL and manifest."), downloadUrl);
  108. hotPatchAssembly = (AssemblyDefinitionAsset)EditorGUILayout.ObjectField(
  109. new GUIContent("Hot Patch Assembly", "Select the game runtime asmdef. Save synchronizes the HybridCLR hot-update assembly settings."),
  110. hotPatchAssembly, typeof(AssemblyDefinitionAsset), false);
  111. EditorGUILayout.LabelField("Saved Assembly", settings.HotPatchAssemblyName);
  112. gameSceneName = EditorGUILayout.TextField(new GUIContent("Game Scene Name", "Enter a unique scene name without .unity. It is used to build the scene bundle, which Launch opens at runtime."), gameSceneName);
  113. EditorGUILayout.Space();
  114. using (new EditorGUILayout.HorizontalScope())
  115. {
  116. if (GUILayout.Button("Reload")) LoadSettings();
  117. if (GUILayout.Button("Save")) SaveSettings();
  118. using (new EditorGUI.DisabledScope(S3UploadController.IsUploading))
  119. if (GUILayout.Button("一键打包资源")) EditorApplication.ExecuteMenuItem("资源构建/一键打包资源");
  120. }
  121. using (new EditorGUI.DisabledScope(S3UploadController.IsUploading || EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode || BuildPipeline.isBuildingPlayer))
  122. {
  123. if (GUILayout.Button("上传资源")) S3UploadController.ChooseAndUpload(downloadUrl);
  124. try { EditorGUILayout.LabelField("上传目标", "s3://" + S3UploadSettings.Bucket + "/" + S3ResourceUploader.TargetPrefix(downloadUrl) + "/"); }
  125. catch (ArgumentException) { EditorGUILayout.LabelField("上传目标", "请设置包含目录的 DownloadUrl"); }
  126. DrawS3Settings();
  127. }
  128. DrawUsageHelp();
  129. EditorGUILayout.EndScrollView();
  130. }
  131. private void DrawS3Settings()
  132. {
  133. showS3Settings = EditorGUILayout.Foldout(showS3Settings, "S3 上传配置(仅本机)", true);
  134. if (!showS3Settings) return;
  135. if (s3Bucket == null)
  136. {
  137. s3Bucket = S3UploadSettings.Bucket; s3Region = S3UploadSettings.Region;
  138. var credentials = S3UploadSettings.LoadCredentials();
  139. s3AccessKey = credentials.AccessKey ?? ""; s3SecretKey = credentials.SecretKey ?? ""; s3SessionToken = credentials.SessionToken ?? "";
  140. }
  141. s3Bucket = EditorGUILayout.TextField("Bucket", s3Bucket);
  142. s3Region = EditorGUILayout.TextField("Region", s3Region);
  143. s3AccessKey = EditorGUILayout.TextField("Access Key", s3AccessKey);
  144. s3SecretKey = EditorGUILayout.PasswordField("Secret Key", s3SecretKey);
  145. s3SessionToken = EditorGUILayout.PasswordField("Session Token (optional)", s3SessionToken);
  146. EditorGUILayout.HelpBox("凭据保存在本机 ~/.aws/credentials 的 app-runtimes 配置中,不进入项目或安装包。上传使用当前 DownloadUrl 的最后一级目录。", MessageType.Info);
  147. if (GUILayout.Button("保存 S3 配置"))
  148. {
  149. try
  150. {
  151. S3UploadSettings.Save(s3Bucket, s3Region, new S3UploadCredentials { AccessKey = s3AccessKey, SecretKey = s3SecretKey, SessionToken = s3SessionToken });
  152. ShowNotification(new GUIContent("S3 配置已保存到本机"));
  153. }
  154. catch (Exception exception) { ShowNotification(new GUIContent(exception.Message)); }
  155. }
  156. }
  157. private sealed class FontSizeScope : IDisposable
  158. {
  159. private readonly Dictionary<GUIStyle, int> originalSizes = new Dictionary<GUIStyle, int>();
  160. internal FontSizeScope(int increase)
  161. {
  162. var styles = new[]
  163. {
  164. EditorStyles.label, EditorStyles.boldLabel, EditorStyles.textField,
  165. EditorStyles.foldout, EditorStyles.helpBox, EditorStyles.textArea,
  166. GUI.skin.button
  167. };
  168. foreach (var style in styles)
  169. {
  170. if (originalSizes.ContainsKey(style)) continue;
  171. originalSizes.Add(style, style.fontSize);
  172. var defaultSize = style.font != null && style.font.fontSize > 0
  173. ? style.font.fontSize : 12;
  174. style.fontSize = (style.fontSize > 0 ? style.fontSize : defaultSize) + increase;
  175. }
  176. }
  177. public void Dispose()
  178. {
  179. foreach (var entry in originalSizes)
  180. entry.Key.fontSize = entry.Value;
  181. }
  182. }
  183. private void DrawUsageHelp()
  184. {
  185. EditorGUILayout.Space(12);
  186. showTestUrlHelp = EditorGUILayout.Foldout(showTestUrlHelp, "Test URL Setup (iOS)", true);
  187. if (showTestUrlHelp)
  188. {
  189. EditorGUILayout.HelpBox(
  190. "After exporting the iOS project, add TestUserID under the main App Target > Info in Xcode. Set its type to String and" +
  191. " its value to the complete test URL (for example, https://example.com/test/).\n" +
  192. "Alternatively, add the following entries directly inside the root <dict> in Info.plist.",
  193. MessageType.Info);
  194. DrawExample(TestUrlExample, "Copy Info.plist Example");
  195. EditorGUILayout.HelpBox(
  196. "iOS reads TestUserID at startup and uses the test URL if it is not empty. Rebuild and launch the app after changing it.\n" +
  197. "Remove the key or clear its value to restore the normal flow. TestUrl is always empty on Android and in the Unity Editor.",
  198. MessageType.None);
  199. }
  200. EditorGUILayout.Space(8);
  201. showUsageHelp = EditorGUILayout.Foldout(showUsageHelp, "使用注意事项", true);
  202. if (showUsageHelp)
  203. {
  204. EditorGUILayout.HelpBox(
  205. "1. 订阅 AppRuntimesEvents.OnPlatformOpen 事件,在回调中停止播放单机游戏的背景音乐。打开 WebView 时会触发该事件。\n\n" +
  206. "2. 操作步骤:Save >>> 一键打包资源 >>> 上传资源",
  207. MessageType.Info);
  208. }
  209. }
  210. private void DrawExample(string example, string copyLabel)
  211. {
  212. var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
  213. var height = style.CalcHeight(new GUIContent(example), Mathf.Max(200, position.width - 40));
  214. EditorGUILayout.SelectableLabel(example, style, GUILayout.Height(height));
  215. if (!string.IsNullOrEmpty(copyLabel) && GUILayout.Button(copyLabel))
  216. {
  217. EditorGUIUtility.systemCopyBuffer = example;
  218. ShowNotification(new GUIContent("Example copied"));
  219. }
  220. }
  221. private void SaveSettings()
  222. {
  223. if (string.IsNullOrWhiteSpace(gameSceneName))
  224. {
  225. ShowNotification(new GUIContent("Enter a game scene name"));
  226. return;
  227. }
  228. if (!string.IsNullOrWhiteSpace(downloadUrl) && (!Uri.TryCreate(downloadUrl.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")))
  229. {
  230. ShowNotification(new GUIContent("The hot patch URL must be an absolute HTTP(S) URL"));
  231. return;
  232. }
  233. if (!string.IsNullOrEmpty(addressError)) return;
  234. string encryptedAddress;
  235. try
  236. {
  237. encryptedAddress = string.IsNullOrEmpty(appAddress)
  238. ? string.Empty : ClientCrypto.EncryptString(appAddress);
  239. }
  240. catch (Exception)
  241. {
  242. addressError = "Failed to encrypt AppAddress. Settings were not saved. Enter the address again and retry.";
  243. return;
  244. }
  245. try { HotPatchAssemblySelection.Save(settings, hotPatchAssembly); }
  246. catch (Exception exception)
  247. {
  248. ShowNotification(new GUIContent(exception.Message));
  249. Debug.LogError("[HotPatch] Settings were not saved: " + exception.Message);
  250. return;
  251. }
  252. Undo.RecordObject(settings, "Save AppSettings");
  253. settings.AppAddress = encryptedAddress;
  254. settings.AppChannel = appChannel;
  255. settings.PrivacyUrl = privacyUrl;
  256. settings.DownloadUrl = (downloadUrl ?? string.Empty).Trim();
  257. settings.GameSceneName = gameSceneName.Trim();
  258. EditorUtility.SetDirty(settings);
  259. if (facebook != null)
  260. {
  261. facebook.Update();
  262. WriteFacebookValue("appLabels", appName);
  263. WriteFacebookValue("appIds", appId);
  264. WriteFacebookValue("clientTokens", clientToken);
  265. facebook.ApplyModifiedProperties();
  266. EditorUtility.SetDirty(facebook.targetObject);
  267. }
  268. AssetDatabase.SaveAssets();
  269. ShowNotification(new GUIContent("Settings saved"));
  270. }
  271. }