XRSettingsManager.cs 20.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

using UnityEditor;
using UnityEditor.PackageManager;

using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.XR.Management;

namespace UnityEditor.XR.Management
{
    class XRSettingsManager : SettingsProvider
    {

        struct Content
        {
            internal static GUIContent s_LoaderInitOnStartLabel = new GUIContent("Initialize on Startup");
            internal static GUIContent s_ProvidersToInstall = new GUIContent("Known XR Plugin Providers");
            internal static GUIContent s_LookingForProviders = new GUIContent("Looking for installable provider packages... ");
            internal static GUIContent s_NoInstallablePackages = new GUIContent("No installable provider packages found.");
            internal static string k_NeedToInstallAProvider = "Before you can use the XR system you need to install at least one provider from the list.";
            internal static string k_ProvidersUnavailable = "We are unable to find any providers usable within Unity at this time. XR is currently unavailable to use.";
            internal static GUIContent s_InstallPackage = new GUIContent("Install");
            internal static GUIContent s_InstallingPackage = new GUIContent("Installing");
            internal static GUIContent s_InstalledPackage = new GUIContent("Installed");
            internal static GUIContent s_LocalPackage = new GUIContent("Local Only");
        }

        internal static GUIStyle GetStyle(string styleName)
        {
            GUIStyle s = GUI.skin.FindStyle(styleName) ?? EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle(styleName);
            if (s == null)
            {
                Debug.LogError("Missing built-in guistyle " + styleName);
                s = GUI.skin.box;
            }
            return s;
        }

        static string s_SettingsRootTitle = "Project/XR Plugin Management";
        static XRSettingsManager s_SettingsManager = null;


        SerializedObject m_SettingsWrapper;

        private Dictionary<BuildTargetGroup, XRManagerSettingsEditor> CachedSettingsEditor = new Dictionary<BuildTargetGroup, XRManagerSettingsEditor>();

        private bool m_HasCompletedRequest = false;
        private bool m_HasKNownLocalLoaders = false;
        private bool m_HasProviders = false;
        private bool m_HasInstalledProviders = false;

        struct XRPackageInformation
        {
            internal PackageManager.PackageInfo uninstalledPackageInfo;
            internal bool isInstalled;
            internal bool isLocalOnly;
        }

        private Dictionary<string, XRPackageInformation> m_XRPackages = new Dictionary<string, XRPackageInformation>();
        private PackageManager.Requests.SearchRequest m_PackageRepositoryListRequest = null;
        private PackageManager.Requests.ListRequest m_LocalPackageListRequest = null;
        private PackageManager.Requests.AddRequest m_InstallingPackage = null;
        private string m_InstallingPackageName = "";

        private BuildTargetGroup m_LastBuildTargetGroup = BuildTargetGroup.Unknown;

        static XRGeneralSettingsPerBuildTarget currentSettings
        {
            get
            {
                XRGeneralSettingsPerBuildTarget generalSettings = null;
                EditorBuildSettings.TryGetConfigObject(XRGeneralSettings.k_SettingsKey, out generalSettings);
                if (generalSettings == null)
                {
                    lock(s_SettingsManager)
                    {
                        EditorBuildSettings.TryGetConfigObject(XRGeneralSettings.k_SettingsKey, out generalSettings);
                        if (generalSettings == null)
                        {
                            string searchText = "t:XRGeneralSettings";
                            string[] assets = AssetDatabase.FindAssets(searchText);
                            if (assets.Length > 0)
                            {
                                string path = AssetDatabase.GUIDToAssetPath(assets[0]);
                                generalSettings = AssetDatabase.LoadAssetAtPath(path, typeof(XRGeneralSettingsPerBuildTarget)) as XRGeneralSettingsPerBuildTarget;
                            }
                        }

                        if (generalSettings == null)
                        {
                            generalSettings = ScriptableObject.CreateInstance(typeof(XRGeneralSettingsPerBuildTarget)) as XRGeneralSettingsPerBuildTarget;
                            string assetPath = EditorUtilities.GetAssetPathForComponents(EditorUtilities.s_DefaultGeneralSettingsPath);
                            if (!string.IsNullOrEmpty(assetPath))
                            {
                                assetPath = Path.Combine(assetPath, "XRGeneralSettings.asset");
                                AssetDatabase.CreateAsset(generalSettings, assetPath);
                            }
                        }

                        EditorBuildSettings.AddConfigObject(XRGeneralSettings.k_SettingsKey, generalSettings, true);

                    }
                }
                return generalSettings;
            }
        }

