text
stringlengths 7
35.3M
| id
stringlengths 11
185
| metadata
dict | __index_level_0__
int64 0
2.14k
|
---|---|---|---|
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Analytics;
namespace UnityEditor.PackageManager.UI.Internal
{
[AnalyticInfo(eventName: k_EventName, vendorKey: k_VendorKey)]
internal class PackageManagerFiltersAnalytics : IAnalytic
{
private const string k_EventName = "packageManagerWindowFilters";
private const string k_VendorKey = "unity.package-manager-ui";
[Serializable]
private class Data : IAnalytic.IData
{
public string filter_tab;
public string order_by;
public string status;
public string[] categories;
public string[] labels;
}
private Data m_Data;
private PackageManagerFiltersAnalytics(PageFilters filters)
{
var servicesContainer = ServicesContainer.instance;
var filterTab = servicesContainer.Resolve<IPageManager>().activePage.id;
m_Data = new Data
{
filter_tab = filterTab,
order_by = filters.sortOption.ToString(),
status = filters.status.ToString(),
categories = filters.categories.ToArray(),
labels = filters.labels.ToArray()
};
}
public bool TryGatherData(out IAnalytic.IData data, out Exception error)
{
error = null;
data = m_Data;
return data != null;
}
public static void SendEvent(PageFilters filters)
{
var editorAnalyticsProxy = ServicesContainer.instance.Resolve<IEditorAnalyticsProxy>();
editorAnalyticsProxy.SendAnalytic(new PackageManagerFiltersAnalytics(filters));
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerFiltersAnalytics.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerFiltersAnalytics.cs",
"repo_id": "UnityCsReference",
"token_count": 786
} | 400 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor.Scripting.ScriptCompilation;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class AssetStorePackageVersion : BasePackageVersion
{
[SerializeField]
private string m_Category;
[SerializeField]
private List<UIError> m_Errors;
[SerializeField]
private string m_LocalPath;
[SerializeField]
private long m_UploadId;
[SerializeField]
private List<SemVersion> m_SupportedUnityVersions;
[SerializeField]
private AssetStoreImportedPackage m_ImportedPackage;
[SerializeField]
private string m_SupportedUnityVersionString;
private SemVersion? m_SupportedUnityVersion;
[SerializeField]
private List<PackageSizeInfo> m_SizeInfos;
// We want to distinguish version.author to the package.publisherName since publisher name is related to a product
// but author here refers to the author data in the PackageInfo, which is empty for an asset store package version
public override string author => string.Empty;
public override string category => m_Category;
public override string packageId => string.Empty;
public override string uniqueId => $"{package.uniqueId}@{uploadId}";
public override bool isInstalled => false;
public override bool isFullyFetched => true;
public override IEnumerable<UIError> errors => m_Errors;
public override bool isDirectDependency => true;
public override string localPath => m_LocalPath;
public override string versionString => m_VersionString;
public override long uploadId => m_UploadId;
public override SemVersion? supportedVersion => m_SupportedUnityVersion;
public override IEnumerable<SemVersion> supportedVersions => m_SupportedUnityVersions;
public override IEnumerable<PackageSizeInfo> sizes => m_SizeInfos;
public override IEnumerable<Asset> importedAssets => m_ImportedPackage;
public AssetStorePackageVersion(AssetStoreProductInfo productInfo, long uploadId = 0, AssetStoreLocalInfo localInfo = null, AssetStoreImportedPackage importedPackage = null)
{
m_Errors = new List<UIError>();
m_Tag = PackageTag.LegacyFormat;
// m_Description is the version level description from PackageInfo, so we set this field to empty here deliberately
// For asset store packages, we have the `productDescription` at the package level.
m_Description = string.Empty;
m_Category = productInfo?.category ?? string.Empty;
m_PublishNotes = localInfo?.publishNotes ?? string.Empty;
m_VersionString = importedPackage?.versionString ?? localInfo?.versionString ?? productInfo?.versionString ?? string.Empty;
m_UploadId = uploadId;
SemVersionParser.TryParse(m_VersionString.Trim(), out m_Version);
m_ImportedPackage = importedPackage;
var publishDateString = localInfo?.publishedDate ?? productInfo?.publishedDate ?? string.Empty;
m_PublishedDateTicks = !string.IsNullOrEmpty(publishDateString) ? DateTime.Parse(publishDateString).Ticks : 0;
m_DisplayName = !string.IsNullOrEmpty(productInfo?.displayName) ? productInfo.displayName : importedPackage?.displayName ?? string.Empty;
m_SupportedUnityVersions = new List<SemVersion>();
if (!string.IsNullOrEmpty(localInfo?.supportedVersion))
{
var simpleVersion = Regex.Replace(localInfo.supportedVersion, @"(?<major>\d+)\.(?<minor>\d+).(?<patch>\d+)[abfp].+", "${major}.${minor}.${patch}");
SemVersionParser.TryParse(simpleVersion.Trim(), out m_SupportedUnityVersion);
m_SupportedUnityVersionString = m_SupportedUnityVersion?.ToString();
}
else if (productInfo?.supportedVersions?.Any() ?? false)
{
foreach (var v in productInfo.supportedVersions)
if (SemVersionParser.TryParse(v, out var parsedSemVer))
m_SupportedUnityVersions.Add(parsedSemVer.Value);
m_SupportedUnityVersions.Sort((left, right) => left.CompareTo(right));
m_SupportedUnityVersion = m_SupportedUnityVersions.LastOrDefault();
m_SupportedUnityVersionString = m_SupportedUnityVersion?.ToString();
}
m_SizeInfos = new List<PackageSizeInfo>(productInfo?.sizeInfos ?? Enumerable.Empty<PackageSizeInfo>());
m_SizeInfos.Sort((left, right) => left.supportedUnityVersion.CompareTo(right.supportedUnityVersion));
var state = productInfo?.state ?? string.Empty;
if (state.Equals("published", StringComparison.InvariantCultureIgnoreCase))
m_Tag |= PackageTag.Published;
else if (state.Equals("disabled", StringComparison.InvariantCultureIgnoreCase))
m_Tag |= PackageTag.Disabled;
m_LocalPath = localInfo?.packagePath ?? string.Empty;
}
public override void OnAfterDeserialize()
{
base.OnAfterDeserialize();
SemVersionParser.TryParse(m_SupportedUnityVersionString, out m_SupportedUnityVersion);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageVersion.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageVersion.cs",
"repo_id": "UnityCsReference",
"token_count": 2119
} | 401 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal;
internal enum Icon
{
None,
InProjectPage,
UpdatesPage,
UnityRegistryPage,
MyAssetsPage,
BuiltInPage,
ServicesPage,
MyRegistriesPage,
Refresh,
Folder,
Installed,
Download,
Import,
Customized,
Pause,
Resume,
Cancel,
Error,
Warning,
Success
}
internal static class IconExtension
{
private const string k_IconClassNamePrefix = "icon";
public static string ClassName(this Icon icon) => k_IconClassNamePrefix + icon;
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/Icon.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/Icon.cs",
"repo_id": "UnityCsReference",
"token_count": 270
} | 402 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEditor.PackageManager.UI
{
internal interface IPackage
{
string uniqueId { get; }
string name { get; }
IEnumerable<IPackageVersion> versions { get; }
}
}
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IPackage : UI.IPackage
{
IProduct product { get; }
string displayName { get; }
new IVersionList versions { get; }
PackageState state { get; }
PackageProgress progress { get; }
bool isDiscoverable { get; }
// package level errors (for upm this refers to operation errors that are separate from the package info)
IEnumerable<UIError> errors { get; }
bool hasEntitlements { get; }
bool hasEntitlementsError { get; }
string deprecationMessage { get; }
bool isDeprecated { get; }
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPackage.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPackage.cs",
"repo_id": "UnityCsReference",
"token_count": 396
} | 403 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.PackageManager.UI.Internal;
internal class ImportUpdateAction : ImportActionBase
{
public ImportUpdateAction(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IApplicationProxy application, IUnityConnectProxy unityConnect)
: base(operationDispatcher, assetStoreDownloadManager, application, unityConnect)
{
}
protected override string analyticEventName => "importUpdate";
public override bool isRecommended => true;
public override Icon icon => Icon.Import;
public override bool IsVisible(IPackageVersion version)
{
var versions = version.package.versions;
return base.IsVisible(version) &&
versions.imported != null &&
versions.importAvailable.uploadId == versions.recommended?.uploadId &&
versions.importAvailable.uploadId != versions.imported.uploadId;
}
public override string GetTooltip(IPackageVersion version, bool isInProgress)
{
var result = string.Format(L10n.Tr("Click to import updates from the {0} into your project."), version.GetDescriptor());
if (IsAdaptedPackageUpdate(version.package.versions.importAvailable, version.package.versions.imported))
result += L10n.Tr("\n*This package update has been adapted for this current version of Unity.");
return result;
}
public override string GetText(IPackageVersion version, bool isInProgress)
{
var importAvailable = version.package.versions.importAvailable;
if (string.IsNullOrEmpty(importAvailable?.versionString))
return L10n.Tr("Import update");
return string.Format(IsAdaptedPackageUpdate(importAvailable, version.package.versions.imported) ? L10n.Tr("Import update {0}* to project") : L10n.Tr("Import update {0} to project"), importAvailable.versionString);
}
// Adapted package update refers to the edge case where a publisher can publish different packages for different unity versions, resulting us
// sometimes recommending user to update to a package with the same version string (or even lower version string)
private static bool IsAdaptedPackageUpdate(IPackageVersion importAvailable, IPackageVersion imported)
{
return importAvailable?.versionString == imported?.versionString || importAvailable?.uploadId < imported?.uploadId;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportUpdateAction.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportUpdateAction.cs",
"repo_id": "UnityCsReference",
"token_count": 785
} | 404 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageLink
{
public IPackageVersion version { get; }
public PackageLink(IPackageVersion version)
{
this.version = version;
}
public string displayName { get; set; }
public string url { get; set; }
public string analyticsEventName { get; set; }
public string offlinePath { get; set; }
public bool isEmpty => string.IsNullOrEmpty(url) && string.IsNullOrEmpty(offlinePath);
public virtual bool isVisible => !isEmpty;
public virtual bool isEnabled => true;
public virtual string tooltip => url;
internal enum ContextMenuAction
{
OpenInBrowser,
OpenLocally,
}
public virtual ContextMenuAction[] contextMenuActions => Array.Empty<ContextMenuAction>();
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageLink.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageLink.cs",
"repo_id": "UnityCsReference",
"token_count": 402
} | 405 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class PageFilters : IEquatable<PageFilters>
{
public enum Status
{
None,
Unlabeled,
Downloaded,
Imported,
UpdateAvailable,
Hidden,
Deprecated,
SubscriptionBased,
}
public Status status;
public PageSortOption sortOption;
private List<string> m_Categories = new();
private List<string> m_Labels = new();
public List<string> categories
{
get => m_Categories;
set => m_Categories = value ?? new List<string>();
}
public List<string> labels
{
get => m_Labels;
set => m_Labels = value ?? new List<string>();
}
public virtual bool isFilterSet => status != Status.None || categories.Any() || labels.Any();
public PageFilters Clone()
{
return (PageFilters)MemberwiseClone();
}
public bool Equals(PageFilters other)
{
return other != null &&
status == other.status &&
sortOption == other.sortOption &&
categories.Count == other.categories.Count && categories.SequenceEqual(other.categories) &&
labels.Count == other.labels.Count && labels.SequenceEqual(other.labels);
}
}
internal static class PageFiltersExtension
{
public static string GetDisplayName(this PageFilters.Status value)
{
return value switch
{
PageFilters.Status.Unlabeled => L10n.Tr("Unlabeled"),
PageFilters.Status.Downloaded => L10n.Tr("Downloaded"),
PageFilters.Status.Imported => L10n.Tr("Imported"),
PageFilters.Status.UpdateAvailable => L10n.Tr("Update available"),
PageFilters.Status.Hidden => L10n.Tr("Hidden"),
PageFilters.Status.Deprecated => L10n.Tr("Deprecated"),
PageFilters.Status.SubscriptionBased => L10n.Tr("Subscription based"),
PageFilters.Status.None => string.Empty,
_ => string.Empty
};
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageFilters.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageFilters.cs",
"repo_id": "UnityCsReference",
"token_count": 1147
} | 406 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class VisualState : IEquatable<VisualState>
{
public string packageUniqueId;
public string groupName;
public bool visible;
public bool lockedByDefault;
public bool userUnlocked;
public bool isLocked => lockedByDefault && !userUnlocked;
public VisualState(string packageUniqueId, string groupName = "", bool lockedByDefault = false)
{
this.packageUniqueId = packageUniqueId;
this.groupName = groupName;
this.lockedByDefault = lockedByDefault;
visible = true;
userUnlocked = false;
}
public bool Equals(VisualState other)
{
return other != null
&& packageUniqueId == other.packageUniqueId
&& groupName == other.groupName
&& visible == other.visible
&& lockedByDefault == other.lockedByDefault
&& userUnlocked == other.userUnlocked;
}
public VisualState Clone()
{
return (VisualState)MemberwiseClone();
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/VisualState.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/VisualState.cs",
"repo_id": "UnityCsReference",
"token_count": 580
} | 407 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Diagnostics.CodeAnalysis;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface ISelectionProxy : IService
{
event Action onSelectionChanged;
UnityEngine.Object[] objects { get; set; }
UnityEngine.Object activeObject { get; set; }
}
[ExcludeFromCodeCoverage]
internal class SelectionProxy : BaseService<ISelectionProxy>, ISelectionProxy
{
public event Action onSelectionChanged = delegate {};
public SelectionProxy()
{
Selection.selectionChanged += OnSelectionChanged;
}
public UnityEngine.Object[] objects
{
get { return Selection.objects; }
set { Selection.objects = value; }
}
public UnityEngine.Object activeObject
{
get { return Selection.activeObject; }
set { Selection.activeObject = value; }
}
private void OnSelectionChanged()
{
onSelectionChanged?.Invoke();
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/SelectionProxy.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/SelectionProxy.cs",
"repo_id": "UnityCsReference",
"token_count": 471
} | 408 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEditorInternal;
using UnityEngine;
using UnityEditor.Scripting.ScriptCompilation;
using System.Linq;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class UpmPackageVersion : BasePackageVersion
{
private const string k_UnityPrefix = "com.unity.";
private const string k_UnityAuthor = "Unity Technologies";
[SerializeField]
private string m_Category;
public override string category => m_Category;
[SerializeField]
private bool m_IsFullyFetched;
public override bool isFullyFetched => m_IsFullyFetched;
[SerializeField]
private bool m_IsDirectDependency;
public override bool isDirectDependency => isFullyFetched && m_IsDirectDependency;
[SerializeField]
private List<UIError> m_Errors = new();
public override IEnumerable<UIError> errors => m_Errors;
[SerializeField]
private string m_PackageId;
public override string packageId => m_PackageId;
public override string uniqueId => m_PackageId;
[SerializeField]
private string m_Author;
public override string author => m_Author;
[SerializeField]
private RegistryType m_AvailableRegistry;
public override RegistryType availableRegistry => m_AvailableRegistry;
[SerializeField]
private PackageSource m_Source;
[SerializeField]
private DependencyInfo[] m_Dependencies;
public override DependencyInfo[] dependencies => m_Dependencies;
[SerializeField]
private DependencyInfo[] m_ResolvedDependencies;
public override DependencyInfo[] resolvedDependencies => m_ResolvedDependencies;
[SerializeField]
private EntitlementsInfo m_Entitlements;
public override EntitlementsInfo entitlements => m_Entitlements;
[SerializeField]
private bool m_HasErrorWithEntitlementMessage;
public override bool hasEntitlementsError => (hasEntitlements && !entitlements.isAllowed) || m_HasErrorWithEntitlementMessage;
public string sourcePath
{
get
{
if (HasTag(PackageTag.Local))
return m_PackageId.Substring(m_PackageId.IndexOf("@file:") + 6);
if (HasTag(PackageTag.Git))
return m_PackageId.Split(new[] { '@' }, 2)[1];
return null;
}
}
[SerializeField]
private bool m_IsInstalled;
public override bool isInstalled => m_IsInstalled;
[SerializeField]
private string m_ResolvedPath;
public override string localPath => m_ResolvedPath;
[SerializeField]
private string m_VersionInManifest;
public override string versionInManifest => m_VersionInManifest;
public override string versionString => isInvalidSemVerInManifest ? versionInManifest : m_VersionString;
// When packages are installed from path (git, local, custom) versionInManifest behaves differently so we don't consider them to have invalid SemVer
public override bool isInvalidSemVerInManifest => !string.IsNullOrEmpty(versionInManifest) && !HasTag(PackageTag.InstalledFromPath) &&
(!SemVersionParser.TryParse(versionInManifest, out var semVersion) || semVersion?.ToString() != versionInManifest);
public override long uploadId => 0;
[SerializeField]
private string m_DeprecationMessage;
public override string deprecationMessage => m_DeprecationMessage;
public UpmPackageVersion(PackageInfo packageInfo, bool isInstalled, SemVersion? version, string displayName, RegistryType availableRegistry)
{
m_Version = version;
m_VersionString = m_Version?.ToString();
m_DisplayName = displayName;
m_IsInstalled = isInstalled;
UpdatePackageInfo(packageInfo, availableRegistry);
}
public UpmPackageVersion(PackageInfo packageInfo, bool isInstalled, RegistryType availableRegistry)
{
SemVersionParser.TryParse(packageInfo.version, out m_Version);
m_VersionString = m_Version?.ToString();
m_DisplayName = packageInfo.displayName;
m_IsInstalled = isInstalled;
UpdatePackageInfo(packageInfo, availableRegistry);
}
internal void UpdatePackageInfo(PackageInfo packageInfo, RegistryType availableRegistry)
{
m_IsFullyFetched = m_Version?.ToString() == packageInfo.version;
m_AvailableRegistry = availableRegistry;
m_Source = packageInfo.source;
m_Category = packageInfo.category;
m_IsDirectDependency = packageInfo.isDirectDependency;
m_Name = packageInfo.name;
m_VersionInManifest = packageInfo.projectDependenciesEntry;
m_Entitlements = packageInfo.entitlements;
RefreshTags(packageInfo);
// For core packages, or packages that are bundled with Unity without being published, use Unity's build date
m_PublishedDateTicks = packageInfo.datePublished?.Ticks ?? 0;
if (m_PublishedDateTicks == 0 && packageInfo.source == PackageSource.BuiltIn)
m_PublishedDateTicks = new DateTime(1970, 1, 1).Ticks + InternalEditorUtility.GetUnityVersionDate() * TimeSpan.TicksPerSecond;
m_Author = HasTag(PackageTag.Unity) ? k_UnityAuthor : packageInfo.author?.name ?? string.Empty;
if (m_IsFullyFetched)
{
m_DisplayName = GetDisplayName(packageInfo);
m_PackageId = packageInfo.packageId;
if (HasTag(PackageTag.InstalledFromPath))
m_PackageId = m_PackageId.Replace("\\", "/");
ProcessErrors(packageInfo);
m_Dependencies = packageInfo.dependencies;
m_ResolvedDependencies = packageInfo.resolvedDependencies;
m_ResolvedPath = packageInfo.resolvedPath;
m_DeprecationMessage = packageInfo.deprecationMessage;
if (packageInfo.ExtractBuiltinDescription(out var result))
m_Description = result;
else
m_Description = packageInfo.description;
}
else
{
m_PackageId = FormatPackageId(name, version.ToString());
m_HasErrorWithEntitlementMessage = false;
m_Errors.Clear();
m_Dependencies = Array.Empty<DependencyInfo>();
m_ResolvedDependencies = Array.Empty<DependencyInfo>();
m_ResolvedPath = string.Empty;
m_Description = string.Empty;
}
}
public void SetInstalled(bool value)
{
m_IsInstalled = value;
RefreshTagsForLocalAndGit(m_Source);
}
private void RefreshTagsForLocalAndGit(PackageSource source)
{
m_Tag &= ~(PackageTag.Custom | PackageTag.VersionLocked | PackageTag.Local | PackageTag.Git);
if (!m_IsInstalled || source is PackageSource.BuiltIn or PackageSource.Registry)
return;
switch (source)
{
case PackageSource.Embedded:
m_Tag |= PackageTag.Custom | PackageTag.VersionLocked;
break;
case PackageSource.Local:
case PackageSource.LocalTarball:
m_Tag |= PackageTag.Local;
break;
case PackageSource.Git:
m_Tag |= PackageTag.Git | PackageTag.VersionLocked;
break;
}
}
private void RefreshTags(PackageInfo packageInfo)
{
m_Tag = PackageTag.UpmFormat;
// in the case of git/local packages, we always assume that the non-installed versions are from the registry
if (packageInfo.source == PackageSource.BuiltIn)
{
m_Tag |= PackageTag.Unity | PackageTag.VersionLocked;
switch (packageInfo.type)
{
case "module":
m_Tag |= PackageTag.BuiltIn;
break;
case "feature":
m_Tag |= PackageTag.Feature;
break;
}
}
else
RefreshTagsForLocalAndGit(packageInfo.source);
// We only tag a package as `Unity` when it's directly installed from registry. A package available on Unity registry can be installed
// through git or local file system but in those cases it is not considered a `Unity` package.
if (m_Source == PackageSource.Registry && m_AvailableRegistry == RegistryType.UnityRegistry)
m_Tag |= PackageTag.Unity;
// We use the logic below instead packageInfo.isDeprecated, since we don't do an extra fetch when we want to tag deprecated version in version history
// We want to know if a version is deprecated before we do the extra fetch
if (!HasTag(PackageTag.InstalledFromPath) && packageInfo.versions.deprecated.Contains(m_VersionString))
m_Tag |= PackageTag.Deprecated;
if (!HasTag(PackageTag.Unity) || HasTag(PackageTag.Deprecated) || isInvalidSemVerInManifest)
return;
var isLifecycleVersionValid = SemVersionParser.TryParse(packageInfo.unityLifecycle?.version, out var lifecycleVersionParsed);
if (m_Version?.HasPreReleaseVersionTag() == true)
{
// must match exactly to be release candidate
if (m_VersionString == packageInfo.unityLifecycle?.version)
m_Tag |= PackageTag.ReleaseCandidate;
else
m_Tag |= PackageTag.PreRelease;
}
else if ((version?.Major == 0 && string.IsNullOrEmpty(version?.Prerelease)) ||
m_Version?.IsExperimental() == true ||
"Preview".Equals(version?.Prerelease.Split('.')[0], StringComparison.InvariantCultureIgnoreCase))
m_Tag |= PackageTag.Experimental;
else if (isLifecycleVersionValid && m_Version?.IsEqualOrPatchOf(lifecycleVersionParsed) == true)
{
m_Tag |= PackageTag.Release;
}
}
public override string GetDescriptor(bool isFirstLetterCapitalized = false)
{
if (HasTag(PackageTag.Feature))
return isFirstLetterCapitalized ? L10n.Tr("Feature") : L10n.Tr("feature");
if (HasTag(PackageTag.BuiltIn))
return isFirstLetterCapitalized ? L10n.Tr("Built-in package") : L10n.Tr("built-in package");
return isFirstLetterCapitalized ? L10n.Tr("Package") : L10n.Tr("package");
}
private static string GetDisplayName(PackageInfo info)
{
return !string.IsNullOrEmpty(info.displayName) ? info.displayName : ExtractDisplayName(info.name);
}
public static string ExtractDisplayName(string packageName)
{
if (!packageName.StartsWith(k_UnityPrefix))
return packageName;
var displayName = packageName.Substring(k_UnityPrefix.Length).Replace("modules.", "");
displayName = string.Join(" ", displayName.Split('.'));
return new CultureInfo("en-US").TextInfo.ToTitleCase(displayName);
}
public static string FormatPackageId(string name, string version)
{
return $"{name.ToLower()}@{version}";
}
private void ProcessErrors(PackageInfo info)
{
m_HasErrorWithEntitlementMessage = info.errors.Any(error
=> error.errorCode == ErrorCode.Forbidden
&& error.message.IndexOf(EntitlementsErrorAndDeprecationChecker.k_NoSubscriptionUpmErrorMessage, StringComparison.InvariantCultureIgnoreCase) >= 0);
m_Errors.Clear();
if (hasEntitlementsError)
m_Errors.Add(isInstalled ? UIError.k_EntitlementError : UIError.k_EntitlementWarning);
foreach (var error in info.errors)
{
if (error.message.Contains(EntitlementsErrorAndDeprecationChecker.k_NotAcquiredUpmErrorMessage))
m_Errors.Add(new UIError(UIErrorCode.UpmError_NotAcquired, error.message));
else if (error.message.Contains(EntitlementsErrorAndDeprecationChecker.k_NotSignedInUpmErrorMessage))
m_Errors.Add(new UIError(UIErrorCode.UpmError_NotSignedIn, error.message));
else
m_Errors.Add(new UIError(error));
}
if (info.signature.status == SignatureStatus.Invalid)
m_Errors.Add(UIError.k_InvalidSignatureWarning);
else if (info.signature.status == SignatureStatus.Unsigned && name.StartsWith(k_UnityPrefix) &&
(info.source == PackageSource.LocalTarball ||
info.source == PackageSource.Registry && !info.registry.isDefault))
// Flag Unsigned packages on a non-default registry and local tarballs
// when the name starts with "com.unity." to prevent dependency confusion
m_Errors.Add(UIError.k_UnsignedUnityPackageWarning);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmPackageVersion.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmPackageVersion.cs",
"repo_id": "UnityCsReference",
"token_count": 6070
} | 409 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class ProgressBar : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new ProgressBar();
}
private IResourceLoader m_ResourceLoader;
static private double s_LastWidthTime;
private const double k_PaintInterval = 1f; // Time interval to repaint
private void ResolveDependencies()
{
var container = ServicesContainer.instance;
m_ResourceLoader = container.Resolve<IResourceLoader>();
}
public ProgressBar()
{
ResolveDependencies();
UIUtils.SetElementDisplay(this, false);
var root = m_ResourceLoader.GetTemplate("ProgressBar.uxml");
Add(root);
root.StretchToParentSize();
cache = new VisualElementCache(root);
currentProgressBar.style.width = Length.Percent(0);
}
public bool UpdateProgress(IOperation operation)
{
var showProgressBar = operation != null && operation.isProgressTrackable && operation.isProgressVisible;
UIUtils.SetElementDisplay(this, showProgressBar);
if (showProgressBar)
{
var currentTime = EditorApplication.timeSinceStartup;
var deltaTime = currentTime - s_LastWidthTime;
if (deltaTime >= k_PaintInterval)
{
var percentage = Mathf.Clamp01(operation.progressPercentage);
currentProgressBar.style.width = Length.Percent(percentage * 100.0f);
currentProgressBar.MarkDirtyRepaint();
s_LastWidthTime = currentTime;
}
if (operation.isInPause)
currentProgressState.text = L10n.Tr("Paused");
else if(operation.isInProgress)
currentProgressState.text = L10n.Tr("Downloading");
else
currentProgressState.text = string.Empty;
}
return showProgressBar;
}
private VisualElementCache cache { get; }
private VisualElement currentProgressBar { get { return cache.Get<VisualElement>("progressBarForeground"); } }
private Label currentProgressState { get { return cache.Get<Label>("currentProgressState"); } }
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/ProgressBar.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/ProgressBar.cs",
"repo_id": "UnityCsReference",
"token_count": 1164
} | 410 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class UpmFiltersWindow : PackageManagerFiltersWindow
{
protected override Vector2 GetSize(IPage page)
{
var height = k_FoldOutHeight + page.supportedStatusFilters.Count() * k_ToggleHeight;
return new Vector2(k_Width, Math.Min(height, k_MaxHeight));
}
protected override void ApplyFilters()
{
foreach (var toggle in m_StatusFoldOut.Children().OfType<Toggle>())
toggle.SetValueWithoutNotify(toggle.name == m_Filters.status.ToString());
}
protected override void DoDisplay(IPage page)
{
m_StatusFoldOut = new Foldout {text = L10n.Tr("Status"), name = k_StatusFoldOutName, classList = {k_FoldoutClass}};
foreach (var status in page.supportedStatusFilters)
{
var toggle = new Toggle(status.GetDisplayName()) {name = status.ToString(), classList = {k_ToggleClass}};
toggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
{
foreach (var t in m_StatusFoldOut.Children().OfType<Toggle>())
{
if (t == toggle)
continue;
t.SetValueWithoutNotify(false);
}
}
UpdateFiltersIfNeeded();
});
m_StatusFoldOut.Add(toggle);
}
m_Container.Add(m_StatusFoldOut);
}
private void UpdateFiltersIfNeeded()
{
var filters = m_Filters.Clone();
var selectedStatus = m_StatusFoldOut.Children().OfType<Toggle>().Where(toggle => toggle.value).Select(toggle => toggle.name).FirstOrDefault();
filters.status = !string.IsNullOrEmpty(selectedStatus) && Enum.TryParse(selectedStatus, out PageFilters.Status status) ? status : PageFilters.Status.None;
if (!filters.Equals(m_Filters))
{
m_Filters = filters;
UpdatePageFilters();
}
}
internal Foldout m_StatusFoldOut;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/Filters/UpmFiltersWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Filters/UpmFiltersWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1206
} | 411 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.PackageManager.UI.Internal
{
internal class NoActionsFoldout : MultiSelectFoldout
{
public NoActionsFoldout(IPageManager pageManager)
: base(new DeselectAction(pageManager, "deselectNoAction"))
{
headerTextTemplate = L10n.Tr("No common action available for {0}");
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/NoActionsFoldout.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/NoActionsFoldout.cs",
"repo_id": "UnityCsReference",
"token_count": 191
} | 412 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Globalization;
using System.Linq;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageDetailsOverviewTabContent : VisualElement
{
private const string k_EmptyDescriptionClass = "empty";
private const int k_maxDescriptionCharacters = 10000;
public PackageDetailsOverviewTabContent(IResourceLoader resourceLoader)
{
name = "packageOverviewContent";
var root = resourceLoader.GetTemplate("DetailsTabs/PackageDetailsOverviewTab.uxml");
Add(root);
m_Cache = new VisualElementCache(root);
}
public void Refresh(IPackageVersion version)
{
RefreshLabels(version);
RefreshSupportedUnityVersions(version);
RefreshSizeInfo(version);
RefreshPurchasedDate(version);
RefreshDescription(version);
}
private void RefreshLabels(IPackageVersion version)
{
var labels = version?.package.product?.labels;
var hasLabels = labels?.Any() == true;
if (hasLabels)
assignedLabelList.Refresh(labels.Count() > 1 ? L10n.Tr("Assigned Labels") : L10n.Tr("Assigned Label"), labels);
UIUtils.SetElementDisplay(assignedLabelList, hasLabels);
}
private void RefreshSupportedUnityVersions(IPackageVersion version)
{
var supportedVersion = version.supportedVersions?.Any() == true ? version.supportedVersions.First() : version.supportedVersion;
var hasSupportedVersions = supportedVersion != null;
if (hasSupportedVersions)
{
detailUnityVersions.SetValueWithoutNotify(string.Format(L10n.Tr("{0} or higher"), supportedVersion));
var tooltip = supportedVersion.ToString();
if (version.supportedVersions?.Any() == true)
{
var versions = version.supportedVersions.Select(version => version.ToString()).ToArray();
tooltip = versions.Length == 1 ? versions[0] :
string.Format(L10n.Tr("{0} and {1} to improve compatibility with the range of these versions of Unity"), string.Join(", ", versions, 0, versions.Length - 1), versions[versions.Length - 1]);
}
detailUnityVersions.tooltip = string.Format(L10n.Tr("Package has been submitted using Unity {0}"), tooltip);
}
UIUtils.SetElementDisplay(detailUnityVersionsContainer, hasSupportedVersions);
}
private void RefreshSizeInfo(IPackageVersion version)
{
var showSizes = version.sizes.Any();
if (showSizes)
{
var sizeInfo = version.sizes.FirstOrDefault(info => info.supportedUnityVersion == version.supportedVersion) ?? version.sizes.Last();
detailSizes.SetValueWithoutNotify(string.Format(L10n.Tr("Size: {0} (Number of files: {1})"), UIUtils.ConvertToHumanReadableSize(sizeInfo.downloadSize), sizeInfo.assetCount));
}
UIUtils.SetElementDisplay(detailSizesContainer, showSizes);
}
private void RefreshPurchasedDate(IPackageVersion version)
{
detailPurchasedDate.SetValueWithoutNotify(version.package.product?.purchasedTime?.ToString("MMMM dd, yyyy", CultureInfo.CreateSpecificCulture("en-US")) ?? string.Empty);
UIUtils.SetElementDisplay(detailPurchasedDateContainer, !string.IsNullOrEmpty(detailPurchasedDate.text));
}
private void RefreshDescription(IPackageVersion version)
{
var productDescription = version.package.product?.description;
var hasProductDescription = !string.IsNullOrEmpty(productDescription);
var desc = hasProductDescription ? productDescription : L10n.Tr("There is no description for this package.");
if (desc.Length > k_maxDescriptionCharacters)
desc = desc.Substring(0, k_maxDescriptionCharacters);
detailDescription.EnableInClassList(k_EmptyDescriptionClass, !hasProductDescription);
detailDescription.style.maxHeight = int.MaxValue;
detailDescription.SetValueWithoutNotify(desc);
}
private readonly VisualElementCache m_Cache;
private TagLabelList assignedLabelList => m_Cache.Get<TagLabelList>("assignedLabelList");
private VisualElement detailUnityVersionsContainer => m_Cache.Get<VisualElement>("detailUnityVersionsContainer");
private SelectableLabel detailUnityVersions => m_Cache.Get<SelectableLabel>("detailUnityVersions");
private VisualElement detailSizesContainer => m_Cache.Get<VisualElement>("detailSizesContainer");
private SelectableLabel detailSizes => m_Cache.Get<SelectableLabel>("detailSizes");
private VisualElement detailPurchasedDateContainer => m_Cache.Get<VisualElement>("detailPurchasedDateContainer");
private SelectableLabel detailPurchasedDate => m_Cache.Get<SelectableLabel>("detailPurchasedDate");
private SelectableLabel detailDescription => m_Cache.Get<SelectableLabel>("detailDescription");
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsOverviewTabContent.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsOverviewTabContent.cs",
"repo_id": "UnityCsReference",
"token_count": 2043
} | 413 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageListView : ListView, IPackageListView
{
[Serializable]
public new class UxmlSerializedData : ListView.UxmlSerializedData
{
public override object CreateInstance() => new PackageListView();
}
private IPackageDatabase m_PackageDatabase;
private IPageManager m_PageManager;
private IAssetStoreCache m_AssetStoreCache;
private IBackgroundFetchHandler m_BackgroundFetchHandler;
private void ResolveDependencies()
{
var container = ServicesContainer.instance;
m_PackageDatabase = container.Resolve<IPackageDatabase>();
m_PageManager = container.Resolve<IPageManager>();
m_AssetStoreCache = container.Resolve<IAssetStoreCache>();
m_BackgroundFetchHandler = container.Resolve<IBackgroundFetchHandler>();
}
private Dictionary<string, PackageItem> m_PackageItemsLookup;
public PackageListView()
{
ResolveDependencies();
m_PackageItemsLookup = new Dictionary<string, PackageItem>();
makeItem = MakeItem;
unbindItem = UnbindItem;
bindItem = BindItem;
selectionType = SelectionType.Multiple;
virtualizationMethod = CollectionVirtualizationMethod.FixedHeight;
fixedItemHeight = PackageItem.k_MainItemHeight;
horizontalScrollingEnabled = false;
var scrollView = this.Q<ScrollView>();
if (scrollView != null)
scrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
}
public void OnEnable()
{
selectionChanged += SyncListViewSelectionToPageManager;
m_PageManager.onSelectionChanged += OnSelectionChanged;
}
public void OnDisable()
{
selectionChanged -= SyncListViewSelectionToPageManager;
m_PageManager.onSelectionChanged -= OnSelectionChanged;
}
private void SyncListViewSelectionToPageManager(IEnumerable<object> items)
{
var selections = items.Select(item =>
{
var visualState = item as VisualState;
var package = m_PackageDatabase.GetPackage(visualState?.packageUniqueId);
if (package != null)
return new PackageAndVersionIdPair(package.uniqueId);
return null;
}).Where(s => s != null).ToArray();
// SelectionChange happens before BindItems, hence we use m_PageManager.SetSelected instead of packageItem.SelectMainItem
// as PackageItems are null sometimes when SelectionChange is triggered
m_PageManager.activePage.SetNewSelection(selections);
}
private void UnbindItem(VisualElement item, int index)
{
var package = (item as PackageItem)?.package;
var product = package?.product;
if(product == null)
return;
m_BackgroundFetchHandler.RemoveFromFetchProductInfoQueue(product.id);
m_PackageItemsLookup.Remove(package.uniqueId);
}
private void BindItem(VisualElement item, int index)
{
var packageItem = item as PackageItem;
if (packageItem == null)
return;
var visualState = GetVisualStateByIndex(index);
if (string.IsNullOrEmpty(visualState?.packageUniqueId))
return;
var package = m_PackageDatabase.GetPackage(visualState.packageUniqueId);
packageItem.SetPackageAndVisualState(package, visualState);
m_PackageItemsLookup[visualState.packageUniqueId] = packageItem;
var product = package?.product;
if(product == null)
return;
if (package.versions.primary.HasTag(PackageTag.Placeholder))
m_BackgroundFetchHandler.AddToFetchProductInfoQueue(product.id);
if (m_AssetStoreCache.GetLocalInfo(product.id) != null && m_AssetStoreCache.GetUpdateInfo(product.id) == null)
m_BackgroundFetchHandler.PushToCheckUpdateStack(product.id);
}
private VisualElement MakeItem()
{
return new PackageItem(m_PageManager, m_PackageDatabase);
}
public PackageItem GetPackageItem(string packageUniqueId)
{
return string.IsNullOrEmpty(packageUniqueId) ? null : m_PackageItemsLookup.Get(packageUniqueId);
}
// Returns true if RefreshItems is triggered and false otherwise
private bool UpdateItemsSource(List<VisualState> visualStates, bool forceRefesh = false)
{
var refresh = forceRefesh || visualStates?.Count != itemsSource?.Count;
itemsSource = visualStates;
if (refresh)
{
RefreshItems();
SyncPageManagerSelectionToListView();
}
return refresh;
}
private VisualState GetVisualStateByIndex(int index)
{
return (itemsSource as List<VisualState>)?.ElementAtOrDefault(index);
}
private void OnSelectionChanged(PageSelectionChangeArgs args)
{
SyncPageManagerSelectionToListView(args.page, args.selection);
}
// In PageManager we track selection by keeping track of the package unique ids (hence it's not affected by reordering)
// In ListView, the selection is tracked by indices. As a result, when we update the itemsSource, we want to sync selection index if needed
// Because there might be some sort of reordering
private void SyncPageManagerSelectionToListView(IPage page = null, PageSelection selection = null)
{
var visualStates = itemsSource as List<VisualState>;
if (visualStates == null)
return;
page ??= m_PageManager.activePage;
if (page.id != MyAssetsPage.k_Id)
return;
selection ??= page.GetSelection();
var oldSelectedVisualStates = selectedItems.Select(item => item as VisualState).ToArray();
if (oldSelectedVisualStates.Length == selection.Count && oldSelectedVisualStates.All(v => selection.Contains(v.packageUniqueId)))
return;
var newSelectionIndices = new List<int>();
for (var i = 0; i < visualStates.Count; i++)
if (selection.Contains(visualStates[i].packageUniqueId))
newSelectionIndices.Add(i);
SetSelection(newSelectionIndices);
}
public void ScrollToSelection()
{
if (m_PackageItemsLookup.Count == 0 || float.IsNaN(layout.height) || layout.height == 0)
{
EditorApplication.delayCall -= ScrollToSelection;
EditorApplication.delayCall += ScrollToSelection;
return;
}
// For now we want to just scroll to any of the selections, this behaviour might change in the future depending on how users react
var firstSelectedPackageUniqueId = m_PageManager.activePage.GetSelection().firstSelection?.packageUniqueId;
if (string.IsNullOrEmpty(firstSelectedPackageUniqueId))
return;
EditorApplication.delayCall -= ScrollToSelection;
var visualStates = itemsSource as List<VisualState>;
var index = visualStates?.FindIndex(v => v.packageUniqueId == firstSelectedPackageUniqueId) ?? -1;
if (index >= 0)
ScrollToItem(index);
}
public void OnVisualStateChange(IEnumerable<VisualState> visualStates)
{
if (!visualStates.Any())
return;
foreach (var state in visualStates)
GetPackageItem(state.packageUniqueId)?.UpdateVisualState(state);
if (m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid())
ScrollToSelection();
}
public void OnListRebuild(IPage page)
{
UpdateItemsSource(page.visualStates.ToList(), true);
m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid();
ScrollToSelection();
}
public void OnListUpdate(ListUpdateArgs args)
{
var rebuildCalled = UpdateItemsSource(args.page.visualStates.ToList(), args.added.Any() || args.removed.Any());
if (!rebuildCalled)
{
foreach (var package in args.updated)
GetPackageItem(package.uniqueId)?.SetPackageAndVisualState(package, m_PageManager.activePage.visualStates.Get(package.uniqueId));
}
if (m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid())
ScrollToSelection();
}
public void OnActivePageChanged(IPage page)
{
// Do nothing as we only show PackageListView for `My Assets` page for now
}
public void OnSeeAllPackageVersionsChanged(bool value)
{
// Do nothing as `My Assets` page is not affected by `See All Package Versions` setting
}
public void OnKeyDownShortcut(KeyDownEvent evt)
{
if (!UIUtils.IsElementVisible(this))
return;
// We use keyboard events for ctrl, shift, A, and esc because UIToolkit does not
// handle naigation events for them (18/07/2022)
int index;
switch (evt.keyCode)
{
case KeyCode.A when evt.actionKey:
SelectAll();
evt.StopPropagation();
break;
case KeyCode.PageUp:
if (!selectedIndices.Any()) return;
index = Mathf.Max(0, selectedIndices.Max() - (virtualizationController.visibleItemCount - 1));
HandleSelectionAndScroll(index, evt.shiftKey);
evt.StopPropagation();
break;
case KeyCode.PageDown:
if (!selectedIndices.Any()) return;
index = Mathf.Min(viewController.itemsSource.Count - 1,
selectedIndices.Max() + (virtualizationController.visibleItemCount - 1));
HandleSelectionAndScroll(index, evt.shiftKey);
evt.StopPropagation();
break;
// On mac moving up and down will trigger the sound of an incorrect key being pressed
// This should be fixed in UUM-26264 by the UIToolkit team
case KeyCode.DownArrow:
case KeyCode.UpArrow:
evt.StopPropagation();
break;
}
Focus();
}
public void OnNavigationMoveShortcut(NavigationMoveEvent evt)
{
if (!UIUtils.IsElementVisible(this))
return;
var newSelectedIndex = -1;
switch (evt.direction)
{
case NavigationMoveEvent.Direction.Up:
newSelectedIndex = selectedIndex - 1;
break;
case NavigationMoveEvent.Direction.Down:
newSelectedIndex = selectedIndex + 1;
break;
}
if (newSelectedIndex < 0 || newSelectedIndex >= itemsSource.Count)
return;
HandleSelectionAndScroll(newSelectedIndex, evt.shiftKey);
Focus();
evt.StopPropagation();
}
private void HandleSelectionAndScroll(int index, bool shiftKey)
{
if (shiftKey)
DoRangeSelection(index);
else
selectedIndex = index;
ScrollToItem(index);
}
internal override ICollectionDragAndDropController CreateDragAndDropController() => null;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageListView.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageListView.cs",
"repo_id": "UnityCsReference",
"token_count": 5499
} | 414 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageAssetStoreTagLabel : PackageBaseTagLabel
{
public PackageAssetStoreTagLabel()
{
name = "tagAssetStore";
text = L10n.Tr("Asset Store");
}
public override void Refresh(IPackageVersion version)
{
UIUtils.SetElementDisplay(this, version.package.product != null);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageAssetStoreTagLabel.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageAssetStoreTagLabel.cs",
"repo_id": "UnityCsReference",
"token_count": 239
} | 415 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal;
internal class SelectionWindowTreeView : TreeView
{
private bool m_ViewDataReady;
private bool m_ResetExpansionAndScrollOnViewDataReady;
public SelectionWindowTreeView(int itemHeight, Func<VisualElement> makeItem, Action<VisualElement, int> bindItem)
: base(itemHeight, makeItem, bindItem)
{
selectionType = SelectionType.None;
}
internal override void OnViewDataReady()
{
base.OnViewDataReady();
m_ViewDataReady = true;
if (m_ResetExpansionAndScrollOnViewDataReady)
{
ResetExpansionAndScroll();
m_ResetExpansionAndScrollOnViewDataReady = false;
}
}
private void ResetExpansionAndScroll()
{
// If the view data is not ready, calling ExpandAll will not work because the expansions will be overriden
// on view data ready. As a workaround, when we know that the view data is not ready, we delay the reset
// expansion and scroll code to when the view data is ready
if (!m_ViewDataReady)
{
m_ResetExpansionAndScrollOnViewDataReady = true;
return;
}
ExpandAll();
// We need to do a delay call because there's a bug with UI toolkit that causes the scrollView
// to be set back to the saved position even after the OnViewDataReady is called.
EditorApplication.delayCall += () => scrollView.scrollOffset = Vector2.zero;
}
private static List<TreeViewItemData<SelectionWindowData.Node>> CreateTreeViewData(SelectionWindowData data, SelectionWindowData.Node parentNode)
{
if (data.nodes?.Any() != true)
return new List<TreeViewItemData<SelectionWindowData.Node>>();
var results = new List<TreeViewItemData<SelectionWindowData.Node>>();
foreach (var node in data.GetChildren(parentNode))
{
var treeViewItemData = new TreeViewItemData<SelectionWindowData.Node>(node.index, node);
treeViewItemData.AddChildren(CreateTreeViewData(data, node));
results.Add(treeViewItemData);
}
return results;
}
public void SetData(SelectionWindowData data, bool resetExpansion)
{
SetRootItems(CreateTreeViewData(data, data.hiddenRootNode));
if (resetExpansion)
ResetExpansionAndScroll();
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowTreeView.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowTreeView.cs",
"repo_id": "UnityCsReference",
"token_count": 984
} | 416 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Bindings;
using Object = UnityEngine.Object;
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
namespace UnityEngine
{
[NativeHeader("ParticleSystemScriptingClasses.h")]
[NativeHeader("Modules/ParticleSystem/ParticleSystem.h")]
[NativeHeader("Modules/ParticleSystem/ScriptBindings/ParticleSystemScriptBindings.h")]
[NativeHeader("Modules/ParticleSystem/ScriptBindings/ParticleSystemModulesScriptBindings.h")]
public partial class ParticleSystem : Component
{
// Modules
public partial struct MainModule
{
internal MainModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public Vector3 emitterVelocity { get; [NativeThrows] set; }
extern public float duration { get; [NativeThrows] set; }
extern public bool loop { get; [NativeThrows] set; }
extern public bool prewarm { get; [NativeThrows] set; }
public MinMaxCurve startDelay { get => startDelayBlittable; set => startDelayBlittable = value; }
[NativeName("StartDelay")] private extern MinMaxCurveBlittable startDelayBlittable { get; [NativeThrows] set; }
extern public float startDelayMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startLifetime { get => startLifetimeBlittable; set => startLifetimeBlittable = value; }
[NativeName("StartLifetime")] private extern MinMaxCurveBlittable startLifetimeBlittable { get; [NativeThrows] set; }
extern public float startLifetimeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startSpeed { get => startSpeedBlittable; set => startSpeedBlittable = value; }
[NativeName("StartSpeed")] private extern MinMaxCurveBlittable startSpeedBlittable { get; [NativeThrows] set; }
extern public float startSpeedMultiplier { get; [NativeThrows] set; }
extern public bool startSize3D { get; [NativeThrows] set; }
public MinMaxCurve startSize { get => startSizeBlittable; set => startSizeBlittable = value; }
[NativeName("StartSizeX")] private extern MinMaxCurveBlittable startSizeBlittable { get; [NativeThrows] set; }
[NativeName("StartSizeXMultiplier")]
extern public float startSizeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startSizeX { get => startSizeXBlittable; set => startSizeXBlittable = value; }
[NativeName("StartSizeX")] private extern MinMaxCurveBlittable startSizeXBlittable { get; [NativeThrows] set; }
extern public float startSizeXMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startSizeY { get => startSizeYBlittable; set => startSizeYBlittable = value; }
[NativeName("StartSizeY")] private extern MinMaxCurveBlittable startSizeYBlittable { get; [NativeThrows] set; }
extern public float startSizeYMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startSizeZ { get => startSizeZBlittable; set => startSizeZBlittable = value; }
[NativeName("StartSizeZ")] private extern MinMaxCurveBlittable startSizeZBlittable { get; [NativeThrows] set; }
extern public float startSizeZMultiplier { get; [NativeThrows] set; }
extern public bool startRotation3D { get; [NativeThrows] set; }
public MinMaxCurve startRotation { get => startRotationBlittable; set => startRotationBlittable = value; }
[NativeName("StartRotationZ")] private extern MinMaxCurveBlittable startRotationBlittable { get; [NativeThrows] set; }
[NativeName("StartRotationZMultiplier")]
extern public float startRotationMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startRotationX { get => startRotationXBlittable; set => startRotationXBlittable = value; }
[NativeName("StartRotationX")] private extern MinMaxCurveBlittable startRotationXBlittable { get; [NativeThrows] set; }
extern public float startRotationXMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startRotationY { get => startRotationYBlittable; set => startRotationYBlittable = value; }
[NativeName("StartRotationY")] private extern MinMaxCurveBlittable startRotationYBlittable { get; [NativeThrows] set; }
extern public float startRotationYMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startRotationZ { get => startRotationZBlittable; set => startRotationZBlittable = value; }
[NativeName("StartRotationZ")] private extern MinMaxCurveBlittable startRotationZBlittable { get; [NativeThrows] set; }
extern public float startRotationZMultiplier { get; [NativeThrows] set; }
extern public float flipRotation { get; [NativeThrows] set; }
public MinMaxGradient startColor { get => startColorBlittable; set => startColorBlittable = value; }
[NativeName("StartColor")] private extern MinMaxGradientBlittable startColorBlittable { get; [NativeThrows] set; }
extern public ParticleSystemGravitySource gravitySource { get; [NativeThrows] set; }
public MinMaxCurve gravityModifier { get => gravityModifierBlittable; set => gravityModifierBlittable = value; }
[NativeName("GravityModifier")] private extern MinMaxCurveBlittable gravityModifierBlittable { get; [NativeThrows] set; }
extern public float gravityModifierMultiplier { get; [NativeThrows] set; }
extern public ParticleSystemSimulationSpace simulationSpace { get; [NativeThrows] set; }
extern public Transform customSimulationSpace { get; [NativeThrows] set; }
extern public float simulationSpeed { get; [NativeThrows] set; }
extern public bool useUnscaledTime { get; [NativeThrows] set; }
extern public ParticleSystemScalingMode scalingMode { get; [NativeThrows] set; }
extern public bool playOnAwake { get; [NativeThrows] set; }
extern public int maxParticles { get; [NativeThrows] set; }
extern public ParticleSystemEmitterVelocityMode emitterVelocityMode { get; [NativeThrows] set; }
extern public ParticleSystemStopAction stopAction { get; [NativeThrows] set; }
extern public ParticleSystemRingBufferMode ringBufferMode { get; [NativeThrows] set; }
extern public Vector2 ringBufferLoopRange { get; [NativeThrows] set; }
extern public ParticleSystemCullingMode cullingMode { get; [NativeThrows] set; }
}
public partial struct EmissionModule
{
internal EmissionModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve rateOverTime { get => rateOverTimeBlittable; set => rateOverTimeBlittable = value; }
[NativeName("RateOverTime")] private extern MinMaxCurveBlittable rateOverTimeBlittable { get; [NativeThrows] set; }
extern public float rateOverTimeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve rateOverDistance { get => rateOverDistanceBlittable; set => rateOverDistanceBlittable = value; }
[NativeName("RateOverDistance")] private extern MinMaxCurveBlittable rateOverDistanceBlittable { get; [NativeThrows] set; }
extern public float rateOverDistanceMultiplier { get; [NativeThrows] set; }
public void SetBursts(Burst[] bursts)
{
SetBursts(bursts, bursts.Length);
}
public void SetBursts(Burst[] bursts, int size)
{
burstCount = size;
for (int i = 0; i < size; i++)
SetBurst(i, bursts[i]);
}
public int GetBursts(Burst[] bursts)
{
int returnValue = burstCount;
for (int i = 0; i < returnValue; i++)
bursts[i] = GetBurst(i);
return returnValue;
}
[NativeThrows]
extern public void SetBurst(int index, Burst burst);
[NativeThrows]
extern public Burst GetBurst(int index);
extern public int burstCount { get; [NativeThrows] set; }
}
public partial struct ShapeModule
{
internal ShapeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemShapeType shapeType { get; [NativeThrows] set; }
extern public float randomDirectionAmount { get; [NativeThrows] set; }
extern public float sphericalDirectionAmount { get; [NativeThrows] set; }
extern public float randomPositionAmount { get; [NativeThrows] set; }
extern public bool alignToDirection { get; [NativeThrows] set; }
extern public float radius { get; [NativeThrows] set; }
extern public ParticleSystemShapeMultiModeValue radiusMode { get; [NativeThrows] set; }
extern public float radiusSpread { get; [NativeThrows] set; }
public MinMaxCurve radiusSpeed { get => radiusSpeedBlittable; set => radiusSpeedBlittable = value; }
[NativeName("RadiusSpeed")] private extern MinMaxCurveBlittable radiusSpeedBlittable { get; [NativeThrows] set; }
extern public float radiusSpeedMultiplier { get; [NativeThrows] set; }
extern public float radiusThickness { get; [NativeThrows] set; }
extern public float angle { get; [NativeThrows] set; }
extern public float length { get; [NativeThrows] set; }
extern public Vector3 boxThickness { get; [NativeThrows] set; }
extern public ParticleSystemMeshShapeType meshShapeType { get; [NativeThrows] set; }
extern public Mesh mesh { get; [NativeThrows] set; }
extern public MeshRenderer meshRenderer { get; [NativeThrows] set; }
extern public SkinnedMeshRenderer skinnedMeshRenderer { get; [NativeThrows] set; }
extern public Sprite sprite { get; [NativeThrows] set; }
extern public SpriteRenderer spriteRenderer { get; [NativeThrows] set; }
extern public bool useMeshMaterialIndex { get; [NativeThrows] set; }
extern public int meshMaterialIndex { get; [NativeThrows] set; }
extern public bool useMeshColors { get; [NativeThrows] set; }
extern public float normalOffset { get; [NativeThrows] set; }
extern public ParticleSystemShapeMultiModeValue meshSpawnMode { get; [NativeThrows] set; }
extern public float meshSpawnSpread { get; [NativeThrows] set; }
public MinMaxCurve meshSpawnSpeed { get => meshSpawnSpeedBlittable; set => meshSpawnSpeedBlittable = value; }
[NativeName("MeshSpawnSpeed")] private extern MinMaxCurveBlittable meshSpawnSpeedBlittable { get; [NativeThrows] set; }
extern public float meshSpawnSpeedMultiplier { get; [NativeThrows] set; }
extern public float arc { get; [NativeThrows] set; }
extern public ParticleSystemShapeMultiModeValue arcMode { get; [NativeThrows] set; }
extern public float arcSpread { get; [NativeThrows] set; }
public MinMaxCurve arcSpeed { get => arcSpeedBlittable; set => arcSpeedBlittable = value; }
[NativeName("ArcSpeed")] private extern MinMaxCurveBlittable arcSpeedBlittable { get; [NativeThrows] set; }
extern public float arcSpeedMultiplier { get; [NativeThrows] set; }
extern public float donutRadius { get; [NativeThrows] set; }
extern public Vector3 position { get; [NativeThrows] set; }
extern public Vector3 rotation { get; [NativeThrows] set; }
extern public Vector3 scale { get; [NativeThrows] set; }
extern public Texture2D texture { get; [NativeThrows] set; }
extern public ParticleSystemShapeTextureChannel textureClipChannel { get; [NativeThrows] set; }
extern public float textureClipThreshold { get; [NativeThrows] set; }
extern public bool textureColorAffectsParticles { get; [NativeThrows] set; }
extern public bool textureAlphaAffectsParticles { get; [NativeThrows] set; }
extern public bool textureBilinearFiltering { get; [NativeThrows] set; }
extern public int textureUVChannel { get; [NativeThrows] set; }
}
public partial struct VelocityOverLifetimeModule
{
internal VelocityOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
public MinMaxCurve orbitalX { get => orbitalXBlittable; set => orbitalXBlittable = value; }
[NativeName("OrbitalX")] private extern MinMaxCurveBlittable orbitalXBlittable { get; [NativeThrows] set; }
public MinMaxCurve orbitalY { get => orbitalYBlittable; set => orbitalYBlittable = value; }
[NativeName("OrbitalY")] private extern MinMaxCurveBlittable orbitalYBlittable { get; [NativeThrows] set; }
public MinMaxCurve orbitalZ { get => orbitalZBlittable; set => orbitalZBlittable = value; }
[NativeName("OrbitalZ")] private extern MinMaxCurveBlittable orbitalZBlittable { get; [NativeThrows] set; }
extern public float orbitalXMultiplier { get; [NativeThrows] set; }
extern public float orbitalYMultiplier { get; [NativeThrows] set; }
extern public float orbitalZMultiplier { get; [NativeThrows] set; }
public MinMaxCurve orbitalOffsetX { get => orbitalOffsetXBlittable; set => orbitalOffsetXBlittable = value; }
[NativeName("OrbitalOffsetX")] private extern MinMaxCurveBlittable orbitalOffsetXBlittable { get; [NativeThrows] set; }
public MinMaxCurve orbitalOffsetY { get => orbitalOffsetYBlittable; set => orbitalOffsetYBlittable = value; }
[NativeName("OrbitalOffsetY")] private extern MinMaxCurveBlittable orbitalOffsetYBlittable { get; [NativeThrows] set; }
public MinMaxCurve orbitalOffsetZ { get => orbitalOffsetZBlittable; set => orbitalOffsetZBlittable = value; }
[NativeName("OrbitalOffsetZ")] private extern MinMaxCurveBlittable orbitalOffsetZBlittable { get; [NativeThrows] set; }
extern public float orbitalOffsetXMultiplier { get; [NativeThrows] set; }
extern public float orbitalOffsetYMultiplier { get; [NativeThrows] set; }
extern public float orbitalOffsetZMultiplier { get; [NativeThrows] set; }
public MinMaxCurve radial { get => radialBlittable; set => radialBlittable = value; }
[NativeName("Radial")] private extern MinMaxCurveBlittable radialBlittable { get; [NativeThrows] set; }
extern public float radialMultiplier { get; [NativeThrows] set; }
public MinMaxCurve speedModifier { get => speedModifierBlittable; set => speedModifierBlittable = value; }
[NativeName("SpeedModifier")] private extern MinMaxCurveBlittable speedModifierBlittable { get; [NativeThrows] set; }
extern public float speedModifierMultiplier { get; [NativeThrows] set; }
extern public ParticleSystemSimulationSpace space { get; [NativeThrows] set; }
}
public partial struct LimitVelocityOverLifetimeModule
{
internal LimitVelocityOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve limitX { get => limitXBlittable; set => limitXBlittable = value; }
[NativeName("LimitX")] private extern MinMaxCurveBlittable limitXBlittable { get; [NativeThrows] set; }
extern public float limitXMultiplier { get; [NativeThrows] set; }
public MinMaxCurve limitY { get => limitYBlittable; set => limitYBlittable = value; }
[NativeName("LimitY")] private extern MinMaxCurveBlittable limitYBlittable { get; [NativeThrows] set; }
extern public float limitYMultiplier { get; [NativeThrows] set; }
public MinMaxCurve limitZ { get => limitZBlittable; set => limitZBlittable = value; }
[NativeName("LimitZ")] private extern MinMaxCurveBlittable limitZBlittable { get; [NativeThrows] set; }
extern public float limitZMultiplier { get; [NativeThrows] set; }
public MinMaxCurve limit { get => limitBlittable; set => limitBlittable = value; }
[NativeName("Magnitude")] private extern MinMaxCurveBlittable limitBlittable { get; [NativeThrows] set; }
[NativeName("MagnitudeMultiplier")]
extern public float limitMultiplier { get; [NativeThrows] set; }
extern public float dampen { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
extern public ParticleSystemSimulationSpace space { get; [NativeThrows] set; }
public MinMaxCurve drag { get => dragBlittable; set => dragBlittable = value; }
[NativeName("Drag")] private extern MinMaxCurveBlittable dragBlittable { get; [NativeThrows] set; }
extern public float dragMultiplier { get; [NativeThrows] set; }
extern public bool multiplyDragByParticleSize { get; [NativeThrows] set; }
extern public bool multiplyDragByParticleVelocity { get; [NativeThrows] set; }
}
public partial struct InheritVelocityModule
{
internal InheritVelocityModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemInheritVelocityMode mode { get; [NativeThrows] set; }
public MinMaxCurve curve { get => curveBlittable; set => curveBlittable = value; }
[NativeName("Curve")] private extern MinMaxCurveBlittable curveBlittable { get; [NativeThrows] set; }
extern public float curveMultiplier { get; [NativeThrows] set; }
}
public partial struct LifetimeByEmitterSpeedModule
{
internal LifetimeByEmitterSpeedModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve curve { get => curveBlittable; set => curveBlittable = value; }
[NativeName("Curve")] private extern MinMaxCurveBlittable curveBlittable { get; [NativeThrows] set; }
extern public float curveMultiplier { get; [NativeThrows] set; }
extern public Vector2 range { get; [NativeThrows] set; }
}
public partial struct ForceOverLifetimeModule
{
internal ForceOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
extern public ParticleSystemSimulationSpace space { get; [NativeThrows] set; }
extern public bool randomized { get; [NativeThrows] set; }
}
public partial struct ColorOverLifetimeModule
{
internal ColorOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxGradient color { get => colorBlittable; set => colorBlittable = value; }
[NativeName("Color")] private extern MinMaxGradientBlittable colorBlittable { get; [NativeThrows] set; }
}
public partial struct ColorBySpeedModule
{
internal ColorBySpeedModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxGradient color { get => colorBlittable; set => colorBlittable = value; }
[NativeName("Color")] private extern MinMaxGradientBlittable colorBlittable { get; [NativeThrows] set; }
extern public Vector2 range { get; [NativeThrows] set; }
}
public partial struct SizeOverLifetimeModule
{
internal SizeOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve size { get => sizeBlittable; set => sizeBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable sizeBlittable { get; [NativeThrows] set; }
[NativeName("XMultiplier")]
extern public float sizeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
}
public partial struct SizeBySpeedModule
{
internal SizeBySpeedModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve size { get => sizeBlittable; set => sizeBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable sizeBlittable { get; [NativeThrows] set; }
[NativeName("XMultiplier")]
extern public float sizeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
extern public Vector2 range { get; [NativeThrows] set; }
}
public partial struct RotationOverLifetimeModule
{
internal RotationOverLifetimeModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
}
public partial struct RotationBySpeedModule
{
internal RotationBySpeedModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
public MinMaxCurve x { get => xBlittable; set => xBlittable = value; }
[NativeName("X")] private extern MinMaxCurveBlittable xBlittable { get; [NativeThrows] set; }
extern public float xMultiplier { get; [NativeThrows] set; }
public MinMaxCurve y { get => yBlittable; set => yBlittable = value; }
[NativeName("Y")] private extern MinMaxCurveBlittable yBlittable { get; [NativeThrows] set; }
extern public float yMultiplier { get; [NativeThrows] set; }
public MinMaxCurve z { get => zBlittable; set => zBlittable = value; }
[NativeName("Z")] private extern MinMaxCurveBlittable zBlittable { get; [NativeThrows] set; }
extern public float zMultiplier { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
extern public Vector2 range { get; [NativeThrows] set; }
}
public partial struct ExternalForcesModule
{
internal ExternalForcesModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public float multiplier { get; [NativeThrows] set; }
public MinMaxCurve multiplierCurve { get => multiplierCurveBlittable; set => multiplierCurveBlittable = value; }
[NativeName("MultiplierCurve")] private extern MinMaxCurveBlittable multiplierCurveBlittable { get; [NativeThrows] set; }
extern public ParticleSystemGameObjectFilter influenceFilter { get; [NativeThrows] set; }
extern public LayerMask influenceMask { get; [NativeThrows] set; }
[NativeThrows]
extern public int influenceCount { get; }
extern public bool IsAffectedBy(ParticleSystemForceField field);
[NativeThrows]
extern public void AddInfluence([NotNull] ParticleSystemForceField field);
[NativeThrows]
extern private void RemoveInfluenceAtIndex(int index);
public void RemoveInfluence(int index) { RemoveInfluenceAtIndex(index); }
[NativeThrows]
extern public void RemoveInfluence([NotNull] ParticleSystemForceField field);
[NativeThrows]
extern public void RemoveAllInfluences();
[NativeThrows]
extern public void SetInfluence(int index, [NotNull] ParticleSystemForceField field);
[NativeThrows]
extern public ParticleSystemForceField GetInfluence(int index);
}
public partial struct NoiseModule
{
internal NoiseModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public bool separateAxes { get; [NativeThrows] set; }
public MinMaxCurve strength { get => strengthBlittable; set => strengthBlittable = value; }
[NativeName("StrengthX")] private extern MinMaxCurveBlittable strengthBlittable { get; [NativeThrows] set; }
[NativeName("StrengthXMultiplier")]
extern public float strengthMultiplier { get; [NativeThrows] set; }
public MinMaxCurve strengthX { get => strengthXBlittable; set => strengthXBlittable = value; }
[NativeName("StrengthX")] private extern MinMaxCurveBlittable strengthXBlittable { get; [NativeThrows] set; }
extern public float strengthXMultiplier { get; [NativeThrows] set; }
public MinMaxCurve strengthY { get => strengthYBlittable; set => strengthYBlittable = value; }
[NativeName("StrengthY")] private extern MinMaxCurveBlittable strengthYBlittable { get; [NativeThrows] set; }
extern public float strengthYMultiplier { get; [NativeThrows] set; }
public MinMaxCurve strengthZ { get => strengthZBlittable; set => strengthZBlittable = value; }
[NativeName("StrengthZ")] private extern MinMaxCurveBlittable strengthZBlittable { get; [NativeThrows] set; }
extern public float strengthZMultiplier { get; [NativeThrows] set; }
extern public float frequency { get; [NativeThrows] set; }
extern public bool damping { get; [NativeThrows] set; }
extern public int octaveCount { get; [NativeThrows] set; }
extern public float octaveMultiplier { get; [NativeThrows] set; }
extern public float octaveScale { get; [NativeThrows] set; }
extern public ParticleSystemNoiseQuality quality { get; [NativeThrows] set; }
public MinMaxCurve scrollSpeed { get => scrollSpeedBlittable; set => scrollSpeedBlittable = value; }
[NativeName("ScrollSpeed")] private extern MinMaxCurveBlittable scrollSpeedBlittable { get; [NativeThrows] set; }
extern public float scrollSpeedMultiplier { get; [NativeThrows] set; }
extern public bool remapEnabled { get; [NativeThrows] set; }
public MinMaxCurve remap { get => remapBlittable; set => remapBlittable = value; }
[NativeName("RemapX")] private extern MinMaxCurveBlittable remapBlittable { get; [NativeThrows] set; }
[NativeName("RemapXMultiplier")]
extern public float remapMultiplier { get; [NativeThrows] set; }
public MinMaxCurve remapX { get => remapXBlittable; set => remapXBlittable = value; }
[NativeName("RemapX")] private extern MinMaxCurveBlittable remapXBlittable { get; [NativeThrows] set; }
extern public float remapXMultiplier { get; [NativeThrows] set; }
public MinMaxCurve remapY { get => remapYBlittable; set => remapYBlittable = value; }
[NativeName("RemapY")] private extern MinMaxCurveBlittable remapYBlittable { get; [NativeThrows] set; }
extern public float remapYMultiplier { get; [NativeThrows] set; }
public MinMaxCurve remapZ { get => remapZBlittable; set => remapZBlittable = value; }
[NativeName("RemapZ")] private extern MinMaxCurveBlittable remapZBlittable { get; [NativeThrows] set; }
extern public float remapZMultiplier { get; [NativeThrows] set; }
public MinMaxCurve positionAmount { get => positionAmountBlittable; set => positionAmountBlittable = value; }
[NativeName("PositionAmount")] private extern MinMaxCurveBlittable positionAmountBlittable { get; [NativeThrows] set; }
public MinMaxCurve rotationAmount { get => rotationAmountBlittable; set => rotationAmountBlittable = value; }
[NativeName("RotationAmount")] private extern MinMaxCurveBlittable rotationAmountBlittable { get; [NativeThrows] set; }
public MinMaxCurve sizeAmount { get => sizeAmountBlittable; set => sizeAmountBlittable = value; }
[NativeName("SizeAmount")] private extern MinMaxCurveBlittable sizeAmountBlittable { get; [NativeThrows] set; }
}
public partial struct CollisionModule
{
internal CollisionModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemCollisionType type { get; [NativeThrows] set; }
extern public ParticleSystemCollisionMode mode { get; [NativeThrows] set; }
public MinMaxCurve dampen { get => dampenBlittable; set => dampenBlittable = value; }
[NativeName("Dampen")] private extern MinMaxCurveBlittable dampenBlittable { get; [NativeThrows] set; }
extern public float dampenMultiplier { get; [NativeThrows] set; }
public MinMaxCurve bounce { get => bounceBlittable; set => bounceBlittable = value; }
[NativeName("Bounce")] private extern MinMaxCurveBlittable bounceBlittable { get; [NativeThrows] set; }
extern public float bounceMultiplier { get; [NativeThrows] set; }
public MinMaxCurve lifetimeLoss { get => lifetimeLossBlittable; set => lifetimeLossBlittable = value; }
[NativeName("LifetimeLoss")] private extern MinMaxCurveBlittable lifetimeLossBlittable { get; [NativeThrows] set; }
extern public float lifetimeLossMultiplier { get; [NativeThrows] set; }
extern public float minKillSpeed { get; [NativeThrows] set; }
extern public float maxKillSpeed { get; [NativeThrows] set; }
extern public LayerMask collidesWith { get; [NativeThrows] set; }
extern public bool enableDynamicColliders { get; [NativeThrows] set; }
extern public int maxCollisionShapes { get; [NativeThrows] set; }
extern public ParticleSystemCollisionQuality quality { get; [NativeThrows] set; }
extern public float voxelSize { get; [NativeThrows] set; }
extern public float radiusScale { get; [NativeThrows] set; }
extern public bool sendCollisionMessages { get; [NativeThrows] set; }
extern public float colliderForce { get; [NativeThrows] set; }
extern public bool multiplyColliderForceByCollisionAngle { get; [NativeThrows] set; }
extern public bool multiplyColliderForceByParticleSpeed { get; [NativeThrows] set; }
extern public bool multiplyColliderForceByParticleSize { get; [NativeThrows] set; }
[NativeThrows]
extern public void AddPlane(Transform transform);
[NativeThrows]
extern public void RemovePlane(int index);
public void RemovePlane(Transform transform) { RemovePlaneObject(transform); }
[NativeThrows]
extern private void RemovePlaneObject(Transform transform);
[NativeThrows]
extern public void SetPlane(int index, Transform transform);
[NativeThrows]
extern public Transform GetPlane(int index);
[NativeThrows]
extern public int planeCount { get; }
[Obsolete("enableInteriorCollisions property is deprecated and is no longer required and has no effect on the particle system.", false)]
extern public bool enableInteriorCollisions { get; [NativeThrows] set; }
}
public partial struct TriggerModule
{
internal TriggerModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemOverlapAction inside { get; [NativeThrows] set; }
extern public ParticleSystemOverlapAction outside { get; [NativeThrows] set; }
extern public ParticleSystemOverlapAction enter { get; [NativeThrows] set; }
extern public ParticleSystemOverlapAction exit { get; [NativeThrows] set; }
extern public ParticleSystemColliderQueryMode colliderQueryMode { get; [NativeThrows] set; }
extern public float radiusScale { get; [NativeThrows] set; }
[NativeThrows]
extern public void AddCollider(Component collider);
[NativeThrows]
extern public void RemoveCollider(int index);
public void RemoveCollider(Component collider) { RemoveColliderObject(collider); }
[NativeThrows]
extern private void RemoveColliderObject(Component collider);
[NativeThrows]
extern public void SetCollider(int index, Component collider);
[NativeThrows]
extern public Component GetCollider(int index);
[NativeThrows]
extern public int colliderCount { get; }
}
public partial struct SubEmittersModule
{
internal SubEmittersModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public int subEmittersCount { get; }
[NativeThrows]
extern public void AddSubEmitter(ParticleSystem subEmitter, ParticleSystemSubEmitterType type, ParticleSystemSubEmitterProperties properties, float emitProbability);
public void AddSubEmitter(ParticleSystem subEmitter, ParticleSystemSubEmitterType type, ParticleSystemSubEmitterProperties properties) { AddSubEmitter(subEmitter, type, properties, 1.0f); }
[NativeThrows]
extern public void RemoveSubEmitter(int index);
public void RemoveSubEmitter(ParticleSystem subEmitter) { RemoveSubEmitterObject(subEmitter); }
[NativeThrows]
extern private void RemoveSubEmitterObject(ParticleSystem subEmitter);
[NativeThrows]
extern public void SetSubEmitterSystem(int index, ParticleSystem subEmitter);
[NativeThrows]
extern public void SetSubEmitterType(int index, ParticleSystemSubEmitterType type);
[NativeThrows]
extern public void SetSubEmitterProperties(int index, ParticleSystemSubEmitterProperties properties);
[NativeThrows]
extern public void SetSubEmitterEmitProbability(int index, float emitProbability);
[NativeThrows]
extern public ParticleSystem GetSubEmitterSystem(int index);
[NativeThrows]
extern public ParticleSystemSubEmitterType GetSubEmitterType(int index);
[NativeThrows]
extern public ParticleSystemSubEmitterProperties GetSubEmitterProperties(int index);
[NativeThrows]
extern public float GetSubEmitterEmitProbability(int index);
}
public partial struct TextureSheetAnimationModule
{
internal TextureSheetAnimationModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemAnimationMode mode { get; [NativeThrows] set; }
extern public ParticleSystemAnimationTimeMode timeMode { get; [NativeThrows] set; }
extern public float fps { get; [NativeThrows] set; }
extern public int numTilesX { get; [NativeThrows] set; }
extern public int numTilesY { get; [NativeThrows] set; }
extern public ParticleSystemAnimationType animation { get; [NativeThrows] set; }
extern public ParticleSystemAnimationRowMode rowMode { get; [NativeThrows] set; }
public MinMaxCurve frameOverTime { get => frameOverTimeBlittable; set => frameOverTimeBlittable = value; }
[NativeName("FrameOverTime")] private extern MinMaxCurveBlittable frameOverTimeBlittable { get; [NativeThrows] set; }
extern public float frameOverTimeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve startFrame { get => startFrameBlittable; set => startFrameBlittable = value; }
[NativeName("StartFrame")] private extern MinMaxCurveBlittable startFrameBlittable { get; [NativeThrows] set; }
extern public float startFrameMultiplier { get; [NativeThrows] set; }
extern public int cycleCount { get; [NativeThrows] set; }
extern public int rowIndex { get; [NativeThrows] set; }
extern public Rendering.UVChannelFlags uvChannelMask { get; [NativeThrows] set; }
extern public int spriteCount { get; }
extern public Vector2 speedRange { get; [NativeThrows] set; }
[NativeThrows]
extern public void AddSprite(Sprite sprite);
[NativeThrows]
extern public void RemoveSprite(int index);
[NativeThrows]
extern public void SetSprite(int index, Sprite sprite);
[NativeThrows]
extern public Sprite GetSprite(int index);
}
public partial struct LightsModule
{
internal LightsModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public float ratio { get; [NativeThrows] set; }
extern public bool useRandomDistribution { get; [NativeThrows] set; }
extern public Light light { get; [NativeThrows] set; }
extern public bool useParticleColor { get; [NativeThrows] set; }
extern public bool sizeAffectsRange { get; [NativeThrows] set; }
extern public bool alphaAffectsIntensity { get; [NativeThrows] set; }
public MinMaxCurve range { get => rangeBlittable; set => rangeBlittable = value; }
[NativeName("Range")] private extern MinMaxCurveBlittable rangeBlittable { get; [NativeThrows] set; }
extern public float rangeMultiplier { get; [NativeThrows] set; }
public MinMaxCurve intensity { get => intensityBlittable; set => intensityBlittable = value; }
[NativeName("Intensity")] private extern MinMaxCurveBlittable intensityBlittable { get; [NativeThrows] set; }
extern public float intensityMultiplier { get; [NativeThrows] set; }
extern public int maxLights { get; [NativeThrows] set; }
}
public partial struct TrailModule
{
internal TrailModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
extern public ParticleSystemTrailMode mode { get; [NativeThrows] set; }
extern public float ratio { get; [NativeThrows] set; }
public MinMaxCurve lifetime { get => lifetimeBlittable; set => lifetimeBlittable = value; }
[NativeName("Lifetime")] private extern MinMaxCurveBlittable lifetimeBlittable { get; [NativeThrows] set; }
extern public float lifetimeMultiplier { get; [NativeThrows] set; }
extern public float minVertexDistance { get; [NativeThrows] set; }
extern public ParticleSystemTrailTextureMode textureMode { get; [NativeThrows] set; }
extern public Vector2 textureScale { get; [NativeThrows] set; }
extern public bool worldSpace { get; [NativeThrows] set; }
extern public bool dieWithParticles { get; [NativeThrows] set; }
extern public bool sizeAffectsWidth { get; [NativeThrows] set; }
extern public bool sizeAffectsLifetime { get; [NativeThrows] set; }
extern public bool inheritParticleColor { get; [NativeThrows] set; }
public MinMaxGradient colorOverLifetime { get => colorOverLifetimeBlittable; set => colorOverLifetimeBlittable = value; }
[NativeName("ColorOverLifetime")] private extern MinMaxGradientBlittable colorOverLifetimeBlittable { get; [NativeThrows] set; }
public MinMaxCurve widthOverTrail { get => widthOverTrailBlittable; set => widthOverTrailBlittable = value; }
[NativeName("WidthOverTrail")] private extern MinMaxCurveBlittable widthOverTrailBlittable { get; [NativeThrows] set; }
extern public float widthOverTrailMultiplier { get; [NativeThrows] set; }
public MinMaxGradient colorOverTrail { get => colorOverTrailBlittable; set => colorOverTrailBlittable = value; }
[NativeName("ColorOverTrail")] private extern MinMaxGradientBlittable colorOverTrailBlittable { get; [NativeThrows] set; }
extern public bool generateLightingData { get; [NativeThrows] set; }
extern public int ribbonCount { get; [NativeThrows] set; }
extern public float shadowBias { get; [NativeThrows] set; }
extern public bool splitSubEmitterRibbons { get; [NativeThrows] set; }
extern public bool attachRibbonsToTransform { get; [NativeThrows] set; }
}
public partial struct CustomDataModule
{
internal CustomDataModule(ParticleSystem particleSystem) { m_ParticleSystem = particleSystem; }
internal ParticleSystem m_ParticleSystem;
extern public bool enabled { get; [NativeThrows] set; }
[NativeThrows]
extern public void SetMode(ParticleSystemCustomData stream, ParticleSystemCustomDataMode mode);
[NativeThrows]
extern public ParticleSystemCustomDataMode GetMode(ParticleSystemCustomData stream);
[NativeThrows]
extern public void SetVectorComponentCount(ParticleSystemCustomData stream, int count);
[NativeThrows]
extern public int GetVectorComponentCount(ParticleSystemCustomData stream);
public void SetVector(ParticleSystemCustomData stream, int component, MinMaxCurve curve)
{
SetVectorInternal(stream, component, MinMaxCurveBlittable.FromMixMaxCurve(curve));
}
[NativeThrows]
private extern void SetVectorInternal(ParticleSystemCustomData stream, int component, MinMaxCurveBlittable curve);
public MinMaxCurve GetVector(ParticleSystemCustomData stream, int component)
{
return MinMaxCurveBlittable.ToMinMaxCurve(GetVectorInternal(stream, component));
}
[NativeThrows]
private extern MinMaxCurveBlittable GetVectorInternal(ParticleSystemCustomData stream, int component);
public void SetColor(ParticleSystemCustomData stream, MinMaxGradient gradient)
{
SetColorInternal(stream, MinMaxGradientBlittable.FromMixMaxGradient(gradient));
}
[NativeThrows]
private extern void SetColorInternal(ParticleSystemCustomData stream, MinMaxGradientBlittable gradient);
public MinMaxGradient GetColor(ParticleSystemCustomData stream)
{
return MinMaxGradientBlittable.ToMinMaxGradient(GetColorInternal(stream));
}
[NativeThrows]
extern private MinMaxGradientBlittable GetColorInternal(ParticleSystemCustomData stream);
}
// Module Accessors
public MainModule main { get { return new MainModule(this); } }
public EmissionModule emission { get { return new EmissionModule(this); } }
public ShapeModule shape { get { return new ShapeModule(this); } }
public VelocityOverLifetimeModule velocityOverLifetime { get { return new VelocityOverLifetimeModule(this); } }
public LimitVelocityOverLifetimeModule limitVelocityOverLifetime { get { return new LimitVelocityOverLifetimeModule(this); } }
public InheritVelocityModule inheritVelocity { get { return new InheritVelocityModule(this); } }
public LifetimeByEmitterSpeedModule lifetimeByEmitterSpeed { get { return new LifetimeByEmitterSpeedModule(this); } }
public ForceOverLifetimeModule forceOverLifetime { get { return new ForceOverLifetimeModule(this); } }
public ColorOverLifetimeModule colorOverLifetime { get { return new ColorOverLifetimeModule(this); } }
public ColorBySpeedModule colorBySpeed { get { return new ColorBySpeedModule(this); } }
public SizeOverLifetimeModule sizeOverLifetime { get { return new SizeOverLifetimeModule(this); } }
public SizeBySpeedModule sizeBySpeed { get { return new SizeBySpeedModule(this); } }
public RotationOverLifetimeModule rotationOverLifetime { get { return new RotationOverLifetimeModule(this); } }
public RotationBySpeedModule rotationBySpeed { get { return new RotationBySpeedModule(this); } }
public ExternalForcesModule externalForces { get { return new ExternalForcesModule(this); } }
public NoiseModule noise { get { return new NoiseModule(this); } }
public CollisionModule collision { get { return new CollisionModule(this); } }
public TriggerModule trigger { get { return new TriggerModule(this); } }
public SubEmittersModule subEmitters { get { return new SubEmittersModule(this); } }
public TextureSheetAnimationModule textureSheetAnimation { get { return new TextureSheetAnimationModule(this); } }
public LightsModule lights { get { return new LightsModule(this); } }
public TrailModule trails { get { return new TrailModule(this); } }
public CustomDataModule customData { get { return new CustomDataModule(this); } }
}
}
| UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemModules.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemModules.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 20338
} | 417 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
class LifetimeByEmitterSpeedModuleUI : ModuleUI
{
// Keep in sync with LifetimeByEmitterSpeedModule.h
SerializedMinMaxCurve m_Curve;
SerializedProperty m_Range;
class Texts
{
public GUIContent speed = EditorGUIUtility.TrTextContent("Multiplier", "Controls the initial lifetime of particles based on the speed of the emitter.");
public GUIContent speedRange = EditorGUIUtility.TrTextContent("Speed Range", "Maps the speed to a value along the curve, when using one of the curve modes.");
}
static Texts s_Texts;
public LifetimeByEmitterSpeedModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName)
: base(owner, o, "LifetimeByEmitterSpeedModule", displayName)
{
m_ToolTip = "Controls the initial lifetime of each particle based on the speed of the emitter when the particle was spawned.";
}
protected override void Init()
{
// Already initialized?
if (m_Curve != null)
return;
if (s_Texts == null)
s_Texts = new Texts();
m_Curve = new SerializedMinMaxCurve(this, GUIContent.none, "m_Curve");
m_Range = GetProperty("m_Range");
}
override public void OnInspectorGUI(InitialModuleUI initial)
{
GUIMinMaxCurve(s_Texts.speed, m_Curve);
GUIMinMaxRange(s_Texts.speedRange, m_Range);
}
override public void UpdateCullingSupportedString(ref string text)
{
Init();
string failureReason = string.Empty;
if (!m_Curve.SupportsProcedural(ref failureReason))
text += "\nLifetime By Emitter Speed module curve: " + failureReason;
}
}
} // namespace UnityEditor
| UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/LifetimeByEmitterSpeedModuleUI.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/LifetimeByEmitterSpeedModuleUI.cs",
"repo_id": "UnityCsReference",
"token_count": 845
} | 418 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
class VelocityModuleUI : ModuleUI
{
SerializedMinMaxCurve m_X;
SerializedMinMaxCurve m_Y;
SerializedMinMaxCurve m_Z;
SerializedMinMaxCurve m_OrbitalX;
SerializedMinMaxCurve m_OrbitalY;
SerializedMinMaxCurve m_OrbitalZ;
SerializedMinMaxCurve m_OrbitalOffsetX;
SerializedMinMaxCurve m_OrbitalOffsetY;
SerializedMinMaxCurve m_OrbitalOffsetZ;
SerializedMinMaxCurve m_Radial;
SerializedProperty m_InWorldSpace;
SerializedMinMaxCurve m_SpeedModifier;
class Texts
{
public GUIContent linearX = EditorGUIUtility.TrTextContent("Linear X", "Apply linear velocity to particles.");
public GUIContent orbitalX = EditorGUIUtility.TrTextContent("Orbital X", "Apply orbital velocity to particles, which will rotate them around the center of the system.");
public GUIContent orbitalOffsetX = EditorGUIUtility.TrTextContent("Offset X", "Apply an offset to the center of rotation.");
public GUIContent y = EditorGUIUtility.TextContent("Y");
public GUIContent z = EditorGUIUtility.TextContent("Z");
public GUIContent space = EditorGUIUtility.TrTextContent("Space", "Specifies if the velocity values are in local space (rotated with the transform) or world space.");
public GUIContent speedMultiplier = EditorGUIUtility.TrTextContent("Speed Modifier", "Multiply the particle speed by this value");
public GUIContent radial = EditorGUIUtility.TrTextContent("Radial", "Apply radial velocity to particles, which will project them out from the center of the system.");
public GUIContent linearSpace = EditorGUIUtility.TrTextContent("Space", "Specifies if the velocity values are in local space (rotated with the transform) or world space.");
public string[] spaces = { "Local", "World" };
}
static Texts s_Texts;
public VelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName)
: base(owner, o, "VelocityModule", displayName)
{
m_ToolTip = "Controls the velocity of each particle during its lifetime.";
}
protected override void Init()
{
// Already initialized?
if (m_X != null)
return;
if (s_Texts == null)
s_Texts = new Texts();
m_X = new SerializedMinMaxCurve(this, s_Texts.linearX, "x", kUseSignedRange);
m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", kUseSignedRange);
m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z", kUseSignedRange);
m_OrbitalX = new SerializedMinMaxCurve(this, s_Texts.orbitalX, "orbitalX", kUseSignedRange);
m_OrbitalY = new SerializedMinMaxCurve(this, s_Texts.y, "orbitalY", kUseSignedRange);
m_OrbitalZ = new SerializedMinMaxCurve(this, s_Texts.z, "orbitalZ", kUseSignedRange);
m_OrbitalOffsetX = new SerializedMinMaxCurve(this, s_Texts.orbitalOffsetX, "orbitalOffsetX", kUseSignedRange);
m_OrbitalOffsetY = new SerializedMinMaxCurve(this, s_Texts.y, "orbitalOffsetY", kUseSignedRange);
m_OrbitalOffsetZ = new SerializedMinMaxCurve(this, s_Texts.z, "orbitalOffsetZ", kUseSignedRange);
m_Radial = new SerializedMinMaxCurve(this, s_Texts.radial, "radial", kUseSignedRange);
m_InWorldSpace = GetProperty("inWorldSpace");
m_SpeedModifier = new SerializedMinMaxCurve(this, s_Texts.speedMultiplier, "speedModifier", kUseSignedRange);
}
override public void OnInspectorGUI(InitialModuleUI initial)
{
GUITripleMinMaxCurve(GUIContent.none, s_Texts.linearX, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null);
EditorGUI.indentLevel++;
GUIBoolAsPopup(s_Texts.linearSpace, m_InWorldSpace, s_Texts.spaces);
EditorGUI.indentLevel--;
GUITripleMinMaxCurve(GUIContent.none, s_Texts.orbitalX, m_OrbitalX, s_Texts.y, m_OrbitalY, s_Texts.z, m_OrbitalZ, null);
GUITripleMinMaxCurve(GUIContent.none, s_Texts.orbitalOffsetX, m_OrbitalOffsetX, s_Texts.y, m_OrbitalOffsetY, s_Texts.z, m_OrbitalOffsetZ, null);
EditorGUI.indentLevel++;
GUIMinMaxCurve(s_Texts.radial, m_Radial);
EditorGUI.indentLevel--;
GUIMinMaxCurve(s_Texts.speedMultiplier, m_SpeedModifier);
}
override public void UpdateCullingSupportedString(ref string text)
{
Init();
string failureReason = string.Empty;
if (!m_X.SupportsProcedural(ref failureReason))
text += "\nVelocity over Lifetime module curve X: " + failureReason;
failureReason = string.Empty;
if (!m_Y.SupportsProcedural(ref failureReason))
text += "\nVelocity over Lifetime module curve Y: " + failureReason;
failureReason = string.Empty;
if (!m_Z.SupportsProcedural(ref failureReason))
text += "\nVelocity over Lifetime module curve Z: " + failureReason;
failureReason = string.Empty;
if (m_SpeedModifier.state != MinMaxCurveState.k_Scalar || m_SpeedModifier.maxConstant != 1.0f)
text += "\nVelocity over Lifetime module curve Speed Multiplier is being used";
failureReason = string.Empty;
if (m_OrbitalX.maxConstant != 0.0f || m_OrbitalY.maxConstant != 0.0f || m_OrbitalZ.maxConstant != 0.0f)
text += "\nVelocity over Lifetime module orbital velocity is being used";
failureReason = string.Empty;
if (m_Radial.maxConstant != 0.0f)
text += "\nVelocity over Lifetime module radial velocity is being used";
}
}
} // namespace UnityEditor
| UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/VelocityModuleUI.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/VelocityModuleUI.cs",
"repo_id": "UnityCsReference",
"token_count": 2586
} | 419 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine
{
//TODO: We should move this type into the VehicleModule assembly when possible.
// WheelFrictionCurve is used by the WheelCollider to describe friction properties of the wheel tire.
public struct WheelFrictionCurve
{
private float m_ExtremumSlip;
private float m_ExtremumValue;
private float m_AsymptoteSlip;
private float m_AsymptoteValue;
private float m_Stiffness;
public float extremumSlip { get { return m_ExtremumSlip; } set { m_ExtremumSlip = value; } }
public float extremumValue { get { return m_ExtremumValue; } set { m_ExtremumValue = value; } }
public float asymptoteSlip { get { return m_AsymptoteSlip; } set { m_AsymptoteSlip = value; } }
public float asymptoteValue { get { return m_AsymptoteValue; } set { m_AsymptoteValue = value; } }
public float stiffness { get { return m_Stiffness; } set { m_Stiffness = value; } }
}
}
| UnityCsReference/Modules/Physics/Managed/WheelFrictionCurve.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/Managed/WheelFrictionCurve.cs",
"repo_id": "UnityCsReference",
"token_count": 411
} | 420 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Bindings;
namespace UnityEngine
{
[NativeHeader("Modules/Physics/Joint.h")]
[NativeClass("Unity::Joint")]
public class Joint : Component
{
extern public Rigidbody connectedBody { get; set; }
extern public ArticulationBody connectedArticulationBody { get; set; }
extern public Vector3 axis { get; set; }
extern public Vector3 anchor { get; set; }
extern public Vector3 connectedAnchor { get; set; }
extern public bool autoConfigureConnectedAnchor { get; set; }
extern public float breakForce { get; set; }
extern public float breakTorque { get; set; }
extern public bool enableCollision { get; set; }
extern public bool enablePreprocessing { get; set; }
extern public float massScale { get; set; }
extern public float connectedMassScale { get; set; }
extern private void GetCurrentForces(ref Vector3 linearForce, ref Vector3 angularForce);
public Vector3 currentForce
{
get
{
Vector3 force = Vector3.zero;
Vector3 torque = Vector3.zero;
GetCurrentForces(ref force, ref torque);
return force;
}
}
public Vector3 currentTorque
{
get
{
Vector3 force = Vector3.zero;
Vector3 torque = Vector3.zero;
GetCurrentForces(ref force, ref torque);
return torque;
}
}
extern internal Matrix4x4 GetLocalPoseMatrix(int bodyIndex);
}
}
| UnityCsReference/Modules/Physics/ScriptBindings/Joint.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/ScriptBindings/Joint.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 764
} | 421 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.ComponentModel;
namespace UnityEngine
{
public partial class Rigidbody
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please use Rigidbody.linearDamping instead. (UnityUpgradable) -> linearDamping")]
public float drag { get => linearDamping; set => linearDamping = value; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please use Rigidbody.angularDamping instead. (UnityUpgradable) -> angularDamping")]
public float angularDrag { get => angularDamping; set => angularDamping = value; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please use Rigidbody.linearVelocity instead. (UnityUpgradable) -> linearVelocity")]
public Vector3 velocity { get => linearVelocity; set => linearVelocity = value; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The sleepVelocity is no longer supported. Use sleepThreshold. Note that sleepThreshold is energy but not velocity.", true)]
public float sleepVelocity { get { return 0; } set { } }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The sleepAngularVelocity is no longer supported. Use sleepThreshold to specify energy.", true)]
public float sleepAngularVelocity { get { return 0; } set { } }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use Rigidbody.maxAngularVelocity instead.")]
public void SetMaxAngularVelocity(float a) { maxAngularVelocity = a; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Cone friction is no longer supported.", true)]
public bool useConeFriction { get { return false; } set { } }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please use Rigidbody.solverIterations instead. (UnityUpgradable) -> solverIterations", true)]
public int solverIterationCount { get { return solverIterations; } set { solverIterations = value; } }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please use Rigidbody.solverVelocityIterations instead. (UnityUpgradable) -> solverVelocityIterations", true)]
public int solverVelocityIterationCount { get { return solverVelocityIterations; } set { solverVelocityIterations = value; } }
}
}
| UnityCsReference/Modules/Physics/ScriptBindings/Rigidbody.deprecated.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/ScriptBindings/Rigidbody.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 855
} | 422 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.EditorTools;
namespace UnityEditor
{
[EditorTool("Edit Edge Collider 2D", typeof(EdgeCollider2D))]
class EdgeCollider2DTool : EditablePath2DTool
{
protected override void CollectEditablePaths(List<EditablePath2D> paths)
{
foreach (var collider in targets)
{
if (collider is EdgeCollider2D edgeCollider2D)
{
// Only add paths that are valid.
if (edgeCollider2D.pointCount > 1)
paths.Add(new EdgeColliderPath(edgeCollider2D));
}
}
}
}
class EdgeColliderPath : EditablePath2D
{
List<Vector2> m_Points2D;
EdgeCollider2D m_Collider;
public override Matrix4x4 localToWorldMatrix => m_Collider.transform.localToWorldMatrix;
public EdgeColliderPath(EdgeCollider2D target) : base(false, 0, 2)
{
m_Collider = target;
m_Points2D = new List<Vector2>();
Update();
}
public override IList<Vector2> GetPoints()
{
Vector2 offset = m_Collider.offset;
m_Collider.GetPoints(m_Points2D);
for (int i = 0, c = m_Points2D.Count; i < c; i++)
m_Points2D[i] += offset;
return m_Points2D;
}
public override void SetPoints(Vector3[] points)
{
Vector2 offset = m_Collider.offset;
int pointCount = points.Length;
m_Points2D.Clear();
m_Points2D.Capacity = pointCount;
for (int i = 0; i < pointCount; i++)
m_Points2D.Add((Vector2)points[i] - offset);
Undo.RecordObject(m_Collider, "Edit Collider");
m_Collider.SetPoints(m_Points2D);
}
}
}
| UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EdgeCollider2DTool.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EdgeCollider2DTool.cs",
"repo_id": "UnityCsReference",
"token_count": 991
} | 423 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.EditorTools;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace UnityEditor
{
[EditorTool("Edit Hinge Joint 2D", typeof(HingeJoint2D))]
class HingeJoint2DTool : EditorTool, IDrawSelectedHandles
{
protected static class Styles
{
public static readonly string editAngularLimitsUndoMessage = EditorGUIUtility.TrTextContent("Change Joint Angular Limits").text;
public static readonly Color handleColor = new Color(0f, 1f, 0f, 0.7f);
public static readonly float handleRadius = 0.8f;
}
private JointAngularLimitHandle2D m_AngularLimitHandle = new JointAngularLimitHandle2D();
private static readonly Quaternion s_RightHandedHandleOrientationOffset =
Quaternion.AngleAxis(180f, Vector3.right) * Quaternion.AngleAxis(90f, Vector3.up);
private static readonly Quaternion s_LeftHandedHandleOrientationOffset =
Quaternion.AngleAxis(180f, Vector3.forward) * Quaternion.AngleAxis(90f, Vector3.up);
static Matrix4x4 GetAnchorSpaceMatrix(Transform transform)
{
// Anchor space transformation matrix.
return Matrix4x4.TRS(transform.position, Quaternion.Euler(0, 0, transform.rotation.eulerAngles.z), transform.lossyScale);
}
protected static Vector3 TransformPoint(Transform transform, Vector3 position)
{
// Local to World.
return GetAnchorSpaceMatrix(transform).MultiplyPoint(position);
}
protected static Vector3 InverseTransformPoint(Transform transform, Vector3 position)
{
// World to Local.
return GetAnchorSpaceMatrix(transform).inverse.MultiplyPoint(position);
}
void OnEnable()
{
m_AngularLimitHandle.handleColor = Color.white;
// +/-PHYSICS_2D_LARGE_RANGE_CLAMP, which is currently used in JointAngleLimits2D.CheckConsistency().
m_AngularLimitHandle.range = new Vector2(-1e+6f, 1e+6f);
}
public override GUIContent toolbarIcon
{
get { return EditorGUIUtility.IconContent("JointAngularLimits"); }
}
public override void OnToolGUI(EditorWindow window)
{
foreach (var obj in targets)
{
if (obj is HingeJoint2D)
{
// Ignore disabled joint.
var hingeJoint2D = obj as HingeJoint2D;
if (hingeJoint2D.enabled)
{
DrawHandle(true, hingeJoint2D, m_AngularLimitHandle);
}
}
}
}
public void OnDrawHandles()
{
foreach (var obj in targets)
{
if (obj is HingeJoint2D)
{
// Ignore disabled joint.
var hingeJoint2D = obj as HingeJoint2D;
if (hingeJoint2D.enabled)
{
DrawHandle(false, hingeJoint2D, m_AngularLimitHandle);
}
}
} }
public static void DrawHandle(bool editMode, HingeJoint2D hingeJoint2D, JointAngularLimitHandle2D angularLimitHandle)
{
// Only display control handles on manipulator if in edit mode.
if (editMode)
angularLimitHandle.angleHandleDrawFunction = ArcHandle.DefaultAngleHandleDrawFunction;
else
angularLimitHandle.angleHandleDrawFunction = null;
// Fetch the reference angle which acts as an offset to the absolute angles this gizmo is displaying/editing.
var referenceAngle = hingeJoint2D.referenceAngle;
// Fetch the joint limits.
var limit = hingeJoint2D.limits;
// Set the limit handle.
angularLimitHandle.jointMotion = hingeJoint2D.useLimits ? JointAngularLimitHandle2D.JointMotion.Limited : JointAngularLimitHandle2D.JointMotion.Free;
angularLimitHandle.min = limit.min + referenceAngle;
angularLimitHandle.max = limit.max + referenceAngle;
// Fetch if we're using the connected anchor.
// NOTE: If we're not then we want to draw the gizmo at the body position.
var usingConnectedAnchor = hingeJoint2D.useConnectedAnchor;
// To enhance usability, orient the manipulator to best illustrate its affects on the dynamic body in the system.
var dynamicBody = hingeJoint2D.attachedRigidbody;
var dynamicBodyLocalReferencePosition = Vector3.right;
var dynamicAnchor = usingConnectedAnchor ? hingeJoint2D.anchor : Vector2.zero;
var connectedBody = usingConnectedAnchor ? hingeJoint2D.connectedBody : null;
var handleOrientationOffset = s_RightHandedHandleOrientationOffset;
if (dynamicBody.bodyType != RigidbodyType2D.Dynamic
&& hingeJoint2D.connectedBody != null
&& hingeJoint2D.connectedBody.bodyType == RigidbodyType2D.Dynamic)
{
dynamicBody = hingeJoint2D.connectedBody;
dynamicBodyLocalReferencePosition = Vector3.left;
dynamicAnchor = usingConnectedAnchor ? hingeJoint2D.connectedAnchor : Vector2.zero;
connectedBody = usingConnectedAnchor ? hingeJoint2D.connectedBody : null;
handleOrientationOffset = s_LeftHandedHandleOrientationOffset;
}
var handlePosition = TransformPoint(dynamicBody.transform, dynamicAnchor);
var handleOrientation = (
connectedBody == null ?
Quaternion.identity :
Quaternion.LookRotation(Vector3.forward, connectedBody.transform.rotation * Vector3.up)
) * handleOrientationOffset;
var dynamicActorReferencePosition =
handlePosition
+ Quaternion.LookRotation(Vector3.forward, dynamicBody.transform.rotation * Vector3.up)
* dynamicBodyLocalReferencePosition;
var handleMatrix = Matrix4x4.TRS(handlePosition, handleOrientation, Vector3.one);
EditorGUI.BeginChangeCheck();
using (new Handles.DrawingScope(Styles.handleColor, handleMatrix))
{
var radius = HandleUtility.GetHandleSize(Vector3.zero) * Styles.handleRadius;
angularLimitHandle.radius = radius;
// Reference line within arc to illustrate affected local axis.
Handles.DrawLine(
Vector3.zero,
handleMatrix.inverse.MultiplyPoint3x4(dynamicActorReferencePosition).normalized * radius
);
angularLimitHandle.DrawHandle();
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(hingeJoint2D, Styles.editAngularLimitsUndoMessage);
limit = hingeJoint2D.limits;
limit.min = angularLimitHandle.min - referenceAngle;
limit.max = angularLimitHandle.max - referenceAngle;
hingeJoint2D.limits = limit;
dynamicBody.WakeUp();
}
}
}
}
| UnityCsReference/Modules/Physics2DEditor/Managed/Joints/HingeJoint2DTool.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/HingeJoint2DTool.cs",
"repo_id": "UnityCsReference",
"token_count": 3377
} | 424 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.EditorTools;
using UnityEngine;
namespace UnityEditor
{
[EditorTool("Articulation Body Anchor Transform Tool", typeof(ArticulationBody))]
class ArticulationBodyAnchorTransformTool : EditorTool
{
protected static class Styles
{
public static readonly GUIContent toolbarIcon = new GUIContent(
EditorGUIUtility.IconContent("AnchorTransformTool").image,
L10n.Tr("Edit the anchor transforms of this Articulation Body"));
}
public override GUIContent toolbarIcon => Styles.toolbarIcon;
public override void OnToolGUI(EditorWindow window)
{
foreach (var obj in targets)
{
ArticulationBody body = obj as ArticulationBody;
if (body == null || body.isRoot)
continue;
ArticulationBody parentBody = ArticulationBodyEditorCommon.FindEnabledParentArticulationBody(body);
{
Vector3 localAnchorT = body.anchorPosition;
Quaternion localAnchorR = body.anchorRotation;
EditorGUI.BeginChangeCheck();
DisplayProperAnchorHandle(body, ref localAnchorT, ref localAnchorR);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changing Articulation body anchor position/rotation");
body.anchorPosition = localAnchorT;
body.anchorRotation = localAnchorR;
}
}
if (!body.matchAnchors)
{
Vector3 localAnchorT = body.parentAnchorPosition;
Quaternion localAnchorR = body.parentAnchorRotation;
EditorGUI.BeginChangeCheck();
DisplayProperAnchorHandle(parentBody, ref localAnchorT, ref localAnchorR);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changing Articulation body parent anchor position/rotation");
body.parentAnchorPosition = localAnchorT;
body.parentAnchorRotation = localAnchorR;
}
}
}
}
private void DisplayProperAnchorHandle(ArticulationBody body, ref Vector3 anchorPos, ref Quaternion anchorRot)
{
// Anchors are relative to the body here, and that includes scale.
// However, we don't want to pass scale to DrawingScope - because that transforms the gizmos themselves.
// For that reason, we add and remove scale to the position manually when drawing.
Vector3 lossyScale = body.transform.lossyScale;
Vector3 inverseScale = new Vector3(1 / lossyScale.x, 1 / lossyScale.y, 1 / lossyScale.z);
var bodySpace = Matrix4x4.TRS(body.transform.position, body.transform.rotation, Vector3.one);
using (new Handles.DrawingScope(bodySpace))
{
Vector3 scaledPos = Vector3.Scale(anchorPos, lossyScale);
anchorRot = Handles.RotationHandle(anchorRot, scaledPos);
// We use the scaled vector to position the gizmo, but we need to unscale it before applying the position when editing
anchorPos = Vector3.Scale(Handles.PositionHandle(scaledPos, anchorRot), inverseScale);
}
}
}
}
| UnityCsReference/Modules/PhysicsEditor/ArticulatonBodyAnchorTransformTool.cs/0 | {
"file_path": "UnityCsReference/Modules/PhysicsEditor/ArticulatonBodyAnchorTransformTool.cs",
"repo_id": "UnityCsReference",
"token_count": 1687
} | 425 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using System;
using System.Collections.Generic;
using static UnityEditor.PhysicsVisualizationSettings;
using static UnityEditor.PhysicsDebugDraw;
using Unity.Collections;
namespace UnityEditor
{
public partial class PhysicsDebugWindow : EditorWindow
{
private const float c_LineThickness = 2f;
private const float c_ConeSize = 0.5f;
private const float c_MaxDistanceFallback = 500f;
[SerializeField] Dictionary<Query, ShapeDraw> m_ShapesToDraw = new Dictionary<Query, ShapeDraw>();
#region Query shape definitions
private abstract class ShapeDraw
{
private readonly Func<bool> m_GetShowShape;
protected ShapeDraw(QueryFilter type)
{
m_GetShowShape = () => GetQueryFilterState(type);
}
protected void InitDraw()
{
Handles.color = queryColor;
Handles.zTest = UnityEngine.Rendering.CompareFunction.Less;
}
public abstract void Draw();
}
private abstract class ShapeCastDraw : ShapeDraw
{
protected bool m_IsFiniteDistance = true;
protected float m_Distance;
protected Vector3 m_Direction;
protected Quaternion m_LookRotation;
protected Vector3[] m_Points;
protected Vector3[] m_SecondaryPoints;
protected Vector3[] m_ConePoints;
protected ShapeDraw m_PrimaryShape;
protected ShapeDraw m_SecondaryShape;
protected ShapeCastDraw(QueryFilter type
, Vector3 direction, float distance)
: base(type)
{
m_IsFiniteDistance = IsFinite(distance);
m_Distance = distance;
m_Direction = direction;
m_LookRotation = direction == Vector3.zero ? Quaternion.identity : Quaternion.LookRotation(direction);
}
public override void Draw()
{
InitDraw();
if(m_PrimaryShape != null)
m_PrimaryShape.Draw();
for (int i = 0; i < m_Points.Length; i++)
{
Handles.DrawLine(m_Points[i], m_SecondaryPoints[i], c_LineThickness);
// Makes the arrow heads a lot nicer for close casts
var cone = Mathf.Lerp(0f, c_ConeSize, m_Distance / 20f);
cone = Mathf.Clamp(cone, 0.1f, c_ConeSize);
Handles.ConeHandleCap(0, m_ConePoints[i], m_LookRotation, cone, EventType.Repaint);
}
if (m_IsFiniteDistance && m_SecondaryShape != null)
m_SecondaryShape.Draw();
}
protected static bool IsFinite(float f)
{
if (f == Mathf.Infinity || f == Mathf.NegativeInfinity || f == float.NaN)
return false;
return true;
}
protected void InitPoints()
{
GetSecondaryPoints();
GetConePoints();
}
private void GetSecondaryPoints()
{
m_SecondaryPoints = new Vector3[m_Points.Length];
for (int i = 0; i < m_Points.Length; i++)
{
m_SecondaryPoints[i] = m_Points[i] + m_Direction * (m_IsFiniteDistance ? Mathf.Min(m_Distance, c_MaxDistanceFallback) : c_MaxDistanceFallback);
}
}
private void GetConePoints()
{
m_ConePoints = new Vector3[m_SecondaryPoints.Length];
if (m_IsFiniteDistance)
{
for (int i = 0; i < m_SecondaryPoints.Length; i++)
m_ConePoints[i] = (m_Points[i] + m_SecondaryPoints[i]) / 2f;
}
else
{
for (int i = 0; i < m_SecondaryPoints.Length; i++)
m_ConePoints[i] = m_Points[i] + m_Direction * 2f;
}
}
}
private class RayCast : ShapeCastDraw
{
public RayCast(Vector3 origin, Vector3 direction, float distance, QueryFilter type)
: base(type, direction, distance)
{
m_PrimaryShape = null;
m_SecondaryPoints = null;
m_Points = new Vector3[1];
m_Points[0] = origin;
InitPoints();
}
}
private class SphereOvelap : ShapeDraw
{
private Vector3 m_Position;
private float m_Radius;
private readonly float h;
private readonly float r2;
public SphereOvelap(Vector3 position, float radius, QueryFilter type)
: base(type)
{
m_Position = position;
m_Radius = radius;
h = m_Radius * 0.5f;
r2 = Mathf.Sqrt(2f * h * m_Radius - h * h);
}
public override void Draw()
{
InitDraw();
Handles.DrawWireDisc(m_Position, Vector3.up, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Position + new Vector3(0f, h, 0f), Vector3.up, r2, c_LineThickness);
Handles.DrawWireDisc(m_Position + new Vector3(0f, -h, 0f), Vector3.up, r2, c_LineThickness);
Handles.DrawWireDisc(m_Position, Vector3.right, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Position, new Vector3(1f, 0f, 1f), m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Position, new Vector3(1f, 0f, -1f), m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Position, new Vector3(0, 0f, 1f), m_Radius, c_LineThickness);
}
}
private class SphereCast : ShapeCastDraw
{
public SphereCast(Vector3 origin, float radius, Vector3 direction, float distance, QueryFilter type)
:base (type, direction, distance)
{
m_PrimaryShape = new SphereOvelap(origin, radius, type);
var inPlane = new Vector3(1f, 0f, 0f);
var perpendicular1 = m_LookRotation * inPlane;
var perpendicular2 = Vector3.Cross(m_Direction, perpendicular1);
m_Points = new Vector3[4];
m_Points[0] = origin + perpendicular1 * radius;
m_Points[1] = origin + (perpendicular1 * -1f) * radius;
m_Points[2] = origin + perpendicular2 * radius;
m_Points[3] = origin + (perpendicular2 * -1f) * radius;
InitPoints();
m_SecondaryShape = m_IsFiniteDistance ? new SphereOvelap(origin + m_Direction * distance, radius, type) : null;
}
}
private class BoxOverlap : ShapeDraw
{
public Vector3[] Corners { get; private set; } = new Vector3[8];
public BoxOverlap(Vector3 center, Vector3 halfExtents, Quaternion orientation, QueryFilter type)
: base(type)
{
Corners[0] = center + halfExtents;
Corners[1] = center - halfExtents;
Corners[2] = center + new Vector3(-halfExtents.x, halfExtents.y, halfExtents.z);
Corners[3] = center + new Vector3(halfExtents.x, -halfExtents.y, halfExtents.z);
Corners[4] = center + new Vector3(halfExtents.x, halfExtents.y, -halfExtents.z);
Corners[5] = center + new Vector3(halfExtents.x, -halfExtents.y, -halfExtents.z);
Corners[6] = center + new Vector3(-halfExtents.x, -halfExtents.y, halfExtents.z);
Corners[7] = center + new Vector3(-halfExtents.x, halfExtents.y, -halfExtents.z);
for (int i = 0; i < Corners.Length; i++)
{
Corners[i] = orientation * (Corners[i] - center) + center;
}
}
public override void Draw()
{
InitDraw();
//Front face
Handles.DrawLine(Corners[1], Corners[5], c_LineThickness);
Handles.DrawLine(Corners[5], Corners[4], c_LineThickness);
Handles.DrawLine(Corners[4], Corners[7], c_LineThickness);
Handles.DrawLine(Corners[7], Corners[1], c_LineThickness);
//Back face
Handles.DrawLine(Corners[0], Corners[3], c_LineThickness);
Handles.DrawLine(Corners[3], Corners[6], c_LineThickness);
Handles.DrawLine(Corners[6], Corners[2], c_LineThickness);
Handles.DrawLine(Corners[2], Corners[0], c_LineThickness);
//Connections
Handles.DrawLine(Corners[0], Corners[4], c_LineThickness);
Handles.DrawLine(Corners[3], Corners[5], c_LineThickness);
Handles.DrawLine(Corners[6], Corners[1], c_LineThickness);
Handles.DrawLine(Corners[2], Corners[7], c_LineThickness);
}
}
private class BoxCast : ShapeCastDraw
{
public BoxCast(Vector3 center, Vector3 halfExtents, Quaternion orientation, Vector3 direction, float distance, QueryFilter type)
: base(type, direction, distance)
{
var box = new BoxOverlap(center, halfExtents, orientation, type);
m_PrimaryShape = box;
m_Points = box.Corners;
InitPoints();
m_SecondaryShape = m_IsFiniteDistance ? new BoxOverlap(center + m_Direction * distance, halfExtents, orientation, type) : null;
}
}
private class CapsuleOverlap : ShapeDraw
{
private Vector3 m_Point0; // The center of the sphere at the start of the capsule.
private Vector3 m_Point1; // The center of the sphere at the end of the capsule.
private float m_Radius;
public CapsuleOverlap(Vector3 point0, Vector3 point1, float radius, QueryFilter type)
: base(type)
{
m_Point0 = point0;
m_Point1 = point1;
m_Radius = radius;
}
public override void Draw()
{
InitDraw();
if(m_Point0 == m_Point1)
{
Handles.DrawWireDisc(m_Point0, Vector3.up, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point0, Vector3.right, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point0, new Vector3(1f, 0f, 1f), m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point0, new Vector3(1f, 0f, -1f), m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point0, new Vector3(0, 0f, 1f), m_Radius, c_LineThickness);
return;
}
Quaternion p1Rotation = Quaternion.LookRotation(m_Point0 - m_Point1);
Quaternion p2Rotation = Quaternion.LookRotation(m_Point1 - m_Point0);
float c = Vector3.Dot((m_Point0 - m_Point1).normalized, Vector3.up);
if (c == 1f || c == -1f)
{
p2Rotation = Quaternion.Euler(p2Rotation.eulerAngles.x, p2Rotation.eulerAngles.y + 180f, p2Rotation.eulerAngles.z);
}
// First side
Handles.DrawWireArc(m_Point0, p1Rotation * Vector3.left, p1Rotation * Vector3.down, 180f, m_Radius, c_LineThickness);
Handles.DrawWireArc(m_Point0, p1Rotation * Vector3.up, p1Rotation * Vector3.left, 180f, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point0, (m_Point1 - m_Point0).normalized, m_Radius, c_LineThickness);
// Second side
Handles.DrawWireArc(m_Point1, p2Rotation * Vector3.left, p2Rotation * Vector3.down, 180f, m_Radius, c_LineThickness);
Handles.DrawWireArc(m_Point1, p2Rotation * Vector3.up, p2Rotation * Vector3.left, 180f, m_Radius, c_LineThickness);
Handles.DrawWireDisc(m_Point1, (m_Point0 - m_Point1).normalized, m_Radius, c_LineThickness);
// Lines
Handles.DrawLine(m_Point0 + p1Rotation * Vector3.down * m_Radius, m_Point1 + p2Rotation * Vector3.down * m_Radius, c_LineThickness);
Handles.DrawLine(m_Point0 + p1Rotation * Vector3.left * m_Radius, m_Point1 + p2Rotation * Vector3.right * m_Radius, c_LineThickness);
Handles.DrawLine(m_Point0 + p1Rotation * Vector3.up * m_Radius, m_Point1 + p2Rotation * Vector3.up * m_Radius, c_LineThickness);
Handles.DrawLine(m_Point0 + p1Rotation * Vector3.right * m_Radius, m_Point1 + p2Rotation * Vector3.left * m_Radius, c_LineThickness);
}
}
private class CapsuleCast : ShapeCastDraw
{
private Vector3 m_Center;
public CapsuleCast( Vector3 point1, Vector3 point2, float radius, Vector3 direction, float distance, QueryFilter type)
: base(type, direction, distance)
{
m_PrimaryShape = new CapsuleOverlap(point1, point2, radius, type);
var inPlane = new Vector3(1f, 0f, 0f);
var perpendicular1 = m_LookRotation * inPlane;
if (point1 == point2)
{
m_Center = point1;
var perpendicular2 = Vector3.Cross(m_Direction, perpendicular1);
m_Points = new Vector3[4];
m_Points[0] = point1 + perpendicular1 * radius;
m_Points[1] = point1 + (perpendicular1 * -1f) * radius;
m_Points[2] = point1 + perpendicular2 * radius;
m_Points[3] = point1 + (perpendicular2 * -1f) * radius;
}
else
{
m_Center = (point1 + point2) / 2f;
var capsuleDirection = (point1 - m_Center).normalized;
var perpendicular2 = Vector3.Cross(capsuleDirection, perpendicular1);
m_Points = new Vector3[10];
m_Points[0] = point1 + capsuleDirection * radius;
m_Points[1] = point2 + -1f * capsuleDirection * radius;
m_Points[2] = point1 + perpendicular1 * radius;
m_Points[3] = point1 + -1f * perpendicular1 * radius;
m_Points[4] = point2 + perpendicular1 * radius;
m_Points[5] = point2 + -1f * perpendicular1 * radius;
m_Points[6] = point1 + perpendicular2 * radius;
m_Points[7] = point1 + -1f * perpendicular2 * radius;
m_Points[8] = point2 + perpendicular2 * radius;
m_Points[9] = point2 + -1f * perpendicular2 * radius;
}
InitPoints();
m_SecondaryShape = m_IsFiniteDistance ? new CapsuleOverlap(point1 + m_Direction * distance, point2 + m_Direction * distance, radius, type) : null;
}
}
#endregion
private void DrawQueriesTab()
{
PropertyDrawingWrapper(Style.showQueries , QueryFilter.ShowQueries);
queryColor = EditorGUILayout.ColorField(Style.queryColor, queryColor);
EditorGUILayout.LabelField(Style.showShapes);
EditorGUI.indentLevel++;
PropertyDrawingWrapper(Style.sphereQueries, QueryFilter.Sphere);
PropertyDrawingWrapper(Style.boxQueries , QueryFilter.Box);
PropertyDrawingWrapper(Style.capsuleQueries , QueryFilter.Capsule);
PropertyDrawingWrapper(Style.rayQueries , QueryFilter.Ray);
EditorGUI.indentLevel--;
EditorGUILayout.LabelField(Style.showTypes);
EditorGUI.indentLevel++;
PropertyDrawingWrapper(Style.overlapQueries , QueryFilter.Overlap);
PropertyDrawingWrapper(Style.checkQueries , QueryFilter.Check);
PropertyDrawingWrapper(Style.castQueries , QueryFilter.Cast);
EditorGUI.indentLevel--;
maxNumberOfQueries = EditorGUILayout.IntField(
Style.maxNumberOfQueries, maxNumberOfQueries);
GUILayout.Space(4);
GUILayout.BeginHorizontal();
bool selectNone = GUILayout.Button(Style.showNone);
bool selectAll = GUILayout.Button(Style.showAll);
if (selectNone || selectAll)
{
SetQueryFilterState(QueryFilter.All, selectAll);
}
GUILayout.EndHorizontal();
}
private void PropertyDrawingWrapper(GUIContent label, QueryFilter filterMask)
{
var value = EditorGUILayout.Toggle(label, GetQueryFilterState(filterMask));
SetQueryFilterState(filterMask, value);
}
private void DrawCastsAndOverlaps()
{
foreach(var (query, shape) in m_ShapesToDraw)
shape.Draw();
}
private void ClearQueryShapes()
{
m_ShapesToDraw.Clear();
}
private void InsertShape(Query query, ShapeDraw shape)
{
if (m_ShapesToDraw.Count > maxNumberOfQueries)
return;
m_ShapesToDraw.Add(query, shape);
}
private void OnQueriesRetrieved(NativeArray<Query> array)
{
for (int i = 0; i < array.Length; i++)
ConstructQueryVisualizationShape(array[i]);
}
private static void ConstructQueryVisualizationShape(Query query)
{
if (!HasOpenInstances<PhysicsDebugWindow>() || s_Window == null)
return;
if (s_Window.m_ShapesToDraw.ContainsKey(query))
return;
if (!GetQueryFilterState(query.filter | QueryFilter.ShowQueries))
return;
if ((query.filter & QueryFilter.Box) != 0)
{
if ((query.filter & (QueryFilter.Check | QueryFilter.Overlap)) != 0)
s_Window.InsertShape(query, new BoxOverlap(query.v1, query.v2, query.q, query.filter));
else if ((query.filter & QueryFilter.Cast) != 0)
s_Window.InsertShape(query, new BoxCast(query.v1, query.v2, query.q, query.direction, query.distance, query.filter));
}
else if ((query.filter & QueryFilter.Sphere) != 0)
{
if ((query.filter & (QueryFilter.Check | QueryFilter.Overlap)) != 0)
s_Window.InsertShape(query, new SphereOvelap(query.v1, query.r, query.filter));
else if ((query.filter & QueryFilter.Cast) != 0)
s_Window.InsertShape(query, new SphereCast(query.v1, query.r, query.direction, query.distance, query.filter));
}
else if ((query.filter & QueryFilter.Capsule) != 0)
{
if ((query.filter & (QueryFilter.Check | QueryFilter.Overlap)) != 0)
s_Window.InsertShape(query, new CapsuleOverlap(query.v1, query.v2, query.r, query.filter));
else if ((query.filter & QueryFilter.Cast) != 0)
s_Window.InsertShape(query, new CapsuleCast(query.v1, query.v2, query.r, query.direction, query.distance, query.filter));
}
else if ((query.filter & QueryFilter.Ray) != 0)
{
if ((query.filter & QueryFilter.Cast) != 0)
s_Window.InsertShape(query, new RayCast(query.v1, query.direction, query.distance, query.filter));
}
}
}
}
| UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowQueries.cs/0 | {
"file_path": "UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowQueries.cs",
"repo_id": "UnityCsReference",
"token_count": 10065
} | 426 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using Object = UnityEngine.Object;
namespace UnityEditor.Presets
{
[NativeType(Header = "Modules/PresetsEditor/Public/Preset.h")]
[NativeHeader("Modules/PresetsEditor/Public/PresetManager.h")]
[UsedByNativeCode]
[HelpURL("https://docs.unity3d.com/2023.2/Documentation/Manual/Presets.html")]
[ExcludeFromPreset]
public sealed class Preset : Object
{
static readonly string[] s_EmptyArray = new string[0];
public Preset(Object source)
{
Internal_Create(this, source);
}
[NativeThrows]
static extern void Internal_Create([Writable] Preset notSelf, [NotNull] Object source);
public extern PropertyModification[] PropertyModifications
{
[NativeName("GetManagedPropertyModifications")]
get;
}
public extern string[] excludedProperties { get; set; }
public bool ApplyTo(Object target)
{
return ApplyTo(target, s_EmptyArray);
}
public extern bool ApplyTo([NotNull] Object target, string[] selectedPropertyPaths);
public extern bool DataEquals([NotNull] Object target);
public extern bool UpdateProperties([NotNull] Object source);
public extern PresetType GetPresetType();
public string GetTargetFullTypeName()
{
return GetPresetType().GetManagedTypeName();
}
public string GetTargetTypeName()
{
string fullTypeName = GetTargetFullTypeName();
int lastDot = fullTypeName.LastIndexOf(".");
if (lastDot == -1)
lastDot = fullTypeName.LastIndexOf(":");
if (lastDot != -1)
return fullTypeName.Substring(lastDot + 1);
return fullTypeName;
}
public extern bool IsValid();
internal extern bool IsCoupled();
public extern bool CanBeAppliedTo(Object target);
// Components returned by this method will have their GameObject hideFlags set with DontAllowDestruction.
// The HideFlags must be set to HideFlags.None before calling Destroy or DestroyImmediate on it.
internal extern Object GetReferenceObject();
[FreeFunction("GetDefaultPresetsForObject")]
public static extern Preset[] GetDefaultPresetsForObject([NotNull] Object target);
[Obsolete("Use GetDefaultPresetsForObject to get the full ordered list of default Presets that would be applied to that Object")]
public static Preset GetDefaultForObject(Object target)
{
var defaults = GetDefaultPresetsForObject(target);
return defaults.Length > 0 ? defaults[0] : null;
}
[Obsolete("Use GetDefaultPresetsForType to get the full list of default Presets for a given PresetType.")]
public static Preset GetDefaultForPreset(Preset preset)
{
if (preset == null)
throw new ArgumentNullException(nameof(preset));
var defaults = GetDefaultPresetsForType(preset.GetPresetType());
foreach (var defaultPreset in defaults)
{
if (defaultPreset.m_Filter == string.Empty)
return defaultPreset.m_Preset;
}
return null;
}
[FreeFunction("GetAllDefaultTypes")]
public static extern PresetType[] GetAllDefaultTypes();
[FreeFunction("GetDefaultPresetsForType")]
public static extern DefaultPreset[] GetDefaultPresetsForType(PresetType type);
[FreeFunction("SetDefaultPresetsForType")]
public static extern bool SetDefaultPresetsForType(PresetType type, DefaultPreset[] presets);
[Obsolete("Use SetDefaultPresetsForType instead.")]
public static bool SetAsDefault(Preset preset)
{
if (preset == null)
throw new ArgumentNullException(nameof(preset));
return SetDefaultPresetsForType(preset.GetPresetType(), new[] {new DefaultPreset {m_Filter = string.Empty, m_Preset = preset}});
}
public static void RemoveFromDefault(Preset preset)
{
var type = preset.GetPresetType();
var list = GetDefaultPresetsForType(type);
var newList = list.Where(d => d.preset != preset);
if (newList.Count() != list.Length)
SetDefaultPresetsForType(type, newList.ToArray());
}
[Obsolete("Use PresetType.IsValidDefault instead.")]
public static bool IsPresetExcludedFromDefaultPresets(Preset preset)
{
if (preset == null)
throw new ArgumentNullException(nameof(preset));
return !preset.GetPresetType().IsValidDefault();
}
[Obsolete("Use PresetType.IsValidDefault instead.")]
public static bool IsObjectExcludedFromDefaultPresets(Object target)
{
return !new PresetType(target).IsValidDefault();
}
[Obsolete("Use PresetType.IsValid instead.")]
public static bool IsObjectExcludedFromPresets(Object target)
{
return !new PresetType(target).IsValid();
}
public static bool IsEditorTargetAPreset(Object target)
{
return target is Component comp ? ((int)comp.gameObject.hideFlags == 93) : !AssetDatabase.Contains(target);
}
}
}
| UnityCsReference/Modules/PresetsEditor/Public/Preset.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/PresetsEditor/Public/Preset.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2284
} | 427 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEditor.Profiling;
using UnityEngine.Scripting;
namespace UnityEditor.Profiling
{
internal class EditorAnalyticsService : IAnalyticsService
{
AnalyticsResult IAnalyticsService.SendAnalytic(IAnalytic analytic)
{
return EditorAnalytics.SendAnalytic(analytic);
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/EditorAnalyticsService.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/EditorAnalyticsService.cs",
"repo_id": "UnityCsReference",
"token_count": 207
} | 428 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Text;
using UnityEditor;
using UnityEditor.Profiling;
using UnityEditorInternal;
using UnityEngine;
namespace Unity.Profiling.Editor.UI
{
class BottlenecksDetailsViewModelBuilder
{
const int k_FrameTimingManagerFixedDelay = 4;
const int k_MainThreadIndex = 0;
static readonly string k_BoundTitleFormat = $"<b>The {{0}} exceeded your target frame time in this frame.</b>";
static readonly string k_NotBoundTitleFormat = $"<b>The {{0}} within your target frame time in this frame.</b>";
static readonly string k_CpuBoundExplanationFormat = $"In this frame the CPU spent the majority of its time executing on the <b>{{0}} thread</b>. Therefore, you should initially focus on this to begin your investigation.";
static readonly string k_SuggestionTitle = $"<b>How to inspect further:</b>";
static readonly string k_CpuBoundSuggestion = $"To optimize your game’s CPU utilization, begin by using the <link={BottlenecksDetailsViewModel.k_DescriptionLinkId_CpuTimeline}><color={EditorGUIUtility.GetHyperlinkColorForSkin()}><u>CPU module’s Timeline view</u></color></link> to see which systems contributed the most to this time spent executing on the CPU.\n\nYou might also consider using the <link={BottlenecksDetailsViewModel.k_DescriptionLinkId_ProfileAnalyzer}><color={EditorGUIUtility.GetHyperlinkColorForSkin()}><u>Profile Analyzer</u></color></link> to perform a deeper statistical analysis and/or to compare Profiler captures after you have made some optimizations.";
static readonly string k_GpuBoundSuggestion = $"To optimize your game’s GPU utilization, use the <link={BottlenecksDetailsViewModel.k_DescriptionLinkId_FrameDebugger}><color={EditorGUIUtility.GetHyperlinkColorForSkin()}><u>Frame Debugger</u></color></link> to step through individual draw calls and see in detail how the scene is constructed from its graphical elements.\n\nYou might also consider using a native GPU profiler for the platform you are targeting. Please see the <link={BottlenecksDetailsViewModel.k_DescriptionLinkId_GpuProfilerDocumentation}><color={EditorGUIUtility.GetHyperlinkColorForSkin()}><u>Unity documentation</u></color></link> for more information.";
readonly IProfilerCaptureDataService m_DataService;
public BottlenecksDetailsViewModelBuilder(IProfilerCaptureDataService dataService)
{
m_DataService = dataService;
}
// Builds a new BottlenecksDetailsViewModel.
public BottlenecksDetailsViewModel Build(int frameIndex, UInt64 targetFrameDurationNs)
{
if (m_DataService.FrameCount == 0)
return null;
using var frameData = m_DataService.GetRawFrameDataView(frameIndex, k_MainThreadIndex);
if (!frameData.valid)
return null;
var cpuMainThreadDurationMarkerId = frameData.GetMarkerId("CPU Main Thread Active Time");
if (cpuMainThreadDurationMarkerId == FrameDataView.invalidMarkerId)
return null;
var cpuRenderThreadDurationMarkerId = frameData.GetMarkerId("CPU Render Thread Active Time");
if (cpuRenderThreadDurationMarkerId == FrameDataView.invalidMarkerId)
return null;
var cpuMainThreadDurationNs = Convert.ToUInt64(frameData.GetCounterValueAsLong(cpuMainThreadDurationMarkerId));
var cpuRenderThreadDurationNs = Convert.ToUInt64(frameData.GetCounterValueAsLong(cpuRenderThreadDurationMarkerId));
var cpuDurationNs = Math.Max(cpuMainThreadDurationNs, cpuRenderThreadDurationNs);
var gpuDurationNs = 0UL;
var frameTimingManagerFrameIndex = frameIndex + k_FrameTimingManagerFixedDelay;
using var frameTimingManagerFrameData = m_DataService.GetRawFrameDataView(frameTimingManagerFrameIndex, k_MainThreadIndex);
if (frameTimingManagerFrameData.valid)
{
var gpuDurationMarkerId = frameTimingManagerFrameData.GetMarkerId("GPU Frame Time");
if (gpuDurationMarkerId != FrameDataView.invalidMarkerId)
gpuDurationNs = Convert.ToUInt64(frameTimingManagerFrameData.GetCounterValueAsLong(gpuDurationMarkerId));
}
if (cpuDurationNs == 0 && gpuDurationNs == 0)
return null;
var localizedBottleneckDescription = BuildDescriptionText(
cpuDurationNs,
gpuDurationNs,
targetFrameDurationNs,
cpuMainThreadDurationNs,
cpuRenderThreadDurationNs);
return new BottlenecksDetailsViewModel(
cpuDurationNs,
gpuDurationNs,
targetFrameDurationNs,
localizedBottleneckDescription);
}
string BuildDescriptionText(
UInt64 cpuDurationNs,
UInt64 gpuDurationNs,
UInt64 targetFrameDurationNs,
UInt64 cpuMainThreadDurationNs,
UInt64 cpuRenderThreadDurationNs)
{
const string k_CpuName = "CPU";
const string k_GpuName = "GPU";
const string k_BothCpuGpuText = k_CpuName + " and the " + k_GpuName;
const string k_CpuIsText = k_CpuName + " is";
const string k_BothCpuGpuAreText = k_BothCpuGpuText + " are";
const string k_MainThreadName = "Main";
const string k_RenderThreadName = "Render";
var stringBuilder = new StringBuilder();
string localizedTitleFormat;
string processorText;
var cpuExceededTarget = cpuDurationNs > targetFrameDurationNs;
var gpuExceededTarget = gpuDurationNs > targetFrameDurationNs;
var isBound = cpuExceededTarget || gpuExceededTarget;
if (isBound)
{
localizedTitleFormat = L10n.Tr(k_BoundTitleFormat);
if (cpuExceededTarget && gpuExceededTarget)
processorText = k_BothCpuGpuText;
else if (cpuExceededTarget)
processorText = k_CpuName;
else
processorText = k_GpuName;
}
else
{
localizedTitleFormat = L10n.Tr(k_NotBoundTitleFormat);
if (IsInvalidDuration(gpuDurationNs))
processorText = k_CpuIsText;
else
processorText = k_BothCpuGpuAreText;
}
var localizedTitle = string.Format(localizedTitleFormat, processorText);
stringBuilder.Append(localizedTitle);
if (isBound)
{
stringBuilder.AppendLine();
stringBuilder.AppendLine();
if (cpuExceededTarget)
{
var longestThreadName = (cpuMainThreadDurationNs > cpuRenderThreadDurationNs) ? k_MainThreadName : k_RenderThreadName;
var localizedThreadDetailFormat = L10n.Tr(k_CpuBoundExplanationFormat);
var localizedThreadDetail = string.Format(localizedThreadDetailFormat, longestThreadName);
stringBuilder.AppendLine(localizedThreadDetail);
stringBuilder.AppendLine();
}
stringBuilder.AppendLine(L10n.Tr(k_SuggestionTitle));
if (cpuExceededTarget)
stringBuilder.Append(L10n.Tr(k_CpuBoundSuggestion));
if (gpuExceededTarget)
{
if (cpuExceededTarget)
{
stringBuilder.AppendLine();
stringBuilder.AppendLine();
}
stringBuilder.Append(L10n.Tr(k_GpuBoundSuggestion));
}
}
return stringBuilder.ToString();
}
static bool IsInvalidDuration(float durationNs)
{
// A value of -1 is what our existing counters API returns when there is no counter data in the selected frame.
// A value of 0 is what FTM will write when GPU misses the deadline and does not record a measurement.
return Mathf.Approximately(durationNs, -1f) || Mathf.Approximately(durationNs, 0f);
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Data/BottlenecksDetailsViewModelBuilder.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Data/BottlenecksDetailsViewModelBuilder.cs",
"repo_id": "UnityCsReference",
"token_count": 3593
} | 429 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace Unity.Profiling.Editor
{
[System.Serializable]
public readonly struct ProfilerCounterDescriptor
{
public ProfilerCounterDescriptor(string name, ProfilerCategory category) : this(name, category.Name) {}
public ProfilerCounterDescriptor(string name, string categoryName)
{
Name = name;
CategoryName = categoryName;
}
public readonly string Name { get; }
public readonly string CategoryName { get; }
public override string ToString() => $"{Name} ({CategoryName})";
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerCounterDescriptor.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerCounterDescriptor.cs",
"repo_id": "UnityCsReference",
"token_count": 261
} | 430 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using Unity.Profiling;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEditor.Profiling;
using UnityEditorInternal.Profiling;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityEditorInternal
{
[Serializable]
internal class ProfilerTimelineGUI : ProfilerFrameDataViewBase
{
const float k_TextFadeStartWidth = 50.0f;
const float k_TextFadeOutWidth = 20.0f;
const float k_LineHeight = 16.0f;
const float k_DefaultEmptySpaceBelowBars = k_LineHeight * 3f;
const float k_ExtraHeightPerThread = 4f;
const float k_FullThreadLineHeight = k_LineHeight + 0.55f;
const float k_GroupHeight = k_LineHeight + 4f;
const float k_ThreadMinHeightCollapsed = 2.0f;
const float k_ThreadSplitterHandleSize = 6f;
const int k_MaxNeighborFrames = 3;
const int k_MaxDisplayFrames = 1 + 2 * k_MaxNeighborFrames;
static readonly float[] k_TickModulos = { 0.001f, 0.005f, 0.01f, 0.05f, 0.1f, 0.5f, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 30000, 60000 };
const string k_TickFormatMilliseconds = "{0}ms";
const string k_TickFormatSeconds = "{0}s";
const int k_TickLabelSeparation = 60;
internal class ThreadInfo : IComparable<ThreadInfo>
{
public float height = 0;
public float linesToDisplay = 2f;
public ulong threadId;
public int threadIndex => threadIndices[k_MaxNeighborFrames];
public int[] threadIndices = new int[k_MaxDisplayFrames];
public int maxDepth;
string m_Name;
public string name
{
get => m_Name;
set
{
m_Name = value; m_Content = null;
}
}
[NonSerialized]
GUIContent m_Content;
public ThreadInfo(string name, ulong threadId, int threadIndex, int maxDepth, int linesToDisplay)
{
this.m_Name = name;
this.threadId = threadId;
for (var i = 0; i < k_MaxDisplayFrames; ++i)
threadIndices[i] = FrameDataView.invalidThreadIndex;
this.threadIndices[k_MaxNeighborFrames] = threadIndex;
this.linesToDisplay = linesToDisplay;
this.maxDepth = Mathf.Max(1, maxDepth);
}
public void Reset()
{
for (var j = 0; j < k_MaxDisplayFrames; ++j)
threadIndices[j] = FrameDataView.invalidThreadIndex;
maxDepth = -1;
ActiveFlowEvents?.Clear();
}
public void Update(string name, int threadIndex, int maxDepth)
{
if (this.name != name)
this.name = name;
this.threadIndices[k_MaxNeighborFrames] = threadIndex;
this.maxDepth = Mathf.Max(1, maxDepth);
}
public List<FlowEventData> ActiveFlowEvents { get; private set; } = null;
public void AddFlowEvent(FlowEventData d)
{
// Most threads don't have flow events - there are no reasons to allocate memory for those.
if (ActiveFlowEvents == null)
ActiveFlowEvents = new List<FlowEventData>();
ActiveFlowEvents.Add(d);
}
public GUIContent DisplayName(bool indent)
{
if (m_Content == null)
m_Content = CreateDisplayNameForThreadOrGroup(name, indent);
return m_Content;
}
public int CompareTo(ThreadInfo other)
{
if (this == other)
return 0;
var results = EditorUtility.NaturalCompare(name, other.name);
if (results != 0)
return results;
if (threadIndex != other.threadIndex)
return threadIndex < other.threadIndex ? -1 : 1;
return threadId.CompareTo(other.threadId);
}
public struct FlowEventData
{
public RawFrameDataView.FlowEvent flowEvent;
public int frameIndex;
public int threadIndex;
public bool hasParentSampleIndex
{
get
{
return (flowEvent.ParentSampleIndex > 0);
}
}
}
}
internal class GroupInfo
{
const int k_DefaultLineCountPerThread = 2;
public AnimBool expanded;
public string name;
public float height;
public List<ThreadInfo> threads;
public Dictionary<ulong, ThreadInfo> threadIdMap;
public int defaultLineCountPerThread = k_DefaultLineCountPerThread;
[NonSerialized]
GUIContent m_Content;
public GroupInfo(string name, UnityEngine.Events.UnityAction foldoutStateChangedCallback)
: this(name, foldoutStateChangedCallback, false) {}
public GroupInfo(string name, UnityEngine.Events.UnityAction foldoutStateChangedCallback, bool expanded, int defaultLineCountPerThread = k_DefaultLineCountPerThread, float height = k_GroupHeight)
{
this.name = name;
this.height = height;
this.defaultLineCountPerThread = defaultLineCountPerThread;
this.expanded = new AnimBool(expanded);
if (foldoutStateChangedCallback != null)
this.expanded.valueChanged.AddListener(foldoutStateChangedCallback);
threads = new List<ThreadInfo>();
threadIdMap = new Dictionary<ulong, ThreadInfo>();
}
public void Clear()
{
height = 0;
threads.Clear();
threadIdMap.Clear();
}
public GUIContent DisplayName
{
get
{
if (m_Content == null)
m_Content = CreateDisplayNameForThreadOrGroup(name, false);
return m_Content;
}
}
}
[NonSerialized]
List<GroupInfo> m_Groups = null;
[NonSerialized]
HashSet<DrawnFlowIndicatorCacheValue> m_DrawnFlowIndicatorsCache = new HashSet<DrawnFlowIndicatorCacheValue>(new DrawnFlowIndicatorCacheValueComparer());
// Not localizable strings - should match group names in native code.
const string k_MainGroupName = "";
const string k_JobSystemGroupName = "Job";
const string k_LoadingGroupName = "Loading";
const string k_ScriptingThreadsGroupName = "Scripting Threads";
const string k_BackgroundJobSystemGroupName = "Background Job";
const string k_ProfilerThreadsGroupName = "Profiler";
const string k_OtherThreadsGroupName = "Other Threads";
internal class Styles
{
public GUIStyle background = "OL Box";
public GUIStyle tooltip = "AnimationEventTooltip";
public GUIStyle tooltipArrow = "AnimationEventTooltipArrow";
public GUIStyle bar = "ProfilerTimelineBar";
public GUIStyle leftPane = "ProfilerTimelineLeftPane";
public GUIStyle rightPane = "ProfilerRightPane";
public GUIStyle foldout = "ProfilerTimelineFoldout";
public GUIStyle profilerGraphBackground = "ProfilerGraphBackground";
public GUIStyle timelineTick = "AnimationTimelineTick";
public GUIStyle rectangleToolSelection = "RectangleToolSelection";
public GUIStyle timeAreaToolbar = "TimeAreaToolbar";
public GUIStyle digDownArrow = "ProfilerTimelineDigDownArrow";
public GUIStyle rollUpArrow = "ProfilerTimelineRollUpArrow";
public GUIStyle bottomShadow = "BottomShadowInwards";
public string localizedStringTotalAcrossFrames = L10n.Tr("\n{0} total over {1} frames on thread '{2}'");
public string localizedStringTotalAcumulatedTime = L10n.Tr("\n\nCurrent frame accumulated time:");
public string localizedStringTotalInThread = L10n.Tr("\n{0} for {1} instances on thread '{2}'");
public string localizedStringTotalInFrame = L10n.Tr("\n{0} for {1} instances over {2} threads");
public string localizedStringUnnamedObject = L10n.Tr("<No Name>");
public Color frameDelimiterColor = Color.white.RGBMultiplied(0.4f);
Color m_RangeSelectionColorLight = new Color32(255, 255, 255, 90);
Color m_RangeSelectionColorDark = new Color32(200, 200, 200, 40);
public Color rangeSelectionColor => EditorGUIUtility.isProSkin ? m_RangeSelectionColorDark : m_RangeSelectionColorLight;
Color m_OutOfRangeColorLight = new Color32(160, 160, 160, 127);
Color m_OutOfRangeColorDark = new Color32(40, 40, 40, 127);
public Color outOfRangeColor => EditorGUIUtility.isProSkin ? m_OutOfRangeColorDark : m_OutOfRangeColorLight;
}
static Styles ms_Styles;
static Styles styles
{
get { return ms_Styles ?? (ms_Styles = new Styles()); }
}
class EntryInfo
{
public int frameId = FrameDataView.invalidOrCurrentFrameIndex;
public int threadIndex = FrameDataView.invalidThreadIndex;
public int sampleIndex = RawFrameDataView.invalidSampleIndex; // Uniquely identifies the sample for the thread and frame in a sense of RawFrameDataView.
public float relativeYPos = 0.0f;
public float time = 0.0f;
public float duration = 0.0f;
public string name = string.Empty;
public bool IsValid()
{
return this.name.Length > 0;
}
public bool Equals(int frameId, int threadIndex, int sampleIndex)
{
return frameId == this.frameId && threadIndex == this.threadIndex && sampleIndex == this.sampleIndex;
}
public virtual void Reset()
{
this.frameId = FrameDataView.invalidOrCurrentFrameIndex;
this.threadIndex = FrameDataView.invalidThreadIndex;
this.sampleIndex = RawFrameDataView.invalidSampleIndex;
this.relativeYPos = 0.0f;
this.time = 0.0f;
this.duration = 0.0f;
this.name = string.Empty;
}
}
class SelectedEntryInfo : EntryInfo
{
public const int invalidInstancIdCount = -1;
public const float invalidDuration = -1.0f;
// The associated GameObjects instance ID. Negative means Native Object, Positive means Managed Object, 0 means not set (as in, no object associated)
public int instanceId = 0;
public string metaData = string.Empty;
public float totalDurationForThread = invalidDuration;
public int instanceCountForThread = invalidInstancIdCount;
public float totalDurationForFrame = invalidDuration;
public int instanceCountForFrame = invalidInstancIdCount;
public int threadCount = 0;
public bool hasCallstack = false;
public string nonProxyName = null;
public ReadOnlyCollection<string> sampleStack = null;
public int nonProxyDepthDifference = 0;
public GUIContent cachedSelectionTooltipContent = null;
public float downwardsZoomableAreaSpaceNeeded = 0;
public List<RawFrameDataView.FlowEvent> FlowEvents { get; } = new List<RawFrameDataView.FlowEvent>();
public override void Reset()
{
base.Reset();
this.instanceId = 0;
this.metaData = string.Empty;
this.totalDurationForThread = invalidDuration;
this.instanceCountForThread = invalidInstancIdCount;
this.totalDurationForFrame = invalidDuration;
this.instanceCountForFrame = invalidInstancIdCount;
this.threadCount = 0;
this.hasCallstack = false;
this.nonProxyName = null;
this.sampleStack = null;
this.cachedSelectionTooltipContent = null;
this.nonProxyDepthDifference = 0;
this.downwardsZoomableAreaSpaceNeeded = 0;
FlowEvents.Clear();
}
}
struct TimelineIndexHelper
{
public static TimelineIndexHelper invalidIndex => new TimelineIndexHelper() { sampleIndex = RawFrameDataView.invalidSampleIndex };
public int sampleIndex { get; set; }
public bool valid => sampleIndex >= 0;
}
// a local cache of the marker Id path, which is modified in frames other than the one originally selected, in case the marker ids changed
// changing m_SelectionPendingTransfer.markerIdPath instead of this local one would potentially corrupt the markerIdPath in the original frame
// that would lead to confusion where it is assumed to be valid.
List<int> m_LocalSelectedItemMarkerIdPath = new List<int>();
ProfilerTimeSampleSelection m_SelectionPendingTransfer = null;
int m_ThreadIndexOfSelectionPendingTransfer = FrameDataView.invalidThreadIndex;
bool m_FrameSelectionVerticallyAfterTransfer = false;
bool m_Scheduled_FrameSelectionVertically = false;
public event Action<ProfilerTimeSampleSelection> selectionChanged;
struct RawSampleIterationInfo { public int partOfThePath; public int lastSampleIndexInScope; }
static RawSampleIterationInfo[] s_SkippedScopesCache = new RawSampleIterationInfo[1024];
static int[] s_LastSampleInScopeOfThePathCache = new int[1024];
static List<int> s_SampleIndexPathCache = new List<int>(1024);
[MethodImpl(256 /*MethodImplOptions.AggressiveInlining*/)]
static List<int> GetCachedSampleIndexPath(int requiredCapacity)
{
if (s_SampleIndexPathCache.Capacity < requiredCapacity)
s_SampleIndexPathCache.Capacity = requiredCapacity;
s_SampleIndexPathCache.Clear();
return s_SampleIndexPathCache;
}
[NonSerialized]
protected IProfilerSampleNameProvider m_ProfilerSampleNameProvider;
float scrollOffsetY
{
get { return -m_TimeArea.shownArea.y * m_TimeArea.scale.y; }
}
int maxContextFramesToShow => m_ProfilerWindow.ProfilerWindowOverheadIsAffectingProfilingRecordingData() ? 1 : k_MaxNeighborFrames;
[NonSerialized]
ZoomableArea m_TimeArea;
TickHandler m_HTicks;
SelectedEntryInfo m_SelectedEntry = new SelectedEntryInfo();
float m_SelectedThreadY = 0.0f;
float m_SelectedThreadYRange = 0.0f;
ThreadInfo m_SelectedThread = null;
float m_LastHeightForAllBars = -1;
float m_LastFullRectHeight = -1;
float m_MaxLinesToDisplayForTheCurrentlyModifiedSplitter = -1;
[NonSerialized]
int m_LastSelectedFrameIndex = FrameDataView.invalidThreadIndex;
[NonSerialized]
int m_LastMaxContextFramesToShow = -1;
[NonSerialized]
List<RawFrameDataView.FlowEvent> m_CachedThreadFlowEvents = new List<RawFrameDataView.FlowEvent>();
[Flags]
enum ProcessedInputs
{
MouseDown = 1 << 0,
PanningOrZooming = 1 << 1,
SplitterMoving = 1 << 2,
FrameSelection = 1 << 3,
RangeSelection = 1 << 4,
}
ProcessedInputs m_LastRepaintProcessedInputs;
ProcessedInputs m_CurrentlyProcessedInputs;
enum HandleThreadSplitterFoldoutButtonsCommand
{
OnlyHandleInput,
OnlyDraw,
}
enum ThreadSplitterCommand
{
HandleThreadSplitter,
HandleThreadSplitterFoldoutButtons,
}
struct RangeSelectionInfo
{
public static readonly int controlIDHint = "RangeSelection".GetHashCode();
public bool active;
public bool mouseDown;
public float mouseDownTime;
public float startTime;
public float endTime;
public float duration => endTime - startTime;
}
RangeSelectionInfo m_RangeSelection = new RangeSelectionInfo();
static readonly ProfilerMarker m_DoGUIMarker = new ProfilerMarker(nameof(ProfilerTimelineGUI) + ".DoGUI");
public ProfilerTimelineGUI()
{
// Configure default groups
m_Groups = new List<GroupInfo>(new GroupInfo[]
{
new GroupInfo(k_MainGroupName, RepaintProfilerWindow, true, 3, 0),
new GroupInfo(k_JobSystemGroupName, RepaintProfilerWindow),
new GroupInfo(k_LoadingGroupName, RepaintProfilerWindow),
new GroupInfo(k_ScriptingThreadsGroupName, RepaintProfilerWindow),
new GroupInfo(k_BackgroundJobSystemGroupName, RepaintProfilerWindow),
new GroupInfo(k_ProfilerThreadsGroupName, RepaintProfilerWindow),
new GroupInfo(k_OtherThreadsGroupName, RepaintProfilerWindow),
});
m_HTicks = new TickHandler();
m_HTicks.SetTickModulos(k_TickModulos);
}
public override void OnEnable(CPUOrGPUProfilerModule cpuOrGpuModule, IProfilerWindowController profilerWindow, bool isGpuView)
{
base.OnEnable(cpuOrGpuModule, profilerWindow, isGpuView);
m_ProfilerSampleNameProvider = cpuOrGpuModule;
if (m_Groups != null)
{
for (int i = 0; i < m_Groups.Count; i++)
{
m_Groups[i].expanded.value = SessionState.GetBool($"Profiler.Timeline.GroupExpanded.{m_Groups[i].name}", false);
}
}
}
void RepaintProfilerWindow()
{
m_ProfilerWindow?.Repaint();
}
static GUIContent CreateDisplayNameForThreadOrGroup(string name, bool indent)
{
var content = GUIContent.Temp(name, name);
const int indentSize = 10;
bool stripped = false;
if ((styles.leftPane.CalcSize(content).x + (indent ? indentSize : 0)) > Chart.kSideWidth)
{
stripped = true;
content.text += "...";
while ((styles.leftPane.CalcSize(content).x + (indent ? indentSize : 0)) > Chart.kSideWidth)
{
content.text = content.text.Remove(content.text.Length - 4, 1);
}
}
var result = new GUIContent();
result.text = content.text;
if (stripped)
result.tooltip = name;
return result;
}
GroupInfo GetOrCreateGroupByName(string name)
{
var group = m_Groups.Find(g => g.name == name);
if (group == null)
{
group = new GroupInfo(name, RepaintProfilerWindow);
m_Groups.Add(group);
}
return group;
}
void AddNeighboringActiveThreads(int currentFrameIndex, int displayFrameOffset)
{
var frameIndex = currentFrameIndex + displayFrameOffset;
GroupInfo lastGroupLookupValue = null;
for (int threadIndex = 0;; ++threadIndex)
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, threadIndex))
{
if (frameData == null || !frameData.valid)
break;
var threadId = frameData.threadId;
// If threadId is unavailable we can't match threads in different frames
if (threadId == 0)
break;
var threadGroupName = frameData.threadGroupName;
GroupInfo group;
if (lastGroupLookupValue != null && lastGroupLookupValue.name == threadGroupName)
group = lastGroupLookupValue;
else
group = lastGroupLookupValue = GetOrCreateGroupByName(threadGroupName);
var maxDepth = frameData.maxDepth - 1;
if (group.threadIdMap.TryGetValue(threadId, out var threadInfo))
{
threadInfo.threadIndices[k_MaxNeighborFrames + displayFrameOffset] = threadIndex;
threadInfo.maxDepth = Mathf.Max(threadInfo.maxDepth, maxDepth);
}
else
{
// frameData.maxDepth includes the thread sample which is not getting displayed, so we store it at -1 for all intents and purposes
threadInfo = new ThreadInfo(frameData.threadName, threadId, FrameDataView.invalidThreadIndex, maxDepth, group.defaultLineCountPerThread);
threadInfo.threadIndices[k_MaxNeighborFrames + displayFrameOffset] = threadIndex;
group.threads.Add(threadInfo);
group.threadIdMap.Add(threadId, threadInfo);
}
}
}
}
void UpdateGroupAndThreadInfo(int frameIndex)
{
// Only update groups cache when we change frame index or neighbor frames count.
if (m_LastSelectedFrameIndex == frameIndex && m_LastMaxContextFramesToShow == maxContextFramesToShow)
return;
m_LastSelectedFrameIndex = frameIndex;
m_LastMaxContextFramesToShow = maxContextFramesToShow;
// Mark threads terminated by nullifying name.
// This helps to reuse the ThreadInfo object in most cases when switching frames and eliminate allocations.
// Besides caching we also preserve linesToDisplay information.
foreach (var group in m_Groups)
{
for (var i = 0; i < group.threads.Count; ++i)
group.threads[i].Reset();
}
GroupInfo lastGroupLookupValue = null;
var canUseThreadIdForThreadAlignment = true;
for (int threadIndex = 0;; ++threadIndex)
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, threadIndex))
{
if (frameData == null || !frameData.valid)
break;
var threadGroupName = frameData.threadGroupName;
var threadId = frameData.threadId;
GroupInfo group;
// Micro optimization by caching last accessed group - that guarantees hits for jobs and scripting threads.
if (lastGroupLookupValue != null && lastGroupLookupValue.name == threadGroupName)
group = lastGroupLookupValue;
else
group = lastGroupLookupValue = GetOrCreateGroupByName(threadGroupName);
if (threadId != 0)
{
var maxDepth = frameData.maxDepth - 1;
if (group.threadIdMap.TryGetValue(threadId, out var thread))
{
// Reuse existing ThreadInfo object, but update its name, index and dempth.
thread.Update(frameData.threadName, threadIndex, maxDepth);
}
else
{
// frameData.maxDepth includes the thread sample which is not getting displayed, so we store it at -1 for all intents and purposes
thread = new ThreadInfo(frameData.threadName, threadId, threadIndex, maxDepth, group.defaultLineCountPerThread);
// the main thread gets double the size
if (threadIndex == 0)
thread.linesToDisplay *= 2;
// Add a new thread
group.threads.Add(thread);
group.threadIdMap.Add(threadId, thread);
}
}
else
{
// Old data compatibility path where we don't have threadId.
canUseThreadIdForThreadAlignment = false;
var threads = group.threads;
ThreadInfo thread = threads.Find(t => t.threadIndex == threadIndex);
if (thread == null)
{
// frameData.maxDepth includes the thread sample which is not getting displayed, so we store it at -1 for all intents and purposes
thread = new ThreadInfo(frameData.threadName, threadId, threadIndex, frameData.maxDepth - 1, group.defaultLineCountPerThread);
for (var i = 0; i < k_MaxDisplayFrames; ++i)
thread.threadIndices[i] = threadIndex;
// the main thread gets double the size
if (threadIndex == 0)
thread.linesToDisplay *= 2;
group.threads.Add(thread);
}
else
{
thread.name = frameData.threadName;
thread.maxDepth = frameData.maxDepth - 1;
}
}
}
}
// If this is a new capture with threadId support we scan neighbor frames to ensure we have a consistent view of threads
// across all visible frames.
if (canUseThreadIdForThreadAlignment)
{
for (var i = -1; i >= -m_LastMaxContextFramesToShow && frameIndex - i >= ProfilerDriver.firstFrameIndex; --i)
{
if (!ProfilerDriver.GetFramesBelongToSameProfilerSession(frameIndex + i, frameIndex))
break;
AddNeighboringActiveThreads(frameIndex, i);
}
for (var i = 1; i <= m_LastMaxContextFramesToShow && frameIndex + i <= ProfilerDriver.lastFrameIndex; ++i)
{
if (!ProfilerDriver.GetFramesBelongToSameProfilerSession(frameIndex + i, frameIndex))
break;
AddNeighboringActiveThreads(frameIndex, i);
}
}
// Sort threads by name
foreach (var group in m_Groups)
{
// and cleanup those that are no longer present in the view.
for (var i = 0; i < group.threads.Count;)
{
if (group.threads[i].maxDepth == -1)
{
group.threadIdMap.Remove(group.threads[i].threadId);
group.threads.RemoveAt(i);
}
else
++i;
}
group.threads.Sort();
}
}
float CalculateHeightForAllBars(Rect fullRect, out float combinedHeaderHeight, out float combinedThreadHeight)
{
combinedHeaderHeight = 0f;
combinedThreadHeight = 0f;
for (int i = 0; i < m_Groups.Count; i++)
{
var group = m_Groups[i];
bool mainGroup = group.name == k_MainGroupName;
if (mainGroup)
{
// main group has no height of it's own and is always expanded
group.height = 0;
group.expanded.value = true;
}
else
{
group.height = group.expanded.value ? k_GroupHeight : Math.Max(group.height, group.threads.Count * k_ThreadMinHeightCollapsed);
// Ensure minimum height is k_GroupHeight.
if (group.height < k_GroupHeight)
group.height = k_GroupHeight;
}
combinedHeaderHeight += group.height;
foreach (var thread in group.threads)
{
int lines = Mathf.RoundToInt(thread.linesToDisplay);
thread.height = CalculateThreadHeight(lines) * group.expanded.faded;
combinedThreadHeight += thread.height;
}
}
return combinedHeaderHeight + combinedThreadHeight;
}
bool DrawBar(Rect r, float y, float height, GUIContent content, bool group, bool expanded, bool indent)
{
Rect leftRect = new Rect(r.x - Chart.kSideWidth, y, Chart.kSideWidth, height);
Rect rightRect = new Rect(r.x, y, r.width, height);
if (Event.current.type == EventType.Repaint)
{
styles.rightPane.Draw(rightRect, false, false, false, false);
if (indent)
styles.leftPane.padding.left += 10;
styles.leftPane.Draw(leftRect, content, false, false, false, false);
if (indent)
styles.leftPane.padding.left -= 10;
}
if (group)
{
leftRect.width -= 1.0f; // text should not draw ontop of right border
leftRect.xMin += 3.0f; // shift toggle arrow right
leftRect.yMin += 1.0f;
return GUI.Toggle(leftRect, expanded, GUIContent.none, styles.foldout);
}
return false;
}
void DrawBars(Rect r, float scaleForThreadHeight)
{
bool hasThreadinfoToDraw = false;
foreach (var group in m_Groups)
{
foreach (var thread in group.threads)
{
if (thread != null)
{
hasThreadinfoToDraw = true;
break;
}
}
if (hasThreadinfoToDraw)
break;
}
if (!hasThreadinfoToDraw)
return; // nothing to draw
float y = r.y;
foreach (var groupInfo in m_Groups)
{
bool mainGroup = groupInfo.name == k_MainGroupName;
if (!mainGroup)
{
var height = groupInfo.height;
var expandedState = groupInfo.expanded.target;
var newExpandedState = DrawBar(r, y, height, groupInfo.DisplayName, true, expandedState, false);
if (newExpandedState != expandedState)
{
SessionState.SetBool($"Profiler.Timeline.GroupExpanded.{groupInfo.name}", newExpandedState);
groupInfo.expanded.value = newExpandedState;
}
y += height;
}
foreach (var threadInfo in groupInfo.threads)
{
var height = threadInfo.height * scaleForThreadHeight;
if (height != 0)
DrawBar(r, y, height, threadInfo.DisplayName(!mainGroup), false, true, !mainGroup);
y += height;
}
}
}
void DoNativeProfilerTimeline(Rect r, int frameIndex, int threadIndex, float timeOffset, bool ghost, float scaleForThreadHeight)
{
// Add some margins to each thread view.
Rect clipRect = r;
float topMargin = Math.Min(clipRect.height * 0.25f, 1); // Reduce margin when drawing thin timelines (to more easily get an overview over collapsed threadgroups)
float bottomMargin = topMargin + 1;
clipRect.y += topMargin;
clipRect.height -= bottomMargin;
GUI.BeginGroup(clipRect);
{
Rect localRect = clipRect;
localRect.x = 0;
if (Event.current.type == EventType.Repaint)
{
DrawNativeProfilerTimeline(localRect, frameIndex, threadIndex, timeOffset, ghost);
}
else
{
var controlId = GUIUtility.GetControlID(BaseStyles.timelineTimeAreaControlId, FocusType.Passive, localRect);
if (!ghost && (Event.current.GetTypeForControl(controlId) == EventType.MouseDown || // Ghosts are not clickable (or can contain an active selection)
// Selection of samples is handled in HandleNativeProfilerTimelineInput so it needs to get called if there is a selection to transfer
(m_SelectionPendingTransfer != null && threadIndex == m_ThreadIndexOfSelectionPendingTransfer)))
{
HandleNativeProfilerTimelineInput(localRect, frameIndex, threadIndex, timeOffset, topMargin, scaleForThreadHeight, controlId);
}
}
}
GUI.EndGroup();
}
void DrawNativeProfilerTimeline(Rect threadRect, int frameIndex, int threadIndex, float timeOffset, bool ghost)
{
bool hasSelection = m_SelectedEntry.threadIndex == threadIndex && m_SelectedEntry.frameId == frameIndex;
NativeProfilerTimeline_DrawArgs drawArgs = new NativeProfilerTimeline_DrawArgs();
drawArgs.Reset();
drawArgs.frameIndex = frameIndex;
drawArgs.threadIndex = threadIndex;
drawArgs.timeOffset = timeOffset;
drawArgs.threadRect = threadRect;
// cull text that would otherwise draw over the bottom scrollbar
drawArgs.threadRect.yMax = Mathf.Min(drawArgs.threadRect.yMax, m_TimeArea.shownArea.height);
drawArgs.shownAreaRect = m_TimeArea.shownArea;
drawArgs.selectedEntryIndex = hasSelection ? m_SelectedEntry.sampleIndex : RawFrameDataView.invalidSampleIndex;
drawArgs.mousedOverEntryIndex = RawFrameDataView.invalidSampleIndex;
NativeProfilerTimeline.Draw(ref drawArgs);
}
static readonly ProfilerMarker k_TransferSelectionMarker = new ProfilerMarker($"{nameof(ProfilerTimelineGUI)} Transfer Selection");
static readonly ProfilerMarker k_TransferSelectionAcrossFramesMarker = new ProfilerMarker($"{nameof(ProfilerTimelineGUI)} Transfer Selection Between Frames");
void HandleNativeProfilerTimelineInput(Rect threadRect, int frameIndex, int threadIndex, float timeOffset, float topMargin, float scaleForThreadHeight, int controlId)
{
// Only let this thread view change mouse state if it contained the mouse pos
Rect clippedRect = threadRect;
clippedRect.y = 0;
var eventType = Event.current.GetTypeForControl(controlId);
bool inThreadRect = clippedRect.Contains(Event.current.mousePosition);
if (!inThreadRect && !(m_SelectionPendingTransfer != null && threadIndex == m_ThreadIndexOfSelectionPendingTransfer))
return;
bool singleClick = Event.current.clickCount == 1 && eventType == EventType.MouseDown;
bool doubleClick = Event.current.clickCount == 2 && eventType == EventType.MouseDown;
bool doSelect = (singleClick || doubleClick) && Event.current.button == 0 || (m_SelectionPendingTransfer != null && threadIndex == m_ThreadIndexOfSelectionPendingTransfer);
if (!doSelect)
return;
using (var frameData = new RawFrameDataView(frameIndex, threadIndex))
{
TimelineIndexHelper indexHelper = TimelineIndexHelper.invalidIndex;
float relativeYPosition = 0;
string name = null;
bool fireSelectionChanged = false;
string nonProxySampleName = null;
ReadOnlyCollection<string> markerNamePath = null;
var nonProxySampleDepthDifference = 0;
if (m_SelectionPendingTransfer != null)
{
using (k_TransferSelectionMarker.Auto())
{
if (m_SelectionPendingTransfer.markerPathDepth <= 0)
return;
markerNamePath = m_SelectionPendingTransfer.markerNamePath;
var markerIdPath = m_SelectionPendingTransfer.markerIdPath;
indexHelper.sampleIndex = m_SelectionPendingTransfer.rawSampleIndex;
fireSelectionChanged = false;
name = m_SelectionPendingTransfer.sampleDisplayName;
var markerPathLength = markerIdPath.Count;
// initial assumption is that the depth is the full marker path. The depth will be revised if it is a Proxy Selection
var depth = markerPathLength;
// A quick sanity check on the validity of going with the raw index
var rawSampleIndexIsValid = m_SelectionPendingTransfer.frameIndexIsSafe &&
frameData.frameIndex == m_SelectionPendingTransfer.safeFrameIndex &&
m_SelectionPendingTransfer.rawSampleIndex < frameData.sampleCount &&
frameData.GetSampleMarkerId(m_SelectionPendingTransfer.rawSampleIndex) == markerIdPath[markerPathLength - 1];
if (!rawSampleIndexIsValid)
{
using (k_TransferSelectionAcrossFramesMarker.Auto())
{
if (m_LocalSelectedItemMarkerIdPath == null)
m_LocalSelectedItemMarkerIdPath = new List<int>(markerPathLength);
else if (m_LocalSelectedItemMarkerIdPath.Capacity < markerPathLength)
m_LocalSelectedItemMarkerIdPath.Capacity = markerPathLength;
m_LocalSelectedItemMarkerIdPath.Clear();
for (int i = 0; i < markerPathLength; i++)
{
// update the marker Ids, they can't be trusted since they originated on another frame
m_LocalSelectedItemMarkerIdPath.Add(frameData.GetMarkerId(markerNamePath[i]));
}
var longestMatchingPath = new List<int>(markerPathLength);
// The selection was made in a different frame so the raw sample ID is worthless here
// instead the selection needs to be transfered by finding the first sample with the same marker path.
if (markerPathLength > 0)
{
indexHelper.sampleIndex = FindFirstSampleThroughMarkerPath(
frameData, m_ProfilerSampleNameProvider,
m_LocalSelectedItemMarkerIdPath, markerPathLength, ref name,
longestMatchingPath: longestMatchingPath);
}
if (!indexHelper.valid && longestMatchingPath.Count > 0)
{
// use the longest matching path for a "proxy" selection, i.e. select the sample that is closest to what was selected in the other frame
indexHelper.sampleIndex = longestMatchingPath[longestMatchingPath.Count - 1];
if (indexHelper.valid)
{
// it's likely not named the same
nonProxySampleName = name;
depth = longestMatchingPath.Count;
nonProxySampleDepthDifference = depth - markerPathLength;
name = null;
}
}
if (!indexHelper.valid)
{
m_SelectionPendingTransfer = null;
m_LocalSelectedItemMarkerIdPath.Clear();
m_ThreadIndexOfSelectionPendingTransfer = FrameDataView.invalidThreadIndex;
m_FrameSelectionVerticallyAfterTransfer = false;
m_Scheduled_FrameSelectionVertically = false;
m_SelectedEntry.Reset();
return;
}
}
}
else if (m_SelectionPendingTransfer.markerIdPath != null)
depth = m_SelectionPendingTransfer.markerPathDepth;
if (string.IsNullOrEmpty(name))
{
name = frameData.GetSampleName(indexHelper.sampleIndex);
}
var requiredThreadHeight = CalculateThreadHeight(depth);
var requiredThreadRect = threadRect;
if (requiredThreadRect.height < requiredThreadHeight)
requiredThreadRect.height = requiredThreadHeight;
var entryPosArgs = new NativeProfilerTimeline_GetEntryPositionInfoArgs();
entryPosArgs.frameIndex = frameData.frameIndex;
entryPosArgs.threadIndex = m_ThreadIndexOfSelectionPendingTransfer;
entryPosArgs.sampleIndex = indexHelper.sampleIndex;
entryPosArgs.threadRect = requiredThreadRect;
entryPosArgs.timeOffset = timeOffset;
entryPosArgs.shownAreaRect = m_TimeArea.shownArea;
NativeProfilerTimeline.GetEntryPositionInfo(ref entryPosArgs);
relativeYPosition = entryPosArgs.out_Position.y + entryPosArgs.out_Size.y + topMargin;
m_SelectionPendingTransfer = null;
m_LocalSelectedItemMarkerIdPath.Clear();
m_ThreadIndexOfSelectionPendingTransfer = FrameDataView.invalidThreadIndex;
m_Scheduled_FrameSelectionVertically = m_FrameSelectionVerticallyAfterTransfer;
m_FrameSelectionVerticallyAfterTransfer = false;
}
}
else
{
NativeProfilerTimeline_GetEntryAtPositionArgs posArgs = new NativeProfilerTimeline_GetEntryAtPositionArgs();
posArgs.Reset();
posArgs.frameIndex = frameData.frameIndex;
posArgs.threadIndex = frameData.threadIndex;
posArgs.timeOffset = timeOffset;
posArgs.threadRect = threadRect;
posArgs.threadRect.height *= scaleForThreadHeight;
posArgs.shownAreaRect = m_TimeArea.shownArea;
posArgs.position = Event.current.mousePosition;
NativeProfilerTimeline.GetEntryAtPosition(ref posArgs);
indexHelper.sampleIndex = posArgs.out_EntryIndex;
relativeYPosition = posArgs.out_EntryYMaxPos + topMargin;
name = posArgs.out_EntryName;
fireSelectionChanged = true;
}
if (indexHelper.valid)
{
bool selectedChanged = !m_SelectedEntry.Equals(frameData.frameIndex, frameData.threadIndex, indexHelper.sampleIndex);
if (selectedChanged)
{
// Read out timing info
NativeProfilerTimeline_GetEntryTimingInfoArgs timingInfoArgs = new NativeProfilerTimeline_GetEntryTimingInfoArgs();
timingInfoArgs.Reset();
timingInfoArgs.frameIndex = frameData.frameIndex;
timingInfoArgs.threadIndex = frameData.threadIndex;
timingInfoArgs.entryIndex = indexHelper.sampleIndex;
timingInfoArgs.calculateFrameData = true;
NativeProfilerTimeline.GetEntryTimingInfo(ref timingInfoArgs);
// Read out instance info for selection
NativeProfilerTimeline_GetEntryInstanceInfoArgs instanceInfoArgs = new NativeProfilerTimeline_GetEntryInstanceInfoArgs();
instanceInfoArgs.Reset();
instanceInfoArgs.frameIndex = frameData.frameIndex;
instanceInfoArgs.threadIndex = frameData.threadIndex;
instanceInfoArgs.entryIndex = indexHelper.sampleIndex;
NativeProfilerTimeline.GetEntryInstanceInfo(ref instanceInfoArgs);
if (fireSelectionChanged)
{
var selection = new ProfilerTimeSampleSelection(frameData.frameIndex, frameData.threadGroupName, frameData.threadName, frameData.threadId, indexHelper.sampleIndex, name);
selection.GenerateMarkerNamePath(frameData, new List<int>(instanceInfoArgs.out_PathMarkerIds), instanceInfoArgs.out_Path);
selectionChanged(selection);
markerNamePath = selection.markerNamePath;
}
// Set selected entry info
m_SelectedEntry.Reset();
m_SelectedEntry.frameId = frameData.frameIndex;
m_SelectedEntry.threadIndex = frameData.threadIndex;
m_SelectedEntry.sampleIndex = indexHelper.sampleIndex;
m_SelectedEntry.instanceId = instanceInfoArgs.out_Id;
m_SelectedEntry.time = timingInfoArgs.out_LocalStartTime;
m_SelectedEntry.duration = timingInfoArgs.out_Duration;
m_SelectedEntry.totalDurationForThread = timingInfoArgs.out_TotalDurationForThread;
m_SelectedEntry.instanceCountForThread = timingInfoArgs.out_InstanceCountForThread;
m_SelectedEntry.totalDurationForFrame = timingInfoArgs.out_TotalDurationForFrame;
m_SelectedEntry.instanceCountForFrame = timingInfoArgs.out_InstanceCountForFrame;
m_SelectedEntry.threadCount = timingInfoArgs.out_ThreadCountForFrame;
m_SelectedEntry.relativeYPos = relativeYPosition;
m_SelectedEntry.name = name;
m_SelectedEntry.hasCallstack = instanceInfoArgs.out_CallstackInfo != null && instanceInfoArgs.out_CallstackInfo.Length > 0;
m_SelectedEntry.metaData = instanceInfoArgs.out_MetaData;
m_SelectedEntry.sampleStack = markerNamePath;
if (nonProxySampleName != null)
{
m_SelectedEntry.nonProxyName = nonProxySampleName;
m_SelectedEntry.nonProxyDepthDifference = nonProxySampleDepthDifference;
}
if ((cpuModule.ViewOptions & CPUOrGPUProfilerModule.ProfilerViewFilteringOptions.ShowExecutionFlow) != 0)
{
// posArgs.out_EntryIndex is a MeshCache index which differs from sample index by 1 as root is not included into MeshCache.
frameData.GetSampleFlowEvents(indexHelper.sampleIndex, m_SelectedEntry.FlowEvents);
UpdateActiveFlowEventsForAllThreadsInAllVisibleFrames(frameData.frameIndex, m_SelectedEntry.FlowEvents);
}
}
if (eventType == EventType.MouseDown)
{
Event.current.Use();
if(ProfilerDriver.FrameDataBelongsToCurrentEditorSession(frameData))
UpdateSelectedObject(singleClick, doubleClick);
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.FrameSelection;
}
}
else
{
// click on empty space de-selects
if (doSelect)
{
ClearSelection();
Event.current.Use();
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.FrameSelection;
}
}
}
}
/// <summary>
/// Use this method to find the first matching Raw Sample Index (returned value).
/// If <paramref name="longestMatchingPath"/> is not null, the search will also look for an approximate fit to the search criteria
/// and fill this list with the path of Raw Sample Indices leading up to and including the searched sample or its approximation.
/// </summary>
/// <param name="iterator">
/// A <see cref="RawFrameDataView"/> to use for searching, already pointing at the right frame and thread.</param>
/// <param name="profilerSampleNameProvider">
/// This sample name provider will be used to fill <paramref name="outName"/> with the name of the found sample.</param>
/// <param name="markerIdPathToMatch">
/// If provided, this method search for a sample that fits this marker Id path.
/// If null, all paths will be explored in the search for a sample at a depth that fits the provided <paramref name="pathLength"/> or the <paramref name="specificRawSampleIndexToFind"/>.</param>
/// <param name="pathLength">
/// How deep should the search go?
/// Any depth layers above the <paramref name="pathLength"/> - 1 threshold will be skipped.
/// Provide iterator.maxDepth + 1 if you want to search through all samples regardless of depth.
/// This value can be lower than the length of <paramref name="markerIdPathToMatch"/>, which means only a part of the path will be searched for.
/// <param name="outName">
/// If null or empty and if the searched sample was found, this name will be filled by the name of that sample as formatted by <paramref name="profilerSampleNameProvider"/>.</param>
/// <param name="longestMatchingPath">
/// If not null, aproximated fits to the search parameters will be explored.
/// If there is a direct match found for the searched sample, this will contain the raw sample indices path leading up to and including the found sample.
/// If there is then no direct match found for the searched sample, i.e. -1 was returned,
/// this raw sample index path will lead to the sample that has the longest contiguous match to the provided <paramref name="markerIdPathToMatch"/>
/// and within the scope of that contiguously matching path, the deepest sample that could be found while skipping some scopes in the <paramref name="markerIdPathToMatch"/>.</param>
/// <returns>The raw sample index of the found sample or -1 if no direct fit was found.</returns>
public static int FindFirstSampleThroughMarkerPath(
RawFrameDataView iterator, IProfilerSampleNameProvider profilerSampleNameProvider,
IList<int> markerIdPathToMatch, int pathLength, ref string outName,
List<int> longestMatchingPath = null)
{
var sampleIndexPath = GetCachedSampleIndexPath(pathLength);
return FindNextSampleThroughMarkerPath(
iterator, profilerSampleNameProvider,
markerIdPathToMatch, pathLength, ref outName, ref sampleIndexPath,
longestMatchingPath: longestMatchingPath);
}
/// <summary>
/// This searches for the MarkerId path leading up to a specific rawSampleIndex.
/// </summary>
/// <param name="iterator">
/// A <see cref="RawFrameDataView"/> to use for searching, already pointing at the right frame and thread.</param>
/// <param name="profilerSampleNameProvider">
/// This sample name provider will be used to fill <paramref name="outName"/> with the name of the found sample.</param>
/// <param name="rawSampleIndex">The sample to find the path to.</param>
/// <param name="outName">
/// If null or empty and if the searched sample was found, this name will be filled by the name of that sample as formatted by <paramref name="profilerSampleNameProvider"/>.</param>
/// <param name="markerIdPath">Expected to be empty, will be filled with the marker id path for the sample, if that sample was found.</param>
/// <returns>The <paramref name="rawSampleIndex"/> if found, otherwise -1.</returns>
public static int GetItemMarkerIdPath(
RawFrameDataView iterator, IProfilerSampleNameProvider profilerSampleNameProvider,
int rawSampleIndex, ref string outName, ref List<int> markerIdPath)
{
var unreachableDepth = iterator.maxDepth + 1;
var sampleIndexPath = GetCachedSampleIndexPath(unreachableDepth);
var sampleIdx = FindNextSampleThroughMarkerPath(
iterator, profilerSampleNameProvider,
markerIdPathToMatch: null, unreachableDepth, ref outName, ref sampleIndexPath,
specificRawSampleIndexToFind: rawSampleIndex);
if (sampleIdx != RawFrameDataView.invalidSampleIndex)
{
for (int i = 0; i < sampleIndexPath.Count; i++)
{
markerIdPath.Add(iterator.GetSampleMarkerId(sampleIndexPath[i]));
}
}
return sampleIdx;
}
/// <summary>
/// Use this method to find the Raw Sample Index (returned value) and the path of Raw Sample Indices (<paramref name="sampleIndexPath"/>) leading up to a sample fitting the search criteria.
/// If <paramref name="longestMatchingPath"/>, the search will also look for approximate fits to the search criteria and fill the path for that approximation, or the found sample, into that list.
/// </summary>
/// <param name="iterator">
/// A <see cref="RawFrameDataView"/> to use for searching, already pointing at the right frame and thread.</param>
/// <param name="profilerSampleNameProvider">
/// This sample name provider will be used to fill <paramref name="outName"/> with the name of the found sample.</param>
/// <param name="markerIdPathToMatch">
/// If provided, this method search for a sample that fits this marker Id path.
/// If null, all paths will be explored in the search for a sample at a depth that fits the provided <paramref name="pathLength"/> or the <paramref name="specificRawSampleIndexToFind"/>.</param>
/// <param name="pathLength">
/// How deep should the search go?
/// Any depth layers above the <paramref name="pathLength"/> - 1 threshold will be skipped.
/// Provide iterator.maxDepth + 1 if you want to search through all samples regardless of depth.
/// This value can be lower than the length of <paramref name="markerIdPathToMatch"/>, which means only a part of the path will be searched for.
/// <param name="outName">
/// If null or empty and if the searched sample was found, this name will be filled by the name of that sample as formatted by <paramref name="profilerSampleNameProvider"/>.</param>
/// <param name="sampleIndexPath">
/// If a sample was found, i.e. the returned value wasn't -1, this list will contain the raw sample index path leading up to the found sample, but won't be including it.
/// If this list isn't provided in empty form, the search will continue after the sample stack scope of the last sample in this path.</param>
/// <param name="longestMatchingPath">
/// If not null, aproximated fits to the search parameters will be explored.
/// If there is a direct match found for the searched sample, this will contain the raw sample indices path leading up to and including the found sample, i.e. essentially a copy of <paramref name="sampleIndexPath"/>.
/// If there is then no direct match found for the searched sample, i.e. -1 was returned,
/// this raw sample index path will lead to the sample that has the longest contiguous match to the provided <paramref name="markerIdPathToMatch"/>
/// and within the scope of that contiguously matching path, the deepest sample that could be found while skipping some scopes in the <paramref name="markerIdPathToMatch"/>.</param>
/// <param name="specificRawSampleIndexToFind">
/// When not provided as -1, the search will try to find the path to this specific sample, or return -1 if it failed to find it.</param>
/// <param name="sampleIdFitsMarkerPathIndex">
/// If provided additionally to <paramref name="markerIdPathToMatch"/>, this delegate will be queried for samples
/// that do not fit <paramref name="markerIdPathToMatch"/> but might otherwise still fit, indicated by this Func returning true.</param>
/// <returns>The raw sample index of the found sample or -1 if no direct fit was found. </returns>
public static int FindNextSampleThroughMarkerPath(
RawFrameDataView iterator, IProfilerSampleNameProvider profilerSampleNameProvider,
IList<int> markerIdPathToMatch, int pathLength, ref string outName, ref List<int> sampleIndexPath,
List<int> longestMatchingPath = null, int specificRawSampleIndexToFind = RawFrameDataView.invalidSampleIndex, Func<int, int, RawFrameDataView, bool> sampleIdFitsMarkerPathIndex = null)
{
var partOfThePath = sampleIndexPath.Count > 0 ? sampleIndexPath.Count - 1 : 0;
var sampleIndex = partOfThePath == 0 ?
/*skip the root sample*/ 1 :
/*skip the last scope*/ sampleIndexPath[partOfThePath] + iterator.GetSampleChildrenCountRecursive(sampleIndexPath[partOfThePath]) + 1;
bool foundSample = false;
if (sampleIndexPath.Capacity < pathLength + 1)
sampleIndexPath.Capacity = pathLength + 1;
if (s_LastSampleInScopeOfThePathCache.Length < sampleIndexPath.Capacity)
s_LastSampleInScopeOfThePathCache = new int[sampleIndexPath.Capacity];
var lastSampleInScopeOfThePath = s_LastSampleInScopeOfThePathCache;
var lastSampleInScopeOfThePathCount = 0;
var lastSampleInScope = partOfThePath == 0 ? iterator.sampleCount - 1 : sampleIndex + iterator.GetSampleChildrenCountRecursive(sampleIndex);
var allowProxySelection = longestMatchingPath != null;
Debug.Assert(!allowProxySelection || longestMatchingPath.Count <= 0, $"{nameof(longestMatchingPath)} should be empty");
int longestContiguousMarkerPathMatch = 0;
int currentlyLongestContiguousMarkerPathMatch = 0;
if (allowProxySelection && s_SkippedScopesCache.Length < sampleIndexPath.Capacity)
{
s_SkippedScopesCache = new RawSampleIterationInfo[sampleIndexPath.Capacity];
}
var skippedScopes = s_SkippedScopesCache;
var skippedScopesCount = 0;
while (sampleIndex <= lastSampleInScope && partOfThePath < pathLength && (specificRawSampleIndexToFind <= 0 || sampleIndex <= specificRawSampleIndexToFind))
{
if (markerIdPathToMatch == null ||
markerIdPathToMatch[partOfThePath + skippedScopesCount] == iterator.GetSampleMarkerId(sampleIndex) ||
(sampleIdFitsMarkerPathIndex != null && sampleIdFitsMarkerPathIndex(sampleIndex, partOfThePath + skippedScopesCount, iterator)))
{
if ((specificRawSampleIndexToFind >= 0 && sampleIndex == specificRawSampleIndexToFind) ||
(specificRawSampleIndexToFind < 0 && partOfThePath == pathLength - 1))
{
foundSample = true;
break;
}
sampleIndexPath.Add(sampleIndex);
lastSampleInScopeOfThePath[lastSampleInScopeOfThePathCount++] = sampleIndex + iterator.GetSampleChildrenCountRecursive(sampleIndex);
++sampleIndex;
++partOfThePath;
if (skippedScopesCount <= 0)
currentlyLongestContiguousMarkerPathMatch = partOfThePath;
if (partOfThePath + skippedScopesCount >= pathLength)
{
if (longestMatchingPath != null && longestContiguousMarkerPathMatch <= currentlyLongestContiguousMarkerPathMatch && longestMatchingPath.Count < sampleIndexPath.Count)
{
// store the longest matching path. this will be used as a proxy selection fallback.
longestMatchingPath.Clear();
longestMatchingPath.AddRange(sampleIndexPath);
longestContiguousMarkerPathMatch = currentlyLongestContiguousMarkerPathMatch;
}
if (skippedScopesCount > 0)
{
//skip the current scope
sampleIndex = lastSampleInScopeOfThePath[--lastSampleInScopeOfThePathCount] + 1;
sampleIndexPath.RemoveAt(--partOfThePath); // same as sampleIndexPath.Count - 1;
}
else
break;
}
}
else if (allowProxySelection && partOfThePath + skippedScopesCount < pathLength - 1 && longestContiguousMarkerPathMatch <= currentlyLongestContiguousMarkerPathMatch)
{
//skip this part of the path and continue checking the current sample against the next marker in the path
skippedScopes[skippedScopesCount++] = new RawSampleIterationInfo { partOfThePath = partOfThePath, lastSampleIndexInScope = sampleIndex + iterator.GetSampleChildrenCountRecursive(sampleIndex) };
}
else
{
// move past this sample and skip all children.
sampleIndex += 1 + iterator.GetSampleChildrenCountRecursive(sampleIndex);
}
// if part of the path has already been "Stepped into", check if iterating means we've stepped out of current scope
// No need to check partOfThePath == 0 because that scope is checked in the encompassing while
while (lastSampleInScopeOfThePathCount > 0 && sampleIndex > lastSampleInScopeOfThePath[lastSampleInScopeOfThePathCount - 1] ||
allowProxySelection && skippedScopesCount > 0 && sampleIndex > skippedScopes[skippedScopesCount - 1].lastSampleIndexInScope)
{
// we've stepped out of the current scope, unwind.
if (skippedScopesCount > 0 && skippedScopes[skippedScopesCount - 1].partOfThePath >= partOfThePath)
{
// if there are skippedScopes belonging to the current part of the path, unskip these first
sampleIndex = skippedScopes[--skippedScopesCount].lastSampleIndexInScope + 1;
}
else
{
if (longestMatchingPath != null && longestContiguousMarkerPathMatch <= currentlyLongestContiguousMarkerPathMatch && longestMatchingPath.Count < sampleIndexPath.Count)
{
// store the longest matching path. this will be used as a proxy selection fallback
longestMatchingPath.Clear();
longestMatchingPath.AddRange(sampleIndexPath);
longestContiguousMarkerPathMatch = currentlyLongestContiguousMarkerPathMatch;
}
sampleIndexPath.RemoveAt(--partOfThePath); // same as sampleIndexPath.Count - 1;
if (skippedScopesCount <= 0)
currentlyLongestContiguousMarkerPathMatch = partOfThePath;
sampleIndex = lastSampleInScopeOfThePath[--lastSampleInScopeOfThePathCount] + 1;
}
}
}
if (foundSample)
{
if (string.IsNullOrEmpty(outName))
{
outName = profilerSampleNameProvider.GetItemName(iterator, sampleIndex);
}
sampleIndexPath.Add(sampleIndex);
if (longestMatchingPath != null)
{
// The longest matching path is the full one
longestMatchingPath.Clear();
longestMatchingPath.AddRange(sampleIndexPath);
}
return sampleIndex;
}
return RawFrameDataView.invalidSampleIndex;
}
public void SetSelection(ProfilerTimeSampleSelection selection, int threadIndexInCurrentFrame, bool frameVertically)
{
m_SelectionPendingTransfer = selection;
m_LocalSelectedItemMarkerIdPath.Clear();
m_LocalSelectedItemMarkerIdPath.AddRange(selection.markerIdPath);
m_ThreadIndexOfSelectionPendingTransfer = threadIndexInCurrentFrame;
m_FrameSelectionVerticallyAfterTransfer = frameVertically;
m_Scheduled_FrameSelectionVertically = false;
}
// Used for testing
internal void GetSelectedSampleIdsForCurrentFrameAndView(ref List<int> ids)
{
if (m_SelectedEntry.IsValid())
{
ids.Add(m_SelectedEntry.sampleIndex);
}
}
void UpdateSelectedObject(bool singleClick, bool doubleClick)
{
var obj = EditorUtility.InstanceIDToObject(m_SelectedEntry.instanceId);
if (obj is Component)
obj = ((Component)obj).gameObject;
if (obj != null)
{
if (singleClick)
{
EditorGUIUtility.PingObject(obj.GetInstanceID());
}
else if (doubleClick)
{
var selection = new List<Object>();
selection.Add(obj);
Selection.objects = selection.ToArray();
}
}
}
public override void Clear()
{
m_LastSelectedFrameIndex = -1;
for (int i = 0; i < m_Groups.Count; i++)
m_Groups[i].Clear();
}
public void ClearSelection()
{
// in case the Selection is cleared in the same frame it was set in, drop the pending transfer
m_SelectionPendingTransfer = null;
m_LocalSelectedItemMarkerIdPath.Clear();
m_ThreadIndexOfSelectionPendingTransfer = FrameDataView.invalidThreadIndex;
m_FrameSelectionVerticallyAfterTransfer = false;
m_Scheduled_FrameSelectionVertically = false;
if (m_SelectedEntry.IsValid())
{
m_SelectedEntry.Reset();
cpuModule.ClearSelection();
}
m_RangeSelection.active = false;
}
internal void FrameThread(int threadIndex)
{
PerformFrameSelected(0, false, false, true, threadIndex);
}
void PerformFrameAll(float frameMS)
{
PerformFrameSelected(frameMS, false, true);
}
void PerformFrameSelected(float frameMS, bool verticallyFrameSelected = true, bool hFrameAll = false, bool keepHorizontalZoomLevel = false, int verticallyFrameThreadIndex = FrameDataView.invalidThreadIndex)
{
float t;
float dt;
if (hFrameAll)
{
t = 0.0f;
dt = frameMS;
}
else if (m_RangeSelection.active)
{
t = m_RangeSelection.startTime;
dt = m_RangeSelection.duration;
}
else
{
t = m_SelectedEntry.time;
dt = m_SelectedEntry.duration;
if (m_SelectedEntry.instanceCountForFrame <= 0)
{
t = 0.0f;
dt = frameMS;
}
}
if (keepHorizontalZoomLevel)
{
// center the selected time
t += dt * 0.5f;
// take current zoom width in both directions
dt = m_TimeArea.shownAreaInsideMargins.width * 0.5f;
m_TimeArea.SetShownHRangeInsideMargins(t - dt, t + dt);
}
else
{
m_TimeArea.SetShownHRangeInsideMargins(t - dt * 0.2f, t + dt * 1.2f);
}
float yMinPosition = -1;
float yMaxPosition = -1;
if (verticallyFrameThreadIndex != FrameDataView.invalidThreadIndex)
{
// this overrides selection framing
verticallyFrameSelected = false;
ThreadInfo focusedThread = null;
float yOffsetFromTop = 0;
foreach (var group in m_Groups)
{
foreach (var thread in group.threads)
{
if (thread.threadIndex == verticallyFrameThreadIndex)
{
focusedThread = thread;
break;
}
yOffsetFromTop += thread.height;
}
if (focusedThread != null)
break;
}
yMinPosition = yOffsetFromTop;
yMaxPosition = yOffsetFromTop;
}
// [Case 1248631] The Analyzer may set m_SelectedEntry via reflection whilst m_SelectedThread is not assigned until later in DoProfilerFrame. Therefore it's possible we get here with a null m_SelectedThread.
if (m_SelectedEntry.instanceCountForFrame >= 0 && verticallyFrameSelected && m_SelectedThread != null)
{
if (m_SelectedEntry.relativeYPos > m_SelectedThread.height)
{
ThreadInfo selectedThread = null;
foreach (var group in m_Groups)
{
foreach (var thread in group.threads)
{
if (thread.threadIndex == m_SelectedEntry.threadIndex)
{
selectedThread = thread;
break;
}
}
if (selectedThread != null)
break;
}
if (selectedThread != null)
{
selectedThread.linesToDisplay = CalculateLineCount(m_SelectedEntry.relativeYPos + k_LineHeight * 2);
RepaintProfilerWindow();
}
}
yMinPosition = m_SelectedThreadYRange + m_SelectedEntry.relativeYPos - k_LineHeight;
yMaxPosition = m_SelectedThreadYRange + m_SelectedEntry.relativeYPos;
}
if (yMinPosition >= 0 && yMaxPosition >= 0)
{
float yMin = m_TimeArea.shownArea.y;
float yMax = yMin + m_TimeArea.shownArea.height;
if (yMinPosition < m_TimeArea.shownAreaInsideMargins.yMin)
{
yMin = yMinPosition;
yMax = Mathf.Min(yMin + m_TimeArea.shownArea.height, m_TimeArea.vBaseRangeMax);
}
if (yMaxPosition > m_TimeArea.shownAreaInsideMargins.yMax - m_TimeArea.hSliderHeight)
{
yMax = yMaxPosition + m_TimeArea.hSliderHeight;
yMin = Mathf.Max(yMax - m_TimeArea.shownArea.height, m_TimeArea.vBaseRangeMin);
}
m_TimeArea.SetShownVRangeInsideMargins(yMin, yMax);
}
}
void HandleFrameSelected(float frameMS)
{
Event evt = Event.current;
if (evt.type == EventType.ValidateCommand || evt.type == EventType.ExecuteCommand)
{
if (evt.commandName == EventCommandNames.FrameSelected)
{
bool execute = evt.type == EventType.ExecuteCommand;
if (execute)
PerformFrameSelected(frameMS, true);
evt.Use();
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.FrameSelection;
}
}
if (evt.type == EventType.KeyDown && evt.keyCode == KeyCode.A)
{
PerformFrameAll(frameMS);
evt.Use();
}
}
void DoProfilerFrame(int currentFrameIndex, int currentFrameIndexOffset, Rect fullRect, bool ghost, float offset, float scaleForThreadHeight)
{
var frameIndex = currentFrameIndex + currentFrameIndexOffset;
float y = fullRect.y;
// the unscaled y value equating to the timeline Y range value
float rangeY = 0;
foreach (var groupInfo in m_Groups)
{
Rect r = fullRect;
var expanded = groupInfo.expanded.value;
if (expanded && groupInfo.threads.Count > 0)
{
y += groupInfo.height;
rangeY += groupInfo.height;
}
// When group is not expanded its header still occupies at least groupInfo.height
var notExpandedLeftOverY = groupInfo.height;
var groupThreadCount = groupInfo.threads.Count;
foreach (var threadInfo in groupInfo.threads)
{
r.y = y;
r.height = expanded ? threadInfo.height * scaleForThreadHeight : Math.Max(groupInfo.height / groupThreadCount, k_ThreadMinHeightCollapsed);
var threadIndex = threadInfo.threadIndices[k_MaxNeighborFrames + currentFrameIndexOffset];
// Draw only threads that belong to the current frame
if (threadIndex != FrameDataView.invalidThreadIndex)
{
var tr = r;
tr.y -= fullRect.y;
if ((tr.yMin < m_TimeArea.shownArea.yMax && tr.yMax > m_TimeArea.shownArea.yMin)
// if there is a pending selection to be transfered to this thread, do process it.
|| (m_SelectionPendingTransfer != null && m_ThreadIndexOfSelectionPendingTransfer == threadIndex))
{
DoNativeProfilerTimeline(r, frameIndex, threadIndex, offset, ghost, scaleForThreadHeight);
}
// Save the y pos and height of the selected thread each time we draw, since it can change
bool containsSelected = m_SelectedEntry.IsValid() && (m_SelectedEntry.frameId == frameIndex) && (m_SelectedEntry.threadIndex == threadIndex);
if (containsSelected)
{
m_SelectedThreadY = y;
m_SelectedThreadYRange = rangeY;
m_SelectedThread = threadInfo;
}
}
y += r.height;
rangeY += r.height;
notExpandedLeftOverY -= r.height;
}
// Align next thread with the next group
if (notExpandedLeftOverY > 0)
{
y += notExpandedLeftOverY;
rangeY += notExpandedLeftOverY;
}
}
}
void DoFlowEvents(int currentFrameIndex, int firstDrawnFrameIndex, int lastDrawnFrameIndex, Rect fullRect, float scaleForThreadHeight)
{
// Do nothing when flow visualization is disabled.
if ((cpuModule.ViewOptions & CPUOrGPUProfilerModule.ProfilerViewFilteringOptions.ShowExecutionFlow) == 0)
return;
// Only redraw on repaint event.
if (m_TimeArea == null || Event.current.type != EventType.Repaint)
return;
// TODO: Only update cache on frame change
m_DrawnFlowIndicatorsCache.Clear();
bool hasSelectedSampleWithFlowEvents = (m_SelectedEntry.FlowEvents.Count > 0) && SelectedSampleIsVisible(firstDrawnFrameIndex, lastDrawnFrameIndex);
FlowLinesDrawer activeFlowLinesDrawer = (hasSelectedSampleWithFlowEvents) ? new FlowLinesDrawer() : null;
ForEachThreadInEachGroup(fullRect, scaleForThreadHeight, (groupInfo, threadInfo, threadRect) =>
{
var groupIsExpanded = groupInfo.expanded.value;
if (hasSelectedSampleWithFlowEvents)
{
ProcessActiveFlowEventsOnThread(ref activeFlowLinesDrawer, threadInfo, threadRect, fullRect, currentFrameIndex, groupIsExpanded);
}
else
{
DrawIndicatorsForAllFlowEventsInFrameOnThread(currentFrameIndex, threadInfo, threadRect, fullRect, groupIsExpanded, hasSelectedSampleWithFlowEvents);
}
});
activeFlowLinesDrawer?.Draw();
}
void DrawIndicatorsForAllFlowEventsInFrameOnThread(int currentFrameIndex, ThreadInfo threadInfo, Rect threadRect, Rect fullRect, bool groupIsExpanded, bool hasSelectedEntryWithFlowEvents)
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(currentFrameIndex, threadInfo.threadIndex))
{
if (!frameData.valid)
return;
frameData.GetFlowEvents(m_CachedThreadFlowEvents);
var localViewport = new Rect(Vector2.zero, fullRect.size);
foreach (var flowEvent in m_CachedThreadFlowEvents)
{
if (flowEvent.ParentSampleIndex != 0)
{
// A sample can have multiple flow events. Check an indicator hasn't already been drawn for this sample on this thread.
var indicatorCacheValue = new DrawnFlowIndicatorCacheValue()
{
threadId = threadInfo.threadIndex,
markerId = flowEvent.ParentSampleIndex,
flowEventType = flowEvent.FlowEventType
};
if (!m_DrawnFlowIndicatorsCache.Contains(indicatorCacheValue))
{
var sampleRect = RectForSampleOnFrameInThread(flowEvent.ParentSampleIndex, currentFrameIndex, threadInfo.threadIndex, threadRect, 0f, m_TimeArea.shownArea, (groupIsExpanded == false));
if (sampleRect.Overlaps(localViewport))
{
FlowIndicatorDrawer.DrawFlowIndicatorForFlowEvent(flowEvent, sampleRect);
m_DrawnFlowIndicatorsCache.Add(indicatorCacheValue);
}
}
}
}
}
}
void ProcessActiveFlowEventsOnThread(ref FlowLinesDrawer flowLinesDrawer, ThreadInfo threadInfo, Rect threadRect, Rect fullRect, int currentFrameIndex, bool groupIsExpanded)
{
if (threadInfo.ActiveFlowEvents == null)
return;
foreach (var flowEventData in threadInfo.ActiveFlowEvents)
{
var flowEvent = flowEventData.flowEvent;
var flowEventFrameIndex = flowEventData.frameIndex;
var flowEventThreadIndex = flowEventData.threadIndex;
var timeOffset = ProfilerFrameTimingUtility.TimeOffsetBetweenFrames(currentFrameIndex, flowEventData.frameIndex);
var sampleRect = RectForSampleOnFrameInThread(flowEvent.ParentSampleIndex, flowEventFrameIndex, flowEventThreadIndex, threadRect, timeOffset, m_TimeArea.shownArea, (groupIsExpanded == false));
// A flow event can have no parent sample if it is not enclosed within a PROFILER_AUTO scope.
if (flowEventData.hasParentSampleIndex)
{
// Add flow events to the 'flow lines drawer' for drawing later.
bool isSelectedSample = false;
if (!flowLinesDrawer.hasSelectedEvent)
{
isSelectedSample = (m_SelectedEntry.threadIndex == threadInfo.threadIndex) && (m_SelectedEntry.frameId == flowEventFrameIndex) && m_SelectedEntry.FlowEvents.Contains(flowEvent);
}
flowLinesDrawer.AddFlowEvent(flowEventData, sampleRect, isSelectedSample);
// A sample can have multiple flow events. Check an indicator hasn't already been drawn for this sample on this thread.
var indicatorCacheValue = new DrawnFlowIndicatorCacheValue()
{
threadId = threadInfo.threadIndex,
markerId = flowEvent.ParentSampleIndex,
flowEventType = flowEvent.FlowEventType
};
if (!m_DrawnFlowIndicatorsCache.Contains(indicatorCacheValue))
{
// Draw indicator for this active flow event.
var localViewport = new Rect(Vector2.zero, fullRect.size);
if (sampleRect.Overlaps(localViewport))
{
FlowIndicatorDrawer.DrawFlowIndicatorForFlowEvent(flowEvent, sampleRect);
m_DrawnFlowIndicatorsCache.Add(indicatorCacheValue);
}
}
}
}
}
/// <summary>
/// Iterate over each group's threads and execute the provided <paramref name="action"/> for each thread. Passes the thread's rect to the provided action, calculated by summing all previous thread rects.
/// </summary>
/// <param name="fullRect"></param>
/// <param name="scaleForThreadHeight"></param>
/// <param name="action"></param>
void ForEachThreadInEachGroup(Rect fullRect, float scaleForThreadHeight, Action<GroupInfo, ThreadInfo, Rect> action)
{
float y = fullRect.y;
foreach (var groupInfo in m_Groups)
{
var threadRect = fullRect;
var groupIsExpanded = groupInfo.expanded.value;
if (groupIsExpanded && groupInfo.threads.Count > 0)
{
y += groupInfo.height;
}
// When group is not expanded its header still occupies at least groupInfo.height.
var notExpandedLeftOverY = groupInfo.height;
var groupThreadCount = groupInfo.threads.Count;
foreach (var threadInfo in groupInfo.threads)
{
threadRect.y = y;
threadRect.height = groupIsExpanded ? threadInfo.height * scaleForThreadHeight : Math.Max(groupInfo.height / groupThreadCount, k_ThreadMinHeightCollapsed);
action(groupInfo, threadInfo, threadRect);
y += threadRect.height;
notExpandedLeftOverY -= threadRect.height;
}
// Align next thread with the next group
if (notExpandedLeftOverY > 0)
{
y += notExpandedLeftOverY;
}
}
}
Rect RectForSampleOnFrameInThread(int sampleIndex, int frameIndex, int threadIndex, Rect threadRect, float timeOffset, Rect shownAreaRect, bool isGroupCollapsed)
{
var positionInfoArgs = RawPositionInfoForSample(sampleIndex, frameIndex, threadIndex, threadRect, timeOffset, shownAreaRect);
CorrectRawPositionInfo(isGroupCollapsed, threadRect, ref positionInfoArgs);
var sampleRect = new Rect(new Vector2(positionInfoArgs.out_Position.x, positionInfoArgs.out_Position.y), positionInfoArgs.out_Size);
return sampleRect;
}
NativeProfilerTimeline_GetEntryPositionInfoArgs RawPositionInfoForSample(int sampleIndex, int frameIndex, int threadIndex, Rect threadRect, float timeOffset, Rect shownAreaRect)
{
var positionInfoArgs = new NativeProfilerTimeline_GetEntryPositionInfoArgs();
positionInfoArgs.Reset();
positionInfoArgs.frameIndex = frameIndex;
positionInfoArgs.threadIndex = threadIndex;
positionInfoArgs.sampleIndex = sampleIndex;
positionInfoArgs.timeOffset = timeOffset;
positionInfoArgs.threadRect = threadRect;
positionInfoArgs.shownAreaRect = shownAreaRect;
NativeProfilerTimeline.GetEntryPositionInfo(ref positionInfoArgs);
return positionInfoArgs;
}
// NativeProfilerTimeline.GetEntryPositionInfo appears to return rects relative to the thread rect. It also appears to not account for collapsed groups and threads.
static void CorrectRawPositionInfo(bool isGroupCollapsed, Rect threadRect, ref NativeProfilerTimeline_GetEntryPositionInfoArgs positionInfo)
{
// Offset the vertical position by the thread rect's vertical position.
positionInfo.out_Position.y += threadRect.y;
// If the group is collapsed, adjust the height to the thread rect's height.
if (isGroupCollapsed)
{
positionInfo.out_Size.y = threadRect.height;
}
// If the rect is below the bottom of the thread rect (i.e. the thread collapsed), clamp the rect to the bottom of the thread rect.
var positionInfoMaxY = positionInfo.out_Position.y + positionInfo.out_Size.y;
if (positionInfoMaxY > threadRect.yMax)
{
positionInfo.out_Position.y = threadRect.yMax;
positionInfo.out_Size.y = 0f;
}
}
bool SelectedSampleIsVisible(int firstDrawnFrameIndex, int lastDrawnFrameIndex)
{
return ((m_SelectedEntry.frameId >= firstDrawnFrameIndex) && (m_SelectedEntry.frameId <= lastDrawnFrameIndex));
}
static RawFrameDataView GetFrameDataForThreadId(int frameIndex, int threadIndex, ulong threadId)
{
RawFrameDataView frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, threadIndex);
// Check for valid data
if (!frameData.valid)
return null;
// If threadId matches for the same index we found our thread.
// (When new thread starts it might change the order of threads)
if (frameData.threadId == threadId)
return frameData;
// Overwise do a scan across all threads matching threadId.
frameData.Dispose();
// Skip main thread which is always 0
for (var i = 1;; ++i)
{
// Skip already inspected thread
if (threadIndex == i)
continue;
frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, i);
// Check is this is the last thread.
if (!frameData.valid)
return null;
// Check if we found correct thread.
if (frameData.threadId == threadId)
return frameData;
// Continue lookup and dispose nonmatching thread.
frameData.Dispose();
}
}
static void GetSampleTimeInNeighboringFrames(bool previousFrames, int sampleIndex, int markerId, int frameIndex, int threadIndex, ulong threadId, List<int> slicedSampleIndexList, ref ulong totalAsyncDurationNs, ref int totalAsyncFramesCount)
{
var sampleDepth = slicedSampleIndexList.IndexOf(sampleIndex);
if (sampleDepth == -1)
return;
var startFrame = previousFrames ? frameIndex - 1 : frameIndex + 1;
var frameDirection = previousFrames ? -1 : 1;
for (var i = startFrame;; i += frameDirection)
{
// Filter out frames which are beyond visible range
if (i < ProfilerDriver.firstFrameIndex || i > ProfilerDriver.lastFrameIndex)
break;
var startedPreviousFrame = false;
var timeNs = 0UL;
using (var frameData = GetFrameDataForThreadId(i, threadIndex, threadId))
{
// Thread not found
if (frameData == null)
return;
var sampleCount = frameData.sampleCount;
// Check for root only sample
if (sampleCount == 1)
return;
// Sliced samples must have matching hierarchies on both sides of frame slice.
// It is expensive to reconstruct hierarchy back from the raw event data, thus we store it in the frame data.
// The list represents the sample hierarchy active at the frame boundary.
if (previousFrames)
frameData.GetSamplesContinuedInNextFrame(slicedSampleIndexList);
else
frameData.GetSamplesStartedInPreviousFrame(slicedSampleIndexList);
if (sampleDepth >= slicedSampleIndexList.Count)
return;
var otherFrameSampleIndex = slicedSampleIndexList[sampleDepth];
// Verify marker is the same
if (frameData.GetSampleMarkerId(otherFrameSampleIndex) != markerId)
return;
// Sample found - catch the duration
timeNs = frameData.GetSampleTimeNs(otherFrameSampleIndex);
// Check out if sample started even earlier
if (previousFrames)
frameData.GetSamplesStartedInPreviousFrame(slicedSampleIndexList);
else
frameData.GetSamplesContinuedInNextFrame(slicedSampleIndexList);
startedPreviousFrame = slicedSampleIndexList.Contains(otherFrameSampleIndex);
}
if (timeNs != 0)
{
totalAsyncDurationNs += timeNs;
totalAsyncFramesCount++;
}
if (!startedPreviousFrame)
break;
}
}
static readonly List<int> s_CachedSamplesStartedInPreviousFrame = new List<int>();
static readonly List<int> s_CachedSamplesContinuedInNextFrame = new List<int>();
internal static void CalculateTotalAsyncDuration(int selectedSampleIndex, int frameIndex, int selectedThreadIndex, out string selectedThreadName, out ulong totalAsyncDurationNs, out int totalAsyncFramesCount)
{
ulong selectedThreadId;
int selectedMarkerId;
using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, selectedThreadIndex))
{
selectedThreadId = frameData.threadId;
selectedThreadName = frameData.threadName;
selectedMarkerId = frameData.GetSampleMarkerId(selectedSampleIndex);
frameData.GetSamplesStartedInPreviousFrame(s_CachedSamplesStartedInPreviousFrame);
frameData.GetSamplesContinuedInNextFrame(s_CachedSamplesContinuedInNextFrame);
totalAsyncDurationNs = frameData.GetSampleTimeNs(selectedSampleIndex);
}
totalAsyncFramesCount = 1;
GetSampleTimeInNeighboringFrames(true, selectedSampleIndex, selectedMarkerId, frameIndex, selectedThreadIndex, selectedThreadId, s_CachedSamplesStartedInPreviousFrame, ref totalAsyncDurationNs, ref totalAsyncFramesCount);
GetSampleTimeInNeighboringFrames(false, selectedSampleIndex, selectedMarkerId, frameIndex, selectedThreadIndex, selectedThreadId, s_CachedSamplesContinuedInNextFrame, ref totalAsyncDurationNs, ref totalAsyncFramesCount);
}
void DoSelectionTooltip(int frameIndex, Rect fullRect)
{
// Draw selected tooltip
if (!m_SelectedEntry.IsValid() || m_SelectedEntry.frameId != frameIndex)
return;
bool hasCallStack = m_SelectedEntry.hasCallstack;
if (callStackNeedsRegeneration || m_SelectedEntry.cachedSelectionTooltipContent == null)
{
string durationString = UnityString.Format(m_SelectedEntry.duration >= 1.0 ? "{0:f2}ms" : "{0:f3}ms", m_SelectedEntry.duration);
System.Text.StringBuilder text = new System.Text.StringBuilder();
if (m_SelectedEntry.nonProxyName != null)
{
var diff = Math.Abs(m_SelectedEntry.nonProxyDepthDifference);
text.AppendFormat(
BaseStyles.proxySampleMessage,
m_SelectedEntry.nonProxyName, diff,
diff == 1 ? BaseStyles.proxySampleMessageScopeSingular : BaseStyles.proxySampleMessageScopePlural);
text.Append(BaseStyles.proxySampleMessagePart2TimelineView);
}
text.Append(UnityString.Format("{0}\n{1}", m_SelectedEntry.name, durationString));
// Calculate total time of the sample across visible frames
var selectedThreadIndex = m_SelectedEntry.threadIndex;
int selectedSampleIndex = m_SelectedEntry.sampleIndex;
string selectedThreadName;
ulong totalAsyncDurationNs;
int totalAsyncFramesCount;
// Check if sample is sliced and started in previous frames
CalculateTotalAsyncDuration(selectedSampleIndex, frameIndex, selectedThreadIndex, out selectedThreadName, out totalAsyncDurationNs, out totalAsyncFramesCount);
// Add total time to the tooltip
if (totalAsyncFramesCount > 1)
{
var totalAsyncDuration = totalAsyncDurationNs * 1e-6f;
var totalAsyncDurationString = UnityString.Format(totalAsyncDuration >= 1.0 ? "{0:f2}ms" : "{0:f3}ms", totalAsyncDuration);
text.Append(string.Format(styles.localizedStringTotalAcrossFrames, totalAsyncDurationString, totalAsyncFramesCount, selectedThreadName));
}
// Show total duration if more than one instance
if (m_SelectedEntry.instanceCountForThread > 1 || m_SelectedEntry.instanceCountForFrame > 1)
{
text.Append(styles.localizedStringTotalAcumulatedTime);
if (m_SelectedEntry.instanceCountForThread > 1)
{
string totalDurationForThreadString = UnityString.Format(m_SelectedEntry.totalDurationForThread >= 1.0 ? "{0:f2}ms" : "{0:f3}ms", m_SelectedEntry.totalDurationForThread);
text.Append(string.Format(styles.localizedStringTotalInThread, totalDurationForThreadString, m_SelectedEntry.instanceCountForThread, selectedThreadName));
}
if (m_SelectedEntry.instanceCountForFrame > m_SelectedEntry.instanceCountForThread)
{
string totalDurationForFrameString = UnityString.Format(m_SelectedEntry.totalDurationForFrame >= 1.0 ? "{0:f2}ms" : "{0:f3}ms", m_SelectedEntry.totalDurationForFrame);
text.Append(string.Format(styles.localizedStringTotalInFrame, totalDurationForFrameString, m_SelectedEntry.instanceCountForFrame, m_SelectedEntry.threadCount));
}
}
if (m_SelectedEntry.metaData.Length > 0)
{
text.Append(string.Format("\n{0}", m_SelectedEntry.metaData));
}
bool hasObject = m_SelectedEntry.instanceId != 0;
if (hasObject || hasCallStack)
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, m_SelectedEntry.threadIndex))
{
if (hasObject)
{
if (frameData.GetUnityObjectInfo(m_SelectedEntry.instanceId, out var info))
{
var name = string.IsNullOrEmpty(info.name) ? styles.localizedStringUnnamedObject : info.name;
var typeName = frameData.GetUnityObjectNativeTypeInfo(info.nativeTypeIndex, out var typeInfo) ? typeInfo.name : "Object";
// For components we display the information about GameObject as usually components are unnamed.
if (info.relatedGameObjectInstanceId != 0 && frameData.GetUnityObjectInfo(info.relatedGameObjectInstanceId, out var goInfo) && !string.IsNullOrEmpty(goInfo.name))
{
text.Append(string.Format("\n{0}: {1}", typeName, goInfo.name));
}
else
{
text.Append(string.Format("\n{0}: {1}", typeName, name));
}
}
}
if (hasCallStack)
{
var callStack = new List<ulong>();
frameData.GetSampleCallstack(m_SelectedEntry.sampleIndex, callStack);
CompileCallStack(text, callStack, frameData);
}
}
}
m_SelectedEntry.cachedSelectionTooltipContent = new GUIContent(text.ToString());
}
float selectedThreadYOffset = fullRect.y + m_SelectedThreadY;
float selectedY = selectedThreadYOffset + m_SelectedEntry.relativeYPos;
float maxYPosition = Mathf.Max(Mathf.Min(fullRect.yMax, selectedThreadYOffset + m_SelectedThread.height), fullRect.y);
// calculate how much of the line height is visible (needed for calculating the offset of the tooltip when flipping)
float selectedLineHeightVisible = Mathf.Clamp(maxYPosition - (selectedY - k_LineHeight), 0, k_LineHeight);
// keep the popup within the drawing area and thread rect
selectedY = Mathf.Clamp(selectedY, fullRect.y, maxYPosition);
float x = m_TimeArea.TimeToPixel(m_SelectedEntry.time + m_SelectedEntry.duration * 0.5f, fullRect);
ShowLargeTooltip(new Vector2(x, selectedY), fullRect, m_SelectedEntry.cachedSelectionTooltipContent, m_SelectedEntry.sampleStack, selectedLineHeightVisible,
frameIndex, m_SelectedEntry.threadIndex, hasCallStack, ref m_SelectedEntry.downwardsZoomableAreaSpaceNeeded, m_SelectedEntry.nonProxyDepthDifference != 0 ? m_SelectedEntry.sampleIndex : RawFrameDataView.invalidSampleIndex);
}
void PrepareTicks()
{
m_HTicks.SetRanges(m_TimeArea.shownArea.xMin, m_TimeArea.shownArea.xMax, m_TimeArea.drawRect.xMin, m_TimeArea.drawRect.xMax);
m_HTicks.SetTickStrengths(TimeArea.kTickRulerDistMin, TimeArea.kTickRulerDistFull, true);
}
void DrawGrid(Rect rect, float frameTime)
{
if (m_TimeArea == null || Event.current.type != EventType.Repaint)
return;
GUI.BeginClip(rect);
rect.x = rect.y = 0;
Color tickColor = styles.timelineTick.normal.textColor;
tickColor.a = 0.1f;
HandleUtility.ApplyWireMaterial();
if (Application.platform == RuntimePlatform.WindowsEditor)
GL.Begin(GL.QUADS);
else
GL.Begin(GL.LINES);
PrepareTicks();
// Draw tick markers of various sizes
for (int l = 0; l < m_HTicks.tickLevels; l++)
{
var strength = m_HTicks.GetStrengthOfLevel(l) * .9f;
if (strength > TimeArea.kTickRulerFatThreshold)
{
var ticks = m_HTicks.GetTicksAtLevel(l, true);
for (int i = 0; i < ticks.Length; i++)
{
// Draw line
var time = ticks[i];
var x = m_TimeArea.TimeToPixel(time, rect);
TimeArea.DrawVerticalLineFast(x, 0, rect.height, tickColor);
}
}
}
// Draw frame start and end delimiters
TimeArea.DrawVerticalLineFast(m_TimeArea.TimeToPixel(0, rect), 0, rect.height, styles.frameDelimiterColor);
TimeArea.DrawVerticalLineFast(m_TimeArea.TimeToPixel(frameTime, rect), 0, rect.height, styles.frameDelimiterColor);
GL.End();
GUI.EndClip();
}
void DoTimeRulerGUI(Rect timeRulerRect, float sideWidth, float frameTime)
{
// m_TimeArea shouldn't ever be null when this method is called, but just to make sure in case the call to this changes.
if (Event.current.type != EventType.Repaint || m_TimeArea == null)
return;
Rect sidebarLeftOfTimeRulerRect = new Rect(timeRulerRect.x - sideWidth, timeRulerRect.y, sideWidth, k_LineHeight);
timeRulerRect.width -= m_TimeArea.vSliderWidth;
Rect spaceRightOftimeRulerRect = new Rect(timeRulerRect.xMax, timeRulerRect.y, m_TimeArea.vSliderWidth, timeRulerRect.height);
styles.leftPane.Draw(sidebarLeftOfTimeRulerRect, GUIContent.none, false, false, false, false);
styles.leftPane.Draw(spaceRightOftimeRulerRect, GUIContent.none, false, false, false, false);
GUI.BeginClip(timeRulerRect);
timeRulerRect.x = timeRulerRect.y = 0;
GUI.Box(timeRulerRect, GUIContent.none, styles.leftPane);
var baseColor = styles.timelineTick.normal.textColor;
baseColor.a *= 0.75f;
PrepareTicks();
// Tick lines
if (Event.current.type == EventType.Repaint)
{
HandleUtility.ApplyWireMaterial();
if (Application.platform == RuntimePlatform.WindowsEditor)
GL.Begin(GL.QUADS);
else
GL.Begin(GL.LINES);
for (int l = 0; l < m_HTicks.tickLevels; l++)
{
var strength = m_HTicks.GetStrengthOfLevel(l) * .8f;
if (strength < 0.1f)
continue;
var ticks = m_HTicks.GetTicksAtLevel(l, true);
for (int i = 0; i < ticks.Length; i++)
{
// Draw line
var time = ticks[i];
var x = m_TimeArea.TimeToPixel(time, timeRulerRect);
var height = timeRulerRect.height * Mathf.Min(1, strength) * TimeArea.kTickRulerHeightMax;
var color = new Color(1, 1, 1, strength / TimeArea.kTickRulerFatThreshold) * baseColor;
TimeArea.DrawVerticalLineFast(x, timeRulerRect.height - height + 0.5f, timeRulerRect.height - 0.5f, color);
}
}
GL.End();
}
// Tick labels
var labelWidth = k_TickLabelSeparation;
int labelLevel = m_HTicks.GetLevelWithMinSeparation(labelWidth);
float[] labelTicks = m_HTicks.GetTicksAtLevel(labelLevel, false);
for (int i = 0; i < labelTicks.Length; i++)
{
var time = labelTicks[i];
float labelpos = Mathf.Floor(m_TimeArea.TimeToPixel(time, timeRulerRect));
string label = FormatTickLabel(time, labelLevel);
GUI.Label(new Rect(labelpos + 3, -3, labelWidth, 20), label, styles.timelineTick);
}
// Outside current frame coloring
DrawOutOfRangeOverlay(timeRulerRect, frameTime);
// Range selection coloring
DrawRangeSelectionOverlay(timeRulerRect);
GUI.EndClip();
}
string FormatTickLabel(float time, int level)
{
string format = k_TickFormatMilliseconds;
var period = m_HTicks.GetPeriodOfLevel(level);
var log10 = Mathf.FloorToInt(Mathf.Log10(period));
if (log10 >= 3)
{
time /= 1000;
format = k_TickFormatSeconds;
}
return UnityString.Format(format, time.ToString("N" + Mathf.Max(0, -log10), CultureInfo.InvariantCulture.NumberFormat));
}
void DrawOutOfRangeOverlay(Rect rect, float frameTime)
{
var color = styles.outOfRangeColor;
var lineColor = styles.frameDelimiterColor;
var frameStartPixel = m_TimeArea.TimeToPixel(0f, rect);
var frameEndPixel = m_TimeArea.TimeToPixel(frameTime, rect);
// Rect shaded shape drawn before selected frame
if (frameStartPixel > rect.xMin)
{
var startRect = Rect.MinMaxRect(rect.xMin, rect.yMin, Mathf.Min(frameStartPixel, rect.xMax), rect.yMax);
EditorGUI.DrawRect(startRect, color);
TimeArea.DrawVerticalLine(startRect.xMax, startRect.yMin, startRect.yMax, lineColor);
}
// Rect shaded shape drawn after selected frame
if (frameEndPixel < rect.xMax)
{
var endRect = Rect.MinMaxRect(Mathf.Max(frameEndPixel, rect.xMin), rect.yMin, rect.xMax, rect.yMax);
EditorGUI.DrawRect(endRect, color);
TimeArea.DrawVerticalLine(endRect.xMin, endRect.yMin, endRect.yMax, lineColor);
}
}
void DrawRangeSelectionOverlay(Rect rect)
{
if (!m_RangeSelection.active)
return;
var startPixel = m_TimeArea.TimeToPixel(m_RangeSelection.startTime, rect);
var endPixel = m_TimeArea.TimeToPixel(m_RangeSelection.endTime, rect);
if (startPixel > rect.xMax || endPixel < rect.xMin)
return;
var selectionRect = Rect.MinMaxRect(Mathf.Max(rect.xMin, startPixel), rect.yMin, Mathf.Min(rect.xMax, endPixel), rect.yMax);
EditorGUI.DrawRect(selectionRect, styles.rangeSelectionColor);
// Duration label
var labelText = UnityString.Format(k_TickFormatMilliseconds, m_RangeSelection.duration.ToString("N3", CultureInfo.InvariantCulture.NumberFormat));
Chart.DoLabel(startPixel + (endPixel - startPixel) / 2, rect.yMin + 3, labelText, -0.5f);
}
void DoTimeArea()
{
int previousHotControl = GUIUtility.hotControl;
// draw the time area
m_TimeArea.BeginViewGUI();
m_TimeArea.EndViewGUI();
if (previousHotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0)
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.PanningOrZooming;
}
void DoThreadSplitters(Rect fullThreadsRect, Rect fullThreadsRectWithoutSidebar, int frame, ThreadSplitterCommand command)
{
float headerHeight = 0;
float threadHeight = 0;
ThreadInfo lastThreadInLastExpandedGroup = null;
GroupInfo lastExpandedGroup = null;
foreach (var group in m_Groups)
{
headerHeight += group.height;
switch (command)
{
case ThreadSplitterCommand.HandleThreadSplitter:
// Another Splitter for the last thread of the previous group on the bottom line of this groups header
// the first group is always main and has no header so that case can be ignored
if (lastThreadInLastExpandedGroup != null && group.height > 0f)
HandleThreadSplitter(lastExpandedGroup, lastThreadInLastExpandedGroup, fullThreadsRect, headerHeight + threadHeight - lastThreadInLastExpandedGroup.height);
break;
case ThreadSplitterCommand.HandleThreadSplitterFoldoutButtons:
// nothing to do here
default:
break;
}
ThreadInfo lastThread = null;
foreach (var thread in group.threads)
{
if (group.expanded.value)
{
switch (command)
{
case ThreadSplitterCommand.HandleThreadSplitter:
HandleThreadSplitter(group, thread, fullThreadsRect, headerHeight + threadHeight);
HandleThreadSplitterFoldoutButtons(group, thread, fullThreadsRectWithoutSidebar, headerHeight + threadHeight, HandleThreadSplitterFoldoutButtonsCommand.OnlyHandleInput);
break;
case ThreadSplitterCommand.HandleThreadSplitterFoldoutButtons:
HandleThreadSplitterFoldoutButtons(group, thread, fullThreadsRectWithoutSidebar, headerHeight + threadHeight, HandleThreadSplitterFoldoutButtonsCommand.OnlyDraw);
break;
default:
break;
}
}
threadHeight += thread.height;
lastThread = thread;
}
lastThreadInLastExpandedGroup = group.expanded.value ? lastThread : lastThreadInLastExpandedGroup;
lastExpandedGroup = group.expanded.value ? group : lastExpandedGroup;
}
}
float CalculateMaxYPositionForThread(float lineCount, float yPositionOfFirstThread, float yOffsetForThisThread)
{
float threadHeight = CalculateThreadHeight(lineCount);
threadHeight *= m_TimeArea.scale.y;
yOffsetForThisThread *= m_TimeArea.scale.y;
return yPositionOfFirstThread + scrollOffsetY + yOffsetForThisThread + threadHeight;
}
float CalculateThreadHeight(float lineCount)
{
// add a bit of extra height through kExtraHeightPerThread to give a sneak peek at the next line
return lineCount * k_FullThreadLineHeight + k_ExtraHeightPerThread;
}
int CalculateLineCount(float threadHeight)
{
return Mathf.RoundToInt((threadHeight - k_ExtraHeightPerThread) / k_FullThreadLineHeight);
}
static bool CheckForExclusiveSplitterInput(ProcessedInputs inputs)
{
// check if there is a MouseDown event happening that is just moving a splitter and doing nothing else
return inputs > 0 && (inputs & ProcessedInputs.SplitterMoving) > 0 && (inputs & ProcessedInputs.MouseDown) > 0 && inputs - (inputs & ProcessedInputs.SplitterMoving) - (inputs & ProcessedInputs.MouseDown) == 0;
}
void HandleThreadSplitter(GroupInfo group, ThreadInfo thread, Rect fullThreadsRect, float yOffsetForThisThread)
{
Rect splitterRect = new Rect(
fullThreadsRect.x + 1,
CalculateMaxYPositionForThread(thread.linesToDisplay, fullThreadsRect.y, yOffsetForThisThread) - (k_ThreadSplitterHandleSize / 2f),
fullThreadsRect.width - 2,
k_ThreadSplitterHandleSize);
// Handle the mouse cursor look
if (Event.current.type == EventType.Repaint)
{
// we're in Repaint so m_CurrentlyProcessedInputs is already filled with all the inputs since the last repaint
if (CheckForExclusiveSplitterInput(m_CurrentlyProcessedInputs))
{
// while dragging the splitter, the cursor should be MouseCursor.SplitResizeUpDown regardless of where the mouse is in the view
EditorGUIUtility.AddCursorRect(fullThreadsRect, MouseCursor.SplitResizeUpDown);
}
else if (fullThreadsRect.Contains(splitterRect.center) && ((m_CurrentlyProcessedInputs & ProcessedInputs.MouseDown) == 0 || (m_CurrentlyProcessedInputs - ProcessedInputs.MouseDown) > 0))
{
//unless a splitter is getting dragged, only change the cursor if this splitter would be in view and no other input is occurring
EditorGUIUtility.AddCursorRect(splitterRect, MouseCursor.SplitResizeUpDown);
}
}
// double clicking the splitter line resizes to fit
if (splitterRect.Contains(Event.current.mousePosition) && Event.current.clickCount == 2 && Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
thread.linesToDisplay = thread.maxDepth;
Event.current.Use();
}
int previousHotControl = GUIUtility.hotControl;
float deltaY = EditorGUI.MouseDeltaReader(splitterRect, true).y;
if (previousHotControl != GUIUtility.hotControl)
{
// the delta reader changed the hot control ...
if (GUIUtility.hotControl != 0)
{
// ... and took it
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.SplitterMoving;
int defaultLineCountForThisThread = group.defaultLineCountPerThread * (group.name.Equals(k_MainGroupName) && thread.threadIndex == 0 ? 2 : 1);
m_MaxLinesToDisplayForTheCurrentlyModifiedSplitter = Mathf.Max(thread.linesToDisplay, Mathf.Max(thread.maxDepth, defaultLineCountForThisThread));
}
else
{
// ... and released it
// so reset the lines to the nearest integer
thread.linesToDisplay = Mathf.Clamp(Mathf.RoundToInt(thread.linesToDisplay), 1, m_MaxLinesToDisplayForTheCurrentlyModifiedSplitter);
m_CurrentlyProcessedInputs -= m_CurrentlyProcessedInputs & (ProcessedInputs.MouseDown | ProcessedInputs.SplitterMoving);
}
}
else if (CheckForExclusiveSplitterInput(m_LastRepaintProcessedInputs) && GUIUtility.hotControl != 0)
{
// continuous dragging
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.SplitterMoving;
}
if (deltaY != 0f)
{
thread.linesToDisplay = Mathf.Clamp((thread.linesToDisplay * k_FullThreadLineHeight + deltaY) / k_FullThreadLineHeight, 1, m_MaxLinesToDisplayForTheCurrentlyModifiedSplitter);
}
}
void HandleThreadSplitterFoldoutButtons(GroupInfo group, ThreadInfo thread, Rect fullThreadsRectWithoutSidebar, float yOffsetForThisThread, HandleThreadSplitterFoldoutButtonsCommand command)
{
int roundedLineCount = Mathf.RoundToInt(thread.linesToDisplay);
int defaultLineCountForThisThread = group.defaultLineCountPerThread * (group.name.Equals(k_MainGroupName) && thread.threadIndex == 0 ? 2 : 1);
// only show the button if clicking it would change anything at all
if (thread.maxDepth > defaultLineCountForThisThread || thread.maxDepth > roundedLineCount)
{
GUI.BeginClip(fullThreadsRectWithoutSidebar);
fullThreadsRectWithoutSidebar.x = 0;
fullThreadsRectWithoutSidebar.y = 0;
bool expandOnButtonClick = true;
GUIStyle expandCollapseButtonStyle = styles.digDownArrow;
if (roundedLineCount >= thread.maxDepth)
{
expandCollapseButtonStyle = styles.rollUpArrow;
expandOnButtonClick = false;
}
float threadYMax = CalculateMaxYPositionForThread(roundedLineCount, fullThreadsRectWithoutSidebar.y, yOffsetForThisThread);
Vector2 expandCollapsButtonSize = expandCollapseButtonStyle.CalcSize(GUIContent.none);
Rect expandCollapseButtonRect = new Rect(
fullThreadsRectWithoutSidebar.x + fullThreadsRectWithoutSidebar.width / 2 - expandCollapsButtonSize.x / 2,
threadYMax - expandCollapsButtonSize.y,
expandCollapsButtonSize.x,
expandCollapsButtonSize.y);
// only do the button if it is visible
if (GUIClip.visibleRect.Overlaps(expandCollapseButtonRect))
{
switch (command)
{
case HandleThreadSplitterFoldoutButtonsCommand.OnlyHandleInput:
if (GUI.Button(expandCollapseButtonRect, GUIContent.none, GUIStyle.none))
{
// Expand or collapse button expands to show all or collapses to default line height
if (expandOnButtonClick)
{
thread.linesToDisplay = thread.maxDepth;
}
else
{
thread.linesToDisplay = group.defaultLineCountPerThread * (group.name.Equals(k_MainGroupName) && thread.threadIndex == 0 ? 2 : 1);
}
Event.current.Use();
// the height just changed dramatically, enforce the new boundaries
m_TimeArea.EnforceScaleAndRange();
}
break;
case HandleThreadSplitterFoldoutButtonsCommand.OnlyDraw:
if (Event.current.type == EventType.Repaint && expandOnButtonClick)
{
float height = styles.bottomShadow.CalcHeight(GUIContent.none, fullThreadsRectWithoutSidebar.width);
styles.bottomShadow.Draw(new Rect(fullThreadsRectWithoutSidebar.x, threadYMax - height, fullThreadsRectWithoutSidebar.width, height), GUIContent.none, 0);
}
if (Event.current.type == EventType.Repaint)
{
expandCollapseButtonStyle.Draw(expandCollapseButtonRect, GUIContent.none,
expandCollapseButtonRect.Contains(Event.current.mousePosition), false, false, false);
}
break;
default:
break;
}
}
GUI.EndClip();
}
}
public void DoGUI(int frameIndex, Rect position, bool fetchData, ref bool updateViewLive)
{
using (var iter = fetchData ? new ProfilerFrameDataIterator() : null)
{
int threadCount = fetchData ? iter.GetThreadCount(frameIndex) : 0;
iter?.SetRoot(frameIndex, 0);
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
DrawToolbar(iter, ref updateViewLive);
EditorGUILayout.EndHorizontal();
using (m_DoGUIMarker.Auto())
{
if (!string.IsNullOrEmpty(dataAvailabilityMessage))
{
GUILayout.Label(dataAvailabilityMessage, BaseStyles.label);
return;
}
else if (!fetchData && !updateViewLive)
{
GUILayout.Label(BaseStyles.liveUpdateMessage, BaseStyles.label);
return;
}
if (threadCount == 0)
{
GUILayout.Label(BaseStyles.noData, BaseStyles.label);
return;
}
position.yMin -= 1; // Workaround: Adjust the y position as a temporary fix to a 1px vertical offset that need to be investigated.
Rect fullRect = position;
float sideWidth = Chart.kSideWidth;
Rect timeRulerRect = new Rect(fullRect.x + sideWidth, fullRect.y, fullRect.width - sideWidth, k_LineHeight);
Rect timeAreaRect = new Rect(fullRect.x + sideWidth, fullRect.y + timeRulerRect.height, fullRect.width - sideWidth, fullRect.height - timeRulerRect.height);
bool initializing = false;
if (m_TimeArea == null)
{
initializing = true;
m_TimeArea = new ZoomableArea();
m_TimeArea.hRangeLocked = false;
m_TimeArea.vRangeLocked = false;
m_TimeArea.hSlider = true;
m_TimeArea.vSlider = true;
m_TimeArea.vAllowExceedBaseRangeMax = false;
m_TimeArea.vAllowExceedBaseRangeMin = false;
m_TimeArea.hBaseRangeMin = 0;
m_TimeArea.vBaseRangeMin = 0;
m_TimeArea.vScaleMax = 1f;
m_TimeArea.vScaleMin = 1f;
m_TimeArea.scaleWithWindow = true;
m_TimeArea.margin = 10;
m_TimeArea.topmargin = 0;
m_TimeArea.bottommargin = 0;
m_TimeArea.upDirection = ZoomableArea.YDirection.Negative;
m_TimeArea.vZoomLockedByDefault = true;
}
m_TimeArea.rect = timeAreaRect;
Rect bottomLeftFillRect = new Rect(0, position.yMax - m_TimeArea.vSliderWidth, sideWidth - 1, m_TimeArea.vSliderWidth);
if (Event.current.type == EventType.Repaint)
{
styles.profilerGraphBackground.Draw(fullRect, false, false, false, false);
}
if (initializing)
{
InitializeNativeTimeline();
}
// Prepare group and Thread Info
UpdateGroupAndThreadInfo(frameIndex);
HandleFrameSelected(iter.frameTimeMS);
// update time area to new bounds
float combinedHeaderHeight, combinedThreadHeight;
float heightForAllBars = CalculateHeightForAllBars(fullRect, out combinedHeaderHeight, out combinedThreadHeight);
// if needed, take up more empty space below, to fill up the ZoomableArea
float emptySpaceBelowBars = Mathf.Max(k_DefaultEmptySpaceBelowBars, timeAreaRect.height - m_TimeArea.hSliderHeight - heightForAllBars);
if (m_SelectedEntry.downwardsZoomableAreaSpaceNeeded > 0)
emptySpaceBelowBars = Mathf.Max(m_SelectedThreadYRange + m_SelectedEntry.relativeYPos + m_SelectedEntry.downwardsZoomableAreaSpaceNeeded - heightForAllBars, emptySpaceBelowBars);
heightForAllBars += emptySpaceBelowBars;
m_TimeArea.hBaseRangeMax = iter.frameTimeMS;
m_TimeArea.vBaseRangeMax = heightForAllBars;
if (Mathf.Abs(heightForAllBars - m_LastHeightForAllBars) >= 0.5f || Mathf.Abs(fullRect.height - m_LastFullRectHeight) >= 0.5f)
{
m_LastHeightForAllBars = heightForAllBars;
m_LastFullRectHeight = fullRect.height;
// set V range to enforce scale of 1 and to shift the shown area up in case the drawn area shrunk down
m_TimeArea.SetShownVRange(m_TimeArea.shownArea.y, m_TimeArea.shownArea.y + m_TimeArea.drawRect.height);
}
// frame the selection if needed and before drawing the time area
if (m_Scheduled_FrameSelectionVertically)
{
// keep current zoom level but frame vertically
PerformFrameSelected(iter.frameTimeMS, verticallyFrameSelected: true, keepHorizontalZoomLevel: true);
m_Scheduled_FrameSelectionVertically = false;
//RepaintProfilerWindow();
}
else if (initializing)
PerformFrameSelected(iter.frameTimeMS);
// DoTimeArea needs to happen before DoTimeRulerGUI due to excess control ids being generated in repaint that breaks repeatbuttons
DoTimeArea();
DoTimeRulerGUI(timeRulerRect, sideWidth, iter.frameTimeMS);
Rect fullThreadsRect = new Rect(fullRect.x, fullRect.y + timeRulerRect.height, fullRect.width - m_TimeArea.vSliderWidth, fullRect.height - timeRulerRect.height - m_TimeArea.hSliderHeight);
Rect fullThreadsRectWithoutSidebar = fullThreadsRect;
fullThreadsRectWithoutSidebar.x += sideWidth;
fullThreadsRectWithoutSidebar.width -= sideWidth;
Rect sideRect = new Rect(fullThreadsRect.x, fullThreadsRect.y, sideWidth, fullThreadsRect.height);
if (sideRect.Contains(Event.current.mousePosition) && Event.current.isScrollWheel)
{
m_TimeArea.SetTransform(new Vector2(m_TimeArea.m_Translation.x, m_TimeArea.m_Translation.y - (Event.current.delta.y * 4)), m_TimeArea.m_Scale);
m_ProfilerWindow.Repaint();
}
// Layout and handle input for tooltips here so it can grab input before threadspillters and selection, draw it at the end of DoGUI to paint on top
if (Event.current.type != EventType.Repaint)
DoSelectionTooltip(frameIndex, m_TimeArea.drawRect);
// The splitters need to be handled after the time area so that they don't interfere with the input for panning/scrolling the ZoomableArea
DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameIndex, ThreadSplitterCommand.HandleThreadSplitter);
Rect barsUIRect = m_TimeArea.drawRect;
DrawGrid(barsUIRect, iter.frameTimeMS);
Rect barsAndSidebarUIRect = new Rect(barsUIRect.x - sideWidth, barsUIRect.y, barsUIRect.width + sideWidth, barsUIRect.height);
if (Event.current.type == EventType.Repaint)
{
Rect leftSideRect = new Rect(0, position.y, sideWidth, position.height);
styles.leftPane.Draw(leftSideRect, false, false, false, false);
// The bar in the lower left side that fills the space next to the horizontal scrollbar.
EditorStyles.toolbar.Draw(bottomLeftFillRect, false, false, false, false);
}
GUI.BeginClip(barsAndSidebarUIRect);
Rect shownBarsUIRect = barsUIRect;
shownBarsUIRect.y = scrollOffsetY;
// since the scale is not applied to the group headers, there would be some height unaccounted for
// this calculation applies that height to the threads via scaleForThreadHeight
float heightUnaccountedForDueToNotScalingHeaders = m_TimeArea.scale.y * combinedHeaderHeight - combinedHeaderHeight;
float scaleForThreadHeight = (combinedThreadHeight * m_TimeArea.scale.y + heightUnaccountedForDueToNotScalingHeaders) / combinedThreadHeight;
DrawBars(shownBarsUIRect, scaleForThreadHeight);
GUI.EndClip();
DoRangeSelection(barsUIRect);
GUI.BeginClip(barsUIRect);
shownBarsUIRect.x = 0;
bool oldEnabled = GUI.enabled;
GUI.enabled = false;
// Walk backwards to find how many previous frames we need to show.
int numContextFramesToShow = maxContextFramesToShow;
int currentFrame = frameIndex;
float currentTime = 0;
do
{
int prevFrame = ProfilerDriver.GetPreviousFrameIndex(currentFrame);
if (prevFrame == FrameDataView.invalidOrCurrentFrameIndex || !ProfilerDriver.GetFramesBelongToSameProfilerSession(currentFrame, prevFrame))
break;
iter.SetRoot(prevFrame, 0);
currentTime -= iter.frameTimeMS;
currentFrame = prevFrame;
--numContextFramesToShow;
}
while (currentTime > m_TimeArea.shownArea.x && numContextFramesToShow > 0);
// Draw previous frames
int firstDrawnFrame = currentFrame;
while (currentFrame != FrameDataView.invalidOrCurrentFrameIndex && currentFrame != frameIndex)
{
iter.SetRoot(currentFrame, 0);
DoProfilerFrame(frameIndex, currentFrame - frameIndex, shownBarsUIRect, true, currentTime, scaleForThreadHeight);
currentTime += iter.frameTimeMS;
currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame);
}
// Draw next frames
numContextFramesToShow = maxContextFramesToShow;
currentFrame = frameIndex;
currentTime = 0;
int lastDrawnFrame = currentFrame;
while (currentTime < m_TimeArea.shownArea.x + m_TimeArea.shownArea.width && numContextFramesToShow >= 0)
{
if (frameIndex != currentFrame)
{
DoProfilerFrame(frameIndex, currentFrame - frameIndex, shownBarsUIRect, true, currentTime, scaleForThreadHeight);
lastDrawnFrame = currentFrame;
}
iter.SetRoot(currentFrame, 0);
var prevFrame = currentFrame;
currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame);
if (currentFrame == FrameDataView.invalidOrCurrentFrameIndex || !ProfilerDriver.GetFramesBelongToSameProfilerSession(currentFrame, prevFrame))
break;
currentTime += iter.frameTimeMS;
--numContextFramesToShow;
}
GUI.enabled = oldEnabled;
// Draw center frame last to get on top
threadCount = 0;
currentTime = 0;
DoProfilerFrame(frameIndex, 0, shownBarsUIRect, false, currentTime, scaleForThreadHeight);
DoFlowEvents(frameIndex, firstDrawnFrame, lastDrawnFrame, shownBarsUIRect, scaleForThreadHeight);
GUI.EndClip();
// Draw Foldout Buttons on top of natively drawn bars
DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameIndex, ThreadSplitterCommand.HandleThreadSplitterFoldoutButtons);
// Draw tooltips on top of clip to be able to extend outside of timeline area
if (Event.current.type == EventType.Repaint)
DoSelectionTooltip(frameIndex, m_TimeArea.drawRect);
if (Event.current.type == EventType.Repaint)
{
// Reset all flags once Repaint finished on this view
m_LastRepaintProcessedInputs = m_CurrentlyProcessedInputs;
m_CurrentlyProcessedInputs = 0;
}
}
}
}
public void ReInitialize()
{
InitializeNativeTimeline();
}
void InitializeNativeTimeline()
{
var args = new NativeProfilerTimeline_InitializeArgs();
args.Reset();
args.ghostAlpha = 0.3f;
args.nonSelectedAlpha = 0.75f;
args.guiStyle = styles.bar.m_Ptr;
args.lineHeight = k_LineHeight;
args.textFadeOutWidth = k_TextFadeOutWidth;
args.textFadeStartWidth = k_TextFadeStartWidth;
var timelineColors = ProfilerColors.timelineColors;
args.profilerColorDescriptors = new ProfilerColorDescriptor[timelineColors.Length];
for (int i = 0; i < timelineColors.Length; ++i)
{
args.profilerColorDescriptors[i] = new ProfilerColorDescriptor(timelineColors[i]);
}
args.showFullScriptingMethodNames = ((cpuModule.ViewOptions & CPUOrGPUProfilerModule.ProfilerViewFilteringOptions.ShowFullScriptingMethodNames) != 0) ? 1 : 0;
NativeProfilerTimeline.Initialize(ref args);
}
void DoRangeSelection(Rect rect)
{
var controlID = EditorGUIUtility.GetControlID(RangeSelectionInfo.controlIDHint, FocusType.Passive);
var evt = Event.current;
switch (evt.GetTypeForControl(controlID))
{
case EventType.MouseDown:
if (EditorGUIUtility.hotControl == 0 && evt.button == 0 && rect.Contains(evt.mousePosition))
{
var delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), controlID);
delay.mouseDownPosition = evt.mousePosition;
m_RangeSelection.mouseDown = true;
m_RangeSelection.active = false;
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.RangeSelection;
}
break;
case EventType.MouseDrag:
if (EditorGUIUtility.hotControl == 0 && m_RangeSelection.mouseDown)
{
var delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), controlID);
if (delay.CanStartDrag())
{
EditorGUIUtility.hotControl = controlID;
m_RangeSelection.mouseDownTime = m_TimeArea.PixelToTime(delay.mouseDownPosition.x, rect);
m_RangeSelection.startTime = m_RangeSelection.endTime = m_RangeSelection.mouseDownTime;
ClearSelection();
m_RangeSelection.active = true;
evt.Use();
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.RangeSelection;
}
}
else if (EditorGUIUtility.hotControl == controlID)
{
var cursorTime = m_TimeArea.PixelToTime(evt.mousePosition.x, rect);
if (cursorTime < m_RangeSelection.mouseDownTime)
{
m_RangeSelection.startTime = cursorTime;
m_RangeSelection.endTime = m_RangeSelection.mouseDownTime;
}
else
{
m_RangeSelection.startTime = m_RangeSelection.mouseDownTime;
m_RangeSelection.endTime = cursorTime;
}
evt.Use();
m_CurrentlyProcessedInputs |= ProcessedInputs.MouseDown | ProcessedInputs.RangeSelection;
}
break;
case EventType.MouseUp:
if (EditorGUIUtility.hotControl == controlID && evt.button == 0)
{
EditorGUIUtility.hotControl = 0;
m_RangeSelection.mouseDown = false;
m_CurrentlyProcessedInputs -= (m_CurrentlyProcessedInputs & ProcessedInputs.MouseDown) | (m_CurrentlyProcessedInputs & ProcessedInputs.RangeSelection);
evt.Use();
}
break;
case EventType.Repaint:
if (m_RangeSelection.active)
{
var startPixel = m_TimeArea.TimeToPixel(m_RangeSelection.startTime, rect);
var endPixel = m_TimeArea.TimeToPixel(m_RangeSelection.endTime, rect);
if (startPixel > rect.xMax || endPixel < rect.xMin)
break;
var selectionRect = Rect.MinMaxRect(Mathf.Max(rect.xMin, startPixel), rect.yMin, Mathf.Min(rect.xMax, endPixel), rect.yMax);
styles.rectangleToolSelection.Draw(selectionRect, false, false, false, false);
}
break;
}
}
internal void DrawToolbar(ProfilerFrameDataIterator frameDataIterator, ref bool updateViewLive)
{
DrawViewTypePopup(ProfilerViewType.Timeline);
DrawLiveUpdateToggle(ref updateViewLive);
GUILayout.FlexibleSpace();
if (frameDataIterator != null)
DrawCPUGPUTime(frameDataIterator.frameTimeMS, frameDataIterator.frameGpuTimeMS);
GUILayout.FlexibleSpace();
cpuModule?.DrawOptionsMenuPopup();
}
void UpdateActiveFlowEventsForAllThreadsInAllVisibleFrames(int frameIndex, List<RawFrameDataView.FlowEvent> activeFlowEvents)
{
if (activeFlowEvents?.Count == 0)
return;
int firstContextFrame = IndexOfFirstContextFrame(frameIndex, maxContextFramesToShow);
int lastContextFrame = frameIndex + maxContextFramesToShow;
int currentFrame = firstContextFrame;
while ((currentFrame != FrameDataView.invalidOrCurrentFrameIndex) && (currentFrame <= lastContextFrame))
{
bool clearActiveFlowEvents = (currentFrame == firstContextFrame);
UpdateActiveFlowEventsForAllThreadsAtFrame(frameIndex, currentFrame - frameIndex, clearActiveFlowEvents, activeFlowEvents);
currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame);
}
}
int IndexOfFirstContextFrame(int currentFrame, int maximumNumberOfContextFramesToShow)
{
int firstVisibleContextFrameIndex = currentFrame;
do
{
int previousFrame = ProfilerDriver.GetPreviousFrameIndex(currentFrame);
if (previousFrame == FrameDataView.invalidOrCurrentFrameIndex)
{
break;
}
firstVisibleContextFrameIndex = previousFrame;
maximumNumberOfContextFramesToShow--;
}
while (maximumNumberOfContextFramesToShow > 0);
return firstVisibleContextFrameIndex;
}
void UpdateActiveFlowEventsForAllThreadsAtFrame(int currentFrameIndex, int currentFrameIndexOffset, bool clearThreadActiveFlowEvents, List<RawFrameDataView.FlowEvent> activeFlowEvents)
{
var frameIndex = currentFrameIndex + currentFrameIndexOffset;
foreach (var groupInfo in m_Groups)
{
foreach (var threadInfo in groupInfo.threads)
{
if (clearThreadActiveFlowEvents)
{
threadInfo.ActiveFlowEvents?.Clear();
}
var threadIndex = threadInfo.threadIndices[k_MaxNeighborFrames + currentFrameIndexOffset];
using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, threadIndex))
{
// In case we're crossing a boundary between data (f.e. captured and loaded, or captured from different devices)
// Some threads present in the first part might not be present in the second part
// As we use m_Groups from the first part, GetRawFrameDataView returns invalid object for the second
if ((frameData == null) || !frameData.valid)
continue;
frameData.GetFlowEvents(m_CachedThreadFlowEvents);
foreach (var threadFlowEvent in m_CachedThreadFlowEvents)
{
bool existsInActiveFlowEvents = false;
foreach (var activeFlowEvent in activeFlowEvents)
{
if (activeFlowEvent.FlowId == threadFlowEvent.FlowId)
{
existsInActiveFlowEvents = true;
break;
}
}
if (existsInActiveFlowEvents)
{
var flowEventData = new ThreadInfo.FlowEventData
{
flowEvent = threadFlowEvent,
frameIndex = frameIndex,
threadIndex = threadIndex
};
threadInfo.AddFlowEvent(flowEventData);
}
}
}
}
}
}
struct DrawnFlowIndicatorCacheValue
{
public int threadId;
public int markerId;
public ProfilerFlowEventType flowEventType;
}
class DrawnFlowIndicatorCacheValueComparer : EqualityComparer<DrawnFlowIndicatorCacheValue>
{
public override bool Equals(DrawnFlowIndicatorCacheValue x, DrawnFlowIndicatorCacheValue y)
{
return x.threadId.Equals(y.threadId) && x.markerId.Equals(y.markerId) && x.flowEventType.Equals(y.flowEventType);
}
public override int GetHashCode(DrawnFlowIndicatorCacheValue obj)
{
return base.GetHashCode();
}
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/ProfilerTimelineGUI.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/ProfilerTimelineGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 70593
} | 431 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Text;
using Unity.Profiling;
using Unity.Profiling.Editor;
using UnityEditor;
using UnityEditor.Networking.PlayerConnection;
using UnityEditor.Profiling;
using UnityEngine;
using UnityEngine.Networking.PlayerConnection;
using UnityEngine.Profiling;
using UnityEngine.Scripting;
using UnityEngine.UIElements;
namespace UnityEditorInternal.Profiling
{
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override.
internal static class MemoryProfilerOverrides
{
static public Func<ProfilerWindow, ProfilerModuleViewController> CreateDetailsViewController = null;
}
[Serializable]
[ProfilerModuleMetadata("Memory", typeof(LocalizationResource), IconPath = "Profiler.Memory")]
internal class MemoryProfilerModule : ProfilerModuleBase
{
class MemoryProfilerModuleViewController : ProfilerModuleViewController
{
// adaptation helper. MemoryProfilerModuleViewController is copied over from the memory profiler package which contains this helper
static class UIElementsHelper
{
public static void SetVisibility(VisualElement element, bool visible)
{
element.visible = visible;
element.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
}
public static Rect GetRect(VisualElement element)
{
return new Rect(element.LocalToWorld(element.contentRect.position), element.contentRect.size);
}
}
static class ResourcePaths
{
public const string MemoryModuleUxmlPath = "Profiler/Modules/Memory/MemoryModule.uxml";
}
static class Content
{
public static readonly string NoFrameDataAvailable = L10n.Tr("No frame data available. Select a frame from the charts above to see its details here.");
public static readonly string Textures = L10n.Tr("Textures");
public static readonly string Meshes = L10n.Tr("Meshes");
public static readonly string Materials = L10n.Tr("Materials");
public static readonly string AnimationClips = L10n.Tr("Animation Clips");
public static readonly string Assets = L10n.Tr("Assets");
public static readonly string GameObjects = L10n.Tr("Game Objects");
public static readonly string SceneObjects = L10n.Tr("Scene Objects");
public static readonly string GCAlloc = L10n.Tr("GC allocated in frame");
}
struct ObjectTableRow
{
public Label Count;
public Label Size;
}
MemoryProfilerModule m_MemoryModule;
// all UI Element and similar references should be grouped into this class.
// Since the things this reference get recreated every time the module is selected, these references shouldn't linger beyond the Dispose()
UIState m_UIState = null;
class UIState
{
public VisualElement ViewArea;
public VisualElement NoDataView;
public VisualElement SimpleView;
public VisualElement DetailedView;
public UnityEngine.UIElements.Button DetailedMenu;
public Label DetailedMenuLabel;
public UnityEngine.UIElements.Button InstallPackageButton;
public VisualElement EditorWarningLabel;
public MemoryUsageBreakdown TopLevelBreakdown;
public MemoryUsageBreakdown Breakdown;
// if no memory counter data is available (i.e. the recording is from a pre 2020.2 Unity version) this whole section can't be populated with info
public VisualElement CounterBasedUI;
public TextField Text;
public ObjectTableRow TexturesRow;
public ObjectTableRow MeshesRow;
public ObjectTableRow MaterialsRow;
public ObjectTableRow AnimationClipsRow;
public ObjectTableRow AssetsRow;
public ObjectTableRow GameObjectsRow;
public ObjectTableRow SceneObjectsRow;
public ObjectTableRow GCAllocRow;
}
ulong[] m_Used = new ulong[6];
ulong[] m_Reserved = new ulong[6];
ulong[] m_TotalUsed = new ulong[1];
ulong[] m_TotalReserved = new ulong[1];
StringBuilder m_SimplePaneStringBuilder = new StringBuilder(1024);
bool m_AddedSimpleDataView = false;
ulong m_MaxSystemUsedMemory = 0;
IConnectionState m_ConnectionState;
bool m_InitiatedPackageSearchQuery;
public MemoryProfilerModuleViewController(ProfilerWindow profilerWindow, MemoryProfilerModule memoryModule) : base(profilerWindow)
{
profilerWindow.SelectedFrameIndexChanged += UpdateContent;
m_MemoryModule = memoryModule;
if (!m_MemoryModule.InitiateMemoryProfilerPackageAvailabilityCheck())
{
m_InitiatedPackageSearchQuery = true;
}
}
int[] oneFrameAvailabilityBuffer = new int[1];
bool CheckMemoryStatsAvailablity(long frameIndex)
{
var dataNotAvailable = frameIndex < 0 || frameIndex<ProfilerWindow.firstAvailableFrameIndex || frameIndex> ProfilerWindow.lastAvailableFrameIndex;
if (!dataNotAvailable)
{
ProfilerDriver.GetStatisticsAvailable(UnityEngine.Profiling.ProfilerArea.Memory, (int)frameIndex, oneFrameAvailabilityBuffer);
if (oneFrameAvailabilityBuffer[0] == 0)
dataNotAvailable = true;
}
return !dataNotAvailable;
}
void ViewChanged(ProfilerMemoryView view)
{
var frameIndex = ProfilerWindow.selectedFrameIndex;
bool isDataAvailable = CheckMemoryStatsAvailablity(frameIndex);
m_MemoryModule.m_ShowDetailedMemoryPane = view;
if (view == ProfilerMemoryView.Simple)
{
if (isDataAvailable)
{
m_AddedSimpleDataView = true;
UpdateContent(frameIndex);
}
else
{
m_AddedSimpleDataView = false;
}
}
else
{
m_AddedSimpleDataView = false;
}
UIElementsHelper.SetVisibility(m_UIState.NoDataView, !isDataAvailable);
UIElementsHelper.SetVisibility(m_UIState.SimpleView, isDataAvailable && (view == ProfilerMemoryView.Simple));
UIElementsHelper.SetVisibility(m_UIState.DetailedView, isDataAvailable && (view == ProfilerMemoryView.Detailed));
m_UIState.DetailedMenuLabel.text = view == ProfilerMemoryView.Simple ? "Simple" : "Detailed";
}
static ProfilerMarker s_UpdateMaxSystemUsedMemoryProfilerMarker = new ProfilerMarker("MemoryProfilerModule.UpdateMaxSystemUsedMemory");
float[] m_CachedArray;
// Total System Memory Used
void UpdateMaxSystemUsedMemory(long firstFrameToCheck, long lastFrameToCheck)
{
s_UpdateMaxSystemUsedMemoryProfilerMarker.Begin();
var frameCountToCheck = lastFrameToCheck - firstFrameToCheck;
m_MaxSystemUsedMemory = 0;
var max = m_MaxSystemUsedMemory;
// try to reuse the array if possible
if (m_CachedArray == null || m_CachedArray.Length != frameCountToCheck)
m_CachedArray = new float[frameCountToCheck];
float maxValueInRange;
ProfilerDriver.GetCounterValuesBatch(UnityEngine.Profiling.ProfilerArea.Memory, "System Used Memory", (int)firstFrameToCheck, 1, m_CachedArray, out maxValueInRange);
if (maxValueInRange > max)
max = (ulong)maxValueInRange;
m_MaxSystemUsedMemory = max;
s_UpdateMaxSystemUsedMemoryProfilerMarker.End();
}
void UpdateContent(long frame)
{
if (m_MemoryModule.m_ShowDetailedMemoryPane != ProfilerMemoryView.Simple)
return;
var dataAvailable = CheckMemoryStatsAvailablity(frame);
if (m_AddedSimpleDataView != dataAvailable)
{
// refresh the view structure
ViewChanged(ProfilerMemoryView.Simple);
return;
}
if (!dataAvailable)
return;
if (m_UIState != null)
{
using (var data = ProfilerDriver.GetRawFrameDataView((int)frame, 0))
{
m_SimplePaneStringBuilder.Clear();
if (data.valid && data.GetMarkerId("Total Reserved Memory") != FrameDataView.invalidMarkerId)
{
var systemUsedMemoryId = data.GetMarkerId("System Used Memory");
var systemUsedMemory = (ulong)data.GetCounterValueAsLong(systemUsedMemoryId);
var systemUsedMemoryIsKnown = (systemUsedMemoryId != FrameDataView.invalidMarkerId && systemUsedMemory > 0);
var maxSystemUsedMemory = m_MaxSystemUsedMemory = systemUsedMemory;
if (!m_MemoryModule.m_Normalized)
{
UpdateMaxSystemUsedMemory(ProfilerWindow.firstAvailableFrameIndex, ProfilerWindow.lastAvailableFrameIndex);
maxSystemUsedMemory = m_MaxSystemUsedMemory;
}
var totalUsedId = data.GetMarkerId("Total Used Memory");
var totalUsed = (ulong)data.GetCounterValueAsLong(totalUsedId);
var totalReservedId = data.GetMarkerId("Total Reserved Memory");
var totalReserved = (ulong)data.GetCounterValueAsLong(totalReservedId);
m_TotalUsed[0] = totalUsed;
m_TotalReserved[0] = totalReserved;
if (!systemUsedMemoryIsKnown)
systemUsedMemory = totalReserved;
m_UIState.TopLevelBreakdown.SetVaules(systemUsedMemory, m_TotalReserved, m_TotalUsed, m_MemoryModule.m_Normalized, maxSystemUsedMemory, systemUsedMemoryIsKnown);
m_Used[4] = totalUsed;
m_Reserved[4] = totalReserved;
var gfxReservedId = data.GetMarkerId("Gfx Reserved Memory");
m_Reserved[1] = m_Used[1] = (ulong)data.GetCounterValueAsLong(gfxReservedId);
var managedUsedId = data.GetMarkerId("GC Used Memory");
m_Used[0] = (ulong)data.GetCounterValueAsLong(managedUsedId);
var managedReservedId = data.GetMarkerId("GC Reserved Memory");
m_Reserved[0] = (ulong)data.GetCounterValueAsLong(managedReservedId);
var audioReservedId = data.GetMarkerId("Audio Used Memory");
m_Reserved[2] = m_Used[2] = (ulong)data.GetCounterValueAsLong(audioReservedId);
var videoReservedId = data.GetMarkerId("Video Used Memory");
m_Reserved[3] = m_Used[3] = (ulong)data.GetCounterValueAsLong(videoReservedId);
var profilerUsedId = data.GetMarkerId("Profiler Used Memory");
m_Used[5] = (ulong)data.GetCounterValueAsLong(profilerUsedId);
var profilerReservedId = data.GetMarkerId("Profiler Reserved Memory");
m_Reserved[5] = (ulong)data.GetCounterValueAsLong(profilerReservedId);
m_Used[4] -= Math.Min(m_Used[0] + m_Used[1] + m_Used[2] + m_Used[3] + m_Used[5], m_Used[4]);
m_Reserved[4] -= Math.Min(m_Reserved[0] + m_Reserved[1] + m_Reserved[2] + m_Reserved[3] + m_Reserved[5], m_Reserved[4]);
m_UIState.Breakdown.SetVaules(systemUsedMemory, m_Reserved, m_Used, m_MemoryModule.m_Normalized, maxSystemUsedMemory, systemUsedMemoryIsKnown);
UpdateObjectRow(data, ref m_UIState.TexturesRow, "Texture Count", "Texture Memory");
UpdateObjectRow(data, ref m_UIState.MeshesRow, "Mesh Count", "Mesh Memory");
UpdateObjectRow(data, ref m_UIState.MaterialsRow, "Material Count", "Material Memory");
UpdateObjectRow(data, ref m_UIState.AnimationClipsRow, "AnimationClip Count", "AnimationClip Memory");
UpdateObjectRow(data, ref m_UIState.AssetsRow, "Asset Count");
UpdateObjectRow(data, ref m_UIState.GameObjectsRow, "Game Object Count");
UpdateObjectRow(data, ref m_UIState.SceneObjectsRow, "Scene Object Count");
UpdateObjectRow(data, ref m_UIState.GCAllocRow, "GC Allocation In Frame Count", "GC Allocated In Frame");
if (!m_UIState.CounterBasedUI.visible)
UIElementsHelper.SetVisibility(m_UIState.CounterBasedUI, true);
var platformSpecifics = MemoryProfilerModule.GetPlatformSpecificText(data, ProfilerWindow);
if (!string.IsNullOrEmpty(platformSpecifics))
{
m_SimplePaneStringBuilder.Append(platformSpecifics);
}
}
else
{
if (m_UIState.CounterBasedUI.visible)
UIElementsHelper.SetVisibility(m_UIState.CounterBasedUI, false);
m_SimplePaneStringBuilder.Append(MemoryProfilerModule.GetSimpleMemoryPaneText(data, ProfilerWindow, false));
}
if (m_SimplePaneStringBuilder.Length > 0)
{
UIElementsHelper.SetVisibility(m_UIState.Text, true);
m_UIState.Text.value = m_SimplePaneStringBuilder.ToString();
}
else
{
UIElementsHelper.SetVisibility(m_UIState.Text, false);
}
}
}
}
void UpdateObjectRow(RawFrameDataView data, ref ObjectTableRow row, string countMarkerName, string sizeMarkerName = null)
{
row.Count.text = data.GetCounterValueAsLong(data.GetMarkerId(countMarkerName)).ToString();
if (!string.IsNullOrEmpty(sizeMarkerName))
row.Size.text = EditorUtility.FormatBytes(data.GetCounterValueAsLong(data.GetMarkerId(sizeMarkerName)));
}
void ConnectionChanged(string playerName)
{
if (m_ConnectionState != null)
UIElementsHelper.SetVisibility(m_UIState.EditorWarningLabel, m_ConnectionState.connectionName == "Editor");
}
void CheckPackageAvailabilityStatus()
{
if (m_InitiatedPackageSearchQuery && !m_MemoryModule.MemoryProfilerPackageAvailabilityCheckMoveNext())
{
m_InitiatedPackageSearchQuery = false;
UpdatePackageInstallButton();
}
}
void UpdatePackageInstallButton()
{
if (m_UIState != null)
{
switch (m_MemoryModule.m_MemoryProfilerPackageStage)
{
case PackageStage.Experimental:
m_UIState.InstallPackageButton.text = Styles.experimentalPackageHint.text;
break;
case PackageStage.PreviewOrReleased:
m_UIState.InstallPackageButton.text = Styles.packageInstallSuggestionButton.text;
break;
case PackageStage.Installed:
UIElementsHelper.SetVisibility(m_UIState.InstallPackageButton, false);
break;
default:
break;
}
}
}
void PackageInstallButtonClicked()
{
switch (m_MemoryModule.m_MemoryProfilerPackageStage)
{
case PackageStage.Experimental:
Application.OpenURL(Styles.memoryProfilerPackageDocumentatinURL);
break;
case PackageStage.PreviewOrReleased:
UnityEditor.PackageManager.Client.Add(m_MemoryModule.m_MemoryProfilerPackageName);
break;
case PackageStage.Installed:
break;
default:
break;
}
}
protected override VisualElement CreateView()
{
VisualTreeAsset memoryModuleViewTree = EditorGUIUtility.Load(ResourcePaths.MemoryModuleUxmlPath) as VisualTreeAsset;
var root = memoryModuleViewTree.CloneTree();
m_UIState = new UIState();
var toolbar = root.Q("memory-module__toolbar");
m_UIState.DetailedMenu = toolbar.Q<UnityEngine.UIElements.Button>("memory-module__toolbar__detail-view-menu");
m_UIState.DetailedMenuLabel = m_UIState.DetailedMenu.Q<Label>("memory-module__toolbar__detail-view-menu__label");
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Simple"), false, () => ViewChanged(ProfilerMemoryView.Simple));
menu.AddItem(new GUIContent("Detailed"), false, () => ViewChanged(ProfilerMemoryView.Detailed));
m_UIState.DetailedMenu.clicked += () =>
{
menu.DropDown(UIElementsHelper.GetRect(m_UIState.DetailedMenu));
};
m_UIState.InstallPackageButton = toolbar.Q<UnityEngine.UIElements.Button>("memory-module__toolbar__install-package-button");
// in the main code base, this button offers to install the memory profiler package, here it is swapped to be one that opens it.
if (m_InitiatedPackageSearchQuery)
m_UIState.InstallPackageButton.schedule.Execute(CheckPackageAvailabilityStatus).Until(() => !m_InitiatedPackageSearchQuery);
m_UIState.InstallPackageButton.clicked += PackageInstallButtonClicked;
UpdatePackageInstallButton();
m_UIState.EditorWarningLabel = toolbar.Q("memory-module__toolbar__editor-warning");
m_ConnectionState = PlayerConnectionGUIUtility.GetConnectionState(ProfilerWindow, ConnectionChanged);
UIElementsHelper.SetVisibility(m_UIState.EditorWarningLabel, m_ConnectionState.connectionName == "Editor");
m_UIState.ViewArea = root.Q("memory-module__view-area");
m_UIState.SimpleView = m_UIState.ViewArea.Q("memory-module__simple-area");
m_UIState.CounterBasedUI = m_UIState.SimpleView.Q("memory-module__simple-area__counter-based-ui");
var normalizedToggle = m_UIState.CounterBasedUI.Q<Toggle>("memory-module__simple-area__breakdown__normalized-toggle");
normalizedToggle.value = m_MemoryModule.m_Normalized;
normalizedToggle.RegisterValueChangedCallback((evt) =>
{
m_MemoryModule.m_Normalized = evt.newValue;
UpdateContent(ProfilerWindow.selectedFrameIndex);
});
m_UIState.TopLevelBreakdown = m_UIState.CounterBasedUI.Q<MemoryUsageBreakdown>("memory-usage-breakdown__top-level");
m_UIState.TopLevelBreakdown.Setup();
m_UIState.Breakdown = m_UIState.CounterBasedUI.Q<MemoryUsageBreakdown>("memory-usage-breakdown");
m_UIState.Breakdown.Setup();
var m_ObjectStatsTable = m_UIState.CounterBasedUI.Q("memory-usage-breakdown__object-stats_list");
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__textures"), ref m_UIState.TexturesRow, Content.Textures);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__meshes"), ref m_UIState.MeshesRow, Content.Meshes);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__materials"), ref m_UIState.MaterialsRow, Content.Materials);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__animation-clips"), ref m_UIState.AnimationClipsRow, Content.AnimationClips);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__assets"), ref m_UIState.AssetsRow, Content.Assets, true);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__game-objects"), ref m_UIState.GameObjectsRow, Content.GameObjects, true);
SetupObjectTableRow(m_ObjectStatsTable.Q("memory-usage-breakdown__object-stats__scene-objects"), ref m_UIState.SceneObjectsRow, Content.SceneObjects, true);
var m_GCAllocExtraRow = m_UIState.CounterBasedUI.Q<VisualElement>("memory-usage-breakdown__object-stats__gc");
SetupObjectTableRow(m_GCAllocExtraRow, ref m_UIState.GCAllocRow, Content.GCAlloc);
m_UIState.Text = m_UIState.SimpleView.Q<TextField>("memory-module__simple-area__label");
var detailedView = m_UIState.ViewArea.Q<VisualElement>("memory-profiler-module__detailed");
m_UIState.DetailedView = detailedView;
m_UIState.NoDataView = m_UIState.ViewArea.Q("memory-module__no-frame-data__area");
m_UIState.NoDataView.Q<Label>("memory-module__no-frame-data__label").text = Content.NoFrameDataAvailable;
ViewChanged(m_MemoryModule.m_ShowDetailedMemoryPane);
return root;
}
void SetupObjectTableRow(VisualElement rowRoot, ref ObjectTableRow row, string name, bool sizesUnknown = false)
{
rowRoot.Q<Label>("memory-usage-breakdown__object-table__name").text = name;
row.Count = rowRoot.Q<Label>("memory-usage-breakdown__object-table__count-column");
row.Count.text = "0";
row.Size = rowRoot.Q<Label>("memory-usage-breakdown__object-table__size-column");
row.Size.text = sizesUnknown ? "-" : "0";
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (ProfilerWindow != null)
ProfilerWindow.SelectedFrameIndexChanged -= UpdateContent;
if (m_ConnectionState != null)
m_ConnectionState.Dispose();
m_ConnectionState = null;
m_UIState = null;
}
}
internal static class Styles
{
public static readonly GUIContent gatherObjectReferences = EditorGUIUtility.TrTextContent("Gather object references", "Collect reference information to see where objects are referenced from. Disable this to save memory");
public static readonly GUIContent takeSample = EditorGUIUtility.TrTextContent("Take Sample {0}", "Warning: this may freeze the Editor and the connected Player for a moment!");
public static readonly GUIContent memoryUsageInEditorDisclaimer = EditorGUIUtility.TrTextContent("Memory usage in the Editor is not the same as it would be in a Player.");
public const string memoryProfilerPackageDocumentatinURL = "https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest/";
public static readonly GUIContent experimentalPackageHint = EditorGUIUtility.TrTextContent("See more details with the experimental Memory Profiler Package.");
public static readonly string packageInstallSuggestion = L10n.Tr("Install Memory Profiler Package{0}");
public static readonly string packageInstallSuggestionVersionPart = L10n.Tr(" (Version {0})");
public static GUIContent packageInstallSuggestionButton = new GUIContent(string.Format(packageInstallSuggestion, ""));
}
const int k_DefaultOrderIndex = 3;
static readonly float[] k_SplitterMinSizes = new[] { 450f, 50f };
static readonly string[] k_DefaultMemoryAreaCounterNames =
{
"Total Used Memory",
"Texture Memory",
"Mesh Memory",
"Material Count",
"Object Count",
"GC Used Memory",
"GC Allocated In Frame",
};
static readonly string[] k_PS4MemoryAreaAdditionalCounterNames = new string[]
{
"GARLIC heap allocs",
"ONION heap allocs"
};
static readonly string k_MemoryCountersCategoryName = ProfilerCategory.Memory.Name;
static WeakReference instance;
const string k_GatherObjectReferencesSettingsKey = "Profiler.MemoryProfilerModule.GatherObjectReferences";
const string k_SplitterRelative0SettingsKey = "Profiler.MemoryProfilerModule.Splitter.Relative[0]";
const string k_SplitterRelative1SettingsKey = "Profiler.MemoryProfilerModule.Splitter.Relative[1]";
[SerializeField]
SplitterState m_ViewSplit;
ProfilerMemoryView m_ShowDetailedMemoryPane;
bool m_Normalized;
MemoryTreeList m_ReferenceListView;
MemoryTreeListClickable m_MemoryListView;
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override. (Only when showing old (pre-2020.2 aka pre-memory-counters) profiler data)
// (Only until the package fully replaces all workflows afforded by this view, at which point the details view will just not be available from the package override UI anymore)
bool m_GatherObjectReferences = true;
internal override ProfilerArea area => ProfilerArea.Memory;
private protected override int defaultOrderIndex => k_DefaultOrderIndex;
private protected override string legacyPreferenceKey => "ProfilerChartMemory";
enum PackageStage
{
Experimental,
PreviewOrReleased,
Installed,
}
PackageStage m_MemoryProfilerPackageStage = PackageStage.Experimental;
UnityEditor.PackageManager.Requests.SearchRequest m_MemoryProfilerSearchRequest = null;
string m_MemoryProfilerPackageName = "com.unity.memoryprofiler";
bool wantsMemoryRefresh { get { return m_MemoryListView.RequiresRefresh; } }
System.Reflection.MethodInfo s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter;
public override ProfilerModuleViewController CreateDetailsViewController()
{
ProfilerModuleViewController detailsViewController = null;
// Try to get a view controller from the Memory Profiler package first.
if (IsMemoryProfilerPackageInstalled())
{
// Old versions of the Memory Profiler package (before 1.0) will use reflection to bind their MemoryProfilerModuleBridge.CreateDetailsViewController callback to MemoryProfilerOverrides.CreateDetailsViewController. New versions of the Memory Profiler package (1.0+) cannot use reflection so instead wait to be called. Therefore, we call MemoryProfilerModuleBridge.CreateDetailsViewController callback manually from here, supporting both old and new versions. Note the callback itself cannot be cached, due to the Editor setting for enabling the functionality being respected in the package providing this callback or not.
Func<ProfilerWindow, ProfilerModuleViewController> createDetailsViewControllerCallback = null;
if (s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter == null)
{
try
{
var type = Type.GetType("Unity.MemoryProfiler.Editor.MemoryProfilerModule.MemoryProfilerModuleBridge, Unity.MemoryProfiler.Editor.MemoryProfilerModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
var property = type.GetProperty("CreateDetailsViewController");
s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter = property.GetMethod;
}
catch (Exception) { }
}
createDetailsViewControllerCallback = s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter?.Invoke(null, null) as Func<ProfilerWindow, ProfilerModuleViewController>;
detailsViewController = createDetailsViewControllerCallback?.Invoke(ProfilerWindow);
}
// Fall back to the built-in view controller.
if (detailsViewController == null)
detailsViewController = new MemoryProfilerModuleViewController(ProfilerWindow, this);
return detailsViewController;
}
internal override void OnEnable()
{
base.OnEnable();
instance = new WeakReference(this);
InitiateMemoryProfilerPackageAvailabilityCheck();
if (m_ReferenceListView == null)
m_ReferenceListView = new MemoryTreeList(ProfilerWindow, null);
if (m_MemoryListView == null)
m_MemoryListView = new MemoryTreeListClickable(ProfilerWindow, m_ReferenceListView);
if (m_ViewSplit == null || !m_ViewSplit.IsValid())
m_ViewSplit = SplitterState.FromRelative(new[] { EditorPrefs.GetFloat(k_SplitterRelative0SettingsKey, 70f), EditorPrefs.GetFloat(k_SplitterRelative1SettingsKey, 30f) }, k_SplitterMinSizes, null);
m_ShowDetailedMemoryPane = ProfilerMemoryView.Simple;
m_GatherObjectReferences = EditorPrefs.GetBool(k_GatherObjectReferencesSettingsKey, true);
}
internal override void SaveViewSettings()
{
base.SaveViewSettings();
EditorPrefs.SetBool(k_GatherObjectReferencesSettingsKey, m_GatherObjectReferences);
if (m_ViewSplit != null && m_ViewSplit.relativeSizes != null && m_ViewSplit.relativeSizes.Length >= 2)
{
EditorPrefs.SetFloat(k_SplitterRelative0SettingsKey, m_ViewSplit.relativeSizes[0]);
EditorPrefs.SetFloat(k_SplitterRelative1SettingsKey, m_ViewSplit.relativeSizes[1]);
}
}
internal override void OnNativePlatformSupportModuleChanged()
{
base.OnNativePlatformSupportModuleChanged();
var chartCounters = CollectDefaultChartCounters();
SetCounters(chartCounters, chartCounters);
}
bool InitiateMemoryProfilerPackageAvailabilityCheck()
{
if (IsMemoryProfilerPackageInstalled())
{
m_MemoryProfilerPackageStage = PackageStage.Installed;
return true;
}
m_MemoryProfilerSearchRequest = UnityEditor.PackageManager.Client.Search(m_MemoryProfilerPackageName, true);
return false;
}
bool IsMemoryProfilerPackageInstalled()
{
return UnityEditor.PackageManager.PackageInfo.IsPackageRegistered(m_MemoryProfilerPackageName);
}
bool MemoryProfilerPackageAvailabilityCheckMoveNext()
{
if (m_MemoryProfilerSearchRequest != null)
{
if (m_MemoryProfilerSearchRequest.IsCompleted)
{
if (m_MemoryProfilerSearchRequest.Result != null)
{
foreach (var result in m_MemoryProfilerSearchRequest.Result)
{
if (!result.version.StartsWith("0."))
{
m_MemoryProfilerPackageStage = PackageStage.PreviewOrReleased;
Styles.packageInstallSuggestionButton = new GUIContent(string.Format(Styles.packageInstallSuggestion, string.Format(Styles.packageInstallSuggestionVersionPart, m_MemoryProfilerSearchRequest.Result[0].versions.latestCompatible)));
break;
}
}
}
m_MemoryProfilerSearchRequest = null;
return false;
}
return true;
}
return false;
}
protected override List<ProfilerCounterData> CollectDefaultChartCounters()
{
var defaultChartCounters = new List<ProfilerCounterData>(k_DefaultMemoryAreaCounterNames.Length);
foreach (var defaultCounterName in k_DefaultMemoryAreaCounterNames)
{
defaultChartCounters.Add(new ProfilerCounterData()
{
m_Name = defaultCounterName,
m_Category = k_MemoryCountersCategoryName,
});
}
// Add any counters specific to native platforms.
var m_ActiveNativePlatformSupportModule = EditorUtility.GetActiveNativePlatformSupportModuleName();
if (m_ActiveNativePlatformSupportModule == "PS4")
{
var ps4ChartCounters = new List<ProfilerCounterData>(k_PS4MemoryAreaAdditionalCounterNames.Length);
foreach (var ps4CounterName in k_PS4MemoryAreaAdditionalCounterNames)
{
ps4ChartCounters.Add(new ProfilerCounterData()
{
m_Name = ps4CounterName,
m_Category = k_MemoryCountersCategoryName,
});
}
defaultChartCounters.AddRange(ps4ChartCounters);
}
return defaultChartCounters;
}
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override. (Only when showing old (pre-2020.2 aka pre-memory-counters) profiler data)
static string GetSimpleMemoryPaneText(RawFrameDataView f, IProfilerWindowController profilerWindow, bool summary = true)
{
if (f.valid)
{
var totalReservedMemoryId = GetCounterValue(f, "Total Reserved Memory");
if (totalReservedMemoryId != -1)
{
// Counter Data is available, a text form display is not needed
return string.Empty;
}
else
{
// Old data compatibility.
return ProfilerDriver.GetOverviewText(ProfilerArea.Memory, profilerWindow.GetActiveVisibleFrameIndex());
}
}
return string.Empty;
}
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override. (To avoid pulling platform specifics into the package)
static string GetPlatformSpecificText(RawFrameDataView f, IProfilerWindowController profilerWindow)
{
if (f.valid)
{
var totalReservedMemoryId = GetCounterValue(f, "Total Reserved Memory");
if (totalReservedMemoryId != -1)
{
StringBuilder stringBuilder = new StringBuilder(1024);
var garlicHeapUsedMemory = GetCounterValue(f, "GARLIC heap used");
if (garlicHeapUsedMemory != -1)
{
var garlicHeapAvailable = GetCounterValue(f, "GARLIC heap available");
stringBuilder.Append($"\n\nGARLIC heap used: {EditorUtility.FormatBytes(garlicHeapUsedMemory)}/{EditorUtility.FormatBytes(garlicHeapAvailable + garlicHeapUsedMemory)} ");
stringBuilder.Append($"({EditorUtility.FormatBytes(garlicHeapAvailable)} available) ");
stringBuilder.Append($"peak used: {GetCounterValueAsBytes(f, "GARLIC heap peak used")} ");
stringBuilder.Append($"num allocs: {GetCounterValue(f, "GARLIC heap allocs")}\n");
stringBuilder.Append($"ONION heap used: {GetCounterValueAsBytes(f, "ONION heap used")} ");
stringBuilder.Append($"peak used: {GetCounterValueAsBytes(f, "ONION heap peak used")} ");
stringBuilder.Append($"num allocs: {GetCounterValue(f, "ONION heap allocs")}");
return stringBuilder.ToString();
}
}
}
return null;
}
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override.
// (Only until the package fully replaces all workflows afforded by this view, at which point the details view will just not be available from the package override UI anymore)
void DrawDetailedMemoryPane()
{
SplitterGUILayout.BeginHorizontalSplit(m_ViewSplit);
m_MemoryListView.OnGUI();
m_ReferenceListView.OnGUI();
SplitterGUILayout.EndHorizontalSplit();
}
// Used with via Reflection (see MemoryProfilerModuleBridge.cs) from the Profiler Memory Profiler Package for the Memory Profiler Module UI Override. (Only when showing old (pre-2020.2 aka pre-memory-counters) profiler data)
// (Only until the package fully replaces all workflows afforded by this view, at which point the details view will just not be available from the package override UI anymore)
void RefreshMemoryData()
{
m_MemoryListView.RequiresRefresh = true;
ProfilerDriver.RequestObjectMemoryInfo(m_GatherObjectReferences);
}
/// <summary>
/// Called from Native in ObjectMemoryProfiler.cpp ObjectMemoryProfiler::DeserializeAndApply
/// </summary>
/// <param name="memoryInfo"></param>
/// <param name="referencedIndices"></param>
[RequiredByNativeCode]
static void SetMemoryProfilerInfo(ObjectMemoryInfo[] memoryInfo, int[] referencedIndices)
{
if (instance.IsAlive && (instance.Target as MemoryProfilerModule).wantsMemoryRefresh)
{
(instance.Target as MemoryProfilerModule).m_MemoryListView.SetRoot(MemoryElementDataManager.GetTreeRoot(memoryInfo, referencedIndices));
}
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryProfilerModule.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryProfilerModule.cs",
"repo_id": "UnityCsReference",
"token_count": 18138
} | 432 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Profiling;
using UnityEditor.IMGUI.Controls;
using UnityEditor.Profiling;
using UnityEngine.UIElements;
using System.Text;
namespace UnityEditor
{
[Serializable]
internal class VirtualTexturingProfilerView
{
Vector2 m_ListScroll, m_SystemScroll, m_PlayerScroll;
static readonly Guid m_VTProfilerGuid = new Guid("AC871613E8884327B4DD29D7469548DC");
MultiColumnHeaderState m_HeaderState;
VTMultiColumnHeader m_Header;
struct FrameData
{
public GraphicsFormat format;
public int demand;
public float bias;
public int size;
}
List<FrameData> m_FrameData = new List<FrameData>();
bool m_SortingChanged = false;
[SerializeField]
bool m_SortAscending = false;
[SerializeField]
int m_SortedColumn = -1;
void Init()
{
int baseWidth = 270;
m_HeaderState = new MultiColumnHeaderState(new MultiColumnHeaderState.Column[]
{
new MultiColumnHeaderState.Column {headerContent = EditorGUIUtility.TrTextContent(" Cache Format"), width = baseWidth, autoResize = false},
new MultiColumnHeaderState.Column {headerContent = EditorGUIUtility.TrTextContent("Demand"), width = baseWidth, autoResize = false},
new MultiColumnHeaderState.Column {headerContent = EditorGUIUtility.TrTextContent("Bias"), width = baseWidth, autoResize = false},
new MultiColumnHeaderState.Column {headerContent = EditorGUIUtility.TrTextContent("Size"), width = baseWidth, autoResize = false}
});
foreach (var column in m_HeaderState.columns)
{
column.sortingArrowAlignment = TextAlignment.Center;
column.headerTextAlignment = TextAlignment.Left;
column.allowToggleVisibility = false;
column.sortedAscending = true;
}
m_Header = new VTMultiColumnHeader(m_HeaderState);
m_Header.height = 34;
m_Header.ResizeToFit();
m_Header.sortingChanged += header => { m_SortingChanged = true; m_SortedColumn = header.sortedColumnIndex; };
//Used to preserve sorting after domain reloads
if (m_SortedColumn != -1)
m_Header.SetSorting(m_SortedColumn, m_SortAscending);
}
internal void DrawUIPane(IProfilerWindowController win)
{
if (Styles.backgroundStyle == null)
Styles.CreateStyles();
//make sure all background textures exist
Styles.CheckBackgroundTextures();
EditorGUILayout.BeginVertical();
var rect = EditorGUILayout.GetControlRect(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
const int padding = 1;
Rect aggregateHeader = rect;
aggregateHeader.width = Mathf.Min(434, rect.width);
aggregateHeader.height = 34;
Rect aggregateData = aggregateHeader;
aggregateData.y += aggregateHeader.height + padding;
float aggregateBoxHeight = rect.height / 2 - aggregateHeader.height - padding * 2;
aggregateData.height = aggregateBoxHeight;
Rect infoBox = new Rect();
if (ProfilerDriver.GetStatisticsAvailabilityState(ProfilerArea.VirtualTexturing, win.GetActiveVisibleFrameIndex()) == 0)
{
GUI.Label(aggregateHeader, "No Virtual Texturing data was collected.");
EditorGUILayout.EndVertical();
return;
}
GUI.Box(rect, "", Styles.backgroundStyle);
using (RawFrameDataView frameDataView = ProfilerDriver.GetRawFrameDataView(win.GetActiveVisibleFrameIndex(), 0))
{
if (frameDataView.valid)
{
Assert.IsTrue(frameDataView.threadName == "Main Thread");
RawFrameDataView fRender = GetRenderThread(frameDataView);
//system statistics
var stringBuilder = new StringBuilder(1024);
int requiredTiles = (int)GetCounterValue(frameDataView, "Required Tiles");
stringBuilder.AppendLine($" Tiles required this frame: {requiredTiles}");
stringBuilder.AppendLine($" Max Cache Mip Bias: {GetCounterValueAsFloat(frameDataView, "Max Cache Mip Bias")}");
stringBuilder.AppendLine($" Max Cache Demand: {GetCounterValue(frameDataView, "Max Cache Demand")}%");
stringBuilder.AppendLine($" Total CPU Cache Size: {EditorUtility.FormatBytes(GetCounterValue(frameDataView, "Total CPU Cache Size"))}");
stringBuilder.AppendLine($" Total GPU Cache Size: {EditorUtility.FormatBytes(GetCounterValue(frameDataView, "Total GPU Cache Size"))}");
stringBuilder.AppendLine($" Atlases: {GetCounterValue(frameDataView, "Atlases")}");
string aggregatedText = stringBuilder.ToString();
float aggregateTextHeight = EditorStyles.wordWrappedLabel.CalcHeight(GUIContent.Temp(aggregatedText), rect.width);
float actualHeight = Mathf.Max(aggregateBoxHeight, aggregateTextHeight);
DrawScrollBackground(new Rect(aggregateData.width - 12, aggregateData.y, 14, aggregateData.height));
GUI.Box(aggregateHeader, " System Statistics", Styles.headerStyle);
m_SystemScroll = GUI.BeginScrollView(aggregateData, m_SystemScroll, new Rect(0, 0, aggregateData.width / 2, actualHeight));
GUI.Box(new Rect(0, 0, aggregateData.width, actualHeight), aggregatedText, Styles.statStyle);
GUI.EndScrollView();
//player build statistics
aggregateHeader.y += aggregateHeader.height + aggregateData.height + padding * 2;
aggregateData.y += aggregateHeader.height + aggregateData.height + padding * 2;
stringBuilder.Clear();
stringBuilder.AppendLine($" Missing Disk Data: {EditorUtility.FormatBytes(GetCounterValue(frameDataView, "Missing Disk Data"))}");
stringBuilder.AppendLine($" Missing Streaming Tiles: {GetCounterValue(frameDataView, "Missing Streaming Tiles")}");
stringBuilder.AppendLine($" Read From Disk: {EditorUtility.FormatBytes(GetCounterValue(frameDataView, "Read From Disk"))}");
aggregatedText = stringBuilder.ToString();
aggregateTextHeight = EditorStyles.wordWrappedLabel.CalcHeight(GUIContent.Temp(aggregatedText), rect.width);
actualHeight = Mathf.Max(aggregateBoxHeight, aggregateTextHeight);
DrawScrollBackground(new Rect(aggregateData.width - 12, aggregateData.y, 14, aggregateData.height));
GUI.Box(aggregateHeader, " Player Build Statistics", Styles.headerStyle);
m_PlayerScroll = GUI.BeginScrollView(aggregateData, m_PlayerScroll, new Rect(0, 0, aggregateData.width / 2, actualHeight));
GUI.Box(new Rect(0, 0, aggregateData.width, actualHeight), aggregatedText, Styles.statStyle);
GUI.EndScrollView();
//PER CACHE DATA
Rect perCacheHeader = rect;
perCacheHeader.width = rect.width - aggregateHeader.width - padding;
perCacheHeader.height = 34;
perCacheHeader.x += aggregateHeader.width + padding;
Rect formatBox = perCacheHeader;
formatBox.height = rect.height - perCacheHeader.height - padding;
formatBox.y += perCacheHeader.height + padding;
GUI.Box(perCacheHeader, " Per Cache Statistics", Styles.headerStyle);
if (m_Header == null || m_HeaderState == null)
Init();
//Keep using the last VT tick untill a new one is available.
if (requiredTiles > 0)
{
ReadFrameData(fRender);
}
if (m_SortingChanged)
SortFrameData();
DrawFormatData(formatBox);
if (fRender != frameDataView)
{
fRender.Dispose();
}
}
else
{
GUI.Label(aggregateData, "No frame data available");
}
}
EditorGUILayout.EndVertical();
infoBox.y = rect.y;
infoBox.x = rect.width - 33;
infoBox.width = 34;
infoBox.height = 34;
DrawDocLink(infoBox);
}
internal void DrawDocLink(Rect infoBox)
{
if (GUI.Button(infoBox, Styles.helpButtonContent, Styles.headerStyle))
{
Application.OpenURL(Styles.linkToDocs);
}
}
internal void ReadFrameData(RawFrameDataView fRender)
{
var frameData = fRender.GetFrameMetaData<int>(m_VTProfilerGuid, 0);
//This function only gets called when there are tiles on the screen so if we received no cache data this frame we use the old data
if (frameData.Length == 0)
{
return;
}
m_FrameData.Clear();
for (int i = 0; i < frameData.Length; i += 4)
{
FrameData data = new FrameData();
data.format = (GraphicsFormat)frameData[i];
data.demand = frameData[i + 1];
data.bias = frameData[i + 2] / 100.0f;
data.size = frameData[i + 3];
m_FrameData.Add(data);
}
SortFrameData();
}
internal void DrawScrollBackground(Rect rect)
{
GUI.Box(rect, "", Styles.evenStyle);
}
internal RawFrameDataView GetRenderThread(RawFrameDataView frameDataView)
{
//Find render thread
using (ProfilerFrameDataIterator frameDataIterator = new ProfilerFrameDataIterator())
{
var threadCount = frameDataIterator.GetThreadCount(frameDataView.frameIndex);
for (int i = 0; i < threadCount; ++i)
{
RawFrameDataView frameData = ProfilerDriver.GetRawFrameDataView(frameDataView.frameIndex, i);
if (frameData.threadName == "Render Thread")
{
return frameData;
}
else
{
frameData.Dispose();
}
}
// If there's no render thread, metadata was pushed on main thread
return frameDataView;
}
}
int SortFormats(FrameData a, FrameData b)
{
if (m_SortAscending)
return b.format.CompareTo(a.format);
else return a.format.CompareTo(b.format);
}
int SortDemand(FrameData a, FrameData b)
{
if (m_SortAscending)
return b.demand.CompareTo(a.demand);
else return a.demand.CompareTo(b.demand);
}
int SortBias(FrameData a, FrameData b)
{
if (m_SortAscending)
return b.bias.CompareTo(a.bias);
else return a.bias.CompareTo(b.bias);
}
int SortSize(FrameData a, FrameData b)
{
if (m_SortAscending)
return b.size.CompareTo(a.size);
else return a.size.CompareTo(b.size);
}
internal void SortFrameData()
{
int sortedColumn = m_Header.sortedColumnIndex;
if (sortedColumn == -1)
return;
m_SortAscending = m_Header.IsSortedAscending(sortedColumn);
switch (sortedColumn)
{
case 0:
m_FrameData.Sort(SortFormats);
break;
case 1:
m_FrameData.Sort(SortDemand);
break;
case 2:
m_FrameData.Sort(SortBias);
break;
case 3:
m_FrameData.Sort(SortSize);
break;
}
m_SortingChanged = false;
}
internal void DrawFormatData(Rect formatRect)
{
const int itemHeight = 34;
Rect headerBox = formatRect;
headerBox.height = itemHeight;
Rect listBox = formatRect;
listBox.y += headerBox.height + 1;
listBox.height -= headerBox.height;
m_Header.OnGUI(headerBox, 0);
DrawScrollBackground(new Rect(listBox.x + listBox.width - 12, listBox.y, 14, listBox.height));
m_ListScroll = GUI.BeginScrollView(listBox, m_ListScroll, new Rect(0, 0, listBox.width / 2.0f, Mathf.Max(itemHeight * m_FrameData.Count, listBox.height)), false, false);
Rect formatColumn = m_Header.GetColumnRect(0);
Rect demandColumn = m_Header.GetColumnRect(1);
Rect biasColumn = m_Header.GetColumnRect(2);
Rect sizeColumn = m_Header.GetColumnRect(3);
GUIStyle dataStyle;
for (int i = 0; i < m_FrameData.Count; ++i)
{
if (i % 2 == 0)
{
dataStyle = Styles.evenStyle;
}
else
{
dataStyle = Styles.oddStyle;
}
//add one extra pixel to fix rounding issue with monitor scaling
GUI.Box(new Rect(formatColumn.x, i * itemHeight, formatColumn.width + 1, itemHeight), " " + m_FrameData[i].format.ToString(), dataStyle);
GUI.Box(new Rect(demandColumn.x, i * itemHeight, demandColumn.width + 1, itemHeight), ' ' + m_FrameData[i].demand.ToString() + '%', dataStyle);
GUI.Box(new Rect(biasColumn.x, i * itemHeight, biasColumn.width + 1, itemHeight), ' ' + m_FrameData[i].bias.ToString(), dataStyle);
GUI.Box(new Rect(sizeColumn.x, i * itemHeight, sizeColumn.width + 1, itemHeight), ' ' + EditorUtility.FormatBytes(m_FrameData[i].size), dataStyle);
GUI.Box(new Rect(sizeColumn.x + sizeColumn.width, i * itemHeight, formatRect.width - sizeColumn.x - sizeColumn.width, itemHeight), "", dataStyle);
}
//add empty boxes to fill screen if needed;
int minElements = (int)listBox.height / itemHeight + 1;
for (int i = m_FrameData.Count; i < minElements; ++i)
{
if (i % 2 == 0)
{
dataStyle = Styles.evenStyle;
}
else
{
dataStyle = Styles.oddStyle;
}
//add one extra pixel to fix rounding issue with monitor scaling
GUI.Box(new Rect(formatColumn.x, i * itemHeight, formatColumn.width + 1, itemHeight), "", dataStyle);
GUI.Box(new Rect(demandColumn.x, i * itemHeight, demandColumn.width + 1, itemHeight), "", dataStyle);
GUI.Box(new Rect(biasColumn.x, i * itemHeight, biasColumn.width + 1, itemHeight), "", dataStyle);
GUI.Box(new Rect(sizeColumn.x, i * itemHeight, sizeColumn.width + 1, itemHeight), "", dataStyle);
GUI.Box(new Rect(sizeColumn.x + sizeColumn.width, i * itemHeight, formatRect.width - sizeColumn.x - sizeColumn.width, itemHeight), "", dataStyle);
}
GUI.EndScrollView();
Rect emptyFiller = formatRect;
emptyFiller.x = m_Header.GetColumnRect(3).x + m_Header.GetColumnRect(3).width + formatRect.x;
emptyFiller.width = formatRect.width;
emptyFiller.height = itemHeight;
GUI.Box(emptyFiller, "", Styles.headerStyle);
}
static long GetCounterValue(FrameDataView frameData, string name)
{
var id = frameData.GetMarkerId(name);
if (id == FrameDataView.invalidMarkerId)
return -1;
return frameData.GetCounterValueAsInt(id);
}
static float GetCounterValueAsFloat(FrameDataView frameData, string name)
{
var id = frameData.GetMarkerId(name);
if (id == FrameDataView.invalidMarkerId)
return -1;
return frameData.GetCounterValueAsFloat(id);
}
internal static class Styles
{
enum backgroundColor
{
header, even, odd, background, COLORCOUNT
}
static Color[] colors = new Color[(int)backgroundColor.COLORCOUNT];
static Texture2D[] backgrounds = new Texture2D[(int)backgroundColor.COLORCOUNT];
static Color textColor;
public static GUIStyle headerStyle;
public static GUIStyle statStyle;
public static GUIStyle backgroundStyle;
public static GUIStyle evenStyle;
public static GUIStyle oddStyle;
public static readonly GUIStyle scrollStyle = "ProfilerScrollviewBackground";
public const string linkToDocs = "https://docs.unity3d.com/2020.2/Documentation/Manual/profiler-virtual-texturing-module.html";
public static readonly GUIContent helpButtonContent = EditorGUIUtility.TrIconContent("_Help@2x", "Open Manual (in a web browser)");
static Styles()
{
//generate background colors
if (EditorGUIUtility.isProSkin)
{
colors[(int)backgroundColor.even] = new Color(0.176f, 0.176f, 0.176f);
colors[(int)backgroundColor.odd] = new Color(0.196f, 0.196f, 0.196f);
colors[(int)backgroundColor.header] = new Color(0.235f, 0.235f, 0.235f);
colors[(int)backgroundColor.background] = Color.black;
}
else
{
colors[(int)backgroundColor.even] = new Color(0.792f, 0.792f, 0.792f);
colors[(int)backgroundColor.odd] = new Color(0.761f, 0.761f, 0.761f);
colors[(int)backgroundColor.header] = new Color(0.796f, 0.796f, 0.796f);
colors[(int)backgroundColor.background] = new Color(0.6f, 0.6f, 0.6f);
}
for (int i = 0; i < (int)backgroundColor.COLORCOUNT; ++i)
{
backgrounds[i] = new Texture2D(1, 1);
backgrounds[i].SetPixel(0, 0, colors[i]);
backgrounds[i].Apply();
}
}
public static void CreateStyles()
{
if (EditorGUIUtility.isProSkin)
textColor = new Color(0xBA, 0xBA, 0xBA);
else textColor = new Color(0.055f, 0.055f, 0.055f);
GUIStyleState state = new GUIStyleState();
state.background = backgrounds[(int)backgroundColor.header];
state.textColor = textColor;
headerStyle = new GUIStyle();
headerStyle.normal = state;
headerStyle.active = state;
headerStyle.focused = state;
headerStyle.hover = state;
headerStyle.alignment = TextAnchor.MiddleLeft;
headerStyle.fontStyle = FontStyle.Normal;
state.background = backgrounds[(int)backgroundColor.odd];
statStyle = new GUIStyle();
statStyle.normal = state;
statStyle.active = state;
statStyle.focused = state;
statStyle.hover = state;
statStyle.alignment = TextAnchor.UpperLeft;
statStyle.padding.top = 5;
statStyle.fontStyle = FontStyle.Normal;
state.background = backgrounds[(int)backgroundColor.even];
evenStyle = new GUIStyle();
evenStyle.normal = state;
evenStyle.active = state;
evenStyle.focused = state;
evenStyle.hover = state;
evenStyle.fontStyle = FontStyle.Normal;
evenStyle.alignment = TextAnchor.MiddleLeft;
state.background = backgrounds[(int)backgroundColor.odd];
oddStyle = new GUIStyle();
oddStyle.normal = state;
oddStyle.active = state;
oddStyle.focused = state;
oddStyle.hover = state;
oddStyle.fontStyle = FontStyle.Normal;
oddStyle.alignment = TextAnchor.MiddleLeft;
state.background = backgrounds[(int)backgroundColor.background];
backgroundStyle = new GUIStyle();
backgroundStyle.normal = state;
backgroundStyle.active = state;
backgroundStyle.focused = state;
backgroundStyle.hover = state;
backgroundStyle.padding = new RectOffset(-2, -2, -2, -2);
}
public static Texture2D GetBackground()
{
return backgrounds[(int)backgroundColor.background];
}
//when exiting playmode the background textures get reset to null
public static void CheckBackgroundTextures()
{
bool shouldRecreateStyles = false;
for (int i = 0; i < (int)backgroundColor.COLORCOUNT; ++i)
{
if (backgrounds[i] == null)
{
backgrounds[i] = new Texture2D(1, 1);
backgrounds[i].SetPixel(0, 0, colors[i]);
backgrounds[i].Apply();
shouldRecreateStyles = true;
}
}
if (shouldRecreateStyles)
CreateStyles();
}
}
internal class VTMultiColumnHeader : MultiColumnHeader
{
public VTMultiColumnHeader(MultiColumnHeaderState state)
: base(state)
{
}
protected override void ColumnHeaderGUI(MultiColumnHeaderState.Column column, Rect headerRect, int columnIndex)
{
//add one extra pixel to fix rounding issue with monitor scaling
headerRect.width++;
GUI.Box(headerRect, column.headerContent, Styles.headerStyle);
if (canSort && column.canSort)
{
SortingButton(column, headerRect, columnIndex);
}
}
Rect GetArrowRect(MultiColumnHeaderState.Column column, Rect headerRect, int columnIndex)
{
int xOffset = 0;
switch (columnIndex)
{
case 0:
xOffset = 95;
break;
case 1:
xOffset = 57;
break;
default:
xOffset = 36;
break;
}
Rect arrowRect = new Rect(headerRect.x + xOffset - 8, headerRect.y + headerRect.height / 2.0f - 8, 16, 16);
return arrowRect;
}
new void SortingButton(MultiColumnHeaderState.Column column, Rect headerRect, int columnIndex)
{
// Button logic
if (EditorGUI.Button(headerRect, GUIContent.none, GUIStyle.none))
{
ColumnHeaderClicked(column, columnIndex);
}
// Draw sorting arrow
if (columnIndex == state.sortedColumnIndex && Event.current.type == EventType.Repaint)
{
var arrowRect = GetArrowRect(column, headerRect, columnIndex);
string arrow;
if (column.sortedAscending)
arrow = "\u25B4";
else arrow = "\u25BE";
GUIStyle style = Styles.headerStyle;
style.fontSize *= 2;
GUI.Label(arrowRect, arrow, DefaultStyles.arrowStyle);
}
}
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/VirtualTexturing/VirtualTexturingProfilerView.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/VirtualTexturing/VirtualTexturingProfilerView.cs",
"repo_id": "UnityCsReference",
"token_count": 12333
} | 433 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
using UnityEngine.UIElements;
namespace Unity.Profiling.Editor.UI
{
static class ViewControllerUtility
{
// Loads the specified Uxml asset and returns its root VisualElement, discarding the Template container. If the Uxml specifies multiple roots, the first will be returned.
public static VisualElement LoadVisualTreeFromUxmlAsset(string uxmlAssetGuid)
{
// Load Uxml template from disk.
var uxmlAssetPath = AssetDatabase.GUIDToAssetPath(uxmlAssetGuid);
var uxml = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxmlAssetPath);
return LoadViewFromUxml(uxml);
}
// Loads the specified built-in Uxml and returns its root VisualElement, discarding the Template container. If the Uxml specifies multiple roots, the first will be returned.
public static VisualElement LoadVisualTreeFromBuiltInUxml(string uxmlResourceName)
{
// Load Uxml template from disk.
var uxml = EditorGUIUtility.Load(uxmlResourceName) as VisualTreeAsset;
return LoadViewFromUxml(uxml);
}
static VisualElement LoadViewFromUxml(VisualTreeAsset uxml)
{
var template = uxml.Instantiate();
// Retrieve first child from template container.
VisualElement view = null;
using (var enumerator = template.Children().GetEnumerator())
{
if (enumerator.MoveNext())
view = enumerator.Current;
}
return view;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/ViewControllerUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/ViewControllerUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 677
} | 434 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace Unity.Properties
{
public static partial class PropertyContainer
{
class ValueAtPathVisitor : PathVisitor
{
public static readonly UnityEngine.Pool.ObjectPool<ValueAtPathVisitor> Pool = new UnityEngine.Pool.ObjectPool<ValueAtPathVisitor>(() => new ValueAtPathVisitor(), null, v => v.Reset());
public IPropertyVisitor Visitor;
public override void Reset()
{
base.Reset();
Visitor = default;
ReadonlyVisit = true;
}
protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property,
ref TContainer container, ref TValue value)
{
((IPropertyAccept<TContainer>) property).Accept(Visitor, ref container);
}
}
class ExistsAtPathVisitor : PathVisitor
{
public static readonly UnityEngine.Pool.ObjectPool<ExistsAtPathVisitor> Pool = new UnityEngine.Pool.ObjectPool<ExistsAtPathVisitor>(() => new ExistsAtPathVisitor(), null, v => v.Reset());
public bool Exists;
public override void Reset()
{
base.Reset();
Exists = default;
ReadonlyVisit = true;
}
protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
{
Exists = true;
}
}
/// <summary>
/// Returns <see langword="true"/> if a property exists at the specified <see cref="PropertyPath"/>.
/// </summary>
/// <param name="container">The container tree to search.</param>
/// <param name="path">The property path to resolve.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <returns><see langword="true"/> if a property can be found at path.</returns>
public static bool IsPathValid<TContainer>(TContainer container, string path)
=> IsPathValid(ref container, new PropertyPath(path));
/// <summary>
/// Returns <see langword="true"/> if a property exists at the specified <see cref="PropertyPath"/>.
/// </summary>
/// <param name="container">The container tree to search.</param>
/// <param name="path">The property path to resolve.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <returns><see langword="true"/> if a property can be found at path.</returns>
public static bool IsPathValid<TContainer>(TContainer container, in PropertyPath path)
=> IsPathValid(ref container, path);
/// <summary>
/// Returns <see langword="true"/> if a property exists at the specified <see cref="PropertyPath"/>.
/// </summary>
/// <param name="container">The container tree to search.</param>
/// <param name="path">The property path to resolve.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <returns><see langword="true"/> if a property can be found at path.</returns>
public static bool IsPathValid<TContainer>(ref TContainer container, string path)
{
var visitor = ExistsAtPathVisitor.Pool.Get();
try
{
visitor.Path = new PropertyPath(path);
TryAccept(visitor, ref container);
return visitor.Exists;
}
finally
{
ExistsAtPathVisitor.Pool.Release(visitor);
}
}
/// <summary>
/// Returns <see langword="true"/> if a property exists at the specified <see cref="PropertyPath"/>.
/// </summary>
/// <param name="container">The container tree to search.</param>
/// <param name="path">The property path to resolve.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <returns><see langword="true"/> if a property can be found at path.</returns>
public static bool IsPathValid<TContainer>(ref TContainer container, in PropertyPath path)
{
var visitor = ExistsAtPathVisitor.Pool.Get();
try
{
visitor.Path = path;
TryAccept(visitor, ref container);
return visitor.Exists;
}
finally
{
ExistsAtPathVisitor.Pool.Release(visitor);
}
}
}
}
| UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+Path.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+Path.cs",
"repo_id": "UnityCsReference",
"token_count": 1983
} | 435 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
namespace Unity.Properties
{
/// <summary>
/// An <see cref="IPropertyBag{T}"/> implementation for a <see cref="Dictionary{TKey, TValue}"/> type.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
public class DictionaryPropertyBag<TKey, TValue> : KeyValueCollectionPropertyBag<Dictionary<TKey, TValue>, TKey, TValue>
{
/// <inheritdoc/>
protected override InstantiationKind InstantiationKind => InstantiationKind.PropertyBagOverride;
/// <inheritdoc/>
protected override Dictionary<TKey, TValue> Instantiate() => new Dictionary<TKey, TValue>();
}
}
| UnityCsReference/Modules/Properties/Runtime/PropertyBags/DictionaryPropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/DictionaryPropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 306
} | 436 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace Unity.Properties
{
/// <summary>
/// Implement this interface to intercept the visitation of any primitive type.
/// </summary>
public interface IVisitPrimitivesPropertyAdapter :
IVisitPropertyAdapter<sbyte>,
IVisitPropertyAdapter<short>,
IVisitPropertyAdapter<int>,
IVisitPropertyAdapter<long>,
IVisitPropertyAdapter<byte>,
IVisitPropertyAdapter<ushort>,
IVisitPropertyAdapter<uint>,
IVisitPropertyAdapter<ulong>,
IVisitPropertyAdapter<float>,
IVisitPropertyAdapter<double>,
IVisitPropertyAdapter<bool>,
IVisitPropertyAdapter<char>
{
}
}
| UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IVisitPrimitivesPropertyAdapter.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IVisitPrimitivesPropertyAdapter.cs",
"repo_id": "UnityCsReference",
"token_count": 308
} | 437 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Jobs;
using UnityEngine.Scripting;
namespace Unity.Properties.Internal
{
static class PropertiesEditorInitialization
{
private static bool s_Initialized;
static JobHandle s_InitializeJobHandle;
public static JobHandle GetInitializationJobHandle()
{
InitializePropertiesEditor();
return s_InitializeJobHandle;
}
[RequiredByNativeCode(optional:false)]
public static void InitializePropertiesEditor()
{
if (s_Initialized)
return;
s_InitializeJobHandle = new InitializePropertiesJob().Schedule();
JobHandle.ScheduleBatchedJobs();
s_Initialized = true;
}
struct InitializePropertiesJob : IJob
{
public void Execute()
{
Internal.PropertiesInitialization.InitializeProperties();
}
}
}
}
| UnityCsReference/Modules/PropertiesEditor/Module/PropertiesEditorInitialization.cs/0 | {
"file_path": "UnityCsReference/Modules/PropertiesEditor/Module/PropertiesEditorInitialization.cs",
"repo_id": "UnityCsReference",
"token_count": 465
} | 438 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
//#define DEBUG_PROGRESS
using System;
using System.Threading;
using UnityEngine;
namespace UnityEditor.Search
{
interface ITaskReporter
{
void Report(string status, params string[] args);
}
class SearchTask<T> : IDisposable
where T : class
{
public delegate void ResolveHandler(SearchTask<T> task, T data);
private const int k_NoProgress = -1;
private const int k_BlockingProgress = -2;
public readonly string name;
public readonly string title;
private int progressId = k_NoProgress;
private volatile float lastProgress = -1f;
private EventWaitHandle cancelEvent;
private readonly ResolveHandler resolver;
private readonly System.Diagnostics.Stopwatch sw;
private string status = null;
private volatile bool disposed = false;
private readonly ITaskReporter reporter;
public int total { get; set; }
public bool canceled { get; private set; }
public Exception error { get; private set; }
public bool async => resolver != null;
public long elapsedTime => sw.ElapsedMilliseconds;
private SearchTask(string name, string title, ITaskReporter reporter)
{
this.name = name;
this.title = title;
this.reporter = reporter;
sw = new System.Diagnostics.Stopwatch();
sw.Start();
}
/// <summary>
/// Create blocking task
/// </summary>
public SearchTask(string name, string title, int total, ITaskReporter reporter)
: this(name, title, reporter)
{
this.total = total;
progressId = StartBlockingReport(title);
}
/// <summary>
/// Create async or threaded task
/// </summary>
public SearchTask(string name, string title, ResolveHandler resolver, int total, ITaskReporter reporter)
: this(name, title, reporter)
{
this.total = total;
this.resolver = resolver;
progressId = StartReport(title);
cancelEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
if (IsProgressRunning(progressId))
{
LogProgress("RegisterCallback");
Progress.RegisterCancelCallback(progressId, () => cancelEvent != null && cancelEvent.Set());
}
}
public SearchTask(string name, string title, ResolveHandler resolver, ITaskReporter reporter)
: this(name, title, resolver, 1, reporter)
{
}
[System.Diagnostics.Conditional("DEBUG_PROGRESS")]
private void LogProgress(in string name, params object[] args)
{
Debug.Log($"{name} {progressId}, {string.Join(", ", args)}, main ={UnityEditorInternal.InternalEditorUtility.CurrentThreadIsMainThread()}");
}
protected virtual void Dispose(bool disposing)
{
LogProgress("Dispose", disposed, disposing);
if (disposed)
return;
cancelEvent?.Dispose();
cancelEvent = null;
if (disposing)
Resolve();
LogProgress("Exists");
if (Progress.Exists(progressId))
{
LogProgress("Remove");
Progress.Remove(progressId);
}
progressId = k_NoProgress;
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~SearchTask() => Dispose(false);
public bool RunThread(Action routine, Action finalize = null)
{
var t = new Thread(() =>
{
try
{
routine();
if (finalize != null)
Dispatcher.Enqueue(finalize);
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
}
catch (Exception ex)
{
Dispatcher.Enqueue(() => Resolve(ex));
}
})
{
Name = name
};
t.Start();
return t.ThreadState == ThreadState.Running;
}
public void Report(string status)
{
Report(status, lastProgress);
}
public void Report(string status, float progress)
{
if (!IsValid())
return;
this.status = status;
if (progressId == k_BlockingProgress)
{
// TODO: should this report the actual progress instead of -1?
EditorUtility.DisplayProgressBar(title, status, -1f);
return;
}
LogProgress("Report");
Progress.Report(progressId, progress, status);
}
public void Report(int current)
{
if (total == 0)
return;
Report(current, total);
}
public void Report(int current, int total)
{
if (!IsValid())
return;
if (progressId == k_BlockingProgress)
{
if (cancelEvent == null)
EditorUtility.DisplayProgressBar(title, status, current / (float)total);
else
{
if (EditorUtility.DisplayCancelableProgressBar(title, status, current / (float)total))
cancelEvent.Set();
}
}
else
{
lastProgress = current / (float)total;
LogProgress("Report");
Progress.Report(progressId, current, total, status);
}
}
public void Cancel()
{
cancelEvent?.Set();
}
public bool Canceled()
{
if (!IsValid())
return true;
if (cancelEvent == null)
return false;
if (!cancelEvent.WaitOne(0))
return false;
canceled = true;
ClearReport();
if (resolver != null)
Dispatcher.Enqueue(() => resolver.Invoke(this, null));
return true;
}
public void Resolve(T data, bool completed = true)
{
if (!IsValid())
return;
if (Canceled())
return;
resolver?.Invoke(this, data);
if (completed)
Dispose();
}
private void Resolve()
{
FinishReport();
}
public void Resolve(Exception err)
{
Console.WriteLine($"Search task exception: {err}");
if (!IsValid())
return;
error = err;
canceled = true;
if (err != null)
{
ReportError(err);
if (resolver == null)
Debug.LogException(err);
}
resolver?.Invoke(this, null);
}
private int StartBlockingReport(string title)
{
status = title;
EditorUtility.DisplayProgressBar(title, null, 0f);
return k_BlockingProgress;
}
private int StartReport(string title)
{
var progressId = Progress.Start(title);
LogProgress("Start");
Progress.SetPriority(progressId, (int)Progress.Priority.Low);
status = title;
return progressId;
}
private void ReportError(Exception err)
{
if (!IsValid())
return;
if (progressId == k_BlockingProgress)
{
Debug.LogException(err);
EditorUtility.ClearProgressBar();
}
else if (IsProgressRunning(progressId))
{
LogProgress("SetDescription", "ReportError");
Progress.SetDescription(progressId, err.Message);
LogProgress("Finish", "ReportError");
Progress.Finish(progressId, Progress.Status.Failed);
}
progressId = k_NoProgress;
status = null;
}
private bool IsValid()
{
if (disposed)
return false;
if (progressId == k_NoProgress)
return false;
return true;
}
private void FinishReport()
{
error = null;
status = null;
canceled = false;
if (!IsValid())
return;
LogProgress("FinishReport", reporter);
reporter?.Report(name, $"took {elapsedTime} ms");
if (progressId == k_BlockingProgress)
EditorUtility.ClearProgressBar();
else if (IsProgressRunning(progressId))
{
LogProgress("Finish");
Progress.Finish(progressId, Progress.Status.Succeeded);
}
progressId = k_NoProgress;
}
private void ClearReport()
{
status = null;
if (!IsValid())
return;
if (progressId == k_BlockingProgress)
EditorUtility.ClearProgressBar();
else if (IsProgressRunning(progressId))
{
Progress.Remove(progressId);
LogProgress("Remove");
}
progressId = k_NoProgress;
}
private bool IsProgressRunning(int progressId)
{
if (progressId == k_NoProgress)
return false;
LogProgress("Exists");
if (!Progress.Exists(progressId))
return false;
var status = Progress.GetStatus(progressId);
LogProgress("GetStatus", status);
return status == Progress.Status.Running;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchTask.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchTask.cs",
"repo_id": "UnityCsReference",
"token_count": 5214
} | 439 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEditor.PackageManager;
using UnityEngine;
namespace UnityEditor.Search.Providers
{
static class PackageManagerProvider
{
internal static string type = "packages";
internal static string displayName = "Packages";
private static PackageManager.Requests.ListRequest s_ListRequest = null;
private static PackageManager.Requests.SearchRequest s_SearchRequest = null;
[SearchItemProvider]
internal static SearchProvider CreateProvider()
{
return new SearchProvider(type, displayName)
{
priority = 90,
filterId = "pkg:",
isExplicitProvider = true,
onEnable = () =>
{
},
onDisable = () =>
{
s_ListRequest = null;
s_SearchRequest = null;
},
fetchItems = (context, items, provider) => SearchPackages(context, provider),
fetchThumbnail = (item, context) => (item.thumbnail = item.score == 0 ? Icons.packageUpdate : Icons.packageInstalled)
};
}
private static IEnumerable<SearchItem> SearchPackages(SearchContext context, SearchProvider provider)
{
if (string.IsNullOrEmpty(context.searchQuery))
yield break;
s_ListRequest = s_ListRequest ?? PackageManager.Client.List(true);
s_SearchRequest = s_SearchRequest ?? PackageManager.Client.SearchAll(Utils.runningTests);
if (s_SearchRequest == null || s_ListRequest == null)
yield break;
while (!s_SearchRequest.IsCompleted || !s_ListRequest.IsCompleted)
{
if (s_SearchRequest.Status == StatusCode.Failure)
yield break;
if (s_ListRequest.Status == StatusCode.Failure)
yield break;
yield return null;
}
if (s_SearchRequest.Status == StatusCode.Failure || s_ListRequest.Status == StatusCode.Failure)
yield break;
if (s_SearchRequest.Result == null || s_ListRequest.Result == null)
yield break;
foreach (var p in s_SearchRequest.Result)
{
if (p.keywords.Contains(context.searchQuery) ||
SearchUtils.MatchSearchGroups(context, p.description.ToLowerInvariant(), true) ||
SearchUtils.MatchSearchGroups(context, p.name.ToLowerInvariant(), true))
yield return provider.CreateItem(context, p.packageId, String.IsNullOrEmpty(p.resolvedPath) ? 0 : 1, FormatLabel(p), FormatDescription(p), null, p);
}
}
private static string FormatName(PackageManager.PackageInfo pi)
{
if (String.IsNullOrEmpty(pi.displayName))
return $"{pi.name}@{pi.version}";
return $"{pi.displayName} ({pi.name}@{pi.version})";
}
private static string FormatLabel(PackageManager.PackageInfo pi)
{
var installedPackage = s_ListRequest.Result.FirstOrDefault(l => l.name == pi.name);
var status = installedPackage != null ? (installedPackage.version == pi.version ?
" - <i>In Project</i>" : " - <b>Update Available</b>") : "";
if (String.IsNullOrEmpty(pi.displayName))
return $"{pi.name}@{pi.version}{status}";
return $"{FormatName(pi)}{status}";
}
private static bool IsPackageInstalled(PackageManager.PackageInfo pi, out string version)
{
version = null;
var installedPackage = s_ListRequest.Result.FirstOrDefault(l => l.name == pi.name);
if (installedPackage == null)
return false;
version = installedPackage.version;
return true;
}
private static bool IsPackageInstalled(PackageManager.PackageInfo pi)
{
return IsPackageInstalled(pi, out _);
}
private static string FormatDescription(PackageManager.PackageInfo pi)
{
return pi.description.Replace("\r", "").Replace("\n", "");
}
private static bool WaitForRequestBase(PackageManager.Requests.Request request, string msg, int loopDelay)
{
var progress = 0.0f;
while (!request.IsCompleted)
{
Thread.Sleep(loopDelay);
EditorUtility.DisplayProgressBar("Unity Package Manager", msg, Mathf.Min(1.0f, progress++ / 100f));
}
EditorUtility.ClearProgressBar();
return request.Status == PackageManager.StatusCode.Success;
}
private static bool WaitForRequest<T>(PackageManager.Requests.Request<T> request, string msg, int loopDelay = 20)
{
return WaitForRequestBase(request, msg, loopDelay) && request.Result != null;
}
[SearchActionsProvider]
internal static IEnumerable<SearchAction> ActionHandlers()
{
return new[]
{
new SearchAction(type, "open", null, "Open in Package Manager", OpenPackageInPackageManager),
new SearchAction(type, "install", null, "Install", InstallPackage, IsCanBeInstalled),
new SearchAction(type, "update", null, "Update", InstallPackage, IsCanBeUpdated),
new SearchAction(type, "remove", null, "Remove", RemovePackage, IsRemoveActionEnabled)
};
}
private static bool IsCanBeUpdated(IReadOnlyCollection<SearchItem> items)
{
foreach (var item in items)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
if (!IsPackageInstalled(packageInfo, out var installedVersion) || installedVersion == packageInfo.version)
return false;
}
return true;
}
private static bool IsCanBeInstalled(IReadOnlyCollection<SearchItem> items)
{
foreach (var item in items)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
if (IsPackageInstalled(packageInfo))
return false;
}
return true;
}
private static void OpenPackageInPackageManager(SearchItem item)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
PackageManager.UI.Window.Open(packageInfo.name);
}
private static void InstallPackage(SearchItem item)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
if (EditorUtility.DisplayDialog("About to install package " + item.id,
"Are you sure you want to install the following package?\r\n\r\n" +
FormatName(packageInfo), "Install...", "Cancel"))
{
WaitForRequest(PackageManager.Client.Add(item.id), $"Installing {item.id}...", 25);
}
}
private static void RemovePackage(SearchItem item)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
WaitForRequestBase(PackageManager.Client.Remove(packageInfo.name), $"Removing {packageInfo.packageId}...", 1);
}
private static bool IsRemoveActionEnabled(IReadOnlyCollection<SearchItem> items)
{
foreach (var item in items)
{
var packageInfo = (PackageManager.PackageInfo)item.data;
if (!IsPackageInstalled(packageInfo))
return false;
}
return true;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Providers/PackageManagerProvider.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/PackageManagerProvider.cs",
"repo_id": "UnityCsReference",
"token_count": 3582
} | 440 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class QueryAndOrBlock : QueryWordBlock
{
public QueryAndOrBlock(IQuerySource source, string combine)
: base(source, combine)
{
}
internal override Color GetBackgroundColor()
{
return QueryColors.combine;
}
internal override IBlockEditor OpenEditor(in Rect rect)
{
return QuerySelector.Open(rect, this);
}
internal override IEnumerable<SearchProposition> FetchPropositions()
{
return BuiltInQueryBuilderPropositions(null);
}
public override void Apply(in SearchProposition searchProposition)
{
value = searchProposition.replacement;
ApplyChanges();
}
public static IEnumerable<SearchProposition> BuiltInQueryBuilderPropositions(string category = "Operators")
{
foreach(var p in QueryEnginePropositionsExtension.GetCombiningOperatorPropositions(QueryEnginePropositionsExtension.CombiningOperatorPropositions.Default))
{
yield return p;
}
}
}
class QueryWordBlock : QueryBlock
{
public QueryWordBlock(IQuerySource source, SearchNode node)
: this(source, node.searchValue)
{
if (node.rawSearchValueStringView.HasQuotes())
explicitQuotes = true;
}
public QueryWordBlock(IQuerySource source, string searchValue)
: base(source)
{
name = string.Empty;
value = searchValue;
}
internal override void CreateBlockElement(VisualElement container)
{
var label = AddLabel(container, value);
if (!@readonly)
{
label.AddToClassList(QueryBlock.arrowButtonClassName);
label.RegisterCallback<ClickEvent>(OnOpenBlockEditor);
}
}
internal override IBlockEditor OpenEditor(in Rect rect)
{
if (@readonly)
return null;
var screenRect = new Rect(rect.position + context.searchView.position.position, rect.size);
return QueryTextBlockEditor.Open(screenRect, this);
}
internal override Color GetBackgroundColor()
{
return QueryColors.word;
}
public override string ToString()
{
return EscapeLiteralString(value);
}
}
class QueryToggleBlock : QueryWordBlock
{
public QueryToggleBlock(IQuerySource source, string toggle)
: base(source, toggle)
{
disabled = false;
}
internal override bool canExclude => false;
internal override bool canOpenEditorOnValueClicked => false;
internal override IBlockEditor OpenEditor(in Rect rect)
{
disabled = !disabled;
ApplyChanges();
return null;
}
public override string ToString()
{
if (disabled)
return null;
return base.ToString();
}
internal override Color GetBackgroundColor() => QueryColors.toggle;
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryWordBlock.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryWordBlock.cs",
"repo_id": "UnityCsReference",
"token_count": 1518
} | 441 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEditor.Search
{
interface INestedQueryHandlerTransformer
{
Type enumerableType { get; }
Type rightHandSideType { get; }
}
class NestedQueryHandlerTransformer<TQueryData, TRhs> : INestedQueryHandlerTransformer
{
public Func<TQueryData, TRhs> handler { get; }
public Type enumerableType => typeof(TQueryData);
public Type rightHandSideType => typeof(TRhs);
public NestedQueryHandlerTransformer(Func<TQueryData, TRhs> handler)
{
this.handler = handler;
}
}
interface INestedQueryHandler
{
Type enumerableType { get; }
}
class NestedQueryHandler<TQueryData> : INestedQueryHandler
{
public Func<string, string, IEnumerable<TQueryData>> handler { get; }
public Type enumerableType => typeof(TQueryData);
public NestedQueryHandler(Func<string, string, IEnumerable<TQueryData>> handler)
{
this.handler = handler;
}
}
interface INestedQueryAggregator
{
Type enumerableType { get; }
}
class NestedQueryAggregator<TQueryData> : INestedQueryAggregator
{
public Type enumerableType => typeof(TQueryData);
public Func<IEnumerable<TQueryData>, IEnumerable<TQueryData>> aggregator { get; }
public NestedQueryAggregator(Func<IEnumerable<TQueryData>, IEnumerable<TQueryData>> aggregator)
{
this.aggregator = aggregator;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/NestedQueryHandler.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/NestedQueryHandler.cs",
"repo_id": "UnityCsReference",
"token_count": 673
} | 442 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor.Search
{
class UnionEnumerable<T> : IQueryEnumerable<T>
{
IEnumerable<T> m_First;
IEnumerable<T> m_Second;
public bool fastYielding { get; }
public UnionEnumerable(IEnumerable<T> first, IEnumerable<T> second, bool fastYielding)
{
m_First = first;
m_Second = second;
this.fastYielding = fastYielding;
}
public void SetPayload(IEnumerable<T> payload)
{}
public IEnumerator<T> GetEnumerator()
{
if (fastYielding)
return FastYieldingEnumerator();
return m_First.Union(m_Second).GetEnumerator();
}
public IEnumerator<T> FastYieldingEnumerator()
{
var distinctFirstElements = new HashSet<T>();
var distinctSecondElements = new HashSet<T>();
foreach (var firstElement in m_First)
{
if (distinctFirstElements.Contains(firstElement))
yield return default;
else
{
distinctFirstElements.Add(firstElement);
yield return firstElement;
}
}
foreach (var secondElement in m_Second)
{
if (distinctFirstElements.Contains(secondElement))
{
yield return default;
continue;
}
if (distinctSecondElements.Contains(secondElement))
{
yield return default;
continue;
}
distinctSecondElements.Add(secondElement);
yield return secondElement;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
[EnumerableCreator(QueryNodeType.Union)]
class UnionEnumerableFactory : IQueryEnumerableFactory
{
public IQueryEnumerable<T> Create<T>(IQueryNode root, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding)
{
if (root.leaf || root.children == null || root.children.Count != 2)
{
errors.Add(new QueryError(root.token.position, root.token.length, "Union node must have two children."));
return null;
}
var firstEnumerable = EnumerableCreator.Create(root.children[0], engine, errors, fastYielding);
var secondEnumerable = EnumerableCreator.Create(root.children[1], engine, errors, fastYielding);
if (firstEnumerable == null || secondEnumerable == null)
{
errors.Add(new QueryError(root.token.position, root.token.length, "Could not create enumerables from Union node's children."));
}
return new UnionEnumerable<T>(firstEnumerable, secondEnumerable, fastYielding);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/UnionEnumerable.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/UnionEnumerable.cs",
"repo_id": "UnityCsReference",
"token_count": 1524
} | 443 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
namespace UnityEditor.Search
{
static partial class Evaluators
{
// except{set, ...sets}
[Description("Produces the set difference of two sequences."), Category("Set Manipulation")]
[SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Iterable | SearchExpressionType.Variadic)]
public static IEnumerable<SearchItem> Except(SearchExpressionContext c)
{
if (c.args.Length < 2)
c.ThrowError("Invalid arguments");
var setExpr = c.args[0];
if (!setExpr.types.IsIterable())
c.ThrowError("Primary set is not iterable", setExpr.outerText);
var exceptSet = new HashSet<SearchItem>();
foreach (var r in setExpr.Execute(c))
{
if (r == null || !exceptSet.Add(r))
yield return null;
}
// Remove from primary set all items from subsequent sets.
foreach (var e in c.args.Skip(1))
{
if (e != null)
{
foreach (var r in e.Execute(c))
{
if (r != null)
exceptSet.Remove(r);
yield return null;
}
}
else
yield return null;
}
// Return excepted set.
foreach (var r in exceptSet)
yield return r;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/ExceptEvaluator.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/ExceptEvaluator.cs",
"repo_id": "UnityCsReference",
"token_count": 890
} | 444 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
namespace UnityEditor.Search
{
static partial class Parsers
{
static readonly SearchExpressionEvaluator QueryEvaluator = EvaluatorManager.GetConstantEvaluatorByName("query");
[SearchExpressionParser("query", BuiltinParserPriority.Query)]
internal static SearchExpression QueryParser(SearchExpressionParserArgs args)
{
var text = ParserUtils.SimplifyExpression(args.text);
var nestedExpressions = new List<SearchExpression>();
var expressionsStartAndLength = ParserUtils.GetExpressionsStartAndLength(text, out _, out var rootHasEscapedOpenersAndClosers);
var lastExpressionEndIndex = 0;
foreach (var expression in expressionsStartAndLength)
{
string exprName = string.Empty;
if (expression[0] == '{')
{
var namedText = text.Substring(lastExpressionEndIndex, expression.startIndex - text.startIndex + 1 - lastExpressionEndIndex).ToString();
var match = ParserUtils.namedExpressionStartRegex.Match(namedText);
if (match != null && match.Success && match.Groups["name"].Value != string.Empty)
exprName = match.Groups["name"].Value;
}
var paramText = args.With(text.Substring(expression.startIndex - text.startIndex - exprName.Length, expression.length + exprName.Length));
var nestedExpression = ParserManager.Parse(paramText);
nestedExpressions.Add(nestedExpression);
lastExpressionEndIndex = expression.startIndex + expression.length - text.startIndex;
}
return new SearchExpression(SearchExpressionType.QueryString, args.text, text, QueryEvaluator, nestedExpressions.ToArray(), rootHasEscapedOpenersAndClosers);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/QueryExpressionParser.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/QueryExpressionParser.cs",
"repo_id": "UnityCsReference",
"token_count": 828
} | 445 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor.Search
{
interface ISearchListComparer : IComparer<SearchItem>
{
}
/// <summary>
/// A search list represents a collection of search results that is filled
/// </summary>
public interface ISearchList : IList<SearchItem>, IDisposable
{
/// <summary>
/// Indicates if the search request is still running and might return more results asynchronously.
/// </summary>
bool pending { get; }
/// <summary>
/// Any valid search context that is used to track async search request. It can be null.
/// </summary>
SearchContext context { get; }
/// <summary>
/// Yields search item until the search query is finished.
/// Nullified items can be returned while the search request is pending.
/// </summary>
/// <returns>List of search items. Items can be null and must be discarded</returns>
IEnumerable<SearchItem> Fetch();
/// <summary>
/// Add new items to the search list.
/// </summary>
/// <param name="items">List of items to be added</param>
void AddItems(IEnumerable<SearchItem> items);
/// <summary>
/// Insert new search items in the current list.
/// </summary>
/// <param name="index">Index where the items should be inserted.</param>
/// <param name="items">Items to be inserted.</param>
void InsertRange(int index, IEnumerable<SearchItem> items);
/// <summary>
/// Return a subset of items.
/// </summary>
/// <param name="skipCount"></param>
/// <param name="count"></param>
/// <returns></returns>
IEnumerable<SearchItem> GetRange(int skipCount, int count);
/// <summary>
///
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="selector"></param>
/// <returns></returns>
IEnumerable<TResult> Select<TResult>(Func<SearchItem, TResult> selector);
internal void SortBy(ISearchListComparer comparer);
}
abstract class BaseSearchList : ISearchList, IList
{
private bool m_Disposed = false;
public SearchContext context { get; private set; }
public bool pending
{
get
{
if (context == null)
return false;
return context.searchInProgress;
}
}
public abstract int Count { get; }
public virtual bool IsReadOnly => true;
bool IList.IsFixedSize => false;
bool ICollection.IsSynchronized => true;
object ICollection.SyncRoot => context;
object IList.this[int index]
{
get => this[index];
set
{
if (value is SearchItem item)
this[index] = item;
}
}
public abstract SearchItem this[int index] { get; set; }
public BaseSearchList()
{
context = null;
}
public BaseSearchList(SearchContext searchContext, bool trackAsyncItems = true)
{
context = searchContext;
if (trackAsyncItems)
context.asyncItemReceived += OnAsyncItemsReceived;
}
~BaseSearchList()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public abstract IEnumerable<SearchItem> Fetch();
public abstract void AddItems(IEnumerable<SearchItem> items);
protected virtual void Dispose(bool disposing)
{
if (!m_Disposed)
{
if (context != null)
context.asyncItemReceived -= OnAsyncItemsReceived;
m_Disposed = true;
}
}
private void OnAsyncItemsReceived(SearchContext context, IEnumerable<SearchItem> items)
{
AddItems(items);
}
public IEnumerable<TResult> Select<TResult>(Func<SearchItem, TResult> selector)
{
return Fetch().Where(item =>
{
context.Tick();
return item != null;
}).Select(item => selector(item));
}
public virtual void InsertRange(int index, IEnumerable<SearchItem> items) { throw new NotSupportedException(); }
public virtual IEnumerable<SearchItem> GetRange(int skipCount, int count) { throw new NotSupportedException(); }
public virtual int IndexOf(SearchItem item) { throw new NotSupportedException(); }
public virtual void Insert(int index, SearchItem item) { throw new NotSupportedException(); }
public virtual void RemoveAt(int index) { throw new NotSupportedException(); }
public virtual void Add(SearchItem item) { throw new NotSupportedException(); }
public virtual void Clear() { throw new NotSupportedException(); }
public virtual bool Contains(SearchItem item) { throw new NotSupportedException(); }
public virtual void CopyTo(SearchItem[] array, int arrayIndex) { throw new NotSupportedException(); }
public virtual bool Remove(SearchItem item) { throw new NotSupportedException(); }
public abstract IEnumerator<SearchItem> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
int IList.Add(object value)
{
Add(value as SearchItem ?? throw new ArgumentNullException(nameof(value)));
return Count-1;
}
bool IList.Contains(object value)
{
return Contains(value as SearchItem ?? throw new ArgumentNullException(nameof(value)));
}
int IList.IndexOf(object value)
{
return IndexOf(value as SearchItem ?? throw new ArgumentNullException(nameof(value)));
}
void IList.Insert(int index, object value)
{
Insert(index, value as SearchItem ?? throw new ArgumentNullException(nameof(value)));
}
void IList.Remove(object value)
{
Remove(value as SearchItem ?? throw new ArgumentNullException(nameof(value)));
}
void ICollection.CopyTo(Array array, int index)
{
CopyTo(array as SearchItem[] ?? throw new ArgumentNullException(nameof(array)), index);
}
void ISearchList.SortBy(ISearchListComparer comparer)
{
SortBy(comparer);
}
public virtual void SortBy(ISearchListComparer comparer)
{
throw new NotSupportedException();
}
}
class SortedSearchList : BaseSearchList
{
private List<SearchItem> m_IncomingBatch;
private HashSet<int> m_IdHashes = new HashSet<int>();
private List<SearchItem> m_Items = new List<SearchItem>();
private ISearchListComparer m_Comparer = new SortByScoreComparer();
public override int Count => m_Items.Count;
public override SearchItem this[int index]
{
get => m_Items[index];
set => throw new NotSupportedException();
}
public SortedSearchList(SearchContext searchContext) : base(searchContext)
{
Clear();
}
public void FromEnumerable(IEnumerable<SearchItem> items)
{
Clear();
AddItems(items);
}
public SearchItem ElementAt(int index) => m_Items[index];
public override int IndexOf(SearchItem item) => m_Items.IndexOf(item);
public override IEnumerable<SearchItem> Fetch()
{
if (context == null)
throw new Exception("Fetch can only be used if the search list was created with a search context.");
bool trackIncomingItems = false;
if (context.searchInProgress)
{
trackIncomingItems = true;
m_IncomingBatch = new List<SearchItem>();
}
// m_Items could be modified while yielding, copy the data
// since items can be inserted anywhere in the list.
var itemsCopy = m_Items.ToArray();
foreach (var item in itemsCopy)
yield return item;
int i = 0;
var nextCount = 0;
while (context.searchInProgress)
{
if (context.Tick())
yield return null;
if (trackIncomingItems && nextCount < m_IncomingBatch.Count)
{
// m_IncomingBatch could be modified while yielding items. Do not use foreach.
nextCount = m_IncomingBatch.Count;
for (; i < nextCount; ++i)
yield return m_IncomingBatch[i];
}
}
if (trackIncomingItems)
{
for (; i < m_IncomingBatch.Count; ++i)
yield return m_IncomingBatch[i];
m_IncomingBatch = null;
}
}
public override void AddItems(IEnumerable<SearchItem> items)
{
foreach (var item in items)
Add(item);
}
public override void Clear()
{
m_Items.Clear();
m_IdHashes.Clear();
m_IncomingBatch?.Clear();
}
public override IEnumerator<SearchItem> GetEnumerator()
{
return Fetch().GetEnumerator();
}
public override IEnumerable<SearchItem> GetRange(int skipCount, int count)
{
return m_Items.GetRange(skipCount, count);
}
public override void InsertRange(int index, IEnumerable<SearchItem> items)
{
foreach (var e in items)
Add(e);
}
private bool AddItem(in SearchItem item)
{
if (item == null)
return false;
var itemHash = item.GetHashCode();
if (m_IdHashes.Contains(itemHash))
{
var startIndex = m_Items.BinarySearch(item, m_Comparer);
if (startIndex < 0)
startIndex = ~startIndex;
var itemIndex = m_Items.IndexOf(item, Math.Max(startIndex - 1, 0));
if (itemIndex >= 0 && item.score < m_Items[itemIndex].score)
{
m_Items.RemoveAt(itemIndex);
m_IdHashes.Remove(itemHash);
}
else
return false;
}
var insertAt = m_Items.BinarySearch(item, m_Comparer);
if (insertAt < 0)
{
insertAt = ~insertAt;
m_Items.Insert(insertAt, item);
m_IdHashes.Add(itemHash);
return true;
}
return false;
}
public override void Add(SearchItem item)
{
if (AddItem(item) && m_IncomingBatch != null)
m_IncomingBatch.Add(item);
}
public override void CopyTo(SearchItem[] array, int arrayIndex)
{
int i = arrayIndex;
var it = GetEnumerator();
while (it.MoveNext())
array[i++] = it.Current;
}
public override bool Contains(SearchItem item)
{
return m_IdHashes.Contains(item.GetHashCode());
}
public override bool Remove(SearchItem item)
{
if (m_IdHashes.Remove(item.GetHashCode()))
return m_Items.Remove(item);
return false;
}
}
interface IGroup
{
string id { get; }
string name { get; }
string type { get; }
int count { get; }
int priority { get; }
bool optional { get; set; }
IEnumerable<SearchItem> items { get; }
SearchItem ElementAt(int index);
int IndexOf(SearchItem item);
bool Add(SearchItem item);
void Sort();
void SortBy(ISearchListComparer comparer);
void Clear();
}
class GroupedSearchList : BaseSearchList
{
class Group : IGroup
{
public string id { get; private set; }
public string name { get; private set; }
public string type { get; private set; }
public bool optional { get; set; }
public IEnumerable<SearchItem> items => m_Items;
public int count => m_Items.Count;
public int priority { get; set; }
private HashSet<int> m_IdHashes;
private List<SearchItem> m_Items;
private ISearchListComparer m_Comparer;
public Group(string id, string type, string name, ISearchListComparer comparer, int priority = int.MaxValue)
{
this.id = id;
this.name = name;
this.type = type;
this.priority = priority;
this.optional = true;
m_Items = new List<SearchItem>();
m_IdHashes = new HashSet<int>();
m_Comparer = comparer ?? new SortByScoreComparer();
}
public void Clear()
{
m_Items.Clear();
m_IdHashes.Clear();
}
public SearchItem ElementAt(int index)
{
return m_Items[index];
}
public bool Add(SearchItem item)
{
var itemHash = item.GetHashCode();
if (m_IdHashes.Contains(itemHash))
{
// TODO: We should revisit this. There is an inconsistency in how we deal with ordering and score.
// If an item has the same id, a higher score (high score=sorted last) but sorted first based on the sorting method, it will not be replaced by the new item.
// Which is ok if we consider that we want to keep the first result based on the sorting method. However,
// if the existing item is sorted last, but has a lower score (lower score=sorted first), it will not be replaced and the new item will not be added, so the behavior
// is not the same as the other case.
var startIndex = m_Items.BinarySearch(item, m_Comparer);
if (startIndex < 0)
startIndex = ~startIndex;
var itemIndex = m_Items.IndexOf(item, Math.Max(startIndex - 1, 0));
if (itemIndex >= 0 && item.score < m_Items[itemIndex].score)
{
m_Items.RemoveAt(itemIndex);
m_IdHashes.Remove(itemHash);
}
else
return false;
}
var insertAt = m_Items.BinarySearch(item, m_Comparer);
if (insertAt < 0)
{
insertAt = ~insertAt;
m_Items.Insert(insertAt, item);
m_IdHashes.Add(itemHash);
return true;
}
return false;
}
public int IndexOf(SearchItem item)
{
return m_Items.IndexOf(item);
}
public override string ToString()
{
return $"{id} ({m_Items.Count})";
}
public void Sort()
{
if (m_Comparer == null)
return;
m_Items.Sort(m_Comparer);
}
void IGroup.SortBy(ISearchListComparer comparer)
{
if (comparer == null)
return;
if (comparer.GetHashCode() == m_Comparer.GetHashCode())
return;
m_Comparer = comparer;
m_Items.Sort(comparer);
}
}
internal const string allGroupId = "all";
private int m_CurrentGroupIndex = 0;
private string m_CurrentGroupId;
private readonly List<IGroup> m_Groups = new List<IGroup>();
private ISearchListComparer m_DefaultComparer;
public override int Count => m_Groups[m_CurrentGroupIndex >= 0 ? m_CurrentGroupIndex : 0].count;
public int TotalCount => m_Groups[0].count;
public override SearchItem this[int index]
{
get => ElementAt(index);
set => throw new NotSupportedException();
}
public GroupedSearchList(SearchContext searchContext)
: this(searchContext, defaultComparer: null)
{
}
public GroupedSearchList(SearchContext searchContext, ISearchListComparer defaultComparer)
: base(searchContext, false)
{
m_DefaultComparer = defaultComparer;
Clear();
}
public override int IndexOf(SearchItem item)
{
return m_Groups[m_CurrentGroupIndex].IndexOf(item);
}
public SearchItem ElementAt(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException($"Failed to access item {index} within {Count}/{TotalCount} items", nameof(index));
return m_Groups[m_CurrentGroupIndex].ElementAt(index);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
public int GetGroupCount(bool showAll = true)
{
return m_Groups.Count + (showAll ? 0 : -1);
}
public IGroup GetGroupById(string groupId)
{
return m_Groups.Find(group => group.id == groupId);
}
internal IEnumerable<IGroup> GetGroupByType(string groupType)
{
return m_Groups.Where(group => group.type == groupType);
}
public IEnumerable<IGroup> EnumerateGroups(bool showAll = true)
{
if (m_Groups.Count == 2 && m_Groups[0].count == m_Groups[1].count)
yield return m_Groups[1];
else
{
foreach (var g in m_Groups.Skip(showAll ? 0 : 1).Where(g => !g.optional || g.count > 0))
yield return g;
}
}
public IEnumerable<SearchItem> GetAll()
{
return m_Groups[0].items;
}
public override IEnumerable<SearchItem> Fetch()
{
if (context == null)
throw new Exception("Fetch can only be used if the search list was created with a search context.");
while (context.searchInProgress)
{
yield return null;
Dispatcher.ProcessOne();
}
foreach (var item in m_Groups[m_CurrentGroupIndex].items)
yield return item;
}
private void AddDefaultGroups()
{
var defaultGroups = context.providers
.Where(p => p.showDetailsOptions.HasFlag(ShowDetailsOptions.DefaultGroup))
.Select(p => new Group(p.id, p.type, p.name, m_DefaultComparer, p.priority) { optional = false });
m_Groups.AddRange(defaultGroups);
m_Groups.Sort((lhs, rhs) => lhs.priority.CompareTo(rhs.priority));
}
public IGroup AddGroup(SearchProvider searchProvider)
{
var itemGroup = m_Groups.Find(g => string.Equals(g.id, searchProvider.id, StringComparison.Ordinal));
if (itemGroup != null)
return itemGroup;
itemGroup = new Group(searchProvider.id, searchProvider.type, searchProvider.name, m_DefaultComparer, searchProvider.priority);
m_Groups.Add(itemGroup);
m_Groups.Sort((lhs, rhs) => lhs.priority.CompareTo(rhs.priority));
if (!string.IsNullOrEmpty(m_CurrentGroupId))
m_CurrentGroupIndex = m_Groups.FindIndex(g => g.id == m_CurrentGroupId);
if (m_CurrentGroupIndex == -1)
m_CurrentGroupIndex = 0;
return itemGroup;
}
public override void AddItems(IEnumerable<SearchItem> items)
{
foreach (var item in items)
Add(item);
// Restore current group if possible
if (m_CurrentGroupIndex == -1 && !string.IsNullOrEmpty(m_CurrentGroupId))
RestoreCurrentGroup(m_CurrentGroupId);
}
public override void Clear()
{
if (m_Groups.Count == 0)
{
m_CurrentGroupIndex = 0;
m_Groups.Add(new Group(allGroupId, allGroupId, "All", m_DefaultComparer, int.MinValue));
AddDefaultGroups();
}
else
{
foreach (var g in m_Groups)
g.Clear();
}
}
public override IEnumerator<SearchItem> GetEnumerator()
{
return m_Groups[m_CurrentGroupIndex].items.GetEnumerator();
}
public override void Add(SearchItem item)
{
var itemGroup = AddGroup(item.provider);
if (itemGroup.Add(item))
m_Groups[0].Add(item);
}
public override void CopyTo(SearchItem[] array, int arrayIndex)
{
int i = arrayIndex;
var it = GetEnumerator();
while (it.MoveNext())
array[i++] = it.Current;
}
public string currentGroup
{
get
{
return m_CurrentGroupId ?? allGroupId;
}
set
{
if (value == null || !RestoreCurrentGroup(value))
{
m_CurrentGroupId = value;
m_CurrentGroupIndex = 0;
}
}
}
private bool RestoreCurrentGroup(string groupId)
{
m_CurrentGroupIndex = m_Groups.FindIndex(g => g.id == groupId);
if (m_CurrentGroupIndex != -1)
m_CurrentGroupId = groupId;
return m_CurrentGroupIndex != -1;
}
internal int GetItemCount(IEnumerable<string> activeProviderTypes)
{
int queryItemCount = 0;
if (activeProviderTypes == null || !activeProviderTypes.Any())
return TotalCount;
foreach (var providerType in activeProviderTypes)
{
var groupsWithType = GetGroupByType(providerType);
if (groupsWithType == null || !groupsWithType.Any())
continue;
foreach (var group in groupsWithType)
queryItemCount += group.count;
}
return queryItemCount;
}
public void Sort()
{
m_Groups[m_CurrentGroupIndex].Sort();
}
public override void SortBy(ISearchListComparer comparer)
{
m_DefaultComparer = comparer;
m_Groups[m_CurrentGroupIndex].SortBy(comparer);
}
}
class AsyncSearchList : BaseSearchList, ISearchList
{
private readonly List<SearchItem> m_UnorderedItems;
public override int Count => m_UnorderedItems.Count;
public override SearchItem this[int index]
{
get => m_UnorderedItems[index];
set => m_UnorderedItems[index] = value;
}
public AsyncSearchList(SearchContext searchContext) : base(searchContext)
{
m_UnorderedItems = new List<SearchItem>();
}
public override void Add(SearchItem item)
{
m_UnorderedItems.Add(item);
}
public override void AddItems(IEnumerable<SearchItem> items)
{
m_UnorderedItems.AddRange(items);
}
public override void Clear()
{
m_UnorderedItems.Clear();
}
public override bool Contains(SearchItem item)
{
return m_UnorderedItems.Contains(item);
}
public override void CopyTo(SearchItem[] array, int arrayIndex)
{
m_UnorderedItems.CopyTo(array, arrayIndex);
}
public override IEnumerable<SearchItem> Fetch()
{
if (context == null)
throw new Exception("Fetch can only be used if the search list was created with a search context.");
int i = 0;
var nextCount = m_UnorderedItems.Count;
for (; i < nextCount; ++i)
yield return m_UnorderedItems[i];
while (context.searchInProgress)
{
if (nextCount < m_UnorderedItems.Count)
{
nextCount = m_UnorderedItems.Count;
for (; i < nextCount; ++i)
yield return m_UnorderedItems[i];
}
else
{
if (context.Tick())
yield return null; // Wait for more items...
}
}
for (; i < m_UnorderedItems.Count; ++i)
yield return m_UnorderedItems[i];
}
public override IEnumerator<SearchItem> GetEnumerator()
{
return Fetch().GetEnumerator();
}
public override void InsertRange(int index, IEnumerable<SearchItem> items)
{
foreach (var item in items.Where(e => e != null))
SearchItem.Insert(m_UnorderedItems, item, SearchItem.DefaultComparer);
}
public override bool Remove(SearchItem item)
{
return m_UnorderedItems.Remove(item);
}
public override IEnumerable<SearchItem> GetRange(int skipCount, int count)
{
return m_UnorderedItems.GetRange(skipCount, count);
}
}
class ConcurrentSearchList : BaseSearchList
{
readonly ConcurrentBag<SearchItem> m_UnorderedItems;
bool m_SearchStarted;
bool m_GetItemsDone;
public ConcurrentSearchList(SearchContext searchContext) : base(searchContext)
{
m_UnorderedItems = new ConcurrentBag<SearchItem>();
searchContext.sessionStarted += SearchContextOnsessionStarted;
m_SearchStarted = searchContext.searchInProgress;
}
protected override void Dispose(bool disposing)
{
context.sessionStarted -= SearchContextOnsessionStarted;
base.Dispose(disposing);
}
void SearchContextOnsessionStarted(SearchContext obj)
{
m_SearchStarted = true;
}
public void GetItemsDone()
{
m_GetItemsDone = true;
}
public override void Add(SearchItem item)
{
m_UnorderedItems.Add(item);
}
public override void AddItems(IEnumerable<SearchItem> items)
{
var addedItems = items;
foreach (var searchItem in addedItems)
{
m_UnorderedItems.Add(searchItem);
}
}
public override bool Contains(SearchItem item)
{
return m_UnorderedItems.Contains(item);
}
public override void CopyTo(SearchItem[] array, int arrayIndex)
{
m_UnorderedItems.CopyTo(array, arrayIndex);
}
public override int Count => m_UnorderedItems.Count;
public override SearchItem this[int index]
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override IEnumerable<SearchItem> Fetch()
{
if (context == null)
throw new Exception("Fetch can only be used if the search list was created with a search context.");
while (!m_SearchStarted)
{
yield return null;
}
while (context.searchInProgress || !m_GetItemsDone)
{
if (m_UnorderedItems.TryTake(out var searchItem))
{
yield return searchItem;
}
else
{
yield return null; // Wait for more items...
}
}
while (!m_UnorderedItems.IsEmpty)
{
if (m_UnorderedItems.TryTake(out var searchItem))
yield return searchItem;
}
}
public override IEnumerator<SearchItem> GetEnumerator()
{
return Fetch().GetEnumerator();
}
}
static class SearchListExtension
{
public static IEnumerable<IEnumerable<SearchItem>> Batch(this IEnumerable<SearchItem> source, int batchSize)
{
using (var enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return YieldBatchElements(enumerator, batchSize - 1);
}
private static IEnumerable<SearchItem> YieldBatchElements(IEnumerator<SearchItem> source, int batchSize)
{
yield return source.Current;
for (int i = 0; i < batchSize && source.MoveNext(); i++)
yield return source.Current;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchList.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchList.cs",
"repo_id": "UnityCsReference",
"token_count": 14365
} | 446 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class MaterialSelectors
{
[SearchSelector(@"#(?<propertyPath>.+)", provider: "asset", priority: 9998)]
public static object GetMaterialPropertyValue(SearchSelectorArgs args)
{
if (!(args["propertyPath"] is string propertyPath))
return null;
var item = args.current;
var material = item.ToObject<Material>();
if (!material)
return null;
var matProp = MaterialEditor.GetMaterialProperty(new Object[] { material }, propertyPath);
if (matProp == null || matProp.name == null)
{
var materialProperties = MaterialEditor.GetMaterialProperties(new Object[] { material });
for (var i = 0; i < materialProperties.Length; i++)
{
if (!materialProperties[i].name.EndsWith(propertyPath, System.StringComparison.OrdinalIgnoreCase))
continue;
matProp = materialProperties[i];
break;
}
}
return GetMaterialPropertyValue(matProp);
}
internal static object GetMaterialPropertyValue(MaterialProperty p)
{
if (p == null || p.name == null)
return null;
switch (p.type)
{
case MaterialProperty.PropType.Color: return p.colorValue;
case MaterialProperty.PropType.Vector: return p.vectorValue;
case MaterialProperty.PropType.Float: return p.floatValue;
case MaterialProperty.PropType.Range: return p.floatValue;
case MaterialProperty.PropType.Texture: return p.textureValue;
}
return null;
}
public static IEnumerable<SearchColumn> Enumerate(IEnumerable<SearchItem> items)
{
var descriptors = new List<SearchColumn>();
var shaderProcessed = new HashSet<string>();
bool materialRootItemAdded = false;
foreach (var item in items)
{
var material = item.ToObject<Material>();
if (!material)
continue;
if (!materialRootItemAdded)
{
descriptors.Add(new SearchColumn("Material", new GUIContent("Material", Utils.FindTextureForType(typeof(Material)))));
materialRootItemAdded = true;
}
if (shaderProcessed.Contains(material.shader.name))
continue;
shaderProcessed.Add(material.shader.name);
var shaderPath = "Material/" + material.shader.name;
var shaderIcon = Utils.FindTextureForType(typeof(Shader));
descriptors.Add(new SearchColumn(shaderPath, new GUIContent(material.shader.name, shaderIcon)));
var materialProperties = MaterialEditor.GetMaterialProperties(new Object[] { material });
for (var i = 0; i < materialProperties.Length; i++)
{
var m = materialProperties[i];
var propName = m.name;
var propPath = shaderPath + "/" + propName;
var col = new SearchColumn(propPath, "#" + propName, provider: $"{m.type}",
new GUIContent(m.displayName, shaderIcon, m.name));
descriptors.Add(col);
}
}
return descriptors;
}
}
static class MaterialPropertyColumnProvider
{
class SearchMaterialPropertyCell : VisualElement, IBindable, ISearchTableViewCellValue
{
private readonly SearchColumn m_SearchColumn;
private VisualElement m_ValueElement;
private MaterialProperty.PropType? m_CurrentBindedType;
IBinding IBindable.binding { get => (m_ValueElement as IBindable)?.binding; set { if (m_ValueElement is IBindable b) b.binding = value; } }
string IBindable.bindingPath { get => (m_ValueElement as IBindable)?.bindingPath; set { if (m_ValueElement is IBindable b) b.bindingPath = value; } }
public SearchMaterialPropertyCell(SearchColumn column)
{
m_SearchColumn = column;
}
private void Create(MaterialProperty property, SearchColumnEventArgs args)
{
Clear();
m_ValueElement = null;
switch (property.type)
{
case MaterialProperty.PropType.Color: m_ValueElement = new UIElements.ColorField(); break;
case MaterialProperty.PropType.Float:
m_ValueElement = new FloatField() { label = "\u2022", style = { flexDirection = FlexDirection.Row } };
break;
case MaterialProperty.PropType.Range:
var slider = new Slider(0f, 1f);
slider.showInputField = true;
m_ValueElement = slider;
break;
case MaterialProperty.PropType.Vector: m_ValueElement = new Vector4Field(); break;
case MaterialProperty.PropType.Texture:
m_ValueElement = new ObjectField() { objectType = typeof(Texture) };
break;
}
visible = true;
m_CurrentBindedType = property.type;
if (m_ValueElement != null)
{
Add(m_ValueElement);
m_ValueElement.style.flexGrow = 1f;
m_ValueElement.style.flexDirection = FlexDirection.Row;
}
}
public void Bind(SearchColumnEventArgs args)
{
if (args.value is not MaterialProperty matProp)
{
visible = false;
return;
}
if (!m_CurrentBindedType.HasValue || m_CurrentBindedType != matProp.type)
Create(matProp, args);
switch (matProp.type)
{
case MaterialProperty.PropType.Color:
{
if (m_ValueElement is INotifyValueChanged<Color> v)
v.SetValueWithoutNotify(matProp.colorValue);
}
break;
case MaterialProperty.PropType.Vector:
{
if (m_ValueElement is INotifyValueChanged<Vector4> v)
v.SetValueWithoutNotify(matProp.vectorValue);
}
break;
case MaterialProperty.PropType.Float:
{
if (m_ValueElement is INotifyValueChanged<float> v)
v.SetValueWithoutNotify(matProp.floatValue);
}
break;
case MaterialProperty.PropType.Range:
{
if (m_ValueElement is Slider s)
{
s.SetValueWithoutNotify(matProp.floatValue);
s.lowValue = matProp.rangeLimits.x;
s.SetHighValueWithoutNotify(matProp.rangeLimits.y);
}
}
break;
case MaterialProperty.PropType.Texture:
{
if (m_ValueElement is INotifyValueChanged<Object> v)
v.SetValueWithoutNotify(matProp.textureValue);
}
break;
}
}
void ISearchTableViewCellValue.Update(object newValue)
{
}
}
[SearchColumnProvider("MaterialProperty")]
public static void InitializeMaterialPropertyColumn(SearchColumn column)
{
column.getter = args => MaterialPropertyGetter(args.item, args.column);
column.setter = args => SetMaterialPropertyValue(args.item, args.column, args.value);
column.comparer = args => MaterialPropertyComparer(args.lhs.value, args.rhs.value, args.sortAscending);
column.cellCreator = args => MaterialMakePropertyField(args);
column.binder = (args, ve) => MaterialBindPropertyField(args, ve);
}
private static VisualElement MaterialMakePropertyField(SearchColumn column)
{
return new SearchMaterialPropertyCell(column);
}
private static void MaterialBindPropertyField(SearchColumnEventArgs args, VisualElement ve)
{
if (ve is SearchMaterialPropertyCell smpc)
smpc.Bind(args);
}
internal static MaterialProperty GetMaterialProperty(SearchItem item, SearchColumn column)
{
var mat = item.ToObject<Material>();
if (!mat)
return null;
foreach (var m in SelectorManager.Match(column.selector, item.provider?.type))
{
var selectorArgs = new SearchSelectorArgs(m, item);
if (selectorArgs.name == null)
continue;
if (!mat.HasProperty(selectorArgs.name))
continue;
return MaterialEditor.GetMaterialProperty(new Object[] { mat }, selectorArgs.name);
}
return null;
}
static object MaterialPropertyGetter(SearchItem item, SearchColumn column)
{
var matProp = GetMaterialProperty(item, column);
if (matProp == null)
return null;
return matProp;
}
internal static void SetMaterialPropertyValue(SearchItem item, SearchColumn column, object newValue)
{
var matProp = GetMaterialProperty(item, column);
if (matProp == null)
return;
switch (matProp.type)
{
case MaterialProperty.PropType.Color:
if (newValue is Color c && matProp.colorValue != c)
matProp.colorValue = c;
break;
case MaterialProperty.PropType.Vector:
if (newValue is Vector4 v && matProp.vectorValue != v)
matProp.vectorValue = v;
break;
case MaterialProperty.PropType.Float:
{
if (newValue is float f && matProp.floatValue != f)
matProp.floatValue = f;
}
break;
case MaterialProperty.PropType.Range:
{
if (newValue is float f && matProp.floatValue != f)
matProp.floatValue = f;
}
break;
case MaterialProperty.PropType.Texture:
{
var texValue = newValue as Texture;
if ((newValue == null || texValue != null) && matProp.textureValue != texValue)
{
matProp.textureValue = texValue;
}
break;
}
}
}
static object MaterialPropertyDrawer(Rect r, object prop)
{
if (!(prop is MaterialProperty matProp))
return null;
switch (matProp.type)
{
case MaterialProperty.PropType.Color:
return MaterialEditor.ColorPropertyInternal(r, matProp, GUIContent.none);
case MaterialProperty.PropType.Float:
return MaterialEditor.FloatPropertyInternal(r, matProp, GUIContent.none);
case MaterialProperty.PropType.Range:
return MaterialEditor.RangePropertyInternal(r, matProp, GUIContent.none);
case MaterialProperty.PropType.Vector:
return MaterialEditor.VectorPropertyInternal(r, matProp, GUIContent.none);
case MaterialProperty.PropType.Texture:
return EditorGUI.DoObjectField(r, r, GUIUtility.GetControlID(FocusType.Passive), matProp.textureValue, matProp.targets[0], typeof(Texture), null, true);
}
return null;
}
static int MaterialPropertyComparer(object lhsObj, object rhsObj, bool sortAscending)
{
if (!(lhsObj is MaterialProperty lm) || !(rhsObj is MaterialProperty rm) || lm.type != rm.type)
return 0;
switch (lm.type)
{
case MaterialProperty.PropType.Color:
Color.RGBToHSV(lm.colorValue, out float lh, out _, out _);
Color.RGBToHSV(rm.colorValue, out float rh, out _, out _);
return lh.CompareTo(rh);
case MaterialProperty.PropType.Range:
case MaterialProperty.PropType.Float:
return lm.floatValue.CompareTo(rm.floatValue);
case MaterialProperty.PropType.Texture:
return string.CompareOrdinal(lm.textureValue?.name, rm.textureValue?.name);
case MaterialProperty.PropType.Vector:
return lm.vectorValue.magnitude.CompareTo(rm.vectorValue.magnitude);
}
return 0;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Selectors/MaterialSelectors.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Selectors/MaterialSelectors.cs",
"repo_id": "UnityCsReference",
"token_count": 7245
} | 447 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
namespace UnityEditor.Search
{
interface IResultView : IDisposable
{
Rect rect { get; }
float itemSize { get; }
bool showNoResultMessage { get; }
void Refresh(RefreshFlags flags = RefreshFlags.Default);
void OnGroupChanged(string prevGroupId, string newGroupId);
void AddSaveQueryMenuItems(SearchContext context, GenericMenu menu);
void Focus();
internal int ComputeVisibleItemCapacity(float size, float height);
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UI/IResultView.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UI/IResultView.cs",
"repo_id": "UnityCsReference",
"token_count": 237
} | 448 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Search;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class SearchEmptyView : SearchElement, IResultView
{
const string k_All = "all";
public static readonly string ussClassName = "search-empty-view";
public static readonly string headerClassName = ussClassName.WithUssElement("header");
public static readonly string noResultsRowContainerClassName = ussClassName.WithUssElement("no-results-row-container");
public static readonly string noResultsClassName = ussClassName.WithUssElement("no-results");
public static readonly string noResultsHelpClassName = ussClassName.WithUssElement("no-results-help");
public static readonly string queryRowClassName = ussClassName.WithUssElement("query-row");
public static readonly string builderClassName = ussClassName.WithUssElement("builder");
public static readonly string descriptionClassName = ussClassName.WithUssElement("description");
public static readonly string helperBackgroundClassName = ussClassName.WithUssElement("helper-background");
public static readonly Texture2D recentSearchesIcon = EditorGUIUtility.FindTexture("UndoHistory");
private bool m_Disposed;
private QueryBuilder m_Areas;
private VisualElement m_QueriesContainer;
private SearchEmptyViewMode m_DisplayMode;
float IResultView.itemSize => m_ViewModel.itemIconSize;
Rect IResultView.rect => worldBound;
bool IResultView.showNoResultMessage => true;
enum SearchEmptyViewMode
{
None,
HideHelpersNoResult,
SearchInProgress,
NoResult,
NoResultWithTips,
QueryHelpersText,
QueryHelpersBlock
}
public SearchViewFlags searchViewFlags { get; set; }
int IResultView.ComputeVisibleItemCapacity(float width, float height)
{
return 0;
}
static readonly string k_NoResultsLabel = L10n.Tr("No Results.");
static readonly string k_SearchInProgressLabel = L10n.Tr("Search in progress...");
static readonly string k_NarrowYourSearchLabel = L10n.Tr("Narrow your search");
static readonly string k_SearchesLabel = L10n.Tr("Searches");
static readonly string k_AreaTooltipFormat = L10n.Tr("Double click to search in: {0}");
static readonly string k_NoResultsFoundLabel = L10n.Tr("No results found.");
static readonly string k_NoResultsFoundQueryFormat = L10n.Tr("No results found for <b>{0}</b>.");
static readonly string k_IndexingInProgressLabel = L10n.Tr("Indexing is still in progress.");
static readonly string k_TrySomethingElseLabel = L10n.Tr("Try something else?");
static readonly string k_NoResultsInProviderFormat = L10n.Tr("There is no result in {0}.");
static readonly string k_SelectAnotherTabLabel = L10n.Tr("Select another search tab?");
static readonly string k_IndexesPropertiesLabel = L10n.Tr("Some indexes don't have properties enabled.");
static readonly string k_OpenIndexManagerLabel = L10n.Tr("Open Index Manager?");
static readonly string k_IndexesDisabledLabel = L10n.Tr("All indexes are disabled.");
static readonly string k_ShowMoreResultsLabel = L10n.Tr("Show more results is off.");
static readonly string k_TurnItOnLabel = L10n.Tr("Turn it on?");
static readonly string k_ShowPackagesLabel = L10n.Tr("Show Packages is off.");
static readonly string k_AddFilterOrKeywordLabel = L10n.Tr("The search query is empty. Try adding some filters or keywords.");
static readonly string k_TryAQueryLabel = L10n.Tr("The search query is empty. Try one of these queries:");
Label m_NoResultLabel;
VisualElement m_QueryPropositionContainer;
Label m_NoResultsHelpLabel;
VisualElement m_IndexHelpLabel;
VisualElement m_WantsMoreLabel;
VisualElement m_ShowPackagesLabel;
public SearchEmptyView(ISearchView viewModel, SearchViewFlags flags)
: base("SearchEmptyView", viewModel, ussClassName)
{
searchViewFlags = flags;
BuildView();
}
public void Update()
{
if (GetDisplayMode() == SearchEmptyViewMode.NoResultWithTips && !context.empty)
{
BuildView(true);
}
}
private SearchEmptyViewMode GetDisplayMode()
{
if (searchViewFlags.HasFlag(SearchViewFlags.DisableQueryHelpers))
return SearchEmptyViewMode.HideHelpersNoResult;
if (m_ViewModel.searchInProgress)
return SearchEmptyViewMode.SearchInProgress;
if (!QueryEmpty())
{
return searchViewFlags.HasFlag(SearchViewFlags.DisableNoResultTips) ?
SearchEmptyViewMode.NoResult :
SearchEmptyViewMode.NoResultWithTips;
}
if (viewState.queryBuilderEnabled)
return SearchEmptyViewMode.QueryHelpersBlock;
return SearchEmptyViewMode.QueryHelpersText;
}
private bool QueryEmpty()
{
return string.IsNullOrEmpty(context.searchText);
}
private void BuildView(bool forceBuild = false)
{
var displayMode = GetDisplayMode();
if (!forceBuild && displayMode == m_DisplayMode)
{
UpdateView();
return;
}
m_DisplayMode = displayMode;
ClearAllNoResultsTipsHelpers();
Clear();
switch(m_DisplayMode)
{
case SearchEmptyViewMode.HideHelpersNoResult:
AddOrUpdateNoResultLabel(ref m_NoResultLabel, k_NoResultsLabel);
break;
case SearchEmptyViewMode.NoResult:
AddOrUpdateNoResultLabel(ref m_NoResultLabel, k_NoResultsLabel);
break;
case SearchEmptyViewMode.NoResultWithTips:
BuildNoResultsTips();
break;
case SearchEmptyViewMode.SearchInProgress:
AddOrUpdateNoResultLabel(ref m_NoResultLabel, k_SearchInProgressLabel);
break;
default:
BuildQueryHelpers();
break;
}
EnableInClassList(helperBackgroundClassName, m_DisplayMode == SearchEmptyViewMode.HideHelpersNoResult || QueryEmpty());
}
void UpdateView()
{
if (m_DisplayMode != SearchEmptyViewMode.NoResultWithTips)
return;
BuildNoResultsTips();
}
private void BuildQueryHelpers()
{
m_QueriesContainer = new VisualElement();
m_QueriesContainer.name = "QueryHelpersContainer";
if (GetActiveHelperProviders(viewState.queryBuilderEnabled).Count() > 1)
{
Add(CreateHeader(k_NarrowYourSearchLabel));
Add(CreateProviderHelpers(viewState.queryBuilderEnabled));
}
else
{
BuildSearches();
}
Add(m_QueriesContainer);
}
private void BuildSearches()
{
m_QueriesContainer.Clear();
var searches = new QueryHelperSearchGroup(viewState.queryBuilderEnabled, k_SearchesLabel);
PopulateSearches(searches);
var searchesHeader = CreateHeader(k_SearchesLabel);
m_QueriesContainer.Add(searchesHeader);
m_QueriesContainer.Add(CreateSearchHelpers(viewState.queryBuilderEnabled, searches));
searchesHeader.text = searches.title.text;
}
private void PopulateSearches(QueryHelperSearchGroup searches)
{
foreach (var q in SearchTemplateAttribute.GetAllQueries())
searches.Add(q, QueryHelperSearchGroup.QueryType.Template, SearchQuery.GetIcon(q));
foreach (var q in SearchQueryAsset.savedQueries.Cast<ISearchQuery>().Concat(SearchQuery.userQueries).Where(q => q.isSearchTemplate))
searches.Add(q, QueryHelperSearchGroup.QueryType.Template, SearchQuery.GetIcon(q));
foreach (var a in EnumerateUniqueRecentSearches().Take(5))
searches.Add(a, QueryHelperSearchGroup.QueryType.Recent, recentSearchesIcon);
}
private VisualElement CreateSearchHelpers(bool blockMode, QueryHelperSearchGroup searches)
{
var container = new ScrollView();
container.style.flexDirection = FlexDirection.Column;
var currentAreaFilterId = SearchSettings.helperWidgetCurrentArea;
var filteredQueries = GetFilteredQueries(searches.queries, currentAreaFilterId, blockMode); ;
PopulateSearchHelpers(filteredQueries, container);
searches.UpdateTitle(filteredQueries.Count());
container.Children().LastOrDefault()?.AddToClassList("last-child");
return container;
}
private void PopulateSearchHelpers(IEnumerable<QueryHelperSearchGroup.QueryData> filteredQueries, VisualElement container)
{
foreach (var qd in filteredQueries)
{
var rowContainer = new VisualElement();
rowContainer.AddToClassList(queryRowClassName);
rowContainer.Add(new Image() { image = qd.icon.image, tooltip = qd.icon.tooltip, pickingMode = PickingMode.Ignore });
if (qd.builder != null)
{
var builderContainer = new VisualElement();
builderContainer.pickingMode = PickingMode.Ignore;
builderContainer.AddToClassList(builderClassName);
foreach (var b in qd.builder.EnumerateBlocks())
{
var be = b.CreateGUI();
be.Query<VisualElement>().ForEach(e => e.pickingMode = PickingMode.Ignore);
be.pickingMode = PickingMode.Ignore;
builderContainer.Add(be);
}
rowContainer.Add(builderContainer);
}
else
{
rowContainer.Add(CreateLabel(qd.searchText, PickingMode.Ignore));
}
rowContainer.Add(CreateLabel(qd.description, PickingMode.Ignore, descriptionClassName));
rowContainer.userData = qd;
rowContainer.RegisterCallback<ClickEvent>(OnQueryHelperClicked);
container.Add(rowContainer);
}
}
private void OnQueryHelperClicked(ClickEvent evt)
{
if (evt.target is not VisualElement ve || ve.userData is not QueryHelperSearchGroup.QueryData qd)
return;
if (qd.query != null && this.GetSearchHostWindow() is ISearchQueryView sqv)
ExecuteQuery(qd.query);
else
m_ViewModel.SetSearchText(qd.searchText);
}
private bool IsFilteredQuery(ISearchQuery query, SearchProvider provider)
{
if (provider == null)
return false;
if (query.searchText.StartsWith(provider.filterId))
return true;
var queryProviders = query.GetProviderIds().ToArray();
return queryProviders.Length == 1 && queryProviders[0] == provider.id;
}
private IEnumerable<QueryHelperSearchGroup.QueryData> GetFilteredQueries(IEnumerable<QueryHelperSearchGroup.QueryData> queries, string currentAreaFilterId, bool blockMode)
{
var activeProviders = GetActiveHelperProviders(blockMode);
var isAll = k_All == currentAreaFilterId;
if (isAll)
{
// Keep only query matching one of the active providers.
return queries.Where(q => activeProviders.Any(p => IsFilteredQuery(q.query, p)));
}
var currentProvider = activeProviders.FirstOrDefault(p => p.filterId == currentAreaFilterId);
return queries.Where(q =>
{
// Keep query matching THE selected provider.
if (q.type == QueryHelperSearchGroup.QueryType.Recent)
return q.searchText.StartsWith(currentAreaFilterId, StringComparison.Ordinal);
return IsFilteredQuery(q.query, currentProvider);
});
}
private IEnumerable<string> EnumerateUniqueRecentSearches()
{
var recentSearches = SearchSettings.recentSearches.ToList();
for (var i = 0; i < recentSearches.Count(); ++i)
{
var a = recentSearches[i];
yield return a;
for (var j = i + 1; j < recentSearches.Count();)
{
var b = recentSearches[j];
if (a.StartsWith(b) || Utils.LevenshteinDistance(a, b, false) < 9)
{
recentSearches.RemoveAt(j);
}
else
{
j++;
}
}
}
}
private VisualElement CreateProviderHelpers(bool blockMode = true)
{
var providersContainer = new VisualElement();
providersContainer.style.flexDirection = FlexDirection.Row;
providersContainer.style.flexWrap = Wrap.Wrap;
providersContainer.style.flexShrink = 0f;
m_Areas = new QueryBuilder(string.Empty);
var allArea = new QueryAreaBlock(m_Areas, k_All, string.Empty);
allArea.RegisterCallback<ClickEvent>(OnProviderClicked);
m_Areas.AddBlock(allArea);
foreach (var p in GetActiveHelperProviders(blockMode))
{
var providerBlock = new QueryAreaBlock(m_Areas, p);
providerBlock.RegisterCallback<ClickEvent>(OnProviderClicked);
m_Areas.AddBlock(providerBlock);
}
m_Areas.@readonly = true;
foreach (var b in m_Areas.blocks)
b.tooltip = string.Format(k_AreaTooltipFormat, b.value);
foreach (var b in m_Areas.EnumerateBlocks())
{
if (b is QueryAreaBlock area && GetFilterId(area) == SearchSettings.helperWidgetCurrentArea)
{
b.selected = true;
}
providersContainer.Add(b.CreateGUI());
}
if (!m_Areas.selectedBlocks.Any())
{
allArea.selected = true;
SetCurrentArea(allArea);
}
else
{
BuildSearches();
}
return providersContainer;
}
private void OnProviderClicked(ClickEvent evt)
{
if (evt.currentTarget is not QueryAreaBlock area)
return;
if (evt.clickCount == 2 && !string.IsNullOrEmpty(area.filterId))
{
SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchHelperWidgetExecuted, viewState.queryBuilderEnabled ? "queryBuilder" : "text", "doubleClick");
var query = CreateQuery(area.ToString());
ExecuteQuery(query);
}
else
{
SetCurrentArea(area);
}
evt.StopPropagation();
}
private void SetCurrentArea(QueryAreaBlock area)
{
var filterId = GetFilterId(area);
SearchSettings.helperWidgetCurrentArea = filterId;
BuildSearches();
}
private static string GetFilterId(QueryAreaBlock area)
{
return string.IsNullOrEmpty(area.filterId) ? area.value : area.filterId;
}
private static ISearchQuery CreateQuery(string queryStr)
{
var q = new SearchQuery() { searchText = queryStr };
q.viewState.itemSize = SearchSettings.itemIconSize;
return q;
}
private void ExecuteQuery(ISearchQuery query)
{
if(this.GetSearchHostWindow() is ISearchQueryView sqv)
sqv.ExecuteSearchQuery(query);
}
private IEnumerable<SearchProvider> GetActiveHelperProviders(bool blockMode)
{
var allProviders = m_ViewModel?.context?.GetProviders() ?? SearchService.GetActiveProviders();
var generalProviders = allProviders.Where(p => !p.isExplicitProvider);
var explicitProviders = allProviders.Where(p => p.isExplicitProvider);
var providers = generalProviders.Concat(explicitProviders);
if (!blockMode)
return providers;
var builtinSearches = SearchTemplateAttribute.GetAllQueries();
return providers.Where(p => p.id != "expression" && (p.fetchPropositions != null ||
builtinSearches.Any(sq => sq.searchText.StartsWith(p.filterId) || sq.GetProviderIds().Any(pid => p.id == pid))));
}
private static Label CreateHeader(in string text)
{
var header = CreateLabel(text, null, headerClassName);
return header;
}
protected override void OnAttachToPanel(AttachToPanelEvent evt)
{
base.OnAttachToPanel(evt);
On(SearchEvent.FilterToggled, ForceRebuildView);
On(SearchEvent.RefreshBuilder, BuildView);
On(SearchEvent.SearchIndexesChanged, BuildView);
On(SearchEvent.SearchTextChanged, BuildView);
}
protected override void OnDetachFromPanel(DetachFromPanelEvent evt)
{
Off(SearchEvent.FilterToggled, ForceRebuildView);
Off(SearchEvent.RefreshBuilder, BuildView);
Off(SearchEvent.SearchIndexesChanged, BuildView);
Off(SearchEvent.SearchTextChanged, BuildView);
base.OnDetachFromPanel(evt);
}
private void BuildView(ISearchEvent evt)
{
BuildView();
}
void ForceRebuildView(ISearchEvent evt)
{
BuildView(true);
}
private void BuildNoResultsTips()
{
var provider = SearchService.GetProvider(m_ViewModel.currentGroup);
var anyNonReady = false;
var anyWithNoPropertyIndexing = false;
var allDisabled = true;
if (!context.noIndexing)
{
foreach (var database in SearchDatabase.EnumerateAll())
{
if (database.settings.options.disabled)
continue;
allDisabled = false;
if (!database.ready)
anyNonReady = true;
if (!database.settings.options.properties)
anyWithNoPropertyIndexing = true;
}
}
else
allDisabled = false;
var structureChanged = false;
if (m_ViewModel.totalCount == 0 || provider == null)
{
if (string.IsNullOrEmpty(context.searchQuery?.Trim()))
{
structureChanged |= ClearNoResultsTipsHelper(ref m_NoResultsHelpLabel);
structureChanged |= AddOrUpdateNoResultLabel(ref m_NoResultLabel, k_NoResultsFoundLabel);
structureChanged |= AddOrUpdateNoResultQueryPropositions(ref m_QueryPropositionContainer, 2);
}
else
{
structureChanged |= ClearNoResultsTipsHelper(ref m_QueryPropositionContainer);
structureChanged |= AddOrUpdateNoResultLabel(ref m_NoResultLabel, string.Format(k_NoResultsFoundQueryFormat, context.searchQuery));
if (anyNonReady)
structureChanged |= AddOrUpdateNoResultHelpLabel(ref m_NoResultsHelpLabel, k_IndexingInProgressLabel);
else
structureChanged |= AddOrUpdateNoResultHelpLabel(ref m_NoResultsHelpLabel, k_TrySomethingElseLabel);
}
}
else
{
structureChanged |= ClearNoResultsTipsHelper(ref m_QueryPropositionContainer);
structureChanged |= AddOrUpdateNoResultLabel(ref m_NoResultLabel, string.Format(k_NoResultsInProviderFormat, provider.name));
if (anyNonReady)
structureChanged |= AddOrUpdateNoResultHelpLabel(ref m_NoResultsHelpLabel, k_IndexingInProgressLabel);
else
structureChanged |= AddOrUpdateNoResultHelpLabel(ref m_NoResultsHelpLabel, k_SelectAnotherTabLabel);
}
if (!anyNonReady)
{
if (anyWithNoPropertyIndexing)
structureChanged |= AddOrUpdateNoResultHelpLabelWithButton(ref m_IndexHelpLabel, k_IndexesPropertiesLabel, k_OpenIndexManagerLabel, () => OpenIndexManager());
else if (allDisabled)
structureChanged |= AddOrUpdateNoResultHelpLabelWithButton(ref m_IndexHelpLabel, k_IndexesDisabledLabel, k_OpenIndexManagerLabel, () => OpenIndexManager());
else
structureChanged |= ClearNoResultsTipsHelper(ref m_IndexHelpLabel);
}
if (!context.wantsMore)
structureChanged |= AddOrUpdateNoResultHelpLabelWithButton(ref m_WantsMoreLabel, k_ShowMoreResultsLabel, k_TurnItOnLabel, () => ToggleWantsMore());
else
structureChanged |= ClearNoResultsTipsHelper(ref m_WantsMoreLabel);
if (!context.showPackages)
structureChanged |= AddOrUpdateNoResultHelpLabelWithButton(ref m_ShowPackagesLabel, k_ShowPackagesLabel, k_TurnItOnLabel, () => TogglePackages());
else
structureChanged |= ClearNoResultsTipsHelper(ref m_ShowPackagesLabel);
if (structureChanged)
{
SetSortOrder(m_NoResultLabel, 0);
SetSortOrder(m_QueryPropositionContainer, 1);
SetSortOrder(m_NoResultsHelpLabel, 2);
SetSortOrder(m_IndexHelpLabel, 3);
SetSortOrder(m_WantsMoreLabel, 4);
SetSortOrder(m_ShowPackagesLabel, 5);
Sort((elementA, elementB) =>
{
if (elementA == null && elementB == null)
return 0;
if (elementA == null)
return -1;
if (elementB == null)
return 1;
var sortOrderA = elementA.userData as int? ?? 0;
var sortOrderB = elementB.userData as int? ?? 0;
return sortOrderA.CompareTo(sortOrderB);
});
}
}
void SetSortOrder(VisualElement element, int sortOrder)
{
if (element == null)
return;
element.userData = sortOrder;
}
// This needs to be generic as converting from ref Label to ref VisualElement does not work.
static bool ClearNoResultsTipsHelper<T>(ref T helper)
where T : VisualElement
{
if (helper == null)
return false;
helper.RemoveFromHierarchy();
helper = null;
return true;
}
void ClearAllNoResultsTipsHelpers()
{
ClearNoResultsTipsHelper(ref m_NoResultLabel);
ClearNoResultsTipsHelper(ref m_NoResultsHelpLabel);
ClearNoResultsTipsHelper(ref m_IndexHelpLabel);
ClearNoResultsTipsHelper(ref m_WantsMoreLabel);
ClearNoResultsTipsHelper(ref m_ShowPackagesLabel);
ClearNoResultsTipsHelper(ref m_QueryPropositionContainer);
}
bool AddOrUpdateNoResultQueryPropositions(ref VisualElement container, int maxQueryCount)
{
container?.RemoveFromHierarchy();
var emptyFilterId = string.IsNullOrEmpty(context.filterId);
if (emptyFilterId)
{
Label label = null;
AddOrUpdateNoResultHelpLabel(ref label, k_AddFilterOrKeywordLabel);
container = label;
return true;
}
var searches = new QueryHelperSearchGroup(viewState.queryBuilderEnabled, k_SearchesLabel);
PopulateSearches(searches);
var filteredQueries = GetFilteredQueries(searches.queries, context.filterId, viewState.queryBuilderEnabled)
.Take(maxQueryCount).ToArray();
if (filteredQueries.Length == 0)
{
Label label = null;
AddOrUpdateNoResultHelpLabel(ref label, k_AddFilterOrKeywordLabel);
container = label;
return true;
}
container = new VisualElement();
Label tryAQueryLabel = null;
AddOrUpdateNoResultHelpLabel(ref tryAQueryLabel, k_TryAQueryLabel, container);
var innerContainer = Create("SearchEmptyViewQueryPropositions", noResultsRowContainerClassName);
PopulateSearchHelpers(filteredQueries, innerContainer);
container.Add(innerContainer);
Add(container);
return true;
}
private bool AddOrUpdateNoResultLabel(ref Label label, in string text)
{
if (label != null)
{
label.text = text;
return false;
}
label = CreateLabel(text, null, PickingMode.Ignore, noResultsClassName);
Add(label);
return true;
}
private bool AddOrUpdateNoResultHelpLabel(ref Label label, in string text, VisualElement container = null)
{
if (label != null)
{
label.text = text;
return false;
}
label = CreateLabel(text, null, PickingMode.Ignore, noResultsHelpClassName);
if (container != null)
container.Add(label);
else
Add(label);
return true;
}
private bool AddOrUpdateNoResultHelpLabelWithButton(ref VisualElement container, in string text, in string buttonText, Action onClickedCallback)
{
if (container != null)
{
var innerLabel = container.Q<Label>();
innerLabel.text = text;
return false;
}
container = Create("SearchEmptyViewAction", noResultsRowContainerClassName);
container.style.flexDirection = FlexDirection.Row;
var label = CreateLabel(text, null, PickingMode.Ignore, noResultsHelpClassName);
container.Add(label);
var button = new Button(onClickedCallback)
{
text = buttonText
};
container.Add(button);
Add(container);
return true;
}
void IResultView.Refresh(RefreshFlags flags)
{
if (flags.HasAny(RefreshFlags.QueryCompleted | RefreshFlags.ItemsChanged | RefreshFlags.StructureChanged))
BuildView();
}
void IResultView.OnGroupChanged(string prevGroupId, string newGroupId)
{
BuildView();
}
void IResultView.AddSaveQueryMenuItems(SearchContext context, GenericMenu menu)
{
// Nothing to do
}
protected virtual void Dispose(bool disposing)
{
if (!m_Disposed)
m_Disposed = true;
}
void IDisposable.Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private static void OpenIndexManager()
{
IndexManager.OpenWindow();
}
private void ToggleWantsMore()
{
Emit(SearchEvent.ToggleWantsMore);
}
private void TogglePackages()
{
Emit(SearchEvent.TogglePackages);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchEmptyView.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchEmptyView.cs",
"repo_id": "UnityCsReference",
"token_count": 13354
} | 449 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor.Profiling;
using UnityEngine.Search;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class SearchView : VisualElement, ISearchView, ISearchElement
{
const int k_ResetSelectionIndex = -1;
internal const double resultViewUpdateThrottleDelay = 0.05d;
private int m_ViewId;
private bool m_Disposed = false;
private SearchViewState m_ViewState;
private Action m_AsyncRequestOff = null;
private IResultView m_ResultView;
internal IResultView resultView => m_ResultView;
protected GroupedSearchList m_FilteredItems;
private SearchSelection m_SearchItemSelection;
private readonly List<int> m_Selection = new List<int>();
private int m_DelayedCurrentSelection = k_ResetSelectionIndex;
private bool m_SyncSearch;
private SearchPreviewManager m_PreviewManager;
private int m_TextureCacheSize;
// UITK
private VisualElement m_ResultViewContainer;
public SearchViewState state => m_ViewState;
public float itemSize { get => viewState.itemSize; set => SetItemSize(value); }
public SearchViewState viewState => m_ViewState;
public Rect position => worldBound;
public ISearchList results => m_FilteredItems;
public SearchContext context => m_ViewState.context;
public DisplayMode displayMode => GetDisplayMode();
float ISearchView.itemIconSize { get => itemSize; set => itemSize = value; }
Action<SearchItem, bool> ISearchView.selectCallback => m_ViewState.selectHandler;
Func<SearchItem, bool> ISearchView.filterCallback => m_ViewState.filterHandler;
public Action<SearchItem> trackingCallback => m_ViewState.trackingHandler;
public bool multiselect
{
get => m_ViewState.context.options.HasAny(SearchFlags.Multiselect);
set
{
if (value)
m_ViewState.context.options |= SearchFlags.Multiselect;
else
m_ViewState.context.options &= ~SearchFlags.Multiselect;
}
}
public SearchSelection selection
{
get
{
if (m_SearchItemSelection == null)
m_SearchItemSelection = new SearchSelection(m_Selection, m_FilteredItems);
return m_SearchItemSelection;
}
}
public string currentGroup
{
get => m_FilteredItems.currentGroup;
set
{
var prevGroup = currentGroup;
viewState.groupChanged?.Invoke(context, value, currentGroup);
var selectedItems = m_SearchItemSelection != null ? m_SearchItemSelection.ToArray() : Array.Empty<SearchItem>();
var newSelectedIndices = new int[selectedItems.Length];
viewState.group = value;
m_FilteredItems.currentGroup = value;
resultView?.OnGroupChanged(prevGroup, value);
if (m_SyncSearch && value != null)
NotifySyncSearch(currentGroup, UnityEditor.SearchService.SearchService.SyncSearchEvent.SyncSearch);
RefreshContent(RefreshFlags.GroupChanged);
for (var i = 0; i < selectedItems.Length; ++i)
{
var selectedItem = selectedItems[i];
newSelectedIndices[i] = m_FilteredItems.IndexOf(selectedItem);
}
SetSelection(true, newSelectedIndices, true);
}
}
SearchPreviewManager ISearchView.previewManager => previewManager;
internal SearchPreviewManager previewManager => m_PreviewManager;
bool ISearchView.syncSearch { get => syncSearch; set => syncSearch = value; }
internal bool syncSearch
{
get => m_SyncSearch;
set
{
if (value == m_SyncSearch)
return;
m_SyncSearch = value;
if (value)
NotifySyncSearch(currentGroup, UnityEditor.SearchService.SearchService.SyncSearchEvent.StartSession);
else
NotifySyncSearch(currentGroup, UnityEditor.SearchService.SearchService.SyncSearchEvent.EndSession);
}
}
public bool hideHelpers { get; set; }
int ISearchView.totalCount => totalCount;
public int totalCount => m_FilteredItems.TotalCount;
public IEnumerable<SearchItem> items => m_FilteredItems;
public bool searchInProgress => context.searchInProgress || m_AsyncRequestOff != null;
public SearchView(SearchViewState viewState, int viewId)
{
using (new EditorPerformanceTracker("SearchView.ctor"))
{
m_ViewId = viewId;
m_ViewState = viewState;
m_PreviewManager = new SearchPreviewManager();
context.searchView = context.searchView ?? this;
multiselect = viewState.context?.options.HasAny(SearchFlags.Multiselect) ?? false;
m_FilteredItems = new GroupedSearchList(context, GetDefaultSearchListComparer());
m_FilteredItems.currentGroup = viewState.group;
viewState.itemSize = viewState.itemSize == 0 ? GetDefaultItemSize() : viewState.itemSize;
hideHelpers = m_ViewState.HasFlag(SearchViewFlags.DisableQueryHelpers);
style.flexGrow = 1f;
Refresh();
UpdateView();
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
}
public void Reset()
{
if (context == (m_FilteredItems?.context))
{
m_FilteredItems.Clear();
}
else
{
m_FilteredItems?.Dispose();
m_FilteredItems = new GroupedSearchList(context, GetDefaultSearchListComparer());
m_FilteredItems.currentGroup = viewState.group;
}
}
private ISearchListComparer GetDefaultSearchListComparer()
{
if (context?.searchView?.IsPicker() ?? false)
return new SortByNameComparer();
return null;
}
public void Refresh(RefreshFlags reason = RefreshFlags.Default)
{
// TODO FetchItemProperties (DOTSE-1994): remove this case and always refresh.
if (reason == RefreshFlags.DisplayModeChanged)
{
RefreshContent(reason);
}
else
{
m_AsyncRequestOff?.Invoke();
m_AsyncRequestOff = Utils.CallDelayed(AsyncRefresh, SearchSettings.debounceMs / 1000d);
}
}
private void AsyncRefresh()
{
using (new EditorPerformanceTracker("SearchView.AsyncRefresh"))
{
if (m_SyncSearch)
NotifySyncSearch(currentGroup, UnityEditor.SearchService.SearchService.SyncSearchEvent.SyncSearch);
FetchItems();
}
}
public void FetchItems()
{
m_AsyncRequestOff?.Invoke();
m_AsyncRequestOff = null;
context.ClearErrors();
m_FilteredItems.Clear();
var hostWindow = this.GetSearchHostWindow();
if (hostWindow != null)
OnIncomingItems(context, hostWindow.FetchItems());
if (context.options.HasAny(SearchFlags.Debug))
Debug.Log($"[{context.sessionId}] Running query {context.searchText}");
RefreshContent(RefreshFlags.QueryStarted, false);
SearchService.Request(context, OnIncomingItems, OnQueryRequestFinished);
}
public override string ToString() => context.searchText;
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (m_Disposed)
return;
if (disposing)
{
AssetPreview.DeletePreviewTextureManagerByID(m_ViewId);
m_AsyncRequestOff?.Invoke();
m_AsyncRequestOff = null;
m_ViewState.context?.Dispose();
}
m_Disposed = true;
}
int ISearchView.GetViewId()
{
return m_ViewId;
}
private void OnGeometryChanged(GeometryChangedEvent evt)
{
UpdatePreviewManagerCacheSize();
}
private void SetItemSize(float value)
{
var previousDisplayModeIsList = false;
if (viewState.itemSize > (float)DisplayMode.Compact && viewState.itemSize <= (float)DisplayMode.List)
previousDisplayModeIsList = true;
if (previousDisplayModeIsList && value > (float)DisplayMode.Compact && value <= (float)DisplayMode.List)
return;
viewState.itemSize = value;
if (!UpdateView())
{
// Still report item size changes even if the view didn't change
EmitDisplayModeChanged();
}
}
private void EmitDisplayModeChanged()
{
m_ResultView?.Refresh(RefreshFlags.DisplayModeChanged);
Dispatcher.Emit(SearchEvent.DisplayModeChanged, new SearchEventPayload(this));
}
private bool UpdateView()
{
using (new EditorPerformanceTracker("SearchView.UpdateView"))
{
IResultView nextView = null;
if (results.Count == 0 && displayMode != DisplayMode.Table)
{
if (!m_ResultView?.showNoResultMessage ?? false)
return false;
if (m_ResultView is not SearchEmptyView)
nextView = new SearchEmptyView(this, viewState.flags);
}
else
{
if (itemSize <= 32f)
{
if (!(m_ResultView is SearchListView))
nextView = new SearchListView(this);
}
else if (itemSize >= (float)DisplayMode.Table)
{
if (!(m_ResultView is SearchTableView))
nextView = new SearchTableView(this);
}
else
{
if (!(m_ResultView is SearchGridView))
nextView = new SearchGridView(this);
}
}
if (nextView == null)
return false;
if (nextView is not SearchTableView)
m_FilteredItems.Sort();
m_ResultView = nextView;
UpdatePreviewManagerCacheSize();
if (m_ResultViewContainer != null)
m_ResultViewContainer.RemoveFromHierarchy();
m_ResultViewContainer = m_ResultView as VisualElement;
if (m_ResultViewContainer == null)
throw new NotSupportedException("Result view must be implemented using UTIK");
m_ResultViewContainer.style.flexGrow = 1f;
Add(m_ResultViewContainer);
EmitDisplayModeChanged();
return true;
}
}
private void UpdatePreviewManagerCacheSize()
{
var width = worldBound.width;
var height = worldBound.height;
if (width <= 0 || float.IsNaN(width) || height <= 0 || float.IsNaN(height))
return;
// Note: We approximate how many items could be displayed in the current Rect. We cannot rely on the ResultView to have
// an exact list of visibleItems since get updated AFTER our resize handler and we need to update the Cache size so preview are properly generated.
var potentialVisibleItems = Mathf.Min(m_ResultView.ComputeVisibleItemCapacity(width, height), results.Count);
var newTextureCacheSize = Mathf.Max(potentialVisibleItems * 2 + 30, 128);
if (potentialVisibleItems == 0 || newTextureCacheSize <= m_TextureCacheSize)
return;
m_PreviewManager.poolSize = newTextureCacheSize;
m_TextureCacheSize = newTextureCacheSize;
AssetPreview.SetPreviewTextureCacheSize(m_TextureCacheSize, ((ISearchView)this).GetViewId());
}
private DisplayMode GetDisplayMode()
{
if (itemSize <= (float)DisplayMode.Compact)
return DisplayMode.Compact;
if (itemSize <= (float)DisplayMode.List)
return DisplayMode.List;
if (itemSize >= (float)DisplayMode.Table)
return DisplayMode.Table;
return DisplayMode.Grid;
}
private float GetDefaultItemSize()
{
if (viewState.flags.HasAny(SearchViewFlags.CompactView))
return 1f;
if (viewState.flags.HasAny(SearchViewFlags.GridView))
return (float)DisplayMode.Grid;
if (viewState.flags.HasAny(SearchViewFlags.TableView))
return (float)DisplayMode.Table;
return viewState.itemSize;
}
public void RefreshContent(RefreshFlags flags, bool updateView = true)
{
using (new EditorPerformanceTracker("SearchView.RefreshContent"))
{
if (updateView)
{
UpdateView();
m_ResultView?.Refresh(flags);
}
if (context.debug)
Debug.Log($"[{searchInProgress}] Refresh {flags} for query \"{context.searchText}\": {m_ResultView}");
Dispatcher.Emit(SearchEvent.RefreshContent, new SearchEventPayload(this, flags, context.searchText));
}
}
private void OnIncomingItems(SearchContext context, IEnumerable<SearchItem> items)
{
var countBefore = m_FilteredItems.TotalCount;
if (m_ViewState.filterHandler != null)
items = items.Where(item => m_ViewState.filterHandler(item));
m_FilteredItems.AddItems(items);
if (m_FilteredItems.TotalCount != countBefore)
RefreshContent(RefreshFlags.ItemsChanged);
}
private void OnQueryRequestFinished(SearchContext context)
{
UpdateSelectionFromIds();
Utils.CallDelayed(() => RefreshContent(RefreshFlags.QueryCompleted));
}
private void UpdateSelectionFromIds()
{
if (selection.SyncSelectionIfInvalid())
{
SetSelection(trackSelection: false, selection.indexes.ToArray());
return;
}
if (viewState.selectedIds.Length == 0 || selection.Count != 0)
return;
var indexesToSelect = new List<int>(viewState.selectedIds.Length);
for (int index = 0; index < results.Count; index++)
{
var item = results[index];
if (Array.IndexOf(viewState.selectedIds, item.GetInstanceId()) != -1)
{
indexesToSelect.Add(index);
if (indexesToSelect.Count == viewState.selectedIds.Length)
break;
}
}
if (indexesToSelect.Count > 0)
SetSelection(trackSelection: false, indexesToSelect.ToArray());
}
public void SetSelection(params int[] selection)
{
SetSelection(true, selection);
}
private bool IsItemValid(int index)
{
if (index < 0 || index >= m_FilteredItems.Count)
return false;
return true;
}
private void SetSelection(bool trackSelection, int[] selection, bool forceChange = false)
{
if (!multiselect && selection.Length > 1)
selection = new int[] { selection[selection.Length - 1] };
var selectedIds = new List<int>();
var lastIndexAdded = k_ResetSelectionIndex;
m_Selection.Clear();
m_SearchItemSelection = null;
foreach (var idx in selection)
{
if (!IsItemValid(idx))
continue;
selectedIds.Add(m_FilteredItems[idx].GetInstanceId());
m_Selection.Add(idx);
lastIndexAdded = idx;
}
if (lastIndexAdded != k_ResetSelectionIndex || forceChange)
{
m_SearchItemSelection = null;
viewState.selectedIds = selectedIds.ToArray();
if (trackSelection)
TrackSelection(lastIndexAdded);
Dispatcher.Emit(SearchEvent.SelectionHasChanged, new SearchEventPayload(this));
}
}
private void TrackSelection(int currentSelection)
{
if (!SearchSettings.trackSelection)
return;
m_DelayedCurrentSelection = currentSelection;
EditorApplication.delayCall -= DelayTrackSelection;
EditorApplication.delayCall += DelayTrackSelection;
}
public void SetItems(IEnumerable<SearchItem> items)
{
m_SearchItemSelection = null;
m_FilteredItems.Clear();
m_FilteredItems.AddItems(items);
if (!string.IsNullOrEmpty(context.filterId))
m_FilteredItems.AddGroup(context.providers.First());
SetSelection(trackSelection: false, m_Selection.ToArray());
}
internal void DelayTrackSelection()
{
if (m_FilteredItems.Count == 0)
return;
if (!IsItemValid(m_DelayedCurrentSelection))
return;
var selectedItem = m_FilteredItems[m_DelayedCurrentSelection];
if (trackingCallback == null)
selectedItem?.provider?.trackSelection?.Invoke(selectedItem, context);
else
trackingCallback(selectedItem);
m_DelayedCurrentSelection = k_ResetSelectionIndex;
}
public void ShowItemContextualMenu(SearchItem item, Rect contextualActionPosition)
{
if (IsPicker())
return;
SearchAnalytics.SendEvent(viewState.sessionId, SearchAnalytics.GenericEventType.QuickSearchShowActionMenu, item.provider.id);
var menu = new GenericMenu();
var shortcutIndex = 0;
var useSelection = context?.selection?.Any(e => string.Equals(e.id, item.id, StringComparison.OrdinalIgnoreCase)) ?? false;
var currentSelection = useSelection ? context.selection : new SearchSelection(new[] { item });
foreach (var action in item.provider.actions.Where(a => a.enabled?.Invoke(currentSelection) ?? true))
{
var itemName = !string.IsNullOrWhiteSpace(action.content.text) ? action.content.text : action.content.tooltip;
if (shortcutIndex == 0)
itemName += " _enter";
else if (shortcutIndex == 1)
itemName += " _&enter";
menu.AddItem(new GUIContent(itemName, action.content.image), false, () => ExecuteAction(action, currentSelection.ToArray()));
++shortcutIndex;
}
menu.AddSeparator("");
if (SearchSettings.searchItemFavorites.Contains(item.id))
menu.AddItem(new GUIContent("Remove from Favorites"), false, () => SearchSettings.RemoveItemFavorite(item));
else
menu.AddItem(new GUIContent("Add to Favorites"), false, () => SearchSettings.AddItemFavorite(item));
if (contextualActionPosition == default)
menu.ShowAsContext();
else
menu.DropDown(contextualActionPosition);
}
internal static SearchAction GetSelectAction(SearchSelection selection, IEnumerable<SearchItem> items)
{
var provider = (items ?? selection).First().provider;
var selectAction = provider.actions.FirstOrDefault(a => string.Equals(a.id, "select", StringComparison.Ordinal));
if (selectAction == null)
{
selectAction = GetDefaultAction(selection, items);
}
return selectAction;
}
internal static SearchAction GetDefaultAction(SearchSelection selection, IEnumerable<SearchItem> items)
{
var provider = (items ?? selection).First().provider;
return provider.actions.FirstOrDefault();
}
internal static SearchAction GetSecondaryAction(SearchSelection selection, IEnumerable<SearchItem> items)
{
var provider = (items ?? selection).First().provider;
return provider.actions.Count > 1 ? provider.actions[1] : GetDefaultAction(selection, items);
}
void ISearchView.ExecuteSelection()
{
ExecuteAction(GetDefaultAction(selection, selection), selection.ToArray(), endSearch: false);
}
public void ExecuteAction(SearchAction action, SearchItem[] items, bool endSearch = false)
{
var item = items.LastOrDefault();
if (item == null)
return;
if (m_ViewState.selectHandler != null && items.Length > 0)
{
m_ViewState.selectHandler(items[0], false);
m_ViewState.selectHandler = null;
if (IsPicker())
endSearch = true;
}
else
{
if (action == null)
action = GetDefaultAction(selection, items);
SendSearchEvent(item, action);
if (endSearch)
EditorApplication.delayCall -= DelayTrackSelection;
if (action.handler != null && items.Length == 1)
action.handler(item);
else if (action.execute != null)
action.execute(items);
else
action.handler?.Invoke(item);
}
var searchWindow = this.GetHostWindow() as SearchWindow;
if (searchWindow != null && endSearch && (action?.closeWindowAfterExecution ?? true) && !searchWindow.docked)
searchWindow.CloseSearchWindow();
}
private void SendSearchEvent(SearchItem item, SearchAction action = null)
{
var evt = new SearchAnalytics.SearchEvent();
if (item != null)
evt.Success(item, action);
if (evt.success)
{
evt.Done();
}
evt.searchText = context.searchText;
evt.useQueryBuilder = viewState.queryBuilderEnabled;
SearchAnalytics.SendSearchEvent(evt, context);
}
public void SetSearchText(string searchText, TextCursorPlacement moveCursor)
{
if (string.Equals(context.searchText, searchText, StringComparison.Ordinal))
return;
var isEquivalent = string.Equals(context.searchText.Trim(), searchText.Trim(), StringComparison.Ordinal);
context.searchText = searchText;
// Don't trigger a refresh if the text is equivalent (i.e. only added new trailing spaces)
if (!isEquivalent)
Refresh(RefreshFlags.ItemsChanged);
}
void ISearchView.SetSearchText(string searchText, TextCursorPlacement moveCursor, int cursorInsertPosition)
{
throw new NotSupportedException("Cursor cannot be set for this control.");
}
public void AddSelection(params int[] selection)
{
if (!multiselect && m_Selection.Count == 1)
throw new Exception("Multi selection is not allowed.");
foreach (var idx in selection)
{
if (!IsItemValid(idx))
continue;
if (m_Selection.Contains(idx))
{
m_Selection.Remove(idx);
}
else
{
m_Selection.Add(idx);
}
}
SetSelection(true, m_Selection.ToArray());
}
void ISearchView.FocusSearch() => m_ResultViewContainer.Focus();
void ISearchView.SelectSearch() => m_ResultViewContainer.Focus();
void ISearchView.Repaint() => MarkDirtyRepaint();
void ISearchView.Close() => throw new NotSupportedException("Cannot close search view element. Close the host window instead.");
void ISearchView.SetColumns(IEnumerable<SearchColumn> columns) => throw new NotSupportedException();
public int GetItemCount(IEnumerable<string> providerIds)
{
return m_FilteredItems.GetItemCount(providerIds);
}
public IEnumerable<IGroup> EnumerateGroups()
{
return EnumerateGroups(!viewState.hideAllGroup);
}
public IEnumerable<IGroup> EnumerateGroups(bool showAll)
{
var groups = m_FilteredItems.EnumerateGroups(showAll);
if (showAll)
groups = groups.Where(g => !string.Equals(g.id, "default", StringComparison.Ordinal));
return groups;
}
public IGroup GetGroupById(string groupId)
{
return m_FilteredItems.GetGroupById(groupId);
}
public int IndexOf(SearchItem item)
{
return m_FilteredItems.IndexOf(item);
}
public bool Add(SearchItem item)
{
if (m_FilteredItems.Contains(item))
return false;
m_FilteredItems.Add(item);
return true;
}
IEnumerable<SearchQueryError> ISearchView.GetAllVisibleErrors() => GetAllVisibleErrors();
internal IEnumerable<SearchQueryError> GetAllVisibleErrors()
{
var visibleProviders = EnumerateGroups().Select(g => g.id).ToArray();
var defaultProvider = SearchService.GetDefaultProvider();
return context.GetAllErrors().Where(e => visibleProviders.Contains(e.provider.type) || e.provider.type == defaultProvider.type);
}
public bool IsPicker()
{
var window = this.GetSearchHostWindow();
return window != null && window.IsPicker();
}
IEnumerable<IGroup> ISearchView.EnumerateGroups()
{
return EnumerateGroups();
}
private void NotifySyncSearch(string groupId, UnityEditor.SearchService.SearchService.SyncSearchEvent evt)
{
var syncViewId = groupId;
switch (groupId)
{
case "asset":
syncViewId = typeof(ProjectSearchEngine).FullName;
break;
case "scene":
syncViewId = typeof(SceneSearchEngine).FullName;
break;
}
UnityEditor.SearchService.SearchService.NotifySyncSearchChanged(evt, syncViewId, context.searchText);
}
public void SetupColumns(IList<SearchField> fields)
{
if (m_ResultView is SearchTableView tableView)
tableView.SetupColumns(fields);
}
void ISearchView.SetupColumns(IList<SearchField> fields)
{
SetupColumns(fields);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchView.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchView.cs",
"repo_id": "UnityCsReference",
"token_count": 13326
} | 450 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace UnityEditor.SceneTemplate
{
internal static class ReferenceUtils
{
public static void GetSceneDependencies(SceneAsset scene, List<Object> dependencies, HashSet<string> editorOnlyDependencies = null)
{
var path = AssetDatabase.GetAssetPath(scene);
GetSceneDependencies(path, dependencies, editorOnlyDependencies);
}
public static void GetSceneDependencies(Scene scene, List<Object> dependencies, HashSet<string> editorOnlyDependencies = null)
{
GetSceneDependencies(scene.path, dependencies, editorOnlyDependencies);
}
public static void GetSceneDependencies(string scenePath, List<Object> dependencies, HashSet<string> editorOnlyDependencies = null)
{
var dependencyPaths = AssetDatabase.GetDependencies(scenePath);
// Convert the dependency paths to assets
// Remove scene from dependencies
foreach (var dependencyPath in dependencyPaths)
{
if (dependencyPath.Equals(scenePath))
continue;
var dependencyType = AssetDatabase.GetMainAssetTypeAtPath(dependencyPath);
if (dependencyType == null)
continue;
if (dependencyType == typeof(MonoScript))
{
var scriptDependencies = AssetDatabase.GetDependencies(dependencyPath);
foreach(var scriptDepPath in scriptDependencies)
{
if (scriptDepPath != dependencyPath)
editorOnlyDependencies.Add(scriptDepPath);
}
}
var typeInfo = SceneTemplateProjectSettings.Get().GetDependencyInfo(dependencyType);
if (typeInfo.ignore)
continue;
var obj = AssetDatabase.LoadAssetAtPath(dependencyPath, dependencyType);
dependencies.Add(obj);
}
}
public static void RemapAssetReferences(Dictionary<string, string> pathMap, Dictionary<int, int> idMap = null)
{
var objects = new List<Object>();
foreach (var dstPath in pathMap.Values)
{
// In case of subscene, we cannot call LoadAllAssetsAtPath on it. It creates loading error.
if (dstPath.EndsWith(".unity"))
continue;
var assetsInDstPath = AssetDatabase.LoadAllAssetsAtPath(dstPath);
foreach (var o in assetsInDstPath)
{
if (o == null)
continue;
objects.Add(o);
}
}
EditorUtility.RemapAssetReferences(objects.ToArray(), pathMap, idMap);
}
}
}
| UnityCsReference/Modules/SceneTemplateEditor/ReferenceUtils.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneTemplateEditor/ReferenceUtils.cs",
"repo_id": "UnityCsReference",
"token_count": 1411
} | 451 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.Overlays
{
class DropdownToggle : BaseField<bool>
{
public new static readonly string ussClassName = "unity-dropdown-toggle";
public static readonly string dropdownClassName = ussClassName + "__dropdown";
public static readonly string toggleClassName = ussClassName + "__toggle";
public static readonly string toggleIconClassName = ussClassName + "__icon";
readonly Button m_Toggle;
readonly Button m_DropdownButton;
public Button dropdownButton => m_DropdownButton;
public DropdownToggle() : this(null) {}
public DropdownToggle(string label) : base(label)
{
AddToClassList(ussClassName);
m_Toggle = new Button(ToggleValue);
m_Toggle.AddToClassList(toggleClassName);
var icon = new VisualElement();
icon.AddToClassList(toggleIconClassName);
icon.pickingMode = PickingMode.Ignore;
m_Toggle.Add(icon);
m_DropdownButton = new Button();
m_DropdownButton.AddToClassList(dropdownClassName);
var arrow = new VisualElement();
arrow.AddToClassList("unity-icon-arrow");
arrow.pickingMode = PickingMode.Ignore;
m_DropdownButton.Add(arrow);
Add(m_Toggle);
Add(m_DropdownButton);
}
void ToggleValue()
{
value = !value;
}
public override void SetValueWithoutNotify(bool newValue)
{
if (newValue)
{
m_Toggle.pseudoStates |= PseudoStates.Checked;
m_DropdownButton.pseudoStates |= PseudoStates.Checked;
}
else
{
m_Toggle.pseudoStates &= ~PseudoStates.Checked;
m_DropdownButton.pseudoStates &= ~PseudoStates.Checked;
}
base.SetValueWithoutNotify(newValue);
}
}
}
| UnityCsReference/Modules/SceneView/DropdownToggle.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneView/DropdownToggle.cs",
"repo_id": "UnityCsReference",
"token_count": 980
} | 452 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.ShaderFoundry
{
internal enum DataType : ushort
{
// THIS ENUM MUST BE KEPT IN SYNC WITH THE ENUM IN DataType.h
Unknown = 0,
// Special types
Array = 1,
String,
Linker,
StartStaticSized,
// Static sized types
ShaderAttributeParameter = StartStaticSized,
ShaderAttribute,
RenderStateDescriptor,
DefineDescriptor,
IncludeDescriptor,
KeywordDescriptor,
PragmaDescriptor,
TagDescriptor,
FunctionParameter,
ShaderFunction,
StructField,
ShaderType,
BlockVariable,
Block,
CustomizationPoint,
TemplatePass,
Template,
TemplateInstance,
ShaderDependency,
ShaderCustomEditor,
PackageRequirement,
CopyRule,
LinkOverride,
LinkAccessor,
LinkElement,
BlockSequenceElement,
CustomizationPointImplementation,
StageDescription,
BlockShaderInterface,
BlockShader,
InterfaceRegistrationStatement,
RegisterTemplatesWithInterface,
Namespace,
// THIS ENUM MUST BE KEPT IN SYNC WITH THE ENUM IN DataType.h -- ALSO ADD THE TYPE MAPPING TO Initialize()
// ALSO ADD THE TYPE MAPPING TO DataTypeStatic.Initialize()
};
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DataType.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DataType.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 664
} | 453 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
namespace UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/PackageRequirement.h")]
internal struct PackageRequirementInternal : IInternalType<PackageRequirementInternal>
{
internal FoundryHandle m_NameHandle;
internal FoundryHandle m_VersionHandle;
internal static extern PackageRequirementInternal Invalid();
internal extern bool IsValid();
// IInternalType
PackageRequirementInternal IInternalType<PackageRequirementInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct PackageRequirement : IEquatable<PackageRequirement>, IPublicType<PackageRequirement>
{
// data members
readonly ShaderContainer container;
internal readonly FoundryHandle handle;
readonly PackageRequirementInternal packageRequirement;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
PackageRequirement IPublicType<PackageRequirement>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new PackageRequirement(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null) && handle.IsValid && (packageRequirement.IsValid());
public string Name => container?.GetString(packageRequirement.m_NameHandle) ?? string.Empty;
public string Version => container?.GetString(packageRequirement.m_VersionHandle) ?? string.Empty;
// private
internal PackageRequirement(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out packageRequirement);
}
public static PackageRequirement Invalid => new PackageRequirement(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is PackageRequirement other && this.Equals(other);
public bool Equals(PackageRequirement other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator==(PackageRequirement lhs, PackageRequirement rhs) => lhs.Equals(rhs);
public static bool operator!=(PackageRequirement lhs, PackageRequirement rhs) => !lhs.Equals(rhs);
public class Builder
{
internal ShaderContainer container;
internal string name;
internal string version;
public Builder(ShaderContainer container, string name)
{
this.container = container;
this.name = name;
this.version = null;
}
public Builder(ShaderContainer container, string name, string version)
{
this.container = container;
this.name = name;
this.version = version;
}
public PackageRequirement Build()
{
var packageRequirementInternal = new PackageRequirementInternal();
packageRequirementInternal.m_NameHandle = container.AddString(name);
packageRequirementInternal.m_VersionHandle = container.AddString(version);
var returnHandle = container.Add(packageRequirementInternal);
return new PackageRequirement(container, returnHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PackageRequirement.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PackageRequirement.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1428
} | 454 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
namespace UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/TagDescriptor.h")]
internal struct TagDescriptorInternal : IInternalType<TagDescriptorInternal>
{
internal FoundryHandle m_NameHandle;
internal FoundryHandle m_ValueHandle;
internal extern static TagDescriptorInternal Invalid();
internal extern bool IsValid();
// IInternalType
TagDescriptorInternal IInternalType<TagDescriptorInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct TagDescriptor : IEquatable<TagDescriptor>, IPublicType<TagDescriptor>
{
// data members
readonly ShaderContainer container;
readonly TagDescriptorInternal descriptor;
internal readonly FoundryHandle handle;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
TagDescriptor IPublicType<TagDescriptor>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new TagDescriptor(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null && descriptor.IsValid());
public string Name => Container?.GetString(descriptor.m_NameHandle) ?? string.Empty;
public string Value => Container?.GetString(descriptor.m_ValueHandle) ?? string.Empty;
// private
internal TagDescriptor(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out descriptor);
}
public static TagDescriptor Invalid => new TagDescriptor(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is TagDescriptor other && this.Equals(other);
public bool Equals(TagDescriptor other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator==(TagDescriptor lhs, TagDescriptor rhs) => lhs.Equals(rhs);
public static bool operator!=(TagDescriptor lhs, TagDescriptor rhs) => !lhs.Equals(rhs);
public class Builder
{
ShaderContainer container;
string name;
string value;
public ShaderContainer Container => container;
public Builder(ShaderContainer container, string name, string value)
{
this.container = container;
this.name = name;
this.value = value;
}
public TagDescriptor Build()
{
var descriptor = new TagDescriptorInternal();
descriptor.m_NameHandle = container.AddString(name);
descriptor.m_ValueHandle = container.AddString(value);
var resultHandle = container.Add(descriptor);
return new TagDescriptor(container, resultHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/TagDescriptor.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/TagDescriptor.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1332
} | 455 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
namespace UnityEditor.ShortcutManagement
{
interface IDiscoveryInvalidShortcutReporter
{
void ReportReservedIdentifierPrefixConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingIdentifierPrefix, string reservedPrefix);
void ReportReservedDisplayNamePrefixConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingDisplayNamePrefix, string reservedPrefix);
void ReportIdentifierConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingIdentifier);
void ReportDisplayNameConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingDisplayName);
void ReportInvalidContext(IShortcutEntryDiscoveryInfo discoveryInfoWithInvalidContext);
void ReportInvalidBinding(IShortcutEntryDiscoveryInfo discoveryInfoWithInvalidBinding, string invalidBindingMessage);
}
class DiscoveryInvalidShortcutReporter : IDiscoveryInvalidShortcutReporter
{
static void LogWarning(IShortcutEntryDiscoveryInfo discoveryInfo, string summary, string detail)
{
var filePath = discoveryInfo.GetFilePath();
if (filePath == null)
Debug.LogWarning($"{summary}\n{detail}");
else
Debug.LogWarning($"{filePath}({discoveryInfo.GetLineNumber()}): {summary}\n{detail}");
}
private void ReportReservedPrefixConflict(IShortcutEntryDiscoveryInfo conflictingInfo, string conflictType, string conflictingText, string reservedPrefix)
{
var fullMemberName = conflictingInfo.GetFullMemberName();
var summary = $"Ignoring shortcut attribute with {conflictType} using reserved prefix \"{conflictingText}\".";
var detail = $"Shortcut attribute on {fullMemberName} is using {conflictType} \"{conflictingText}\" with reserved prefix \"{reservedPrefix}\".";
LogWarning(conflictingInfo, summary, detail);
}
public void ReportReservedIdentifierPrefixConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingIdentifierPrefix, string reservedPrefix)
{
var shortcutEntry = discoveryInfoWithConflictingIdentifierPrefix.GetShortcutEntry();
ReportReservedPrefixConflict(discoveryInfoWithConflictingIdentifierPrefix, "identifier", shortcutEntry.identifier.path, reservedPrefix);
}
public void ReportReservedDisplayNamePrefixConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingDisplayNamePrefix, string reservedPrefix)
{
var shortcutEntry = discoveryInfoWithConflictingDisplayNamePrefix.GetShortcutEntry();
ReportReservedPrefixConflict(discoveryInfoWithConflictingDisplayNamePrefix, "display name", shortcutEntry.displayName, reservedPrefix);
}
private void ReportConflict(IShortcutEntryDiscoveryInfo conflictingInfo, string conflictType, string conflictingText)
{
var fullMemberName = conflictingInfo.GetFullMemberName();
var summary = $"Ignoring shortcut attribute with duplicate {conflictType} \"{conflictingText}\".";
var detail = $"Shortcut attribute on {fullMemberName} is using {conflictType} \"{conflictingText}\" which is already in use by another shortcut attribute.";
LogWarning(conflictingInfo, summary, detail);
}
public void ReportIdentifierConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingIdentifier)
{
var shortcutEntry = discoveryInfoWithConflictingIdentifier.GetShortcutEntry();
ReportConflict(discoveryInfoWithConflictingIdentifier, "identifier", shortcutEntry.identifier.path);
}
public void ReportDisplayNameConflict(IShortcutEntryDiscoveryInfo discoveryInfoWithConflictingDisplayName)
{
var shortcutEntry = discoveryInfoWithConflictingDisplayName.GetShortcutEntry();
ReportConflict(discoveryInfoWithConflictingDisplayName, "display name", shortcutEntry.displayName);
}
public void ReportInvalidContext(IShortcutEntryDiscoveryInfo discoveryInfoWithInvalidContext)
{
var shortcutEntry = discoveryInfoWithInvalidContext.GetShortcutEntry();
var context = shortcutEntry.context;
if (context == typeof(ContextManager.GlobalContext))
throw new ArgumentException("Context type is valid", nameof(discoveryInfoWithInvalidContext));
var isEditorWindow = typeof(EditorWindow).IsAssignableFrom(context);
var isIShortcutToolContext = typeof(IShortcutContext).IsAssignableFrom(context);
string detail;
if (isEditorWindow)
{
if (context == typeof(EditorWindow))
detail = $"The context type cannot be {typeof(EditorWindow).FullName}.";
else if (isIShortcutToolContext)
detail = $"The context type cannot both derive from {typeof(EditorWindow).FullName} and implement {typeof(IShortcutContext).FullName}.";
else
throw new ArgumentException("Context type is valid", nameof(discoveryInfoWithInvalidContext));
}
else if (isIShortcutToolContext)
{
if (context == typeof(IShortcutContext))
detail = $"The context type cannot be {typeof(IShortcutContext).FullName}.";
else
throw new ArgumentException("Context type is valid", nameof(discoveryInfoWithInvalidContext));
}
else
detail = $"The context type must either be null, derive from {typeof(EditorWindow).FullName}, or implement {typeof(IShortcutContext).FullName}.";
var fullMemberName = discoveryInfoWithInvalidContext.GetFullMemberName();
var summary = $"Ignoring shortcut attribute with invalid context type {context.FullName} on {fullMemberName}.";
LogWarning(discoveryInfoWithInvalidContext, summary, detail);
}
public void ReportInvalidBinding(IShortcutEntryDiscoveryInfo discoveryInfoWithInvalidBinding, string invalidBindingMessage)
{
var fullMemberName = discoveryInfoWithInvalidBinding.GetFullMemberName();
var summary = $"Ignoring shortcut attribute with invalid binding on {fullMemberName}.";
var detail = $"{invalidBindingMessage}.";
LogWarning(discoveryInfoWithInvalidBinding, summary, detail);
}
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/DiscoveryInvalidShortcutReporter.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/DiscoveryInvalidShortcutReporter.cs",
"repo_id": "UnityCsReference",
"token_count": 2421
} | 456 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace UnityEditor.ShortcutManagement
{
public interface IShortcutManager
{
event Action<ActiveProfileChangedEventArgs> activeProfileChanged;
string activeProfileId { get; set; }
IEnumerable<string> GetAvailableProfileIds();
bool IsProfileIdValid(string profileId);
bool IsProfileReadOnly(string profileId);
void CreateProfile(string profileId);
void DeleteProfile(string profileId);
void RenameProfile(string profileId, string newProfileId);
event Action<ShortcutBindingChangedEventArgs> shortcutBindingChanged;
IEnumerable<string> GetAvailableShortcutIds();
ShortcutBinding GetShortcutBinding(string shortcutId);
void RebindShortcut(string shortcutId, ShortcutBinding binding);
void ClearShortcutOverride(string shortcutId);
bool IsShortcutOverridden(string shortcutId);
}
public struct ActiveProfileChangedEventArgs
{
public string previousActiveProfileId { get; }
public string currentActiveProfileId { get; }
public ActiveProfileChangedEventArgs(string previousActiveProfileId, string currentActiveProfileId)
{
this.previousActiveProfileId = previousActiveProfileId;
this.currentActiveProfileId = currentActiveProfileId;
}
}
public struct ShortcutBindingChangedEventArgs
{
public string shortcutId { get; }
public ShortcutBinding oldBinding { get; }
public ShortcutBinding newBinding { get; }
public ShortcutBindingChangedEventArgs(string shortcutId, ShortcutBinding oldBinding, ShortcutBinding newBinding)
{
this.shortcutId = shortcutId;
this.oldBinding = oldBinding;
this.newBinding = newBinding;
}
}
public static class ShortcutManager
{
public const string defaultProfileId = "Default";
public static IShortcutManager instance { get; } = new ShortcutManagerImplementation(ShortcutIntegration.instance.profileManager);
public static void RegisterTag(string tag) => ShortcutIntegration.instance.contextManager.RegisterTag(tag);
public static void RegisterTag(Enum e) => ShortcutIntegration.instance.contextManager.RegisterTag(e);
public static void UnregisterTag(string tag) => ShortcutIntegration.instance.contextManager.UnregisterTag(tag);
public static void UnregisterTag(Enum e) => ShortcutIntegration.instance.contextManager.UnregisterTag(e);
public static void RegisterContext(IShortcutContext context) => ShortcutIntegration.instance.contextManager.RegisterToolContext(context);
public static void UnregisterContext(IShortcutContext context) => ShortcutIntegration.instance.contextManager.DeregisterToolContext(context);
}
class ShortcutManagerImplementation : IShortcutManager
{
IShortcutProfileManager m_ShortcutProfileManager;
internal ShortcutManagerImplementation(IShortcutProfileManager profileManager)
{
m_ShortcutProfileManager = profileManager;
// TODO: Not sure if these events mean the same
m_ShortcutProfileManager.activeProfileChanged += RaiseActiveProfileChanged;
m_ShortcutProfileManager.shortcutBindingChanged += RaiseShortcutBindingChanged;
}
void RaiseActiveProfileChanged(IShortcutProfileManager shortcutProfileManager, ShortcutProfile oldActiveProfile, ShortcutProfile newActiveProfile)
{
var oldActiveProfileId = oldActiveProfile?.id ?? ShortcutManager.defaultProfileId;
var newActiveProfileId = newActiveProfile?.id ?? ShortcutManager.defaultProfileId;
var eventArgs = new ActiveProfileChangedEventArgs(oldActiveProfileId, newActiveProfileId);
activeProfileChanged?.Invoke(eventArgs);
}
void RaiseShortcutBindingChanged(IShortcutProfileManager shortcutProfileManager, Identifier identifier, ShortcutBinding oldBinding, ShortcutBinding newBinding)
{
var eventArgs = new ShortcutBindingChangedEventArgs(identifier.path, oldBinding, newBinding);
shortcutBindingChanged?.Invoke(eventArgs);
}
public event Action<ActiveProfileChangedEventArgs> activeProfileChanged;
public string activeProfileId
{
get { return m_ShortcutProfileManager.activeProfile?.id ?? ShortcutManager.defaultProfileId; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value == ShortcutManager.defaultProfileId)
m_ShortcutProfileManager.activeProfile = null;
else
{
var profile = m_ShortcutProfileManager.GetProfileById(value);
if (profile == null)
throw new ArgumentException("Profile not available");
m_ShortcutProfileManager.activeProfile = profile;
}
}
}
public IEnumerable<string> GetAvailableProfileIds()
{
yield return ShortcutManager.defaultProfileId;
foreach (var id in m_ShortcutProfileManager.GetProfiles().Select(profile => profile.id))
yield return id;
}
public bool IsProfileIdValid(string profileId)
{
if (profileId == null)
{
throw new ArgumentNullException(nameof(profileId));
}
return !profileId.Equals(string.Empty) && profileId.Length <= 127 && profileId.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
}
public bool IsProfileReadOnly(string profileId)
{
if (profileId == null)
throw new ArgumentNullException(nameof(profileId));
if (profileId == ShortcutManager.defaultProfileId)
return true;
if (m_ShortcutProfileManager.GetProfileById(profileId) == null)
throw new ArgumentException("Profile not available", nameof(profileId));
return false;
}
public void CreateProfile(string profileId)
{
if (profileId == null)
throw new ArgumentNullException(nameof(profileId));
if (profileId == ShortcutManager.defaultProfileId)
throw new ArgumentException("Duplicate profile id", nameof(profileId));
switch (m_ShortcutProfileManager.CanCreateProfile(profileId))
{
case CanCreateProfileResult.Success:
m_ShortcutProfileManager.CreateProfile(profileId);
break;
case CanCreateProfileResult.InvalidProfileId:
throw new ArgumentException("Invalid profile id", nameof(profileId));
case CanCreateProfileResult.DuplicateProfileId:
throw new ArgumentException("Duplicate profile id", nameof(profileId));
default:
throw new ArgumentOutOfRangeException();
}
}
public void DeleteProfile(string profileId)
{
if (IsProfileReadOnly(profileId))
throw new ArgumentException("Cannot delete read-only profile", nameof(profileId));
var profile = m_ShortcutProfileManager.GetProfileById(profileId);
switch (m_ShortcutProfileManager.CanDeleteProfile(profile))
{
case CanDeleteProfileResult.Success:
m_ShortcutProfileManager.DeleteProfile(profile);
break;
case CanDeleteProfileResult.ProfileHasDependencies:
// Should not never happen through use of IShortcutManager API
throw new ArgumentException("Profile has dependencies", nameof(profileId));
default:
throw new ArgumentOutOfRangeException();
}
}
public void RenameProfile(string profileId, string newProfileId)
{
if (IsProfileReadOnly(profileId))
throw new ArgumentException("Cannot rename read-only profile", nameof(profileId));
if (newProfileId == ShortcutManager.defaultProfileId)
throw new ArgumentException("Duplicate profile id", nameof(newProfileId));
var profile = m_ShortcutProfileManager.GetProfileById(profileId);
switch (m_ShortcutProfileManager.CanRenameProfile(profile, newProfileId))
{
case CanRenameProfileResult.Success:
m_ShortcutProfileManager.RenameProfile(profile, newProfileId);
break;
case CanRenameProfileResult.InvalidProfileId:
throw new ArgumentException("Profile not available", nameof(profileId));
case CanRenameProfileResult.DuplicateProfileId:
throw new ArgumentException("Duplicate profile id", nameof(newProfileId));
default:
throw new ArgumentOutOfRangeException();
}
}
public event Action<ShortcutBindingChangedEventArgs> shortcutBindingChanged;
public IEnumerable<string> GetAvailableShortcutIds()
{
return m_ShortcutProfileManager.GetAllShortcuts().Select(entry => entry.identifier.path);
}
public ShortcutBinding GetShortcutBinding(string shortcutId)
{
if (shortcutId == null)
throw new ArgumentNullException(nameof(shortcutId) + ":" + shortcutId);
var shortcutEntries = m_ShortcutProfileManager.GetAllShortcuts();
var shortcutEntry = shortcutEntries.FirstOrDefault(entry => entry.identifier.path == shortcutId);
if (shortcutEntry == null)
{
if (MenuService.IsShortcutAvailableInMode(shortcutId))
throw new ArgumentException("Shortcut not available", nameof(shortcutId) + ": " + shortcutId);
else
return ShortcutBinding.empty;
}
return new ShortcutBinding(shortcutEntry.combinations);
}
public void RebindShortcut(string shortcutId, ShortcutBinding binding)
{
if (shortcutId == null)
throw new ArgumentNullException(nameof(shortcutId) + ":" + shortcutId);
var shortcutEntries = m_ShortcutProfileManager.GetAllShortcuts();
var shortcutEntry = shortcutEntries.FirstOrDefault(entry => entry.identifier.path == shortcutId);
if (shortcutEntry == null)
throw new ArgumentException("Shortcut not available", nameof(shortcutId) + ": " + shortcutId);
if (IsProfileReadOnly(activeProfileId))
throw new InvalidOperationException("Cannot rebind shortcut on read-only profile");
m_ShortcutProfileManager.ModifyShortcutEntry(shortcutEntry.identifier, binding.keyCombinationSequence);
}
public void ClearShortcutOverride(string shortcutId)
{
if (shortcutId == null)
throw new ArgumentNullException(nameof(shortcutId) + ": " + shortcutId);
var shortcutEntries = m_ShortcutProfileManager.GetAllShortcuts();
var shortcutEntry = shortcutEntries.FirstOrDefault(entry => entry.identifier.path == shortcutId);
if (shortcutEntry == null)
throw new ArgumentException("Shortcut not available", nameof(shortcutId) + ": " + shortcutId);
if (IsProfileReadOnly(activeProfileId))
throw new InvalidOperationException("Cannot clear shortcut override on read-only profile");
m_ShortcutProfileManager.ClearShortcutOverride(shortcutEntry.identifier);
}
public bool IsShortcutOverridden(string shortcutId)
{
if (shortcutId == null)
throw new ArgumentNullException(nameof(shortcutId) + ": " + shortcutId);
var shortcutEntries = m_ShortcutProfileManager.GetAllShortcuts();
var shortcutEntry = shortcutEntries.FirstOrDefault(entry => entry.identifier.path == shortcutId);
if (shortcutEntry == null)
throw new ArgumentException("Shortcut not available", nameof(shortcutId) + ": " + shortcutId);
return shortcutEntry.overridden;
}
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManager.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManager.cs",
"repo_id": "UnityCsReference",
"token_count": 5095
} | 457 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Bindings;
namespace UnityEngine
{
[RequireComponent(typeof(Camera))]
[NativeHeader("Modules/Streaming/StreamingController.h")]
public class StreamingController : Behaviour
{
extern public float streamingMipmapBias { get; set; }
extern public void SetPreloading(float timeoutSeconds = 0.0f, bool activateCameraOnTimeout = false, Camera disableCameraCuttingFrom = null);
extern public void CancelPreloading();
extern public bool IsPreloading();
}
}
| UnityCsReference/Modules/Streaming/ScriptBindings/StreamingController.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Streaming/ScriptBindings/StreamingController.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 218
} | 458 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UsedByNativeCodeAttribute = UnityEngine.Scripting.UsedByNativeCodeAttribute;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnityEngine.Subsystems
{
[NativeType(Header = "Modules/Subsystems/Example/ExampleSubsystem.h")]
[UsedByNativeCode]
public class ExampleSubsystem : IntegratedSubsystem<ExampleSubsystemDescriptor>
{
public extern void PrintExample();
public extern bool GetBool();
new internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(ExampleSubsystem exampleSubsystem) => exampleSubsystem.m_Ptr;
}
}
}
| UnityCsReference/Modules/Subsystems/Example/ExampleSubsystem.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Subsystems/Example/ExampleSubsystem.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 281
} | 459 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.SubsystemsImplementation
{
public abstract class SubsystemProvider
{
public bool running => m_Running;
internal bool m_Running;
}
public abstract class SubsystemProvider<TSubsystem> : SubsystemProvider
where TSubsystem : SubsystemWithProvider, new()
{
protected internal virtual bool TryInitialize() => true;
public abstract void Start();
public abstract void Stop();
public abstract void Destroy();
}
}
| UnityCsReference/Modules/Subsystems/SubsystemProvider.cs/0 | {
"file_path": "UnityCsReference/Modules/Subsystems/SubsystemProvider.cs",
"repo_id": "UnityCsReference",
"token_count": 217
} | 460 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(Brush))]
internal class BrushEditor : Editor
{
[SerializeField]
protected Vector2 m_Pos;
SerializedProperty m_Mask;
SerializedProperty m_Falloff;
SerializedProperty m_RadiusScale;
SerializedProperty m_BlackWhiteRemapMin;
SerializedProperty m_BlackWhiteRemapMax;
SerializedProperty m_InvertRemapRange;
bool m_HasChanged = true;
Texture2D m_PreviewTexture = null;
static class Styles
{
public static GUIContent readonlyText = EditorGUIUtility.TrTextContent("One or more selected Brushes are read-only.");
public static GUIContent maskTexture = EditorGUIUtility.TrTextContent("Mask Texture", "Texture Red channel controls the shape of the Brush");
public static GUIContent falloff = EditorGUIUtility.TrTextContent("Falloff Curve", "Controls the Brush falloff curve, over the distance from the center of the Brush.");
public static GUIContent radiusScale = EditorGUIUtility.TrTextContent("Falloff Radius Scale", "Controls the radius of the falloff curve.");
public static GUIContent remap = EditorGUIUtility.TrTextContent("Brush Remap", "Remaps the grayscale values of the Brush");
public static GUIContent remapInvert = EditorGUIUtility.TrTextContent("Brush Invert", "Inverts the Brush shape, swapping black and white");
}
protected virtual void OnEnable()
{
m_Mask = serializedObject.FindProperty("m_Mask");
m_Falloff = serializedObject.FindProperty("m_Falloff");
m_RadiusScale = serializedObject.FindProperty("m_RadiusScale");
m_BlackWhiteRemapMin = serializedObject.FindProperty("m_BlackWhiteRemapMin");
m_BlackWhiteRemapMax = serializedObject.FindProperty("m_BlackWhiteRemapMax");
m_InvertRemapRange = serializedObject.FindProperty("m_InvertRemapRange");
}
bool IsAnyReadOnly()
{
foreach (Brush b in targets)
{
if (b.readOnly)
return true;
}
return false;
}
public override void OnInspectorGUI()
{
if (IsAnyReadOnly())
{
EditorGUILayout.HelpBox(Styles.readonlyText);
return;
}
serializedObject.Update();
bool brushChanged = false;
EditorGUI.BeginChangeCheck();
Texture2D origMask = (Texture2D)m_Mask.objectReferenceValue;
Texture2D mask = (Texture2D)EditorGUILayout.ObjectField(Styles.maskTexture,
origMask, typeof(Texture2D), false);
if (mask == null)
{
mask = Brush.DefaultMask();
brushChanged = true;
}
if (origMask != mask)
m_Mask.objectReferenceValue = mask;
EditorGUILayout.CurveField(m_Falloff, Color.white, new Rect(0, 0, 1, 1), Styles.falloff);
EditorGUILayout.PropertyField(m_RadiusScale, Styles.radiusScale);
float blackWhiteRemapMin = m_BlackWhiteRemapMin.floatValue;
float blackWhiteRemapMax = m_BlackWhiteRemapMax.floatValue;
EditorGUILayout.MinMaxSlider(Styles.remap, ref blackWhiteRemapMin, ref blackWhiteRemapMax, 0.0f, 1.0f);
if (m_BlackWhiteRemapMin.floatValue != blackWhiteRemapMin || m_BlackWhiteRemapMax.floatValue != blackWhiteRemapMax)
{
m_BlackWhiteRemapMin.floatValue = blackWhiteRemapMin;
m_BlackWhiteRemapMax.floatValue = blackWhiteRemapMax;
brushChanged = true;
}
EditorGUILayout.PropertyField(m_InvertRemapRange, Styles.remapInvert);
brushChanged |= EditorGUI.EndChangeCheck();
m_HasChanged |= brushChanged;
serializedObject.ApplyModifiedProperties();
if (brushChanged)
{
foreach (Brush b in targets)
{
b.SetDirty(true);
}
}
}
public override bool HasPreviewGUI()
{
return true;
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (Event.current.type == EventType.Repaint)
background.Draw(r, false, false, false, false);
Texture2D mask = (Texture2D)m_Mask.objectReferenceValue;
if (mask == null)
{
mask = Brush.DefaultMask();
m_HasChanged = true;
}
int texWidth = Mathf.Min(mask.width, 256);
int texHeight = Mathf.Min(mask.height, 256);
if (m_HasChanged || m_PreviewTexture == null)
{
m_PreviewTexture = Brush.GenerateBrushTexture(mask, m_Falloff.animationCurveValue, m_RadiusScale.floatValue, m_BlackWhiteRemapMin.floatValue, m_BlackWhiteRemapMax.floatValue, m_InvertRemapRange.boolValue, texWidth, texHeight, true);
m_HasChanged = false;
}
float zoomLevel = Mathf.Min(Mathf.Min(r.width / texWidth, r.height / texHeight), 1);
Rect wantedRect = new Rect(r.x, r.y, texWidth * zoomLevel, texHeight * zoomLevel);
PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb");
if (m_PreviewTexture.alphaIsTransparency)
EditorGUI.DrawTextureTransparent(wantedRect, m_PreviewTexture);
else
EditorGUI.DrawPreviewTexture(wantedRect, m_PreviewTexture);
m_Pos = PreviewGUI.EndScrollView();
}
public sealed override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height)
{
Brush brush = AssetDatabase.LoadMainAssetAtPath(assetPath) as Brush;
if (brush == null)
return null;
if (brush.m_Mask == null)
brush.m_Mask = Brush.DefaultMask();
PreviewHelpers.AdjustWidthAndHeightForStaticPreview(brush.m_Mask.width, brush.m_Mask.height, ref width, ref height);
return Brush.GenerateBrushTexture(brush.m_Mask, brush.m_Falloff, brush.m_RadiusScale, brush.m_BlackWhiteRemapMin, brush.m_BlackWhiteRemapMax, brush.m_InvertRemapRange, width, height, true);
}
}
}
| UnityCsReference/Modules/TerrainEditor/Brush/BrushEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/Brush/BrushEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 2967
} | 461 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditor;
using UnityEngine.TerrainTools;
using UnityEditor.ShortcutManagement;
namespace UnityEditor.TerrainTools
{
internal class SmoothHeightTool : TerrainPaintToolWithOverlays<SmoothHeightTool>
{
const string k_ToolName = "Smooth Height";
public override string OnIcon => "TerrainOverlays/Smooth_On.png";
public override string OffIcon => "TerrainOverlays/Smooth.png";
[SerializeField]
public float m_direction = 0.0f; // -1 to 1
class Styles
{
public readonly GUIContent description = EditorGUIUtility.TrTextContent("Click to smooth the terrain height.");
public readonly GUIContent direction = EditorGUIUtility.TrTextContent("Blur Direction", "Blur only up (1.0), only down (-1.0) or both (0.0)");
}
private static Styles m_styles;
private Styles GetStyles()
{
if (m_styles == null)
{
m_styles = new Styles();
}
return m_styles;
}
[FormerlyPrefKeyAs("Terrain/Smooth Height", "f3")]
[Shortcut("Terrain/Smooth Height", typeof(TerrainToolShortcutContext), KeyCode.F3)]
static void SelectShortcut(ShortcutArguments args)
{
TerrainToolShortcutContext context = (TerrainToolShortcutContext)args.context;
context.SelectPaintToolWithOverlays<SmoothHeightTool>();
}
public override int IconIndex
{
get { return (int) SculptIndex.Smooth; }
}
public override TerrainCategory Category
{
get { return TerrainCategory.Sculpt; }
}
public override string GetName()
{
return k_ToolName;
}
public override string GetDescription()
{
return GetStyles().description.text;
}
public override bool HasToolSettings => true;
public override bool HasBrushMask => true;
public override bool HasBrushAttributes => true;
public override void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext)
{
Styles styles = GetStyles();
m_direction = EditorGUILayout.Slider(styles.direction, m_direction, -1.0f, 1.0f);
}
public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext)
{
OnToolSettingsGUI(terrain, editContext);
int textureRez = terrain.terrainData.heightmapResolution;
editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All, textureRez);
}
private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform)
{
Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial();
Vector4 brushParams = new Vector4(brushStrength, 0.0f, 0.0f, 0.0f);
mat.SetTexture("_BrushTex", brushTexture);
mat.SetVector("_BrushParams", brushParams);
Vector4 smoothWeights = new Vector4(
Mathf.Clamp01(1.0f - Mathf.Abs(m_direction)), // centered
Mathf.Clamp01(-m_direction), // min
Mathf.Clamp01(m_direction), // max
0.0f); // unused
mat.SetVector("_SmoothWeights", smoothWeights);
TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat);
Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainBuiltinPaintMaterialPasses.SmoothHeights);
}
public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext)
{
// We're only doing painting operations, early out if it's not a repaint
if (Event.current.type != EventType.Repaint)
return;
if (editContext.hitValidTerrain)
{
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f);
PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1);
TerrainPaintUtilityEditor.DrawBrushPreview(ctx, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(), 0);
TerrainPaintUtility.ReleaseContextResources(ctx);
}
}
public override bool OnPaint(Terrain terrain, IOnPaint editContext)
{
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f);
PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds());
ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform);
TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Smooth Height");
return true;
}
}
}
| UnityCsReference/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs",
"repo_id": "UnityCsReference",
"token_count": 2285
} | 462 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine.Scripting;
namespace UnityEngine.TextCore.LowLevel
{
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct OTL_Tag
{
public byte c0, c1, c2, c3, c4;
public override unsafe string ToString()
{
var chars = stackalloc char[4];
chars[0] = (char)c0;
chars[1] = (char)c1;
chars[2] = (char)c2;
chars[3] = (char)c3;
return new string(chars);
}
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct OTL_Table
{
public OTL_Script[] scripts;
public OTL_Feature[] features;
public OTL_Lookup[] lookups;
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Script = {tag}, Language Count = {languages.Length}")]
internal struct OTL_Script
{
public OTL_Tag tag;
public OTL_Language[] languages;
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Language = {tag}, Feature Count = {featureIndexes.Length}")]
internal struct OTL_Language
{
public OTL_Tag tag;
public uint[] featureIndexes;
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Feature = {tag}, Lookup Count = {lookupIndexes.Length}")]
internal struct OTL_Feature
{
public OTL_Tag tag;
public uint[] lookupIndexes;
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("{(OTL_LookupType)lookupType}")]
internal struct OTL_Lookup
{
public uint lookupType;
public uint lookupFlag;
public uint markFilteringSet;
}
/// <summary>
/// Structure used for marshalling glyphs between managed and native code.
/// </summary>
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct GlyphMarshallingStruct
{
/// <summary>
/// The index of the glyph in the source font file.
/// </summary>
public uint index;
/// <summary>
/// Metrics defining the size, positioning and spacing of a glyph when doing text layout.
/// </summary>
public GlyphMetrics metrics;
/// <summary>
/// A rectangle that defines the position of a glyph within an atlas texture.
/// </summary>
public GlyphRect glyphRect;
/// <summary>
/// The relative scale of the text element. The default value is 1.0.
/// </summary>
public float scale;
/// <summary>
/// The index of the atlas texture that contains this glyph.
/// </summary>
public int atlasIndex;
/// <summary>
/// Glyph class definition type.
/// </summary>
public GlyphClassDefinitionType classDefinitionType;
/// <summary>
/// Constructor for a new glyph
/// </summary>
/// <param name="glyph">Glyph whose values are copied to the new glyph.</param>
public GlyphMarshallingStruct(Glyph glyph)
{
this.index = glyph.index;
this.metrics = glyph.metrics;
this.glyphRect = glyph.glyphRect;
this.scale = glyph.scale;
this.atlasIndex = glyph.atlasIndex;
this.classDefinitionType = glyph.classDefinitionType;
}
/// <summary>
/// Constructor for new glyph
/// </summary>
/// <param name="index">The index of the glyph in the font file.</param>
/// <param name="metrics">The metrics of the glyph.</param>
/// <param name="glyphRect">A rectangle defining the position of the glyph in the atlas texture.</param>
/// <param name="scale">The relative scale of the glyph.</param>
/// <param name="atlasIndex">The index of the atlas texture that contains the glyph.</param>
public GlyphMarshallingStruct(uint index, GlyphMetrics metrics, GlyphRect glyphRect, float scale, int atlasIndex)
{
this.index = index;
this.metrics = metrics;
this.glyphRect = glyphRect;
this.scale = scale;
this.atlasIndex = atlasIndex;
this.classDefinitionType = GlyphClassDefinitionType.Undefined;
}
/// <summary>
/// Constructor for new glyph
/// </summary>
/// <param name="index">The index of the glyph in the font file.</param>
/// <param name="metrics">The metrics of the glyph.</param>
/// <param name="glyphRect">A rectangle defining the position of the glyph in the atlas texture.</param>
/// <param name="scale">The relative scale of the glyph.</param>
/// <param name="atlasIndex">The index of the atlas texture that contains the glyph.</param>
/// <param name="classDefinitionType">Class definition type for the glyph.</param>
public GlyphMarshallingStruct(uint index, GlyphMetrics metrics, GlyphRect glyphRect, float scale, int atlasIndex, GlyphClassDefinitionType classDefinitionType)
{
this.index = index;
this.metrics = metrics;
this.glyphRect = glyphRect;
this.scale = scale;
this.atlasIndex = atlasIndex;
this.classDefinitionType = classDefinitionType;
}
}
}
| UnityCsReference/Modules/TextCoreFontEngine/Managed/FontEngineMarshallingCommon.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreFontEngine/Managed/FontEngineMarshallingCommon.cs",
"repo_id": "UnityCsReference",
"token_count": 2262
} | 463 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEngine.TextCore.Text
{
struct MaterialReference
{
public int index;
public FontAsset fontAsset;
public SpriteAsset spriteAsset;
public Material material;
public bool isFallbackMaterial;
public Material fallbackMaterial;
public float padding;
public int referenceCount;
/// <summary>
/// Constructor for new Material Reference.
/// </summary>
/// <param name="index"></param>
/// <param name="fontAsset"></param>
/// <param name="spriteAsset"></param>
/// <param name="material"></param>
/// <param name="padding"></param>
public MaterialReference(int index, FontAsset fontAsset, SpriteAsset spriteAsset, Material material, float padding)
{
this.index = index;
this.fontAsset = fontAsset;
this.spriteAsset = spriteAsset;
this.material = material;
isFallbackMaterial = false;
fallbackMaterial = null;
this.padding = padding;
referenceCount = 0;
}
/// <summary>
/// Function to check if a certain font asset is contained in the material reference array.
/// </summary>
/// <param name="materialReferences"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static bool Contains(MaterialReference[] materialReferences, FontAsset fontAsset)
{
int id = fontAsset.GetHashCode();
for (int i = 0; i < materialReferences.Length && materialReferences[i].fontAsset != null; i++)
{
if (materialReferences[i].fontAsset.GetHashCode() == id)
return true;
}
return false;
}
/// <summary>
/// Function to add a new material reference and returning its index in the material reference array.
/// </summary>
/// <param name="material"></param>
/// <param name="fontAsset"></param>
/// <param name="materialReferences"></param>
/// <param name="materialReferenceIndexLookup"></param>
/// <returns></returns>
public static int AddMaterialReference(Material material, FontAsset fontAsset, ref MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
{
int materialId = material.GetHashCode();
int index;
if (materialReferenceIndexLookup.TryGetValue(materialId, out index))
{
return index;
}
index = materialReferenceIndexLookup.Count;
// Add new reference index
materialReferenceIndexLookup[materialId] = index;
if (index >= materialReferences.Length)
Array.Resize(ref materialReferences, Mathf.NextPowerOfTwo(index + 1));
materialReferences[index].index = index;
materialReferences[index].fontAsset = fontAsset;
materialReferences[index].spriteAsset = null;
materialReferences[index].material = material;
materialReferences[index].referenceCount = 0;
return index;
}
/// <summary>
///
/// </summary>
/// <param name="material"></param>
/// <param name="spriteAsset"></param>
/// <param name="materialReferences"></param>
/// <param name="materialReferenceIndexLookup"></param>
/// <returns></returns>
public static int AddMaterialReference(Material material, SpriteAsset spriteAsset, ref MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
{
int materialId = material.GetHashCode();
int index;
if (materialReferenceIndexLookup.TryGetValue(materialId, out index))
return index;
index = materialReferenceIndexLookup.Count;
// Add new reference index
materialReferenceIndexLookup[materialId] = index;
if (index >= materialReferences.Length)
Array.Resize(ref materialReferences, Mathf.NextPowerOfTwo(index + 1));
materialReferences[index].index = index;
materialReferences[index].fontAsset = materialReferences[0].fontAsset;
materialReferences[index].spriteAsset = spriteAsset;
materialReferences[index].material = material;
materialReferences[index].referenceCount = 0;
return index;
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialReference.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialReference.cs",
"repo_id": "UnityCsReference",
"token_count": 1902
} | 464 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine.Serialization;
using UnityEngine.TextCore.LowLevel;
namespace UnityEngine.TextCore.Text
{
[System.Serializable][ExcludeFromPresetAttribute][ExcludeFromObjectFactory]
public class TextSettings : ScriptableObject
{
internal string k_SystemFontName =
"Lucida Grande"
;
/// <summary>
/// The version of the TextSettings class.
/// Version 1.2.0 was introduced with the TextCore package
/// </summary>
public string version
{
get => m_Version;
internal set => m_Version = value;
}
[SerializeField]
protected string m_Version;
/// <summary>
/// The Font Asset automatically assigned to newly created text objects.
/// </summary>
public FontAsset defaultFontAsset
{
get => m_DefaultFontAsset;
set => m_DefaultFontAsset = value;
}
[FormerlySerializedAs("m_defaultFontAsset")][SerializeField]
protected FontAsset m_DefaultFontAsset;
/// <summary>
/// The relative path to a Resources folder in the project where the text system will look to load font assets.
/// The default location is "Resources/Fonts & Materials".
/// </summary>
public string defaultFontAssetPath
{
get => m_DefaultFontAssetPath;
set => m_DefaultFontAssetPath = value;
}
[FormerlySerializedAs("m_defaultFontAssetPath")][SerializeField]
protected string m_DefaultFontAssetPath = "Fonts & Materials/";
/// <summary>
/// List of potential font assets the text system will search recursively to look for requested characters.
/// </summary>
public List<FontAsset> fallbackFontAssets
{
get => m_FallbackFontAssets;
set => m_FallbackFontAssets = value;
}
[FormerlySerializedAs("m_fallbackFontAssets")][SerializeField]
protected List<FontAsset> m_FallbackFontAssets;
/// <summary>
/// Determines if the text system will use an instance material derived from the primary material preset or use the default material of the fallback font asset.
/// </summary>
public bool matchMaterialPreset
{
get => m_MatchMaterialPreset;
set => m_MatchMaterialPreset = value;
}
[FormerlySerializedAs("m_matchMaterialPreset")][SerializeField]
protected bool m_MatchMaterialPreset;
/// <summary>
/// Determines if OpenType Font Features should be retrieved at runtime from the source font file.
/// </summary>
// public bool getFontFeaturesAtRuntime
// {
// get { return m_GetFontFeaturesAtRuntime; }
// }
// [SerializeField]
// private bool m_GetFontFeaturesAtRuntime = true;
/// <summary>
/// The unicode value of the character that will be used when the requested character is missing from the font asset and potential fallbacks.
/// </summary>
public int missingCharacterUnicode
{
get => m_MissingCharacterUnicode;
set => m_MissingCharacterUnicode = value;
}
[FormerlySerializedAs("m_missingGlyphCharacter")][SerializeField]
protected int m_MissingCharacterUnicode;
/// <summary>
/// Determines if the "Clear Dynamic Data on Build" property will be set to true or false on newly created dynamic font assets.
/// </summary>
public bool clearDynamicDataOnBuild
{
get => m_ClearDynamicDataOnBuild;
set => m_ClearDynamicDataOnBuild = value;
}
[SerializeField]
protected bool m_ClearDynamicDataOnBuild = true;
/// <summary>
/// Determines if Emoji support is enabled in the Input Field TouchScreenKeyboard.
/// </summary>
public bool enableEmojiSupport
{
get { return m_EnableEmojiSupport; }
set { m_EnableEmojiSupport = value; }
}
[SerializeField]
private bool m_EnableEmojiSupport;
/// <summary>
/// list of Fallback Text Assets (Font Assets and Sprite Assets) used to lookup characters defined in the Unicode as Emojis.
/// </summary>
public List<TextAsset> emojiFallbackTextAssets
{
get => m_EmojiFallbackTextAssets;
set => m_EmojiFallbackTextAssets = value;
}
[SerializeField]
private List<TextAsset> m_EmojiFallbackTextAssets;
/// <summary>
/// The Sprite Asset to be used by default.
/// </summary>
public SpriteAsset defaultSpriteAsset
{
get => m_DefaultSpriteAsset;
set => m_DefaultSpriteAsset = value;
}
[FormerlySerializedAs("m_defaultSpriteAsset")][SerializeField]
protected SpriteAsset m_DefaultSpriteAsset;
/// <summary>
/// The relative path to a Resources folder in the project where the text system will look to load sprite assets.
/// The default location is "Resources/Sprite Assets".
/// </summary>
public string defaultSpriteAssetPath
{
get => m_DefaultSpriteAssetPath;
set => m_DefaultSpriteAssetPath = value;
}
[FormerlySerializedAs("m_defaultSpriteAssetPath")][SerializeField]
protected string m_DefaultSpriteAssetPath = "Sprite Assets/";
[Obsolete("The Fallback Sprite Assets list is now obsolete. Use the emojiFallbackTextAssets instead.", true)]
public List<SpriteAsset> fallbackSpriteAssets
{
get => m_FallbackSpriteAssets;
set => m_FallbackSpriteAssets = value;
}
[SerializeField]
protected List<SpriteAsset> m_FallbackSpriteAssets;
internal static SpriteAsset s_GlobalSpriteAsset { private set; get; }
/// <summary>
/// The unicode value of the sprite character that will be used when the requested character sprite is missing from the sprite asset and potential fallbacks.
/// </summary>
public uint missingSpriteCharacterUnicode
{
get => m_MissingSpriteCharacterUnicode;
set => m_MissingSpriteCharacterUnicode = value;
}
[SerializeField]
protected uint m_MissingSpriteCharacterUnicode;
/// <summary>
/// The Default Style Sheet used by the text objects.
/// </summary>
public TextStyleSheet defaultStyleSheet
{
get => m_DefaultStyleSheet;
set => m_DefaultStyleSheet = value;
}
[FormerlySerializedAs("m_defaultStyleSheet")][SerializeField]
protected TextStyleSheet m_DefaultStyleSheet;
/// <summary>
/// The relative path to a Resources folder in the project where the text system will look to load style sheets.
/// The default location is "Resources/Style Sheets".
/// </summary>
public string styleSheetsResourcePath
{
get => m_StyleSheetsResourcePath;
set => m_StyleSheetsResourcePath = value;
}
[SerializeField]
protected string m_StyleSheetsResourcePath = "Text Style Sheets/";
/// <summary>
/// The relative path to a Resources folder in the project where the text system will look to load color gradient presets.
/// The default location is "Resources/Color Gradient Presets".
/// </summary>
public string defaultColorGradientPresetsPath
{
get => m_DefaultColorGradientPresetsPath;
set => m_DefaultColorGradientPresetsPath = value;
}
[FormerlySerializedAs("m_defaultColorGradientPresetsPath")][SerializeField]
protected string m_DefaultColorGradientPresetsPath = "Text Color Gradients/";
// =============================================
// Line breaking rules
// =============================================
/// <summary>
/// Text file that contains the line breaking rules for all unicode characters.
/// </summary>
public UnicodeLineBreakingRules lineBreakingRules
{
get
{
if (m_UnicodeLineBreakingRules == null)
{
m_UnicodeLineBreakingRules = new UnicodeLineBreakingRules();
m_UnicodeLineBreakingRules.LoadLineBreakingRules();
}
return m_UnicodeLineBreakingRules;
}
set => m_UnicodeLineBreakingRules = value;
}
[SerializeField]
protected UnicodeLineBreakingRules m_UnicodeLineBreakingRules;
// =============================================
// Text object specific settings
// =============================================
// To be implemented in the derived classes
// =============================================
//
// =============================================
/// <summary>
/// Controls the display of warning messages in the console.
/// </summary>
public bool displayWarnings
{
get => m_DisplayWarnings;
set => m_DisplayWarnings = value;
}
[FormerlySerializedAs("m_warningsDisabled")][SerializeField]
protected bool m_DisplayWarnings = false;
// =============================================
// Functions
// =============================================
void OnEnable()
{
lineBreakingRules.LoadLineBreakingRules();
if (s_GlobalSpriteAsset == null)
s_GlobalSpriteAsset = Resources.Load<SpriteAsset>("Sprite Assets/Default Sprite Asset");
}
protected void InitializeFontReferenceLookup()
{
if (m_FontReferences == null)
m_FontReferences = new List<FontReferenceMap>();
for (int i = 0; i < m_FontReferences.Count; i++)
{
FontReferenceMap fontRef = m_FontReferences[i];
// Validate fontRef data
if (fontRef.font == null || fontRef.fontAsset == null)
{
Debug.LogWarning("Deleting invalid font reference.");
m_FontReferences.RemoveAt(i);
i -= 1;
continue;
}
int id = fontRef.font.GetHashCode() + fontRef.fontAsset.material.shader.GetHashCode();
if (!m_FontLookup.ContainsKey(id))
m_FontLookup.Add(id, fontRef.fontAsset);
}
}
[System.Serializable]
struct FontReferenceMap
{
public Font font;
public FontAsset fontAsset;
public FontReferenceMap(Font font, FontAsset fontAsset)
{
this.font = font;
this.fontAsset = fontAsset;
}
}
// Internal for testing purposes
internal Dictionary<int, FontAsset> m_FontLookup;
private List<FontReferenceMap> m_FontReferences = new List<FontReferenceMap>();
protected FontAsset GetCachedFontAssetInternal(Font font)
{
return GetCachedFontAsset(font, TextShaderUtilities.ShaderRef_MobileSDF);
}
[VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")]
internal FontAsset GetCachedFontAsset(Font font, Shader shader)
{
if (font == null || shader == null)
return null;
if (m_FontLookup == null)
{
m_FontLookup = new Dictionary<int, FontAsset>();
InitializeFontReferenceLookup();
}
int id = font.GetHashCode() + shader.GetHashCode();
if (m_FontLookup.ContainsKey(id))
return m_FontLookup[id];
if (TextGenerator.IsExecutingJob)
return null;
FontAsset fontAsset;
if (font.name == "System Normal" || font.name == "System Small" || font.name == "System Big" || font.name == "System Warning")
{
fontAsset = FontAsset.CreateFontAsset(k_SystemFontName, "Regular", 90);
}
else if (font.name == "System Normal Bold" || font.name == "System Small Bold")
{
fontAsset = FontAsset.CreateFontAsset(k_SystemFontName, "Bold", 90);
}
else
{
fontAsset = FontAsset.CreateFontAsset(font, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, AtlasPopulationMode.Dynamic, true);
}
if (fontAsset != null)
{
fontAsset.hideFlags = HideFlags.DontSave;
fontAsset.atlasTextures[0].hideFlags = HideFlags.DontSave;
fontAsset.material.hideFlags = HideFlags.DontSave;
fontAsset.isMultiAtlasTexturesEnabled = true;
fontAsset.material.shader = shader;
m_FontReferences.Add(new FontReferenceMap(font, fontAsset));
m_FontLookup.Add(id, fontAsset);
}
return fontAsset;
}
[VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")]
internal virtual float GetEditorTextSharpness()
{
Debug.LogWarning("GetEditorTextSettings() should only be called on EditorTextSettings");
return 0.0f;
}
[VisibleToOtherModules("UnityEngine.IMGUIModule")]
internal virtual Font GetEditorFont()
{
Debug.LogWarning("GetEditorTextSettings() should only be called on EditorTextSettings");
return null;
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextSettings.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextSettings.cs",
"repo_id": "UnityCsReference",
"token_count": 5976
} | 465 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Text;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine.Bindings;
using UnityEngine.Profiling;
using UnityEngine.TextCore.LowLevel;
namespace UnityEngine.TextCore.Text
{
internal partial class TextGenerator
{
[VisibleToOtherModules("UnityEngine.UIElementsModule")]
internal void Prepare(TextGenerationSettings generationSettings, TextInfo textInfo)
{
Profiler.BeginSample("TextGenerator.Prepare");
m_Padding = generationSettings.extraPadding;
m_CurrentFontAsset = generationSettings.fontAsset;
// Set the font style that is assigned by the builder
m_FontStyleInternal = generationSettings.fontStyle;
m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight;
// Find and cache Underline & Ellipsis characters.
GetSpecialCharacters(generationSettings);
ComputeMarginSize(generationSettings.screenRect, generationSettings.margins);
//ParseInputText
PopulateTextBackingArray(generationSettings.renderedText);
PopulateTextProcessingArray(generationSettings);
SetArraySizes(m_TextProcessingArray, generationSettings, textInfo);
// Reset Font min / max used with Auto-sizing
if (generationSettings.autoSize)
m_FontSize = Mathf.Clamp(generationSettings.fontSize, generationSettings.fontSizeMin, generationSettings.fontSizeMax);
else
m_FontSize = generationSettings.fontSize;
m_MaxFontSize = generationSettings.fontSizeMax;
m_MinFontSize = generationSettings.fontSizeMin;
m_LineSpacingDelta = 0;
m_CharWidthAdjDelta = 0;
Profiler.EndSample();
}
internal bool PrepareFontAsset(TextGenerationSettings generationSettings)
{
m_CurrentFontAsset = generationSettings.fontAsset;
// Set the font style that is assigned by the builder
m_FontStyleInternal = generationSettings.fontStyle;
m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight;
// Find and cache Underline & Ellipsis characters.
GetSpecialCharacters(generationSettings);
//ParseInputText
PopulateTextBackingArray(generationSettings.renderedText);
PopulateTextProcessingArray(generationSettings);
bool success = PopulateFontAsset(generationSettings, m_TextProcessingArray);
return success;
}
// This function parses through the Char[] to determine how many characters will be visible. It then makes sure the arrays are large enough for all those characters.
int SetArraySizes(TextProcessingElement[] textProcessingArray, TextGenerationSettings generationSettings, TextInfo textInfo)
{
TextSettings textSettings = generationSettings.textSettings;
int spriteCount = 0;
m_TotalCharacterCount = 0;
m_isTextLayoutPhase = false;
m_TagNoParsing = false;
m_FontStyleInternal = generationSettings.fontStyle;
m_FontStyleStack.Clear();
m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight;
m_FontWeightStack.SetDefault(m_FontWeightInternal);
m_CurrentFontAsset = generationSettings.fontAsset;
m_CurrentMaterial = generationSettings.material;
m_CurrentMaterialIndex = 0;
m_MaterialReferenceStack.SetDefault(new MaterialReference(m_CurrentMaterialIndex, m_CurrentFontAsset, null, m_CurrentMaterial, m_Padding));
m_MaterialReferenceIndexLookup.Clear();
MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_CurrentSpriteAsset = null;
if (textInfo == null)
textInfo = new TextInfo(VertexDataLayout.Mesh);
else if (textInfo.textElementInfo.Length < m_InternalTextProcessingArraySize)
TextInfo.Resize(ref textInfo.textElementInfo, m_InternalTextProcessingArraySize, false);
m_TextElementType = TextElementType.Character;
// Handling for Underline special character
#region Setup Underline Special Character
/*
GetUnderlineSpecialCharacter(m_CurrentFontAsset);
if (m_Underline.character != null)
{
if (m_Underline.fontAsset.GetInstanceID() != m_CurrentFontAsset.GetInstanceID())
{
if (generationSettings.textSettings.matchMaterialPreset && m_CurrentMaterial.GetInstanceID() != m_Underline.fontAsset.material.GetInstanceID())
m_Underline.material = TMP_MaterialManager.GetFallbackMaterial(m_CurrentMaterial, m_Underline.fontAsset.material);
else
m_Underline.material = m_Underline.fontAsset.material;
m_Underline.materialIndex = MaterialReference.AddMaterialReference(m_Underline.material, m_Underline.fontAsset, m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_Underline.materialIndex].referenceCount = 0;
}
}
*/
#endregion
// Handling for Ellipsis special character
#region Setup Ellipsis Special Character
if (generationSettings.overflowMode == TextOverflowMode.Ellipsis)
{
GetEllipsisSpecialCharacter(generationSettings);
if (m_Ellipsis.character != null)
{
if (m_Ellipsis.fontAsset.GetHashCode() != m_CurrentFontAsset.GetHashCode())
{
if (textSettings.matchMaterialPreset && m_CurrentMaterial.GetHashCode() != m_Ellipsis.fontAsset.material.GetHashCode())
m_Ellipsis.material = MaterialManager.GetFallbackMaterial(m_CurrentMaterial, m_Ellipsis.fontAsset.material);
else
m_Ellipsis.material = m_Ellipsis.fontAsset.material;
m_Ellipsis.materialIndex = MaterialReference.AddMaterialReference(m_Ellipsis.material, m_Ellipsis.fontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_Ellipsis.materialIndex].referenceCount = 0;
}
}
else
{
generationSettings.overflowMode = TextOverflowMode.Truncate;
if (textSettings.displayWarnings)
Debug.LogWarning("The character used for Ellipsis is not available in font asset [" + m_CurrentFontAsset.name + "] or any potential fallbacks. Switching Text Overflow mode to Truncate.");
}
}
#endregion
// Check if we should process Ligatures
bool ligature = generationSettings.fontFeatures.Contains(OTL_FeatureTag.liga);
// Clear Linked Text object if we have one
//if (generationSettings.overflowMode == TextOverflowMode.Linked && m_linkedTextComponent != null && !m_IsCalculatingPreferredValues)
// m_linkedTextComponent.text = string.Empty;
// Parsing XML tags in the text
for (int i = 0; i < textProcessingArray.Length && textProcessingArray[i].unicode != 0; i++)
{
//Make sure the characterInfo array can hold the next text element.
if (textInfo.textElementInfo == null || m_TotalCharacterCount >= textInfo.textElementInfo.Length)
TextInfo.Resize(ref textInfo.textElementInfo, m_TotalCharacterCount + 1, true);
uint unicode = textProcessingArray[i].unicode;
int prevMaterialIndex = m_CurrentMaterialIndex;
// PARSE XML TAGS
#region PARSE XML TAGS
if (generationSettings.richText && unicode == '<')
{
prevMaterialIndex = m_CurrentMaterialIndex;
int endTagIndex;
// Check if Tag is Valid
if (ValidateHtmlTag(textProcessingArray, i + 1, out endTagIndex, generationSettings, textInfo, out bool isThreadSuccess))
{
int tagStartIndex = textProcessingArray[i].stringIndex;
i = endTagIndex;
if (m_TextElementType == TextElementType.Sprite)
{
m_MaterialReferences[m_CurrentMaterialIndex].referenceCount += 1;
textInfo.textElementInfo[m_TotalCharacterCount].character = (char)(57344 + m_SpriteIndex);
textInfo.textElementInfo[m_TotalCharacterCount].fontAsset = m_CurrentFontAsset;
textInfo.textElementInfo[m_TotalCharacterCount].materialReferenceIndex = m_CurrentMaterialIndex;
textInfo.textElementInfo[m_TotalCharacterCount].textElement = m_CurrentSpriteAsset.spriteCharacterTable[m_SpriteIndex];
textInfo.textElementInfo[m_TotalCharacterCount].elementType = m_TextElementType;
textInfo.textElementInfo[m_TotalCharacterCount].index = tagStartIndex;
textInfo.textElementInfo[m_TotalCharacterCount].stringLength = textProcessingArray[i].stringIndex - tagStartIndex + 1;
// Restore element type and material index to previous values.
m_TextElementType = TextElementType.Character;
m_CurrentMaterialIndex = prevMaterialIndex;
spriteCount += 1;
m_TotalCharacterCount += 1;
}
continue;
}
}
#endregion
bool isUsingAlternativeTypeface;
bool isUsingFallbackOrAlternativeTypeface = false;
FontAsset prevFontAsset = m_CurrentFontAsset;
Material prevMaterial = m_CurrentMaterial;
prevMaterialIndex = m_CurrentMaterialIndex;
// Handle Font Styles like LowerCase, UpperCase and SmallCaps.
#region Handling of LowerCase, UpperCase and SmallCaps Font Styles
if (m_TextElementType == TextElementType.Character)
{
if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
{
// If this character is lowercase, switch to uppercase.
if (char.IsLower((char)unicode))
unicode = char.ToUpper((char)unicode);
}
else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
{
// If this character is uppercase, switch to lowercase.
if (char.IsUpper((char)unicode))
unicode = char.ToLower((char)unicode);
}
else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
{
// Only convert lowercase characters to uppercase.
if (char.IsLower((char)unicode))
unicode = char.ToUpper((char)unicode);
}
}
#endregion
// Lookup the Glyph data for each character and cache it.
#region LOOKUP GLYPH
TextElement character = GetTextElement(generationSettings, (uint)unicode, m_CurrentFontAsset, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
// Check if Lowercase or Uppercase variant of the character is available.
/* Not sure this is necessary anyone as it is very unlikely with recursive search through fallback fonts.
if (glyph == null)
{
if (char.IsLower((char)c))
{
if (m_CurrentFontAsset.characterDictionary.TryGetValue(char.ToUpper((char)c), out glyph))
c = chars[i] = char.ToUpper((char)c);
}
else if (char.IsUpper((char)c))
{
if (m_CurrentFontAsset.characterDictionary.TryGetValue(char.ToLower((char)c), out glyph))
c = chars[i] = char.ToLower((char)c);
}
}*/
// Special handling for missing character.
// Replace missing glyph by the Square (9633) glyph or possibly the Space (32) glyph.
if (character == null)
{
DoMissingGlyphCallback(unicode, textProcessingArray[i].stringIndex, m_CurrentFontAsset, textInfo);
// Save the original unicode character
uint srcGlyph = unicode;
// Try replacing the missing glyph character by the Settings file Missing Glyph or Square (9633) character.
unicode = textProcessingArray[i].unicode = (uint)textSettings.missingCharacterUnicode == 0 ? k_Square : (uint)textSettings.missingCharacterUnicode;
// Check for the missing glyph character in the currently assigned font asset and its fallbacks
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
if (character == null)
{
// Search for the missing glyph character in the Settings Fallback list.
if (textSettings.fallbackFontAssets != null && textSettings.fallbackFontAssets.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal((uint)unicode, m_CurrentFontAsset, textSettings.fallbackFontAssets, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
}
if (character == null)
{
// Search for the missing glyph in the Settings Default Font Asset.
if (textSettings.defaultFontAsset != null)
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, textSettings.defaultFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
}
if (character == null)
{
// Use Space (32) Glyph from the currently assigned font asset.
unicode = textProcessingArray[i].unicode = 32;
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
}
if (character == null)
{
// Use End of Text (0x03) Glyph from the currently assigned font asset.
unicode = textProcessingArray[i].unicode = k_EndOfText;
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, ligature);
}
if (textSettings.displayWarnings)
{
bool isMainThread = !JobsUtility.IsExecutingJob;
string formattedWarning = srcGlyph > 0xFFFF
? string.Format("The character with Unicode value \\U{0:X8} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4}.", srcGlyph, isMainThread ? generationSettings.fontAsset.name : generationSettings.fontAsset.GetHashCode(), character.unicode)
: string.Format("The character with Unicode value \\u{0:X4} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4}.", srcGlyph, isMainThread ? generationSettings.fontAsset.name : generationSettings.fontAsset.GetHashCode(), character.unicode);
Debug.LogWarning(formattedWarning);
}
}
textInfo.textElementInfo[m_TotalCharacterCount].alternativeGlyph = null;
if (character.elementType == TextElementType.Character)
{
if (character.textAsset.instanceID != m_CurrentFontAsset.instanceID)
{
isUsingFallbackOrAlternativeTypeface = true;
m_CurrentFontAsset = character.textAsset as FontAsset;
}
#region VARIATION SELECTOR
uint nextCharacter = i + 1 < textProcessingArray.Length ? (uint)textProcessingArray[i + 1].unicode : 0;
if (nextCharacter >= 0xFE00 && nextCharacter <= 0xFE0F || nextCharacter >= 0xE0100 && nextCharacter <= 0xE01EF)
{
uint variantGlyphIndex;
// Get potential variant glyph index
if (!m_CurrentFontAsset.TryGetGlyphVariantIndexInternal(unicode, nextCharacter, out variantGlyphIndex))
{
variantGlyphIndex = m_CurrentFontAsset.GetGlyphVariantIndex(unicode, nextCharacter);
m_CurrentFontAsset.TryAddGlyphVariantIndexInternal(unicode, nextCharacter, variantGlyphIndex);
}
if (variantGlyphIndex != 0)
{
if (m_CurrentFontAsset.TryAddGlyphInternal(variantGlyphIndex, out Glyph glyph))
{
textInfo.textElementInfo[m_TotalCharacterCount].alternativeGlyph = glyph;
}
}
textProcessingArray[i + 1].unicode = 0x1A;
i += 1;
}
#endregion
#region LIGATURES
if (ligature && m_CurrentFontAsset.fontFeatureTable.m_LigatureSubstitutionRecordLookup.TryGetValue(character.glyphIndex, out List<LigatureSubstitutionRecord> records))
{
if (records == null)
break;
for (int j = 0; j < records.Count; j++)
{
LigatureSubstitutionRecord record = records[j];
int componentCount = record.componentGlyphIDs.Length;
uint ligatureGlyphID = record.ligatureGlyphID;
//
for (int k = 1; k < componentCount; k++)
{
uint componentUnicode = (uint)textProcessingArray[i + k].unicode;
// Special Handling for Zero Width Joiner (ZWJ)
//if (componentUnicode == 0x200D)
// continue;
uint glyphIndex = m_CurrentFontAsset.GetGlyphIndex(componentUnicode, out bool _);
if (glyphIndex == record.componentGlyphIDs[k])
continue;
ligatureGlyphID = 0;
break;
}
if (ligatureGlyphID != 0)
{
if (m_CurrentFontAsset.TryAddGlyphInternal(ligatureGlyphID, out Glyph glyph))
{
textInfo.textElementInfo[m_TotalCharacterCount].alternativeGlyph = glyph;
// Update text processing array
for (int c = 0; c < componentCount; c++)
{
if (c == 0)
{
textProcessingArray[i + c].length = componentCount;
continue;
}
textProcessingArray[i + c].unicode = 0x1A;
}
i += componentCount - 1;
break;
}
}
}
}
#endregion
}
#endregion
// Save text element data
textInfo.textElementInfo[m_TotalCharacterCount].elementType = TextElementType.Character;
textInfo.textElementInfo[m_TotalCharacterCount].textElement = character;
textInfo.textElementInfo[m_TotalCharacterCount].isUsingAlternateTypeface = isUsingAlternativeTypeface;
textInfo.textElementInfo[m_TotalCharacterCount].character = (char)unicode;
textInfo.textElementInfo[m_TotalCharacterCount].index = textProcessingArray[i].stringIndex;
textInfo.textElementInfo[m_TotalCharacterCount].stringLength = textProcessingArray[i].length;
textInfo.textElementInfo[m_TotalCharacterCount].fontAsset = m_CurrentFontAsset;
// Special handling if the character is a sprite.
if (character.elementType == TextElementType.Sprite)
{
SpriteAsset spriteAssetRef = character.textAsset as SpriteAsset;
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(spriteAssetRef.material, spriteAssetRef, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_CurrentMaterialIndex].referenceCount += 1;
textInfo.textElementInfo[m_TotalCharacterCount].elementType = TextElementType.Sprite;
textInfo.textElementInfo[m_TotalCharacterCount].materialReferenceIndex = m_CurrentMaterialIndex;
// Restore element type and material index to previous values.
m_TextElementType = TextElementType.Character;
m_CurrentMaterialIndex = prevMaterialIndex;
spriteCount += 1;
m_TotalCharacterCount += 1;
continue;
}
if (isUsingFallbackOrAlternativeTypeface && m_CurrentFontAsset.instanceID != generationSettings.fontAsset.instanceID)
{
// Create Fallback material instance matching current material preset if necessary
if (textSettings.matchMaterialPreset)
m_CurrentMaterial = MaterialManager.GetFallbackMaterial(m_CurrentMaterial, m_CurrentFontAsset.material);
else
m_CurrentMaterial = m_CurrentFontAsset.material;
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
}
// Handle Multi Atlas Texture support
if (character != null && character.glyph.atlasIndex > 0)
{
m_CurrentMaterial = MaterialManager.GetFallbackMaterial(m_CurrentFontAsset, m_CurrentMaterial, character.glyph.atlasIndex);
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
isUsingFallbackOrAlternativeTypeface = true;
}
if (!char.IsWhiteSpace((char)unicode) && unicode != CodePoint.ZERO_WIDTH_SPACE)
{
// Limit the mesh of the main text object to 65535 vertices and use sub objects for the overflow.
if (generationSettings.isIMGUI && m_MaterialReferences[m_CurrentMaterialIndex].referenceCount >= 16383)
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(new Material(m_CurrentMaterial), m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_CurrentMaterialIndex].referenceCount += 1;
}
textInfo.textElementInfo[m_TotalCharacterCount].material = m_CurrentMaterial;
textInfo.textElementInfo[m_TotalCharacterCount].materialReferenceIndex = m_CurrentMaterialIndex;
m_MaterialReferences[m_CurrentMaterialIndex].isFallbackMaterial = isUsingFallbackOrAlternativeTypeface;
// Restore previous font asset and material if fallback font was used.
if (isUsingFallbackOrAlternativeTypeface)
{
m_MaterialReferences[m_CurrentMaterialIndex].fallbackMaterial = prevMaterial;
m_CurrentFontAsset = prevFontAsset;
m_CurrentMaterial = prevMaterial;
m_CurrentMaterialIndex = prevMaterialIndex;
}
m_TotalCharacterCount += 1;
}
// Early return if we are calculating the preferred values.
if (m_IsCalculatingPreferredValues)
{
m_IsCalculatingPreferredValues = false;
return m_TotalCharacterCount;
}
// Save material and sprite count.
textInfo.spriteCount = spriteCount;
int materialCount = textInfo.materialCount = m_MaterialReferenceIndexLookup.Count;
// Check if we need to resize the MeshInfo array for handling different materials.
if (materialCount > textInfo.meshInfo.Length)
TextInfo.Resize(ref textInfo.meshInfo, materialCount, false);
// Resize textElementInfo[] if allocations are excessive
if (m_VertexBufferAutoSizeReduction && textInfo.textElementInfo.Length - m_TotalCharacterCount > 256)
TextInfo.Resize(ref textInfo.textElementInfo, Mathf.Max(m_TotalCharacterCount + 1, 256), true);
// Iterate through the material references to set the mesh buffer allocations
for (int i = 0; i < materialCount; i++)
{
int referenceCount = m_MaterialReferences[i].referenceCount;
// Check to make sure buffer allocations can accommodate the required text elements.
if ((textInfo.meshInfo[i].vertexData == null && textInfo.meshInfo[i].vertices == null) || textInfo.meshInfo[i].vertexBufferSize < referenceCount * 4)
{
if (textInfo.meshInfo[i].vertexData == null && textInfo.meshInfo[i].vertices == null)
{
textInfo.meshInfo[i] = new MeshInfo(referenceCount + 1, textInfo.vertexDataLayout, generationSettings.isIMGUI);
}
else
textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.NextPowerOfTwo(referenceCount), generationSettings.isIMGUI);
}
else if (textInfo.meshInfo[i].vertexBufferSize - referenceCount * 4 > 1024)
{
// Resize vertex buffers if allocations are excessive.
textInfo.meshInfo[i].ResizeMeshInfo(referenceCount > 1024 ? referenceCount + 256 : Mathf.Max(Mathf.NextPowerOfTwo(referenceCount), 256), generationSettings.isIMGUI);
}
// Assign material reference
textInfo.meshInfo[i].material = m_MaterialReferences[i].material;
textInfo.meshInfo[i].glyphRenderMode = m_MaterialReferences[i].fontAsset.atlasRenderMode;
}
return m_TotalCharacterCount;
}
TextElement GetTextElement(TextGenerationSettings generationSettings, uint unicode, FontAsset fontAsset, FontStyles fontStyle, TextFontWeight fontWeight, out bool isUsingAlternativeTypeface, bool populateLigatures)
{
bool canWriteOnAsset = !IsExecutingJob;
//Debug.Log("Unicode: " + unicode.ToString("X8"));
TextSettings textSettings = generationSettings.textSettings;
if (generationSettings.emojiFallbackSupport && TextGeneratorUtilities.IsEmoji(unicode))
{
if (textSettings.emojiFallbackTextAssets != null && textSettings.emojiFallbackTextAssets.Count > 0)
{
TextElement textElement = FontAssetUtilities.GetTextElementFromTextAssets(unicode, fontAsset, textSettings.emojiFallbackTextAssets, true, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (textElement != null)
{
// Add character to font asset lookup cache
//fontAsset.AddCharacterToLookupCache(unicode, character);
return textElement;
}
}
}
Character character = FontAssetUtilities.GetCharacterFromFontAsset(unicode, fontAsset, false, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (character != null)
return character;
if (!canWriteOnAsset && (fontAsset.atlasPopulationMode == AtlasPopulationMode.Dynamic || fontAsset.atlasPopulationMode == AtlasPopulationMode.DynamicOS))
return null;
// Search potential list of fallback font assets assigned to the font asset.
if (fontAsset.m_FallbackFontAssetTable != null && fontAsset.m_FallbackFontAssetTable.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal(unicode, fontAsset, fontAsset.m_FallbackFontAssetTable, true, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (character != null)
{
// Add character to font asset lookup cache
fontAsset.AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight);
return character;
}
bool fontAssetEquals = canWriteOnAsset ? fontAsset.instanceID == generationSettings.fontAsset.instanceID : fontAsset == generationSettings.fontAsset;
// Search for the character in the primary font asset if not the current font asset
if (!fontAssetEquals)
{
// Search primary font asset
character = FontAssetUtilities.GetCharacterFromFontAsset(unicode, generationSettings.fontAsset, false, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
// Use material and index of primary font asset.
if (character != null)
{
m_CurrentMaterialIndex = 0;
m_CurrentMaterial = m_MaterialReferences[0].material;
// Add character to font asset lookup cache
fontAsset.AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight);
return character;
}
// Search list of potential fallback font assets assigned to the primary font asset.
if (generationSettings.fontAsset.m_FallbackFontAssetTable != null && generationSettings.fontAsset.m_FallbackFontAssetTable.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal(unicode, fontAsset, generationSettings.fontAsset.m_FallbackFontAssetTable, true, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (character != null)
{
// Add character to font asset lookup cache
fontAsset.AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight);
return character;
}
}
// Search for the character in potential local Sprite Asset assigned to the text object.
if (generationSettings.spriteAsset != null)
{
SpriteCharacter spriteCharacter = FontAssetUtilities.GetSpriteCharacterFromSpriteAsset(unicode, generationSettings.spriteAsset, true);
if (spriteCharacter != null)
return spriteCharacter;
}
// Search for the character in the list of fallback assigned in the settings (General Fallbacks).
if (textSettings.fallbackFontAssets != null && textSettings.fallbackFontAssets.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal(unicode, fontAsset, textSettings.fallbackFontAssets, true, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (character != null)
{
// Add character to font asset lookup cache
fontAsset.AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight);
return character;
}
// Search for the character in the Default Font Asset assigned in the settings file.
if (textSettings.defaultFontAsset != null)
character = FontAssetUtilities.GetCharacterFromFontAsset(unicode, textSettings.defaultFontAsset, true, fontStyle, fontWeight, out isUsingAlternativeTypeface, populateLigatures);
if (character != null)
{
// Add character to font asset lookup cache
fontAsset.AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight);
return character;
}
// Search for the character in the Default Sprite Asset assigned in the settings file.
if (textSettings.defaultSpriteAsset != null)
{
if (!canWriteOnAsset && textSettings.defaultSpriteAsset.m_SpriteCharacterLookup == null)
return null;
SpriteCharacter spriteCharacter = FontAssetUtilities.GetSpriteCharacterFromSpriteAsset(unicode, textSettings.defaultSpriteAsset, true);
if (spriteCharacter != null)
return spriteCharacter;
}
return null;
}
/// <summary>
/// Convert source text to Unicode (uint) and populate internal text backing array.
/// </summary>
/// <param name="sourceText">Source text to be converted</param>
void PopulateTextBackingArray(in RenderedText sourceText)
{
int writeIndex = 0;
int length = sourceText.CharacterCount;
// Make sure array size is appropriate
if (length >= m_TextBackingArray.Capacity)
m_TextBackingArray.Resize((length));
foreach (var character in sourceText)
{
m_TextBackingArray[writeIndex] = character;
writeIndex += 1;
}
// Terminate array with zero as we are not clearing the array on new invocation of this function.
m_TextBackingArray[writeIndex] = 0;
m_TextBackingArray.Count = writeIndex;
}
/// <summary>
///
/// </summary>
void PopulateTextProcessingArray(TextGenerationSettings generationSettings)
{
int srcLength = m_TextBackingArray.Count;
// Make sure parsing buffer is large enough to handle the required text.
if (m_TextProcessingArray.Length < srcLength)
TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray, srcLength);
// Reset Style stack back to default
TextProcessingStack<int>.SetDefault(m_TextStyleStacks, 0);
m_TextStyleStackDepth = 0;
int writeIndex = 0;
int styleHashCode = m_TextStyleStacks[0].Pop();
TextStyle textStyle = TextGeneratorUtilities.GetStyle(generationSettings, styleHashCode);
// Insert Opening Style
if (textStyle != null && textStyle.hashCode != (int)MarkupTag.NORMAL)
TextGeneratorUtilities.InsertOpeningStyleTag(textStyle, ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings);
var tagNoParsing = generationSettings.tagNoParsing;
int readIndex = 0;
for (; readIndex < srcLength; readIndex++)
{
uint c = m_TextBackingArray[readIndex];
if (c == 0)
break;
// TODO: Since we do not set the TextInputSource at this very moment, we have defaulted this conditional to check for
// TextInputSource.TextString whereas in TMP, it checks for TextInputSource.TextInputBox
if (/*generationSettings.inputSource == TextInputSource.TextString && */ c == '\\' && readIndex < srcLength - 1)
{
switch (m_TextBackingArray[readIndex + 1])
{
case 92: // \ escape
if (!generationSettings.parseControlCharacters) break;
readIndex += 1;
break;
case 110: // \n LineFeed
if (!generationSettings.parseControlCharacters) break;
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 10 };
readIndex += 1;
writeIndex += 1;
continue;
case 114: // \r Carriage Return
if (!generationSettings.parseControlCharacters) break;
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 13 };
readIndex += 1;
writeIndex += 1;
continue;
case 116: // \t Tab
if (!generationSettings.parseControlCharacters) break;
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 9 };
readIndex += 1;
writeIndex += 1;
continue;
case 118: // \v Vertical tab used as soft line break
if (!generationSettings.parseControlCharacters) break;
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 11 };
readIndex += 1;
writeIndex += 1;
continue;
case 117: // \u0000 for UTF-16 Unicode
if (srcLength > readIndex + 5 && TextGeneratorUtilities.IsValidUTF16(m_TextBackingArray, readIndex + 2))
{
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 6, unicode = TextGeneratorUtilities.GetUTF16(m_TextBackingArray, readIndex + 2) };
readIndex += 5;
writeIndex += 1;
continue;
}
break;
case 85: // \U00000000 for UTF-32 Unicode
if (srcLength > readIndex + 9 && TextGeneratorUtilities.IsValidUTF32(m_TextBackingArray, readIndex + 2))
{
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 10, unicode = TextGeneratorUtilities.GetUTF32(m_TextBackingArray, readIndex + 2) };
readIndex += 9;
writeIndex += 1;
continue;
}
break;
}
}
// Handle surrogate pair conversion
if (c >= CodePoint.HIGH_SURROGATE_START && c <= CodePoint.HIGH_SURROGATE_END && srcLength > readIndex + 1 && m_TextBackingArray[readIndex + 1] >= CodePoint.LOW_SURROGATE_START && m_TextBackingArray[readIndex + 1] <= CodePoint.LOW_SURROGATE_END)
{
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 2, unicode = TextGeneratorUtilities.ConvertToUTF32(c, m_TextBackingArray[readIndex + 1]) };
readIndex += 1;
writeIndex += 1;
continue;
}
// Handle inline replacement of <style> and <br> tags.
if (c == '<' && generationSettings.richText)
{
// Read tag hash code
int hashCode = TextGeneratorUtilities.GetMarkupTagHashCode(m_TextBackingArray, readIndex + 1);
switch ((MarkupTag)hashCode)
{
case MarkupTag.NO_PARSE:
tagNoParsing = true;
break;
case MarkupTag.SLASH_NO_PARSE:
tagNoParsing = false;
break;
case MarkupTag.BR:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 4, unicode = 10 };
writeIndex += 1;
readIndex += 3;
continue;
case MarkupTag.CR:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 4, unicode = 13 };
writeIndex += 1;
readIndex += 3;
continue;
case MarkupTag.NBSP:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 6, unicode = k_NoBreakSpace };
writeIndex += 1;
readIndex += 5;
continue;
case MarkupTag.ZWSP:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 6, unicode = 0x200B };
writeIndex += 1;
readIndex += 5;
continue;
case MarkupTag.ZWJ:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 5, unicode = 0x200D };
writeIndex += 1;
readIndex += 4;
continue;
case MarkupTag.SHY:
if (tagNoParsing) break;
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 5, unicode = 0xAD };
writeIndex += 1;
readIndex += 4;
continue;
case MarkupTag.A:
// Additional check
if (m_TextBackingArray.Count > readIndex + 4 && m_TextBackingArray[readIndex + 3] == 'h' && m_TextBackingArray[readIndex + 4] == 'r')
TextGeneratorUtilities.InsertOpeningTextStyle(TextGeneratorUtilities.GetStyle(generationSettings, (int)MarkupTag.A), ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings);
break;
case MarkupTag.STYLE:
if (tagNoParsing) break;
int openWriteIndex = writeIndex;
if (TextGeneratorUtilities.ReplaceOpeningStyleTag(ref m_TextBackingArray, readIndex, out int srcOffset, ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings))
{
// Update potential text elements added by the opening style.
for (; openWriteIndex < writeIndex; openWriteIndex++)
{
m_TextProcessingArray[openWriteIndex].stringIndex = readIndex;
m_TextProcessingArray[openWriteIndex].length = (srcOffset - readIndex) + 1;
}
readIndex = srcOffset;
continue;
}
break;
case MarkupTag.SLASH_A:
TextGeneratorUtilities.InsertClosingTextStyle(TextGeneratorUtilities.GetStyle(generationSettings, (int)MarkupTag.A), ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings);
break;
case MarkupTag.SLASH_STYLE:
if (tagNoParsing) break;
int closeWriteIndex = writeIndex;
TextGeneratorUtilities.ReplaceClosingStyleTag(ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings);
// Update potential text elements added by the closing style.
for (; closeWriteIndex < writeIndex; closeWriteIndex++)
{
m_TextProcessingArray[closeWriteIndex].stringIndex = readIndex;
m_TextProcessingArray[closeWriteIndex].length = 8;
}
readIndex += 7;
continue;
}
// Validate potential text markup element
// if (TryGetTextMarkupElement(m_TextBackingArray.Text, ref readIndex, out TextProcessingElement markupElement))
// {
// m_TextProcessingArray[writeIndex] = markupElement;
// writeIndex += 1;
// continue;
// }
}
// Lookup character and glyph data
// TODO: Add future implementation for character and glyph lookups
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = c };
writeIndex += 1;
}
m_TextStyleStackDepth = 0;
// Insert Closing Style
if (textStyle != null && textStyle.hashCode != (int)MarkupTag.NORMAL)
TextGeneratorUtilities.InsertClosingStyleTag(ref m_TextProcessingArray, ref writeIndex, ref m_TextStyleStackDepth, ref m_TextStyleStacks, ref generationSettings);
if (writeIndex == m_TextProcessingArray.Length) TextGeneratorUtilities.ResizeInternalArray(ref m_TextProcessingArray);
m_TextProcessingArray[writeIndex].unicode = 0;
m_InternalTextProcessingArraySize = writeIndex;
}
bool PopulateFontAsset(TextGenerationSettings generationSettings, TextProcessingElement[] textProcessingArray)
{
bool canWriteOnAsset = !IsExecutingJob;
TextSettings textSettings = generationSettings.textSettings;
int spriteCount = 0;
m_TotalCharacterCount = 0;
m_isTextLayoutPhase = false;
m_TagNoParsing = false;
m_FontStyleInternal = generationSettings.fontStyle;
m_FontStyleStack.Clear();
m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight;
m_FontWeightStack.SetDefault(m_FontWeightInternal);
m_CurrentFontAsset = generationSettings.fontAsset;
m_CurrentMaterial = generationSettings.material;
m_CurrentMaterialIndex = 0;
m_MaterialReferenceStack.SetDefault(new MaterialReference(m_CurrentMaterialIndex, m_CurrentFontAsset, null, m_CurrentMaterial, m_Padding));
m_MaterialReferenceIndexLookup.Clear();
MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_TextElementType = TextElementType.Character;
if (generationSettings.overflowMode == TextOverflowMode.Ellipsis)
{
GetEllipsisSpecialCharacter(generationSettings);
if (m_Ellipsis.character != null)
{
if (m_Ellipsis.fontAsset.GetHashCode() != m_CurrentFontAsset.GetHashCode())
{
if (textSettings.matchMaterialPreset && m_CurrentMaterial.GetHashCode() != m_Ellipsis.fontAsset.material.GetHashCode())
{
if (!canWriteOnAsset)
return false;
m_Ellipsis.material = MaterialManager.GetFallbackMaterial(m_CurrentMaterial, m_Ellipsis.fontAsset.material);
}
else
m_Ellipsis.material = m_Ellipsis.fontAsset.material;
m_Ellipsis.materialIndex = MaterialReference.AddMaterialReference(m_Ellipsis.material, m_Ellipsis.fontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_Ellipsis.materialIndex].referenceCount = 0;
}
}
}
// Check if we should process Ligatures
bool ligature = generationSettings.fontFeatures.Contains(OTL_FeatureTag.liga);
// Parsing XML tags in the text
for (int i = 0; i < textProcessingArray.Length && textProcessingArray[i].unicode != 0; i++)
{
uint unicode = textProcessingArray[i].unicode;
int prevMaterialIndex = m_CurrentMaterialIndex;
// PARSE XML TAGS
#region PARSE XML TAGS
if (generationSettings.richText && unicode == '<')
{
prevMaterialIndex = m_CurrentMaterialIndex;
int endTagIndex;
// Check if Tag is Valid
if (ValidateHtmlTag(textProcessingArray, i + 1, out endTagIndex, generationSettings, null, out bool isThreadSuccess))
{
int tagStartIndex = textProcessingArray[i].stringIndex;
i = endTagIndex;
if (m_TextElementType == TextElementType.Sprite)
{
// Restore element type and material index to previous values.
m_TextElementType = TextElementType.Character;
m_CurrentMaterialIndex = prevMaterialIndex;
spriteCount += 1;
m_TotalCharacterCount += 1;
}
continue;
}
if(!isThreadSuccess)
return false;
}
#endregion
bool isUsingFallbackOrAlternativeTypeface = false;
FontAsset prevFontAsset = m_CurrentFontAsset;
Material prevMaterial = m_CurrentMaterial;
prevMaterialIndex = m_CurrentMaterialIndex;
// Handle Font Styles like LowerCase, UpperCase and SmallCaps.
#region Handling of LowerCase, UpperCase and SmallCaps Font Styles
if (m_TextElementType == TextElementType.Character)
{
if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
{
// If this character is lowercase, switch to uppercase.
if (char.IsLower((char)unicode))
unicode = char.ToUpper((char)unicode);
}
else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
{
// If this character is uppercase, switch to lowercase.
if (char.IsUpper((char)unicode))
unicode = char.ToLower((char)unicode);
}
else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
{
// Only convert lowercase characters to uppercase.
if (char.IsLower((char)unicode))
unicode = char.ToUpper((char)unicode);
}
}
#endregion
if (!canWriteOnAsset && m_CurrentFontAsset.m_CharacterLookupDictionary == null)
return false;
// Lookup the Glyph data for each character and cache it.
#region LOOKUP GLYPH
TextElement character = GetTextElement(generationSettings, (uint)unicode, m_CurrentFontAsset, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
// Special handling for missing character.
// Replace missing glyph by the Square (9633) glyph or possibly the Space (32) glyph.
if (character == null)
{
if (!canWriteOnAsset)
return false;
// Save the original unicode character
uint srcGlyph = unicode;
// Try replacing the missing glyph character by the Settings file Missing Glyph or Square (9633) character.
unicode = textProcessingArray[i].unicode = (uint)textSettings.missingCharacterUnicode == 0 ? k_Square : (uint)textSettings.missingCharacterUnicode;
// Check for the missing glyph character in the currently assigned font asset and its fallbacks
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
if (character == null)
{
// Search for the missing glyph character in the Settings Fallback list.
if (textSettings.fallbackFontAssets != null && textSettings.fallbackFontAssets.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal((uint)unicode, m_CurrentFontAsset, textSettings.fallbackFontAssets, true, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
}
if (character == null)
{
// Search for the missing glyph in the Settings Default Font Asset.
if (textSettings.defaultFontAsset != null)
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, textSettings.defaultFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
}
if (character == null)
{
// Use Space (32) Glyph from the currently assigned font asset.
unicode = textProcessingArray[i].unicode = 32;
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
}
if (character == null)
{
// Use End of Text (0x03) Glyph from the currently assigned font asset.
unicode = textProcessingArray[i].unicode = k_EndOfText;
character = FontAssetUtilities.GetCharacterFromFontAsset((uint)unicode, m_CurrentFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out _, ligature);
}
if (textSettings.displayWarnings)
{
string formattedWarning = srcGlyph > 0xFFFF
? string.Format("The character with Unicode value \\U{0:X8} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4}.", srcGlyph, generationSettings.fontAsset.name, character.unicode)
: string.Format("The character with Unicode value \\u{0:X4} was not found in the [{1}] font asset or any potential fallbacks. It was replaced by Unicode character \\u{2:X4}.", srcGlyph, generationSettings.fontAsset.name, character.unicode);
Debug.LogWarning(formattedWarning);
}
}
if (character.elementType == TextElementType.Character)
{
bool textAssetEquals = canWriteOnAsset ? character.textAsset.instanceID == m_CurrentFontAsset.instanceID : character.textAsset == m_CurrentFontAsset;
if (!textAssetEquals)
{
isUsingFallbackOrAlternativeTypeface = true;
m_CurrentFontAsset = character.textAsset as FontAsset;
}
#region VARIATION SELECTOR
uint nextCharacter = i + 1 < textProcessingArray.Length ? (uint)textProcessingArray[i + 1].unicode : 0;
if (nextCharacter >= 0xFE00 && nextCharacter <= 0xFE0F || nextCharacter >= 0xE0100 && nextCharacter <= 0xE01EF)
{
uint variantGlyphIndex;
// Get potential variant glyph index
if (!m_CurrentFontAsset.TryGetGlyphVariantIndexInternal(unicode, nextCharacter, out variantGlyphIndex))
{
if (!canWriteOnAsset)
return false;
variantGlyphIndex = m_CurrentFontAsset.GetGlyphVariantIndex(unicode, nextCharacter);
m_CurrentFontAsset.TryAddGlyphVariantIndexInternal(unicode, nextCharacter, variantGlyphIndex);
}
if (variantGlyphIndex != 0)
{
m_CurrentFontAsset.TryAddGlyphInternal(variantGlyphIndex, out Glyph glyph);
}
textProcessingArray[i + 1].unicode = 0x1A;
i += 1;
}
#endregion
#region LIGATURES
if (ligature && m_CurrentFontAsset.fontFeatureTable.m_LigatureSubstitutionRecordLookup.TryGetValue(character.glyphIndex, out List<LigatureSubstitutionRecord> records))
{
if (records == null)
break;
for (int j = 0; j < records.Count; j++)
{
LigatureSubstitutionRecord record = records[j];
int componentCount = record.componentGlyphIDs.Length;
uint ligatureGlyphID = record.ligatureGlyphID;
//
for (int k = 1; k < componentCount; k++)
{
uint componentUnicode = (uint)textProcessingArray[i + k].unicode;
// Special Handling for Zero Width Joiner (ZWJ)
//if (componentUnicode == 0x200D)
// continue;
uint glyphIndex = m_CurrentFontAsset.GetGlyphIndex(componentUnicode, out bool success);
if (!success)
return false;
if (glyphIndex == record.componentGlyphIDs[k])
continue;
ligatureGlyphID = 0;
break;
}
if (ligatureGlyphID != 0)
{
if (!canWriteOnAsset)
return false;
if (m_CurrentFontAsset.TryAddGlyphInternal(ligatureGlyphID, out Glyph _))
{
// Update text processing array
for (int c = 0; c < componentCount; c++)
{
if (c == 0)
{
textProcessingArray[i + c].length = componentCount;
continue;
}
textProcessingArray[i + c].unicode = 0x1A;
}
i += componentCount - 1;
break;
}
}
}
}
#endregion
}
#endregion
// Special handling if the character is a sprite.
if (character.elementType == TextElementType.Sprite)
{
SpriteAsset spriteAssetRef = character.textAsset as SpriteAsset;
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(spriteAssetRef.material, spriteAssetRef, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
// Restore element type and material index to previous values.
m_TextElementType = TextElementType.Character;
m_CurrentMaterialIndex = prevMaterialIndex;
spriteCount += 1;
m_TotalCharacterCount += 1;
continue;
}
if (isUsingFallbackOrAlternativeTypeface && m_CurrentFontAsset.instanceID != generationSettings.fontAsset.instanceID)
{
// Create Fallback material instance matching current material preset if necessary
if (canWriteOnAsset)
{
if (textSettings.matchMaterialPreset)
m_CurrentMaterial = MaterialManager.GetFallbackMaterial(m_CurrentMaterial, m_CurrentFontAsset.material);
else
m_CurrentMaterial = m_CurrentFontAsset.material;
}
else
{
if (textSettings.matchMaterialPreset)
return false;
else
m_CurrentMaterial = m_CurrentFontAsset.material;
}
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
}
// Handle Multi Atlas Texture support
if (character != null && character.glyph.atlasIndex > 0)
{
if (canWriteOnAsset)
m_CurrentMaterial = MaterialManager.GetFallbackMaterial(m_CurrentFontAsset, m_CurrentMaterial, character.glyph.atlasIndex);
else
return false;
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
isUsingFallbackOrAlternativeTypeface = true;
}
if (!char.IsWhiteSpace((char)unicode) && unicode != CodePoint.ZERO_WIDTH_SPACE)
{
// Limit the mesh of the main text object to 65535 vertices and use sub objects for the overflow.
if (generationSettings.isIMGUI && m_MaterialReferences[m_CurrentMaterialIndex].referenceCount >= 16383)
m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(new Material(m_CurrentMaterial), m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup);
m_MaterialReferences[m_CurrentMaterialIndex].referenceCount += 1;
}
m_MaterialReferences[m_CurrentMaterialIndex].isFallbackMaterial = isUsingFallbackOrAlternativeTypeface;
// Restore previous font asset and material if fallback font was used.
if (isUsingFallbackOrAlternativeTypeface)
{
m_MaterialReferences[m_CurrentMaterialIndex].fallbackMaterial = prevMaterial;
m_CurrentFontAsset = prevFontAsset;
m_CurrentMaterial = prevMaterial;
m_CurrentMaterialIndex = prevMaterialIndex;
}
m_TotalCharacterCount += 1;
}
return true;
}
/// <summary>
/// Update the margin width and height
/// </summary>
void ComputeMarginSize(Rect rect, Vector4 margins)
{
m_MarginWidth = rect.width - margins.x - margins.z;
m_MarginHeight = rect.height - margins.y - margins.w;
// Update the corners of the RectTransform
m_RectTransformCorners[0].x = 0;
m_RectTransformCorners[0].y = 0;
m_RectTransformCorners[1].x = 0;
m_RectTransformCorners[1].y = rect.height;
m_RectTransformCorners[2].x = rect.width;
m_RectTransformCorners[2].y = rect.height;
m_RectTransformCorners[3].x = rect.width;
m_RectTransformCorners[3].y = 0;
}
protected struct SpecialCharacter
{
public Character character;
public FontAsset fontAsset;
public Material material;
public int materialIndex;
public SpecialCharacter(Character character, int materialIndex)
{
this.character = character;
this.fontAsset = character.textAsset as FontAsset;
this.material = this.fontAsset != null ? this.fontAsset.material : null;
this.materialIndex = materialIndex;
}
}
/// <summary>
/// Method used to find and cache references to the Underline and Ellipsis characters.
/// </summary>
/// <param name=""></param>
protected void GetSpecialCharacters(TextGenerationSettings generationSettings)
{
GetEllipsisSpecialCharacter(generationSettings);
GetUnderlineSpecialCharacter(generationSettings);
}
protected void GetEllipsisSpecialCharacter(TextGenerationSettings generationSettings)
{
bool isUsingAlternativeTypeface;
FontAsset fontAsset = m_CurrentFontAsset ?? generationSettings.fontAsset;
TextSettings textSettings = generationSettings.textSettings;
bool populateLigature = generationSettings.fontFeatures.Contains(OTL_FeatureTag.liga);
// Search base font asset
Character character = FontAssetUtilities.GetCharacterFromFontAsset(k_HorizontalEllipsis, fontAsset, false, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, populateLigature);
if (character == null)
{
// Search primary fallback list
if (fontAsset.m_FallbackFontAssetTable != null && fontAsset.m_FallbackFontAssetTable.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal(k_HorizontalEllipsis, fontAsset, fontAsset.m_FallbackFontAssetTable, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, populateLigature);
}
// Search the setting's general fallback list
if (character == null)
{
if (textSettings.fallbackFontAssets != null && textSettings.fallbackFontAssets.Count > 0)
character = FontAssetUtilities.GetCharacterFromFontAssetsInternal(k_HorizontalEllipsis, fontAsset, textSettings.fallbackFontAssets, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, populateLigature);
}
// Search the setting's default font asset
if (character == null)
{
if (textSettings.defaultFontAsset != null)
character = FontAssetUtilities.GetCharacterFromFontAsset(k_HorizontalEllipsis, textSettings.defaultFontAsset, true, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, populateLigature);
}
if (character != null)
m_Ellipsis = new SpecialCharacter(character, 0);
}
protected void GetUnderlineSpecialCharacter(TextGenerationSettings generationSettings)
{
bool isUsingAlternativeTypeface;
FontAsset fontAsset = m_CurrentFontAsset ?? generationSettings.fontAsset;
TextSettings textSettings = generationSettings.textSettings;
bool populateLigature = generationSettings.fontFeatures.Contains(OTL_FeatureTag.liga);
// Search base font asset
Character character = FontAssetUtilities.GetCharacterFromFontAsset(0x5F, fontAsset, false, m_FontStyleInternal, m_FontWeightInternal, out isUsingAlternativeTypeface, populateLigature);
if (character != null)
m_Underline = new SpecialCharacter(character, m_CurrentMaterialIndex);
}
protected void DoMissingGlyphCallback(uint unicode, int stringIndex, FontAsset fontAsset, TextInfo textInfo)
{
// Event to allow users to modify the content of the text info before the text is rendered.
OnMissingCharacter?.Invoke(unicode, stringIndex, textInfo, fontAsset);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorPrepare.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorPrepare.cs",
"repo_id": "UnityCsReference",
"token_count": 35692
} | 466 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEditorInternal;
using System.Collections.Generic;
using UnityEngine.TextCore.Text;
using UnityEngine.TextCore.LowLevel;
using UnityEditor.TextCore.LowLevel;
using Glyph = UnityEngine.TextCore.Glyph;
using GlyphRect = UnityEngine.TextCore.GlyphRect;
using GlyphMetrics = UnityEngine.TextCore.GlyphMetrics;
namespace UnityEditor.TextCore.Text
{
[CustomPropertyDrawer(typeof(FontWeightPair))]
internal class FontWeightDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_regular = property.FindPropertyRelative("regularTypeface");
SerializedProperty prop_italic = property.FindPropertyRelative("italicTypeface");
float width = position.width;
position.width = EditorGUIUtility.labelWidth;
EditorGUI.LabelField(position, label);
int oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
// NORMAL TYPEFACE
if (label.text[0] == '4') GUI.enabled = false;
position.x += position.width; position.width = (width - position.width) / 2;
EditorGUI.PropertyField(position, prop_regular, GUIContent.none);
// ITALIC TYPEFACE
GUI.enabled = true;
position.x += position.width;
EditorGUI.PropertyField(position, prop_italic, GUIContent.none);
EditorGUI.indentLevel = oldIndent;
}
}
[CustomEditor(typeof(FontAsset))]
internal class FontAssetEditor : Editor
{
internal struct UI_PanelState
{
public static bool generationSettingsPanel = true;
public static bool fontAtlasInfoPanel = true;
public static bool fontWeightPanel = true;
public static bool fallbackFontAssetPanel = true;
public static bool glyphTablePanel = false;
public static bool characterTablePanel = false;
public static bool LigatureSubstitutionTablePanel;
public static bool PairAdjustmentTablePanel = false;
public static bool MarkToBaseTablePanel = false;
public static bool MarkToMarkTablePanel = false;
}
internal struct GenerationSettings
{
public Font sourceFont;
public int faceIndex;
public GlyphRenderMode glyphRenderMode;
public int pointSize;
public int padding;
public int atlasWidth;
public int atlasHeight;
}
/// <summary>
/// Material used to display SDF glyphs in the Character and Glyph tables.
/// </summary>
internal static Material internalSDFMaterial
{
get
{
if (s_InternalSDFMaterial == null)
{
Shader shader = TextShaderUtilities.ShaderRef_MobileSDF;
if (shader != null)
s_InternalSDFMaterial = new Material(shader);
}
return s_InternalSDFMaterial;
}
}
static Material s_InternalSDFMaterial;
/// <summary>
/// Material used to display Bitmap glyphs in the Character and Glyph tables.
/// </summary>
internal static Material internalBitmapMaterial
{
get
{
if (s_InternalBitmapMaterial == null)
{
Shader shader = Shader.Find("Hidden/Internal-GUITextureClipText");
if (shader != null)
s_InternalBitmapMaterial = new Material(shader);
}
return s_InternalBitmapMaterial;
}
}
static Material s_InternalBitmapMaterial;
/// <summary>
/// Material used to display color glyphs in the Character and Glyph tables.
/// </summary>
internal static Material internalRGBABitmapMaterial
{
get
{
if (s_Internal_Bitmap_RGBA_Material == null)
{
Shader shader = Shader.Find("Hidden/Internal-GUITextureClip");
if (shader != null)
s_Internal_Bitmap_RGBA_Material = new Material(shader);
}
return s_Internal_Bitmap_RGBA_Material;
}
}
static Material s_Internal_Bitmap_RGBA_Material;
private static string[] s_UiStateLabel = new string[] { "<i>(Click to collapse)</i> ", "<i>(Click to expand)</i> " };
public static readonly GUIContent getFontFeaturesLabel = new GUIContent("Get Font Features", "Determines if OpenType font features should be retrieved from the source font file as new characters and glyphs are added to the font asset.");
private GUIContent[] m_AtlasResolutionLabels = { new GUIContent("8"), new GUIContent("16"), new GUIContent("32"), new GUIContent("64"), new GUIContent("128"), new GUIContent("256"), new GUIContent("512"), new GUIContent("1024"), new GUIContent("2048"), new GUIContent("4096"), new GUIContent("8192") };
private int[] m_AtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
private struct Warning
{
public bool isEnabled;
public double expirationTime;
}
private int m_CurrentGlyphPage = 0;
private int m_CurrentCharacterPage = 0;
private int m_CurrentLigaturePage = 0;
private int m_CurrentAdjustmentPairPage = 0;
private int m_CurrentMarkToBasePage = 0;
private int m_CurrentMarkToMarkPage = 0;
internal int m_SelectedGlyphRecord = -1;
internal int m_SelectedCharacterRecord = -1;
internal int m_SelectedLigatureRecord = -1;
internal int m_SelectedAdjustmentRecord = -1;
internal int m_SelectedMarkToBaseRecord = -1;
internal int m_SelectedMarkToMarkRecord = -1;
enum RecordSelectionType { CharacterRecord, GlyphRecord, LigatureSubstitutionRecord, AdjustmentPairRecord, MarkToBaseRecord, MarkToMarkRecord }
private string m_dstGlyphID;
private string m_dstUnicode;
private const string k_placeholderUnicodeHex = "<i>New Unicode (Hex)</i>";
private string m_unicodeHexLabel = k_placeholderUnicodeHex;
private const string k_placeholderGlyphID = "<i>New Glyph ID</i>";
private string m_GlyphIDLabel = k_placeholderGlyphID;
private Warning m_AddGlyphWarning;
private Warning m_AddCharacterWarning;
private bool m_DisplayDestructiveChangeWarning;
private GenerationSettings m_GenerationSettings;
private bool m_MaterialPresetsRequireUpdate;
private static readonly string[] k_InvalidFontFaces = { string.Empty };
private string[] m_FontFaces;
private bool m_FaceInfoDirty;
private string m_GlyphSearchPattern;
private List<int> m_GlyphSearchList;
private string m_LigatureTableSearchPattern;
private List<int> m_LigatureTableSearchList;
private string m_CharacterSearchPattern;
private List<int> m_CharacterSearchList;
private string m_KerningTableSearchPattern;
private List<int> m_KerningTableSearchList;
private string m_MarkToBaseTableSearchPattern;
private List<int> m_MarkToBaseTableSearchList;
private string m_MarkToMarkTableSearchPattern;
private List<int> m_MarkToMarkTableSearchList;
private HashSet<uint> m_GlyphsToAdd;
private bool m_isSearchDirty;
private const string k_UndoRedo = "UndoRedoPerformed";
private SerializedProperty m_AtlasPopulationMode_prop;
private SerializedProperty font_atlas_prop;
private SerializedProperty font_material_prop;
private SerializedProperty m_FontFaceIndex_prop;
private SerializedProperty m_AtlasRenderMode_prop;
private SerializedProperty m_SamplingPointSize_prop;
private SerializedProperty m_AtlasPadding_prop;
private SerializedProperty m_AtlasWidth_prop;
private SerializedProperty m_AtlasHeight_prop;
private SerializedProperty m_IsMultiAtlasTexturesEnabled_prop;
private SerializedProperty m_ClearDynamicDataOnBuild_prop;
private SerializedProperty m_GetFontFeatures_prop;
private SerializedProperty fontWeights_prop;
//private SerializedProperty fallbackFontAssets_prop;
private ReorderableList m_FallbackFontAssetList;
private SerializedProperty font_normalStyle_prop;
private SerializedProperty font_normalSpacing_prop;
private SerializedProperty font_boldStyle_prop;
private SerializedProperty font_boldSpacing_prop;
private SerializedProperty font_italicStyle_prop;
private SerializedProperty font_tabSize_prop;
private SerializedProperty m_FaceInfo_prop;
private SerializedProperty m_GlyphTable_prop;
private SerializedProperty m_CharacterTable_prop;
private FontFeatureTable m_FontFeatureTable;
private SerializedProperty m_FontFeatureTable_prop;
private SerializedProperty m_GlyphPairAdjustmentRecords_prop;
private SerializedProperty m_LigatureSubstitutionRecords_prop;
private SerializedProperty m_MarkToBaseAdjustmentRecords_prop;
private SerializedProperty m_MarkToMarkAdjustmentRecords_prop;
private SerializedPropertyHolder m_SerializedPropertyHolder;
private SerializedProperty m_EmptyGlyphPairAdjustmentRecord_prop;
private SerializedProperty m_FirstCharacterUnicode_prop;
private SerializedProperty m_SecondCharacterUnicode_prop;
// private string m_SecondCharacter;
// private uint m_SecondGlyphIndex;
private FontAsset m_fontAsset;
private Material[] m_materialPresets;
private bool isAssetDirty = false;
private bool m_IsFallbackGlyphCacheDirty;
private int errorCode;
private System.DateTime timeStamp;
public void OnEnable()
{
m_FaceInfo_prop = serializedObject.FindProperty("m_FaceInfo");
font_atlas_prop = serializedObject.FindProperty("m_AtlasTextures").GetArrayElementAtIndex(0);
font_material_prop = serializedObject.FindProperty("m_Material");
m_FontFaceIndex_prop = m_FaceInfo_prop.FindPropertyRelative("m_FaceIndex");
m_AtlasPopulationMode_prop = serializedObject.FindProperty("m_AtlasPopulationMode");
m_AtlasRenderMode_prop = serializedObject.FindProperty("m_AtlasRenderMode");
m_SamplingPointSize_prop = m_FaceInfo_prop.FindPropertyRelative("m_PointSize");
m_AtlasPadding_prop = serializedObject.FindProperty("m_AtlasPadding");
m_AtlasWidth_prop = serializedObject.FindProperty("m_AtlasWidth");
m_AtlasHeight_prop = serializedObject.FindProperty("m_AtlasHeight");
m_IsMultiAtlasTexturesEnabled_prop = serializedObject.FindProperty("m_IsMultiAtlasTexturesEnabled");
m_ClearDynamicDataOnBuild_prop = serializedObject.FindProperty("m_ClearDynamicDataOnBuild");
m_GetFontFeatures_prop = serializedObject.FindProperty("m_GetFontFeatures");
fontWeights_prop = serializedObject.FindProperty("m_FontWeightTable");
m_FallbackFontAssetList = PrepareReorderableList(serializedObject.FindProperty("m_FallbackFontAssetTable"), "Fallback Font Assets");
// Clean up fallback list in the event if contains null elements.
CleanFallbackFontAssetTable();
font_normalStyle_prop = serializedObject.FindProperty("m_RegularStyleWeight");
font_normalSpacing_prop = serializedObject.FindProperty("m_RegularStyleSpacing");
font_boldStyle_prop = serializedObject.FindProperty("m_BoldStyleWeight");
font_boldSpacing_prop = serializedObject.FindProperty("m_BoldStyleSpacing");
font_italicStyle_prop = serializedObject.FindProperty("m_ItalicStyleSlant");
font_tabSize_prop = serializedObject.FindProperty("m_TabMultiple");
m_CharacterTable_prop = serializedObject.FindProperty("m_CharacterTable");
m_GlyphTable_prop = serializedObject.FindProperty("m_GlyphTable");
m_FontFeatureTable_prop = serializedObject.FindProperty("m_FontFeatureTable");
m_LigatureSubstitutionRecords_prop = m_FontFeatureTable_prop.FindPropertyRelative("m_LigatureSubstitutionRecords");
m_GlyphPairAdjustmentRecords_prop = m_FontFeatureTable_prop.FindPropertyRelative("m_GlyphPairAdjustmentRecords");
m_MarkToBaseAdjustmentRecords_prop = m_FontFeatureTable_prop.FindPropertyRelative("m_MarkToBaseAdjustmentRecords");
m_MarkToMarkAdjustmentRecords_prop = m_FontFeatureTable_prop.FindPropertyRelative("m_MarkToMarkAdjustmentRecords");
m_fontAsset = target as FontAsset;
m_FontFeatureTable = m_fontAsset.fontFeatureTable;
// Get Font Faces and Styles
m_FontFaces = GetFontFaces();
// Create serialized object to allow us to use a serialized property of an empty kerning pair.
m_SerializedPropertyHolder = CreateInstance<SerializedPropertyHolder>();
m_SerializedPropertyHolder.fontAsset = m_fontAsset;
SerializedObject internalSerializedObject = new SerializedObject(m_SerializedPropertyHolder);
m_FirstCharacterUnicode_prop = internalSerializedObject.FindProperty("firstCharacter");
m_SecondCharacterUnicode_prop = internalSerializedObject.FindProperty("secondCharacter");
m_EmptyGlyphPairAdjustmentRecord_prop = internalSerializedObject.FindProperty("glyphPairAdjustmentRecord");
m_materialPresets = TextCoreEditorUtilities.FindMaterialReferences(m_fontAsset);
m_GlyphSearchList = new List<int>();
m_KerningTableSearchList = new List<int>();
// Sort Font Asset Tables
m_fontAsset.SortAllTables();
// Clear glyph proxy lookups
TextCorePropertyDrawerUtilities.ClearGlyphProxyLookups();
}
private ReorderableList PrepareReorderableList(SerializedProperty property, string label)
{
SerializedObject so = property.serializedObject;
ReorderableList list = new ReorderableList(so, property, true, true, true, true);
list.drawHeaderCallback = rect =>
{
EditorGUI.LabelField(rect, label);
};
list.drawElementCallback = (rect, index, isActive, isFocused) =>
{
var element = list.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none);
};
list.onChangedCallback = itemList => { };
return list;
}
public void OnDisable()
{
// Revert changes if user closes or changes selection without having made a choice.
if (m_DisplayDestructiveChangeWarning)
{
m_DisplayDestructiveChangeWarning = false;
RestoreGenerationSettings();
GUIUtility.keyboardControl = 0;
serializedObject.ApplyModifiedProperties();
}
}
internal static Func<bool> IsAdvancedTextEnabled;
public override void OnInspectorGUI()
{
//Debug.Log("OnInspectorGUI Called.");
if (IsAdvancedTextEnabled.Invoke())
{
EditorGUILayout.HelpBox("Enabling the Advanced Text Generator restricts customization of font metrics and static font assets. Additionally, some properties are still in development and may not be available.", MessageType.Warning, true);
}
Event currentEvent = Event.current;
serializedObject.Update();
Rect rect = EditorGUILayout.GetControlRect(false, 24);
float labelWidth = EditorGUIUtility.labelWidth;
float fieldWidth = EditorGUIUtility.fieldWidth;
// FACE INFO PANEL
#region Face info
GUI.Label(rect, new GUIContent("<b>Face Info</b> - v" + m_fontAsset.version), TM_EditorStyles.sectionHeader);
rect.x += rect.width - 132f;
rect.y += 2;
rect.width = 130f;
rect.height = 18f;
if (GUI.Button(rect, new GUIContent("Update Atlas Texture")))
{
FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(target as FontAsset);
}
EditorGUI.indentLevel = 1;
GUI.enabled = false; // Lock UI
// TODO : Consider creating a property drawer for these.
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_FamilyName"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_StyleName"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_PointSize"));
GUI.enabled = true;
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_Scale"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_LineHeight"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_AscentLine"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_CapLine"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_MeanLine"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_Baseline"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_DescentLine"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_UnderlineOffset"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_UnderlineThickness"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_StrikethroughOffset"));
//EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("strikethroughThickness"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SuperscriptOffset"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SuperscriptSize"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SubscriptOffset"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_SubscriptSize"));
EditorGUILayout.PropertyField(m_FaceInfo_prop.FindPropertyRelative("m_TabWidth"));
// TODO : Add clamping for some of these values.
//subSize_prop.floatValue = Mathf.Clamp(subSize_prop.floatValue, 0.25f, 1f);
EditorGUILayout.Space();
#endregion
// GENERATION SETTINGS
#region Generation Settings
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Generation Settings</b>"), TM_EditorStyles.sectionHeader))
UI_PanelState.generationSettingsPanel = !UI_PanelState.generationSettingsPanel;
GUI.Label(rect, (UI_PanelState.generationSettingsPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.generationSettingsPanel)
{
EditorGUI.indentLevel = 1;
EditorGUI.BeginChangeCheck();
Font sourceFont = (Font)EditorGUILayout.ObjectField("Source Font File", m_fontAsset.SourceFont_EditorRef, typeof(Font), false);
if (EditorGUI.EndChangeCheck())
{
UpdateSourceFontFile(sourceFont);
}
EditorGUI.BeginDisabledGroup(sourceFont == null);
{
EditorGUI.BeginChangeCheck();
m_FontFaceIndex_prop.intValue = EditorGUILayout.Popup(new GUIContent("Font Face"), m_FontFaceIndex_prop.intValue, m_FontFaces);
if (EditorGUI.EndChangeCheck())
{
UpdateFontFaceIndex(m_FontFaceIndex_prop.intValue);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AtlasPopulationMode_prop, new GUIContent("Atlas Population Mode"));
if (EditorGUI.EndChangeCheck())
{
UpdateAtlasPopulationMode(m_AtlasPopulationMode_prop.intValue);
}
// Save state of atlas settings
if (m_DisplayDestructiveChangeWarning == false)
{
SavedGenerationSettings();
//Undo.RegisterCompleteObjectUndo(m_fontAsset, "Font Asset Changes");
}
EditorGUI.BeginDisabledGroup(m_AtlasPopulationMode_prop.intValue == (int)AtlasPopulationMode.Static);
{
EditorGUI.BeginChangeCheck();
// TODO: Switch shaders depending on GlyphRenderMode.
EditorGUILayout.PropertyField(m_AtlasRenderMode_prop);
EditorGUILayout.PropertyField(m_SamplingPointSize_prop, new GUIContent("Sampling Point Size"));
if (EditorGUI.EndChangeCheck())
{
m_DisplayDestructiveChangeWarning = true;
}
// Changes to these properties require updating Material Presets for this font asset.
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AtlasPadding_prop, new GUIContent("Padding"));
EditorGUILayout.IntPopup(m_AtlasWidth_prop, m_AtlasResolutionLabels, m_AtlasResolutions, new GUIContent("Atlas Width"));
EditorGUILayout.IntPopup(m_AtlasHeight_prop, m_AtlasResolutionLabels, m_AtlasResolutions, new GUIContent("Atlas Height"));
EditorGUILayout.PropertyField(m_IsMultiAtlasTexturesEnabled_prop, new GUIContent("Multi Atlas Textures", "Determines if the font asset will store glyphs in multiple atlas textures."));
if (EditorGUI.EndChangeCheck())
{
if (m_AtlasPadding_prop.intValue < 0)
{
m_AtlasPadding_prop.intValue = 0;
serializedObject.ApplyModifiedProperties();
}
m_MaterialPresetsRequireUpdate = true;
m_DisplayDestructiveChangeWarning = true;
}
EditorGUILayout.PropertyField(m_ClearDynamicDataOnBuild_prop, new GUIContent("Clear Dynamic Data On Build", "Clears all dynamic data restoring the font asset back to its default creation and empty state."));
EditorGUILayout.PropertyField(m_GetFontFeatures_prop, getFontFeaturesLabel);
EditorGUILayout.Space();
if (m_DisplayDestructiveChangeWarning)
{
bool guiEnabledState = GUI.enabled;
GUI.enabled = true;
// These changes are destructive on the font asset
rect = EditorGUILayout.GetControlRect(false, 60);
rect.x += 15;
rect.width -= 15;
EditorGUI.HelpBox(rect, "Changing these settings will clear the font asset's character, glyph and texture data.", MessageType.Warning);
if (GUI.Button(new Rect(rect.width - 140, rect.y + 36, 80, 18), new GUIContent("Apply")))
{
ApplyDestructiveChanges();
}
if (GUI.Button(new Rect(rect.width - 56, rect.y + 36, 80, 18), new GUIContent("Revert")))
{
RevertDestructiveChanges();
}
GUI.enabled = guiEnabledState;
}
}
EditorGUI.EndDisabledGroup();
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
}
#endregion
// ATLAS & MATERIAL PANEL
#region Atlas & Material
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Atlas & Material</b>"), TM_EditorStyles.sectionHeader))
UI_PanelState.fontAtlasInfoPanel = !UI_PanelState.fontAtlasInfoPanel;
GUI.Label(rect, (UI_PanelState.fontAtlasInfoPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.fontAtlasInfoPanel)
{
EditorGUI.indentLevel = 1;
GUI.enabled = false;
EditorGUILayout.PropertyField(font_atlas_prop, new GUIContent("Font Atlas"));
EditorGUILayout.PropertyField(font_material_prop, new GUIContent("Font Material"));
GUI.enabled = true;
EditorGUILayout.Space();
}
#endregion
string evt_cmd = Event.current.commandName; // Get Current Event CommandName to check for Undo Events
// FONT WEIGHT PANEL
#region Font Weights
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Font Weights</b>", "The Font Assets that will be used for different font weights and the settings used to simulate a typeface when no asset is available."), TM_EditorStyles.sectionHeader))
UI_PanelState.fontWeightPanel = !UI_PanelState.fontWeightPanel;
GUI.Label(rect, (UI_PanelState.fontWeightPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.fontWeightPanel)
{
EditorGUIUtility.labelWidth *= 0.75f;
EditorGUIUtility.fieldWidth *= 0.25f;
EditorGUILayout.BeginVertical();
EditorGUI.indentLevel = 1;
rect = EditorGUILayout.GetControlRect(true);
rect.x += EditorGUIUtility.labelWidth;
rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2f;
GUI.Label(rect, "Regular Typeface", EditorStyles.label);
rect.x += rect.width;
GUI.Label(rect, "Italic Typeface", EditorStyles.label);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(1), new GUIContent("100 - Thin"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(2), new GUIContent("200 - Extra-Light"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(3), new GUIContent("300 - Light"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(4), new GUIContent("400 - Regular"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(5), new GUIContent("500 - Medium"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(6), new GUIContent("600 - Semi-Bold"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(7), new GUIContent("700 - Bold"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(8), new GUIContent("800 - Heavy"));
EditorGUILayout.PropertyField(fontWeights_prop.GetArrayElementAtIndex(9), new GUIContent("900 - Black"));
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
EditorGUILayout.BeginVertical();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_normalStyle_prop, new GUIContent("Regular Weight"));
font_normalStyle_prop.floatValue = Mathf.Clamp(font_normalStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
// Modify the material property on matching material presets.
for (int i = 0; i < m_materialPresets.Length; i++)
m_materialPresets[i].SetFloat("_WeightNormal", font_normalStyle_prop.floatValue);
}
EditorGUILayout.PropertyField(font_boldStyle_prop, new GUIContent("Bold Weight"));
font_boldStyle_prop.floatValue = Mathf.Clamp(font_boldStyle_prop.floatValue, -3.0f, 3.0f);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
// Modify the material property on matching material presets.
for (int i = 0; i < m_materialPresets.Length; i++)
m_materialPresets[i].SetFloat("_WeightBold", font_boldStyle_prop.floatValue);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_normalSpacing_prop, new GUIContent("Regular Spacing"));
font_normalSpacing_prop.floatValue = Mathf.Clamp(font_normalSpacing_prop.floatValue, -100, 100);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
}
EditorGUILayout.PropertyField(font_boldSpacing_prop, new GUIContent("Bold Spacing"));
font_boldSpacing_prop.floatValue = Mathf.Clamp(font_boldSpacing_prop.floatValue, 0, 100);
if (GUI.changed || evt_cmd == k_UndoRedo)
{
GUI.changed = false;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(font_italicStyle_prop, new GUIContent("Italic Slant"));
font_italicStyle_prop.intValue = Mathf.Clamp(font_italicStyle_prop.intValue, 15, 60);
EditorGUILayout.PropertyField(font_tabSize_prop, new GUIContent("Tab Multiple"));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
}
EditorGUIUtility.labelWidth = 0;
EditorGUIUtility.fieldWidth = 0;
#endregion
// FALLBACK FONT ASSETS
#region Fallback Font Asset
rect = EditorGUILayout.GetControlRect(false, 24);
EditorGUI.indentLevel = 0;
if (GUI.Button(rect, new GUIContent("<b>Fallback Font Assets</b>", "Select the Font Assets that will be searched and used as fallback when characters are missing from this font asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.fallbackFontAssetPanel = !UI_PanelState.fallbackFontAssetPanel;
GUI.Label(rect, (UI_PanelState.fallbackFontAssetPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.fallbackFontAssetPanel)
{
EditorGUIUtility.labelWidth = 120;
EditorGUI.indentLevel = 0;
EditorGUI.BeginChangeCheck();
m_FallbackFontAssetList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
{
m_IsFallbackGlyphCacheDirty = true;
}
EditorGUILayout.Space();
}
#endregion
// CHARACTER TABLE TABLE
#region Character Table
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
int characterCount = m_fontAsset.characterTable.Count;
if (GUI.Button(rect, new GUIContent("<b>Character Table</b> [" + characterCount + "]" + (rect.width > 320 ? " Characters" : ""), "List of characters contained in this font asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.characterTablePanel = !UI_PanelState.characterTablePanel;
GUI.Label(rect, (UI_PanelState.characterTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.characterTablePanel)
{
int arraySize = m_CharacterTable_prop.arraySize;
int itemsPerPage = 15;
// Display Glyph Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 130f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Character Search", m_CharacterSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_CharacterSearchPattern = searchPattern;
// Search Character Table for potential matches
SearchCharacterTable(m_CharacterSearchPattern, ref m_CharacterSearchList);
}
else
m_CharacterSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_CharacterSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_CharacterSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_CharacterSearchPattern))
arraySize = m_CharacterSearchList.Count;
DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
// Display Character Table Elements
if (arraySize > 0)
{
// Display each character entry using the CharacterPropertyDrawer.
for (int i = itemsPerPage * m_CurrentCharacterPage; i < arraySize && i < itemsPerPage * (m_CurrentCharacterPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_CharacterSearchPattern))
elementIndex = m_CharacterSearchList[i];
SerializedProperty characterProperty = m_CharacterTable_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUI.BeginDisabledGroup(i != m_SelectedCharacterRecord);
{
EditorGUILayout.PropertyField(characterProperty);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedCharacterRecord == i)
m_SelectedCharacterRecord = -1;
else
{
m_SelectedCharacterRecord = i;
m_AddCharacterWarning.isEnabled = false;
m_unicodeHexLabel = k_placeholderUnicodeHex;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Glyph Options
if (m_SelectedCharacterRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.CharacterRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width * 0.6f;
float btnWidth = optionAreaWidth / 3;
Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height);
// Copy Selected Glyph to Target Glyph ID
GUI.enabled = !string.IsNullOrEmpty(m_dstUnicode);
if (GUI.Button(position, new GUIContent("Copy to")))
{
GUIUtility.keyboardControl = 0;
// Convert Hex Value to Decimal
int dstGlyphID = (int)TextUtilities.StringHexToInt(m_dstUnicode);
//Add new glyph at target Unicode hex id.
if (!AddNewCharacter(elementIndex, dstGlyphID))
{
m_AddCharacterWarning.isEnabled = true;
m_AddCharacterWarning.expirationTime = EditorApplication.timeSinceStartup + 1;
}
m_dstUnicode = string.Empty;
m_isSearchDirty = true;
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
}
// Target Glyph ID
GUI.enabled = true;
position.x += btnWidth;
GUI.SetNextControlName("CharacterID_Input");
m_dstUnicode = EditorGUI.TextField(position, m_dstUnicode);
// Placeholder text
EditorGUI.LabelField(position, new GUIContent(m_unicodeHexLabel, "The Unicode (Hex) ID of the duplicated Character"), TM_EditorStyles.label);
// Only filter the input when the destination glyph ID text field has focus.
if (GUI.GetNameOfFocusedControl() == "CharacterID_Input")
{
m_unicodeHexLabel = string.Empty;
//Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F'))
{
Event.current.character = '\0';
}
}
else
{
m_unicodeHexLabel = k_placeholderUnicodeHex;
//m_dstUnicode = string.Empty;
}
// Remove Glyph
position.x += btnWidth;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveCharacterFromList(elementIndex);
isAssetDirty = true;
m_SelectedCharacterRecord = -1;
m_isSearchDirty = true;
break;
}
if (m_AddCharacterWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddCharacterWarning.expirationTime)
{
EditorGUILayout.HelpBox("The Destination Character ID already exists", MessageType.Warning);
}
}
}
}
DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage);
EditorGUILayout.Space();
}
#endregion
// GLYPH TABLE
#region Glyph Table
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
GUIStyle glyphPanelStyle = new GUIStyle(EditorStyles.helpBox);
int glyphCount = m_fontAsset.glyphTable.Count;
if (GUI.Button(rect, new GUIContent("<b>Glyph Table</b> [" + glyphCount + "]" + (rect.width > 275 ? " Glyphs" : ""), "List of glyphs contained in this font asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.glyphTablePanel = !UI_PanelState.glyphTablePanel;
GUI.Label(rect, (UI_PanelState.glyphTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.glyphTablePanel)
{
int arraySize = m_GlyphTable_prop.arraySize;
int itemsPerPage = 15;
// Display Glyph Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 130f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Glyph Search", m_GlyphSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_GlyphSearchPattern = searchPattern;
// Search Glyph Table for potential matches
SearchGlyphTable(m_GlyphSearchPattern, ref m_GlyphSearchList);
}
else
m_GlyphSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_GlyphSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_GlyphSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
arraySize = m_GlyphSearchList.Count;
DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
// Display Glyph Table Elements
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_CurrentGlyphPage; i < arraySize && i < itemsPerPage * (m_CurrentGlyphPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
elementIndex = m_GlyphSearchList[i];
SerializedProperty glyphProperty = m_GlyphTable_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(glyphPanelStyle);
using (new EditorGUI.DisabledScope(i != m_SelectedGlyphRecord))
{
EditorGUILayout.PropertyField(glyphProperty);
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedGlyphRecord == i)
m_SelectedGlyphRecord = -1;
else
{
m_SelectedGlyphRecord = i;
m_AddGlyphWarning.isEnabled = false;
m_unicodeHexLabel = k_placeholderUnicodeHex;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Glyph Options
if (m_SelectedGlyphRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.GlyphRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width * 0.6f;
float btnWidth = optionAreaWidth / 3;
Rect position = new Rect(controlRect.x + controlRect.width * .4f, controlRect.y, btnWidth, controlRect.height);
// Copy Selected Glyph to Target Glyph ID
GUI.enabled = !string.IsNullOrEmpty(m_dstGlyphID);
if (GUI.Button(position, new GUIContent("Copy to")))
{
GUIUtility.keyboardControl = 0;
int dstGlyphID;
// Convert Hex Value to Decimal
int.TryParse(m_dstGlyphID, out dstGlyphID);
//Add new glyph at target Unicode hex id.
if (!AddNewGlyph(elementIndex, dstGlyphID))
{
m_AddGlyphWarning.isEnabled = true;
m_AddGlyphWarning.expirationTime = EditorApplication.timeSinceStartup + 1;
}
m_dstGlyphID = string.Empty;
m_isSearchDirty = true;
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
}
// Target Glyph ID
GUI.enabled = true;
position.x += btnWidth;
GUI.SetNextControlName("GlyphID_Input");
m_dstGlyphID = EditorGUI.TextField(position, m_dstGlyphID);
// Placeholder text
EditorGUI.LabelField(position, new GUIContent(m_GlyphIDLabel, "The Glyph ID of the duplicated Glyph"), TM_EditorStyles.label);
// Only filter the input when the destination glyph ID text field has focus.
if (GUI.GetNameOfFocusedControl() == "GlyphID_Input")
{
m_GlyphIDLabel = string.Empty;
//Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9'))
{
Event.current.character = '\0';
}
}
else
{
m_GlyphIDLabel = k_placeholderGlyphID;
//m_dstGlyphID = string.Empty;
}
// Remove Glyph
position.x += btnWidth;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveGlyphFromList(elementIndex);
isAssetDirty = true;
m_SelectedGlyphRecord = -1;
m_isSearchDirty = true;
break;
}
if (m_AddGlyphWarning.isEnabled && EditorApplication.timeSinceStartup < m_AddGlyphWarning.expirationTime)
{
EditorGUILayout.HelpBox("The Destination Glyph ID already exists", MessageType.Warning);
}
}
}
}
//DisplayAddRemoveButtons(m_GlyphTable_prop, m_SelectedGlyphRecord, glyphRecordCount);
DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);
EditorGUILayout.Space();
}
#endregion
// FONT FEATURE TABLES
// LIGATURE SUBSTITUTION TABLE
#region LIGATURE
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
int ligatureSubstitutionRecordCount = m_fontAsset.fontFeatureTable.ligatureRecords.Count;
if (GUI.Button(rect, new GUIContent("<b>Ligature Table</b> [" + ligatureSubstitutionRecordCount + "]" + (rect.width > 340 ? " Records" : ""), "List of Ligature substitution records."), TM_EditorStyles.sectionHeader))
UI_PanelState.LigatureSubstitutionTablePanel = !UI_PanelState.LigatureSubstitutionTablePanel;
GUI.Label(rect, (UI_PanelState.LigatureSubstitutionTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.LigatureSubstitutionTablePanel)
{
int arraySize = m_LigatureSubstitutionRecords_prop.arraySize;
int itemsPerPage = 20;
// Display Mark Adjust Records Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 150f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Ligature Search", m_LigatureTableSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_LigatureTableSearchPattern = searchPattern;
// Search Glyph Table for potential matches
SearchLigatureTable(m_LigatureTableSearchPattern, ref m_LigatureTableSearchList);
}
else
m_LigatureTableSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_LigatureTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_LigatureTableSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_LigatureTableSearchPattern))
arraySize = m_LigatureTableSearchList.Count;
DisplayPageNavigation(ref m_CurrentLigaturePage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_CurrentLigaturePage; i < arraySize && i < itemsPerPage * (m_CurrentLigaturePage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_LigatureTableSearchPattern))
elementIndex = m_LigatureTableSearchList[i];
SerializedProperty ligaturePropertyRecord = m_LigatureSubstitutionRecords_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
using (new EditorGUI.DisabledScope(i != m_SelectedLigatureRecord))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(ligaturePropertyRecord, new GUIContent("Selectable"));
if (EditorGUI.EndChangeCheck())
{
UpdateLigatureSubstitutionRecordLookup(ligaturePropertyRecord);
}
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedLigatureRecord == i)
{
m_SelectedLigatureRecord = -1;
}
else
{
m_SelectedLigatureRecord = i;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Kerning Pair Options
if (m_SelectedLigatureRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.LigatureSubstitutionRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width;
float btnWidth = optionAreaWidth / 4;
Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height);
// Move record up
bool guiEnabled = GUI.enabled;
if (m_SelectedLigatureRecord == 0) { GUI.enabled = false; }
if (GUI.Button(new Rect(controlRect.x, controlRect.y, btnWidth, controlRect.height), "Up"))
{
SwapCharacterElements(m_LigatureSubstitutionRecords_prop, m_SelectedLigatureRecord, m_SelectedLigatureRecord - 1);
serializedObject.ApplyModifiedProperties();
m_SelectedLigatureRecord -= 1;
isAssetDirty = true;
m_isSearchDirty = true;
m_fontAsset.InitializeLigatureSubstitutionLookupDictionary();
}
GUI.enabled = guiEnabled;
// Move record down
if (m_SelectedLigatureRecord == arraySize - 1) { GUI.enabled = false; }
if (GUI.Button(new Rect(controlRect.x + btnWidth, controlRect.y, btnWidth, controlRect.height), "Down"))
{
SwapCharacterElements(m_LigatureSubstitutionRecords_prop, m_SelectedLigatureRecord, m_SelectedLigatureRecord + 1);
serializedObject.ApplyModifiedProperties();
m_SelectedLigatureRecord += 1;
isAssetDirty = true;
m_isSearchDirty = true;
m_fontAsset.InitializeLigatureSubstitutionLookupDictionary();
}
GUI.enabled = guiEnabled;
// Remove record
GUI.enabled = true;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveRecord(m_LigatureSubstitutionRecords_prop, m_SelectedLigatureRecord);
isAssetDirty = true;
m_SelectedLigatureRecord = -1;
m_isSearchDirty = true;
break;
}
}
}
}
DisplayAddRemoveButtons(m_LigatureSubstitutionRecords_prop, m_SelectedLigatureRecord, ligatureSubstitutionRecordCount);
DisplayPageNavigation(ref m_CurrentLigaturePage, arraySize, itemsPerPage);
GUILayout.Space(5);
}
#endregion
// PAIR ADJUSTMENT TABLE
#region Pair Adjustment Table
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
int adjustmentPairCount = m_fontAsset.fontFeatureTable.glyphPairAdjustmentRecords.Count;
if (GUI.Button(rect, new GUIContent("<b>Glyph Adjustment Table</b> [" + adjustmentPairCount + "]" + (rect.width > 340 ? " Records" : ""), "List of glyph adjustment / advanced kerning pairs."), TM_EditorStyles.sectionHeader))
UI_PanelState.PairAdjustmentTablePanel = !UI_PanelState.PairAdjustmentTablePanel;
GUI.Label(rect, (UI_PanelState.PairAdjustmentTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.PairAdjustmentTablePanel)
{
int arraySize = m_GlyphPairAdjustmentRecords_prop.arraySize;
int itemsPerPage = 20;
// Display Kerning Pair Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 150f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Adjustment Pair Search", m_KerningTableSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_KerningTableSearchPattern = searchPattern;
// Search Glyph Table for potential matches
SearchKerningTable(m_KerningTableSearchPattern, ref m_KerningTableSearchList);
}
else
m_KerningTableSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_KerningTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_KerningTableSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_KerningTableSearchPattern))
arraySize = m_KerningTableSearchList.Count;
DisplayPageNavigation(ref m_CurrentAdjustmentPairPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_CurrentAdjustmentPairPage; i < arraySize && i < itemsPerPage * (m_CurrentAdjustmentPairPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_KerningTableSearchPattern))
elementIndex = m_KerningTableSearchList[i];
SerializedProperty pairAdjustmentRecordProperty = m_GlyphPairAdjustmentRecords_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
using (new EditorGUI.DisabledScope(i != m_SelectedAdjustmentRecord))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(pairAdjustmentRecordProperty, new GUIContent("Selectable"));
if (EditorGUI.EndChangeCheck())
{
UpdatePairAdjustmentRecordLookup(pairAdjustmentRecordProperty);
}
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedAdjustmentRecord == i)
{
m_SelectedAdjustmentRecord = -1;
}
else
{
m_SelectedAdjustmentRecord = i;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Kerning Pair Options
if (m_SelectedAdjustmentRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.AdjustmentPairRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width;
float btnWidth = optionAreaWidth / 4;
Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height);
// Remove Kerning pair
GUI.enabled = true;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveRecord(m_GlyphPairAdjustmentRecords_prop, i);
isAssetDirty = true;
m_SelectedAdjustmentRecord = -1;
m_isSearchDirty = true;
break;
}
}
}
}
DisplayPageNavigation(ref m_CurrentAdjustmentPairPage, arraySize, itemsPerPage);
GUILayout.Space(5);
// Add new kerning pair
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_EmptyGlyphPairAdjustmentRecord_prop);
if (EditorGUI.EndChangeCheck())
{
SetPropertyHolderGlyphIndexes();
}
}
EditorGUILayout.EndVertical();
if (GUILayout.Button("Add New Glyph Adjustment Record"))
{
SerializedProperty firstAdjustmentRecordProperty = m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_FirstAdjustmentRecord");
SerializedProperty secondAdjustmentRecordProperty = m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_SecondAdjustmentRecord");
uint firstGlyphIndex = (uint)firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue;
uint secondGlyphIndex = (uint)secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue;
GlyphValueRecord firstValueRecord = GetValueRecord(firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord"));
GlyphValueRecord secondValueRecord = GetValueRecord(secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord"));
errorCode = -1;
uint pairKey = secondGlyphIndex << 16 | firstGlyphIndex;
if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(pairKey) == false)
{
GlyphPairAdjustmentRecord adjustmentRecord = new GlyphPairAdjustmentRecord(new GlyphAdjustmentRecord(firstGlyphIndex, firstValueRecord), new GlyphAdjustmentRecord(secondGlyphIndex, secondValueRecord));
m_FontFeatureTable.glyphPairAdjustmentRecords.Add(adjustmentRecord);
m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.Add(pairKey, adjustmentRecord);
errorCode = 0;
}
// Add glyphs and characters
Character character;
uint firstCharacter = m_SerializedPropertyHolder.firstCharacter;
if (!m_fontAsset.characterLookupTable.ContainsKey(firstCharacter))
m_fontAsset.TryAddCharacterInternal(firstCharacter, FontStyles.Normal, TextFontWeight.Regular, out character);
uint secondCharacter = m_SerializedPropertyHolder.secondCharacter;
if (!m_fontAsset.characterLookupTable.ContainsKey(secondCharacter))
m_fontAsset.TryAddCharacterInternal(secondCharacter, FontStyles.Normal, TextFontWeight.Regular, out character);
// Sort Kerning Pairs & Reload Font Asset if new kerning pair was added.
if (errorCode != -1)
{
m_FontFeatureTable.SortGlyphPairAdjustmentRecords();
serializedObject.ApplyModifiedProperties();
isAssetDirty = true;
m_isSearchDirty = true;
}
else
{
timeStamp = System.DateTime.Now.AddSeconds(5);
}
// Clear Add Kerning Pair Panel
// TODO
}
if (errorCode == -1)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label("Kerning Pair already <color=#ffff00>exists!</color>", TM_EditorStyles.label);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (System.DateTime.Now > timeStamp)
errorCode = 0;
}
}
#endregion
// MARK TO BASE Font Feature Table
#region MARK TO BASE
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
int markToBaseAdjustmentRecordCount = m_fontAsset.fontFeatureTable.MarkToBaseAdjustmentRecords.Count;
if (GUI.Button(rect, new GUIContent("<b>Mark To Base Adjustment Table</b> [" + markToBaseAdjustmentRecordCount + "]" + (rect.width > 340 ? " Records" : ""), "List of Mark to Base adjustment records."), TM_EditorStyles.sectionHeader))
UI_PanelState.MarkToBaseTablePanel = !UI_PanelState.MarkToBaseTablePanel;
GUI.Label(rect, (UI_PanelState.MarkToBaseTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.MarkToBaseTablePanel)
{
int arraySize = m_MarkToBaseAdjustmentRecords_prop.arraySize;
int itemsPerPage = 20;
// Display Mark Adjust Records Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 150f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Mark to Base Search", m_MarkToBaseTableSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_MarkToBaseTableSearchPattern = searchPattern;
// Search Glyph Table for potential matches
SearchMarkToBaseTable(m_MarkToBaseTableSearchPattern, ref m_MarkToBaseTableSearchList);
}
else
m_MarkToBaseTableSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_MarkToBaseTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_MarkToBaseTableSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_MarkToBaseTableSearchPattern))
arraySize = m_MarkToBaseTableSearchList.Count;
DisplayPageNavigation(ref m_CurrentMarkToBasePage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_CurrentMarkToBasePage; i < arraySize && i < itemsPerPage * (m_CurrentMarkToBasePage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_MarkToBaseTableSearchPattern))
elementIndex = m_MarkToBaseTableSearchList[i];
SerializedProperty markToBasePropertyRecord = m_MarkToBaseAdjustmentRecords_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
using (new EditorGUI.DisabledScope(i != m_SelectedMarkToBaseRecord))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(markToBasePropertyRecord, new GUIContent("Selectable"));
if (EditorGUI.EndChangeCheck())
{
UpdateMarkToBaseAdjustmentRecordLookup(markToBasePropertyRecord);
}
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedMarkToBaseRecord == i)
{
m_SelectedMarkToBaseRecord = -1;
}
else
{
m_SelectedMarkToBaseRecord = i;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Kerning Pair Options
if (m_SelectedMarkToBaseRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.MarkToBaseRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width;
float btnWidth = optionAreaWidth / 4;
Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height);
// Remove Mark to Base Record
GUI.enabled = true;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveRecord(m_MarkToBaseAdjustmentRecords_prop, i);
isAssetDirty = true;
m_SelectedMarkToBaseRecord = -1;
m_isSearchDirty = true;
break;
}
}
}
}
DisplayAddRemoveButtons(m_MarkToBaseAdjustmentRecords_prop, m_SelectedMarkToBaseRecord, markToBaseAdjustmentRecordCount);
DisplayPageNavigation(ref m_CurrentMarkToBasePage, arraySize, itemsPerPage);
GUILayout.Space(5);
}
#endregion
// MARK TO MARK Font Feature Table
#region MARK TO MARK
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
int markToMarkAdjustmentRecordCount = m_fontAsset.fontFeatureTable.MarkToMarkAdjustmentRecords.Count;
if (GUI.Button(rect, new GUIContent("<b>Mark To Mark Adjustment Table</b> [" + markToMarkAdjustmentRecordCount + "]" + (rect.width > 340 ? " Records" : ""), "List of Mark to Mark adjustment records."), TM_EditorStyles.sectionHeader))
UI_PanelState.MarkToMarkTablePanel = !UI_PanelState.MarkToMarkTablePanel;
GUI.Label(rect, (UI_PanelState.MarkToMarkTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.MarkToMarkTablePanel)
{
int arraySize = m_MarkToMarkAdjustmentRecords_prop.arraySize;
int itemsPerPage = 20;
// Display Kerning Pair Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 150f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Mark to Mark Search", m_MarkToMarkTableSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_isSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
m_MarkToMarkTableSearchPattern = searchPattern;
// Search Glyph Table for potential matches
SearchMarkToMarkTable(m_MarkToMarkTableSearchPattern, ref m_MarkToMarkTableSearchList);
}
else
m_MarkToMarkTableSearchPattern = null;
m_isSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_MarkToMarkTableSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_MarkToMarkTableSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_MarkToMarkTableSearchPattern))
arraySize = m_MarkToMarkTableSearchList.Count;
DisplayPageNavigation(ref m_CurrentMarkToMarkPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each GlyphInfo entry using the GlyphInfo property drawer.
for (int i = itemsPerPage * m_CurrentMarkToMarkPage; i < arraySize && i < itemsPerPage * (m_CurrentMarkToMarkPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_MarkToMarkTableSearchPattern))
elementIndex = m_MarkToMarkTableSearchList[i];
SerializedProperty markToMarkPropertyRecord = m_MarkToMarkAdjustmentRecords_prop.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
using (new EditorGUI.DisabledScope(i != m_SelectedMarkToMarkRecord))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(markToMarkPropertyRecord, new GUIContent("Selectable"));
if (EditorGUI.EndChangeCheck())
{
UpdateMarkToMarkAdjustmentRecordLookup(markToMarkPropertyRecord);
}
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedMarkToMarkRecord == i)
{
m_SelectedMarkToMarkRecord = -1;
}
else
{
m_SelectedMarkToMarkRecord = i;
GUIUtility.keyboardControl = 0;
}
}
// Draw Selection Highlight and Kerning Pair Options
if (m_SelectedMarkToMarkRecord == i)
{
// Reset other selections
ResetSelections(RecordSelectionType.MarkToMarkRecord);
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw Glyph management options
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
float optionAreaWidth = controlRect.width;
float btnWidth = optionAreaWidth / 4;
Rect position = new Rect(controlRect.x + controlRect.width - btnWidth, controlRect.y, btnWidth, controlRect.height);
// Remove Mark to Base Record
GUI.enabled = true;
if (GUI.Button(position, "Remove"))
{
GUIUtility.keyboardControl = 0;
RemoveRecord(m_MarkToMarkAdjustmentRecords_prop, i);
isAssetDirty = true;
m_SelectedMarkToMarkRecord = -1;
m_isSearchDirty = true;
break;
}
}
}
}
DisplayAddRemoveButtons(m_MarkToMarkAdjustmentRecords_prop, m_SelectedMarkToMarkRecord, markToMarkAdjustmentRecordCount);
DisplayPageNavigation(ref m_CurrentMarkToMarkPage, arraySize, itemsPerPage);
GUILayout.Space(5);
}
#endregion
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty || m_IsFallbackGlyphCacheDirty)
{
// Delay callback until user has decided to Apply or Revert the changes.
if (m_DisplayDestructiveChangeWarning == false)
{
TextResourceManager.RebuildFontAssetCache();
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);
m_IsFallbackGlyphCacheDirty = false;
}
if (m_fontAsset.IsFontAssetLookupTablesDirty || evt_cmd == k_UndoRedo)
m_fontAsset.ReadFontAssetDefinition();
isAssetDirty = false;
EditorUtility.SetDirty(target);
}
// Clear selection if mouse event was not consumed.
GUI.enabled = true;
if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
{
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToBaseRecord = -1;
m_SelectedMarkToMarkRecord = -1;
}
}
/// <summary>
/// Overrided method from the Editor class.
/// </summary>
/// <returns></returns>
[UnityEngine.Internal.ExcludeFromDocs]
public override bool HasPreviewGUI()
{
return true;
}
/// <summary>
/// Overrided method to implement custom preview inspector.
/// </summary>
/// <param name="rect"></param>
/// <param name="background"></param>
[UnityEngine.Internal.ExcludeFromDocs]
public override void OnPreviewGUI(Rect rect, GUIStyle background)
{
if (m_SelectedMarkToBaseRecord != -1)
DrawMarkToBasePreview(m_SelectedMarkToBaseRecord, rect);
if (m_SelectedMarkToMarkRecord != -1)
DrawMarkToMarkPreview(m_SelectedMarkToMarkRecord, rect);
}
void ResetSelections(RecordSelectionType type)
{
switch (type)
{
case RecordSelectionType.CharacterRecord:
m_SelectedGlyphRecord = -1;
m_SelectedLigatureRecord = -1;
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToBaseRecord = -1;
m_SelectedMarkToMarkRecord = -1;
break;
case RecordSelectionType.GlyphRecord:
m_SelectedCharacterRecord = -1;
m_SelectedLigatureRecord = -1;
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToBaseRecord = -1;
m_SelectedMarkToMarkRecord = -1;
break;
case RecordSelectionType.LigatureSubstitutionRecord:
m_SelectedCharacterRecord = -1;
m_SelectedGlyphRecord = -1;
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToBaseRecord = -1;
m_SelectedMarkToMarkRecord = -1;
break;
case RecordSelectionType.AdjustmentPairRecord:
m_SelectedCharacterRecord = -1;
m_SelectedGlyphRecord = -1;
m_SelectedLigatureRecord = -1;
m_SelectedMarkToBaseRecord = -1;
m_SelectedMarkToMarkRecord = -1;
break;
case RecordSelectionType.MarkToBaseRecord:
m_SelectedCharacterRecord = -1;
m_SelectedGlyphRecord = -1;
m_SelectedLigatureRecord = -1;
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToMarkRecord = -1;
break;
case RecordSelectionType.MarkToMarkRecord:
m_SelectedCharacterRecord = -1;
m_SelectedGlyphRecord = -1;
m_SelectedLigatureRecord = -1;
m_SelectedAdjustmentRecord = -1;
m_SelectedMarkToBaseRecord = -1;
break;
}
}
string[] GetFontFaces()
{
return GetFontFaces(m_FontFaceIndex_prop.intValue);
}
string[] GetFontFaces(int faceIndex)
{
if (LoadFontFace(m_SamplingPointSize_prop.intValue, faceIndex) == FontEngineError.Success)
return FontEngine.GetFontFaces();
return k_InvalidFontFaces;
}
FontEngineError LoadFontFace(int pointSize, int faceIndex)
{
if (m_fontAsset.SourceFont_EditorRef != null)
{
if (FontEngine.LoadFontFace(m_fontAsset.SourceFont_EditorRef, pointSize, faceIndex) == FontEngineError.Success)
return FontEngineError.Success;
}
return FontEngine.LoadFontFace(m_fontAsset.faceInfo.familyName, m_fontAsset.faceInfo.styleName, pointSize);
}
void CleanFallbackFontAssetTable()
{
SerializedProperty m_FallbackFontAsseTable = serializedObject.FindProperty("m_FallbackFontAssetTable");
bool isListDirty = false;
int elementCount = m_FallbackFontAsseTable.arraySize;
for (int i = 0; i < elementCount; i++)
{
SerializedProperty element = m_FallbackFontAsseTable.GetArrayElementAtIndex(i);
if (element.objectReferenceValue == null)
{
m_FallbackFontAsseTable.DeleteArrayElementAtIndex(i);
elementCount -= 1;
i -= 1;
isListDirty = true;
}
}
if (isListDirty)
{
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}
internal void SavedGenerationSettings()
{
m_GenerationSettings.faceIndex = m_FontFaceIndex_prop.intValue;
m_GenerationSettings.glyphRenderMode = (GlyphRenderMode)m_AtlasRenderMode_prop.intValue;
m_GenerationSettings.pointSize = m_SamplingPointSize_prop.intValue;
m_GenerationSettings.padding = m_AtlasPadding_prop.intValue;
m_GenerationSettings.atlasWidth = m_AtlasWidth_prop.intValue;
m_GenerationSettings.atlasHeight = m_AtlasHeight_prop.intValue;
}
internal void RestoreGenerationSettings()
{
m_fontAsset.SourceFont_EditorRef = m_GenerationSettings.sourceFont;
m_FontFaceIndex_prop.intValue = m_GenerationSettings.faceIndex;
m_SamplingPointSize_prop.intValue = m_GenerationSettings.pointSize;
m_FontFaces = GetFontFaces();
m_AtlasRenderMode_prop.intValue = (int)m_GenerationSettings.glyphRenderMode;
m_AtlasPadding_prop.intValue = m_GenerationSettings.padding;
m_AtlasWidth_prop.intValue = m_GenerationSettings.atlasWidth;
m_AtlasHeight_prop.intValue = m_GenerationSettings.atlasHeight;
}
void UpdateFontAssetCreationSettings()
{
m_fontAsset.m_fontAssetCreationEditorSettings.faceIndex = m_FontFaceIndex_prop.intValue;
m_fontAsset.m_fontAssetCreationEditorSettings.pointSize = m_SamplingPointSize_prop.intValue;
m_fontAsset.m_fontAssetCreationEditorSettings.renderMode = m_AtlasRenderMode_prop.intValue;
m_fontAsset.m_fontAssetCreationEditorSettings.padding = m_AtlasPadding_prop.intValue;
m_fontAsset.m_fontAssetCreationEditorSettings.atlasWidth = m_AtlasWidth_prop.intValue;
m_fontAsset.m_fontAssetCreationEditorSettings.atlasHeight = m_AtlasHeight_prop.intValue;
}
void UpdateCharacterData(SerializedProperty property, int index)
{
Character character = m_fontAsset.characterTable[index];
character.unicode = (uint)property.FindPropertyRelative("m_Unicode").intValue;
character.scale = property.FindPropertyRelative("m_Scale").floatValue;
SerializedProperty glyphProperty = property.FindPropertyRelative("m_Glyph");
character.glyph.index = (uint)glyphProperty.FindPropertyRelative("m_Index").intValue;
SerializedProperty glyphRectProperty = glyphProperty.FindPropertyRelative("m_GlyphRect");
character.glyph.glyphRect = new GlyphRect(glyphRectProperty.FindPropertyRelative("m_X").intValue, glyphRectProperty.FindPropertyRelative("m_Y").intValue, glyphRectProperty.FindPropertyRelative("m_Width").intValue, glyphRectProperty.FindPropertyRelative("m_Height").intValue);
SerializedProperty glyphMetricsProperty = glyphProperty.FindPropertyRelative("m_Metrics");
character.glyph.metrics = new UnityEngine.TextCore.GlyphMetrics(glyphMetricsProperty.FindPropertyRelative("m_Width").floatValue, glyphMetricsProperty.FindPropertyRelative("m_Height").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalBearingX").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalBearingY").floatValue, glyphMetricsProperty.FindPropertyRelative("m_HorizontalAdvance").floatValue);
character.glyph.scale = glyphProperty.FindPropertyRelative("m_Scale").floatValue;
character.glyph.atlasIndex = glyphProperty.FindPropertyRelative("m_AtlasIndex").intValue;
}
void UpdateGlyphData(SerializedProperty property, int index)
{
UnityEngine.TextCore.Glyph glyph = m_fontAsset.glyphTable[index];
glyph.index = (uint)property.FindPropertyRelative("m_Index").intValue;
SerializedProperty glyphRect = property.FindPropertyRelative("m_GlyphRect");
glyph.glyphRect = new GlyphRect(glyphRect.FindPropertyRelative("m_X").intValue, glyphRect.FindPropertyRelative("m_Y").intValue, glyphRect.FindPropertyRelative("m_Width").intValue, glyphRect.FindPropertyRelative("m_Height").intValue);
SerializedProperty glyphMetrics = property.FindPropertyRelative("m_Metrics");
glyph.metrics = new GlyphMetrics(glyphMetrics.FindPropertyRelative("m_Width").floatValue, glyphMetrics.FindPropertyRelative("m_Height").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue, glyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue);
glyph.scale = property.FindPropertyRelative("m_Scale").floatValue;
}
void DisplayAddRemoveButtons(SerializedProperty property, int selectedRecord, int recordCount)
{
Rect rect = EditorGUILayout.GetControlRect(false, 20);
rect.width /= 6;
// Add Style
rect.x = rect.width * 4 + 15;
if (GUI.Button(rect, "+"))
{
int index = selectedRecord == -1 ? 0 : selectedRecord;
if (index > recordCount)
index = recordCount;
// Copy selected element
property.InsertArrayElementAtIndex(index);
// Select newly inserted element
selectedRecord = index + 1;
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontAssetDefinition();
}
// Delete style
rect.x += rect.width;
if (selectedRecord == -1 || selectedRecord >= recordCount) GUI.enabled = false;
if (GUI.Button(rect, "-"))
{
int index = selectedRecord == -1 ? 0 : selectedRecord;
property.DeleteArrayElementAtIndex(index);
selectedRecord = -1;
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontAssetDefinition();
return;
}
GUI.enabled = true;
}
void DisplayPageNavigation(ref int currentPage, int arraySize, int itemsPerPage)
{
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 3;
int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward
// Previous Page
GUI.enabled = currentPage > 0;
if (GUI.Button(pagePos, "Previous Page"))
currentPage -= 1 * shiftMultiplier;
// Page Counter
GUI.enabled = true;
pagePos.x += pagePos.width;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Label(pagePos, "Page " + (currentPage + 1) + " / " + totalPages, TM_EditorStyles.centeredLabel);
// Next Page
pagePos.x += pagePos.width;
GUI.enabled = itemsPerPage * (currentPage + 1) < arraySize;
if (GUI.Button(pagePos, "Next Page"))
currentPage += 1 * shiftMultiplier;
// Clamp page range
currentPage = Mathf.Clamp(currentPage, 0, arraySize / itemsPerPage);
GUI.enabled = true;
}
/// <summary>
///
/// </summary>
/// <param name="srcGlyphID"></param>
/// <param name="dstGlyphID"></param>
bool AddNewGlyph(int srcIndex, int dstGlyphID)
{
// Make sure Destination Glyph ID doesn't already contain a Glyph
if (m_fontAsset.glyphLookupTable.ContainsKey((uint)dstGlyphID))
return false;
// Add new element to glyph list.
m_GlyphTable_prop.arraySize += 1;
// Get a reference to the source glyph.
SerializedProperty sourceGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(srcIndex);
int dstIndex = m_GlyphTable_prop.arraySize - 1;
// Get a reference to the target / destination glyph.
SerializedProperty targetGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(dstIndex);
CopyGlyphSerializedProperty(sourceGlyph, ref targetGlyph);
// Update the ID of the glyph
targetGlyph.FindPropertyRelative("m_Index").intValue = dstGlyphID;
serializedObject.ApplyModifiedProperties();
m_fontAsset.SortGlyphTable();
m_fontAsset.ReadFontAssetDefinition();
return true;
}
/// <summary>
///
/// </summary>
/// <param name="glyphID"></param>
void RemoveGlyphFromList(int index)
{
if (index > m_GlyphTable_prop.arraySize)
return;
int targetGlyphIndex = m_GlyphTable_prop.GetArrayElementAtIndex(index).FindPropertyRelative("m_Index").intValue;
m_GlyphTable_prop.DeleteArrayElementAtIndex(index);
// Remove all characters referencing this glyph.
for (int i = 0; i < m_CharacterTable_prop.arraySize; i++)
{
int glyphIndex = m_CharacterTable_prop.GetArrayElementAtIndex(i).FindPropertyRelative("m_GlyphIndex").intValue;
if (glyphIndex == targetGlyphIndex)
{
// Remove character
m_CharacterTable_prop.DeleteArrayElementAtIndex(i);
}
}
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontAssetDefinition();
}
bool AddNewCharacter(int srcIndex, int dstGlyphID)
{
// Make sure Destination Glyph ID doesn't already contain a Glyph
if (m_fontAsset.characterLookupTable.ContainsKey((uint)dstGlyphID))
return false;
// Add new element to glyph list.
m_CharacterTable_prop.arraySize += 1;
// Get a reference to the source glyph.
SerializedProperty sourceCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(srcIndex);
int dstIndex = m_CharacterTable_prop.arraySize - 1;
// Get a reference to the target / destination glyph.
SerializedProperty targetCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(dstIndex);
CopyCharacterSerializedProperty(sourceCharacter, ref targetCharacter);
// Update the ID of the glyph
targetCharacter.FindPropertyRelative("m_Unicode").intValue = dstGlyphID;
serializedObject.ApplyModifiedProperties();
m_fontAsset.SortCharacterTable();
m_fontAsset.ReadFontAssetDefinition();
return true;
}
void RemoveCharacterFromList(int index)
{
if (index > m_CharacterTable_prop.arraySize)
return;
m_CharacterTable_prop.DeleteArrayElementAtIndex(index);
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontAssetDefinition();
}
void AddNewGlyphsFromProperty(SerializedProperty property)
{
if (m_GlyphsToAdd == null)
m_GlyphsToAdd = new HashSet<uint>();
else
m_GlyphsToAdd.Clear();
string propertyType = property.type;
switch (propertyType)
{
case "LigatureSubstitutionRecord":
int componentCount = property.FindPropertyRelative("m_ComponentGlyphIDs").arraySize;
for (int i = 0; i < componentCount; i++)
{
uint glyphIndex = (uint)property.FindPropertyRelative("m_ComponentGlyphIDs").GetArrayElementAtIndex(i).intValue;
m_GlyphsToAdd.Add(glyphIndex);
}
m_GlyphsToAdd.Add((uint)property.FindPropertyRelative("m_LigatureGlyphID").intValue);
foreach (uint glyphIndex in m_GlyphsToAdd)
{
if (glyphIndex != 0)
m_fontAsset.TryAddGlyphInternal(glyphIndex, out _);
}
break;
}
}
// Check if any of the Style elements were clicked on.
private bool DoSelectionCheck(Rect selectionArea)
{
Event currentEvent = Event.current;
switch (currentEvent.type)
{
case EventType.MouseDown:
if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0)
{
currentEvent.Use();
return true;
}
break;
}
return false;
}
private void UpdateLigatureSubstitutionRecordLookup(SerializedProperty property)
{
serializedObject.ApplyModifiedProperties();
AddNewGlyphsFromProperty(property);
m_fontAsset.InitializeLigatureSubstitutionLookupDictionary();
isAssetDirty = true;
}
void SetPropertyHolderGlyphIndexes()
{
uint firstCharacterUnicode = (uint)m_FirstCharacterUnicode_prop.intValue;
if (firstCharacterUnicode != 0)
{
uint glyphIndex = m_fontAsset.GetGlyphIndex(firstCharacterUnicode, out bool success);
if (glyphIndex != 0)
m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_FirstAdjustmentRecord").FindPropertyRelative("m_GlyphIndex").intValue = (int)glyphIndex;
}
uint secondCharacterUnicode = (uint)m_SecondCharacterUnicode_prop.intValue;
if (secondCharacterUnicode != 0)
{
uint glyphIndex = m_fontAsset.GetGlyphIndex(secondCharacterUnicode, out bool success);
if (glyphIndex != 0)
m_EmptyGlyphPairAdjustmentRecord_prop.FindPropertyRelative("m_SecondAdjustmentRecord").FindPropertyRelative("m_GlyphIndex").intValue = (int)glyphIndex;
}
}
private void UpdatePairAdjustmentRecordLookup(SerializedProperty property)
{
GlyphPairAdjustmentRecord pairAdjustmentRecord = GetGlyphPairAdjustmentRecord(property);
uint firstGlyphIndex = pairAdjustmentRecord.firstAdjustmentRecord.glyphIndex;
uint secondGlyphIndex = pairAdjustmentRecord.secondAdjustmentRecord.glyphIndex;
uint key = secondGlyphIndex << 16 | firstGlyphIndex;
// Lookup dictionary entry and update it
if (m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.ContainsKey(key))
m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup[key] = pairAdjustmentRecord;
}
GlyphPairAdjustmentRecord GetGlyphPairAdjustmentRecord(SerializedProperty property)
{
GlyphPairAdjustmentRecord pairAdjustmentRecord = new GlyphPairAdjustmentRecord();
SerializedProperty firstAdjustmentRecordProperty = property.FindPropertyRelative("m_FirstAdjustmentRecord");
uint firstGlyphIndex = (uint)firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue;
GlyphValueRecord firstValueRecord = GetValueRecord(firstAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord"));
pairAdjustmentRecord.firstAdjustmentRecord = new GlyphAdjustmentRecord(firstGlyphIndex, firstValueRecord);
SerializedProperty secondAdjustmentRecordProperty = property.FindPropertyRelative("m_SecondAdjustmentRecord");
uint secondGlyphIndex = (uint)secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphIndex").intValue;
GlyphValueRecord secondValueRecord = GetValueRecord(secondAdjustmentRecordProperty.FindPropertyRelative("m_GlyphValueRecord"));
pairAdjustmentRecord.secondAdjustmentRecord = new GlyphAdjustmentRecord(secondGlyphIndex, secondValueRecord);
// TODO : Need to revise how Everything is handled in the event more enum values are added.
int flagValue = property.FindPropertyRelative("m_FeatureLookupFlags").intValue;
//pairAdjustmentRecord.featureLookupFlags = flagValue == -1 ? FontFeatureLookupFlags.IgnoreLigatures | FontFeatureLookupFlags.IgnoreSpacingAdjustments : (FontFeatureLookupFlags) flagValue;
return pairAdjustmentRecord;
}
void SwapCharacterElements(SerializedProperty property, int selectedIndex, int newIndex)
{
property.MoveArrayElement(selectedIndex, newIndex);
}
void RemoveRecord(SerializedProperty property, int index)
{
if (index > property.arraySize)
return;
property.DeleteArrayElementAtIndex(index);
serializedObject.ApplyModifiedProperties();
m_fontAsset.ReadFontAssetDefinition();
}
GlyphValueRecord GetValueRecord(SerializedProperty property)
{
GlyphValueRecord record = new GlyphValueRecord();
record.xPlacement = property.FindPropertyRelative("m_XPlacement").floatValue;
record.yPlacement = property.FindPropertyRelative("m_YPlacement").floatValue;
record.xAdvance = property.FindPropertyRelative("m_XAdvance").floatValue;
record.yAdvance = property.FindPropertyRelative("m_YAdvance").floatValue;
return record;
}
private void UpdateMarkToBaseAdjustmentRecordLookup(SerializedProperty property)
{
MarkToBaseAdjustmentRecord adjustmentRecord = GetMarkToBaseAdjustmentRecord(property);
uint firstGlyphIndex = adjustmentRecord.baseGlyphID;
uint secondGlyphIndex = adjustmentRecord.markGlyphID;
uint key = secondGlyphIndex << 16 | firstGlyphIndex;
// Lookup dictionary entry and update it
if (m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.ContainsKey(key))
m_FontFeatureTable.m_MarkToBaseAdjustmentRecordLookup[key] = adjustmentRecord;
}
MarkToBaseAdjustmentRecord GetMarkToBaseAdjustmentRecord(SerializedProperty property)
{
MarkToBaseAdjustmentRecord adjustmentRecord = new MarkToBaseAdjustmentRecord();
adjustmentRecord.baseGlyphID = (uint)property.FindPropertyRelative("m_BaseGlyphID").intValue;
SerializedProperty baseAnchorPointProperty = property.FindPropertyRelative("m_BaseGlyphAnchorPoint");
GlyphAnchorPoint baseAnchorPoint = new GlyphAnchorPoint();
baseAnchorPoint.xCoordinate = baseAnchorPointProperty.FindPropertyRelative("m_XCoordinate").floatValue;
baseAnchorPoint.yCoordinate = baseAnchorPointProperty.FindPropertyRelative("m_YCoordinate").floatValue;
adjustmentRecord.baseGlyphAnchorPoint = baseAnchorPoint;
adjustmentRecord.markGlyphID = (uint)property.FindPropertyRelative("m_MarkGlyphID").intValue;
SerializedProperty markAdjustmentRecordProperty = property.FindPropertyRelative("m_MarkPositionAdjustment");
MarkPositionAdjustment markAdjustmentRecord = new MarkPositionAdjustment();
markAdjustmentRecord.xPositionAdjustment = markAdjustmentRecordProperty.FindPropertyRelative("m_XPositionAdjustment").floatValue;
markAdjustmentRecord.yPositionAdjustment = markAdjustmentRecordProperty.FindPropertyRelative("m_YPositionAdjustment").floatValue;
adjustmentRecord.markPositionAdjustment = markAdjustmentRecord;
return adjustmentRecord;
}
private void UpdateMarkToMarkAdjustmentRecordLookup(SerializedProperty property)
{
MarkToMarkAdjustmentRecord adjustmentRecord = GetMarkToMarkAdjustmentRecord(property);
uint firstGlyphIndex = adjustmentRecord.baseMarkGlyphID;
uint secondGlyphIndex = adjustmentRecord.combiningMarkGlyphID;
uint key = secondGlyphIndex << 16 | firstGlyphIndex;
// Lookup dictionary entry and update it
if (m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.ContainsKey(key))
m_FontFeatureTable.m_MarkToMarkAdjustmentRecordLookup[key] = adjustmentRecord;
}
MarkToMarkAdjustmentRecord GetMarkToMarkAdjustmentRecord(SerializedProperty property)
{
MarkToMarkAdjustmentRecord adjustmentRecord = new MarkToMarkAdjustmentRecord();
adjustmentRecord.baseMarkGlyphID = (uint)property.FindPropertyRelative("m_BaseMarkGlyphID").intValue;
SerializedProperty baseAnchorPointProperty = property.FindPropertyRelative("m_BaseMarkGlyphAnchorPoint");
GlyphAnchorPoint baseAnchorPoint = new GlyphAnchorPoint();
baseAnchorPoint.xCoordinate = baseAnchorPointProperty.FindPropertyRelative("m_XCoordinate").floatValue;
baseAnchorPoint.yCoordinate = baseAnchorPointProperty.FindPropertyRelative("m_YCoordinate").floatValue;
adjustmentRecord.baseMarkGlyphAnchorPoint = baseAnchorPoint;
adjustmentRecord.combiningMarkGlyphID = (uint)property.FindPropertyRelative("m_CombiningMarkGlyphID").intValue;
SerializedProperty markAdjustmentRecordProperty = property.FindPropertyRelative("m_CombiningMarkPositionAdjustment");
MarkPositionAdjustment markAdjustment = new MarkPositionAdjustment();
markAdjustment.xPositionAdjustment = markAdjustmentRecordProperty.FindPropertyRelative("m_XPositionAdjustment").floatValue;
markAdjustment.yPositionAdjustment = markAdjustmentRecordProperty.FindPropertyRelative("m_YPositionAdjustment").floatValue;
adjustmentRecord.combiningMarkPositionAdjustment = markAdjustment;
return adjustmentRecord;
}
/// <summary>
///
/// </summary>
/// <param name="srcGlyph"></param>
/// <param name="dstGlyph"></param>
void CopyGlyphSerializedProperty(SerializedProperty srcGlyph, ref SerializedProperty dstGlyph)
{
// TODO : Should make a generic function which copies each of the properties.
dstGlyph.FindPropertyRelative("m_Index").intValue = srcGlyph.FindPropertyRelative("m_Index").intValue;
// Glyph -> GlyphMetrics
SerializedProperty srcGlyphMetrics = srcGlyph.FindPropertyRelative("m_Metrics");
SerializedProperty dstGlyphMetrics = dstGlyph.FindPropertyRelative("m_Metrics");
dstGlyphMetrics.FindPropertyRelative("m_Width").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Width").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_Height").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Height").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue;
// Glyph -> GlyphRect
SerializedProperty srcGlyphRect = srcGlyph.FindPropertyRelative("m_GlyphRect");
SerializedProperty dstGlyphRect = dstGlyph.FindPropertyRelative("m_GlyphRect");
dstGlyphRect.FindPropertyRelative("m_X").intValue = srcGlyphRect.FindPropertyRelative("m_X").intValue;
dstGlyphRect.FindPropertyRelative("m_Y").intValue = srcGlyphRect.FindPropertyRelative("m_Y").intValue;
dstGlyphRect.FindPropertyRelative("m_Width").intValue = srcGlyphRect.FindPropertyRelative("m_Width").intValue;
dstGlyphRect.FindPropertyRelative("m_Height").intValue = srcGlyphRect.FindPropertyRelative("m_Height").intValue;
dstGlyph.FindPropertyRelative("m_Scale").floatValue = srcGlyph.FindPropertyRelative("m_Scale").floatValue;
dstGlyph.FindPropertyRelative("m_AtlasIndex").intValue = srcGlyph.FindPropertyRelative("m_AtlasIndex").intValue;
}
void CopyCharacterSerializedProperty(SerializedProperty source, ref SerializedProperty target)
{
// TODO : Should make a generic function which copies each of the properties.
int unicode = source.FindPropertyRelative("m_Unicode").intValue;
target.FindPropertyRelative("m_Unicode").intValue = unicode;
int srcGlyphIndex = source.FindPropertyRelative("m_GlyphIndex").intValue;
target.FindPropertyRelative("m_GlyphIndex").intValue = srcGlyphIndex;
target.FindPropertyRelative("m_Scale").floatValue = source.FindPropertyRelative("m_Scale").floatValue;
}
/// <summary>
///
/// </summary>
/// <param name="searchPattern"></param>
/// <returns></returns>
void SearchGlyphTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
int arraySize = m_GlyphTable_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty sourceGlyph = m_GlyphTable_prop.GetArrayElementAtIndex(i);
int id = sourceGlyph.FindPropertyRelative("m_Index").intValue;
// Check for potential match against a character.
//if (searchPattern.Length == 1 && id == searchPattern[0])
// searchResults.Add(i);
// Check for potential match against decimal id
if (id.ToString().Contains(searchPattern))
searchResults.Add(i);
//if (id.ToString("x").Contains(searchPattern))
// searchResults.Add(i);
//if (id.ToString("X").Contains(searchPattern))
// searchResults.Add(i);
}
}
void SearchCharacterTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
int arraySize = m_CharacterTable_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty sourceCharacter = m_CharacterTable_prop.GetArrayElementAtIndex(i);
int id = sourceCharacter.FindPropertyRelative("m_Unicode").intValue;
// Check for potential match against a character.
if (searchPattern.Length == 1 && id == searchPattern[0])
searchResults.Add(i);
else if (id.ToString("x").Contains(searchPattern))
searchResults.Add(i);
else if (id.ToString("X").Contains(searchPattern))
searchResults.Add(i);
// Check for potential match against decimal id
//if (id.ToString().Contains(searchPattern))
// searchResults.Add(i);
}
}
void SearchLigatureTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
// Lookup glyph index of potential characters contained in the search pattern.
uint firstGlyphIndex = 0;
Character firstCharacterSearch;
if (searchPattern.Length > 0 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[0], out firstCharacterSearch))
firstGlyphIndex = firstCharacterSearch.glyphIndex;
uint secondGlyphIndex = 0;
Character secondCharacterSearch;
if (searchPattern.Length > 1 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[1], out secondCharacterSearch))
secondGlyphIndex = secondCharacterSearch.glyphIndex;
int arraySize = m_MarkToBaseAdjustmentRecords_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty record = m_MarkToBaseAdjustmentRecords_prop.GetArrayElementAtIndex(i);
int baseGlyphIndex = record.FindPropertyRelative("m_BaseGlyphID").intValue;
int markGlyphIndex = record.FindPropertyRelative("m_MarkGlyphID").intValue;
if (firstGlyphIndex == baseGlyphIndex && secondGlyphIndex == markGlyphIndex)
searchResults.Add(i);
else if (searchPattern.Length == 1 && (firstGlyphIndex == baseGlyphIndex || firstGlyphIndex == markGlyphIndex))
searchResults.Add(i);
else if (baseGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
else if (markGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
}
}
void SearchKerningTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
// Lookup glyph index of potential characters contained in the search pattern.
uint firstGlyphIndex = 0;
Character firstCharacterSearch;
if (searchPattern.Length > 0 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[0], out firstCharacterSearch))
firstGlyphIndex = firstCharacterSearch.glyphIndex;
uint secondGlyphIndex = 0;
Character secondCharacterSearch;
if (searchPattern.Length > 1 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[1], out secondCharacterSearch))
secondGlyphIndex = secondCharacterSearch.glyphIndex;
int arraySize = m_GlyphPairAdjustmentRecords_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty record = m_GlyphPairAdjustmentRecords_prop.GetArrayElementAtIndex(i);
SerializedProperty firstAdjustmentRecord = record.FindPropertyRelative("m_FirstAdjustmentRecord");
SerializedProperty secondAdjustmentRecord = record.FindPropertyRelative("m_SecondAdjustmentRecord");
int firstGlyph = firstAdjustmentRecord.FindPropertyRelative("m_GlyphIndex").intValue;
int secondGlyph = secondAdjustmentRecord.FindPropertyRelative("m_GlyphIndex").intValue;
if (firstGlyphIndex == firstGlyph && secondGlyphIndex == secondGlyph)
searchResults.Add(i);
else if (searchPattern.Length == 1 && (firstGlyphIndex == firstGlyph || firstGlyphIndex == secondGlyph))
searchResults.Add(i);
else if (firstGlyph.ToString().Contains(searchPattern))
searchResults.Add(i);
else if (secondGlyph.ToString().Contains(searchPattern))
searchResults.Add(i);
}
}
void SearchMarkToBaseTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
// Lookup glyph index of potential characters contained in the search pattern.
uint firstGlyphIndex = 0;
Character firstCharacterSearch;
if (searchPattern.Length > 0 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[0], out firstCharacterSearch))
firstGlyphIndex = firstCharacterSearch.glyphIndex;
uint secondGlyphIndex = 0;
Character secondCharacterSearch;
if (searchPattern.Length > 1 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[1], out secondCharacterSearch))
secondGlyphIndex = secondCharacterSearch.glyphIndex;
int arraySize = m_MarkToBaseAdjustmentRecords_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty record = m_MarkToBaseAdjustmentRecords_prop.GetArrayElementAtIndex(i);
int baseGlyphIndex = record.FindPropertyRelative("m_BaseGlyphID").intValue;
int markGlyphIndex = record.FindPropertyRelative("m_MarkGlyphID").intValue;
if (firstGlyphIndex == baseGlyphIndex && secondGlyphIndex == markGlyphIndex)
searchResults.Add(i);
else if (searchPattern.Length == 1 && (firstGlyphIndex == baseGlyphIndex || firstGlyphIndex == markGlyphIndex))
searchResults.Add(i);
else if (baseGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
else if (markGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
}
}
void SearchMarkToMarkTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
// Lookup glyph index of potential characters contained in the search pattern.
uint firstGlyphIndex = 0;
Character firstCharacterSearch;
if (searchPattern.Length > 0 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[0], out firstCharacterSearch))
firstGlyphIndex = firstCharacterSearch.glyphIndex;
uint secondGlyphIndex = 0;
Character secondCharacterSearch;
if (searchPattern.Length > 1 && m_fontAsset.characterLookupTable.TryGetValue(searchPattern[1], out secondCharacterSearch))
secondGlyphIndex = secondCharacterSearch.glyphIndex;
int arraySize = m_MarkToMarkAdjustmentRecords_prop.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty record = m_MarkToMarkAdjustmentRecords_prop.GetArrayElementAtIndex(i);
int baseGlyphIndex = record.FindPropertyRelative("m_BaseMarkGlyphID").intValue;
int markGlyphIndex = record.FindPropertyRelative("m_CombiningMarkGlyphID").intValue;
if (firstGlyphIndex == baseGlyphIndex && secondGlyphIndex == markGlyphIndex)
searchResults.Add(i);
else if (searchPattern.Length == 1 && (firstGlyphIndex == baseGlyphIndex || firstGlyphIndex == markGlyphIndex))
searchResults.Add(i);
else if (baseGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
else if (markGlyphIndex.ToString().Contains(searchPattern))
searchResults.Add(i);
}
}
void DrawMarkToBasePreview(int selectedRecord, Rect rect)
{
MarkToBaseAdjustmentRecord adjustmentRecord = m_fontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecords[selectedRecord];
uint baseGlyphIndex = adjustmentRecord.baseGlyphID;
uint markGlyphIndex = adjustmentRecord.markGlyphID;
if (baseGlyphIndex == 0 || markGlyphIndex == 0)
return;
float lineHeight = m_fontAsset.faceInfo.ascentLine - m_fontAsset.faceInfo.descentLine;
float scale = rect.width < rect.height ? rect.width / lineHeight : rect.height / lineHeight;
scale *= 0.9f;
Glyph baseGlyph;
m_fontAsset.glyphLookupTable.TryGetValue(baseGlyphIndex, out baseGlyph);
if (baseGlyph == null)
return;
Rect center = new Rect(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.width, rect.height);
Vector2 origin = new Vector2(center.x, center.y);
origin.x = origin.x - (baseGlyph.metrics.horizontalBearingX + baseGlyph.metrics.width / 2) * scale;
origin.y = origin.y + (baseGlyph.metrics.horizontalBearingY - baseGlyph.metrics.height / 2) * scale;
// Draw Baseline
DrawBaseline(origin, rect.width, Color.grey);
// Draw Origin
DrawAnchorPoint(origin, Color.yellow);
Rect baseGlyphPosition = new Rect(origin.x + baseGlyph.metrics.horizontalBearingX * scale, origin.y - baseGlyph.metrics.horizontalBearingY * scale , rect.width, rect.height);
DrawGlyph(baseGlyph, baseGlyphPosition, scale);
Vector2 baseAnchorPosition = new Vector2(origin.x + adjustmentRecord.baseGlyphAnchorPoint.xCoordinate * scale, origin.y - adjustmentRecord.baseGlyphAnchorPoint.yCoordinate * scale);
DrawAnchorPoint(baseAnchorPosition, Color.green);
// Draw Mark
if (m_fontAsset.glyphLookupTable.ContainsKey(markGlyphIndex))
{
Glyph markGlyph = m_fontAsset.glyphLookupTable[markGlyphIndex];
Rect markGlyphPosition = new Rect(baseAnchorPosition.x + (markGlyph.metrics.horizontalBearingX - adjustmentRecord.markPositionAdjustment.xPositionAdjustment) * scale, baseAnchorPosition.y + (adjustmentRecord.markPositionAdjustment.yPositionAdjustment - markGlyph.metrics.horizontalBearingY) * scale, markGlyph.metrics.width, markGlyph.metrics.height);
// Draw Mark Origin
DrawGlyph(markGlyph, markGlyphPosition, scale);
}
}
void DrawMarkToMarkPreview(int selectedRecord, Rect rect)
{
MarkToMarkAdjustmentRecord adjustmentRecord = m_fontAsset.fontFeatureTable.m_MarkToMarkAdjustmentRecords[selectedRecord];
uint baseGlyphIndex = adjustmentRecord.baseMarkGlyphID;
uint markGlyphIndex = adjustmentRecord.combiningMarkGlyphID;
if (baseGlyphIndex == 0 || markGlyphIndex == 0)
return;
float lineHeight = m_fontAsset.faceInfo.ascentLine - m_fontAsset.faceInfo.descentLine;
float scale = rect.width < rect.height ? rect.width / lineHeight : rect.height / lineHeight;
scale *= 0.9f;
Glyph baseGlyph;
m_fontAsset.glyphLookupTable.TryGetValue(baseGlyphIndex, out baseGlyph);
if (baseGlyph == null)
return;
Rect center = new Rect(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.width, rect.height);
Vector2 origin = new Vector2(center.x, center.y);
origin.x = origin.x - (baseGlyph.metrics.horizontalBearingX + baseGlyph.metrics.width / 2) * scale;
origin.y = origin.y + (baseGlyph.metrics.horizontalBearingY - baseGlyph.metrics.height / 2) * scale;
// Draw Baseline
DrawBaseline(origin, rect.width, Color.grey);
// Draw Origin
DrawAnchorPoint(origin, Color.yellow);
Rect baseGlyphPosition = new Rect(origin.x + baseGlyph.metrics.horizontalBearingX * scale, origin.y - baseGlyph.metrics.horizontalBearingY * scale , rect.width, rect.height);
DrawGlyph(baseGlyph, baseGlyphPosition, scale);
Vector2 baseAnchorPosition = new Vector2(origin.x + adjustmentRecord.baseMarkGlyphAnchorPoint.xCoordinate * scale, origin.y - adjustmentRecord.baseMarkGlyphAnchorPoint.yCoordinate * scale);
DrawAnchorPoint(baseAnchorPosition, Color.green);
// Draw Mark Glyph
if (m_fontAsset.glyphLookupTable.ContainsKey(markGlyphIndex))
{
Glyph markGlyph = m_fontAsset.glyphLookupTable[markGlyphIndex];
Rect markGlyphPosition = new Rect(baseAnchorPosition.x + (markGlyph.metrics.horizontalBearingX - adjustmentRecord.combiningMarkPositionAdjustment.xPositionAdjustment) * scale, baseAnchorPosition.y + (adjustmentRecord.combiningMarkPositionAdjustment.yPositionAdjustment - markGlyph.metrics.horizontalBearingY) * scale, markGlyph.metrics.width, markGlyph.metrics.height);
DrawGlyph(markGlyph, markGlyphPosition, scale);
}
}
void DrawBaseline(Vector2 position, float width, Color color)
{
Handles.color = color;
// Horizontal line
Handles.DrawLine(new Vector2(0f, position.y), new Vector2(width, position.y));
}
void DrawAnchorPoint(Vector2 position, Color color)
{
Handles.color = color;
// Horizontal line
Handles.DrawLine(new Vector2(position.x - 25, position.y), new Vector2(position.x + 25, position.y));
// Vertical line
Handles.DrawLine(new Vector2(position.x, position.y - 25), new Vector2(position.x, position.y + 25));
}
void DrawGlyph(Glyph glyph, Rect position, float scale)
{
// Get the atlas index of the glyph and lookup its atlas texture
int atlasIndex = glyph.atlasIndex;
Texture2D atlasTexture = m_fontAsset.atlasTextures.Length > atlasIndex ? m_fontAsset.atlasTextures[atlasIndex] : null;
if (atlasTexture == null)
return;
Material mat;
if (((GlyphRasterModes)m_fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
{
if (m_fontAsset.atlasRenderMode == GlyphRenderMode.COLOR || m_fontAsset.atlasRenderMode == GlyphRenderMode.COLOR_HINTED)
mat = internalRGBABitmapMaterial;
else
mat = internalBitmapMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
}
else
{
mat = EditorShaderUtilities.internalSDFMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
mat.SetFloat(TextShaderUtilities.ID_GradientScale, m_fontAsset.atlasPadding + 1);
}
GlyphRect glyphRect = glyph.glyphRect;
int padding = m_fontAsset.atlasPadding;
int glyphOriginX = glyphRect.x - padding;
int glyphOriginY = glyphRect.y - padding;
int glyphWidth = glyphRect.width + padding * 2;
int glyphHeight = glyphRect.height + padding * 2;
// Compute the normalized texture coordinates
Rect texCoords = new Rect((float)glyphOriginX / atlasTexture.width, (float)glyphOriginY / atlasTexture.height, (float)glyphWidth / atlasTexture.width, (float)glyphHeight / atlasTexture.height);
if (Event.current.type == EventType.Repaint)
{
// Draw glyph from atlas texture.
Rect glyphDrawPosition = new Rect(position.x - padding * scale, position.y - padding * scale, position.width, position.height);
//glyphDrawPosition.x += (glyphDrawPosition.width - glyphWidth * scale); // / 2;
//glyphDrawPosition.y += (glyphDrawPosition.height - glyphHeight * scale); // / 2;
glyphDrawPosition.width = glyphWidth * scale;
glyphDrawPosition.height = glyphHeight * scale;
// Could switch to using the default material of the font asset which would require passing scale to the shader.
Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(0.8f, 0.8f, 0.8f), mat);
}
}
internal void UpdateSourceFontFile(Font sourceFont)
{
m_GenerationSettings.sourceFont = m_fontAsset.SourceFont_EditorRef;
m_fontAsset.SourceFont_EditorRef = sourceFont;
m_FontFaces = GetFontFaces(0);
m_FaceInfoDirty = true;
m_DisplayDestructiveChangeWarning = true;
}
internal void UpdateFontFaceIndex(int index)
{
var faceInfo = m_fontAsset.faceInfo;
faceInfo.faceIndex = index;
m_fontAsset.faceInfo = faceInfo;
m_MaterialPresetsRequireUpdate = true;
m_DisplayDestructiveChangeWarning = true;
m_FaceInfoDirty = true;
}
// 0 = Static, 1 = Dynamic, 2 = Dynamic OS
internal void UpdateAtlasPopulationMode(int populationMode)
{
serializedObject.ApplyModifiedProperties();
m_fontAsset.atlasPopulationMode = (AtlasPopulationMode)populationMode;
// Static font asset
if (populationMode == 0)
{
m_fontAsset.sourceFontFile = null;
//Set atlas textures to non readable.
for (int i = 0; i < m_fontAsset.atlasTextures.Length; i++)
{
Texture2D tex = m_fontAsset.atlasTextures[i];
if (tex != null && tex.isReadable)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, false);
}
//Debug.Log("Atlas Population mode set to [Static].");
}
else // Dynamic font asset
{
if (m_fontAsset.m_SourceFontFile_EditorRef.dynamic == false)
{
Debug.LogWarning("Please set the [" + m_fontAsset.name + "] font to dynamic mode as this is required for Dynamic SDF support.", m_fontAsset.m_SourceFontFile_EditorRef);
m_AtlasPopulationMode_prop.intValue = 0;
m_fontAsset.atlasPopulationMode = (AtlasPopulationMode)populationMode;
serializedObject.ApplyModifiedProperties();
}
else
{
m_fontAsset.sourceFontFile = m_fontAsset.m_SourceFontFile_EditorRef;
// Set atlas textures to readable.
for (int i = 0; i < m_fontAsset.atlasTextures.Length; i++)
{
Texture2D tex = m_fontAsset.atlasTextures[i];
if (tex != null && tex.isReadable == false)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, true);
}
//Debug.Log("Atlas Population mode set to [" + (m_AtlasPopulationMode_prop.intValue == 1 ? "Dynamic" : "Dynamic OS") + "].");
}
// Dynamic OS font asset
if (populationMode == 2)
m_fontAsset.sourceFontFile = null;
}
serializedObject.Update();
isAssetDirty = true;
}
internal void ApplyDestructiveChanges()
{
m_DisplayDestructiveChangeWarning = false;
// Update face info if sampling point size was changed.
if (m_GenerationSettings.pointSize != m_SamplingPointSize_prop.intValue || m_FaceInfoDirty)
{
LoadFontFace(m_SamplingPointSize_prop.intValue, m_FontFaceIndex_prop.intValue);
m_fontAsset.faceInfo = FontEngine.GetFaceInfo();
m_FaceInfoDirty = false;
}
Material mat = m_fontAsset.material;
// Update material
mat.SetFloat(TextShaderUtilities.ID_TextureWidth, m_AtlasWidth_prop.intValue);
mat.SetFloat(TextShaderUtilities.ID_TextureHeight, m_AtlasHeight_prop.intValue);
if (mat.HasProperty(TextShaderUtilities.ID_GradientScale))
mat.SetFloat(TextShaderUtilities.ID_GradientScale, m_AtlasPadding_prop.intValue + 1);
// Update material presets if any of the relevant properties have been changed.
if (m_MaterialPresetsRequireUpdate)
{
m_MaterialPresetsRequireUpdate = false;
Material[] materialPresets = TextCoreEditorUtilities.FindMaterialReferences(m_fontAsset);
for (int i = 0; i < materialPresets.Length; i++)
{
mat = materialPresets[i];
mat.SetFloat(TextShaderUtilities.ID_TextureWidth, m_AtlasWidth_prop.intValue);
mat.SetFloat(TextShaderUtilities.ID_TextureHeight, m_AtlasHeight_prop.intValue);
if (mat.HasProperty(TextShaderUtilities.ID_GradientScale))
mat.SetFloat(TextShaderUtilities.ID_GradientScale, m_AtlasPadding_prop.intValue + 1);
}
}
m_fontAsset.UpdateFontAssetData();
GUIUtility.keyboardControl = 0;
isAssetDirty = true;
// Update Font Asset Creation Settings to reflect new changes.
UpdateFontAssetCreationSettings();
// TODO: Clear undo buffers.
//Undo.ClearUndo(m_fontAsset);
}
internal void RevertDestructiveChanges()
{
m_DisplayDestructiveChangeWarning = false;
RestoreGenerationSettings();
GUIUtility.keyboardControl = 0;
// TODO: Clear undo buffers.
//Undo.ClearUndo(m_fontAsset);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 69993
} | 467 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.U2D;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using GlyphRect = UnityEngine.TextCore.GlyphRect;
using GlyphMetrics = UnityEngine.TextCore.GlyphMetrics;
namespace UnityEditor.TextCore.Text
{
internal static class SpriteAssetCreationMenu
{
// Add a Context Menu to the Sprite Asset Editor Panel to Create and Add a Default Material.
[MenuItem("CONTEXT/SpriteAsset/Add Default Material", true, 2200)]
static bool AddDefaultMaterialValidate(MenuCommand command)
{
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/SpriteAsset/Add Default Material", false, 2200)]
static void AddDefaultMaterial(MenuCommand command)
{
SpriteAsset spriteAsset = (SpriteAsset)command.context;
// Make sure the sprite asset already contains a default material
if (spriteAsset != null && spriteAsset.material == null)
{
// Add new default material for sprite asset.
AddDefaultMaterial(spriteAsset);
}
}
// Add a Context Menu to the Sprite Asset Editor Panel to update existing sprite assets.
[MenuItem("CONTEXT/SpriteAsset/Update Sprite Asset", true, 2100)]
static bool UpdateSpriteAssetValidate(MenuCommand command)
{
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/SpriteAsset/Update Sprite Asset", false, 2100)]
static void UpdateSpriteAsset(MenuCommand command)
{
SpriteAsset spriteAsset = (SpriteAsset)command.context;
if (spriteAsset == null)
return;
UpdateSpriteAsset(spriteAsset);
}
internal static void UpdateSpriteAsset(SpriteAsset spriteAsset)
{
// Get a list of all the sprites contained in the texture referenced by the sprite asset.
// This only works if the texture is set to sprite mode.
string filePath = AssetDatabase.GetAssetPath(spriteAsset.spriteSheet);
if (string.IsNullOrEmpty(filePath))
return;
// Get all the sprites defined in the sprite sheet texture referenced by this sprite asset.
Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).ToArray();
// Return if sprite sheet texture does not have any sprites defined in it.
if (sprites.Length == 0)
{
Debug.Log("Sprite Asset <color=#FFFF80>[" + spriteAsset.name + "]</color>'s atlas texture does not appear to have any sprites defined in it. Use the Unity Sprite Editor to define sprites for this texture.", spriteAsset.spriteSheet);
return;
}
List<SpriteGlyph> spriteGlyphTable = spriteAsset.spriteGlyphTable;
// Find available glpyh indexes
uint[] existingGlyphIndexes = spriteGlyphTable.Select(x => x.index).ToArray();
List<uint> availableGlyphIndexes = new List<uint>();
uint lastGlyphIndex = existingGlyphIndexes.Length > 0 ? existingGlyphIndexes.Last() : 0;
int elementIndex = 0;
for (uint i = 0; i < lastGlyphIndex; i++)
{
uint existingGlyphIndex = existingGlyphIndexes[elementIndex];
if (i == existingGlyphIndex)
elementIndex += 1;
else
availableGlyphIndexes.Add(i);
}
// Iterate over sprites contained in the updated sprite sheet to identify new and / or modified sprites.
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
// Check if current sprites is already contained in the sprite glyph table of the sprite asset.
SpriteGlyph spriteGlyph = spriteGlyphTable.FirstOrDefault(x => x.sprite == sprite);
if (spriteGlyph != null)
{
// update existing sprite glyph
if (spriteGlyph.glyphRect.x != sprite.rect.x || spriteGlyph.glyphRect.y != sprite.rect.y || spriteGlyph.glyphRect.width != sprite.rect.width || spriteGlyph.glyphRect.height != sprite.rect.height)
spriteGlyph.glyphRect = new GlyphRect(sprite.rect);
}
else
{
SpriteCharacter spriteCharacter;
// Check if this sprite potentially exists under the same name in the sprite character table.
if (spriteAsset.spriteCharacterTable != null && spriteAsset.spriteCharacterTable.Count > 0)
{
spriteCharacter = spriteAsset.spriteCharacterTable.FirstOrDefault(x => x.name == sprite.name);
spriteGlyph = spriteCharacter != null ? spriteGlyphTable[(int)spriteCharacter.glyphIndex] : null;
if (spriteGlyph != null)
{
// Update sprite reference and data
spriteGlyph.sprite = sprite;
if (spriteGlyph.glyphRect.x != sprite.rect.x || spriteGlyph.glyphRect.y != sprite.rect.y || spriteGlyph.glyphRect.width != sprite.rect.width || spriteGlyph.glyphRect.height != sprite.rect.height)
spriteGlyph.glyphRect = new GlyphRect(sprite.rect);
}
}
spriteGlyph = new SpriteGlyph();
// Get available glyph index
if (availableGlyphIndexes.Count > 0)
{
spriteGlyph.index = availableGlyphIndexes[0];
availableGlyphIndexes.RemoveAt(0);
}
else
spriteGlyph.index = (uint)spriteGlyphTable.Count;
spriteGlyph.metrics = new GlyphMetrics(sprite.rect.width, sprite.rect.height, -sprite.pivot.x, sprite.rect.height - sprite.pivot.y, sprite.rect.width);
spriteGlyph.glyphRect = new GlyphRect(sprite.rect);
spriteGlyph.scale = 1.0f;
spriteGlyph.sprite = sprite;
spriteGlyphTable.Add(spriteGlyph);
spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph);
// Special handling for .notdef sprite name.
string fileNameToLowerInvariant = sprite.name.ToLowerInvariant();
if (fileNameToLowerInvariant == ".notdef" || fileNameToLowerInvariant == "notdef")
{
spriteCharacter.unicode = 0;
spriteCharacter.name = fileNameToLowerInvariant;
}
else
{
spriteCharacter.unicode = 0xFFFE;
if (!string.IsNullOrEmpty(sprite.name) && sprite.name.Length > 2 && sprite.name[0] == '0' && (sprite.name[1] == 'x' || sprite.name[1] == 'X'))
{
spriteCharacter.unicode = TextUtilities.StringHexToInt(sprite.name.Remove(0, 2));
}
spriteCharacter.name = sprite.name;
}
spriteCharacter.scale = 1.0f;
spriteAsset.spriteCharacterTable.Add(spriteCharacter);
}
}
// Update Sprite Character Table to replace unicode 0x0 by 0xFFFE
for (int i = 0; i < spriteAsset.spriteCharacterTable.Count; i++)
{
SpriteCharacter spriteCharacter = spriteAsset.spriteCharacterTable[i];
if (spriteCharacter.unicode == 0)
spriteCharacter.unicode = 0xFFFE;
}
// Sort glyph table by glyph index
spriteAsset.SortGlyphTable();
spriteAsset.UpdateLookupTables();
spriteAsset.MarkDirty();
TextEventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, spriteAsset);
}
[MenuItem("Assets/Create/Text Core/Sprite Asset", false, 150)]
internal static void CreateSpriteAsset()
{
Object[] targets = Selection.objects;
if (targets == null)
{
Debug.LogWarning("A Sprite Texture must first be selected in order to create a Sprite Asset.");
return;
}
for (int i = 0; i < targets.Length; i++)
{
Object target = targets[i];
// Make sure the selection is a font file
if (target == null || target.GetType() != typeof(Texture2D))
{
Debug.LogWarning("Selected Object [" + target.name + "] is not a Sprite Texture. A Sprite Texture must be selected in order to create a Sprite Asset.", target);
continue;
}
CreateSpriteAssetFromSelectedObject(target);
}
}
static void CreateSpriteAssetFromSelectedObject(Object target)
{
// Get the path to the selected asset.
string filePathWithName = AssetDatabase.GetAssetPath(target);
string fileNameWithExtension = Path.GetFileName(filePathWithName);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
string filePath = filePathWithName.Replace(fileNameWithExtension, "");
string uniqueAssetPath = AssetDatabase.GenerateUniqueAssetPath(filePath + fileNameWithoutExtension + ".asset");
// Create new Sprite Asset
SpriteAsset spriteAsset = ScriptableObject.CreateInstance<SpriteAsset>();
AssetDatabase.CreateAsset(spriteAsset, uniqueAssetPath);
spriteAsset.version = "1.1.0";
// Compute the hash code for the sprite asset.
spriteAsset.hashCode = TextUtilities.GetSimpleHashCode(spriteAsset.name);
List<SpriteGlyph> spriteGlyphTable = new List<SpriteGlyph>();
List<SpriteCharacter> spriteCharacterTable = new List<SpriteCharacter>();
if (target.GetType() == typeof(Texture2D))
{
Texture2D sourceTex = target as Texture2D;
// Assign new Sprite Sheet texture to the Sprite Asset.
spriteAsset.spriteSheet = sourceTex;
PopulateSpriteTables(sourceTex, ref spriteCharacterTable, ref spriteGlyphTable);
spriteAsset.spriteCharacterTable = spriteCharacterTable;
spriteAsset.spriteGlyphTable = spriteGlyphTable;
// Add new default material for sprite asset.
AddDefaultMaterial(spriteAsset);
}
else if (target.GetType() == typeof(SpriteAtlas))
{
//SpriteAtlas spriteAtlas = target as SpriteAtlas;
//PopulateSpriteTables(spriteAtlas, ref spriteCharacterTable, ref spriteGlyphTable);
//spriteAsset.spriteCharacterTable = spriteCharacterTable;
//spriteAsset.spriteGlyphTable = spriteGlyphTable;
//spriteAsset.spriteSheet = spriteGlyphTable[0].sprite.texture;
//// Add new default material for sprite asset.
//AddDefaultMaterial(spriteAsset);
}
// Update Lookup tables.
spriteAsset.UpdateLookupTables();
// Get the Sprites contained in the Sprite Sheet
EditorUtility.SetDirty(spriteAsset);
//spriteAsset.sprites = sprites;
// Set source texture back to Not Readable.
//texImporter.isReadable = false;
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset)); // Re-import font asset to get the new updated version.
//AssetDatabase.Refresh();
}
private static void PopulateSpriteTables(Texture source, ref List<SpriteCharacter> spriteCharacterTable, ref List<SpriteGlyph> spriteGlyphTable)
{
//Debug.Log("Creating new Sprite Asset.");
string filePath = AssetDatabase.GetAssetPath(source);
// Get all the Sprites sorted by Index
Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray();
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
SpriteGlyph spriteGlyph = new SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.metrics = new GlyphMetrics(sprite.rect.width, sprite.rect.height, -sprite.pivot.x, sprite.rect.height - sprite.pivot.y, sprite.rect.width);
spriteGlyph.glyphRect = new GlyphRect(sprite.rect);
spriteGlyph.scale = 1.0f;
spriteGlyph.sprite = sprite;
spriteGlyphTable.Add(spriteGlyph);
SpriteCharacter spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph);
// Special handling for .notdef sprite name.
string fileNameToLowerInvariant = sprite.name.ToLowerInvariant();
if (fileNameToLowerInvariant == ".notdef" || fileNameToLowerInvariant == "notdef")
{
spriteCharacter.unicode = 0;
spriteCharacter.name = fileNameToLowerInvariant;
}
else
{
if (!string.IsNullOrEmpty(sprite.name) && sprite.name.Length > 2 && sprite.name[0] == '0' && (sprite.name[1] == 'x' || sprite.name[1] == 'X'))
{
spriteCharacter.unicode = TextUtilities.StringHexToInt(sprite.name.Remove(0, 2));
}
spriteCharacter.name = sprite.name;
}
spriteCharacter.scale = 1.0f;
spriteCharacterTable.Add(spriteCharacter);
}
}
private static void PopulateSpriteTables(SpriteAtlas spriteAtlas, ref List<SpriteCharacter> spriteCharacterTable, ref List<SpriteGlyph> spriteGlyphTable)
{
// Get number of sprites contained in the sprite atlas.
int spriteCount = spriteAtlas.spriteCount;
Sprite[] sprites = new Sprite[spriteCount];
// Get all the sprites
spriteAtlas.GetSprites(sprites);
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
SpriteGlyph spriteGlyph = new SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.metrics = new GlyphMetrics(sprite.textureRect.width, sprite.textureRect.height, -sprite.pivot.x, sprite.textureRect.height - sprite.pivot.y, sprite.textureRect.width);
spriteGlyph.glyphRect = new GlyphRect(sprite.textureRect);
spriteGlyph.scale = 1.0f;
spriteGlyph.sprite = sprite;
spriteGlyphTable.Add(spriteGlyph);
SpriteCharacter spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph);
spriteCharacter.name = sprite.name;
spriteCharacter.scale = 1.0f;
spriteCharacterTable.Add(spriteCharacter);
}
}
/// <summary>
/// Create and add new default material to sprite asset.
/// </summary>
/// <param name="spriteAsset"></param>
private static void AddDefaultMaterial(SpriteAsset spriteAsset)
{
Shader shader = TextShaderUtilities.ShaderRef_Sprite;
Material material = new Material(shader);
material.SetTexture(TextShaderUtilities.ID_MainTex, spriteAsset.spriteSheet);
spriteAsset.material = material;
material.hideFlags = HideFlags.HideInHierarchy;
material.name = spriteAsset.name + " Material";
AssetDatabase.AddObjectToAsset(material, spriteAsset);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetCreationMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetCreationMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 7654
} | 468 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.IO;
using UnityEngine;
using UnityEngine.TextCore.Text;
namespace UnityEditor.TextCore.Text
{
internal static class TextStyleAssetCreationMenu
{
[MenuItem("Assets/Create/Text Core/Text StyleSheet", false, 200)]
internal static void CreateTextMeshProObjectPerform()
{
string filePath;
if (Selection.assetGUIDs.Length == 0)
{
// No asset selected.
filePath = "Assets";
}
else
{
// Get the path of the selected folder or asset.
filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
// Get the file extension of the selected asset as it might need to be removed.
string fileExtension = Path.GetExtension(filePath);
if (fileExtension != "")
{
filePath = Path.GetDirectoryName(filePath);
}
}
string filePathWithName = AssetDatabase.GenerateUniqueAssetPath(filePath + "/Text StyleSheet.asset");
// Create new Style Sheet Asset.
TextStyleSheet styleSheet = ScriptableObject.CreateInstance<TextStyleSheet>();
// Create Normal default style
TextStyle style = new TextStyle("Normal", string.Empty, string.Empty);
styleSheet.styles.Add(style);
AssetDatabase.CreateAsset(styleSheet, filePathWithName);
EditorUtility.SetDirty(styleSheet);
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(styleSheet);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextStyleAssetCreationMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextStyleAssetCreationMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 815
} | 469 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.Scripting;
using UnityEngine.Tilemaps;
namespace UnityEditor
{
[RequiredByNativeCode]
internal class EditorPreviewTilemap : ITilemap
{
private EditorPreviewTilemap()
{
}
// Tile
public override Sprite GetSprite(Vector3Int position)
{
var tile = m_Tilemap.GetEditorPreviewTile(position);
return tile ? m_Tilemap.GetEditorPreviewSprite(position) : m_Tilemap.GetSprite(position);
}
public override Color GetColor(Vector3Int position)
{
var tile = m_Tilemap.GetEditorPreviewTile(position);
return tile ? m_Tilemap.GetEditorPreviewColor(position) : m_Tilemap.GetColor(position);
}
public override Matrix4x4 GetTransformMatrix(Vector3Int position)
{
var tile = m_Tilemap.GetEditorPreviewTile(position);
return tile ? m_Tilemap.GetEditorPreviewTransformMatrix(position) : m_Tilemap.GetTransformMatrix(position);
}
public override TileFlags GetTileFlags(Vector3Int position)
{
var tile = m_Tilemap.GetEditorPreviewTile(position);
return tile ? m_Tilemap.GetEditorPreviewTileFlags(position) : m_Tilemap.GetTileFlags(position);
}
// Tile Assets
public override TileBase GetTile(Vector3Int position)
{
return m_Tilemap.GetAnyTile(position);
}
public override T GetTile<T>(Vector3Int position)
{
return m_Tilemap.GetAnyTile<T>(position);
}
// Called from native code - TilemapScripting.cpp
private TileBase CreateInvalidTile()
{
Texture2D tex = Texture2D.whiteTexture;
Sprite sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), tex.width);
Tile tile = ScriptableObject.CreateInstance<Tile>();
tile.sprite = sprite;
// Try to get a pinkish look with a random color to differentiate between other invalid tiles
tile.color = UnityEngine.Random.ColorHSV(340f / 360f, 1f, 0.3f, 0.6f, 0.7f, 1.0f);
tile.transform = Matrix4x4.identity;
tile.flags = TileFlags.LockAll;
return tile;
}
// Called from native code - TilemapScripting.cpp
[UsedByNativeCode]
private static ITilemap CreateInstance()
{
s_Instance = new EditorPreviewTilemap();
return s_Instance;
}
}
}
| UnityCsReference/Modules/TilemapEditor/Editor/Managed/EditorPreviewTilemap.cs/0 | {
"file_path": "UnityCsReference/Modules/TilemapEditor/Editor/Managed/EditorPreviewTilemap.cs",
"repo_id": "UnityCsReference",
"token_count": 1144
} | 470 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEditor;
namespace TreeEditor
{
[System.Serializable]
public class TreeGroupRoot : TreeGroup
{
// These should be propagated to every child..
public float adaptiveLODQuality = 0.8f;
public int shadowTextureQuality = 3; // texture resolution / 2^shadowTextureQuality
public bool enableWelding = true;
public bool enableAmbientOcclusion = true;
public bool enableMaterialOptimize = true;
public float aoDensity = 1.0f;
public float rootSpread = 5.0f;
public float groundOffset;
public Matrix4x4 rootMatrix = Matrix4x4.identity;
static class Styles
{
public static string groupSeedString = LocalizationDatabase.GetLocalizedString("Tree Seed|The global seed that affects the entire tree. Use it to randomize your tree, while keeping the general structure of it.");
}
public void SetRootMatrix(Matrix4x4 m)
{
rootMatrix = m;
// Root node needs to remove scale and position...
rootMatrix.m03 = 0.0f;
rootMatrix.m13 = 0.0f;
rootMatrix.m23 = 0.0f;
rootMatrix = MathUtils.OrthogonalizeMatrix(rootMatrix);
nodes[0].matrix = rootMatrix;
}
override public bool CanHaveSubGroups()
{
return true;
}
override public void UpdateParameters()
{
Profiler.BeginSample("UpdateParameters");
// Set properties
nodes[0].size = rootSpread;
nodes[0].matrix = rootMatrix;
// Update sub-groups
base.UpdateParameters();
Profiler.EndSample(); // UpdateParameters
}
internal override string GroupSeedString { get { return Styles.groupSeedString; } }
internal override string FrequencyString { get { return null; } }
internal override string DistributionModeString { get { return null; } }
internal override string TwirlString { get { return null; } }
internal override string WhorledStepString { get { return null; } }
internal override string GrowthScaleString { get { return null; } }
internal override string GrowthAngleString { get { return null; } }
internal override string MainWindString { get { return null; } }
internal override string MainTurbulenceString { get { return null; } }
internal override string EdgeTurbulenceString { get { return null; } }
}
}
| UnityCsReference/Modules/TreeEditor/Includes/TreeGroupRoot.cs/0 | {
"file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeGroupRoot.cs",
"repo_id": "UnityCsReference",
"token_count": 1036
} | 471 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace UnityEditor.UIAutomation
{
class DragOverTime
{
public float numEventsPerSecond = 10;
float nextEventTime;
float startTime;
float endTime;
Vector2 mouseStart;
Vector2 mouseEnd;
public void DragAndDrop(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd, float seconds)
{
DragAndDrop(window, mousePositionStart, mousePositionEnd, seconds, EventModifiers.None);
}
public void DragAndDrop(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd, float seconds, EventModifiers modifiers)
{
mouseStart = mousePositionStart;
mouseEnd = mousePositionEnd;
mouseStart.y += 23f;
mouseEnd.y += 23f;
startTime = (float)EditorApplication.timeSinceStartup;
endTime = startTime + seconds;
EventUtility.BeginDragAndDrop(window, mouseStart);
}
public bool Update(EditorWindow window)
{
return Update(window, EventModifiers.None);
}
public bool Update(EditorWindow window, EventModifiers modifiers)
{
float curtime = (float)EditorApplication.timeSinceStartup;
if (curtime > nextEventTime)
{
// Dispatch fake drag and drop events
float frac = Mathf.Clamp01((curtime - startTime) / (endTime - startTime));
frac = Easing.Quadratic.InOut(frac);
Vector2 mousePosition = Vector2.Lerp(mouseStart, mouseEnd, frac);
EventUtility.UpdateDragAndDrop(window, mousePosition);
bool shouldContinue = frac < 1.0f;
if (!shouldContinue)
EventUtility.EndDragAndDrop(window, mousePosition);
nextEventTime = curtime + (1 / numEventsPerSecond);
window.Repaint();
return shouldContinue;
}
return true;
}
}
}
| UnityCsReference/Modules/UIAutomationEditor/DragOverTime.cs/0 | {
"file_path": "UnityCsReference/Modules/UIAutomationEditor/DragOverTime.cs",
"repo_id": "UnityCsReference",
"token_count": 979
} | 472 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderUXMLFileSettings
{
const string k_EditorExtensionModeAttributeName = "editor-extension-mode";
bool m_EditorExtensionMode;
readonly VisualElementAsset m_RootElementAsset;
public bool editorExtensionMode
{
get => m_EditorExtensionMode;
set
{
m_EditorExtensionMode = value;
m_RootElementAsset?.SetAttribute(k_EditorExtensionModeAttributeName, m_EditorExtensionMode.ToString());
var builderWindow = Builder.ActiveWindow;
if (builderWindow != null)
builderWindow.toolbar?.InitCanvasTheme();
}
}
public BuilderUXMLFileSettings(VisualTreeAsset visualTreeAsset)
{
m_RootElementAsset = visualTreeAsset.GetRootUxmlElement();
RetrieveEditorExtensionModeSetting();
}
void RetrieveEditorExtensionModeSetting()
{
if (m_RootElementAsset != null && m_RootElementAsset.HasAttribute(k_EditorExtensionModeAttributeName))
m_EditorExtensionMode = Convert.ToBoolean(m_RootElementAsset.GetAttributeValue(k_EditorExtensionModeAttributeName));
else
editorExtensionMode = BuilderProjectSettings.enableEditorExtensionModeByDefault;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderUXMLFileSettings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderUXMLFileSettings.cs",
"repo_id": "UnityCsReference",
"token_count": 653
} | 473 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal static class BuilderStyleSheetsUtilities
{
public static void SetActiveUSS(BuilderSelection selection, BuilderPaneWindow paneWindow, StyleSheet styleSheet)
{
paneWindow.document.UpdateActiveStyleSheet(selection, styleSheet, null);
}
public static bool AddUSSToAsset(BuilderPaneWindow paneWindow, string ussPath)
{
bool added = BuilderAssetUtilities.AddStyleSheetToAsset(paneWindow.document, ussPath);
if (added)
paneWindow.OnEnableAfterAllSerialization();
return added;
}
public static bool CreateNewUSSAsset(BuilderPaneWindow paneWindow)
{
string ussPath = s_SaveFileDialogCallback();
if (string.IsNullOrEmpty(ussPath))
return false;
return CreateNewUSSAsset(paneWindow, ussPath);
}
public static bool CreateNewUSSAsset(BuilderPaneWindow paneWindow, string ussPath)
{
// Create the file. Can be empty.
File.WriteAllText(ussPath, string.Empty);
AssetDatabase.Refresh();
return AddUSSToAsset(paneWindow, ussPath);
}
public static bool AddExistingUSSToAsset(BuilderPaneWindow paneWindow)
{
string ussPath = s_OpenFileDialogCallback();
if (string.IsNullOrEmpty(ussPath))
return false;
return AddUSSToAsset(paneWindow, ussPath);
}
public static void RemoveUSSFromAsset(BuilderPaneWindow paneWindow, BuilderSelection selection, VisualElement clickedElement)
{
// We need to save all files before we remove the USS references.
// If we don't do this, changes in the removed USS will be lost.
var shouldContinue = s_CheckForUnsavedChanges(paneWindow);
if (!shouldContinue)
return;
var selectedElements = selection.selection;
if (!selectedElements.Contains(clickedElement))
{
// Removed just clicked element
var clickedStyleSheetIndex = (int)clickedElement.GetProperty(BuilderConstants.ElementLinkedStyleSheetIndexVEPropertyName);
BuilderAssetUtilities.RemoveStyleSheetFromAsset(paneWindow.document, clickedStyleSheetIndex);
}
else
{
// Removed selected elements
var styleSheetIndexes = selectedElements.Where(x => BuilderSharedStyles.IsStyleSheetElement(x) &&
string.IsNullOrEmpty(x.GetProperty(BuilderConstants.ExplorerItemLinkedUXMLFileName) as string))
.Select(x => (int)x.GetProperty(BuilderConstants.ElementLinkedStyleSheetIndexVEPropertyName))
.OrderByDescending(x => x)
.ToArray();
BuilderAssetUtilities.RemoveStyleSheetsFromAsset(paneWindow.document, styleSheetIndexes);
}
paneWindow.OnEnableAfterAllSerialization();
}
// For tests only.
static string DisplaySaveFileDialogForUSS()
{
var path = BuilderDialogsUtility.DisplaySaveFileDialog(
"Save USS File", null, null, "uss");
return path;
}
static string DisplayOpenFileDialogForUSS()
{
var path = BuilderDialogsUtility.DisplayOpenFileDialog(
"Open USS File", null, "uss");
return path;
}
static bool CheckForUnsavedChanges(BuilderPaneWindow paneWindow)
{
return paneWindow.document.CheckForUnsavedChanges();
}
internal static Func<string> s_SaveFileDialogCallback = DisplaySaveFileDialogForUSS;
internal static Func<string> s_OpenFileDialogCallback = DisplayOpenFileDialogForUSS;
internal static Func<BuilderPaneWindow, bool> s_CheckForUnsavedChanges = CheckForUnsavedChanges;
internal static void RestoreTestCallbacks()
{
s_SaveFileDialogCallback = DisplaySaveFileDialogForUSS;
s_OpenFileDialogCallback = DisplayOpenFileDialogForUSS;
s_CheckForUnsavedChanges = CheckForUnsavedChanges;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 1925
} | 474 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.IO;
using UnityEngine.UIElements;
using System.Collections.Generic;
using System.Linq;
using Unity.Profiling;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Pool;
using UnityEditor.UIElements.Debugger;
using UnityEngine.UIElements.StyleSheets;
using UnityEditor.UIElements.Bindings;
namespace Unity.UI.Builder
{
internal class BuilderInspector : BuilderPaneContent, IBuilderSelectionNotifier
{
enum Section
{
NothingSelected = 1 << 0,
Header = 1 << 1,
StyleSheet = 1 << 2,
StyleSelector = 1 << 3,
ElementAttributes = 1 << 4,
ElementInheritedStyles = 1 << 5,
LocalStyles = 1 << 6,
VisualTreeAsset = 1 << 7,
MultiSelection = 1 << 8,
}
// View Data
// HACK: So...we want to restore the scroll position of the inspector but
// lots of events cause it to reset. For example, undo/redo will reset the
// builder, select nothing, then restore the selection. While nothing is selected,
// the ScrollView will rightly reset the scroll position to 0 since it does not
// need a scroller just to display the "Nothing selected" message. Then, when
// the selection is restored, the scroll position will still be zero.
//
// The solution here, which is definitely overkill, is to cache the previous
// s_MaxCachedScrollPositions m_ScrollView.contentContainer.layout.heights
// and their associated scroll positions. Then, when we detect a
// m_ScrollView.contentContainer GeometryChangeEvent, we look up our
// cache and restore the correct scroll position for this particular content
// height.
[Serializable]
struct CachedScrollPosition
{
public float scrollPosition;
public float maxScrollValue;
}
ScrollView m_ScrollView;
static readonly int s_MaxCachedScrollPositions = 5;
[SerializeField] int m_CachedScrollPositionCount = 0;
[SerializeField] int m_OldestScrollPositionIndex = 0;
[SerializeField] float[] m_CachedContentHeights = new float[s_MaxCachedScrollPositions];
[SerializeField] CachedScrollPosition[] m_CachedScrollPositions = new CachedScrollPosition[s_MaxCachedScrollPositions];
float contentHeight => m_ScrollView.contentContainer.layout.height;
const float m_PreviewDefaultHeight = 200;
const float m_PreviewMinHeight = 20;
float m_CachedPreviewHeight = m_PreviewDefaultHeight;
VisualElement m_TextGeneratorStyle;
// Utilities
BuilderInspectorMatchingSelectors m_MatchingSelectors;
BuilderInspectorStyleFields m_StyleFields;
BuilderBindingsCache m_BindingsCache;
BuilderNotifications m_Notifications;
public BuilderBindingsCache bindingsCache => m_BindingsCache;
public BuilderInspectorMatchingSelectors matchingSelectors => m_MatchingSelectors;
public BuilderInspectorStyleFields styleFields => m_StyleFields;
// Header
BuilderInspectorHeader m_HeaderSection;
internal BuilderInspectorHeader headerSection => m_HeaderSection;
// Sections
BuilderInspectorCanvas m_CanvasSection;
BuilderInspectorAttributes m_AttributesSection;
BuilderInspectorInheritedStyles m_InheritedStyleSection;
BuilderInspectorLocalStyles m_LocalStylesSection;
BuilderInspectorStyleSheet m_StyleSheetSection;
// Selector Preview
TwoPaneSplitView m_SplitView;
BuilderInspectorPreview m_SelectorPreview;
BuilderInspectorPreviewWindow m_PreviewWindow;
public BuilderInspectorCanvas canvasInspector => m_CanvasSection;
public BuilderInspectorAttributes attributesSection => m_AttributesSection;
// Constants
static readonly string s_UssClassName = "unity-builder-inspector";
// Used in tests.
// ReSharper disable MemberCanBePrivate.Global
internal const string refreshUIMarkerName = "BuilderInspector.RefreshUI";
internal const string hierarchyChangedMarkerName = "BuilderInspector.HierarchyChanged";
internal const string selectionChangedMarkerName = "BuilderInspector.SelectionChanged";
internal const string stylingChangedMarkerName = "BuilderInspector.StylingChanged";
// ReSharper restore MemberCanBePrivate.Global
// Profiling
static readonly ProfilerMarker k_RefreshUIMarker = new (refreshUIMarkerName);
static readonly ProfilerMarker k_HierarchyChangedMarker = new (hierarchyChangedMarkerName);
static readonly ProfilerMarker k_SelectionChangedMarker = new (selectionChangedMarkerName);
static readonly ProfilerMarker k_StylingChangedMarker = new (stylingChangedMarkerName);
// External References
BuilderPaneWindow m_PaneWindow;
BuilderSelection m_Selection;
// Current Selection
StyleRule m_CurrentRule;
VisualElement m_CurrentVisualElement;
// Cached Selection
VisualElement m_CachedVisualElement;
internal Binding cachedBinding;
// Sections List (for hiding/showing based on current selection)
List<VisualElement> m_Sections;
// Minor Sections
VisualElement m_NothingSelectedSection;
VisualElement m_NothingSelectedDayZeroVisualElement;
VisualElement m_NothingSelectedIdleStateVisualElement;
VisualElement m_MultiSelectionSection;
HashSet<VisualElement> m_ResolvedBoundFields = new();
public BuilderSelection selection => m_Selection;
public BuilderDocument document => m_PaneWindow.document;
public BuilderPaneWindow paneWindow => m_PaneWindow;
public BuilderInspectorAttributes attributeSection => m_AttributesSection;
public BuilderInspectorPreview preview => m_SelectorPreview;
public BuilderInspectorPreviewWindow previewWindow => m_PreviewWindow;
public bool showingPreview => m_SplitView?.fixedPane?.resolvedStyle.height > m_PreviewMinHeight;
public StyleSheet styleSheet
{
get
{
if (currentVisualElement == null)
return null;
if (BuilderSharedStyles.IsStyleSheetElement(currentVisualElement))
return currentVisualElement.GetStyleSheet();
if (BuilderSharedStyles.IsSelectorElement(currentVisualElement))
return currentVisualElement.GetClosestStyleSheet();
return visualTreeAsset.inlineSheet;
}
}
public VisualTreeAsset visualTreeAsset
{
get
{
var element = currentVisualElement;
if (element == null)
return m_PaneWindow.document.visualTreeAsset;
// It's important to return the VTA of the element, not the
// currently active VTA.
var elementVTA = element.GetProperty(BuilderConstants.ElementLinkedBelongingVisualTreeAssetVEPropertyName) as VisualTreeAsset;
if (elementVTA == null)
return m_PaneWindow.document.visualTreeAsset;
return elementVTA;
}
}
public StyleRule currentRule
{
get
{
if (m_CurrentRule != null)
return m_CurrentRule;
if (currentVisualElement == null)
return null;
if (BuilderSharedStyles.IsSelectorElement(currentVisualElement))
{
var complexSelector = currentVisualElement.GetStyleComplexSelector();
m_CurrentRule = complexSelector?.rule;
}
else if (currentVisualElement.GetVisualElementAsset() != null && currentVisualElement.IsPartOfActiveVisualTreeAsset(document))
{
var vea = currentVisualElement.GetVisualElementAsset();
m_CurrentRule = visualTreeAsset.GetOrCreateInlineStyleRule(vea);
}
else
{
return null;
}
return m_CurrentRule;
}
set
{
m_CurrentRule = value;
}
}
public VisualElement selectedVisualElement => m_CurrentVisualElement;
public VisualElement currentVisualElement
{
get
{
return m_CurrentVisualElement != null ? m_CurrentVisualElement : m_CachedVisualElement;
}
}
HighlightOverlayPainter m_HighlightOverlayPainter;
public HighlightOverlayPainter highlightOverlayPainter => m_HighlightOverlayPainter;
string boundFieldInlineValueBeingEditedName { get; set; }
public BuilderInspector(BuilderPaneWindow paneWindow, BuilderSelection selection, HighlightOverlayPainter highlightOverlayPainter = null, BuilderBindingsCache bindingsCache = null, BuilderNotifications builderNotifications = null)
{
m_BindingsCache = bindingsCache;
m_HighlightOverlayPainter = highlightOverlayPainter;
m_Notifications = builderNotifications;
// Yes, we give ourselves a view data key. Don't do this at home!
viewDataKey = "unity-ui-builder-inspector";
// Init External References
m_Selection = selection;
m_PaneWindow = paneWindow;
// Load Template
var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(
BuilderConstants.UIBuilderPackagePath + "/Inspector/BuilderInspector.uxml");
template.CloneTree(this);
m_TextGeneratorStyle = this.Q<BuilderStyleRow>(null, "unity-text-generator");
if (Unsupported.IsDeveloperMode())
{
UIToolkitProjectSettings.onEnableAdvancedTextChanged += ChangeTextGeneratorStyleVisibility;
m_TextGeneratorStyle.style.display = UIToolkitProjectSettings.enableAdvancedText ? DisplayStyle.Flex : DisplayStyle.None;
}
else
{
UIToolkitProjectSettings.onEnableAdvancedTextChanged -= ChangeTextGeneratorStyleVisibility;
m_TextGeneratorStyle.style.display = DisplayStyle.None;
}
// Get the scroll view.
// HACK: ScrollView is not capable of remembering a scroll position for content that changes often.
// The main issue is that we expand/collapse/display/hide different parts of the Inspector
// all the time so initially the ScrollView is empty and it restores the scroll position to zero.
m_ScrollView = this.Q<ScrollView>("inspector-scroll-view");
m_ScrollView.contentContainer.RegisterCallback<GeometryChangedEvent>(OnScrollViewContentGeometryChange);
m_ScrollView.verticalScroller.valueChanged += (newValue) =>
{
CacheScrollPosition(newValue, m_ScrollView.verticalScroller.highValue);
SaveViewData();
};
// Load styles.
AddToClassList(s_UssClassName);
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UssPath_InspectorWindow));
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UssPath_InspectorWindow_Themed));
// Matching Selectors
m_MatchingSelectors = new BuilderInspectorMatchingSelectors(this);
// Style Fields
m_StyleFields = new BuilderInspectorStyleFields(this);
// Sections
m_Sections = new List<VisualElement>();
// Header Section
m_HeaderSection = new BuilderInspectorHeader(this);
m_Sections.Add(m_HeaderSection.header);
// Nothing Selected Section
m_NothingSelectedSection = this.Q<VisualElement>("nothing-selected-visual-element");
m_NothingSelectedDayZeroVisualElement = this.Q<VisualElement>("day-zero-visual-element");
m_NothingSelectedIdleStateVisualElement = this.Q<VisualElement>("idle-state-visual-element");
m_NothingSelectedDayZeroVisualElement.style.display = DisplayStyle.None;
m_NothingSelectedIdleStateVisualElement.style.display = DisplayStyle.None;
m_Sections.Add(m_NothingSelectedSection);
// Update URL with the correct Unity version (UUM-54027)
var readMoreLabel = this.Q<Label>("day-zero-documentation-body");
readMoreLabel.text = readMoreLabel.text.Replace("{0}", BuilderConstants.ManualUIBuilderUrl);
// Multi-Selection Section
m_MultiSelectionSection = this.Q("multi-selection-unsupported-message");
m_MultiSelectionSection.Add(new IMGUIContainer(
() => EditorGUILayout.HelpBox(BuilderConstants.MultiSelectionNotSupportedMessage, MessageType.Info, true)));
m_Sections.Add(m_MultiSelectionSection);
// Canvas Section
m_CanvasSection = new BuilderInspectorCanvas(this);
m_Sections.Add(m_CanvasSection.root);
// StyleSheet Section
m_StyleSheetSection = new BuilderInspectorStyleSheet(this);
m_Sections.Add(m_StyleSheetSection.root);
// Attributes Section
m_AttributesSection = new BuilderInspectorAttributes(this);
m_Sections.Add(m_AttributesSection.root);
// Inherited Styles Section
m_InheritedStyleSection = new BuilderInspectorInheritedStyles(this, m_MatchingSelectors);
m_Sections.Add(m_InheritedStyleSection.root);
// Local Styles Section
m_LocalStylesSection = new BuilderInspectorLocalStyles(this, m_StyleFields);
m_Sections.Add(m_LocalStylesSection.root);
m_SplitView = this.Q<TwoPaneSplitView>("inspector-content");
m_SplitView.RegisterCallback<GeometryChangedEvent>(OnFirstDisplay);
var previewPane = this.Q<BuilderPane>("inspector-selector-preview");
// Preview Section
m_SelectorPreview = new BuilderInspectorPreview(this);
previewPane.Add(m_SelectorPreview);
// Adding transparency toggle to toolbar
previewPane.toolbar.Add(m_SelectorPreview.backgroundToggle);
previewPane.RegisterCallback<GeometryChangedEvent>(OnSizeChange);
RegisterDraglineInteraction();
// This will take into account the current selection and then call RefreshUI().
SelectionChanged();
// Forward focus to the panel header.
this.Query().Where(e => e.focusable).ForEach((e) => AddFocusable(e));
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
if (m_BindingsCache != null)
{
m_BindingsCache.onBindingStatusChanged += OnBindingStatusChanged;
m_BindingsCache.onBindingRemoved += OnBindingStatusChanged;
}
cachedBinding = null;
}
public void UnsetBoundFieldInlineValue(DropdownMenuAction menuAction)
{
var fieldElement = menuAction.userData as VisualElement;
boundFieldInlineValueBeingEditedName = BuilderInspectorUtilities.GetBindingProperty(fieldElement);
attributeSection.UnsetAttributeProperty(fieldElement, false);
boundFieldInlineValueBeingEditedName = null;
}
public void EnableInlineValueEditing(VisualElement fieldElement)
{
boundFieldInlineValueBeingEditedName = BuilderInspectorUtilities.GetBindingProperty(fieldElement);
var binding = currentVisualElement.GetBinding(boundFieldInlineValueBeingEditedName);
if (binding != null)
cachedBinding = binding;
if (fieldElement == null)
{
return;
}
SetFieldsEnabled(fieldElement, true);
ToggleInlineEditingClasses(fieldElement, true);
var isAttribute = fieldElement.HasLinkedAttributeDescription();
if (isAttribute)
{
// Force the field update to the inline value, because it's disconnected.
var propertyName = fieldElement.GetProperty(BuilderConstants.InspectorAttributeBindingPropertyNameVEPropertyName) as string;
if (!string.IsNullOrEmpty(propertyName))
{
attributeSection.SetInlineValue(fieldElement, propertyName);
}
}
else
{
var styleName =
fieldElement.GetProperty(BuilderConstants.InspectorStylePropertyNameVEPropertyName) as string;
if (!string.IsNullOrEmpty(styleName) &&
StylePropertyUtil.propertyNameToStylePropertyId.TryGetValue(styleName, out var id) &&
id.IsTransitionId())
{
var transitionsListView = fieldElement.GetFirstAncestorOfType<TransitionsListView>();
styleFields.RefreshInlineEditedTransitionField(transitionsListView, id);
}
else
{
// Before the StyleField value is changed, we need to manually update the computed style value
// to the base/default unset value in case there is no set inline value.
styleFields.ResetInlineStyle(styleName);
styleFields.RefreshStyleFieldValue(styleName, fieldElement, true);
// Because we want the inline value to be reflected immediately, we need to force the field to update the element
// Without marking the file as dirty.
var styleProperty = BuilderInspectorStyleFields.GetLastStyleProperty(currentRule, styleName);
styleFields.PostStyleFieldSteps(fieldElement, styleProperty, styleName, false, false, BuilderInspectorStyleFields.NotifyType.Default, true);
}
}
var baseField = fieldElement.Q<VisualElement>(className: BaseField<string>.ussClassName);
baseField?.Focus();
}
public void RegisterFieldToInlineEditingEvents(VisualElement field)
{
field.RegisterCallback<FocusOutEvent, VisualElement>((evt, e) =>
{
DisableInlineValueEditing(e, false);
}, field, TrickleDown.TrickleDown);
field.RegisterCallback<KeyDownEvent, VisualElement>((evt, e) =>
{
if (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.Escape)
{
DisableInlineValueEditing(e, true);
}
}, field, TrickleDown.TrickleDown);
var objectFields = field.Query<ObjectField>();
objectFields.ForEach(x => x.onObjectSelectorShow += x.Focus);
}
private void DisableInlineValueEditing(VisualElement fieldElement, bool skipFocusCheck)
{
boundFieldInlineValueBeingEditedName = null;
m_Notifications.ClearNotifications(BuilderConstants.inlineEditingNotificationKey);
if (!IsInlineEditingEnabled(fieldElement))
{
return;
}
if (skipFocusCheck)
{
DisableInlineEditedField(fieldElement);
}
else
{
// We keep inline editing enabled if focus is still in the field.
// This check is delayed so the focus is updated properly.
fieldElement.schedule.Execute(t =>
{
var focusedElement = fieldElement.FindElement(x => x.IsFocused());
if (focusedElement != null)
{
return;
}
DisableInlineEditedField(fieldElement);
});
}
}
private void DisableInlineEditedField(VisualElement fieldElement)
{
ToggleInlineEditingClasses(fieldElement, false);
SetFieldsEnabled(fieldElement, false);
if (!currentVisualElement.TryGetBinding(cachedBinding.property, out _))
currentVisualElement.SetBinding(cachedBinding.property, cachedBinding);
cachedBinding = null;
}
public void ToggleInlineEditingClasses(VisualElement fieldElement, bool useInlineEditMode)
{
var styleRow = fieldElement.GetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName) as BuilderStyleRow;
var statusIndicator = fieldElement.GetFieldStatusIndicator();
styleRow?.EnableInClassList(BuilderConstants.InspectorFieldBindingInlineEditingEnabledClassName, useInlineEditMode);
statusIndicator?.EnableInClassList(BuilderConstants.InspectorFieldBindingInlineEditingEnabledClassName, useInlineEditMode);
fieldElement.SetProperty(BuilderConstants.InspectorFieldBindingInlineEditingEnabledPropertyName, useInlineEditMode);
}
public bool IsInlineEditingEnabled(VisualElement field)
{
return field.HasProperty(BuilderConstants.InspectorFieldBindingInlineEditingEnabledPropertyName)
&& (bool)field.GetProperty(BuilderConstants.InspectorFieldBindingInlineEditingEnabledPropertyName);
}
private void OnBindingStatusChanged(VisualElement target, string bindingPath)
{
if (target != currentVisualElement || !IsElementSelected())
return;
// Find field
var field = BuilderInspectorUtilities.FindInspectorField(this, bindingPath);
if (field != null)
{
UpdateFieldStatus(field, null);
}
}
public void UpdateBoundFields()
{
if (!IsElementSelected())
return;
foreach (var field in m_ResolvedBoundFields)
{
// Update value current visual element
UpdateBoundValue(field);
}
}
public new void AddFocusable(VisualElement focusable)
{
base.AddFocusable(focusable);
}
void RefreshAfterFirstInit(GeometryChangedEvent evt)
{
currentVisualElement?.UnregisterCallback<GeometryChangedEvent>(RefreshAfterFirstInit);
RefreshUI();
}
void ResetSection(VisualElement section)
{
// For performance reasons, it's important NOT to use a style class!
section.style.display = DisplayStyle.None;
if (section != m_NothingSelectedSection)
return;
m_ScrollView.contentContainer.style.flexGrow = 0;
m_ScrollView.contentContainer.style.justifyContent = Justify.FlexStart;
}
void EnableSection(VisualElement section)
{
// For performance reasons, it's important NOT to use a style class!
section.style.display = DisplayStyle.Flex;
}
void EnableFields()
{
m_HeaderSection.Enable();
m_AttributesSection.Enable();
m_InheritedStyleSection.Enable();
m_LocalStylesSection.Enable();
}
void DisableFields()
{
m_HeaderSection.Disable();
m_AttributesSection.Disable();
m_InheritedStyleSection.Disable();
m_LocalStylesSection.Disable();
}
void EnableSections(Section section)
{
if (section.HasFlag(Section.NothingSelected))
EnableSection(m_NothingSelectedSection);
if (section.HasFlag(Section.Header))
EnableSection(m_HeaderSection.header);
if (section.HasFlag(Section.StyleSheet))
EnableSection(m_StyleSheetSection.root);
if (section.HasFlag(Section.ElementAttributes))
EnableSection(m_AttributesSection.root);
if (section.HasFlag(Section.ElementInheritedStyles))
EnableSection(m_InheritedStyleSection.root);
if (section.HasFlag(Section.LocalStyles))
EnableSection(m_LocalStylesSection.root);
if (section.HasFlag(Section.VisualTreeAsset))
EnableSection(m_CanvasSection.root);
if (section.HasFlag(Section.MultiSelection))
EnableSection(m_MultiSelectionSection);
}
void ResetSections()
{
EnableFields();
foreach (var section in m_Sections)
ResetSection(section);
}
public void UpdateFieldStatus(VisualElement field, StyleProperty property)
{
if (m_CurrentVisualElement == null)
{
return;
}
var valueInfo = FieldValueInfo.Get(this, field, property);
field.SetProperty(BuilderConstants.InspectorFieldValueInfoVEPropertyName, valueInfo);
UpdateFieldStatusIconAndStyling(currentVisualElement, field, valueInfo);
UpdateFieldTooltip(field, valueInfo, currentVisualElement);
UpdateBoundFieldsState(field, valueInfo);
var isAttribute = field.HasLinkedAttributeDescription();
if (isAttribute)
{
attributeSection.UpdateAttributeOverrideStyle(field);
}
else
{
m_StyleFields.UpdateOverrideStyles(field, property);
var isSelectorElement = currentVisualElement.IsSelector();
if (isSelectorElement)
{
var isVariable = valueInfo.valueBinding.type == FieldValueBindingInfoType.USSVariable;
if (isVariable)
{
var isResolvedVariable = valueInfo.valueBinding.variable.sheet != null;
SetFieldsEnabled(field, !isResolvedVariable);
}
}
}
}
private void UpdateBoundFieldsState(VisualElement field, in FieldValueInfo valueInfo)
{
var hasBinding = valueInfo.valueBinding.type == FieldValueBindingInfoType.Binding;
var hasResolvedBinding = false;
if (hasBinding)
{
hasResolvedBinding = valueInfo.valueSource.type == FieldValueSourceInfoType.ResolvedBinding;
if (hasResolvedBinding)
{
m_ResolvedBoundFields.Add(field);
field.RegisterCallback<DetachFromPanelEvent>(OnBoundFieldDetached);
}
else
{
UnregisterBoundField(field);
}
}
else
{
UnregisterBoundField(field);
}
SetFieldsEnabled(field, !hasResolvedBinding);
}
void OnBoundFieldDetached(DetachFromPanelEvent evt)
{
UnregisterBoundField(evt.elementTarget);
}
void UnregisterBoundField(VisualElement field)
{
if (!m_ResolvedBoundFields.Contains(field))
{
return;
}
field.UnregisterCallback<DetachFromPanelEvent>(OnBoundFieldDetached);
m_ResolvedBoundFields.Remove(field);
}
public void SetFieldsEnabled(VisualElement field, bool enabled)
{
if (IsInlineEditingEnabled(field))
{
return;
}
if (field is TextShadowStyleField)
{
// Special case for TextShadowStyleField.
// We need to disabled the fields inside so the foldout is still functional
var foldout = field.Q<Foldout>();
foldout.contentContainer.SetEnabled(enabled);
}
else
{
if (field is BuilderUxmlAttributesView.UxmlSerializedDataAttributeField)
{
// If enabled is false, then field has resolved binding
// and we need to allow tabbing on UxmlSerializedDataAttributeField
var boundPropertyField = field.Q<PropertyField>();
SetFieldAndParentContainerEnabledState(field, boundPropertyField, !enabled);
}
else
{
var styleRow = field.GetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName) as BuilderStyleRow;
SetFieldAndParentContainerEnabledState(styleRow, field, !enabled);
}
if (field.GetProperty(BuilderConstants.FoldoutFieldPropertyName) is FoldoutField foldout)
{
var fields = foldout.Query<VisualElement>(classes: BaseField<float>.ussClassName);
var hasBindings = false;
var hasResolvedBindings = false;
fields.ForEach(x =>
{
var bindingProperty = BuilderInspectorUtilities.GetBindingProperty(x);
var bindingId = new BindingId(bindingProperty);
if (DataBindingUtility.TryGetLastUIBindingResult(bindingId, currentVisualElement, out var bindingResult))
{
hasBindings = true;
hasResolvedBindings |= bindingResult.status == BindingStatus.Success;
}
});
foldout.EnableInClassList(BuilderConstants.BoundFoldoutFieldClassName, hasBindings);
foldout.SetHeaderInputEnabled(!hasResolvedBindings);
}
}
}
void UpdateBoundValue(VisualElement field)
{
var attributeName = BuilderInspectorUtilities.GetBindingProperty(field);
var isAttribute = field.HasLinkedAttributeDescription();
if (isAttribute && (IsInlineEditingEnabled(field) || boundFieldInlineValueBeingEditedName == attributeName))
{
// Don't update value now, it's being edited
return;
}
if (isAttribute)
{
var value = currentVisualElement.GetValueByReflection(attributeName);
attributeSection.SetBoundValue(field, value);
// Because the basefield could have previously not been yet created,
// we need to refresh the enabled state of the property field and its child basefield.
// This only happens once, when the field is first created but not yet bound.
var propertyField = field.Q<PropertyField>();
if (field.focusable == false || propertyField.enabledSelf == false)
{
propertyField.SetEnabled(true);
SetFieldAndParentContainerEnabledState(field, propertyField, true);
}
}
else
{
var styleName =
field.GetProperty(BuilderConstants.InspectorStylePropertyNameVEPropertyName) as string;
StylePropertyUtil.propertyNameToStylePropertyId.TryGetValue(styleName, out var id);
if (id.IsTransitionId())
{
var transitionsListView = field.GetFirstAncestorOfType<TransitionsListView>();
styleFields.RefreshStyleField(transitionsListView);
}
else
{
var forceInlineIfBinding = IsInlineEditingEnabled(field) && cachedBinding != null && cachedBinding.property == boundFieldInlineValueBeingEditedName;
styleFields.RefreshStyleFieldValue(styleName, field, forceInlineIfBinding);
}
}
}
// Used when the field should be disabled,
// but the parent container should have tabbing enabled for keyboard navigation.
private void SetFieldAndParentContainerEnabledState(VisualElement focusableContainer, VisualElement field, bool parentContainerShouldBeFocusable)
{
if (focusableContainer == null || field == null)
return;
focusableContainer.focusable = parentContainerShouldBeFocusable;
var baseField = field.Q<VisualElement>(className: BaseField<string>.ussClassName);
if (baseField == null)
field.SetEnabled(!parentContainerShouldBeFocusable);
else
baseField.SetEnabled(!parentContainerShouldBeFocusable);
}
internal static void UpdateFieldStatusIconAndStyling(VisualElement currentElement, VisualElement field, FieldValueInfo valueInfo, bool inInspector = true)
{
var statusIndicator = field.GetFieldStatusIndicator();
void ClearClassLists(VisualElement ve)
{
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleDefaultStatusClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleInheritedClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleSelectorClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleVariableClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleUnresolvedVariableClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleBindingClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleUnresolvedBindingClassName);
ve.RemoveFromClassList(BuilderConstants.InspectorLocalStyleSelectorElementClassName);
};
ClearClassLists(field);
ClearClassLists(statusIndicator);
var statusClassName = valueInfo.valueBinding.type switch
{
FieldValueBindingInfoType.USSVariable => valueInfo.valueBinding.variable.sheet != null
? BuilderConstants.InspectorLocalStyleVariableClassName
: BuilderConstants.InspectorLocalStyleUnresolvedVariableClassName,
FieldValueBindingInfoType.Binding => valueInfo.valueSource.type == FieldValueSourceInfoType.ResolvedBinding ?
BuilderConstants.InspectorLocalStyleBindingClassName : BuilderConstants.InspectorLocalStyleUnresolvedBindingClassName,
_ => valueInfo.valueSource.type switch
{
FieldValueSourceInfoType.Inherited => BuilderConstants.InspectorLocalStyleInheritedClassName,
FieldValueSourceInfoType.MatchingUSSSelector => BuilderConstants.InspectorLocalStyleSelectorClassName,
_ => BuilderConstants.InspectorLocalStyleDefaultStatusClassName
}
};
statusIndicator.AddToClassList(statusClassName);
field.AddToClassList(statusClassName);
if (currentElement != null)
{
var isSelector = currentElement.IsSelector();
if (isSelector)
{
statusIndicator.AddToClassList(BuilderConstants.InspectorLocalStyleSelectorElementClassName);
field.AddToClassList(BuilderConstants.InspectorLocalStyleSelectorElementClassName);
}
}
// If the element's data source / data source type is inherited: data source toggle group label, field status indicator and data source object field display need to be updated
if (!valueInfo.name.Equals(BuilderDataSourceAndPathView.k_BindingAttr_DataSource) && !valueInfo.name.Equals(BuilderDataSourceAndPathView.k_BindingAttr_DataSourceType))
return;
UpdateFieldTooltip(field, valueInfo, currentElement);
var styleRow = field.GetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName) as BuilderStyleRow;
var bindingAttributeTypeButtonGroup = styleRow?.Q<ToggleButtonGroup>();
if (bindingAttributeTypeButtonGroup == null)
return;
if (valueInfo.valueBinding.type == FieldValueBindingInfoType.Constant && valueInfo.valueSource.type == FieldValueSourceInfoType.Inherited)
{
var parent = currentElement.parent;
if (parent == null)
return;
// update the label to show that source is inherited
bindingAttributeTypeButtonGroup.label = string.Format(BuilderConstants.BuilderLabelWithInheritedLabelSuffix, BuilderNameUtilities.ConvertDashToHuman(BuilderDataSourceAndPathView.k_BindingAttr_DataSource));
if (!valueInfo.name.Equals(BuilderDataSourceAndPathView.k_BindingAttr_DataSource))
return;
// Object field display label must be truncated to fit in the display.
var objectFieldDisplay = field.Q<ObjectField.ObjectFieldDisplay>();
DataBindingUtility.TryGetRelativeDataSourceFromHierarchy(inInspector ? parent : currentElement, out var dataSource);
var dataSourceName = BuilderNameUtilities.GetNameByReflection(dataSource);
var objectFieldDisplayLabel = objectFieldDisplay?.Q<Label>();
if (objectFieldDisplayLabel != null && objectFieldDisplayLabel.text.Contains(BuilderConstants.UnnamedValue))
{
objectFieldDisplayLabel.text = dataSourceName.Contains(BuilderConstants.UnnamedValue) ?
string.Format(BuilderConstants.BuilderBindingObjectFieldEmptyMessage, dataSource)
: dataSourceName;
}
}
else
{
bindingAttributeTypeButtonGroup.label = BuilderNameUtilities.ConvertDashToHuman(BuilderDataSourceAndPathView.k_BindingAttr_DataSource);
}
}
internal static void UpdateFieldTooltip(VisualElement field, in FieldValueInfo valueInfo, VisualElement currentElement = null)
{
var draggerLabel = GetDraggerLabel(field);
var tooltipValue = GetFieldTooltip(field, valueInfo);
if (draggerLabel != null)
{
draggerLabel.tooltip = tooltipValue;
}
field.GetFieldStatusIndicator().tooltip = GetFieldStatusIndicatorTooltip(valueInfo, field, currentElement);
}
internal static Label GetDraggerLabel(VisualElement field)
{
var labelDraggers = field.Query<Label>(classes: BaseField<float>.labelDraggerVariantUssClassName).Build();
return GetFirstItemIfCountIs1(labelDraggers);
}
static Label GetFirstItemIfCountIs1(UQueryState<Label> query)
{
using (var enumerator = query.GetEnumerator())
{
if (enumerator.MoveNext())
{
var firstItem = enumerator.Current;
if (!enumerator.MoveNext())
{
return firstItem;
}
}
return null;
}
}
static string GetFieldStatusIndicatorTooltip(in FieldValueInfo info, VisualElement field, VisualElement currentElement, string description = null)
{
// Data source type attribute's tooltip should not override the data source attribute's tooltip if data source is set
if (info.name.Equals(BuilderDataSourceAndPathView.k_BindingAttr_DataSourceType) && currentElement.dataSource != null)
{
return BuilderConstants.FieldStatusIndicatorInlineTooltip;
}
if (info.valueSource.type == FieldValueSourceInfoType.Default)
return BuilderConstants.FieldStatusIndicatorDefaultTooltip;
if (info.valueBinding.type == FieldValueBindingInfoType.USSVariable)
return info.valueBinding.variable.sheet != null ? GetVariableTooltip(info.valueBinding.variable) : BuilderConstants.FieldStatusIndicatorUnresolvedVariableTooltip;
// data binding
if (info.valueBinding.type == FieldValueBindingInfoType.Binding)
{
// detailed binding information
var inspector = Builder.ActiveWindow.inspector;
var currentVisualElement = inspector.currentVisualElement;
var property = BuilderInspectorUtilities.GetBindingProperty(field);
if (!BuilderBindingUtility.TryGetBinding(property, out var binding, out var bindingUxml) ||
binding is not DataBinding dataBinding)
return BuilderConstants.FieldStatusIndicatorUnresolvedBindingTooltip;
var notDefinedString = L10n.Tr(BuilderConstants.BindingNotDefinedAttributeString);
var currentElementDataSource =
BuilderBindingUtility.GetBindingDataSourceOrRelativeHierarchicalDataSource(currentVisualElement,
property);
var dataSourceString = currentElementDataSource ?? notDefinedString;
var bindingMode = dataBinding.bindingMode;
var dataSourcePathStr = dataBinding.dataSourcePath.IsEmpty
? notDefinedString
: dataBinding.dataSourcePath.ToString();
var convertersToSource =
bindingUxml.GetAttributeValue(BuilderBindingUxmlAttributesView
.k_BindingAttr_ConvertersToSource);
var convertersToUI =
bindingUxml.GetAttributeValue(BuilderBindingUxmlAttributesView.k_BindingAttr_ConvertersToUi);
var converters = GetFormattedConvertersString(convertersToSource, convertersToUI);
return info.valueSource.type switch
{
FieldValueSourceInfoType.ResolvedBinding => string.Format(BuilderConstants.FieldTooltipDataDefinitionBindingFormatString,
BuilderConstants.FieldStatusIndicatorResolvedBindingTooltip,
dataSourceString, dataSourcePathStr, bindingMode, converters),
FieldValueSourceInfoType.UnhandledBinding => string.Format(BuilderConstants.FieldTooltipDataDefinitionBindingFormatString,
BuilderConstants.FieldStatusIndicatorUnhandledBindingTooltip,
dataSourceString, dataSourcePathStr, bindingMode, converters),
_ => string.Format(BuilderConstants.FieldTooltipDataDefinitionBindingFormatString,
BuilderConstants.FieldStatusIndicatorUnresolvedBindingTooltip,
dataSourceString, dataSourcePathStr, bindingMode, converters),
};
}
// inherited data source or data source type
if (info.valueBinding.type == FieldValueBindingInfoType.Constant && info.valueSource.type == FieldValueSourceInfoType.Inherited)
{
var parent = currentElement.parent;
if (parent == null)
return "";
var parentString = string.Format(BuilderConstants.FieldStatusIndicatorInheritedTooltip, parent.typeName,
parent.name);
DataBindingUtility.TryGetDataSourceOrDataSourceTypeFromHierarchy(parent, out var dataSourceObject, out var dataSourceType, out var fullPath);
if (dataSourceObject != null)
return string.Format(BuilderConstants.FieldStatusIndicatorInheritedDataSourceTooltip, parentString, dataSourceObject, fullPath);
if (dataSourceType != null)
return string.Format(BuilderConstants.FieldStatusIndicatorInheritedDataSourceTypeTooltip, parentString, dataSourceType, fullPath);
return "";
}
return info.valueSource.type switch
{
FieldValueSourceInfoType.Inline => BuilderConstants.FieldStatusIndicatorInlineTooltip,
FieldValueSourceInfoType.Inherited => GetInheritedValueTooltip(currentElement),
FieldValueSourceInfoType.MatchingUSSSelector => GetMatchingStyleSheetRuleSourceTooltip(info.valueSource.matchedRule),
FieldValueSourceInfoType.LocalUSSSelector => BuilderConstants.FieldStatusIndicatorLocalTooltip,
_ => null
};
}
internal static string GetFieldTooltip(VisualElement field, in FieldValueInfo info, string description = null, bool allowValueDescription = true)
{
if (info.type == FieldValueInfoType.None)
return "";
var tooltipFormat = BuilderConstants.FieldTooltipNameOnlyFormatString;
var value = string.Format(tooltipFormat, info.type.ToDisplayString(), info.name);
var valueDataText = "";
var valueDefinitionDataText = "";
// binding
if (info.valueSource.type != FieldValueSourceInfoType.Default
&& info.valueSource.type != FieldValueSourceInfoType.Inherited)
{
if (allowValueDescription)
tooltipFormat = BuilderConstants.FieldTooltipFormatString;
// if the value is bound to variable then display the variable info
if (allowValueDescription && info.valueBinding.type == FieldValueBindingInfoType.USSVariable)
valueDataText = $"\n{GetVariableTooltip(info.valueBinding.variable)}";
}
// source
if (allowValueDescription && info.valueSource.type.IsFromUSSSelector())
valueDefinitionDataText = $"\n{GetMatchingStyleSheetRuleSourceTooltip(info.valueSource.matchedRule)}";
// For UX purposes, some USS properties have custom tooltips. If no custom tooltip is found, fall back to generated tooltip
if (info.type == FieldValueInfoType.USSProperty && BuilderConstants.InspectorStylePropertiesTooltipsDictionary.TryGetValue(info.name, out var ussTooltip))
{
tooltipFormat = BuilderConstants.FieldTooltipWithDescription;
value = string.Format(tooltipFormat, info.type.ToDisplayString(), info.name, ussTooltip);
}
else
{
value = string.Format(tooltipFormat, info.type.ToDisplayString(), info.name, info.valueBinding.type.ToDisplayString(), valueDataText, info.valueSource.type.ToDisplayString(), valueDefinitionDataText);
}
if (!string.IsNullOrEmpty(description))
value += "\n\n" + description;
return value;
}
static string GetFormattedConvertersString(string convertersToSource, string convertersToUI)
{
if (string.IsNullOrEmpty(convertersToSource) && string.IsNullOrEmpty(convertersToUI))
{
return L10n.Tr(BuilderConstants.EmptyConvertersString);
}
if (string.IsNullOrEmpty(convertersToSource))
{
return convertersToUI;
}
if (string.IsNullOrEmpty(convertersToUI))
{
return convertersToSource;
}
return $"{convertersToSource}, {convertersToUI}";
}
static string GetMatchingStyleSheetRuleSourceTooltip(in MatchedRule matchedRule)
{
var displayPath = matchedRule.displayPath;
// Remove line number
var index = displayPath.IndexOf(':');
if (index != -1)
{
displayPath = displayPath.Substring(0, index);
}
return string.Format(BuilderConstants.FieldStatusIndicatorFromSelectorTooltip, StyleSheetToUss.ToUssSelector(matchedRule.matchRecord.complexSelector), displayPath);
}
static string GetVariableTooltip(in VariableInfo info)
{
string variableName = "";
string sourceStyleSheet = "";
if (info.sheet)
{
var varStyleSheetOrigin = info.sheet;
var fullPath = AssetDatabase.GetAssetPath(varStyleSheetOrigin);
if (string.IsNullOrEmpty(fullPath))
{
sourceStyleSheet = varStyleSheetOrigin.name;
}
else
{
sourceStyleSheet = fullPath == BuilderConstants.EditorResourcesBundlePath ? varStyleSheetOrigin.name : Path.GetFileName(fullPath);
}
}
else
{
sourceStyleSheet = BuilderConstants.FileNotFoundMessage;
}
variableName = info.name;
return string.Format(BuilderConstants.FieldStatusIndicatorVariableTooltip, variableName, sourceStyleSheet);
}
static string GetInheritedValueTooltip(VisualElement child)
{
var parent = child.parent;
return string.Format(BuilderConstants.FieldStatusIndicatorInheritedTooltip,
parent != null ? parent.typeName : "",
parent != null ? parent.name : "");
}
internal override void OnViewDataReady()
{
base.OnViewDataReady();
string key = GetFullHierarchicalViewDataKey();
OverwriteFromViewData(this, key);
SetScrollerPositionFromSavedState();
}
void OnScrollViewContentGeometryChange(GeometryChangedEvent evt)
{
SetScrollerPositionFromSavedState();
}
void CacheScrollPosition(float currentScrollPosition, float currentMaxScrollValue)
{
// This avoid pushing legitimate cached positions out of the cache with
// short (nothing selected) content.
if (!m_ScrollView.needsVertical)
return;
int index = -1;
for (int i = 0; i < m_CachedScrollPositionCount; ++i)
if (m_CachedContentHeights[i] == contentHeight)
{
index = i;
break;
}
if (index < 0)
{
if (m_CachedScrollPositionCount < s_MaxCachedScrollPositions)
{
index = m_CachedScrollPositionCount;
m_CachedScrollPositionCount++;
}
else
{
index = m_OldestScrollPositionIndex;
m_OldestScrollPositionIndex = (m_OldestScrollPositionIndex + 1) % s_MaxCachedScrollPositions;
}
}
var cached = m_CachedScrollPositions[index];
cached.scrollPosition = currentScrollPosition;
cached.maxScrollValue = currentMaxScrollValue;
m_CachedScrollPositions[index] = cached;
m_CachedContentHeights[index] = contentHeight;
}
int GetCachedScrollPositionIndex()
{
int index = -1;
for (int i = 0; i < m_CachedScrollPositionCount; ++i)
if (m_CachedContentHeights[i] == contentHeight)
{
index = i;
break;
}
return index;
}
void SetScrollerPositionFromSavedState()
{
var index = GetCachedScrollPositionIndex();
if (index < 0)
return;
var cached = m_CachedScrollPositions[index];
m_ScrollView.verticalScroller.highValue = cached.maxScrollValue;
m_ScrollView.verticalScroller.value = cached.scrollPosition;
}
public void RefreshUI()
{
using var marker = k_RefreshUIMarker.Auto();
// On the first RefreshUI, if an element is already selected, we need to make sure it
// has a valid style. If not, we need to delay our UI building until it is properly initialized.
if (currentVisualElement != null &&
// TODO: This is just for tests to pass. When adding selectors via the fake events
// we sometimes get selector elements that have no layout and will not layout
// no matter how many yields we add. They do have the correct panel.
m_Selection.selectionType != BuilderSelectionType.StyleSelector &&
float.IsNaN(currentVisualElement.layout.width))
{
currentVisualElement.RegisterCallback<GeometryChangedEvent>(RefreshAfterFirstInit);
return;
}
foreach (var field in m_ResolvedBoundFields)
{
field.UnregisterCallback<DetachFromPanelEvent>(OnBoundFieldDetached);
}
m_ResolvedBoundFields.Clear();
// Determine what to show based on selection.
ResetSections();
UpdateSelectorPreviewsVisibility();
if (m_Selection.selectionCount > 1)
{
EnableSections(Section.MultiSelection);
return;
}
switch (m_Selection.selectionType)
{
case BuilderSelectionType.Nothing:
EnableSections(Section.NothingSelected);
m_ScrollView.contentContainer.style.flexGrow = 1;
m_ScrollView.contentContainer.style.justifyContent = Justify.Center;
var hierarchyOrStyleSectionsNotEmpty = document.visualTreeAsset.visualElementAssets.Count > 1 ||
document.activeStyleSheet != null;
if (!string.IsNullOrEmpty(document.activeOpenUXMLFile.uxmlPath) || hierarchyOrStyleSectionsNotEmpty)
{
m_NothingSelectedIdleStateVisualElement.style.display = DisplayStyle.Flex;
m_NothingSelectedDayZeroVisualElement.style.display = DisplayStyle.None;
}
else
{
m_NothingSelectedDayZeroVisualElement.style.display = DisplayStyle.Flex;
m_NothingSelectedIdleStateVisualElement.style.display = DisplayStyle.None;
}
return;
case BuilderSelectionType.StyleSheet:
EnableSections(Section.StyleSheet);
return;
case BuilderSelectionType.ParentStyleSelector:
case BuilderSelectionType.StyleSelector:
EnableSections(
Section.Header |
Section.StyleSelector |
Section.LocalStyles);
break;
case BuilderSelectionType.ElementInTemplateInstance:
case BuilderSelectionType.ElementInControlInstance:
case BuilderSelectionType.ElementInParentDocument:
case BuilderSelectionType.Element:
EnableSections(
Section.Header |
Section.ElementAttributes |
Section.ElementInheritedStyles |
Section.LocalStyles);
break;
case BuilderSelectionType.VisualTreeAsset:
EnableSections(Section.VisualTreeAsset);
m_CanvasSection.Refresh();
return;
}
bool selectionInTemplateInstance = m_Selection.selectionType == BuilderSelectionType.ElementInTemplateInstance;
bool selectionInControlInstance = m_Selection.selectionType == BuilderSelectionType.ElementInControlInstance;
bool selectionInParentSelector = m_Selection.selectionType == BuilderSelectionType.ParentStyleSelector;
bool selectionInParentDocument = m_Selection.selectionType == BuilderSelectionType.ElementInParentDocument;
if (selectionInTemplateInstance || selectionInParentSelector || selectionInParentDocument || selectionInControlInstance)
{
DisableFields();
}
if (selectionInTemplateInstance && !string.IsNullOrEmpty(currentVisualElement.name))
{
m_HeaderSection.Enable();
m_AttributesSection.Enable();
}
// Reselect Icon, Type & Name in Header
m_HeaderSection.Refresh();
if (m_AttributesSection.refreshScheduledItem != null)
{
// Pause to stop it in case it's already running; and then restart it to execute it.
m_AttributesSection.refreshScheduledItem.Pause();
m_AttributesSection.refreshScheduledItem.Resume();
}
else
{
m_AttributesSection.refreshScheduledItem = m_AttributesSection.fieldsContainer.schedule.Execute(() => m_AttributesSection.Refresh());
}
// Reset current style rule.
currentRule = null;
// Get all shared style selectors and draw their fields.
m_MatchingSelectors.GetElementMatchers();
m_InheritedStyleSection.Refresh();
// Create the fields for the overridable styles.
m_LocalStylesSection.Refresh();
m_CanvasSection.Refresh();
if (selectionInTemplateInstance)
{
m_HeaderSection.Disable();
}
}
public void OnAfterBuilderDeserialize()
{
m_CanvasSection.Refresh();
}
public void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType)
{
using var marker = k_HierarchyChangedMarker.Auto();
m_HeaderSection.Refresh();
if ((changeType & BuilderHierarchyChangeType.Attributes) == BuilderHierarchyChangeType.Attributes)
{
if (m_AttributesSection.refreshScheduledItem != null)
{
// Pause to stop it in case it's already running; and then restart it to execute it.
m_AttributesSection.refreshScheduledItem.Pause();
m_AttributesSection.refreshScheduledItem.Resume();
}
else
{
m_AttributesSection.refreshScheduledItem = m_AttributesSection.fieldsContainer.schedule.Execute(() => m_AttributesSection.Refresh());
}
}
}
public void SelectionChanged()
{
using var marker = k_SelectionChangedMarker.Auto();
if (!string.IsNullOrEmpty(boundFieldInlineValueBeingEditedName))
{
if (focusController.focusedElement is VisualElement element && IsInlineEditingEnabled(element))
{
DisableInlineValueEditing(element, true);
}
}
if (m_CurrentVisualElement != null)
{
if (BuilderSharedStyles.IsSelectorElement(m_CurrentVisualElement))
{
StyleSheetUtilities.RemoveFakeSelector(m_CurrentVisualElement);
}
m_CurrentVisualElement.UnregisterCallback<PropertyChangedEvent>(OnPropertyChanged, TrickleDown.TrickleDown);
}
m_CurrentVisualElement = null;
foreach (var element in m_Selection.selection)
{
if (m_CurrentVisualElement != null) // We only support editing one element. Disable for for multiple elements.
{
m_CurrentVisualElement = null;
break;
}
m_CurrentVisualElement = element;
}
if (m_CurrentVisualElement != null)
{
m_CurrentVisualElement.RegisterCallback<PropertyChangedEvent>(OnPropertyChanged, TrickleDown.TrickleDown);
m_CachedVisualElement = m_CurrentVisualElement;
}
if (IsElementSelected())
{
m_AttributesSection.SetAttributesOwner(visualTreeAsset, currentVisualElement, m_Selection.selectionType == BuilderSelectionType.ElementInTemplateInstance);
}
else
{
m_AttributesSection.ResetAttributesOwner();
}
if (m_CurrentVisualElement != null && BuilderSharedStyles.IsSelectorElement(m_CurrentVisualElement))
{
StyleSheetUtilities.AddFakeSelector(m_CurrentVisualElement);
m_Selection.NotifyOfStylingChange(null, null, BuilderStylingChangeType.RefreshOnly);
}
else
{
RefreshUI();
}
}
private void OnPropertyChanged(PropertyChangedEvent evt)
{
if (!string.IsNullOrEmpty(boundFieldInlineValueBeingEditedName))
{
// Stop propagation during inline editing to avoid changing data source
evt.StopImmediatePropagation();
}
}
private bool IsElementSelected()
{
return m_CurrentVisualElement != null && m_Selection.selectionType is BuilderSelectionType.Element
or BuilderSelectionType.ElementInTemplateInstance or BuilderSelectionType.ElementInControlInstance;
}
#pragma warning disable CS0618 // Type or member is obsolete
private UnityEngine.UIElements.UxmlTraits GetCurrentElementTraits()
{
var currentVisualElementTypeName = currentVisualElement.GetType().ToString();
if (!VisualElementFactoryRegistry.TryGetValue(currentVisualElementTypeName, out var factoryList))
{
// We fallback on the BindableElement factory if we don't find any so
// we can update the modified attributes. This fixes the TemplateContainer
// factory not found.
if (!VisualElementFactoryRegistry.TryGetValue(typeof(BindableElement).FullName,
out factoryList))
{
return null;
}
}
var traits = factoryList[0].GetTraits() as UxmlTraits;
return traits;
}
#pragma warning restore CS0618 // Type or member is obsolete
internal void CallInitOnElement()
{
var traits = GetCurrentElementTraits();
if (traits == null)
return;
// We need to clear bindings before calling Init to avoid corrupting the data source.
BuilderBindingUtility.ClearUxmlBindings(currentVisualElement);
var context = new CreationContext(null, null, visualTreeAsset, currentVisualElement);
var vea = currentVisualElement.GetVisualElementAsset();
traits.Init(currentVisualElement, vea, context);
}
internal void CallInitOnTemplateChild(VisualElement visualElement, VisualElementAsset vea,
List<CreationContext.AttributeOverrideRange> attributeOverridesRanges)
{
var traits = GetCurrentElementTraits();
if (traits == null)
return;
// We need to clear bindings before calling Init to avoid corrupting the data source.
BuilderBindingUtility.ClearUxmlBindings(currentVisualElement);
var context = new CreationContext(null, attributeOverridesRanges, null, null);
traits.Init(visualElement, vea, context);
}
public void StylingChanged(List<string> styles, BuilderStylingChangeType changeType = BuilderStylingChangeType.Default)
{
using var marker = k_StylingChangedMarker.Auto();
if (styles != null)
{
foreach (var styleName in styles)
{
var fieldList = m_StyleFields.GetFieldListForStyleName(styleName);
if (fieldList == null)
continue;
// Transitions are composed of dynamic elements which can add/remove themselves in the fieldList
// when the style is refreshed, so we take a copy of the list to ensure we do not iterate and
// mutate the list at the same time.
var tempFieldList = ListPool<VisualElement>.Get();
try
{
tempFieldList.AddRange(fieldList);
foreach (var field in tempFieldList)
m_StyleFields.RefreshStyleField(styleName, field);
}
finally
{
ListPool<VisualElement>.Release(tempFieldList);
}
}
m_LocalStylesSection.UpdateStyleCategoryFoldoutOverrides();
}
else
{
RefreshUI();
}
}
public VisualElement FindFieldAtPath(string propertyPath)
{
const string k_StylePrefix = "style.";
if (propertyPath.StartsWith(k_StylePrefix))
{
return FindStyleField(BuilderNameUtilities.ConvertStyleCSharpNameToUssName(propertyPath.Substring(k_StylePrefix.Length)));
}
else
{
return FindAttributeField(attributeSection.GetRemapCSPropertyToAttributeName(propertyPath));
}
}
public VisualElement FindAttributeField(string propName)
{
bool IsFieldElement(VisualElement ve)
{
var attribute = ve.GetLinkedAttributeDescription();
return attribute?.name == propName;
}
VisualElement field;
if (propName is "data-source" or "data-source-type" or "data-source-path")
field = m_HeaderSection.m_DataSourceAndPathView.fieldsContainer.Query().Where(IsFieldElement);
else
field = attributeSection.root.Query().Where(IsFieldElement);
return field;
}
VisualElement FindTransitionField(string fieldPath)
{
var openBracketIndex = fieldPath.IndexOf('[');
var closeBracketIndex = fieldPath.IndexOf(']');
var transitionIndexStr = fieldPath.Substring(openBracketIndex + 1, (closeBracketIndex - openBracketIndex - 1));
var transitionIndex = int.Parse(transitionIndexStr);
var fieldName = fieldPath.Substring(closeBracketIndex + 2);
var transitionListView = this.Q<TransitionsListView>();
var transitionView = transitionListView[transitionIndex];
return transitionView.Q(fieldName);
}
public VisualElement FindStyleField(string styleName)
{
VisualElement field = null;
if (styleName.StartsWith("transitions"))
field = FindTransitionField(styleName);
else
field = styleFields.m_StyleFields[styleName].First();
return field;
}
void OnFirstDisplay(GeometryChangedEvent evt)
{
if (m_PreviewWindow != null)
OpenPreviewWindow();
else
{
UpdatePreviewHeight(m_PreviewDefaultHeight);
// Needed to stop the TwoPaneSplitView from calling its own GeometryChangedEvent callback (OnSizeChange)
// which would change the pane's layout to have the cached height when reopening the builder.
evt.StopImmediatePropagation();
}
UpdateSelectorPreviewsVisibility();
m_SplitView.UnregisterCallback<GeometryChangedEvent>(OnFirstDisplay);
}
private void OnSizeChange(GeometryChangedEvent evt)
{
var hideToggle = !showingPreview && m_PreviewWindow == null;
m_SelectorPreview.backgroundToggle.style.display = hideToggle ? DisplayStyle.None : DisplayStyle.Flex;
}
private void OnDragLineChange(PointerUpEvent evt)
{
var previewHeight = m_SplitView.fixedPane.resolvedStyle.height;
var isSingleClick = (previewHeight == m_CachedPreviewHeight || previewHeight == m_PreviewMinHeight)
&& Math.Abs(m_SplitView.m_Resizer.delta) <= 5;
if (isSingleClick && evt.button == (int) MouseButton.LeftMouse)
{
TogglePreviewInInspector();
return;
}
if (!showingPreview) return;
m_CachedPreviewHeight = previewHeight;
}
internal void ReattachPreview()
{
var previewPane = this.Q<BuilderPane>("inspector-selector-preview");
m_SplitView.fixedPaneDimension = m_PreviewDefaultHeight;
previewPane.Add(m_SelectorPreview);
previewPane.toolbar.Add(m_SelectorPreview.backgroundToggle);
m_PreviewWindow = null;
UpdateSelectorPreviewsVisibility();
}
void UpdateSelectorPreviewsVisibility()
{
var currElementIsSelector = m_CurrentVisualElement != null &&
BuilderSharedStyles.IsSelectorElement(m_CurrentVisualElement);
if (m_PreviewWindow == null)
{
if (currElementIsSelector)
{
m_SplitView.UnCollapse();
m_SelectorPreview.style.display = DisplayStyle.Flex;
}
else
m_SplitView.CollapseChild(1);
}
else if (currElementIsSelector)
{
m_SelectorPreview.style.display = DisplayStyle.Flex;
// hiding empty state message
m_PreviewWindow.idleMessage.style.display = DisplayStyle.None;
}
else
{
m_SelectorPreview.style.display = DisplayStyle.None;
// showing empty state message
m_PreviewWindow.idleMessage.style.display = DisplayStyle.Flex;
}
}
internal void TogglePreviewInInspector()
{
if (showingPreview)
{
m_CachedPreviewHeight = m_SplitView.fixedPane.resolvedStyle.height;
UpdatePreviewHeight(m_PreviewMinHeight);
}
else
{
UpdatePreviewHeight(m_CachedPreviewHeight);
}
}
void UpdatePreviewHeight(float newHeight)
{
var draglineAnchor = m_SplitView.Q("unity-dragline-anchor");
m_SplitView.fixedPane.style.height = newHeight;
m_SplitView.fixedPaneDimension = newHeight;
draglineAnchor.style.top = m_SplitView.resolvedStyle.height - newHeight;
}
internal void OpenPreviewWindow()
{
m_PreviewWindow = BuilderInspectorPreviewWindow.ShowWindow();
m_SplitView.CollapseChild(1);
}
public void ReloadPreviewWindow(BuilderInspectorPreviewWindow window)
{
m_PreviewWindow = window;
m_SplitView.CollapseChild(1);
}
private void RegisterDraglineInteraction()
{
m_SplitView.Q("unity-dragline-anchor").RegisterCallback<PointerUpEvent>(OnDragLineChange);
m_SplitView.Q("unity-dragline").RegisterCallback<MouseUpEvent>(e =>
{
if (e.button == (int) MouseButton.RightMouse)
{
OpenPreviewWindow();
// stops the context menu from opening
e.StopImmediatePropagation();
}
});
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
UIToolkitProjectSettings.onEnableAdvancedTextChanged -= ChangeTextGeneratorStyleVisibility;
if (m_PreviewWindow != null)
{
previewWindow.Close();
}
}
void ChangeTextGeneratorStyleVisibility(bool show)
{
m_TextGeneratorStyle.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspector.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 32938
} | 475 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Toolbar = UnityEditor.UIElements.Toolbar;
using TreeViewItem = UnityEngine.UIElements.TreeViewItemData<Unity.UI.Builder.BuilderLibraryTreeItem>;
namespace Unity.UI.Builder
{
static class BuilderLibraryContent
{
class AssetModificationProcessor : IBuilderAssetModificationProcessor
{
readonly Action m_OnAssetChange;
public AssetModificationProcessor(Action onAssetChange)
{
m_OnAssetChange = onAssetChange;
}
public void OnAssetChange()
{
// AssetDatabase.FindAllAssets(filter) will return outdated assets if
// we refresh immediately.
// Note: This used to rely on Builder.ActiveWindow.rootVisualElement.schedule
// when not in batch mode to do the delay call but this caused problems with
// tests that waited on the LibraryContent to refresh based on asset changes
// before the any UI Builder window was open.
EditorApplication.delayCall += m_OnAssetChange.Invoke;
}
public AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
=> AssetMoveResult.DidNotMove;
public AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option)
=> AssetDeleteResult.DidNotDelete;
}
internal class AssetPostprocessor : IBuilderOneTimeAssetPostprocessor
{
readonly Action m_OnPostprocessAllAssets;
public AssetPostprocessor(Action onPostprocessAllAssets)
{
m_OnPostprocessAllAssets = onPostprocessAllAssets;
}
public void OnPostProcessAsset()
{
// AssetDatabase.FindAllAssets(filter) will return outdated assets if
// we refresh immediately.
// Note: This used to rely on Builder.ActiveWindow.rootVisualElement.schedule
// when not in batch mode to do the delay call but this caused problems with
// tests that waited on the LibraryContent to refresh based on asset changes
// before the any UI Builder window was open.
EditorApplication.delayCall += m_OnPostprocessAllAssets.Invoke;
}
}
static readonly Dictionary<Type, BuilderLibraryTreeItem> s_ControlsTypeCache = new Dictionary<Type, BuilderLibraryTreeItem>();
static readonly BuilderLibraryProjectScanner s_ProjectAssetsScanner = new BuilderLibraryProjectScanner();
static int s_ProjectUxmlPathsHash;
// Used to keep track of when the library content is being needlessly regenerated on Domain Reload.
internal static int libraryRegenerationTestCounter = 0;
public static event Action OnLibraryContentUpdated;
public static List<TreeViewItem> standardControlsTree { get; private set; }
public static List<TreeViewItem> standardControlsTreeNoEditor { get; private set; }
public static List<TreeViewItem> projectContentTree { get; private set; }
public static List<TreeViewItem> projectContentTreeNoPackages { get; private set; }
static HashSet<string> s_StandardEditorControls = new();
static HashSet<string> s_StandardControls = new();
static readonly int k_DefaultVisualElementFlexGrow = 1;
static readonly Color k_DefaultVisualElementBackgroundColor = new (0, 0, 0, 0);
static readonly AssetModificationProcessor s_AssetModificationProcessor = new AssetModificationProcessor(() =>
{
RegenerateLibraryContent();
});
static readonly AssetPostprocessor s_AssetPostProcessor = new AssetPostprocessor(() =>
{
RegenerateLibraryContent();
});
static BuilderLibraryContent()
{
BuilderAssetModificationProcessor.Register(s_AssetModificationProcessor);
BuilderAssetPostprocessor.Register(s_AssetPostProcessor);
}
public static bool IsEditorOnlyControl(string fullTypeName)
{
return s_StandardEditorControls.Contains(fullTypeName);
}
public static bool IsStandardControl(string fullTypeName)
{
return s_StandardControls.Contains(fullTypeName);
}
public static void RegenerateLibraryContent(bool mustRegisterProcessors = false)
{
if (mustRegisterProcessors && !BuilderAssetModificationProcessor.IsProcessorRegistered(s_AssetModificationProcessor))
BuilderAssetModificationProcessor.Register(s_AssetModificationProcessor);
if (mustRegisterProcessors && !BuilderAssetPostprocessor.IsOneTimeProcessorRegistered(s_AssetPostProcessor))
BuilderAssetPostprocessor.Register(s_AssetPostProcessor);
s_ProjectAssetsScanner.FindAssets();
var previousProjectUxmlPathsHash = s_ProjectUxmlPathsHash;
s_ProjectUxmlPathsHash = s_ProjectAssetsScanner.GetAllProjectUxmlFilePathsHash();
if (previousProjectUxmlPathsHash == s_ProjectUxmlPathsHash)
return;
if (standardControlsTree == null)
{
standardControlsTree = GenerateControlsItemsTree();
standardControlsTreeNoEditor = new List<TreeViewItem>();
foreach (var item in standardControlsTree)
{
var builderLibraryTreeItem = item.data;
if (!builderLibraryTreeItem.isEditorOnly)
{
standardControlsTreeNoEditor.Add(item);
}
}
UpdateControlsTypeCache(standardControlsTree, true);
}
GenerateProjectContentTrees();
UpdateControlsTypeCache(projectContentTree);
OnLibraryContentUpdated?.Invoke();
libraryRegenerationTestCounter++;
}
internal static void ResetProjectUxmlPathsHash()
{
s_ProjectUxmlPathsHash = default;
}
public static Texture2D GetTypeLibraryIcon(Type type)
{
if (s_ControlsTypeCache.TryGetValue(type, out var builderLibraryTreeItem))
return builderLibraryTreeItem.icon;
// Just in case to avoid infinity loop.
if (type != typeof(VisualElement))
return GetTypeLibraryIcon(typeof(VisualElement));
return null;
}
public static Texture2D GetTypeLibraryLargeIcon(Type type)
{
if (s_ControlsTypeCache.TryGetValue(type, out var builderLibraryTreeItem))
{
if (builderLibraryTreeItem.largeIcon != null)
return builderLibraryTreeItem.largeIcon;
return builderLibraryTreeItem.icon;
}
// Just in case to avoid infinity loop.
if (type != typeof(VisualElement))
return GetTypeLibraryIcon(typeof(VisualElement));
return null;
}
internal static BuilderLibraryTreeItem GetLibraryItemForType(Type type)
{
return s_ControlsTypeCache.TryGetValue(type, out var builderLibraryTreeItem)
? builderLibraryTreeItem
: null;
}
public static Texture2D GetTypeDarkSkinLibraryIcon(Type type)
{
if (s_ControlsTypeCache.TryGetValue(type, out var builderLibraryTreeItem))
return builderLibraryTreeItem.darkSkinIcon;
return null;
}
public static Texture2D GetUXMLAssetIcon(string uxmlAssetPath)
{
return GetUXMLAssetIcon(projectContentTree, uxmlAssetPath);
}
static Texture2D GetUXMLAssetIcon(IEnumerable<TreeViewItem> items, string uxmlAssetPath)
{
foreach (var item in items)
{
var builderLibraryTreeItem = item.data;
if (!string.IsNullOrEmpty(builderLibraryTreeItem.sourceAssetPath) && builderLibraryTreeItem.sourceAssetPath.Equals(uxmlAssetPath))
{
return builderLibraryTreeItem.icon;
}
if (item.hasChildren)
{
var icon = GetUXMLAssetIcon(item.children, uxmlAssetPath);
if (icon != null)
return icon;
}
}
return (Texture2D)EditorGUIUtility.IconContent("VisualTreeAsset Icon").image;
}
static void GenerateProjectContentTrees()
{
projectContentTree = new List<TreeViewItem>();
projectContentTreeNoPackages = new List<TreeViewItem>();
var fromProjectCategory = CreateItem(BuilderConstants.LibraryAssetsSectionHeaderName, null, null, null, isHeader: true);
s_ProjectAssetsScanner.ImportUxmlFromProject(fromProjectCategory, true);
projectContentTree.Add(fromProjectCategory);
var fromProjectCategoryNoPackages = CreateItem(BuilderConstants.LibraryAssetsSectionHeaderName, null, null, null, isHeader: true);
s_ProjectAssetsScanner.ImportUxmlFromProject(fromProjectCategoryNoPackages, false);
projectContentTreeNoPackages.Add(fromProjectCategoryNoPackages);
var customControlsCategory = CreateItem(BuilderConstants.LibraryCustomControlsSectionHeaderName, null, null, null, isHeader: true);
s_ProjectAssetsScanner.ImportUxmlSerializedDataFromSource(customControlsCategory);
s_ProjectAssetsScanner.ImportFactoriesFromSource(customControlsCategory);
if (customControlsCategory.hasChildren)
{
projectContentTree.Add(customControlsCategory);
projectContentTreeNoPackages.Add(customControlsCategory);
}
}
internal static TreeViewItemData<BuilderLibraryTreeItem> CreateItem(string name, string iconName, Type type, Func<VisualElement> makeVisualElementCallback,
Func<VisualTreeAsset, VisualElementAsset, VisualElement, VisualElementAsset> makeElementAssetCallback = null, List<TreeViewItemData<BuilderLibraryTreeItem>> children = null, VisualTreeAsset asset = null,
int id = default, bool isHeader = false, bool isEditorOnly = false)
{
var itemId = BuilderLibraryTreeItem.GetItemId(name, type, asset, id);
var data = new BuilderLibraryTreeItem(name, iconName, type, makeVisualElementCallback, makeElementAssetCallback, asset) { isHeader = isHeader, isEditorOnly = isEditorOnly };
return new TreeViewItemData<BuilderLibraryTreeItem>(itemId, data, children);
}
static List<TreeViewItem> GenerateControlsItemsTree()
{
s_StandardEditorControls.Clear();
s_StandardControls.Clear();
var containersItem = CreateItem(BuilderConstants.LibraryContainersSectionHeaderName, null, null, null, id: 1, isHeader:true);
var controlsTree = new List<TreeViewItem>();
IList<TreeViewItem> containersItemList = new List<TreeViewItem>
{
CreateItem("Visual Element", "VisualElement", typeof(VisualElement),
() => new VisualElement(),
(inVta, inParent, ve) =>
{
var vea = inVta.AddElement(inParent, ve);
const int visualElementStyled = (int)BuilderLibrary.DefaultVisualElementType.Styled;
if (EditorPrefs.GetInt(BuilderConstants.LibraryDefaultVisualElementType, visualElementStyled) == visualElementStyled)
{
BuilderStyleUtilities.SetInlineStyleValue(inVta, vea, ve, "flex-grow",
k_DefaultVisualElementFlexGrow);
}
return vea;
}),
CreateItem("Scroll View", "ScrollView", typeof(ScrollView), () => new ScrollView()),
CreateItem("List View", "ListView", typeof(ListView), () => new ListView()),
CreateItem("Tree View", "TreeView", typeof(TreeView), () => new TreeView()),
CreateItem("Multi-Column List View", "MultiColumnListView", typeof(MultiColumnListView), () => new MultiColumnListView()),
CreateItem("Multi-Column Tree View", "MultiColumnTreeView", typeof(MultiColumnTreeView), () => new MultiColumnTreeView()),
CreateItem("Group Box", nameof(GroupBox), typeof(GroupBox), () => new GroupBox()),
};
containersItem.AddChildren(containersItemList);
controlsTree.Add(containersItem);
var editorContainersItemList = CreateItem(BuilderConstants.LibraryEditorContainersSectionHeaderName, null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("IMGUI Container", nameof(IMGUIContainer), typeof(IMGUIContainer), () => new IMGUIContainer()),
}, id: 2, isEditorOnly: true, isHeader: true);
var controlsItem = CreateItem(BuilderConstants.LibraryControlsSectionHeaderName, null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("Label", nameof(Label), typeof(Label), () => new Label("Label")),
CreateItem("Button", nameof(Button), typeof(Button), () => new Button { text = "Button" }),
CreateItem("Toggle", nameof(Toggle), typeof(Toggle), () => new Toggle("Toggle")),
CreateItem("Toggle Button Group", nameof(ToggleButtonGroup), typeof(ToggleButtonGroup), () => new ToggleButtonGroup("Toggle Button Group")),
CreateItem("Scroller", nameof(Scroller), typeof(Scroller), () => new Scroller(0, 100, (v) => {}, SliderDirection.Horizontal) { value = 42 }),
CreateItem("Text Field", nameof(TextField), typeof(TextField), () => new TextField("Text Field") { placeholderText = "filler text", maskChar = TextInputBaseField<string>.kMaskCharDefault }),
CreateItem("Foldout", nameof(Foldout), typeof(Foldout), () => new Foldout { text = "Foldout" }),
CreateItem("Slider", nameof(Slider), typeof(Slider), () => new Slider("Slider", 0, 100) { value = 42 }),
CreateItem("Slider (Int)", nameof(SliderInt), typeof(SliderInt), () => new SliderInt("SliderInt", 0, 100) { value = 42 }),
CreateItem("Min-Max Slider", nameof(MinMaxSlider), typeof(MinMaxSlider), () => new MinMaxSlider("Min/Max Slider", 0, 20, -10, 40) { value = new Vector2(10, 12) }),
CreateItem("Progress Bar", nameof(ProgressBar), typeof(ProgressBar), () => new ProgressBar() { title = "my-progress", value = 22 }),
CreateItem("Dropdown", nameof(DropdownField), typeof(DropdownField), () => new DropdownField("Dropdown")),
CreateItem("Enum", nameof(EnumField), typeof(EnumField), () => new EnumField("Enum", TextAlignment.Center)),
CreateItem("Radio Button", nameof(RadioButton), typeof(RadioButton), () => new RadioButton("Radio Button")),
CreateItem("Radio Button Group", nameof(RadioButtonGroup), typeof(RadioButtonGroup), () => new RadioButtonGroup("Radio Button Group")),
CreateItem("Tab", nameof(Tab), typeof(Tab), () => new Tab("Tab")),
CreateItem("Tab View", nameof(TabView), typeof(TabView), () => new TabView()),
}, isHeader: true);
var numericFields = CreateItem("Numeric Fields", null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("Integer", nameof(IntegerField), typeof(IntegerField), () => new IntegerField("Integer Field") { value = 42 }),
CreateItem("Float", nameof(FloatField), typeof(FloatField), () => new FloatField("Float Field") { value = 42.2f }),
CreateItem("Long", nameof(LongField), typeof(LongField), () => new LongField("Long Field") { value = 42 }),
CreateItem("Double", nameof(DoubleField), typeof(DoubleField), () => new DoubleField("Double Field") { value = 42.2 }),
CreateItem("Hash128", nameof(Hash128Field), typeof(Hash128Field), () => new Hash128Field("Hash128 Field") { value = Hash128.Compute("42") }),
CreateItem("Vector2", nameof(Vector2Field), typeof(Vector2Field), () => new Vector2Field("Vec2 Field")),
CreateItem("Vector3", nameof(Vector3Field), typeof(Vector3Field), () => new Vector3Field("Vec3 Field")),
CreateItem("Vector4", nameof(Vector4Field), typeof(Vector4Field), () => new Vector4Field("Vec4 Field")),
CreateItem("Rect", nameof(RectField), typeof(RectField), () => new RectField("Rect")),
CreateItem("Bounds", nameof(BoundsField), typeof(BoundsField), () => new BoundsField("Bounds")),
CreateItem("Integer (Unsigned)", nameof(UnsignedIntegerField), typeof(UnsignedIntegerField), () => new UnsignedIntegerField("Unsigned Integer Field") { value = 42 }),
CreateItem("Long (Unsigned)", nameof(UnsignedLongField), typeof(UnsignedLongField), () => new UnsignedLongField("Unsigned Long Field") { value = 42 }),
CreateItem("Vector2 (Int)", nameof(Vector2IntField), typeof(Vector2IntField), () => new Vector2IntField("Vector2Int")),
CreateItem("Vector3 (Int)", nameof(Vector3IntField), typeof(Vector3IntField), () => new Vector3IntField("Vector3Int")),
CreateItem("Rect (Int)", nameof(RectIntField), typeof(RectIntField), () => new RectIntField("RectInt")),
CreateItem("Bounds (Int)", nameof(BoundsIntField), typeof(BoundsIntField), () => new BoundsIntField("BoundsInt")),
}, isHeader: true);
var valueFields = CreateItem("Value Fields", null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("Color", nameof(ColorField), typeof(ColorField), () => new ColorField("Color") { value = Color.cyan }),
CreateItem("Curve", nameof(CurveField), typeof(CurveField), () => new CurveField("Curve")
{
value = new AnimationCurve(new Keyframe(0, 0), new Keyframe(5, 8), new Keyframe(10, 4))
}),
CreateItem("Gradient", nameof(GradientField), typeof(GradientField), () => new GradientField("Gradient")
{
value = new Gradient()
{
colorKeys = new[]
{
new GradientColorKey(Color.red, 0),
new GradientColorKey(Color.blue, 10),
new GradientColorKey(Color.green, 20)
}
}
})
}, isEditorOnly: true, isHeader: true);
var choiceFields = CreateItem("Choice Fields", null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
// No UXML support for PopupField.
//new LibraryTreeItem("Popup", () => new PopupField<string>("Normal Field", choices, 0)),
CreateItem("Tag", nameof(TagField), typeof(TagField), () => new TagField("Tag", "Player")),
CreateItem("Mask", nameof(MaskField), typeof(MaskField), () => new MaskField("Mask")),
CreateItem("Layer", nameof(LayerField), typeof(LayerField), () => new LayerField("Layer")),
CreateItem("Layer Mask", nameof(LayerMaskField), typeof(LayerMaskField), () => new LayerMaskField("LayerMask")),
CreateItem("Enum Flags", nameof(EnumFlagsField), typeof(EnumFlagsField), () => new EnumFlagsField("EnumFlags", UsageHints.DynamicTransform))
}, isEditorOnly: true, isHeader: true);
var toolbar = CreateItem("Toolbar", null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("Toolbar", nameof(Toolbar), typeof(Toolbar), () => new Toolbar()),
CreateItem("Toolbar Menu", nameof(ToolbarMenu), typeof(ToolbarMenu), () => new ToolbarMenu()),
CreateItem("Toolbar Button", nameof(ToolbarButton), typeof(ToolbarButton), () => new ToolbarButton { text = "Button" }),
CreateItem("Toolbar Spacer", nameof(ToolbarSpacer), typeof(ToolbarSpacer), () => new ToolbarSpacer()),
CreateItem("Toolbar Toggle", nameof(ToolbarToggle), typeof(ToolbarToggle), () => new ToolbarToggle { label = "Toggle" }),
CreateItem("Toolbar Breadcrumbs", nameof(ToolbarBreadcrumbs), typeof(ToolbarBreadcrumbs), () => new ToolbarBreadcrumbs()),
CreateItem("Toolbar Search Field", nameof(ToolbarSearchField), typeof(ToolbarSearchField), () => new ToolbarSearchField()),
CreateItem("Toolbar Popup Search Field", nameof(ToolbarPopupSearchField), typeof(ToolbarPopupSearchField), () => new ToolbarPopupSearchField()),
}, isEditorOnly: true, isHeader: true);
var inspectors = CreateItem("Inspectors", null, null, null, null, new List<TreeViewItemData<BuilderLibraryTreeItem>>
{
CreateItem("Object Field", nameof(ObjectField), typeof(ObjectField), () => new ObjectField("Object Field")),
CreateItem("Property Field", nameof(PropertyField), typeof(PropertyField), () => new PropertyField())
}, isEditorOnly: true, isHeader: true);
controlsTree.Add(editorContainersItemList);
controlsTree.Add(controlsItem);
controlsTree.Add(numericFields);
controlsTree.Add(valueFields);
controlsTree.Add(choiceFields);
controlsTree.Add(toolbar);
controlsTree.Add(inspectors);
foreach (var categoryData in controlsTree)
{
foreach (var itemData in categoryData.children)
{
if (categoryData.data.isEditorOnly)
{
s_StandardEditorControls.Add(itemData.data.type.FullName);
}
s_StandardControls.Add(itemData.data.type.FullName);
}
}
return controlsTree;
}
static void UpdateControlsTypeCache(IEnumerable<TreeViewItem> items, bool overrideExisting = false)
{
foreach (var item in items)
{
var builderLibraryTreeItem = item.data;
if (builderLibraryTreeItem.type != null)
{
if (!s_StandardControls.Contains(builderLibraryTreeItem.type.FullName) || overrideExisting)
s_ControlsTypeCache[builderLibraryTreeItem.type] = builderLibraryTreeItem;
}
if (item.hasChildren)
UpdateControlsTypeCache(item.children, overrideExisting);
}
}
internal static void UnregisterProcessors()
{
BuilderAssetModificationProcessor.Unregister(s_AssetModificationProcessor);
BuilderAssetPostprocessor.Unregister(s_AssetPostProcessor);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryContent.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryContent.cs",
"repo_id": "UnityCsReference",
"token_count": 9954
} | 476 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Unity.UI.Builder
{
internal abstract class BuilderCodePreview : BuilderPaneContent
{
static readonly string s_UssClassName = "unity-builder-code-preview";
static readonly string s_CodeScrollViewClassName = "unity-builder-code__scroll-view";
static readonly string s_CodeContainerClassName = "unity-builder-code__container";
static readonly string s_CodeName = "unity-builder-code__code";
static readonly string s_CodeClassName = "unity-builder-code__code";
static readonly string s_CodeLineNumbersClassName = "unity-builder-code__code-line-numbers";
static readonly string s_CodeTextClassName = "unity-builder-code__code-text";
static readonly string s_CodeInputClassName = "unity-builder-code__input";
static readonly string s_CodeCodeOuterContainerClassName = "unity-builder-code__code_outer_container";
static readonly string s_CodeCodeContainerClassName = "unity-builder-code__code_container";
static readonly string s_CodeOpenSourceFileClassName = "unity-builder-code__open-source-file-button";
static readonly string s_TruncatedPreviewTextMessage = BuilderConstants.EllipsisText + $"\n({BuilderConstants.CodePreviewTruncatedTextMessage})";
ScrollView m_ScrollView;
VisualElement m_Container;
VisualElement m_CodeContainer;
VisualElement m_CodeOuterContainer;
TextField m_Code;
Label m_LineNumbers;
bool m_NeedsRefreshOnResize;
private Button m_OpenTargetAssetSourceButton;
ScriptableObject m_TargetAsset;
BuilderPaneWindow m_PaneWindow;
public BuilderCodePreview(BuilderPaneWindow paneWindow)
{
m_PaneWindow = paneWindow;
m_ScrollView = new ScrollView(ScrollViewMode.VerticalAndHorizontal);
m_ScrollView.AddToClassList(s_CodeScrollViewClassName);
m_ScrollView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
Add(m_ScrollView);
AddToClassList(s_UssClassName);
m_Container = new VisualElement();
m_Container.AddToClassList(s_CodeContainerClassName);
m_LineNumbers = new Label();
m_LineNumbers.RemoveFromClassList(TextField.ussClassName);
m_LineNumbers.AddToClassList(s_CodeClassName);
m_LineNumbers.AddToClassList(s_CodeLineNumbersClassName);
m_LineNumbers.AddToClassList(s_CodeInputClassName);
m_Code = new TextField(TextField.kMaxLengthNone, true, false, char.MinValue);
m_Code.textSelection.isSelectable = true;
m_Code.isReadOnly = true;
m_Code.name = s_CodeName;
m_Code.RemoveFromClassList(TextField.ussClassName);
m_Code.AddToClassList(s_CodeClassName);
m_Code.AddToClassList(s_CodeTextClassName);
m_Code.AddToClassList(disabledUssClassName);
var codeInput = m_Code.Q(className: TextField.inputUssClassName);
codeInput.AddToClassList(s_CodeInputClassName);
m_CodeOuterContainer = new VisualElement();
m_CodeOuterContainer.AddToClassList(s_CodeCodeOuterContainerClassName);
m_Container.Add(m_CodeOuterContainer);
m_CodeContainer = new VisualElement();
m_CodeContainer.AddToClassList(s_CodeCodeContainerClassName);
m_CodeOuterContainer.Add(m_CodeContainer);
m_CodeContainer.Add(m_LineNumbers);
m_CodeContainer.Add(m_Code);
m_ScrollView.Add(m_Container);
// Make sure the Hierarchy View gets focus when the pane gets focused.
primaryFocusable = m_Code;
// Make sure no key events get through to the code field.
m_Code.RegisterCallback<KeyDownEvent>(BlockEvent, TrickleDown.TrickleDown);
m_Code.RegisterCallback<KeyUpEvent>(BlockEvent, TrickleDown.TrickleDown);
SetText(string.Empty);
}
protected override void OnAttachToPanelDefaultAction()
{
base.OnAttachToPanelDefaultAction();
if (m_OpenTargetAssetSourceButton == null)
{
m_OpenTargetAssetSourceButton = new Button(OnOpenSourceFileButtonClick);
m_OpenTargetAssetSourceButton.AddToClassList(s_CodeOpenSourceFileClassName);
pane.toolbar.Add(m_OpenTargetAssetSourceButton);
}
RefreshPreviewIfVisible();
}
void OnGeometryChanged(GeometryChangedEvent evt)
{
if (!m_NeedsRefreshOnResize)
return;
RefreshPreview();
m_NeedsRefreshOnResize = false;
}
protected void RefreshPreviewIfVisible()
{
RefreshHeader();
if (m_ScrollView.contentViewport.resolvedStyle.height <= 0 ||
m_ScrollView.contentViewport.resolvedStyle.width <= 0)
{
m_NeedsRefreshOnResize = true;
return;
}
RefreshPreview();
}
protected abstract void RefreshPreview();
protected abstract void RefreshHeader();
protected abstract string previewAssetExtension { get; }
string targetAssetPath
{
get
{
if (m_TargetAsset == null)
return string.Empty;
return AssetDatabase.GetAssetPath(m_TargetAsset);
}
}
private bool isTargetAssetAvailableOnDisk => !string.IsNullOrEmpty(targetAssetPath);
protected bool hasDocument => m_PaneWindow != null && m_PaneWindow.document != null;
protected BuilderDocument document => m_PaneWindow.document;
void OnOpenSourceFileButtonClick()
{
if(!isTargetAssetAvailableOnDisk)
return;
AssetDatabase.OpenAsset(m_TargetAsset, BuilderConstants.OpenInIDELineNumber);
}
void BlockEvent(KeyUpEvent evt)
{
// Allow copy/paste.
if (evt.keyCode == KeyCode.C)
return;
evt.StopImmediatePropagation();
}
void BlockEvent(KeyDownEvent evt)
{
// Allow copy/paste.
if (evt.keyCode == KeyCode.C)
return;
evt.StopImmediatePropagation();
}
protected void SetTargetAsset(ScriptableObject targetAsset, bool hasUnsavedChanges)
{
if (pane == null)
return;
m_TargetAsset = targetAsset;
pane.subTitle = BuilderAssetUtilities.GetAssetName(targetAsset, previewAssetExtension, hasUnsavedChanges);
m_OpenTargetAssetSourceButton.style.display = isTargetAssetAvailableOnDisk ? DisplayStyle.Flex : DisplayStyle.None;
}
internal static string GetClampedText(string text, out bool truncated)
{
var clippedCharIndex = 0;
var printableCharCount = 0;
truncated = false;
var maxTextPrintableCharCount = BuilderConstants.MaxTextPrintableCharCount;
foreach (var c in text)
{
if (!char.IsControl(c))
printableCharCount++;
if (printableCharCount > maxTextPrintableCharCount)
{
truncated = true;
break;
}
clippedCharIndex++;
}
if (truncated)
{
return text.Substring(0, clippedCharIndex);
}
return text;
}
protected void SetText(string text)
{
if (string.IsNullOrEmpty(text))
{
m_LineNumbers.text = string.Empty;
m_Code.value = string.Empty;
return;
}
var clampedText = GetClampedText(text, out var truncated);
if (truncated)
clampedText = clampedText.Substring(0, clampedText.Length - s_TruncatedPreviewTextMessage.Length);
var lineCount = clampedText.Count(x => x == '\n') + 1;
string lineNumbersText = "";
for (int i = 1; i <= lineCount; ++i)
{
if (!string.IsNullOrEmpty(lineNumbersText))
lineNumbersText += "\n";
lineNumbersText += i.ToString();
}
m_LineNumbers.text = lineNumbersText;
if (truncated)
clampedText += s_TruncatedPreviewTextMessage;
m_Code.value = clampedText;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderCodePreview.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderCodePreview.cs",
"repo_id": "UnityCsReference",
"token_count": 4014
} | 477 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderElementContextMenu
{
readonly BuilderPaneWindow m_PaneWindow;
readonly BuilderSelection m_Selection;
bool m_WeStartedTheDrag;
List<ManipulatorActivationFilter> activators { get; }
ManipulatorActivationFilter m_CurrentActivator;
protected BuilderDocument document => m_PaneWindow.document;
protected BuilderPaneWindow paneWindow => m_PaneWindow;
protected BuilderSelection selection => m_Selection;
public BuilderElementContextMenu(BuilderPaneWindow paneWindow, BuilderSelection selection)
{
m_PaneWindow = paneWindow;
m_Selection = selection;
m_WeStartedTheDrag = false;
activators = new List<ManipulatorActivationFilter>();
activators.Add(new ManipulatorActivationFilter { button = MouseButton.RightMouse });
if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer)
{
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Control });
}
}
public void RegisterCallbacksOnTarget(VisualElement target)
{
target.RegisterCallback<MouseDownEvent>(OnMouseDown);
target.RegisterCallback<MouseUpEvent>(OnMouseUp, TrickleDown.TrickleDown);
target.RegisterCallback<ContextualMenuPopulateEvent>(a => BuildElementContextualMenu(a, target));
target.RegisterCallback<DetachFromPanelEvent>(UnregisterCallbacksFromTarget);
}
void UnregisterCallbacksFromTarget(DetachFromPanelEvent evt)
{
var target = evt.elementTarget;
target.UnregisterCallback<MouseDownEvent>(OnMouseDown);
target.UnregisterCallback<MouseUpEvent>(OnMouseUp, TrickleDown.TrickleDown);
target.UnregisterCallback<ContextualMenuPopulateEvent>(a => BuildElementContextualMenu(a, target));
target.UnregisterCallback<DetachFromPanelEvent>(UnregisterCallbacksFromTarget);
}
void OnMouseDown(MouseDownEvent evt)
{
if (!CanStartManipulation(evt))
return;
var target = evt.currentTarget as VisualElement;
target.CaptureMouse();
m_WeStartedTheDrag = true;
evt.StopPropagation();
}
void OnMouseUp(MouseUpEvent evt)
{
var target = evt.currentTarget as VisualElement;
if (!target.HasMouseCapture() || !m_WeStartedTheDrag)
return;
if (!CanStopManipulation(evt))
return;
DisplayContextMenu(evt, target);
target.ReleaseMouse();
m_WeStartedTheDrag = false;
evt.StopPropagation();
}
public void DisplayContextMenu(EventBase triggerEvent, VisualElement target)
{
if (target.elementPanel?.contextualMenuManager != null)
{
target.elementPanel.contextualMenuManager.DisplayMenu(triggerEvent, target);
triggerEvent.StopPropagation();
}
}
bool CanStartManipulation(IMouseEvent evt)
{
foreach (var activator in activators)
{
if (activator.Matches(evt))
{
m_CurrentActivator = activator;
return true;
}
}
return false;
}
bool CanStopManipulation(IMouseEvent evt)
{
if (evt == null)
{
return false;
}
return ((MouseButton)evt.button == m_CurrentActivator.button);
}
void ReselectIfNecessary(VisualElement documentElement)
{
if (!m_Selection.selection.Contains(documentElement))
m_Selection.Select(null, documentElement);
}
public virtual void BuildElementContextualMenu(ContextualMenuPopulateEvent evt, VisualElement target)
{
var documentElement = target.GetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName) as VisualElement;
var linkedOpenVTA = documentElement?.GetProperty(BuilderConstants.ElementLinkedVisualTreeAssetVEPropertyName) as VisualTreeAsset;
var isValidTarget = documentElement != null && !linkedOpenVTA &&
(documentElement.IsPartOfActiveVisualTreeAsset(paneWindow.document) ||
documentElement.GetStyleComplexSelector() != null);
var isValidCopyTarget = documentElement != null && !linkedOpenVTA &&
(documentElement.IsPartOfCurrentDocument() ||
documentElement.GetStyleComplexSelector() != null);
evt.StopImmediatePropagation();
evt.menu.AppendAction(
"Copy",
a =>
{
ReselectIfNecessary(documentElement);
if (isValidCopyTarget)
m_PaneWindow.commandHandler.CopySelection();
},
isValidCopyTarget
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
evt.menu.AppendAction(
"Paste",
a =>
{
m_PaneWindow.commandHandler.Paste();
},
BuilderEditorUtility.CopyBufferMatchesTarget(target)
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
evt.menu.AppendSeparator();
evt.menu.AppendAction(
"Rename",
a =>
{
ReselectIfNecessary(documentElement);
m_PaneWindow.commandHandler.RenameSelection();
},
isValidTarget
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
evt.menu.AppendAction(
"Duplicate",
a =>
{
ReselectIfNecessary(documentElement);
m_PaneWindow.commandHandler.DuplicateSelection();
},
isValidTarget
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
evt.menu.AppendAction(
"Delete",
a =>
{
ReselectIfNecessary(documentElement);
m_PaneWindow.commandHandler.DeleteSelection();
},
isValidTarget
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
var linkedInstancedVTA = documentElement?.GetProperty(BuilderConstants.ElementLinkedInstancedVisualTreeAssetVEPropertyName) as VisualTreeAsset;
var linkedVEA = documentElement?.GetVisualElementAsset();
var linkedTemplateVEA = linkedVEA as TemplateAsset;
var activeOpenUXML = document.activeOpenUXMLFile;
var isLinkedOpenVTAActiveVTA = linkedOpenVTA == activeOpenUXML.visualTreeAsset;
var isLinkedInstancedVTAActiveVTA = linkedInstancedVTA == activeOpenUXML.visualTreeAsset;
var isLinkedVEADirectChild = activeOpenUXML.visualTreeAsset.templateAssets.Contains(linkedTemplateVEA);
var showOpenInBuilder = linkedInstancedVTA != null;
var showReturnToParentAction = isLinkedOpenVTAActiveVTA && activeOpenUXML.isChildSubDocument;
var showOpenInIsolationAction = isLinkedVEADirectChild;
var showOpenInPlaceAction = showOpenInIsolationAction;
var showSiblingOpenActions = !isLinkedOpenVTAActiveVTA && isLinkedInstancedVTAActiveVTA;
var showUnpackAction = isLinkedVEADirectChild;
var showCreateTemplateAction = activeOpenUXML.visualTreeAsset.visualElementAssets.Contains(linkedVEA);
if (showOpenInBuilder || showReturnToParentAction || showOpenInIsolationAction || showOpenInPlaceAction || showSiblingOpenActions)
evt.menu.AppendSeparator();
if (showOpenInBuilder)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyOpenInBuilder,
action => { paneWindow.LoadDocument(linkedInstancedVTA); });
}
if (showReturnToParentAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyReturnToParentDocument +
BuilderConstants.SingleSpace + "(" + activeOpenUXML.openSubDocumentParent.visualTreeAsset.name + ")",
action => document.GoToSubdocument(documentElement, paneWindow, activeOpenUXML.openSubDocumentParent));
}
if (showOpenInIsolationAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyPaneOpenSubDocument,
action => BuilderHierarchyUtilities.OpenAsSubDocument(paneWindow, linkedInstancedVTA));
}
if (showOpenInPlaceAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyPaneOpenSubDocumentInPlace,
action => BuilderHierarchyUtilities.OpenAsSubDocument(paneWindow, linkedInstancedVTA, linkedTemplateVEA));
}
if (showSiblingOpenActions)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyPaneOpenSubDocument,
action =>
{
document.GoToSubdocument(documentElement, paneWindow, activeOpenUXML.openSubDocumentParent);
BuilderHierarchyUtilities.OpenAsSubDocument(paneWindow, linkedInstancedVTA);
});
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyPaneOpenSubDocumentInPlace,
action =>
{
document.GoToSubdocument(documentElement, paneWindow, activeOpenUXML.openSubDocumentParent);
BuilderHierarchyUtilities.OpenAsSubDocument(paneWindow, linkedInstancedVTA, linkedTemplateVEA);
});
}
if (isLinkedVEADirectChild)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchySelectTemplate,
action =>
{
Selection.activeObject = linkedInstancedVTA;
EditorGUIUtility.PingObject(linkedInstancedVTA.GetInstanceID());
});
}
evt.menu.AppendSeparator();
if (showUnpackAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyUnpackTemplate,
action =>
{
m_PaneWindow.commandHandler.UnpackTemplateContainer(documentElement);
});
}
if (showUnpackAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyUnpackCompletely,
action =>
{
m_PaneWindow.commandHandler.UnpackTemplateContainer(documentElement, true);
});
}
if (showCreateTemplateAction)
{
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyCreateTemplate,
action =>
{
m_PaneWindow.commandHandler.CreateTemplateFromHierarchy(documentElement, activeOpenUXML.visualTreeAsset);
});
}
evt.menu.AppendSeparator();
evt.menu.AppendAction(
BuilderConstants.ExplorerHierarchyAddSelector,
a =>
{
m_PaneWindow.commandHandler.CreateTargetedSelector(documentElement);
},
documentElement != null
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderElementContextMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderElementContextMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 6205
} | 478 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal sealed class BuilderUxmlStringAttributeFieldFactory : IBuilderUxmlAttributeFieldFactory
{
public bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
return attribute is UxmlStringAttributeDescription;
}
static bool CheckNullOrEmptyTextChange(ChangeEvent<string> evt)
{
// Ignore change if both texts are null or empty
return !(string.IsNullOrEmpty(evt.newValue) && string.IsNullOrEmpty(evt.previousValue));
}
public VisualElement CreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
var fieldLabel = BuilderNameUtilities.ConvertDashToHuman(attribute.name);
if (attribute.name.Equals("value") && attributeOwner is EnumField enumField)
{
var uiField = new EnumField(fieldLabel);
if (null != enumField.value)
uiField.Init(enumField.value, enumField.includeObsoleteValues);
else
uiField.SetValueWithoutNotify(null);
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement)
return;
InvokeValueChangedCallback(uiField, attribute, evt.newValue, ValueToUxml.Convert(uiField.value), onValueChange);
});
return uiField;
}
if (attribute.name.Equals("value") && attributeOwner is EnumFlagsField enumFlagsField)
{
var uiField = new EnumFlagsField(fieldLabel);
if (null != enumFlagsField.value)
uiField.Init(enumFlagsField.value, enumFlagsField.includeObsoleteValues);
else
uiField.SetValueWithoutNotify(null);
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement)
return;
InvokeValueChangedCallback(uiField, attribute, evt.newValue, ValueToUxml.Convert(uiField.value), onValueChange);
});
return uiField;
}
if (attribute.name.Equals("value") && attributeOwner is TagField)
{
var uiField = new TagField(fieldLabel);
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement)
return;
InvokeValueChangedCallback(uiField, attribute, evt.newValue, ValueToUxml.Convert(uiField.value), onValueChange);
});
return uiField;
}
if (attribute.name.Equals("value") && attributeOwner is TextField { multiline: true })
{
var uiField = new TextField(fieldLabel);
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement || !CheckNullOrEmptyTextChange(evt))
return;
InvokeValueChangedCallback(uiField, attribute, evt.newValue, ValueToUxml.Convert(uiField.value), onValueChange);
});
uiField.multiline = true;
uiField.AddToClassList(BuilderConstants.InspectorMultiLineTextFieldClassName);
return uiField;
}
else
{
var uiField = new TextField(fieldLabel);
if (attribute.name.Equals("name") || attribute.name.Equals("view-data-key"))
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement || !CheckNullOrEmptyTextChange(evt))
return;
OnValidatedAttributeValueChange(evt, BuilderNameUtilities.attributeRegex,
BuilderConstants.AttributeValidationSpacialCharacters, attribute, onValueChange);
});
else if (attributeOwner is VisualElement && attribute.name.Equals("binding-path") || attribute.name.Equals("data-source-path"))
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement || !CheckNullOrEmptyTextChange(evt))
return;
OnValidatedAttributeValueChange(evt, BuilderNameUtilities.bindingPathAttributeRegex,
BuilderConstants.BindingPathAttributeValidationSpacialCharacters, attribute, onValueChange);
});
else
{
uiField.RegisterValueChangedCallback(evt =>
{
if (evt.target == uiField.labelElement || !CheckNullOrEmptyTextChange(evt))
return;
InvokeValueChangedCallback(uiField, attribute, evt.newValue, ValueToUxml.Convert(uiField.value), onValueChange);
});
}
if (attribute.name.Equals("text") || attribute.name.Equals("label"))
{
uiField.multiline = true;
uiField.AddToClassList(BuilderConstants.InspectorMultiLineTextFieldClassName);
}
return uiField;
}
}
public void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value)
{
if (field is EnumField enumField)
{
var enumFieldAttributeOwner = attributeOwner as EnumField;
var hasValue = enumFieldAttributeOwner.value != null;
if (hasValue)
enumField.Init(enumFieldAttributeOwner.value, enumFieldAttributeOwner.includeObsoleteValues);
else
enumField.SetValueWithoutNotify(null);
enumField.SetEnabled(hasValue);
}
else if (field is TagField tagField)
{
var tagFieldAttributeOwner = attributeOwner as TagField;
tagField.SetValueWithoutNotify(tagFieldAttributeOwner.value);
}
else if (field is EnumFlagsField enumFlagsField)
{
var enumFlagsFieldAttributeOwner = attributeOwner as EnumFlagsField;
var hasValue = enumFlagsFieldAttributeOwner.value != null;
if (hasValue)
enumFlagsField.Init(enumFlagsFieldAttributeOwner.value, enumFlagsFieldAttributeOwner.includeObsoleteValues);
else
enumFlagsField.SetValueWithoutNotify(null);
enumFlagsField.SetEnabled(hasValue);
}
else
{
var strValue = GetAttributeStringValue(value);
if (field is TextField textField)
{
textField.SetValueWithoutNotify(strValue);
}
}
}
public void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
var a = attribute as UxmlStringAttributeDescription;
if (field is EnumField enumField)
{
if (null == enumField.type)
enumField.SetValueWithoutNotify(null);
else
enumField.SetValueWithoutNotify((Enum)Enum.ToObject(enumField.type, 0));
}
else if (field is TagField tagField)
{
tagField.SetValueWithoutNotify(a.defaultValue);
}
else if (field is EnumFlagsField enumFlagsField)
{
if (null == enumFlagsField.type)
enumFlagsField.SetValueWithoutNotify(null);
else
enumFlagsField.SetValueWithoutNotify((Enum)Enum.ToObject(enumFlagsField.type, 0));
}
else
{
(field as TextField).SetValueWithoutNotify(a.defaultValue);
}
}
public void ResetFieldValueToInline(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
var a = attribute as UxmlStringAttributeDescription;
var value = a.GetValueFromBag(attributeUxmlOwner, CreationContext.Default);
SetFieldValue(field, attributeOwner, uxmlDocument, attributeUxmlOwner, attribute, value);
}
private static string GetAttributeStringValue(object attributeValue)
{
string value;
if (attributeValue is Enum @enum)
value = @enum.ToString();
else if (attributeValue is IEnumerable<string> list)
{
value = string.Join(",", list.ToArray());
}
else
{
value = attributeValue?.ToString();
}
return value;
}
private static void OnValidatedAttributeValueChange(ChangeEvent<string> evt, Regex regex, string message, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
// Prevent ChangeEvent caused by changing the label of the field to be propagated
if (string.IsNullOrEmpty(evt.newValue) && string.IsNullOrEmpty(evt.previousValue))
{
evt.StopPropagation();
return;
}
var field = evt.elementTarget as TextField;
if (!string.IsNullOrEmpty(evt.newValue) && !regex.IsMatch(evt.newValue))
{
Builder.ShowWarning(string.Format(message, field.label));
field.SetValueWithoutNotify(evt.previousValue);
evt.StopPropagation();
return;
}
onValueChange?.Invoke(field, attribute, evt.newValue, ValueToUxml.Convert(evt.newValue));
}
private static void InvokeValueChangedCallback(VisualElement field, UxmlAttributeDescription attribute, object value, string uxmlValue, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
onValueChange?.Invoke(field, attribute, value, uxmlValue);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlStringAttributeField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlStringAttributeField.cs",
"repo_id": "UnityCsReference",
"token_count": 5297
} | 479 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
partial class CategoryDropdownField : BaseField<string>
{
[Serializable]
public new class UxmlSerializedData : BaseField<string>.UxmlSerializedData
{
public override object CreateInstance() => new CategoryDropdownField();
}
// Base selectors coming from BasePopupField
const string k_UssClassNameBasePopupField = "unity-base-popup-field";
const string k_TextUssClassNameBasePopupField = k_UssClassNameBasePopupField + "__text";
const string k_ArrowUssClassNameBasePopupField = k_UssClassNameBasePopupField + "__arrow";
const string k_LabelUssClassNameBasePopupField = k_UssClassNameBasePopupField + "__label";
const string k_InputUssClassNameBasePopupField = k_UssClassNameBasePopupField + "__input";
// Base selectors coming from PopupField
const string k_UssClassNamePopupField = "unity-popup-field";
const string k_LabelUssClassNamePopupField = k_UssClassNamePopupField + "__label";
const string k_InputUssClassNamePopupField = k_UssClassNamePopupField + "__input";
readonly TextElement m_Input;
internal Func<CategoryDropdownContent> getContent;
public CategoryDropdownField() : this(null)
{
}
public CategoryDropdownField(string label) : base(label, null)
{
AddToClassList(k_UssClassNameBasePopupField);
labelElement.AddToClassList(k_LabelUssClassNameBasePopupField);
m_Input = new PopupTextElement
{
pickingMode = PickingMode.Ignore
};
m_Input.AddToClassList(k_TextUssClassNameBasePopupField);
visualInput.AddToClassList(k_InputUssClassNameBasePopupField);
visualInput.Add(m_Input);
var dropdownArrow = new VisualElement();
dropdownArrow.AddToClassList(k_ArrowUssClassNameBasePopupField);
dropdownArrow.pickingMode = PickingMode.Ignore;
visualInput.Add(dropdownArrow);
AddToClassList(k_UssClassNamePopupField);
labelElement.AddToClassList(k_LabelUssClassNamePopupField);
visualInput.AddToClassList(k_InputUssClassNamePopupField);
}
class PopupTextElement : TextElement
{
protected internal override Vector2 DoMeasure(float desiredWidth, MeasureMode widthMode,
float desiredHeight,
MeasureMode heightMode)
{
var textToMeasure = text;
if (string.IsNullOrEmpty(textToMeasure))
{
textToMeasure = " ";
}
return MeasureTextSize(textToMeasure, desiredWidth, widthMode, desiredHeight, heightMode);
}
}
[EventInterest(typeof(KeyDownEvent), typeof(MouseDownEvent))]
protected override void HandleEventBubbleUp(EventBase evt)
{
base.HandleEventBubbleUp(evt);
if (evt == null)
return;
var showPopupMenu = false;
if (evt is KeyDownEvent kde)
{
if (kde.keyCode == KeyCode.Space ||
kde.keyCode == KeyCode.KeypadEnter ||
kde.keyCode == KeyCode.Return)
showPopupMenu = true;
}
else if (evt is MouseDownEvent {button: (int) MouseButton.LeftMouse} mde)
{
if (visualInput.ContainsPoint(visualInput.WorldToLocal(mde.mousePosition)))
showPopupMenu = true;
}
if (!showPopupMenu)
return;
ShowMenu();
evt.StopPropagation();
}
void ShowMenu()
{
var windowContent = new WindowContent();
windowContent.onSelectionChanged += selected => value = selected;
var content = getContent?.Invoke() ?? default;
windowContent.Show(visualInput.worldBound, value, content.Items);
}
public override void SetValueWithoutNotify(string newValue)
{
base.SetValueWithoutNotify(newValue);
((INotifyValueChanged<string>) m_Input).SetValueWithoutNotify(value);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownField.cs",
"repo_id": "UnityCsReference",
"token_count": 2047
} | 480 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
class LibraryFoldout : PersistedFoldout
{
[Serializable]
public new class UxmlSerializedData : PersistedFoldout.UxmlSerializedData
{
public override object CreateInstance() => new LibraryFoldout();
}
public const string TagLabelName = "tag";
const string k_TagPillClassName = "builder-library-foldout__tag-pill";
Label m_Tag;
public LibraryFoldout()
{
// Load styles.
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/LibraryFoldout/LibraryFoldout.uss"));
styleSheets.Add(EditorGUIUtility.isProSkin
? BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/LibraryFoldout/LibraryFoldoutDark.uss")
: BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/LibraryFoldout/LibraryFoldoutLight.uss"));
}
// Should be defined after Toggle text.
// Known Issue: If label text will be defined before Toggle text, it could be placed before Toggle default label.
public string tag
{
get => m_Tag?.text;
set
{
if (!string.IsNullOrEmpty(value))
{
// Lazy allocation of label if needed...
if (m_Tag == null)
{
m_Tag = new Label
{
name = TagLabelName,
pickingMode = PickingMode.Ignore
};
m_Tag.AddToClassList(k_TagPillClassName);
toggle.visualInput.Add(m_Tag);
}
m_Tag.text = value;
}
else if (m_Tag != null)
{
Remove(m_Tag);
m_Tag = null;
}
}
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/LibraryFoldout/LibraryFoldout.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/LibraryFoldout/LibraryFoldout.cs",
"repo_id": "UnityCsReference",
"token_count": 1142
} | 481 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor.UIElements.Debugger;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
using UnityEngine.Pool;
namespace Unity.UI.Builder
{
/// <summary>
/// Represents the different ways the value of a field can be bound.
/// </summary>
internal enum FieldValueBindingInfoType
{
/// <summary>
/// No binding.
/// </summary>
None,
/// <summary>
/// Set to a constant value.
/// </summary>
Constant,
/// <summary>
/// Bound to a USS variable
/// </summary>
USSVariable,
/// <summary>
/// Bound to data binding
/// </summary>
Binding
}
/// <summary>
/// Provides extension methods for <see cref="FieldValueBindingInfoType"/> enum.
/// </summary>
internal static class FieldValueBindingInfoTypeExtensions
{
/// <summary>
/// Returns the text displayed in the inspector for a <see cref="FieldValueBindingInfoType"/> value.
/// </summary>
/// <param name="type">The target type</param>
/// <returns></returns>
public static string ToDisplayString(this FieldValueBindingInfoType type)
{
return type switch
{
FieldValueBindingInfoType.USSVariable => BuilderConstants.FieldValueBindingInfoTypeEnumUSSVariableDisplayString,
_ => type.ToString()
};
}
}
/// <summary>
/// Provides information about how the value of a field is bound.
/// </summary>
internal struct FieldValueBindingInfo
{
/// <summary>
/// Data that provides details about the value binding. It is a <see cref="VariableInfo"/> object if the value is bound to a variable.
/// </summary>
object m_Data;
/// <summary>
/// The type of value binding.
/// </summary>
public FieldValueBindingInfoType type { get; }
/// <summary>
/// Provides details about the USS variable to which the field is bound.
/// </summary>
public VariableInfo variable
{
get
{
if (m_Data is VariableInfo varInfo)
return varInfo;
return default;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">The type of value binding</param>
public FieldValueBindingInfo(in FieldValueBindingInfoType type)
{
this.type = type;
m_Data = default;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">The type of value binding</param>
/// <param name="variable">The details about the variable to which the field is bound</param>
public FieldValueBindingInfo(in FieldValueBindingInfoType type, in VariableInfo variable)
{
this.type = type;
this.m_Data = variable;
}
}
/// <summary>
/// Represents the different ways the value of a field has been resolved.
/// </summary>
internal enum FieldValueSourceInfoType
{
/// <summary>
/// Indicates that the value of the underlying VisualElement property is set as inline in its source UXML file.
/// </summary>
Inline,
/// <summary>
/// Indicates that the value of the underlying Selector property is set in the selector's definition in its
/// source StyleSheet file.
/// </summary>
LocalUSSSelector,
/// <summary>
/// Indicates that the value of the underlying VisualElement property is resolved from one of its matching
/// USS selectors.
/// </summary>
MatchingUSSSelector,
/// <summary>
/// Indicates that the value of the underlying VisualElement property is inherited from one of its parents
/// (ancestors).
/// </summary>
Inherited,
/// <summary>
/// Indicates that the value of the underlying property is default.
/// </summary>
Default,
/// <summary>
/// Indicates that the value of the underlying VisualElement property is resolved from a Binding
/// </summary>
ResolvedBinding,
/// <summary>
/// Indicates that the value of the underlying VisualElement property is resolved from a Binding but the binding
/// is unresolved
/// </summary>
UnresolvedBinding,
/// <summary>
/// Indicates that the value of the underlying VisualElement property is resolved from a Binding but the binding
/// is unhandled
/// </summary>
UnhandledBinding
}
/// <summary>
/// Provides extension methods for <see cref="FieldValueSourceInfoType"/> enum.
/// </summary>
internal static class FieldValueSourceInfoTypeExtensions
{
/// <summary>
/// Indicates whether the source is the currently selected USS selector or a USS selector matching the currently selected VisualElement.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsFromUSSSelector(this FieldValueSourceInfoType type) => type is FieldValueSourceInfoType.LocalUSSSelector
or FieldValueSourceInfoType.MatchingUSSSelector;
/// <summary>
/// Returns the text displayed in the inspector for a <see cref="FieldValueSourceInfoType"/> value.
/// </summary>
/// <param name="type">The target type</param>
/// <returns></returns>
public static string ToDisplayString(this FieldValueSourceInfoType type)
{
return type switch
{
FieldValueSourceInfoType.Inherited => BuilderConstants.FieldValueSourceInfoTypeEnumInheritedDisplayString,
FieldValueSourceInfoType.MatchingUSSSelector => BuilderConstants.FieldValueSourceInfoTypeEnumUSSSelectorDisplayString,
FieldValueSourceInfoType.LocalUSSSelector => BuilderConstants.FieldValueSourceInfoTypeEnumLocalUSSSelectorDisplayString,
FieldValueSourceInfoType.ResolvedBinding => BuilderConstants.FieldStatusIndicatorResolvedBindingTooltip,
FieldValueSourceInfoType.UnresolvedBinding => BuilderConstants.FieldStatusIndicatorUnresolvedBindingTooltip,
FieldValueSourceInfoType.UnhandledBinding => BuilderConstants.FieldStatusIndicatorUnhandledBindingTooltip,
_ => type.ToString()
};
}
}
/// <summary>
/// Provides information about how the value of a field has been resolved.
/// </summary>
internal struct FieldValueSourceInfo
{
/// <summary>
/// Data that provides details about the value source. It is a <see cref="MatchedRule"/> object if the value is from a USS selector.
/// </summary>
object m_Data;
/// <summary>
/// The type of value source.
/// </summary>
public FieldValueSourceInfoType type { get; }
/// <summary>
/// Provides details about the matching USS rule from which the value is resolved source.
/// </summary>
public MatchedRule matchedRule
{
get
{
if (m_Data is MatchedRule rule)
return rule;
return default;
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of value source.</param>
public FieldValueSourceInfo(FieldValueSourceInfoType type)
{
this.type = type;
this.m_Data = default;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">The type of value source.</param>
/// <param name="rule">The data that provides about the value source.</param>
public FieldValueSourceInfo(FieldValueSourceInfoType type, in MatchedRule rule)
{
this.type = type;
m_Data = rule;
}
}
/// <summary>
/// The type of the underlying property.
/// </summary>
internal enum FieldValueInfoType
{
/// <summary>
/// None
/// </summary>
None,
/// <summary>
/// UXML attribute.
/// </summary>
UXMLAttribute,
/// <summary>
/// USS property.
/// </summary>
USSProperty
}
/// <summary>
/// Provides extension methods for <see cref="FieldValueInfoType"/> enum.
/// </summary>
internal static class FieldValueInfoTypeExtensions
{
/// <summary>
/// Returns the text displayed in the inspector for a <see cref="FieldValueInfoType"/> value.
/// </summary>
/// <param name="type">The target type</param>
/// <returns></returns>
public static string ToDisplayString(this FieldValueInfoType type)
{
return type switch
{
FieldValueInfoType.USSProperty => BuilderConstants.FieldValueInfoTypeEnumUSSPropertyDisplayString,
FieldValueInfoType.UXMLAttribute => BuilderConstants.FieldValueInfoTypeEnumUXMLAttributeDisplayString,
_ => null
};
}
}
/// <summary>
/// Provides information about how the value of a UXML attribute or USS property is bound and resolved.
/// </summary>
internal struct FieldValueInfo
{
/// <summary>
/// Type of the underlying property.
/// </summary>
public FieldValueInfoType type;
/// <summary>
/// The name of the underlying property.
/// </summary>
public string name;
/// <summary>
/// Information about how the value is bound.
/// </summary>
public FieldValueBindingInfo valueBinding;
/// <summary>
/// Information about how the value has been resolved.
/// </summary>
public FieldValueSourceInfo valueSource;
/// <summary>
/// Gets the value binding and value source information of the specified field in the specified inspector.
/// </summary>
/// <param name="inspector">The inspector</param>
/// <param name="field">The field</param>
/// <param name="property">The overridden USS property</param>
/// <returns></returns>
public static FieldValueInfo Get(BuilderInspector inspector, VisualElement field, StyleProperty property)
{
return FieldValueInfoGetter.Get(inspector, field, property);
}
}
/// <summary>
/// Helper class to get the value binding and value source information of a given field.
/// </summary>
static class FieldValueInfoGetter
{
/// <summary>
/// Gets the value binding and value source information of the specified field in the specified inspector.
/// </summary>
/// <param name="inspector">The inspector</param>
/// <param name="field">The field</param>
/// <param name="property">The overridden USS property</param>
/// <returns></returns>
public static FieldValueInfo Get(BuilderInspector inspector, VisualElement field, StyleProperty property)
{
// If the field is not contained in the Builder inspector then ignore
if (inspector == null)
return default;
var uxmlAttr = field.GetLinkedAttributeDescription();
FieldValueBindingInfo valueBinding = default;
FieldValueSourceInfo valueSource = default;
var propName = "";
// If the field is a UXML attribute of a visual element then...
if (uxmlAttr != null)
{
propName = uxmlAttr.name;
valueBinding = new FieldValueBindingInfo(FieldValueBindingInfoType.Constant);
bool isInline =
BuilderInspectorAttributes.IsAttributeOverriden(inspector.currentVisualElement, uxmlAttr);
valueSource = new FieldValueSourceInfo(isInline ? FieldValueSourceInfoType.Inline : FieldValueSourceInfoType.Default);
}
// .. otherwise, if the field is a USS property then...
else
{
// 1. Determine the value binding type
// Look for the USS variable bound to the field
var selectionIsSelector = BuilderSharedStyles.IsSelectorElement(inspector.currentVisualElement);
var varHandler = StyleVariableUtilities.GetOrCreateVarHandler(field as BindableElement);
var varName = VariableEditingHandler.GetBoundVariableName(varHandler);
if (!string.IsNullOrEmpty(varName))
{
var varInfo = StyleVariableUtilities.FindVariable(inspector.currentVisualElement, varName, inspector.document.fileSettings.editorExtensionMode);
// If the variable cannot be resolved then at least set the name
if (!varInfo.IsValid())
varInfo = new VariableInfo(varName);
valueBinding = new FieldValueBindingInfo(FieldValueBindingInfoType.USSVariable, varInfo);
}
else
{
valueBinding = new FieldValueBindingInfo(FieldValueBindingInfoType.Constant);
}
// 2. Determine the value source
// Check whether there is a style property specified
propName = field.GetProperty(BuilderConstants.InspectorStylePropertyNameVEPropertyName) as string;
// If the style property is set in the file then...
if (property != null)
{
if (selectionIsSelector)
{
var selectorMatchRecord =
new SelectorMatchRecord(inspector.currentVisualElement.GetClosestStyleSheet(), 0)
{
complexSelector = inspector.currentVisualElement.GetStyleComplexSelector()
};
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.LocalUSSSelector, new MatchedRule(selectorMatchRecord));
}
else
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.Inline);
}
}
// otherwise ...
else
{
var sourceIsSet = false;
if (!selectionIsSelector)
{
// Check if the value is from a matching selector
var matchedRules = inspector.matchingSelectors.matchedRulesExtractor.selectedElementRules;
for (var i = matchedRules.Count - 1; i >= 0; --i)
{
var matchedRule = matchedRules.ElementAt(i);
var matchRecord = matchedRule.matchRecord;
var ruleProperty = matchRecord.sheet.FindProperty(matchRecord.complexSelector, propName);
// If propName has a short hand then try to find the matching selector using the shorthand
if (ruleProperty == null)
{
var id = StylePropertyName.StylePropertyIdFromString(propName);
var shorthandId = id.GetShorthandProperty();
if (shorthandId != StylePropertyId.Unknown)
{
if (StylePropertyUtil.stylePropertyIdToPropertyName.TryGetValue(shorthandId, out var shorthandName))
{
ruleProperty = matchRecord.sheet.FindProperty(matchRecord.complexSelector, shorthandName);
}
}
}
if (ruleProperty != null)
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.MatchingUSSSelector,
matchedRule);
sourceIsSet = true;
break;
}
}
// If the value does not come from a matching stylesheet selector then check if it comes from inheritance
if (!sourceIsSet)
{
var result = DictionaryPool<StylePropertyId, int>.Get();
StyleDebug.FindSpecifiedStyles(inspector.currentVisualElement.computedStyle,
inspector.matchingSelectors.matchedRulesExtractor.matchRecords, result);
StylePropertyId id;
if (StylePropertyUtil.propertyNameToStylePropertyId.TryGetValue(propName, out id))
{
if (result.TryGetValue(id, out var spec))
{
if (spec == StyleDebug.InheritedSpecificity)
{
valueBinding = default;
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.Inherited);
sourceIsSet = true;
}
}
}
DictionaryPool<StylePropertyId, int>.Release(result);
}
}
// If no source is set so far then we assume the source is default
if (!sourceIsSet)
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.Default);
}
}
}
var bindingProperty = BuilderInspectorUtilities.GetBindingProperty(field);
if (inspector.bindingsCache != null
&& inspector.bindingsCache.TryGetCachedData(inspector.currentVisualElement, bindingProperty, out var cacheData))
{
valueBinding = new FieldValueBindingInfo(FieldValueBindingInfoType.Binding);
if (cacheData.isStatusResultValid && cacheData.status == BindingStatus.Success)
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.ResolvedBinding);
}
// Check if Status Result valid for unhandled
else if (cacheData.isStatusResultValid && cacheData.status == BindingStatus.Pending)
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.UnhandledBinding);
}
else
{
valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.UnresolvedBinding);
}
}
return new FieldValueInfo()
{
type = uxmlAttr != null ? FieldValueInfoType.UXMLAttribute : FieldValueInfoType.USSProperty,
name = propName,
valueBinding = valueBinding,
valueSource = valueSource
};
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldValueInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldValueInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 9038
} | 482 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.UIElements.Debugger;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace Unity.UI.Builder
{
static class StyleVariableUtilities
{
private static Dictionary<string, string> s_EmptyEditorVarDescriptions = new Dictionary<string, string>();
private static Dictionary<string, string> s_EditorVarDescriptions;
[Serializable]
public class DescriptionInfo
{
public string name;
public string description;
}
[Serializable]
public class DescriptionInfoList
{
public List<DescriptionInfo> infos;
}
static void InitEditorVarDescriptions()
{
if (s_EditorVarDescriptions != null)
return;
var textAsset = EditorGUIUtility.Load("UIPackageResources/StyleSheets/Default/Variables/Public/descriptions.json") as TextAsset;
if (textAsset)
{
s_EditorVarDescriptions = new Dictionary<string, string>();
var descriptionsContent = textAsset.text;
var descriptionInfoList = JsonUtility.FromJson<DescriptionInfoList>(descriptionsContent);
foreach (var descriptionInfo in descriptionInfoList.infos)
{
s_EditorVarDescriptions[descriptionInfo.name] = descriptionInfo.description;
}
}
else
{
Builder.ShowWarning(BuilderConstants.VariableDescriptionsCouldNotBeLoadedMessage);
}
}
static public Dictionary<string, string> editorVariableDescriptions
{
get
{
InitEditorVarDescriptions();
return s_EditorVarDescriptions ?? s_EmptyEditorVarDescriptions;
}
}
public static IEnumerable<VariableInfo> GetAllAvailableVariables(VisualElement currentVisualElement, StyleValueType[] compatibleTypes, bool editorExtensionMode)
{
return currentVisualElement.variableContext.variables
.Where(variable =>
{
if (variable.name == BuilderConstants.SelectedStyleRulePropertyName)
return false;
if (variable.name.StartsWith(BuilderConstants.USSVariableUIBuilderPrefix))
return false;
if (!editorExtensionMode && variable.sheet.IsUnityEditorStyleSheet())
return false;
var valueHandle = variable.handles[0];
var valueType = valueHandle.valueType;
if (valueType == StyleValueType.Enum)
{
var colorName = variable.sheet.ReadAsString(valueHandle);
if (StyleSheetColor.TryGetColor(colorName.ToLower(), out var color))
valueType = StyleValueType.Color;
}
if (valueType == StyleValueType.Function)
{
var function = (StyleValueFunction)valueHandle.valueIndex;
if (function == StyleValueFunction.Var)
{
// resolve to find the true value type
var varName = variable.sheet.ReadVariable(variable.handles[2]);
var varInfo = FindVariable(currentVisualElement, varName, editorExtensionMode);
if (varInfo.styleVariable.handles != null)
valueType = varInfo.styleVariable.handles[0].valueType;
}
}
return (compatibleTypes == null || compatibleTypes.Contains(valueType)) && !variable.name.StartsWith("--unity-theme");
})
.Distinct()
.Select(variable =>
{
string descr = null;
if (variable.sheet.IsUnityEditorStyleSheet())
{
editorVariableDescriptions.TryGetValue(variable.name, out descr);
}
return new VariableInfo(variable, descr);
});
}
public static VariableEditingHandler GetOrCreateVarHandler(BindableElement field)
{
if (field == null)
return null;
VariableEditingHandler handler = GetVarHandler(field);
if (handler == null)
{
handler = new VariableEditingHandler(field);
field.SetProperty(BuilderConstants.ElementLinkedVariableHandlerVEPropertyName, handler);
}
return handler;
}
public static VariableEditingHandler GetVarHandler(BindableElement field)
{
if (field == null)
return null;
return field?.GetProperty(BuilderConstants.ElementLinkedVariableHandlerVEPropertyName) as VariableEditingHandler;
}
public static VariableInfo FindVariable(VisualElement currentVisualElement, string variableName, bool editorExtensionMode)
{
var variables = currentVisualElement.variableContext.variables;
for (int i = variables.Count - 1; i >= 0; --i)
{
var variable = variables[i];
if (!editorExtensionMode && variable.sheet.isDefaultStyleSheet)
continue;
if (variables[i].name == variableName)
{
string descr = null;
if (variable.sheet.isDefaultStyleSheet)
{
editorVariableDescriptions.TryGetValue(variableName, out descr);
}
return new VariableInfo(variable, descr);
}
}
return default;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleVariableUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleVariableUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 3018
} | 483 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
namespace Unity.UI.Builder
{
internal static class StyleSheetExtensions
{
public static bool IsUnityEditorStyleSheet(this StyleSheet styleSheet)
{
if ((UIElementsEditorUtility.IsCommonDarkStyleSheetLoaded() && styleSheet == UIElementsEditorUtility.GetCommonDarkStyleSheet())
|| (UIElementsEditorUtility.IsCommonLightStyleSheetLoaded() && styleSheet == UIElementsEditorUtility.GetCommonLightStyleSheet()))
return true;
return false;
}
public static StyleSheet DeepCopy(this StyleSheet styleSheet)
{
if (styleSheet == null)
return null;
var newStyleSheet = StyleSheetUtilities.CreateInstance();
styleSheet.DeepOverwrite(newStyleSheet);
return newStyleSheet;
}
public static void DeepOverwrite(this StyleSheet styleSheet, StyleSheet other)
{
if (other == null)
return;
var json = JsonUtility.ToJson(styleSheet);
JsonUtility.FromJsonOverwrite(json, other);
other.FixRuleReferences();
other.name = styleSheet.name;
}
public static void FixRuleReferences(this StyleSheet styleSheet)
{
// This is very important. When moving selectors around via drag/drop in
// the StyleSheets pane, the nextInTable references can become corrupt.
// Most corruption is corrected in the StyleSheet.SetupReferences() call
// made below. However, the ends of each chain are not set in
// SetupReferences() because it assumes always starting with a clean
// StyleSheets. Therefore, you can have these end selectors point to an
// existing selector and style resolution entering a infinite loop.
//
// Case 1274584
if (styleSheet.complexSelectors != null)
foreach (var selector in styleSheet.complexSelectors)
selector.nextInTable = null;
// Force call to StyleSheet.SetupReferences().
styleSheet.rules = styleSheet.rules;
}
internal static List<string> GetSelectorStrings(this StyleSheet styleSheet)
{
var list = new List<string>();
foreach (var complexSelector in styleSheet.complexSelectors)
{
var str = StyleSheetToUss.ToUssSelector(complexSelector);
list.Add(str);
}
return list;
}
internal static string GenerateUSS(this StyleSheet styleSheet)
{
string result = null;
try
{
result = StyleSheetToUss.ToUssString(styleSheet);
}
catch (Exception ex)
{
if (!styleSheet.name.Contains(BuilderConstants.InvalidUXMLOrUSSAssetNameSuffix))
{
var message = string.Format(BuilderConstants.InvalidUSSDialogMessage, styleSheet.name);
BuilderDialogsUtility.DisplayDialog(BuilderConstants.InvalidUSSDialogTitle, message);
styleSheet.name = styleSheet.name + BuilderConstants.InvalidUXMLOrUSSAssetNameSuffix;
}
else
{
var name = styleSheet.name.Replace(BuilderConstants.InvalidUXMLOrUSSAssetNameSuffix, string.Empty);
var message = string.Format(BuilderConstants.InvalidUSSDialogMessage, name);
Builder.ShowWarning(message);
}
Debug.LogError(ex.Message + "\n" + ex.StackTrace);
}
return result;
}
internal static StyleComplexSelector FindSelector(this StyleSheet styleSheet, string selectorStr)
{
// Remove extra whitespace.
var selectorSplit = selectorStr.Split(' ');
selectorStr = String.Join(" ", selectorSplit);
foreach (var complexSelector in styleSheet.complexSelectors)
{
var str = StyleSheetToUss.ToUssSelector(complexSelector);
if (str == selectorStr)
return complexSelector;
}
return null;
}
internal static void RemoveSelector(
this StyleSheet styleSheet, StyleComplexSelector selector, string undoMessage = null)
{
if (selector == null)
return;
// Undo/Redo
if (string.IsNullOrEmpty(undoMessage))
undoMessage = "Delete UI Style Selector";
Undo.RegisterCompleteObjectUndo(styleSheet, undoMessage);
var selectorList = styleSheet.complexSelectors.ToList();
selectorList.Remove(selector);
styleSheet.complexSelectors = selectorList.ToArray();
}
internal static void RemoveSelector(
this StyleSheet styleSheet, string selectorStr, string undoMessage = null)
{
var selector = styleSheet.FindSelector(selectorStr);
if (selector == null)
return;
RemoveSelector(styleSheet, selector, undoMessage);
}
public static int AddRule(this StyleSheet styleSheet)
{
var rule = new StyleRule { line = -1 };
rule.properties = new StyleProperty[0];
// Add rule to StyleSheet.
var rulesList = styleSheet.rules.ToList();
var index = rulesList.Count;
rulesList.Add(rule);
styleSheet.rules = rulesList.ToArray();
return index;
}
public static StyleRule GetRule(this StyleSheet styleSheet, int index)
{
if (styleSheet.rules.Count() <= index)
return null;
return styleSheet.rules[index];
}
public static StyleComplexSelector AddSelector(
this StyleSheet styleSheet, string complexSelectorStr, string undoMessage = null)
{
// Undo/Redo
if (string.IsNullOrEmpty(undoMessage))
undoMessage = "New UI Style Selector";
Undo.RegisterCompleteObjectUndo(styleSheet, undoMessage);
if (!SelectorUtility.TryCreateSelector(complexSelectorStr, out var complexSelector))
return null;
// Add rule to StyleSheet.
var rulesList = styleSheet.rules.ToList();
rulesList.Add(complexSelector.rule);
styleSheet.rules = rulesList.ToArray();
complexSelector.ruleIndex = styleSheet.rules.Length - 1;
// Add complex selector to list in stylesheet.
var complexSelectorsList = styleSheet.complexSelectors.ToList();
complexSelectorsList.Add(complexSelector);
styleSheet.complexSelectors = complexSelectorsList.ToArray();
styleSheet.UpdateContentHash();
return complexSelector;
}
public static void TransferRulePropertiesToSelector(this StyleSheet toStyleSheet, StyleComplexSelector toSelector, StyleSheet fromStyleSheet, StyleRule fromRule)
{
foreach (var property in fromRule.properties)
{
var newProperty = toStyleSheet.AddProperty(toSelector, property.name);
foreach (var value in property.values)
{
switch (value.valueType)
{
case StyleValueType.Float: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetFloat(value)); break;
case StyleValueType.Dimension: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetDimension(value)); break;
case StyleValueType.Enum: toStyleSheet.AddValueAsEnum(newProperty, fromStyleSheet.GetEnum(value)); break;
case StyleValueType.String: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetString(value)); break;
case StyleValueType.Color: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetColor(value)); break;
case StyleValueType.AssetReference: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetAsset(value)); break;
case StyleValueType.ResourcePath: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetAsset(value)); break;
case StyleValueType.Variable: toStyleSheet.AddVariable(newProperty, fromStyleSheet.GetString(value)); break;
case StyleValueType.Keyword: toStyleSheet.AddValue(newProperty, fromStyleSheet.GetKeyword(value)); break;
}
}
}
foreach (var property in fromRule.properties)
{
fromStyleSheet.RemoveProperty(fromRule, property);
}
}
public static bool IsSelected(this StyleSheet styleSheet)
{
var selector = styleSheet.FindSelector(BuilderConstants.SelectedStyleSheetSelectorName);
return selector != null;
}
static void SwallowStyleRule(
StyleSheet toStyleSheet, StyleComplexSelector toSelector,
StyleSheet fromStyleSheet, StyleComplexSelector fromSelector)
{
SwallowStyleRule(toStyleSheet, toSelector.rule, fromStyleSheet, fromSelector.rule);
}
public static void SwallowStyleRule(
StyleSheet toStyleSheet, StyleRule toRule,
StyleSheet fromStyleSheet, StyleRule fromRule)
{
// Add property values to sheet.
foreach (var fromProperty in fromRule.properties)
{
var toProperty = toStyleSheet.AddProperty(toRule, fromProperty.name);
for (int i = 0; i < fromProperty.values.Length; ++i)
{
var fromValueHandle = fromProperty.values[i];
var toValueIndex = toStyleSheet.SwallowStyleValue(fromStyleSheet, fromValueHandle);
toStyleSheet.AddValueHandle(toProperty, toValueIndex, fromValueHandle.valueType);
}
}
}
public static StyleComplexSelector Swallow(this StyleSheet toStyleSheet, StyleSheet fromStyleSheet, StyleComplexSelector fromSelector)
{
var toSelector = toStyleSheet.AddSelector(StyleSheetToUss.ToUssSelector(fromSelector));
if (toSelector == null)
return null;
SwallowStyleRule(toStyleSheet, toSelector, fromStyleSheet, fromSelector);
return toSelector;
}
public static void Swallow(this StyleSheet toStyleSheet, StyleSheet fromStyleSheet)
{
foreach (var fromSelector in fromStyleSheet.complexSelectors)
{
Swallow(toStyleSheet, fromStyleSheet, fromSelector);
}
toStyleSheet.contentHash = fromStyleSheet.contentHash;
}
public static void ClearUndo(this StyleSheet styleSheet)
{
if (styleSheet == null)
return;
Undo.ClearUndo(styleSheet);
}
public static void Destroy(this StyleSheet styleSheet)
{
if (styleSheet == null)
return;
ScriptableObject.DestroyImmediate(styleSheet);
}
public static void UpdateContentHash(this StyleSheet styleSheet)
{
// Set the contentHash to 0 if the style sheet is empty
if (styleSheet.rules == null || styleSheet.rules.Length == 0)
styleSheet.contentHash = 0;
else
// Use a random value instead of computing the real contentHash.
// This is faster (for large content) and safe enough to avoid conflicts with other style sheets
// since contentHash is used internally as a optimized way to compare style sheets.
// However, note that the real contentHash will still be computed on import.
styleSheet.contentHash = UnityEngine.Random.Range(1, int.MaxValue);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetExtensions.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 5635
} | 484 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using static Unity.UI.Builder.BuilderUxmlAttributesView;
namespace Unity.UI.Builder
{
internal static class VisualElementExtensions
{
static readonly List<string> s_SkippedAttributeNames = new List<string>()
{
"content-container",
"class",
"style",
"template",
};
public static bool HasLinkedAttributeDescription(this VisualElement ve)
{
return ve.GetProperty(BuilderConstants.InspectorLinkedAttributeDescriptionVEPropertyName) is UxmlAttributeDescription;
}
public static UxmlAttributeDescription GetLinkedAttributeDescription(this VisualElement ve)
{
// UxmlSerializedFields have a UxmlSerializedDataAttributeField as the parent
var dataField = ve as UxmlSerializedDataAttributeField ?? ve.GetFirstAncestorOfType<UxmlSerializedDataAttributeField>();
return (dataField ?? ve).GetProperty(BuilderConstants.InspectorLinkedAttributeDescriptionVEPropertyName) as UxmlAttributeDescription;
}
public static void SetLinkedAttributeDescription(this VisualElement ve, UxmlAttributeDescription attribute)
{
ve.SetProperty(BuilderConstants.InspectorLinkedAttributeDescriptionVEPropertyName, attribute);
}
public static void SetInspectorStylePropertyName(this VisualElement ve, string styleName)
{
ve.SetProperty(BuilderConstants.InspectorStylePropertyNameVEPropertyName, styleName);
var cSharpStyleName = BuilderNameUtilities.ConvertStyleUssNameToCSharpName(styleName);
ve.SetProperty(BuilderConstants.InspectorStyleBindingPropertyNameVEPropertyName, $"style.{cSharpStyleName}");
}
public static BuilderStyleRow GetContainingRow(this VisualElement ve)
{
return ve.GetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName) as BuilderStyleRow;
}
public static void SetContainingRow(this VisualElement ve, BuilderStyleRow row)
{
ve.SetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName, row);
}
public static List<VisualElement> GetLinkedFieldElements(this BuilderStyleRow row)
{
return row.GetProperty(BuilderConstants.InspectorLinkedFieldsForStyleRowVEPropertyName) as List<VisualElement>;
}
public static void AddLinkedFieldElement(this BuilderStyleRow row, VisualElement fieldElement)
{
var list = row.GetProperty(BuilderConstants.InspectorLinkedFieldsForStyleRowVEPropertyName) as List<VisualElement>;
list ??= new List<VisualElement>();
list.Add(fieldElement);
row.SetProperty(BuilderConstants.InspectorLinkedFieldsForStyleRowVEPropertyName, list);
}
public static List<UxmlAttributeDescription> GetAttributeDescriptions(this VisualElement ve, bool useTraits = false)
{
var uxmlQualifiedName = GetUxmlQualifiedName(ve);
var desc = UxmlSerializedDataRegistry.GetDescription(uxmlQualifiedName);
if (desc != null && !useTraits)
return desc.serializedAttributes.ToList<UxmlAttributeDescription>();
var attributeList = new List<UxmlAttributeDescription>();
if (!VisualElementFactoryRegistry.TryGetValue(uxmlQualifiedName, out var factoryList))
return attributeList;
#pragma warning disable CS0618 // Type or member is obsolete
foreach (IUxmlFactory f in factoryList)
{
// For user created types, they may return null for uxmlAttributeDescription, so we need to check in order not to crash.
if (f.uxmlAttributesDescription != null)
{
foreach (var a in f.uxmlAttributesDescription)
{
// For user created types, they may `yield return null` which would create an array with a null, so we need
// to check in order not to crash.
if (a == null || s_SkippedAttributeNames.Contains(a.name))
continue;
attributeList.Add(a);
}
}
}
#pragma warning restore CS0618 // Type or member is obsolete
return attributeList;
}
static string GetUxmlQualifiedName(VisualElement ve)
{
var uxmlQualifiedName = ve.GetType().FullName;
// Try get uxmlQualifiedName from the UxmlFactory.
var factoryTypeName = $"{ve.GetType().FullName}+UxmlFactory";
var asm = ve.GetType().Assembly;
var factoryType = asm.GetType(factoryTypeName);
if (factoryType != null)
{
#pragma warning disable CS0618 // Type or member is obsolete
var factoryTypeInstance = (IUxmlFactory)Activator.CreateInstance(factoryType);
if (factoryTypeInstance != null)
{
uxmlQualifiedName = factoryTypeInstance.uxmlQualifiedName;
}
#pragma warning restore CS0618 // Type or member is obsolete
}
return uxmlQualifiedName;
}
public static Dictionary<string, string> GetOverriddenAttributes(this VisualElement ve)
{
var attributeList = ve.GetAttributeDescriptions();
var overriddenAttributes = new Dictionary<string, string>();
foreach (var attribute in attributeList)
{
if (attribute?.name == null)
continue;
if (attribute is UxmlSerializedAttributeDescription attributeDescription)
{
// UxmlSerializedData
if (attributeDescription.TryGetValueFromObject(ve, out var value) &&
UxmlAttributeComparison.ObjectEquals(value, attributeDescription.defaultValue))
{
continue;
}
string valueAsString = null;
if (value != null)
UxmlAttributeConverter.TryConvertToString(value, ve.visualTreeAssetSource, out valueAsString);
overriddenAttributes.Add(attribute.name, valueAsString);
}
else
{
// UxmlTraits
var veType = ve.GetType();
var camel = BuilderNameUtilities.ConvertDashToCamel(attribute.name);
var fieldInfo = veType.GetProperty(camel);
if (fieldInfo != null)
{
var veValueAbstract = fieldInfo.GetValue(ve, null);
if (veValueAbstract == null)
continue;
var veValueStr = veValueAbstract.ToString();
if (veValueStr == "False")
veValueStr = "false";
else if (veValueStr == "True")
veValueStr = "true";
// The result of Type.ToString is not enough for us to find the correct Type.
if (veValueAbstract is Type type)
veValueStr = $"{type.FullName}, {type.Assembly.GetName().Name}";
if (veValueAbstract is IEnumerable<string> enumerable)
veValueStr = string.Join(",", enumerable);
var attributeValueStr = attribute.defaultValueAsString;
if (veValueStr == attributeValueStr)
continue;
overriddenAttributes.Add(attribute.name, veValueStr);
}
// This is a special patch that allows to search for built-in elements' attribute specifically
// without needing to add to the public API.
// Allowing to search for internal/private properties in all cases could lead to unforeseen issues.
else if (ve is EnumField or EnumFlagsField && camel == "type")
{
fieldInfo = veType.GetProperty(camel, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var veValueAbstract = fieldInfo.GetValue(ve, null);
if (!(veValueAbstract is Type type))
continue;
var veValueStr = $"{type.FullName}, {type.Assembly.GetName().Name}";
var attributeValueStr = attribute.defaultValueAsString;
if (veValueStr == attributeValueStr)
continue;
overriddenAttributes.Add(attribute.name, veValueStr);
}
}
}
return overriddenAttributes;
}
public static VisualTreeAsset GetVisualTreeAsset(this VisualElement element)
{
if (element == null)
return null;
var obj = element.GetProperty(BuilderConstants.ElementLinkedVisualTreeAssetVEPropertyName);
if (obj == null)
return null;
var vta = obj as VisualTreeAsset;
return vta;
}
public static VisualElementAsset GetVisualElementAsset(this VisualElement element)
{
if (element == null)
return null;
var obj = element.GetProperty(BuilderConstants.ElementLinkedVisualElementAssetVEPropertyName);
if (obj == null)
return null;
var vea = obj as VisualElementAsset;
return vea;
}
public static void SetVisualElementAsset(this VisualElement element, VisualElementAsset vea)
{
element.SetProperty(BuilderConstants.ElementLinkedVisualElementAssetVEPropertyName, vea);
}
public static StyleSheet GetStyleSheet(this VisualElement element)
{
if (element == null)
return null;
var obj = element.GetProperty(BuilderConstants.ElementLinkedStyleSheetVEPropertyName);
if (obj == null)
return null;
var styleSheet = obj as StyleSheet;
return styleSheet;
}
public static StyleComplexSelector GetStyleComplexSelector(this VisualElement element)
{
if (element == null)
return null;
var obj = element.GetProperty(BuilderConstants.ElementLinkedStyleSelectorVEPropertyName);
if (obj == null)
return null;
var scs = obj as StyleComplexSelector;
return scs;
}
public static bool IsLinkedToAsset(this VisualElement element)
{
var vta = element.GetVisualTreeAsset();
if (vta != null)
return true;
var vea = element.GetVisualElementAsset();
if (vea != null)
return true;
var styleSheet = element.GetStyleSheet();
if (styleSheet != null)
return true;
var scs = element.GetStyleComplexSelector();
if (scs != null)
return true;
return false;
}
public static bool IsSelected(this VisualElement element)
{
var vta = element.GetVisualTreeAsset();
if (vta != null)
return vta.IsSelected();
var vea = element.GetVisualElementAsset();
if (vea != null)
return vea.IsSelected();
var styleSheet = element.GetStyleSheet();
if (styleSheet != null)
return styleSheet.IsSelected();
var scs = element.GetStyleComplexSelector();
if (scs != null)
return scs.IsSelected();
return false;
}
public static bool IsPartOfCurrentDocument(this VisualElement element)
{
return element.GetVisualElementAsset() != null || element.GetVisualTreeAsset() != null || BuilderSharedStyles.IsDocumentElement(element);
}
public static bool IsPartOfActiveVisualTreeAsset(this VisualElement element, BuilderDocument builderDocument)
{
var isSubDocument = builderDocument != null && builderDocument.activeOpenUXMLFile.isChildSubDocument;
var elementVTA = element.GetVisualTreeAsset();
var activeVTA = builderDocument == null ? elementVTA : builderDocument.activeOpenUXMLFile.visualTreeAsset;
var belongsToActiveVisualTreeAsset = (VisualTreeAsset)element.GetProperty(BuilderConstants.ElementLinkedBelongingVisualTreeAssetVEPropertyName) == builderDocument?.visualTreeAsset;
var hasAssetLink = element.GetVisualElementAsset() != null && belongsToActiveVisualTreeAsset;
var hasVTALink = elementVTA != null && elementVTA == activeVTA && !(element is TemplateContainer);
var isDocumentRootElement = !isSubDocument && BuilderSharedStyles.IsDocumentElement(element);
return hasAssetLink || hasVTALink || isDocumentRootElement;
}
public static bool IsActiveSubDocumentRoot(this VisualElement element, BuilderDocument builderDocument)
{
if (!builderDocument.activeOpenUXMLFile.isChildSubDocument ||
element is not TemplateContainer templateContainer ||
templateContainer.templateSource != builderDocument.activeOpenUXMLFile.visualTreeAsset)
{
return false;
}
var templateAsset = templateContainer.GetVisualElementAsset() as TemplateAsset;
var activeOpenUxmlFile = builderDocument.activeOpenUXMLFile;
var templateAssetIndex =
activeOpenUxmlFile.openSubDocumentParent.visualTreeAsset.templateAssets.IndexOf(templateAsset);
return templateAssetIndex == activeOpenUxmlFile.openSubDocumentParentSourceTemplateAssetIndex;
}
public static bool IsSelector(this VisualElement element)
{
return BuilderSharedStyles.IsSelectorElement(element);
}
public static bool IsParentSelector(this VisualElement element)
{
return BuilderSharedStyles.IsParentSelectorElement(element);
}
public static bool IsStyleSheet(this VisualElement element)
{
return BuilderSharedStyles.IsStyleSheetElement(element);
}
public static StyleSheet GetClosestStyleSheet(this VisualElement element)
{
if (element == null)
return null;
var ss = element.GetStyleSheet();
if (ss != null)
return ss;
return element.parent.GetClosestStyleSheet();
}
public static VisualElement GetClosestElementPartOfCurrentDocument(this VisualElement element)
{
if (element == null)
return null;
if (element.IsPartOfCurrentDocument())
return element;
return element.parent.GetClosestElementPartOfCurrentDocument();
}
public static VisualElement GetClosestElementThatIsValid(this VisualElement element, Func<VisualElement, bool> test)
{
if (element == null)
return null;
if (test(element))
return element;
return element.parent.GetClosestElementPartOfCurrentDocument();
}
static void FindElementsRecursive(VisualElement parent, Func<VisualElement, bool> predicate, List<VisualElement> selected)
{
if (predicate(parent))
selected.Add(parent);
foreach (var child in parent.Children())
FindElementsRecursive(child, predicate, selected);
}
public static List<VisualElement> FindElements(this VisualElement element, Func<VisualElement, bool> predicate)
{
var selected = new List<VisualElement>();
FindElementsRecursive(element, predicate, selected);
return selected;
}
public static VisualElement FindElement(this VisualElement element, Func<VisualElement, bool> predicate)
{
var selected = new List<VisualElement>();
FindElementsRecursive(element, predicate, selected);
if (selected.Count == 0)
return null;
return selected[0];
}
static void FindSelectedElementsRecursive(VisualElement parent, List<VisualElement> selected)
{
if (parent.IsSelected())
selected.Add(parent);
foreach (var child in parent.Children())
FindSelectedElementsRecursive(child, selected);
}
public static List<VisualElement> FindSelectedElements(this VisualElement element)
{
var selected = new List<VisualElement>();
FindSelectedElementsRecursive(element, selected);
return selected;
}
public static bool IsFocused(this VisualElement element)
{
if (element.focusController == null)
return false;
return element.focusController.focusedElement == element;
}
public static bool HasAnyAncestorInList(this VisualElement element, IEnumerable<VisualElement> ancestors)
{
foreach (var ancestor in ancestors)
{
if (ancestor == element)
continue;
if (element.HasAncestor(ancestor))
return true;
}
return false;
}
public static bool HasAncestor(this VisualElement element, VisualElement ancestor)
{
if (ancestor == null || element == null)
return false;
if (element == ancestor)
return true;
return element.parent.HasAncestor(ancestor);
}
public static VisualElement GetFirstAncestorWithClass(this VisualElement element, string className)
{
if (element == null)
return null;
if (element.ClassListContains(className))
return element;
return element.parent.GetFirstAncestorWithClass(className);
}
static CustomStyleProperty<string> s_BuilderElementStyleProperty = new CustomStyleProperty<string>("--builder-style");
public static void RegisterCustomBuilderStyleChangeEvent(this VisualElement element, Action<BuilderElementStyle> onElementStyleChanged)
{
element.RegisterCallback<CustomStyleResolvedEvent>(e =>
{
if (e.customStyle.TryGetValue(s_BuilderElementStyleProperty, out var value))
{
BuilderElementStyle elementStyle;
try
{
elementStyle = (BuilderElementStyle)Enum.Parse(typeof(BuilderElementStyle), value, true);
onElementStyleChanged.Invoke(elementStyle);
}
catch
{
throw new NotSupportedException($"The `{value}` value is not supported for {s_BuilderElementStyleProperty.name} property.");
}
}
});
}
public static VisualElement GetVisualInput(this VisualElement ve)
{
var visualInput = ve.GetValueByReflection("visualInput") as VisualElement;
if (visualInput == null)
visualInput = ve.Q("unity-visual-input");
return visualInput;
}
public static FieldStatusIndicator GetFieldStatusIndicator(this VisualElement field)
{
// UxmlSerialization uses a common parent.
var dataField = field as UxmlSerializedDataAttributeField ?? field.GetFirstAncestorOfType<UxmlSerializedDataAttributeField>();
if (dataField != null)
field = dataField;
var statusIndicator = field.GetProperty(FieldStatusIndicator.s_FieldStatusIndicatorVEPropertyName) as FieldStatusIndicator;
if (statusIndicator == null)
{
var row = field.GetContainingRow();
if (row == null)
return null;
// If the field has a name then look for a FieldStatusIndicator in the same containing row that has
// targetFieldName matching the field's name.
if (!string.IsNullOrEmpty(field.name))
{
statusIndicator = row.Query<FieldStatusIndicator>().Where((b) => b.targetFieldName == field.name);
}
// If a status indicator matching the field's name could not be found then pick the first FieldMenuButton in the row.
if (statusIndicator == null)
{
statusIndicator = row.Q<FieldStatusIndicator>();
}
// If no status indicator could not be found in the row then create a new one and insert it to
// the row right after the Override indicators container.
if (statusIndicator == null)
{
statusIndicator = new FieldStatusIndicator();
row.hierarchy.Insert(1, statusIndicator);
}
statusIndicator.targetField = field;
}
return statusIndicator;
}
public static IBuilderUxmlAttributeFieldFactory GetFieldFactory(this VisualElement field) => field.GetProperty(BuilderConstants.AttributeFieldFactoryVEPropertyName) as IBuilderUxmlAttributeFieldFactory;
public static string GetUxmlTypeName(this VisualElement element)
{
if (null == element)
return null;
var desc = UxmlSerializedDataRegistry.GetDescription(element.fullTypeName);
if (null != desc)
return desc.uxmlName;
if (VisualElementFactoryRegistry.TryGetValue(element.fullTypeName, out var factories))
return factories[0].uxmlName;
if (VisualElementFactoryRegistry.TryGetValue(element.GetType(), out factories))
return factories[0].uxmlName;
return null;
}
public static string GetUxmlFullTypeName(this VisualElement element)
{
if (null == element)
return null;
var desc = UxmlSerializedDataRegistry.GetDescription(element.fullTypeName);
if (null != desc)
return desc.uxmlFullName;
if (VisualElementFactoryRegistry.TryGetValue(element.fullTypeName, out var factories))
return factories[0].uxmlQualifiedName;
if (VisualElementFactoryRegistry.TryGetValue(element.GetType(), out factories))
return factories[0].uxmlQualifiedName;
return null;
}
}
enum BuilderElementStyle
{
Default,
Highlighted
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualElementExtensions/VisualElementExtensions.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualElementExtensions/VisualElementExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 10564
} | 485 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
namespace UnityEngine.UIElements
{
/// <summary>
/// Script interface for <see cref="VisualElement"/> background-repeat style property <see cref="IStyle.backgroundRepeat"/>.
/// </summary>
public partial struct BackgroundRepeat : IEquatable<BackgroundRepeat>
{
/// <summary>
/// Background repeat in the x direction.
/// </summary>
public Repeat x;
/// <summary>
/// Background repeat in the y direction.
/// </summary>
public Repeat y;
/// <summary>
/// Create a BackgroundRepeat with x and y repeat
/// </summary>
public BackgroundRepeat(Repeat repeatX, Repeat repeatY)
{
x = repeatX;
y = repeatY;
}
internal static BackgroundRepeat Initial()
{
return BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat();
}
/// <undoc/>
public override bool Equals(object obj)
{
return obj is BackgroundRepeat && Equals((BackgroundRepeat)obj);
}
/// <undoc/>
public bool Equals(BackgroundRepeat other)
{
return other.x == x && other.y == y;
}
/// <undoc/>
public override int GetHashCode()
{
var hashCode = 1500536833;
hashCode = hashCode * -1521134295 + x.GetHashCode();
hashCode = hashCode * -1521134295 + y.GetHashCode();
return hashCode;
}
/// <undoc/>
public static bool operator==(BackgroundRepeat style1, BackgroundRepeat style2)
{
return style1.Equals(style2);
}
/// <undoc/>
public static bool operator!=(BackgroundRepeat style1, BackgroundRepeat style2)
{
return !(style1 == style2);
}
/// <undoc/>
public override string ToString()
{
return $"(x:{x}, y:{y})";
}
}
}
| UnityCsReference/Modules/UIElements/Core/BackgroundRepeat.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/BackgroundRepeat.cs",
"repo_id": "UnityCsReference",
"token_count": 932
} | 486 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Properties;
namespace UnityEngine.UIElements
{
/// <summary>
/// Binding mode to control how a binding is updated.
/// </summary>
/// <remarks>To let the data binding system know that the value in the UI changed, use <see cref="VisualElement.NotifyPropertyChanged"/>.</remarks>
public enum BindingMode
{
/// <summary>
/// Changes on the data source will be replicated in the UI.
/// Changes on the UI will be replicated to the data source.
/// </summary>
TwoWay,
/// <summary>
/// Changes will only be replicated from the UI to the data source for this binding.
/// </summary>
ToSource,
/// <summary>
/// Changes will only be replicated from the source to the UI for this binding.
/// </summary>
ToTarget,
/// <summary>
/// Changes will only be replicated once, from the source to the UI. This binding will be ignored on subsequent updates.
/// </summary>
ToTargetOnce,
}
/// <summary>
/// Binding type that enables data synchronization between a property of a data source and a property of a <see cref="VisualElement"/>.
/// </summary>
public partial class DataBinding : Binding, IDataSourceProvider
{
private static MethodInfo s_UpdateUIMethodInfo;
internal static MethodInfo updateUIMethod => s_UpdateUIMethodInfo ??= CacheReflectionInfo();
private static MethodInfo CacheReflectionInfo()
{
foreach (var method in typeof(DataBinding).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic))
{
if (method.Name != nameof(UpdateUI))
continue;
if (method.GetParameters().Length != 2) continue;
return s_UpdateUIMethodInfo = method;
}
throw new InvalidOperationException($"Could not find method {nameof(UpdateUI)} by reflection. This is an internal bug. Please report using `Help > Report a Bug...` ");
}
private BindingMode m_BindingMode;
private ConverterGroup m_SourceToUiConverters;
private ConverterGroup m_UiToSourceConverters;
/// <summary>
/// Object that serves as a local source for the binding, and is particularly useful when the data source is not
/// part of the UI hierarchy, such as a static localization table. If this object is null, the binding resolves
/// the data source using its normal resolution method.
/// </summary>
/// <remarks>
/// Using a local source does not prevent children of the target from using the hierarchy source.
/// </remarks>
[CreateProperty]
public object dataSource { get; set; }
/// <summary>
/// The possible data source types that can be assigned to the binding.
/// </summary>
/// <remarks>
/// This information is only used by the UI Builder as a hint to provide some completion to the data source path field when the effective data source cannot be specified at design time.
/// </remarks>
internal Type dataSourceType { get; set; }
internal string dataSourceTypeString
{
get => UxmlUtility.TypeToString(dataSourceType);
set => dataSourceType = UxmlUtility.ParseType(value);
}
/// <summary>
/// Path from the data source to the value.
/// </summary>
[CreateProperty]
public PropertyPath dataSourcePath { get; set; }
internal string dataSourcePathString
{
get => dataSourcePath.ToString();
set => dataSourcePath = new PropertyPath(value);
}
/// <summary>
/// Controls how this binding should be updated.
/// The default value is <see cref="BindingMode.TwoWay"/>.
/// </summary>
[CreateProperty]
public BindingMode bindingMode
{
get => m_BindingMode;
set
{
if (m_BindingMode == value)
return;
m_BindingMode = value;
MarkDirty();
}
}
/// <summary>
/// Returns the <see cref="ConverterGroup"/> used when trying to convert data from the data source to a UI property.
/// </summary>
[CreateProperty(ReadOnly = true)]
public ConverterGroup sourceToUiConverters
{
get
{
return m_SourceToUiConverters ??= new ConverterGroup(string.Empty);
}
}
/// <summary>
/// Returns the <see cref="ConverterGroup"/> used when trying to convert data from a UI property back to the data source.
/// </summary>
[CreateProperty(ReadOnly = true)]
public ConverterGroup uiToSourceConverters
{
get
{
return m_UiToSourceConverters ??= new ConverterGroup(string.Empty);
}
}
List<string> m_SourceToUIConvertersString;
internal string sourceToUiConvertersString
{
get => m_SourceToUIConvertersString != null ? string.Join(", ", m_SourceToUIConvertersString) : null;
set
{
m_SourceToUIConvertersString = UxmlUtility.ParseStringListAttribute(value);
if (m_SourceToUIConvertersString != null)
{
foreach (var id in m_SourceToUIConvertersString)
{
if (ConverterGroups.TryGetConverterGroup(id, out var group))
{
ApplyConverterGroupToUI(group);
}
}
}
}
}
List<string> m_UiToSourceConvertersString;
internal string uiToSourceConvertersString
{
get => m_UiToSourceConvertersString != null ? string.Join(", ", m_UiToSourceConvertersString) : null;
set
{
m_UiToSourceConvertersString = UxmlUtility.ParseStringListAttribute(value);
if (m_UiToSourceConvertersString != null)
{
foreach (var id in m_UiToSourceConvertersString)
{
if (ConverterGroups.TryGetConverterGroup(id, out var group))
{
ApplyConverterGroupToSource(group);
}
}
}
}
}
/// <summary>
/// Initializes and returns an instance of <see cref="DataBinding"/>.
/// </summary>
public DataBinding()
{
updateTrigger = BindingUpdateTrigger.OnSourceChanged;
}
/// <summary>
/// Applies a <see cref="ConverterGroup"/> to this binding that will be used when converting data between a
/// UI control to a data source.
/// </summary>
/// <remarks>
/// Converter groups can be queried using <see cref="ConverterGroups.TryGetConverterGroup"/>.
/// </remarks>
/// <param name="group">The converter group.</param>
public void ApplyConverterGroupToSource(ConverterGroup group)
{
var localToSource = uiToSourceConverters;
localToSource.registry.Apply(group.registry);
}
/// <summary>
/// Applies a <see cref="ConverterGroup"/> to this binding that will be used when converting data between a
/// data source to a UI control.
/// </summary>
/// <remarks>
/// Converter groups can be queried using <see cref="ConverterGroups.TryGetConverterGroup"/>.
/// </remarks>
/// <param name="group">The converter group.</param>
public void ApplyConverterGroupToUI(ConverterGroup group)
{
var localToUI = sourceToUiConverters;
localToUI.registry.Apply(group.registry);
}
/// <summary>
/// Callback called to allow derived classes to update the UI with the resolved value from the data source.
/// </summary>
/// <param name="context">Context object containing the necessary information to resolve a binding.</param>
/// <param name="value">The resolved value from the data source.</param>
/// <typeparam name="TValue">The type of the <paramref name="value"/></typeparam>
/// <returns>A <see cref="BindingResult"/> indicating if the binding update succeeded or not.</returns>
protected internal virtual BindingResult UpdateUI<TValue>(in BindingContext context, ref TValue value)
{
var target = context.targetElement;
// When a field is delayed, we should avoid setting the value.
var focusController = target.focusController;
if (null != focusController && focusController.IsFocused(target) && target is IDelayedField {isDelayed: true})
{
// Only skip setting the value when the actual input field is focused.
var leaf = focusController.GetLeafFocusedElement();
if (leaf is TextElement textElement && textElement.ClassListContains("unity-text-element--inner-input-field-component"))
{
return new BindingResult(BindingStatus.Pending);
}
}
var succeeded = sourceToUiConverters.TrySetValue(ref target, context.bindingId, value, out var returnCode);
if (succeeded)
return default;
var message = GetSetValueErrorString(returnCode, context.dataSource, context.dataSourcePath, target, context.bindingId, value);
return new BindingResult(BindingStatus.Failure, message);
}
/// <summary>
/// Callback called to allow derived classes to update the data source with the resolved value when a change from the UI is detected.
/// </summary>
/// <param name="context">Context object containing the necessary information to resolve a binding.</param>
/// <param name="value">The resolved value from the data source.</param>
/// <typeparam name="TValue">The type of the <paramref name="value"/></typeparam>
/// <returns>A <see cref="BindingResult"/> indicating if the binding update succeeded or not.</returns>
protected internal virtual BindingResult UpdateSource<TValue>(in BindingContext context, ref TValue value)
{
var target = context.dataSource;
var succeeded = uiToSourceConverters.TrySetValue(ref target, context.dataSourcePath, value, out var returnCode);
if (succeeded)
return default;
var message = GetSetValueErrorString(returnCode, context.targetElement, context.bindingId, context.dataSource, context.dataSourcePath, value);
return new BindingResult(BindingStatus.Failure, message);
}
// Internal for tests
internal static string GetSetValueErrorString<TValue>(VisitReturnCode returnCode, object source, in PropertyPath sourcePath, object target, in BindingId targetPath, TValue extractedValueFromSource)
{
var prefix = $"[UI Toolkit] Could not set value for target of type '<b>{target.GetType().Name}</b>' at path '<b>{targetPath}</b>':";
switch (returnCode)
{
case VisitReturnCode.MissingPropertyBag:
return $"{prefix} the type '{target.GetType().Name}' is missing a property bag.";
case VisitReturnCode.InvalidPath:
return $"{prefix} the path is either invalid or contains a null value.";
case VisitReturnCode.InvalidCast:
if (sourcePath.IsEmpty)
{
if (PropertyContainer.TryGetValue(ref target, targetPath, out object obj) && null != obj)
{
return null == extractedValueFromSource
? $"{prefix} could not convert from '<b>null</b>' to '<b>{obj.GetType().Name}</b>'."
: $"{prefix} could not convert from type '<b>{extractedValueFromSource.GetType().Name}</b>' to type '<b>{obj.GetType().Name}</b>'.";
}
}
if (PropertyContainer.TryGetProperty(ref source, sourcePath, out var property))
{
if (PropertyContainer.TryGetValue(ref target, targetPath, out object obj) && null != obj)
{
return null == extractedValueFromSource
? $"{prefix} could not convert from '<b>null ({property.DeclaredValueType().Name})</b>' to '<b>{obj.GetType().Name}</b>'."
: $"{prefix} could not convert from type '<b>{extractedValueFromSource.GetType().Name}</b>' to type '<b>{obj.GetType().Name}</b>'.";
}
}
return $"{prefix} conversion failed.";
case VisitReturnCode.AccessViolation:
return $"{prefix} the path is read-only.";
case VisitReturnCode.Ok: // Can't extract an error message from a success.
case VisitReturnCode.NullContainer: // Should be checked before trying to set a value.
case VisitReturnCode.InvalidContainerType: // Target should always be a VisualElement
throw new InvalidOperationException($"{prefix} internal data binding error. Please report this using the '<b>Help/Report a bug...</b>' menu item.");
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Bindings/DataBinding.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/DataBinding.cs",
"repo_id": "UnityCsReference",
"token_count": 6067
} | 487 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using System.Linq;
using Unity.Hierarchy;
using UnityEngine.Assertions;
namespace UnityEngine.UIElements
{
/// <summary>
/// Base collection view controller. View controllers are meant to take care of data virtualized by any <see cref="BaseVerticalCollectionView"/> inheritor.
/// </summary>
public abstract class CollectionViewController : IDisposable
{
BaseVerticalCollectionView m_View;
IList m_ItemsSource;
/// <summary>
/// Raised when the <see cref="itemsSource"/> changes.
/// </summary>
public event Action itemsSourceChanged;
/// <summary>
/// Raised when an item in the source changes index.
/// The first argument is source index, second is destination index.
/// </summary>
public event Action<int, int> itemIndexChanged;
/// <summary>
/// The items source stored in a non-generic list.
/// </summary>
public virtual IList itemsSource
{
get => m_ItemsSource;
set
{
if (m_ItemsSource == value)
return;
m_ItemsSource = value;
// We need RefreshItems if itemsSource was changed, but only when we're not using
// ListViewBindings, that does the refresh already when the SerializedProperty is ready.
if (m_View.GetProperty(BaseVerticalCollectionView.internalBindingKey) == null)
{
m_View.RefreshItems();
}
RaiseItemsSourceChanged();
}
}
/// <summary>
/// Set the <see cref="itemsSource"/> without raising the <see cref="itemsSourceChanged"/> event.
/// </summary>
/// <param name="source">The new source.</param>
protected void SetItemsSourceWithoutNotify(IList source)
{
m_ItemsSource = source;
}
/// <summary>
/// Set the <see cref="itemsSource"/> without raising the <see cref="itemsSourceChanged"/> event.
/// </summary>
/// <param name="source">The new source.</param>
private protected void SetHierarchyViewModelWithoutNotify(HierarchyViewModel source)
{
m_ItemsSource = new ReadOnlyHierarchyViewModelList(source);
}
/// <summary>
/// The view for this controller.
/// </summary>
protected BaseVerticalCollectionView view => m_View;
/// <summary>
/// Sets the view for this controller.
/// </summary>
/// <param name="collectionView">The view for this controller. Must not be null.</param>
public void SetView(BaseVerticalCollectionView collectionView)
{
m_View = collectionView;
PrepareView();
Assert.IsNotNull(m_View, "View must not be null.");
}
/// <summary>
/// Initialization step once the view is set.
/// </summary>
protected virtual void PrepareView()
{
// Nothing to do here in the base class.
}
/// <summary>
/// Called when this controller is not longer needed to provide a way to release resources.
/// </summary>
public virtual void Dispose()
{
itemsSourceChanged = null;
itemIndexChanged = null;
m_View = null;
}
/// <summary>
/// Returns the expected item count in the source.
/// </summary>
/// <returns>The item count.</returns>
public virtual int GetItemsCount()
{
return m_ItemsSource?.Count ?? 0;
}
internal virtual int GetItemsMinCount() => GetItemsCount();
/// <summary>
/// Returns the index for the specified id.
/// </summary>
/// <param name="id">The item id..</param>
/// <returns>The item index.</returns>
/// <remarks>For example, the index will be different from the id in a tree.</remarks>
public virtual int GetIndexForId(int id)
{
return id;
}
/// <summary>
/// Returns the id for the specified index.
/// </summary>
/// <param name="index">The item index.</param>
/// <returns>The item id.</returns>
/// <remarks>For example, the index will be different from the id in a tree.</remarks>
public virtual int GetIdForIndex(int index)
{
return index;
}
/// <summary>
/// Returns the item with the specified index.
/// </summary>
/// <param name="index">The item index.</param>
/// <returns>The object in the source at this index.</returns>
public virtual object GetItemForIndex(int index)
{
if (m_ItemsSource == null)
return null;
if (index < 0 || index >= m_ItemsSource.Count)
return null;
return m_ItemsSource[index];
}
/// <summary>
/// Returns the item with the specified ID.
/// </summary>
/// <param name="id">The item ID.</param>
/// <returns>The object in the source with this ID.</returns>
public virtual object GetItemForId(int id)
{
if (m_ItemsSource == null)
return null;
var index = GetIndexForId(id);
if (index < 0 || index >= m_ItemsSource.Count)
return null;
return m_ItemsSource[index];
}
internal virtual void InvokeMakeItem(ReusableCollectionItem reusableItem)
{
reusableItem.Init(MakeItem());
}
internal virtual void InvokeBindItem(ReusableCollectionItem reusableItem, int index)
{
BindItem(reusableItem.bindableElement, index);
reusableItem.SetSelected(m_View.selectedIndices.Contains(index));
reusableItem.rootElement.pseudoStates &= ~PseudoStates.Hover;
reusableItem.index = index;
}
internal virtual void InvokeUnbindItem(ReusableCollectionItem reusableItem, int index)
{
UnbindItem(reusableItem.bindableElement, index);
reusableItem.index = ReusableCollectionItem.UndefinedIndex;
}
internal virtual void InvokeDestroyItem(ReusableCollectionItem reusableItem)
{
DestroyItem(reusableItem.bindableElement);
}
internal virtual void PreRefresh() {}
/// <summary>
/// Creates a VisualElement to use in the virtualization of the collection view.
/// </summary>
/// <returns>A VisualElement for the row.</returns>
protected abstract VisualElement MakeItem();
/// <summary>
/// Binds a row to an item index.
/// </summary>
/// <param name="element">The element from that row, created by MakeItem().</param>
/// <param name="index">The item index.</param>
protected abstract void BindItem(VisualElement element, int index);
/// <summary>
/// Unbinds a row to an item index.
/// </summary>
/// <param name="element">The element from that row, created by MakeItem().</param>
/// <param name="index">The item index.</param>
protected abstract void UnbindItem(VisualElement element, int index);
/// <summary>
/// Destroys a VisualElement when the view is rebuilt or cleared.
/// </summary>
/// <param name="element">The element being destroyed.</param>
protected abstract void DestroyItem(VisualElement element);
/// <summary>
/// Invokes the <see cref="itemsSourceChanged"/> event.
/// </summary>
protected void RaiseItemsSourceChanged()
{
itemsSourceChanged?.Invoke();
}
/// <summary>
/// Invokes the <see cref="itemIndexChanged"/> event.
/// </summary>
/// <param name="srcIndex">The source index.</param>
/// <param name="dstIndex">The destination index.</param>
protected void RaiseItemIndexChanged(int srcIndex, int dstIndex)
{
itemIndexChanged?.Invoke(srcIndex, dstIndex);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Controllers/CollectionViewController.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Controllers/CollectionViewController.cs",
"repo_id": "UnityCsReference",
"token_count": 3501
} | 488 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
class ReusableMultiColumnListViewItem : ReusableListViewItem
{
public override VisualElement rootElement => bindableElement;
public override void Init(VisualElement item)
{
// Do nothing here, we are using the other Init.
}
public void Init(VisualElement container, Columns columns, bool usesAnimatedDrag)
{
var i = 0;
bindableElement = container;
foreach (var column in columns.visibleList)
{
if (columns.IsPrimary(column))
{
var cellContainer = container[i];
var cellItem = cellContainer.GetProperty(MultiColumnController.bindableElementPropertyName) as VisualElement;
UpdateHierarchy(cellContainer, cellItem, usesAnimatedDrag);
break;
}
i++;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableMultiColumnListViewItem.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableMultiColumnListViewItem.cs",
"repo_id": "UnityCsReference",
"token_count": 505
} | 489 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
/// <summary>
/// Styled visual element to match the IMGUI Box Style. For more information, refer to [[wiki:UIE-uxml-element-box|UXML element Box]].
/// </summary>
public class Box : VisualElement
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new Box();
}
/// <summary>
/// Instantiates a <see cref="Box"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<Box> {}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public static readonly string ussClassName = "unity-box";
/// <summary>
/// Initializes and returns an instance of Box.
/// </summary>
public Box()
{
AddToClassList(ussClassName);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/Box.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Box.cs",
"repo_id": "UnityCsReference",
"token_count": 494
} | 490 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using Unity.Properties;
using UnityEngine.Bindings;
using UnityEngine.Internal;
namespace UnityEngine.UIElements
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal interface IPrefixLabel
{
string label { get; }
Label labelElement { get; }
}
internal interface IDelayedField
{
bool isDelayed { get; }
}
/// <summary>
/// Interface for all editable elements.
/// </summary>
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal interface IEditableElement
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal Action editingStarted { get; set; }
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal Action editingEnded { get; set; }
}
/// <summary>
/// <para>Abstract base class for controls.</para>
/// <para>A BaseField is a base class for field elements like <see cref="TextField"/> and <see cref="IntegerField"/>.
/// To align a BaseField element automatically with other fields in an Inspector window,
/// use the @@.unity-base-field__aligned@@ USS class. This style class is designed for use with
/// Inspector elements like <see cref="PropertyField"/>, which has the style class by default.
/// However, if you manually add a child BaseField element to a PropertyField, you must add
/// the style class manually.</para>
/// <para>When the style class is present, the field automatically calculates the label width
/// to align with other fields in the Inspector window. If there are IMGUI fields present,
/// UI Toolkit fields are aligned with them for consistency and compatibility.</para>
/// </summary>
public abstract class BaseField<TValueType> : BindableElement, INotifyValueChanged<TValueType>, IMixedValueSupport, IPrefixLabel, IEditableElement
{
internal static readonly BindingId valueProperty = nameof(value);
internal static readonly BindingId labelProperty = nameof(label);
internal static readonly BindingId showMixedValueProperty = nameof(showMixedValue);
[ExcludeFromDocs, Serializable]
public new abstract class UxmlSerializedData : BindableElement.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField, MultilineTextField] string label;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags label_UxmlAttributeFlags;
[SerializeField] TValueType value;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags value_UxmlAttributeFlags;
#pragma warning restore 649
/// Used by <see cref="IUxmlSerializedDataCustomAttributeHandler"/> to set the value from legacy field values
internal TValueType Value { set => this.value = value; get => this.value; }
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (BaseField<TValueType>)obj;
if (ShouldWriteAttributeValue(label_UxmlAttributeFlags))
e.label = label;
if (ShouldWriteAttributeValue(value_UxmlAttributeFlags))
e.SetValueWithoutNotify(value);
}
}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="BaseField"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : BindableElement.UxmlTraits
{
UxmlStringAttributeDescription m_Label = new UxmlStringAttributeDescription { name = "label" };
/// <summary>
/// Constructor.
/// </summary>
public UxmlTraits()
{
focusIndex.defaultValue = 0;
focusable.defaultValue = true;
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((BaseField<TValueType>)ve).label = m_Label.GetValueFromBag(bag, cc);
}
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public static readonly string ussClassName = "unity-base-field";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// USS class name of elements of this type, when there is no label.
/// </summary>
public static readonly string noLabelVariantUssClassName = ussClassName + "--no-label";
/// <summary>
/// USS class name of labels in elements of this type, when there is a dragger attached on them.
/// </summary>
public static readonly string labelDraggerVariantUssClassName = labelUssClassName + "--with-dragger";
/// <summary>
/// USS class name of elements that show mixed values
/// </summary>
public static readonly string mixedValueLabelUssClassName = labelUssClassName + "--mixed-value";
/// <summary>
/// USS class name of elements that are aligned in a inspector element
/// </summary>
public static readonly string alignedFieldUssClassName = ussClassName + "__aligned";
private static readonly string inspectorFieldUssClassName = ussClassName + "__inspector-field";
protected internal static readonly string mixedValueString = "\u2014";
protected internal static readonly PropertyName serializedPropertyCopyName = "SerializedPropertyCopyName";
static CustomStyleProperty<float> s_LabelWidthRatioProperty = new CustomStyleProperty<float>("--unity-property-field-label-width-ratio");
static CustomStyleProperty<float> s_LabelExtraPaddingProperty = new CustomStyleProperty<float>("--unity-property-field-label-extra-padding");
static CustomStyleProperty<float> s_LabelBaseMinWidthProperty = new CustomStyleProperty<float>("--unity-property-field-label-base-min-width");
static CustomStyleProperty<float> s_LabelExtraContextWidthProperty = new CustomStyleProperty<float>("--unity-base-field-extra-context-width");
private float m_LabelWidthRatio;
private float m_LabelExtraPadding;
private float m_LabelBaseMinWidth;
private float m_LabelExtraContextWidth;
private VisualElement m_VisualInput;
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal VisualElement visualInput
{
get { return m_VisualInput; }
set
{
// Get rid of the older value...
if (m_VisualInput != null)
{
if (m_VisualInput.parent == this)
{
m_VisualInput.RemoveFromHierarchy();
}
m_VisualInput = null;
}
// Handle the new value...
if (value != null)
{
m_VisualInput = value;
}
else
{
m_VisualInput = new VisualElement() { pickingMode = PickingMode.Ignore };
}
m_VisualInput.focusable = true;
m_VisualInput.AddToClassList(inputUssClassName);
Add(m_VisualInput);
}
}
[SerializeField, DontCreateProperty]
TValueType m_Value;
/// <summary>
/// The value of the element.
/// </summary>
protected TValueType rawValue
{
get { return m_Value; }
set { m_Value = value; }
}
internal event Func<TValueType, TValueType> onValidateValue;
/// <summary>
/// The value associated with the field.
/// </summary>
[CreateProperty]
public virtual TValueType value
{
get
{
return m_Value;
}
set
{
if (!EqualityComparer<TValueType>.Default.Equals(m_Value, value))
{
if (panel != null)
{
var previousValue = m_Value;
SetValueWithoutNotify(value);
using (ChangeEvent<TValueType> evt = ChangeEvent<TValueType>.GetPooled(previousValue, m_Value))
{
evt.elementTarget = this;
SendEvent(evt);
}
NotifyPropertyChanged(valueProperty);
}
else
{
SetValueWithoutNotify(value);
}
}
}
}
/// <summary>
/// This is the <see cref="Label"/> object that appears beside the input for the field.
/// </summary>
public Label labelElement { get; private set; }
/// <summary>
/// The string representing the label that will appear beside the field.
/// </summary>
[CreateProperty]
public string label
{
get
{
return labelElement.text;
}
set
{
if (labelElement.text != value)
{
labelElement.text = value;
if (string.IsNullOrEmpty(labelElement.text))
{
AddToClassList(noLabelVariantUssClassName);
labelElement.RemoveFromHierarchy();
}
else
{
if (!Contains(labelElement))
{
hierarchy.Insert(0, labelElement);
RemoveFromClassList(noLabelVariantUssClassName);
}
}
NotifyPropertyChanged(labelProperty);
}
}
}
bool m_ShowMixedValue;
/// <summary>
/// When set to true, gives the field the appearance of editing multiple different values.
/// </summary>
[CreateProperty]
public bool showMixedValue
{
get => m_ShowMixedValue;
set
{
if (value == m_ShowMixedValue) return;
m_ShowMixedValue = value;
// Once value has been set, update the field's appearance
UpdateMixedValueContent();
NotifyPropertyChanged(showMixedValueProperty);
}
}
Label m_MixedValueLabel;
/// <summary>
/// Read-only label used to give the appearance of editing multiple different values.
/// </summary>
protected Label mixedValueLabel
{
get
{
if (m_MixedValueLabel == null)
{
m_MixedValueLabel = new Label(mixedValueString) { focusable = true, tabIndex = -1 };
m_MixedValueLabel.AddToClassList(labelUssClassName);
m_MixedValueLabel.AddToClassList(mixedValueLabelUssClassName);
}
return m_MixedValueLabel;
}
}
bool m_SkipValidation;
private VisualElement m_CachedContextWidthElement;
private VisualElement m_CachedInspectorElement;
Action IEditableElement.editingStarted { get; set; }
Action IEditableElement.editingEnded { get; set; }
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal BaseField(string label)
{
isCompositeRoot = true;
focusable = true;
tabIndex = 0;
excludeFromFocusRing = true;
delegatesFocus = true;
AddToClassList(ussClassName);
labelElement = new Label() { focusable = true, tabIndex = -1 };
labelElement.AddToClassList(labelUssClassName);
if (label != null)
{
this.label = label;
}
else
{
AddToClassList(noLabelVariantUssClassName);
}
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
m_VisualInput = null;
}
protected BaseField(string label, VisualElement visualInput)
: this(label)
{
this.visualInput = visualInput;
}
private void OnAttachToPanel(AttachToPanelEvent e)
{
// indicates the start and end of the field value being edited
RegisterEditingCallbacks();
if (e.destinationPanel == null)
{
return;
}
if (e.destinationPanel.contextType == ContextType.Player)
{
return;
}
m_CachedInspectorElement = null;
m_CachedContextWidthElement = null;
var currentElement = parent;
while (currentElement != null)
{
if (currentElement.ClassListContains("unity-inspector-element"))
{
m_CachedInspectorElement = currentElement;
}
if (currentElement.ClassListContains("unity-inspector-main-container"))
{
m_CachedContextWidthElement = currentElement;
break;
}
currentElement = currentElement.parent;
}
if (m_CachedInspectorElement == null)
{
RemoveFromClassList(inspectorFieldUssClassName);
return;
}
// These default values are based of IMGUI
m_LabelWidthRatio = 0.45f;
// Those values are 40 and 120 in IMGUI, but they already take in account the fields margin. We readjust them
// because the uitk margin is being taken in account later.
m_LabelExtraPadding = 37.0f;
m_LabelBaseMinWidth = 123.0f;
// The inspector panel has a 1px border we need to consider as part of the context width.
m_LabelExtraContextWidth = 1.0f;
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
AddToClassList(inspectorFieldUssClassName);
RegisterCallback<GeometryChangedEvent>(OnInspectorFieldGeometryChanged);
}
private void OnDetachFromPanel(DetachFromPanelEvent e)
{
UnregisterEditingCallbacks();
onValidateValue = null;
}
internal virtual void RegisterEditingCallbacks()
{
RegisterCallback<FocusInEvent>(StartEditing);
RegisterCallback<FocusOutEvent>(EndEditing);
}
internal virtual void UnregisterEditingCallbacks()
{
UnregisterCallback<FocusInEvent>(StartEditing);
UnregisterCallback<FocusOutEvent>(EndEditing);
}
internal void StartEditing(EventBase e)
{
((IEditableElement)this).editingStarted?.Invoke();
}
internal void EndEditing(EventBase e)
{
((IEditableElement)this).editingEnded?.Invoke();
}
private void OnCustomStyleResolved(CustomStyleResolvedEvent evt)
{
if (evt.customStyle.TryGetValue(s_LabelWidthRatioProperty, out var labelWidthRatio))
{
m_LabelWidthRatio = labelWidthRatio;
}
if (evt.customStyle.TryGetValue(s_LabelExtraPaddingProperty, out var labelExtraPadding))
{
m_LabelExtraPadding = labelExtraPadding;
}
if (evt.customStyle.TryGetValue(s_LabelBaseMinWidthProperty, out var labelBaseMinWidth))
{
m_LabelBaseMinWidth = labelBaseMinWidth;
}
if (evt.customStyle.TryGetValue(s_LabelExtraContextWidthProperty, out var labelExtraContextWidth))
{
m_LabelExtraContextWidth = labelExtraContextWidth;
}
AlignLabel();
}
private void OnInspectorFieldGeometryChanged(GeometryChangedEvent e)
{
AlignLabel();
}
private void AlignLabel()
{
if (!ClassListContains(alignedFieldUssClassName) || m_CachedInspectorElement == null)
{
return;
}
// Not all visual input controls have the same padding so we can't base our total padding on
// that information. Instead we add a flat value to totalPadding to best match the hard coded
// calculation in IMGUI
var totalPadding = m_LabelExtraPadding;
var spacing = worldBound.x - m_CachedInspectorElement.worldBound.x - m_CachedInspectorElement.resolvedStyle.paddingLeft;
totalPadding += spacing;
totalPadding += resolvedStyle.paddingLeft;
var minWidth = m_LabelBaseMinWidth - spacing - resolvedStyle.paddingLeft;
var contextWidthElement = m_CachedContextWidthElement ?? m_CachedInspectorElement;
labelElement.style.minWidth = Mathf.Max(minWidth, 0);
// Formula to follow IMGUI label width settings
var newWidth = (contextWidthElement.resolvedStyle.width + m_LabelExtraContextWidth) * m_LabelWidthRatio - totalPadding;
if (Mathf.Abs(labelElement.resolvedStyle.width - newWidth) > UIRUtility.k_Epsilon)
{
labelElement.style.width = Mathf.Max(0f, newWidth);
}
}
internal TValueType ValidatedValue(TValueType value)
{
if (onValidateValue != null)
{
return onValidateValue.Invoke(value);
}
return value;
}
/// <summary>
/// Update the field's visual content depending on showMixedValue.
/// </summary>
protected virtual void UpdateMixedValueContent()
{
throw new NotImplementedException();
}
/// <summary>
/// Allow to set a value without being notified of the change, if any.
/// </summary>
/// <param name="newValue">New value to be set.</param>
public virtual void SetValueWithoutNotify(TValueType newValue)
{
if (m_SkipValidation)
{
m_Value = newValue;
}
else
{
m_Value = ValidatedValue(newValue);
}
if (!string.IsNullOrEmpty(viewDataKey))
SaveViewData();
MarkDirtyRepaint();
if (showMixedValue)
UpdateMixedValueContent();
}
internal void SetValueWithoutValidation(TValueType newValue)
{
m_SkipValidation = true;
value = newValue;
m_SkipValidation = false;
}
internal override void OnViewDataReady()
{
base.OnViewDataReady();
if (m_VisualInput != null)
{
var key = GetFullHierarchicalViewDataKey();
var oldValue = m_Value;
OverwriteFromViewData(this, key);
if (!EqualityComparer<TValueType>.Default.Equals(oldValue, m_Value))
{
using (ChangeEvent<TValueType> evt = ChangeEvent<TValueType>.GetPooled(oldValue, m_Value))
{
evt.elementTarget = this;
SetValueWithoutNotify(m_Value);
SendEvent(evt);
}
}
}
}
internal override Rect GetTooltipRect()
{
return !string.IsNullOrEmpty(label) ? labelElement.worldBound : worldBound;
}
}
/// <summary>
/// Traits for the <see cref="BaseField"/>.
/// </summary>
[Obsolete("BaseFieldTraits<TValueType, TValueUxmlAttributeType> is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public class BaseFieldTraits<TValueType, TValueUxmlAttributeType> : BaseField<TValueType>.UxmlTraits
where TValueUxmlAttributeType : TypedUxmlAttributeDescription<TValueType>, new()
{
TValueUxmlAttributeType m_Value = new TValueUxmlAttributeType { name = "value" };
/// <summary>
/// Initializes the trait of <see cref="BaseField"/>.
/// </summary>
/// <param name="ve">The VisualElement to initialize.</param>
/// <param name="bag">Bag of attributes.</param>
/// <param name="cc">The creation context associated with these traits.</param>
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
((INotifyValueChanged<TValueType>)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc));
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/InputField/BaseField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/InputField/BaseField.cs",
"repo_id": "UnityCsReference",
"token_count": 10055
} | 491 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Pool;
namespace UnityEngine.UIElements.Internal
{
/// <summary>
/// The multi-column header. It handles resize, sorting, visibility events and sends them to the listening controller.
/// </summary>
class MultiColumnCollectionHeader : VisualElement, IDisposable
{
const int kMaxStableLayoutPassCount = 2; // Beyond this threshold, DoLayout must be performed in the next frame; otherwise, this may lead to Layout instabilities. This is caused by the dependencies between the geometries of the header, the viewport and the content.
[Serializable]
class ViewState
{
[SerializeField]
bool m_HasPersistedData;
/// <summary>
/// State of columns.
/// </summary>
[Serializable]
struct ColumnState
{
public int index;
public string name;
public float actualWidth;
public float width;
public bool visible;
}
[SerializeField]
List<SortColumnDescription> m_SortDescriptions = new List<SortColumnDescription>();
[SerializeField]
List<ColumnState> m_OrderedColumnStates = new List<ColumnState>();
/// <summary>
/// Saves the state of the specified header control.
/// </summary>
/// <param name="header">The header control of which state to save.</param>
internal void Save(MultiColumnCollectionHeader header)
{
m_SortDescriptions.Clear();
m_OrderedColumnStates.Clear();
foreach (var sortDesc in header.sortDescriptions)
{
m_SortDescriptions.Add(sortDesc);
}
foreach (var column in header.columns.displayList)
{
var columnState = new ColumnState() { index = column.index, name = column.name, actualWidth = column.desiredWidth, width = column.width.value, visible = column.visible };
m_OrderedColumnStates.Add(columnState);
}
m_HasPersistedData = true;
}
/// <summary>
/// Applies the state of the specified header control.
/// </summary>
internal void Apply(MultiColumnCollectionHeader header)
{
if (!m_HasPersistedData)
return;
var minCount = Math.Min(m_OrderedColumnStates.Count, header.columns.Count);
var nextValidOrderedIndex = 0;
for (var orderedIndex = 0; (orderedIndex < m_OrderedColumnStates.Count) && (nextValidOrderedIndex < minCount); orderedIndex++)
{
var columnState = m_OrderedColumnStates[orderedIndex];
Column column = null;
// Find column by name
if (!string.IsNullOrEmpty(columnState.name))
{
if (header.columns.Contains(columnState.name))
{
column = header.columns[columnState.name];
}
}
else
{
if (columnState.index > header.columns.Count - 1)
continue;
column = header.columns[columnState.index];
// If the column has a name then we assume it is not the same column anymore
if (!string.IsNullOrEmpty(column.name))
{
column = null;
}
}
if (column == null)
continue;
header.columns.ReorderDisplay(column.displayIndex, nextValidOrderedIndex++);
column.visible = columnState.visible;
column.width = columnState.width;
column.desiredWidth = columnState.actualWidth;
}
header.sortDescriptions.Clear();
foreach (var sortDesc in m_SortDescriptions)
{
header.sortDescriptions.Add(sortDesc);
}
}
}
internal class ColumnData
{
public MultiColumnHeaderColumn control { get; set; }
public MultiColumnHeaderColumnResizeHandle resizeHandle { get; set; }
}
/// <summary>
/// Used to determine whether the actual sorting has changed.
/// </summary>
struct SortedColumnState
{
public SortedColumnState(SortColumnDescription desc, SortDirection dir)
{
columnDesc = desc;
direction = dir;
}
public SortColumnDescription columnDesc;
public SortDirection direction;
}
/// <summary>
/// The USS class name for MultiColumnCollectionHeader elements.
/// </summary>
public static readonly string ussClassName = "unity-multi-column-header";
/// <summary>
/// The USS class name for column container elements of multi column headers.
/// </summary>
public static readonly string columnContainerUssClassName = ussClassName + "__column-container";
/// <summary>
/// The USS class name for handle container elements of multi column headers.
/// </summary>
public static readonly string handleContainerUssClassName = ussClassName + "__resize-handle-container";
/// <summary>
/// The USS class name for MultiColumnCollectionHeader elements that are in animated reorder mode.
/// </summary>
public static readonly string reorderableUssClassName = ussClassName + "__header";
bool m_SortingEnabled;
List<SortColumnDescription> m_SortedColumns;
SortColumnDescriptions m_SortDescriptions;
List<SortedColumnState> m_OldSortedColumnStates = new List<SortedColumnState>();
bool m_SortingUpdatesTemporarilyDisabled;
ViewState m_ViewState;
bool m_ApplyingViewState;
internal bool isApplyingViewState => m_ApplyingViewState;
bool m_DoLayoutScheduled;
/// <summary>
/// Per-Column data.
/// </summary>
public Dictionary<Column, ColumnData> columnDataMap { get; } = new Dictionary<Column, ColumnData>();
/// <summary>
/// The layout manager to lay columns.
/// </summary>
public ColumnLayout columnLayout { get; }
/// <summary>
/// Container for column elements.
/// </summary>
public VisualElement columnContainer { get; }
/// <summary>
/// Container for resize handles.
/// </summary>
public VisualElement resizeHandleContainer { get; }
/// <summary>
/// The effective list of sorted columns.
/// </summary>
public IEnumerable<SortColumnDescription> sortedColumns => m_SortedColumns;
internal IReadOnlyList<SortColumnDescription> sortedColumnReadonly => m_SortedColumns;
/// <summary>
/// The descriptions of sorted columns.
/// </summary>
public SortColumnDescriptions sortDescriptions
{
get => m_SortDescriptions;
protected internal set
{
m_SortDescriptions = value;
m_SortDescriptions.changed += UpdateSortedColumns;
UpdateSortedColumns();
}
}
/// <summary>
/// The list of columns.
/// </summary>
public Columns columns { get; }
/// <summary>
/// Gets or sets the value that indicates whether sorting is enabled.
/// </summary>
public bool sortingEnabled
{
get => m_SortingEnabled;
set
{
if (m_SortingEnabled == value)
return;
m_SortingEnabled = value;
UpdateSortingStatus();
UpdateSortedColumns();
}
}
/// <summary>
/// Sent whenever the column at the specified visual index is resized to the specified size.
/// </summary>
public event Action<int, float> columnResized;
/// <summary>
/// Sent whenever the column sorting status has changed.
/// </summary>
public event Action columnSortingChanged;
/// <summary>
/// Sent whenever a ContextMenuPopulate event sent allowing user code to add its own actions to the context menu.
/// </summary>
public event Action<ContextualMenuPopulateEvent, Column> contextMenuPopulateEvent;
/// <summary>
/// Sent whenever a ContextMenuPopulate event sent allowing user code to add its own actions to the context menu.
/// </summary>
internal event Action viewDataRestored;
/// <summary>
/// Default constructor.
/// </summary>
public MultiColumnCollectionHeader()
: this(new Columns(), new SortColumnDescriptions(), new List<SortColumnDescription>()) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="columns"></param>
/// <param name="sortDescriptions"></param>
/// <param name="sortedColumns"></param>
public MultiColumnCollectionHeader(Columns columns, SortColumnDescriptions sortDescriptions, List<SortColumnDescription> sortedColumns)
{
AddToClassList(ussClassName);
this.columns = columns;
m_SortedColumns = sortedColumns;
this.sortDescriptions = sortDescriptions;
columnContainer = new VisualElement()
{
pickingMode = PickingMode.Ignore
};
columnContainer.AddToClassList(columnContainerUssClassName);
Add(columnContainer);
//Ensure that the resize handlers are on top of the columns.
resizeHandleContainer = new VisualElement()
{
pickingMode = PickingMode.Ignore
};
resizeHandleContainer.AddToClassList(handleContainerUssClassName);
resizeHandleContainer.StretchToParentSize();
Add(resizeHandleContainer);
columnLayout = new ColumnLayout(columns);
columnLayout.layoutRequested += ScheduleDoLayout;
foreach (var column in columns.visibleList)
{
OnColumnAdded(column);
}
this.columns.columnAdded += OnColumnAdded;
this.columns.columnRemoved += OnColumnRemoved;
this.columns.columnChanged += OnColumnChanged;
this.columns.columnReordered += OnColumnReordered;
this.columns.columnResized += OnColumnResized;
this.AddManipulator(new ContextualMenuManipulator(OnContextualMenuManipulator));
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
void ScheduleDoLayout()
{
if (m_DoLayoutScheduled)
return;
schedule.Execute(DoLayout);
m_DoLayoutScheduled = true;
}
/// <summary>
/// Resizes all columns to fit the width of the header.
/// </summary>
void ResizeToFit()
{
columnLayout.ResizeToFit(layout.width);
}
/// <summary>
/// Updates the effective list of sorted columns.
/// </summary>
void UpdateSortedColumns()
{
if (m_SortingUpdatesTemporarilyDisabled)
return;
using (ListPool<SortedColumnState>.Get(out var sortedColumnStates))
{
if (sortingEnabled)
{
foreach (var desc in sortDescriptions)
{
Column column = null;
if (desc.columnIndex != -1)
column = columns[desc.columnIndex];
else if (!string.IsNullOrEmpty(desc.columnName))
column = columns[desc.columnName];
if (column != null && column.sortable)
{
desc.column = column;
sortedColumnStates.Add(new SortedColumnState(desc, desc.direction));
}
else
{
desc.column = null;
}
}
}
if (m_OldSortedColumnStates.SequenceEqual(sortedColumnStates))
return;
m_SortedColumns.Clear();
foreach (var state in sortedColumnStates)
{
m_SortedColumns.Add(state.columnDesc);
}
m_OldSortedColumnStates.CopyFrom(sortedColumnStates);
}
SaveViewState();
RaiseColumnSortingChanged();
}
/// <summary>
/// Update the column controls and resize handles from the columns.
/// </summary>
void UpdateColumnControls()
{
bool hasStretch = false;
Column lastVisibleColumn = null;
foreach (var col in columns.visibleList)
{
hasStretch |= col.stretchable;
ColumnData columnData = null;
if (columnDataMap.TryGetValue(col, out columnData))
{
columnData.control.style.minWidth = col.minWidth;
columnData.control.style.maxWidth = col.maxWidth;
columnData.resizeHandle.style.display = (columns.resizable && col.resizable) ? DisplayStyle.Flex : DisplayStyle.None;
}
lastVisibleColumn = col;
}
if (hasStretch)
{
columnContainer.style.flexGrow = 1;
// If there is at least one stretchable column then hide the last resizer
if (columns.stretchMode == Columns.StretchMode.GrowAndFill && columnDataMap.TryGetValue(lastVisibleColumn, out var columnData))
{
columnData.resizeHandle.style.display = DisplayStyle.None;
}
}
else
{
columnContainer.style.flexGrow = 0;
}
UpdateSortingStatus();
}
void OnColumnAdded(Column column, int index) => OnColumnAdded(column);
/// <summary>
/// Called whenever a column is added to the header.
/// </summary>
/// <param name="column"></param>
void OnColumnAdded(Column column)
{
// If the column was already added then ignore it
if (columnDataMap.ContainsKey(column))
return;
var columnElement = new MultiColumnHeaderColumn(column);
var resizeHandle = new MultiColumnHeaderColumnResizeHandle();
columnElement.RegisterCallback<GeometryChangedEvent>(OnColumnControlGeometryChanged);
columnElement.clickable.clickedWithEventInfo += OnColumnClicked;
// Prevent cursor change when hovering handles while drag reordering columns
columnElement.mover.activeChanged += OnMoveManipulatorActivated;
resizeHandle.dragArea.AddManipulator(new ColumnResizer(column));
columnDataMap[column] = new ColumnData()
{
control = columnElement,
resizeHandle = resizeHandle
};
if (column.visible)
{
columnContainer.Insert(column.visibleIndex, columnElement);
resizeHandleContainer.Insert(column.visibleIndex, resizeHandle);
}
else
{
OnColumnRemoved(column);
}
UpdateColumnControls();
SaveViewState();
}
/// <summary>
/// Called whenever a column is removed from the header.
/// </summary>
/// <param name="column"></param>
void OnColumnRemoved(Column column)
{
// If the column was not already added then ignore it
if (!columnDataMap.ContainsKey(column))
return;
var data = columnDataMap[column];
data.control.UnregisterCallback<GeometryChangedEvent>(OnColumnControlGeometryChanged);
data.control.clickable.clickedWithEventInfo -= OnColumnClicked;
data.control.mover.activeChanged -= OnMoveManipulatorActivated;
data.control.RemoveFromHierarchy();
data.resizeHandle.RemoveFromHierarchy();
columnDataMap.Remove(column);
UpdateColumnControls();
SaveViewState();
}
/// <summary>
/// Called whenever the data of a column has changed specifing the associated data role.
/// </summary>
/// <param name="column"></param>
/// <param name="type"></param>
void OnColumnChanged(Column column, ColumnDataType type)
{
if (type == ColumnDataType.Visibility)
{
if (column.visible)
OnColumnAdded(column);
else
OnColumnRemoved(column);
ApplyColumnSorting();
}
UpdateColumnControls();
if (type == ColumnDataType.Visibility)
SaveViewState();
}
/// <summary>
/// Called whenever a column is reordered.
/// </summary>
/// <param name="column"></param>
/// <param name="from"></param>
/// <param name="to"></param>
void OnColumnReordered(Column column, int from, int to)
{
if (!column.visible || from == to)
return;
if (columnDataMap.TryGetValue(column, out var columnData))
{
var index = column.visibleIndex;
if (index == columns.visibleList.Count() - 1)
{
columnData.control.BringToFront();
}
else
{
if (to > from)
++index;
columnData.control.PlaceBehind(columnContainer[index]);
columnData.resizeHandle.PlaceBehind(resizeHandleContainer[index]);
}
}
UpdateColumnControls();
SaveViewState();
}
/// <summary>
/// Called whenever a column is resized.
/// </summary>
void OnColumnResized(Column column)
{
SaveViewState();
}
/// <summary>
/// Called whenever a ContextualMenuPopulateEvent event is received.
/// </summary>
/// <param name="evt"></param>
void OnContextualMenuManipulator(ContextualMenuPopulateEvent evt)
{
Column columnUnderMouse = null;
bool canResizeToFit = this.columns.visibleList.Count() > 0;
foreach (var column in this.columns.visibleList)
{
if (this.columns.stretchMode == Columns.StretchMode.GrowAndFill && canResizeToFit && column.stretchable)
canResizeToFit = false;
if (columnUnderMouse == null)
{
if (columnDataMap.TryGetValue(column, out var data))
{
if (data.control.layout.Contains(evt.localMousePosition))
{
columnUnderMouse = column;
}
}
}
}
evt.menu.AppendAction("Resize To Fit", (a) => ResizeToFit(), canResizeToFit ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
evt.menu.AppendSeparator();
foreach (var column in this.columns)
{
var title = column.title;
if (string.IsNullOrEmpty(title))
title = column.name;
if (string.IsNullOrEmpty(title))
title = "Unnamed Column_" + column.index;
evt.menu.AppendAction(title,
(a) =>
{
column.visible = !column.visible;
}
,
(a) =>
{
if (!string.IsNullOrEmpty(column.name) && columns.primaryColumnName == column.name)
return DropdownMenuAction.Status.Disabled;
else if (!column.optional)
return DropdownMenuAction.Status.Disabled;
else if (column.visible)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
});
}
contextMenuPopulateEvent?.Invoke(evt, columnUnderMouse);
}
/// <summary>
/// Called whenever the move manipulator is activated.
/// </summary>
/// <param name="mover"></param>
void OnMoveManipulatorActivated(ColumnMover mover)
{
resizeHandleContainer.style.display = mover.active ? DisplayStyle.None : DisplayStyle.Flex;
}
/// <summary>
/// Called whenever the geometry of the header has changed.
/// </summary>
/// <param name="e"></param>
void OnGeometryChanged(GeometryChangedEvent e)
{
if (float.IsNaN(e.newRect.width) || float.IsNaN(e.newRect.height))
return;
columnLayout.Dirty();
if (e.layoutPass > kMaxStableLayoutPassCount)
{
ScheduleDoLayout();
}
else
{
// Force the layout to be computed right away
DoLayout();
}
}
/// <summary>
/// Performs layout of columns.
/// </summary>
void DoLayout()
{
columnLayout.DoLayout(layout.width);
m_DoLayoutScheduled = false;
}
/// <summary>
/// Called when the geometry of a column control has changed.
/// </summary>
/// <param name="evt"></param>
void OnColumnControlGeometryChanged(GeometryChangedEvent evt)
{
if (!(evt.target is MultiColumnHeaderColumn columnControl))
return;
var controlData = columnDataMap[columnControl.column];
controlData.resizeHandle.style.left = columnControl.layout.xMax;
if (Math.Abs(evt.newRect.width - evt.oldRect.width) < float.Epsilon)
return;
RaiseColumnResized(columnContainer.IndexOf(evt.elementTarget));
}
/// <summary>
/// Called whenever a column is clicked.
/// </summary>
/// <param name="evt"></param>
void OnColumnClicked(EventBase evt)
{
if (!sortingEnabled)
return;
var columnControl = evt.currentTarget as MultiColumnHeaderColumn;
if (columnControl == null || !columnControl.column.sortable)
{
return;
}
EventModifiers modifiers;
if (evt is IPointerEvent ptEvt)
modifiers = ptEvt.modifiers;
else if (evt is IMouseEvent msEvt)
modifiers = msEvt.modifiers;
else
return;
m_SortingUpdatesTemporarilyDisabled = true;
try
{
UpdateSortColumnDescriptionsOnClick(columnControl.column, modifiers);
}
finally
{
m_SortingUpdatesTemporarilyDisabled = false;
}
UpdateSortedColumns();
}
/// <summary>
/// Updates the list of sort column descriptions upon click on a column.
/// </summary>
/// <param name="column">The clicked column</param>
/// <param name="modifiers">The modifiers of the pointer event</param>
void UpdateSortColumnDescriptionsOnClick(Column column, EventModifiers modifiers)
{
var desc = sortDescriptions.FirstOrDefault((d) => (d.column == column || (!string.IsNullOrEmpty(column.name) && d.columnName == column.name) || d.columnIndex == column.index));
// If a sort description matching the column is found then ...
if (desc != null)
{
// If Shift is pressed then unsort the column
if (modifiers == EventModifiers.Shift)
{
sortDescriptions.Remove(desc);
return;
}
// otherwise, flip the sort direction
desc.direction = desc.direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
}
// otherwise, create a new sort description in ascending order
else
{
desc = string.IsNullOrEmpty(column.name) ? new SortColumnDescription(column.index, SortDirection.Ascending) :
new SortColumnDescription(column.name, SortDirection.Ascending);
}
// If multi sort is not active then clear
EventModifiers multiSortingModifier = EventModifiers.Control;
if (Application.platform is RuntimePlatform.OSXEditor or RuntimePlatform.OSXPlayer)
{
multiSortingModifier = EventModifiers.Command;
}
if (modifiers != multiSortingModifier)
{
sortDescriptions.Clear();
}
if (!sortDescriptions.Contains(desc))
{
sortDescriptions.Add(desc);
}
}
public void ScrollHorizontally(float horizontalOffset)
{
transform.position = new Vector3(-horizontalOffset, transform.position.y, transform.position.z);
}
void RaiseColumnResized(int columnIndex)
{
columnResized?.Invoke(columnIndex, columnContainer[columnIndex].resolvedStyle.width);
}
void RaiseColumnSortingChanged()
{
ApplyColumnSorting();
if (!m_ApplyingViewState)
columnSortingChanged?.Invoke();
}
void ApplyColumnSorting()
{
foreach (var column in columns.visibleList)
{
if (!columnDataMap.TryGetValue(column, out var columnData))
{
continue;
}
columnData.control.sortOrderLabel = "";
columnData.control.RemoveFromClassList(MultiColumnHeaderColumn.sortedAscendingUssClassName);
columnData.control.RemoveFromClassList(MultiColumnHeaderColumn.sortedDescendingUssClassName);
}
var sortedColumnDataList = new List<ColumnData>();
foreach (var sortedColumn in sortedColumns)
{
if (columnDataMap.TryGetValue(sortedColumn.column, out var columnData))
{
sortedColumnDataList.Add(columnData);
if (sortedColumn.direction == SortDirection.Ascending)
columnData.control.AddToClassList(MultiColumnHeaderColumn.sortedAscendingUssClassName);
else
columnData.control.AddToClassList(MultiColumnHeaderColumn.sortedDescendingUssClassName);
}
}
if (sortedColumnDataList.Count > 1)
{
for (int i = 0; i < sortedColumnDataList.Count; ++i)
{
sortedColumnDataList[i].control.sortOrderLabel = (i + 1).ToString();
}
}
}
void UpdateSortingStatus()
{
bool hasSortableColumns = false;
foreach (var column in columns.visibleList)
{
if (!columnDataMap.TryGetValue(column, out var columnData))
{
continue;
}
if (sortingEnabled && column.sortable)
hasSortableColumns = true;
}
foreach (var column in columns.visibleList)
{
if (!columnDataMap.TryGetValue(column, out var columnData))
{
continue;
}
if (hasSortableColumns)
{
columnData.control.AddToClassList(MultiColumnHeaderColumn.sortableUssClassName);
}
else
{
columnData.control.RemoveFromClassList(MultiColumnHeaderColumn.sortableUssClassName);
}
}
}
internal override void OnViewDataReady()
{
try
{
m_ApplyingViewState = true;
base.OnViewDataReady();
var key = GetFullHierarchicalViewDataKey();
m_ViewState = GetOrCreateViewData<ViewState>(m_ViewState, key);
m_ViewState.Apply(this);
viewDataRestored?.Invoke();
}
finally
{
m_ApplyingViewState = false;
}
}
void SaveViewState()
{
if (m_ApplyingViewState)
return;
m_ViewState?.Save(this);
SaveViewData();
}
public void Dispose()
{
sortDescriptions.changed -= UpdateSortedColumns;
columnLayout.layoutRequested -= ScheduleDoLayout;
columns.columnAdded -= OnColumnAdded;
columns.columnRemoved -= OnColumnRemoved;
columns.columnChanged -= OnColumnChanged;
columns.columnReordered -= OnColumnReordered;
columns.columnResized -= OnColumnResized;
foreach (var data in columnDataMap.Values)
{
data.control.clickable.clickedWithEventInfo -= OnColumnClicked;
data.control.mover.activeChanged -= OnMoveManipulatorActivated;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnCollectionHeader.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnCollectionHeader.cs",
"repo_id": "UnityCsReference",
"token_count": 15072
} | 492 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
/// <summary>
/// A slider containing floating point values. For more information, refer to [[wiki:UIE-uxml-element-slider|UXML element Slider]].
/// </summary>
public class Slider : BaseSlider<float>
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : BaseSlider<float>.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] float lowValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags lowValue_UxmlAttributeFlags;
[SerializeField] float highValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags highValue_UxmlAttributeFlags;
[SerializeField] float pageSize;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags pageSize_UxmlAttributeFlags;
[SerializeField] bool showInputField;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags showInputField_UxmlAttributeFlags;
[SerializeField] SliderDirection direction;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags direction_UxmlAttributeFlags;
[SerializeField] bool inverted;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags inverted_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new Slider();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (Slider)obj;
if (ShouldWriteAttributeValue(lowValue_UxmlAttributeFlags))
e.lowValue = lowValue;
if (ShouldWriteAttributeValue(highValue_UxmlAttributeFlags))
e.highValue = highValue;
if (ShouldWriteAttributeValue(direction_UxmlAttributeFlags))
e.direction = direction;
if (ShouldWriteAttributeValue(pageSize_UxmlAttributeFlags))
e.pageSize = pageSize;
if (ShouldWriteAttributeValue(showInputField_UxmlAttributeFlags))
e.showInputField = showInputField;
if (ShouldWriteAttributeValue(inverted_UxmlAttributeFlags))
e.inverted = inverted;
}
}
/// <summary>
/// Instantiates a <see cref="Slider"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<Slider, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="Slider"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : UxmlTraits<UxmlFloatAttributeDescription>
{
UxmlFloatAttributeDescription m_LowValue = new UxmlFloatAttributeDescription { name = "low-value" };
UxmlFloatAttributeDescription m_HighValue = new UxmlFloatAttributeDescription { name = "high-value", defaultValue = kDefaultHighValue };
UxmlFloatAttributeDescription m_PageSize = new UxmlFloatAttributeDescription { name = "page-size", defaultValue = kDefaultPageSize };
UxmlBoolAttributeDescription m_ShowInputField = new UxmlBoolAttributeDescription { name = "show-input-field", defaultValue = kDefaultShowInputField };
UxmlEnumAttributeDescription<SliderDirection> m_Direction = new UxmlEnumAttributeDescription<SliderDirection> { name = "direction", defaultValue = SliderDirection.Horizontal };
UxmlBoolAttributeDescription m_Inverted = new UxmlBoolAttributeDescription { name = "inverted", defaultValue = kDefaultInverted };
/// <summary>
/// Initialize <see cref="Slider"/> properties using values from the attribute bag.
/// </summary>
/// <param name="ve">The object to initialize.</param>
/// <param name="bag">The attribute bag.</param>
/// <param name="cc">The creation context; unused.</param>
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
var f = (Slider)ve;
f.lowValue = m_LowValue.GetValueFromBag(bag, cc);
f.highValue = m_HighValue.GetValueFromBag(bag, cc);
f.direction = m_Direction.GetValueFromBag(bag, cc);
f.pageSize = m_PageSize.GetValueFromBag(bag, cc);
f.showInputField = m_ShowInputField.GetValueFromBag(bag, cc);
f.inverted = m_Inverted.GetValueFromBag(bag, cc);
base.Init(ve, bag, cc);
}
}
internal const float kDefaultHighValue = 10.0f;
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-slider";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// Creates a new instance of a Slider.
/// </summary>
public Slider()
: this((string)null, 0, kDefaultHighValue) {}
/// <summary>
/// Creates a new instance of a Slider.
/// </summary>
/// <param name="start">The minimum value that the slider encodes.</param>
/// <param name="end">The maximum value that the slider encodes.</param>
/// <param name="direction">The direction of the slider (Horizontal or Vertical).</param>
/// <param name="pageSize">A generic page size used to change the value when clicking in the slider.</param>
public Slider(float start, float end, SliderDirection direction = SliderDirection.Horizontal, float pageSize = kDefaultPageSize)
: this(null, start, end, direction, pageSize) {}
/// <summary>
/// Creates a new instance of a Slider.
/// </summary>
/// <param name="label">The string representing the label that will appear beside the field.</param>
/// <param name="start">The minimum value that the slider encodes.</param>
/// <param name="end">The maximum value that the slider encodes.</param>
/// <param name="direction">The direction of the slider (Horizontal or Vertical).</param>
/// <param name="pageSize">A generic page size used to change the value when clicking in the slider.</param>
public Slider(string label, float start = 0, float end = kDefaultHighValue, SliderDirection direction = SliderDirection.Horizontal, float pageSize = kDefaultPageSize)
: base(label, start, end, direction, pageSize)
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
visualInput.AddToClassList(inputUssClassName);
}
/// <inheritdoc />
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, float startValue)
{
double sensitivity = NumericFieldDraggerUtility.CalculateFloatDragSensitivity(startValue, lowValue, highValue);
float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow);
double v = value;
v += NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity;
value = (float)v;
}
internal override float SliderLerpUnclamped(float a, float b, float interpolant)
{
var newValue = Mathf.LerpUnclamped(a, b, interpolant);
// The purpose of this code is to reproduce the same rounding as IMGUI, based on min/max values and container size.
// Equivalent of UnityEditor.MathUtils.RoundBasedOnMinimumDifference
var minDifference = Mathf.Abs((highValue - lowValue) / (dragContainer.resolvedStyle.width - dragElement.resolvedStyle.width));
var numOfDecimalsForMinDifference = minDifference == 0.0f ?
Mathf.Clamp((int)(5.0 - Mathf.Log10(Mathf.Abs(minDifference))), 0, 15) :
Mathf.Clamp(-Mathf.FloorToInt(Mathf.Log10(Mathf.Abs(minDifference))), 0, 15);
var valueRoundedBasedOnMinimumDifference = (float)Math.Round(newValue, numOfDecimalsForMinDifference, MidpointRounding.AwayFromZero);
return valueRoundedBasedOnMinimumDifference;
}
internal override float SliderNormalizeValue(float currentValue, float lowerValue, float higherValue)
{
return (currentValue - lowerValue) / (higherValue - lowerValue);
}
internal override float SliderRange()
{
return Math.Abs(highValue - lowValue);
}
internal override float ParseStringToValue(string previousValue, string newValue)
{
if (UINumericFieldsUtils.TryConvertStringToFloat(newValue, previousValue, out var value))
return value;
return 0;
}
internal override void ComputeValueFromKey(SliderKey sliderKey, bool isShift)
{
switch (sliderKey)
{
case SliderKey.None:
return;
case SliderKey.Lowest:
value = lowValue;
return;
case SliderKey.Highest:
value = highValue;
return;
}
bool isPageSize = sliderKey == SliderKey.LowerPage || sliderKey == SliderKey.HigherPage;
// Change by approximately 1/100 of entire range, or 1/10 if holding down shift
// But round to nearest power of ten to get nice resulting numbers.
var delta = GetClosestPowerOfTen(Mathf.Abs((highValue - lowValue) * 0.01f));
if (isPageSize)
delta *= pageSize;
else if (isShift)
delta *= 10;
// Increment or decrement by just over half the delta.
// This means that e.g. if delta is 1, incrementing from 1.0 will go to 2.0,
// but incrementing from 0.9 is going to 1.0 rather than 2.0.
// This feels more right since 1.0 is the "next" one.
if (sliderKey == SliderKey.Lower || sliderKey == SliderKey.LowerPage)
delta = -delta;
// Now round to a multiple of our delta value so we get a round end result instead of just a round delta.
value = RoundToMultipleOf(value + (delta * 0.5001f), Mathf.Abs(delta));
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/Slider.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Slider.cs",
"repo_id": "UnityCsReference",
"token_count": 4582
} | 493 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Globalization;
namespace UnityEngine.UIElements
{
/// <summary>
/// Makes a text field for entering unsigned long integers. For more information, refer to [[wiki:UIE-uxml-element-UnsignedLongField|UXML element UnsignedLongField]].
/// </summary>
public class UnsignedLongField : TextValueField<ulong>
{
// This property to alleviate the fact we have to cast all the time
UnsignedLongInput unsignedLongInput => (UnsignedLongInput)textInputBase;
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : TextValueField<ulong>.UxmlSerializedData
{
public override object CreateInstance() => new UnsignedLongField();
}
/// <summary>
/// Instantiates a <see cref="UnsignedLongField"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<UnsignedLongField, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="UnsignedLongField"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : TextValueFieldTraits<ulong, UxmlUnsignedLongAttributeDescription> {}
/// <summary>
/// Converts the given unsigned long integer to a string.
/// </summary>
/// <param name="v">The unsigned long integer to be converted to string.</param>
/// <returns>The ulong integer as string.</returns>
protected override string ValueToString(ulong v)
{
return v.ToString(formatString, CultureInfo.InvariantCulture.NumberFormat);
}
/// <summary>
/// Converts a string to a unsigned long integer.
/// </summary>
/// <param name="str">The string to convert.</param>
/// <returns>The unsigned long integer parsed from the string.</returns>
protected override ulong StringToValue(string str)
{
var success = UINumericFieldsUtils.TryConvertStringToULong(str, textInputBase.originalText, out var v);
return success ? v : rawValue;
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-unsigned-long-field";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// Constructor.
/// </summary>
public UnsignedLongField()
: this((string)null) {}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="maxLength">Maximum number of characters the field can take.</param>
public UnsignedLongField(int maxLength)
: this(null, maxLength) {}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="maxLength">Maximum number of characters the field can take.</param>
public UnsignedLongField(string label, int maxLength = kMaxValueFieldLength)
: base(label, maxLength, new UnsignedLongInput())
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
visualInput.AddToClassList(inputUssClassName);
AddLabelDragger<ulong>();
}
internal override bool CanTryParse(string textString) => ulong.TryParse(textString, out _);
/// <summary>
/// Applies the values of a 3D delta and a speed from an input device.
/// </summary>
/// <param name="delta">A vector used to compute the value change.</param>
/// <param name="speed">A multiplier for the value change.</param>
/// <param name="startValue">The start value.</param>
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, ulong startValue)
{
unsignedLongInput.ApplyInputDeviceDelta(delta, speed, startValue);
}
class UnsignedLongInput : TextValueInput
{
UnsignedLongField parentUnsignedLongField => (UnsignedLongField)parent;
internal UnsignedLongInput()
{
formatString = UINumericFieldsUtils.k_IntFieldFormatString;
}
protected override string allowedCharacters => UINumericFieldsUtils.k_AllowedCharactersForInt;
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, ulong startValue)
{
double sensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(startValue);
var acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow);
var v = StringToValue(text);
var niceDelta = (long)Math.Round(NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity);
v = ClampToMinMaxULongValue(niceDelta, v);
if (parentUnsignedLongField.isDelayed)
{
text = ValueToString(v);
}
else
{
parentUnsignedLongField.value = v;
}
}
private ulong ClampToMinMaxULongValue(long niceDelta, ulong value)
{
var niceDeltaAbs = (ulong)Math.Abs(niceDelta);
if (niceDelta > 0)
{
if (niceDeltaAbs > ulong.MaxValue - value)
{
return ulong.MaxValue;
}
return value + niceDeltaAbs;
}
if (niceDeltaAbs > value)
{
return ulong.MinValue;
}
return value - niceDeltaAbs;
}
protected override string ValueToString(ulong v)
{
return v.ToString(formatString);
}
protected override ulong StringToValue(string str)
{
UINumericFieldsUtils.TryConvertStringToULong(str, originalText, out var v);
return v;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/UnsignedLongField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/UnsignedLongField.cs",
"repo_id": "UnityCsReference",
"token_count": 2915
} | 494 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Pool;
using UnityEngine.UIElements.Experimental;
namespace UnityEngine.UIElements
{
/// <summary>
/// Defines the structure of a callback that can be registered onto an element for an event type
/// </summary>
/// <param name="evt">The event instance</param>
/// <typeparam name="TEventType">The type of event to register the callback for</typeparam>
public delegate void EventCallback<in TEventType>(TEventType evt);
/// <summary>
/// Defines the structure of a callback that can be registered onto an element for an event type,
/// along with a custom user defined argument.
/// </summary>
/// <param name="evt">The event instance.</param>
/// <param name="userArgs">The user argument instance.</param>
/// <typeparam name="TEventType">The type of event registered for the callback.</typeparam>
/// <typeparam name="TCallbackArgs">The type of the user argument.</typeparam>
public delegate void EventCallback<in TEventType, in TCallbackArgs>(TEventType evt, TCallbackArgs userArgs);
internal abstract class EventCallbackFunctorBase : IDisposable
{
public long eventTypeId;
public InvokePolicy invokePolicy;
public abstract void Invoke(EventBase evt);
public abstract void UnregisterCallback(CallbackEventHandler target, TrickleDown useTrickleDown);
public abstract void Dispose();
// The eventTypeId is necessary because we allow the same callback to be registered for multiple event types
public abstract bool IsEquivalentTo(long eventTypeId, Delegate callback);
}
internal class EventCallbackFunctor<TEventType> : EventCallbackFunctorBase
where TEventType : EventBase<TEventType>, new()
{
EventCallback<TEventType> m_Callback;
public static EventCallbackFunctor<TEventType> GetPooled(long eventTypeId, EventCallback<TEventType> callback,
InvokePolicy invokePolicy = InvokePolicy.Default)
{
var self = GenericPool<EventCallbackFunctor<TEventType>>.Get();
self.eventTypeId = eventTypeId;
self.invokePolicy = invokePolicy;
self.m_Callback = callback;
return self;
}
public override void Dispose()
{
eventTypeId = default;
invokePolicy = default;
m_Callback = default;
GenericPool<EventCallbackFunctor<TEventType>>.Release(this);
}
public override void Invoke(EventBase evt)
{
using (new EventDebuggerLogCall(m_Callback, evt))
{
m_Callback(evt as TEventType);
}
}
public override void UnregisterCallback(CallbackEventHandler target, TrickleDown useTrickleDown)
{
target.UnregisterCallback(m_Callback, useTrickleDown);
}
public override bool IsEquivalentTo(long eventTypeId, Delegate callback)
{
return this.eventTypeId == eventTypeId && (Delegate)m_Callback == callback;
}
}
internal class EventCallbackFunctor<TEventType, TCallbackArgs> : EventCallbackFunctorBase
where TEventType : EventBase<TEventType>, new()
{
EventCallback<TEventType, TCallbackArgs> m_Callback;
internal TCallbackArgs userArgs { get; set; }
public static EventCallbackFunctor<TEventType, TCallbackArgs> GetPooled(long eventTypeId,
EventCallback<TEventType, TCallbackArgs> callback, TCallbackArgs userArgs,
InvokePolicy invokePolicy = InvokePolicy.Default)
{
var self = GenericPool<EventCallbackFunctor<TEventType, TCallbackArgs>>.Get();
self.eventTypeId = eventTypeId;
self.invokePolicy = invokePolicy;
self.userArgs = userArgs;
self.m_Callback = callback;
return self;
}
public override void Dispose()
{
eventTypeId = default;
invokePolicy = default;
userArgs = default;
m_Callback = default;
GenericPool<EventCallbackFunctor<TEventType, TCallbackArgs>>.Release(this);
}
public override void Invoke(EventBase evt)
{
using (new EventDebuggerLogCall(m_Callback, evt))
{
m_Callback(evt as TEventType, userArgs);
}
}
public override void UnregisterCallback(CallbackEventHandler target, TrickleDown useTrickleDown)
{
target.UnregisterCallback(m_Callback, useTrickleDown);
}
public override bool IsEquivalentTo(long eventTypeId, Delegate callback)
{
return this.eventTypeId == eventTypeId && (Delegate)m_Callback == callback;
}
}
}
| UnityCsReference/Modules/UIElements/Core/Events/EventCallback.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/EventCallback.cs",
"repo_id": "UnityCsReference",
"token_count": 1910
} | 495 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements
{
/// <summary>
/// Interface for panel change events.
/// </summary>
public interface IPanelChangedEvent
{
}
/// <summary>
/// Abstract base class for events notifying of a panel change.
/// </summary>
[EventCategory(EventCategory.ChangePanel)]
public abstract class PanelChangedEventBase<T> : EventBase<T>, IPanelChangedEvent where T : PanelChangedEventBase<T>, new()
{
/// <summary>
/// In the case of AttachToPanelEvent, the panel to which the event target element was attached. In the case of DetachFromPanelEvent, the panel from which the event target element is detached.
/// </summary>
public IPanel originPanel { get; private set; }
/// <summary>
/// In the case of AttachToPanelEvent, the panel to which the event target element is now attached. In the case of DetachFromPanelEvent, the panel to which the event target element will be attached.
/// </summary>
public IPanel destinationPanel { get; private set; }
/// <summary>
/// Resets the event members to their initial values.
/// </summary>
protected override void Init()
{
base.Init();
LocalInit();
}
void LocalInit()
{
originPanel = null;
destinationPanel = null;
}
/// <summary>
/// Gets an event from the event pool and initializes it with the given values. Use this function instead of creating new events. Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them.
/// </summary>
/// <param name="originPanel">Sets the originPanel property of the event.</param>
/// <param name="destinationPanel">Sets the destinationPanel property of the event.</param>
/// <returns>An initialized event.</returns>
public static T GetPooled(IPanel originPanel, IPanel destinationPanel)
{
T e = GetPooled();
e.originPanel = originPanel;
e.destinationPanel = destinationPanel;
return e;
}
protected PanelChangedEventBase()
{
LocalInit();
}
}
/// <summary>
/// Event sent after an element is added to an element that is a descendent of a panel.
/// </summary>
public class AttachToPanelEvent : PanelChangedEventBase<AttachToPanelEvent>
{
static AttachToPanelEvent()
{
SetCreateFunction(() => new AttachToPanelEvent());
}
}
/// <summary>
/// Event sent just before an element is detach from its parent, if the parent is the descendant of a panel.
/// </summary>
public class DetachFromPanelEvent : PanelChangedEventBase<DetachFromPanelEvent>
{
static DetachFromPanelEvent()
{
SetCreateFunction(() => new DetachFromPanelEvent());
}
}
}
| UnityCsReference/Modules/UIElements/Core/Events/PanelEvents.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/PanelEvents.cs",
"repo_id": "UnityCsReference",
"token_count": 1155
} | 496 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
namespace UnityEngine.UIElements
{
internal class UIDocumentList
{
internal List<UIDocument> m_AttachedUIDocuments = new List<UIDocument>();
internal void RemoveFromListAndFromVisualTree(UIDocument uiDocument)
{
m_AttachedUIDocuments.Remove(uiDocument);
uiDocument.rootVisualElement?.RemoveFromHierarchy();
}
internal void AddToListAndToVisualTree(UIDocument uiDocument, VisualElement visualTree, int firstInsertIndex = 0)
{
int index = 0;
foreach (var sibling in m_AttachedUIDocuments)
{
if (uiDocument.sortingOrder > sibling.sortingOrder)
{
index++;
continue;
}
if (uiDocument.sortingOrder < sibling.sortingOrder)
{
break;
}
// They're the same value, compare their count (UIDocuments created first show up first).
if (uiDocument.m_UIDocumentCreationIndex > sibling.m_UIDocumentCreationIndex)
{
index++;
continue;
}
break;
}
if (index < m_AttachedUIDocuments.Count)
{
m_AttachedUIDocuments.Insert(index, uiDocument);
if (visualTree == null || uiDocument.rootVisualElement == null)
{
return;
}
// Not every UIDocument is in the tree already (because their root is null, for example), so we need
// to figure out the insertion point.
if (index > 0)
{
VisualElement previousInTree = null;
int i = 1;
while (previousInTree == null && index - i >= 0)
{
var previousUIDocument = m_AttachedUIDocuments[index - i++];
previousInTree = previousUIDocument.rootVisualElement;
}
if (previousInTree != null)
{
index = visualTree.IndexOf(previousInTree) + 1;
}
}
if (index > visualTree.childCount)
{
index = visualTree.childCount;
}
}
else
{
// Add in the end.
m_AttachedUIDocuments.Add(uiDocument);
}
if (visualTree == null || uiDocument.rootVisualElement == null)
{
return;
}
int insertionIndex = firstInsertIndex + index;
if (insertionIndex < visualTree.childCount)
{
visualTree.Insert(insertionIndex, uiDocument.rootVisualElement);
}
else
{
visualTree.Add(uiDocument.rootVisualElement);
}
}
}
/// <summary>
/// Defines a Component that connects VisualElements to GameObjects. This makes it
/// possible to render UI defined in UXML documents in the Game view.
/// </summary>
[HelpURL("UIE-get-started-with-runtime-ui")]
[AddComponentMenu("UI Toolkit/UI Document"), ExecuteAlways, DisallowMultipleComponent]
[DefaultExecutionOrder(-100)] // UIDocument's OnEnable should run before user's OnEnable
public sealed class UIDocument : MonoBehaviour
{
internal const string k_RootStyleClassName = "unity-ui-document__root";
internal const string k_VisualElementNameSuffix = "-container";
private const int k_DefaultSortingOrder = 0;
// We count instances of UIDocument to be able to insert UIDocuments that have the same sort order in a
// deterministic way (i.e. instances created before will be placed before in the visual tree).
private static int s_CurrentUIDocumentCounter = 0;
internal readonly int m_UIDocumentCreationIndex;
internal static Func<bool> IsEditorPlaying;
internal static Func<bool> IsEditorPlayingOrWillChangePlaymode;
[SerializeField]
private PanelSettings m_PanelSettings;
// For Reset, we need to always keep track of what our previous PanelSettings was so we can react to being
// removed from it (as our PanelSettings becomes null in that operation).
private PanelSettings m_PreviousPanelSettings = null;
/// <summary>
/// Specifies the PanelSettings instance to connect this UIDocument component to.
/// </summary>
/// <remarks>
/// The Panel Settings asset defines the panel that renders UI in the game view. See <see cref="PanelSettings"/>.
///
/// If this UIDocument has a parent UIDocument, it uses the parent's PanelSettings automatically.
/// </remarks>
public PanelSettings panelSettings
{
get
{
return m_PanelSettings;
}
set
{
if (parentUI == null)
{
if (m_PanelSettings == value)
{
m_PreviousPanelSettings = m_PanelSettings;
return;
}
if (m_PanelSettings != null)
{
m_PanelSettings.DetachUIDocument(this);
}
m_PanelSettings = value;
if (m_PanelSettings != null)
{
SetupVisualTreeAssetTracker();
m_PanelSettings.AttachAndInsertUIDocumentToVisualTree(this);
}
}
else
{
// Children only hold the same instance as the parent, they don't attach themselves directly.
Assert.AreEqual(parentUI.m_PanelSettings, value);
m_PanelSettings = parentUI.m_PanelSettings;
}
if (m_ChildrenContent != null)
{
// Guarantee changes to panel settings trickles down the hierarchy.
foreach (var child in m_ChildrenContent.m_AttachedUIDocuments)
{
child.panelSettings = m_PanelSettings;
}
}
m_PreviousPanelSettings = m_PanelSettings;
}
}
/// <summary>
/// If the GameObject that this UIDocument component is attached to has a parent GameObject, and
/// that parent GameObject also has a UIDocument component attached to it, this value is set to
/// the parent GameObject's UIDocument component automatically.
/// </summary>
/// <remarks>
/// If a UIDocument has a parent, you cannot add it directly to a panel. Unity adds it to
/// the parent's root visual element instead.
/// </remarks>
public UIDocument parentUI
{
get => m_ParentUI;
private set => m_ParentUI = value;
}
[SerializeField]
private UIDocument m_ParentUI;
// If this UIDocument has UIDocument children (1st level only, 2nd level would be the child's
// children), they're added to this list instead of to the PanelSetting's list.
private UIDocumentList m_ChildrenContent = null;
private List<UIDocument> m_ChildrenContentCopy = null;
[SerializeField]
private VisualTreeAsset sourceAsset;
/// <summary>
/// The <see cref="VisualTreeAsset"/> loaded into the root visual element automatically.
/// </summary>
/// <remarks>
/// If you leave this empty, the root visual element is also empty.
/// </remarks>
public VisualTreeAsset visualTreeAsset
{
get { return sourceAsset; }
set
{
sourceAsset = value;
RecreateUI();
}
}
private VisualElement m_RootVisualElement;
private BaseRuntimePanel m_RuntimePanel;
/// <summary>
/// The root visual element where the UI hierarchy starts.
/// </summary>
public VisualElement rootVisualElement
{
get { return m_RootVisualElement; }
}
private int m_FirstChildInsertIndex;
internal int firstChildInserIndex
{
get => m_FirstChildInsertIndex;
}
[SerializeField]
private float m_SortingOrder = k_DefaultSortingOrder;
internal enum WorldSpaceSizeMode
{
Dynamic,
Fixed
}
[SerializeField]
private WorldSpaceSizeMode m_WorldSpaceSizeMode = WorldSpaceSizeMode.Fixed;
internal WorldSpaceSizeMode worldSpaceSizeMode => m_WorldSpaceSizeMode;
[SerializeField]
private float m_WorldSpaceWidth = 1920;
[SerializeField]
private float m_WorldSpaceHeight = 1080;
/// <summary>
/// The order in which this UIDocument will show up on the hierarchy in relation to other UIDocuments either
/// attached to the same PanelSettings, or with the same UIDocument parent.
/// </summary>
public float sortingOrder
{
get => m_SortingOrder;
set
{
if (m_SortingOrder == value)
{
return;
}
m_SortingOrder = value;
ApplySortingOrder();
}
}
internal void ApplySortingOrder()
{
AddRootVisualElementToTree();
}
internal static Func<UIDocument, ILiveReloadAssetTracker<VisualTreeAsset>> CreateLiveReloadVisualTreeAssetTracker;
private ILiveReloadAssetTracker<VisualTreeAsset> m_LiveReloadVisualTreeAssetTracker;
// Private constructor so it's not present on the public API file.
private UIDocument()
{
m_UIDocumentCreationIndex = s_CurrentUIDocumentCounter++;
}
private void Awake()
{
if (IsEditorPlayingOrWillChangePlaymode.Invoke() && !IsEditorPlaying.Invoke())
{
// We're in a weird transition state that causes an error with the logic below so let's skip it.
return;
}
// By default, the UI Content will try to attach itself to a parent somewhere in the hierarchy.
// This is done to mimic the behaviour we get from UGUI's Canvas/Game Object relationship.
SetupFromHierarchy();
}
private void OnEnable()
{
if (IsEditorPlayingOrWillChangePlaymode.Invoke() && !IsEditorPlaying.Invoke())
{
// We're in a weird transition state that causes an error with the logic below so let's skip it.
return;
}
if (parentUI != null && m_PanelSettings == null)
{
// Ensures we have the same PanelSettings set as our parent, as the
// initialization of the parent may have happened after ours.
m_PanelSettings = parentUI.m_PanelSettings;
}
if (m_RootVisualElement == null)
{
RecreateUI();
}
else
{
AddRootVisualElementToTree();
}
ResolveRuntimePanel();
}
void ResolveRuntimePanel()
{
if (m_RuntimePanel == null)
m_RuntimePanel = rootVisualElement.panel as BaseRuntimePanel;
}
bool m_RootHasWorldTransform;
void LateUpdate()
{
if (m_RootVisualElement == null || panelSettings == null || panelSettings.panel == null)
return;
AddOrRemoveRendererComponent();
if (!panelSettings.panel.isFlat)
{
// TODO: In editor we may loose the m_RuntimePanel connection when manipulation
// the hierarchy. This is weird and should be investigated.
ResolveRuntimePanel();
SetTransform();
UpdateRenderer();
}
else if (m_RootHasWorldTransform)
ClearTransform();
}
void UpdateRenderer()
{
UIRenderer renderer;
if (!TryGetComponent<UIRenderer>(out renderer))
{
rootVisualElement.uiRenderer = null;
UpdateCutRenderChainFlag();
return;
}
rootVisualElement.uiRenderer = renderer;
renderer.skipRendering = (parentUI != null); // Don't render embedded documents which will be rendered as part of their parents
BaseRuntimePanel rtp = (BaseRuntimePanel)m_RootVisualElement.panel;
if (rtp == null)
return;
Debug.Assert(rtp.drawsInCameras);
float ppu = m_RuntimePanel == null ? 1.0f : m_RuntimePanel.pixelsPerUnit;
if (ppu < UIRUtility.k_Epsilon)
ppu = Panel.k_DefaultPixelsPerUnit;
float ppuScale = 1.0f / ppu;
// TODO: Compute actual aabb by accounting for 3D transforms.
var rect = rootVisualElement.boundingBox;
var center = rect.center;
center.y = -center.y;
renderer.localBounds = new Bounds(center * ppuScale, new Vector3(rect.width * ppuScale, rect.height * ppuScale, 0.0f));
UpdateCutRenderChainFlag();
}
void AddOrRemoveRendererComponent()
{
// Automatically add the UIRenderer component when working in world-space
TryGetComponent<UIRenderer>(out var renderer);
if (m_PanelSettings != null && m_PanelSettings.panel?.drawsInCameras == true)
{
if (renderer == null)
gameObject.AddComponent<UIRenderer>();
}
else
{
UIRUtility.Destroy(renderer);
}
}
void UpdateCutRenderChainFlag()
{
// Every UIDocument associated with a world-space panel should cut the render-chain.
// If we don't, some UIDocument may try to render from the main thread, or risk being
// rendered as part of a previous UIDocument.
bool shouldCutRenderChain = (parentUI == null);
if (rootVisualElement.shouldCutRenderChain != shouldCutRenderChain)
{
rootVisualElement.shouldCutRenderChain = shouldCutRenderChain;
rootVisualElement.MarkDirtyRepaint(); // Necessary to insert a CutRenderChain command
}
}
void SetTransform()
{
Matrix4x4 matrix;
ComputeTransform(transform, out matrix);
m_RootVisualElement.style.transformOrigin = new TransformOrigin(Vector3.zero);
m_RootVisualElement.style.translate = new Translate(matrix.GetPosition());
m_RootVisualElement.style.rotate = new Rotate(matrix.rotation);
m_RootVisualElement.style.scale = new Scale(matrix.lossyScale);
m_RootHasWorldTransform = true;
}
void ClearTransform()
{
m_RootVisualElement.style.transformOrigin = StyleKeyword.Null;
m_RootVisualElement.style.translate = StyleKeyword.Null;
m_RootVisualElement.style.rotate = StyleKeyword.Null;
m_RootVisualElement.style.scale = StyleKeyword.Null;
m_RootHasWorldTransform = false;
}
void ComputeTransform(Transform transform, out Matrix4x4 matrix)
{
// This is the root, apply the pixels-per-unit scaling, and the y-flip.
float ppu = m_RuntimePanel == null ? 1.0f : m_RuntimePanel.pixelsPerUnit;
float ppuScale = 1.0f / ppu;
var scale = Vector3.one * ppuScale;
var flipRotation = Quaternion.AngleAxis(180.0f, Vector3.right); // Y-axis flip
if (parentUI == null)
{
matrix = Matrix4x4.TRS(Vector3.zero, flipRotation, scale);
}
else
{
var ui2World = Matrix4x4.TRS(Vector3.zero, flipRotation, scale);
var world2UI = ui2World.inverse;
var childGoToWorld = transform.localToWorldMatrix;
var worldToParentGo = parentUI.transform.worldToLocalMatrix;
// (GOa - To - World) * (UI2W) * (VEb - Space - To - VEa - Space) = (GOb - To - World) * (UI2W)
// (VEb - Space - To - VEa - Space) = (UI2W) ^ -1 * (GOa - To - World) ^ -1 * (GOb - To - World) * (UI2W)
matrix = world2UI * worldToParentGo * childGoToWorld * ui2World;
}
}
static void SetNoTransform(VisualElement visualElement)
{
visualElement.style.translate = Translate.None();
visualElement.style.rotate = Rotate.None();
visualElement.style.scale = Scale.None();
}
/// <summary>
/// Orders UIDocument components based on the way their GameObjects are ordered in the Hierarchy View.
/// </summary>
private void SetupFromHierarchy()
{
if (parentUI != null)
{
parentUI.RemoveChild(this);
}
parentUI = FindUIDocumentParent();
}
private UIDocument FindUIDocumentParent()
{
// Go up looking for a parent UIDocument, which we'd add ourselves too.
// If that fails, we'll just add ourselves to the runtime panel through the PanelSettings
// (assuming one is set, otherwise nothing gets drawn so it's pointless to not be
// parented by another UIDocument OR have a PanelSettings set).
Transform t = transform;
Transform parentTransform = t.parent;
if (parentTransform != null)
{
// We need to make sure we can get a parent even if they're disabled/inactive to reflect the good values.
var potentialParents = parentTransform.GetComponentsInParent<UIDocument>(true);
if (potentialParents != null && potentialParents.Length > 0)
{
return potentialParents[0];
}
}
return null;
}
internal void Reset()
{
if (parentUI == null)
{
m_PreviousPanelSettings?.DetachUIDocument(this);
panelSettings = null;
}
SetupFromHierarchy();
if (parentUI != null)
{
m_PanelSettings = parentUI.m_PanelSettings;
AddRootVisualElementToTree();
}
else if (m_PanelSettings != null)
{
AddRootVisualElementToTree();
}
OnValidate();
}
private void AddChildAndInsertContentToVisualTree(UIDocument child)
{
if (m_ChildrenContent == null)
{
m_ChildrenContent = new UIDocumentList();
}
else
{
// Before adding, we need to make sure it's nowhere else in the list (and in the hierarchy) as if we're
// re-adding, the position probably changed.
m_ChildrenContent.RemoveFromListAndFromVisualTree(child);
}
m_ChildrenContent.AddToListAndToVisualTree(child, m_RootVisualElement, m_FirstChildInsertIndex);
}
private void RemoveChild(UIDocument child)
{
m_ChildrenContent?.RemoveFromListAndFromVisualTree(child);
}
/// <summary>
/// Force rebuild the UI from UXML (if one is attached) and of all children (if any).
/// </summary>
private void RecreateUI()
{
if (m_RootVisualElement != null)
{
RemoveFromHierarchy();
if (m_PanelSettings != null)
m_PanelSettings.panel.liveReloadSystem.UnregisterVisualTreeAssetTracker(m_RootVisualElement);
m_RootVisualElement = null;
}
// Even though the root element is of type VisualElement, we use a TemplateContainer internally
// because we still want to use it as a TemplateContainer.
if (sourceAsset != null)
{
m_RootVisualElement = sourceAsset.Instantiate();
// This shouldn't happen but if it does we don't fail silently.
if (m_RootVisualElement == null)
{
Debug.LogError("The UXML file set for the UIDocument could not be cloned.");
}
}
if (m_RootVisualElement == null)
{
// Empty container if no UXML is set or if there was an error with cloning the set UXML.
m_RootVisualElement = new TemplateContainer() { name = gameObject.name + k_VisualElementNameSuffix };
}
else
{
m_RootVisualElement.name = gameObject.name + k_VisualElementNameSuffix;
}
m_RootVisualElement.pickingMode = PickingMode.Ignore;
// Setting the live reload tracker has to be done prior to attaching to panel in order to work properly
SetupVisualTreeAssetTracker();
if (isActiveAndEnabled)
{
AddRootVisualElementToTree();
}
// Save the last VisualElement before we start adding children so we can guarantee
// the order from the game object hierarchy.
m_FirstChildInsertIndex = m_RootVisualElement.childCount;
// Finally, we re-add our known children's element.
// This makes sure the hierarchy of game objects reflects on the order of VisualElements.
if (m_ChildrenContent != null)
{
// We need a copy to iterate because in the process of creating the children UI we modify the list.
if (m_ChildrenContentCopy == null)
{
m_ChildrenContentCopy = new List<UIDocument>(m_ChildrenContent.m_AttachedUIDocuments);
}
else
{
m_ChildrenContentCopy.AddRange(m_ChildrenContent.m_AttachedUIDocuments);
}
foreach (var child in m_ChildrenContentCopy)
{
if (child.isActiveAndEnabled)
{
if (child.m_RootVisualElement == null)
{
child.RecreateUI();
}
else
{
// Since the root is already created, make sure it's inserted into the right position.
AddChildAndInsertContentToVisualTree(child);
}
}
}
m_ChildrenContentCopy.Clear();
}
SetupRootClassList();
}
private void SetupRootClassList()
{
if (m_RootVisualElement == null)
return;
if (panelSettings == null || panelSettings.renderMode != PanelRenderMode.WorldSpace)
{
// If we're not a child of any other UIDocument stretch to take the full screen.
m_RootVisualElement.EnableInClassList(k_RootStyleClassName, parentUI == null);
}
else
{
UpdateWorldSpaceSize();
}
}
private void UpdateWorldSpaceSize()
{
if (m_RootVisualElement == null)
return;
if (m_WorldSpaceSizeMode == WorldSpaceSizeMode.Fixed)
{
m_RootVisualElement.style.position = Position.Absolute;
m_RootVisualElement.style.width = m_WorldSpaceWidth;
m_RootVisualElement.style.height = m_WorldSpaceHeight;
}
else
{
m_RootVisualElement.style.position = Position.Relative;
m_RootVisualElement.style.width = StyleKeyword.Null;
m_RootVisualElement.style.height = StyleKeyword.Null;
}
}
private void AddRootVisualElementToTree()
{
if (!enabled)
return; // Case 1388963, don't add the root if the component is disabled
// If we do have a parent, it will add us.
if (parentUI != null)
{
parentUI.AddChildAndInsertContentToVisualTree(this);
}
else if (m_PanelSettings != null)
{
m_PanelSettings.AttachAndInsertUIDocumentToVisualTree(this);
}
}
private void RemoveFromHierarchy()
{
if (parentUI != null)
{
parentUI.RemoveChild(this);
}
else if (m_PanelSettings != null)
{
m_PanelSettings.DetachUIDocument(this);
}
}
private void OnDisable()
{
if (m_RootVisualElement != null)
{
RemoveFromHierarchy();
// Unhook tracking, we're going down (but only after we detach from the panel).
if (m_PanelSettings != null)
m_PanelSettings.panel.liveReloadSystem.UnregisterVisualTreeAssetTracker(m_RootVisualElement);
m_RootVisualElement = null;
}
}
private void OnTransformChildrenChanged()
{
// In Editor, when not playing, we let a watcher listen for hierarchy changed events, except if
// we're disabled in which case the watcher can't find us.
if (!IsEditorPlaying.Invoke() && isActiveAndEnabled)
{
return;
}
if (m_ChildrenContent != null)
{
// The list may change inside the call to ReactToHierarchyChanged so we need a copy.
if (m_ChildrenContentCopy == null)
{
m_ChildrenContentCopy = new List<UIDocument>(m_ChildrenContent.m_AttachedUIDocuments);
}
else
{
m_ChildrenContentCopy.AddRange(m_ChildrenContent.m_AttachedUIDocuments);
}
foreach (var child in m_ChildrenContentCopy)
{
child.ReactToHierarchyChanged();
}
m_ChildrenContentCopy.Clear();
}
}
private void OnTransformParentChanged()
{
// In Editor, when not playing, we let a watcher listen for hierarchy changed events, except if
// we're disabled in which case the watcher can't find us.
if (!IsEditorPlaying.Invoke() && isActiveAndEnabled)
{
return;
}
ReactToHierarchyChanged();
}
internal void ReactToHierarchyChanged()
{
SetupFromHierarchy();
if (parentUI != null)
{
// Using the property guarantees the change trickles down the hierarchy (if there is one).
panelSettings = parentUI.m_PanelSettings;
}
m_RootVisualElement?.RemoveFromHierarchy();
AddRootVisualElementToTree();
SetupRootClassList();
}
private void OnGUI()
{
if (m_PanelSettings != null)
{
m_PanelSettings.UpdateScreenDPI();
}
}
private void SetupVisualTreeAssetTracker()
{
if (m_RootVisualElement == null)
return;
if (m_LiveReloadVisualTreeAssetTracker == null)
{
m_LiveReloadVisualTreeAssetTracker = CreateLiveReloadVisualTreeAssetTracker.Invoke(this);
}
if (m_PanelSettings != null)
m_PanelSettings.panel.liveReloadSystem.RegisterVisualTreeAssetTracker(m_LiveReloadVisualTreeAssetTracker, m_RootVisualElement);
}
internal void OnLiveReloadOptionChanged()
{
// We not only have to recreate ourselves but also our children (and their children).
ClearChildrenRecursively();
HandleLiveReload();
}
private void ClearChildrenRecursively()
{
if (m_ChildrenContent == null)
{
return;
}
foreach (var child in m_ChildrenContent.m_AttachedUIDocuments)
{
if (child.m_RootVisualElement != null)
{
child.m_RootVisualElement.RemoveFromHierarchy();
child.m_RootVisualElement = null;
}
child.ClearChildrenRecursively();
}
}
internal void HandleLiveReload()
{
var disabledCompanions = DisableCompanions();
RecreateUI();
if (disabledCompanions != null && disabledCompanions.Count > 0)
{
EnableCompanions(disabledCompanions);
}
else if (IsEditorPlaying.Invoke())
{
Debug.LogWarning("UI was recreated and no companion MonoBehaviour found, some UI functionality may have been lost.");
}
}
private HashSet<MonoBehaviour> DisableCompanions()
{
HashSet<MonoBehaviour> disabledCompanions = null;
var companions = GetComponents<MonoBehaviour>();
if (companions != null && companions.Length > 1) // If only one is found, it's this UIDocument.
{
disabledCompanions = new HashSet<MonoBehaviour>();
foreach (var companion in companions)
{
if (companion != this && companion.isActiveAndEnabled)
{
companion.enabled = false;
disabledCompanions.Add(companion);
}
}
}
return disabledCompanions;
}
private void EnableCompanions(HashSet<MonoBehaviour> disabledCompanions)
{
foreach (var companion in disabledCompanions)
{
companion.enabled = true;
}
}
private VisualTreeAsset m_OldUxml = null;
private float m_OldSortingOrder = k_DefaultSortingOrder;
private void OnValidate()
{
if (!gameObject.activeInHierarchy)
{
return;
}
if (m_OldUxml != sourceAsset)
{
visualTreeAsset = sourceAsset;
m_OldUxml = sourceAsset;
}
if (m_PreviousPanelSettings != m_PanelSettings && m_RootVisualElement != null && m_RootVisualElement.panel != null)
{
// We'll use the setter as it guarantees the right behavior.
// It's necessary for the setter that the old value is still in place.
var tempPanelSettings = m_PanelSettings;
m_PanelSettings = m_PreviousPanelSettings;
panelSettings = tempPanelSettings;
}
if (m_OldSortingOrder != m_SortingOrder)
{
if (m_RootVisualElement != null && m_RootVisualElement.panel != null)
{
ApplySortingOrder();
}
m_OldSortingOrder = m_SortingOrder;
}
if (m_PanelSettings != null && m_PanelSettings.renderMode == PanelRenderMode.WorldSpace)
{
UpdateWorldSpaceSize();
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/GameObjects/UIDocument.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/GameObjects/UIDocument.cs",
"repo_id": "UnityCsReference",
"token_count": 15687
} | 497 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements.Layout;
[StructLayout(LayoutKind.Sequential)]
readonly struct LayoutConfig
{
public static LayoutConfig Undefined => new LayoutConfig(default, LayoutHandle.Undefined);
readonly LayoutDataAccess m_Access;
readonly LayoutHandle m_Handle;
internal LayoutConfig(LayoutDataAccess access, LayoutHandle handle)
{
m_Access = access;
m_Handle = handle;
}
/// <summary>
/// Returns <see langword="true"/> if this is an invalid/undefined node.
/// </summary>
public bool IsUndefined => m_Handle.Equals(LayoutHandle.Undefined);
/// <summary>
/// Returns the handle for this node.
/// </summary>
public LayoutHandle Handle => m_Handle;
/// <summary>
/// Gets or sets the shared point scale factor for configured nodes.
/// </summary>
public ref float PointScaleFactor => ref m_Access.GetConfigData(m_Handle).PointScaleFactor;
}
| UnityCsReference/Modules/UIElements/Core/Layout/LayoutConfig.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/LayoutConfig.cs",
"repo_id": "UnityCsReference",
"token_count": 357
} | 498 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements.Layout;
enum LayoutAlign
{
Auto,
FlexStart,
Center,
FlexEnd,
Stretch,
Baseline,
SpaceBetween,
SpaceAround,
}
| UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutAlign.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutAlign.cs",
"repo_id": "UnityCsReference",
"token_count": 120
} | 499 |