        [UnityEngine.Internal.ExcludeFromDocs]
        XRSettingsManager(string path, SettingsScope scopes = SettingsScope.Project) : base(path, scopes)
        {
            m_HasCompletedRequest = false;
            m_XRPackages.Clear();
            m_PackageRepositoryListRequest = Client.SearchAll();
            m_LocalPackageListRequest = Client.List();

            EditorApplication.update += UpdatePackageManagerQuery;
        }

        [SettingsProvider]
        [UnityEngine.Internal.ExcludeFromDocs]
        static SettingsProvider Create()
        {
            if (s_SettingsManager == null)
            {
                s_SettingsManager = new XRSettingsManager(s_SettingsRootTitle);
            }

            return s_SettingsManager;
        }

        [SettingsProviderGroup]
        [UnityEngine.Internal.ExcludeFromDocs]
        static SettingsProvider[] CreateAllChildSettingsProviders()
        {
            List<SettingsProvider> ret = new List<SettingsProvider>();
            if (s_SettingsManager != null)
            {
                var ats = TypeLoaderExtensions.GetAllTypesWithAttribute<XRConfigurationDataAttribute>();
                foreach (var at in ats)
                {
                    XRConfigurationDataAttribute xrbda = at.GetCustomAttributes(typeof(XRConfigurationDataAttribute), true)[0] as XRConfigurationDataAttribute;
                    string settingsPath = String.Format("{1}/{0}", xrbda.displayName, s_SettingsRootTitle);
                    var resProv = new XRConfigurationProvider(settingsPath, xrbda.buildSettingsKey, at);
                    ret.Add(resProv);
                }
            }

            // LIH Package Provider
            string settingsPathLIH = String.Format("{1}/{0}", "Input Helpers", s_SettingsRootTitle);
            var lihProv = new InputHelpersConfigurationProvider(settingsPathLIH);
            ret.Add(lihProv);
            return ret.ToArray();
        }

        void InitEditorData(ScriptableObject settings)
        {
            if (settings != null)
            {
                m_SettingsWrapper = new SerializedObject(settings);
            }
            EditorApplication.update += UpdatePackageManagerQuery;
        }

        void UpdatePackageManagerQuery()
        {
            Repaint();
            EditorApplication.update -= UpdatePackageManagerQuery;

            if (m_PackageRepositoryListRequest == null)
                return;

            if (!m_PackageRepositoryListRequest.IsCompleted || !m_LocalPackageListRequest.IsCompleted)
            {
                EditorApplication.update += UpdatePackageManagerQuery;
                return;
            }

            m_HasCompletedRequest = true;
            m_HasInstalledProviders = false;

            if (m_PackageRepositoryListRequest.Status != StatusCode.Success)
            {
                m_HasProviders = false;
                m_PackageRepositoryListRequest = null;
                return;
            }

            foreach (var pinfo in m_LocalPackageListRequest.Result)
            {
                var xrp = from keyword in pinfo.keywords
                    where String.Compare("xreditorsubsystem", keyword, true) == 0
                    select keyword;

                if (xrp.Any())
                {
                    XRPackageInformation xrpinfo = new XRPackageInformation();
                    xrpinfo.uninstalledPackageInfo = pinfo;
                    xrpinfo.isInstalled = true;
                    xrpinfo.isLocalOnly = true;
                    m_HasInstalledProviders = true;
                    m_XRPackages.Add(pinfo.name, xrpinfo);
                }
            }

            foreach (var pinfo in m_PackageRepositoryListRequest.Result)
            {
                if (m_XRPackages.ContainsKey(pinfo.name))
                {
                    XRPackageInformation xrpinfo;
                    if (m_XRPackages.TryGetValue(pinfo.name, out xrpinfo))
                    {
                        xrpinfo.isLocalOnly = false;
                        m_XRPackages[pinfo.name] = xrpinfo;
                    }
                    continue;
                }

                var xrp = from keyword in pinfo.keywords
                    where String.Compare("xreditorsubsystem", keyword, true) == 0
                    select keyword;

                if (xrp.Any())
                {
                    XRPackageInformation xrpinfo = new XRPackageInformation();
                    xrpinfo.uninstalledPackageInfo = pinfo;
                    xrpinfo.isInstalled = false;
                    m_XRPackages.Add(pinfo.name, xrpinfo);
               }
            }

            List<XRLoaderInfo> onDiskLoaderInfos = new List<XRLoaderInfo>();
            XRLoaderInfo.GetAllKnownLoaderInfos(onDiskLoaderInfos);
            m_HasKNownLocalLoaders = onDiskLoaderInfos.Any();

            m_HasProviders = m_XRPackages.Any();
            m_PackageRepositoryListRequest = null;
        }

        void UpdatePackageInstallationQuery()
        {
            Repaint();
            EditorApplication.update -= UpdatePackageInstallationQuery;

            if (m_InstallingPackage == null)
                return;

            if (!m_InstallingPackage.IsCompleted)
            {
                EditorApplication.update += UpdatePackageInstallationQuery;
                return;
            }

            if (m_InstallingPackage.Status != StatusCode.Success)
            {
                // TODO Track installation error...
                m_InstallingPackage = null;
                m_InstallingPackageName = "";
                return;
            }

            try
            {
                PackageManager.PackageInfo pinfo = m_InstallingPackage.Result;

                XRPackageInformation xrpinfo;
                bool addPackage = false;

                if (!m_XRPackages.TryGetValue(pinfo.name, out xrpinfo))
                {
                    xrpinfo.uninstalledPackageInfo = pinfo;
                    xrpinfo.isInstalled = false;
                    addPackage = true;
                }

                string tempPath = $"Packages/{pinfo.name}/package.json";
                var packagePath = Path.GetFullPath(tempPath);

                if (File.Exists(packagePath))
                {
                    xrpinfo.isInstalled = true;
                    m_HasInstalledProviders = true;
                }

                if (addPackage)
                    m_XRPackages.Add(pinfo.name, xrpinfo);
            }
            catch (Exception)
            {
                // TODO Track creation error...
            }

            m_InstallingPackage = null;
            m_InstallingPackageName = "";
        }


        /// <summary>See <see href="https://docs.unity3d.com/ScriptReference/SettingsProvider.html">SettingsProvider documentation</see>.</summary>
        public override void OnActivate(string searchContext, VisualElement rootElement)
        {
            InitEditorData(currentSettings);
        }

        /// <summary>See <see href="https://docs.unity3d.com/ScriptReference/SettingsProvider.html">SettingsProvider documentation</see>.</summary>
        public override void OnDeactivate()
        {
            EditorApplication.update -= UpdatePackageManagerQuery;
            EditorApplication.update -= UpdatePackageInstallationQuery;
            m_SettingsWrapper = null;
            CachedSettingsEditor.Clear();
        }

        private void DisplayProviderSelectionUI()
        {
            EditorGUI.BeginDisabledGroup(!m_HasProviders);
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField(Content.s_ProvidersToInstall, GetStyle("BoldLabel"));
            EditorGUILayout.Space();

            using (new EditorGUILayout.VerticalScope(GUI.skin.box, GUILayout.ExpandWidth(true)))
            {

                if (!m_HasCompletedRequest)
                {
                    EditorGUILayout.LabelField(Content.s_LookingForProviders);
                }
                else
                {
                    if (m_XRPackages.Any())
                    {
                        bool isInstalling = !String.IsNullOrEmpty(m_InstallingPackageName);

                        EditorGUI.BeginDisabledGroup(isInstalling);
                        foreach (var kv in m_XRPackages)
                        {
                            var isLocalOnly = kv.Value.isLocalOnly;
                            var isInstalled = kv.Value.isInstalled;
                            var pinfo = kv.Value.uninstalledPackageInfo;
                            EditorGUILayout.BeginHorizontal();
                            EditorGUILayout.LabelField(pinfo.displayName, GetStyle("label"));
                            if (isLocalOnly)
                            {
                                EditorGUILayout.LabelField(Content.s_LocalPackage, GUILayout.Width(100));
                            }
                            else if (isInstalling && String.Compare(m_InstallingPackageName, pinfo.name) == 0)
                            {
                                EditorGUILayout.LabelField(Content.s_InstallingPackage, GUILayout.Width(100));
                            }
                            else if (isInstalled)
                            {
                                EditorGUILayout.LabelField(Content.s_InstalledPackage, GUILayout.Width(100));
                            }
                            else
                            {
                                if (GUILayout.Button(Content.s_InstallPackage, GUILayout.Width(100)))
                                {
                                    m_InstallingPackageName = pinfo.name;
                                    m_InstallingPackage = PackageManager.Client.Add(pinfo.name);
                                    EditorApplication.update += UpdatePackageInstallationQuery;
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        EditorGUI.EndDisabledGroup();
                    }
                    else
                    {
                        EditorGUILayout.LabelField(Content.s_NoInstallablePackages);
                    }
                }
            }

            EditorGUILayout.EndVertical();
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.Space();

        }

        private void DisplayLoaderSelectionUI()
        {
            if (!m_HasCompletedRequest)
                return;

            if (!m_HasKNownLocalLoaders)
            {
                if (!m_XRPackages.Any())
                {
                    EditorGUILayout.HelpBox(Content.k_ProvidersUnavailable, MessageType.Error);
                    return;
                }

                if (!m_HasInstalledProviders)
                {
                    EditorGUILayout.HelpBox(Content.k_NeedToInstallAProvider, MessageType.Warning);
                    return;
                }
            }

            BuildTargetGroup buildTargetGroup = EditorGUILayout.BeginBuildTargetSelectionGrouping();
            bool buildTargetChanged = m_LastBuildTargetGroup != buildTargetGroup;
            if (buildTargetChanged)
                m_LastBuildTargetGroup = buildTargetGroup;

            XRGeneralSettings settings = currentSettings.SettingsForBuildTarget(buildTargetGroup);
            if (settings == null)
            {
                settings = ScriptableObject.CreateInstance<XRGeneralSettings>() as XRGeneralSettings;
                currentSettings.SetSettingsForBuildTarget(buildTargetGroup, settings);
                settings.name = $"{buildTargetGroup.ToString()} Settings";
                AssetDatabase.AddObjectToAsset(settings, AssetDatabase.GetAssetOrScenePath(currentSettings));
            }

            var serializedSettingsObject = new SerializedObject(settings);
            serializedSettingsObject.Update();

            SerializedProperty initOnStart = serializedSettingsObject.FindProperty("m_InitManagerOnStart");
            EditorGUILayout.PropertyField(initOnStart, Content.s_LoaderInitOnStartLabel);

            SerializedProperty loaderProp = serializedSettingsObject.FindProperty("m_LoaderManagerInstance");

            if (!CachedSettingsEditor.ContainsKey(buildTargetGroup))
            {
                CachedSettingsEditor.Add(buildTargetGroup, null);
            }

            if (loaderProp.objectReferenceValue == null)
            {
                var xrManagerSettings = ScriptableObject.CreateInstance<XRManagerSettings>() as XRManagerSettings;
                xrManagerSettings.name = $"{buildTargetGroup.ToString()} Providers";
                AssetDatabase.AddObjectToAsset(xrManagerSettings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                loaderProp.objectReferenceValue = xrManagerSettings;
                serializedSettingsObject.ApplyModifiedProperties();
            }

            var obj = loaderProp.objectReferenceValue;

            if (obj != null)
            {
                loaderProp.objectReferenceValue = obj;

                if(CachedSettingsEditor[buildTargetGroup] == null)
                {
                    CachedSettingsEditor[buildTargetGroup] = Editor.CreateEditor(obj) as XRManagerSettingsEditor;

                    if (CachedSettingsEditor[buildTargetGroup] == null)
                    {
                        Debug.LogError("Failed to create a view for XR Manager Settings Instance");
                    }
                }

                if (CachedSettingsEditor[buildTargetGroup] != null)
                {
                    if (buildTargetChanged)
                    {
                        CachedSettingsEditor[buildTargetGroup].BuildTarget = buildTargetGroup;
                        CachedSettingsEditor[buildTargetGroup].Reload();
                    }
                    CachedSettingsEditor[buildTargetGroup].OnInspectorGUI();
                }
            }
            else if (obj == null)
            {
                settings.AssignedSettings = null;
                loaderProp.objectReferenceValue = null;
            }

            EditorGUILayout.EndBuildTargetSelectionGrouping();

            serializedSettingsObject.ApplyModifiedProperties();
        }

        /// <summary>See <see href="https://docs.unity3d.com/ScriptReference/SettingsProvider.html">SettingsProvider documentation</see>.</summary>
        public override void OnGUI(string searchContext)
        {
            if (m_SettingsWrapper != null  && m_SettingsWrapper.targetObject != null)
            {
                m_SettingsWrapper.Update();

                EditorGUILayout.Space();

                DisplayLoaderSelectionUI();

                EditorGUILayout.Space();

                DisplayProviderSelectionUI();

                m_SettingsWrapper.ApplyModifiedProperties();
            }

            base.OnGUI(searchContext);
        }
    }
}