text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
Imports System
Imports System.Linq
Public Class Issue2192
Public Shared Sub M()
Dim words As String() = {"abc", "defgh", "ijklm"}
Dim word As String = "test"
Console.WriteLine(words.Count(Function(w) w.Length > word.Length))
End Sub
End Class | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Issue2192.vb/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/VBPretty/Issue2192.vb",
"repo_id": "ILSpy",
"token_count": 89
} | 214 |
// Copyright (c) 2010-2018 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: ICSharpCode.Decompiler.Tests.TypeSystem.TypeTestAttribute(
42, typeof(System.Action<>), typeof(IDictionary<string, IList<NUnit.Framework.TestAttribute>>))]
[assembly: TypeForwardedTo(typeof(Func<,>))]
namespace ICSharpCode.Decompiler.Tests.TypeSystem
{
public delegate S GenericDelegate<in T, out S>(T input) where T : S where S : class;
public class SimplePublicClass
{
public void Method() { }
public SimplePublicClass() { }
[Double(1)]
~SimplePublicClass() { }
}
public class TypeTestAttribute : Attribute
{
public TypeTestAttribute(int a1, Type a2, Type a3) { }
#pragma warning disable CS0465
private void Finalize()
{
}
#pragma warning restore CS0465
}
[Params(1, StringComparison.CurrentCulture, null, 4.0, "Test")]
public class ParamsAttribute : Attribute
{
public ParamsAttribute(params object[] x) { }
[Params(Property = new string[] { "a", "b" })]
public string[] Property {
[return: Params("Attribute on return type of getter")]
get { return null; }
set { }
}
}
[Double(1)]
public class DoubleAttribute : Attribute
{
public DoubleAttribute(double val) { }
}
public unsafe class DynamicTest
{
public dynamic DynamicField;
public dynamic SimpleProperty { get; set; }
public List<dynamic> DynamicGenerics1(Action<object, dynamic[], object> param) { return null; }
public void DynamicGenerics2(Action<object, dynamic, object> param) { }
public void DynamicGenerics3(Action<int, dynamic, object> param) { }
public void DynamicGenerics4(Action<int[], dynamic, object> param) { }
public void DynamicGenerics5(Action<int*[], dynamic, object> param) { }
public void DynamicGenerics6(ref Action<object, dynamic, object> param) { }
public void DynamicGenerics7(Action<int[,][], dynamic, object> param) { }
}
public class GenericClass<A, B> where A : B
{
public void TestMethod<K, V>(string param) where V : K where K : IComparable<V> { }
public void GetIndex<T>(T element) where T : IEquatable<T> { }
public NestedEnum EnumField;
public A Property { get; set; }
public enum NestedEnum
{
EnumMember
}
}
public class PropertyTest
{
public int PropertyWithProtectedSetter { get; protected set; }
public object PropertyWithPrivateSetter { get; private set; }
public object PropertyWithoutSetter { get { return null; } }
public object PropertyWithPrivateGetter { private get; set; }
public string this[int index] { get { return "Test"; } set { } }
}
public enum MyEnum : short
{
First,
Second,
Flag1 = 0x10,
Flag2 = 0x20,
CombinedFlags = Flag1 | Flag2
}
public class Base<T>
{
public class Nested<X> { }
~Base() { }
public virtual void GenericMethodWithConstraints<X>(T a) where X : IComparer<T>, new() { }
}
public class Derived<A, B> : Base<B>
{
~Derived() { }
public override void GenericMethodWithConstraints<Y>(B a) { }
}
public struct MyStructWithCtor
{
public MyStructWithCtor(int a) { }
}
public struct MyStructWithDefaultCtor
{
public MyStructWithDefaultCtor() { }
}
public class MyClassWithCtor
{
private MyClassWithCtor(int a) { }
}
[Serializable]
public class NonCustomAttributes
{
[SpecialName]
public class SpecialNameClass
{
}
[SpecialName]
public struct SpecialNameStruct
{
}
[NonSerialized]
public readonly int NonSerializedField;
[SpecialName]
public readonly int SpecialNameField;
[SpecialName]
public event EventHandler SpecialNameEvent;
[SpecialName]
public int SpecialNameProperty { get; set; }
[DllImport("unmanaged.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DllMethod([In, Out] ref int p);
[DllImport("unmanaged.dll", PreserveSig = false)]
public static extern bool DoNotPreserveSig();
[PreserveSig]
public static void PreserveSigAsAttribute()
{
}
[SpecialName]
public static void SpecialNameMethod()
{
}
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode, Pack = 8)]
public struct ExplicitFieldLayoutStruct
{
[FieldOffset(0)]
public int Field0;
[FieldOffset(100)]
public int Field100;
}
public class ParameterTests
{
public void MethodWithOutParameter(out int x) { x = 0; }
public void MethodWithParamsArray(params object[] x) { }
public void MethodWithOptionalParameter(int x = 4) { }
public void MethodWithExplicitOptionalParameter([Optional] int x) { }
public void MethodWithRefParameter(ref int x) { }
public void MethodWithInParameter(in int x) { }
public void MethodWithEnumOptionalParameter(StringComparison x = StringComparison.OrdinalIgnoreCase) { }
public void MethodWithOptionalNullableParameter(int? x = null) { }
public void MethodWithOptionalLongParameter(long x = 1) { }
public void MethodWithOptionalNullableLongParameter(long? x = 1) { }
public void MethodWithOptionalDecimalParameter(decimal x = 1) { }
public void VarArgsMethod(__arglist) { }
}
public class VarArgsCtor
{
public VarArgsCtor(__arglist) { }
}
[ComImport(), Guid("21B8916C-F28E-11D2-A473-00C04F8EF448"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAssemblyEnum
{
[PreserveSig()]
int GetNextAssembly(uint dwFlags);
}
public class OuterGeneric<X>
{
public class Inner
{
public OuterGeneric<X> referenceToOuter;
public Inner(OuterGeneric<X> referenceToOuter) { }
}
public OuterGeneric<X>.Inner Field1;
public Inner Field2;
public OuterGeneric<OuterGeneric<X>.Inner>.Inner Field3;
}
public class ExplicitDisposableImplementation : IDisposable
{
void IDisposable.Dispose() { }
}
public interface IGenericInterface<T>
{
void Test<S>(T a, S b) where S : T;
void Test<S>(T a, ref S b);
}
public class ExplicitGenericInterfaceImplementation : IGenericInterface<string>
{
void IGenericInterface<string>.Test<T>(string a, T b) { }
void IGenericInterface<string>.Test<T>(string a, ref T b) { }
}
public interface IGenericInterfaceWithUnifiableMethods<T, S>
{
void Test(T a);
void Test(S a);
}
public class ImplementationOfUnifiedMethods : IGenericInterfaceWithUnifiableMethods<int, int>
{
public void Test(int a) { }
}
public class ExplicitGenericInterfaceImplementationWithUnifiableMethods<T, S> : IGenericInterfaceWithUnifiableMethods<T, S>
{
void IGenericInterfaceWithUnifiableMethods<T, S>.Test(T a) { }
void IGenericInterfaceWithUnifiableMethods<T, S>.Test(S a) { }
}
public partial class PartialClass
{
partial void PartialMethodWithImplementation(int a);
partial void PartialMethodWithImplementation(System.Int32 a)
{
}
partial void PartialMethodWithImplementation(string a);
partial void PartialMethodWithImplementation(System.String a)
{
}
partial void PartialMethodWithoutImplementation();
}
public class ClassWithStaticAndNonStaticMembers
{
public static event System.EventHandler Event1 { add { } remove { } }
public event System.EventHandler Event2 { add { } remove { } }
#pragma warning disable 67
public static event System.EventHandler Event3;
public event System.EventHandler Event4;
public static int Prop1 { get { return 0; } set { } }
public int Prop2 { get { return 0; } set { } }
public static int Prop3 { get; set; }
public int Prop4 { get; set; }
}
public interface IInterfaceWithProperty
{
int Prop { get; set; }
}
public interface IBase1
{
int Prop { get; set; }
}
public interface IBase2
{
int Prop { get; set; }
}
public interface IDerived : IBase1, IBase2
{
new int Prop { get; set; }
}
public class ClassWithVirtualProperty
{
public virtual int Prop { get; protected set; }
}
public class ClassThatOverridesAndSealsVirtualProperty : ClassWithVirtualProperty
{
public sealed override int Prop { get; protected set; }
}
public class ClassThatOverridesGetterOnly : ClassWithVirtualProperty
{
public override int Prop { get { return 1; } }
}
public class ClassThatOverridesSetterOnly : ClassThatOverridesGetterOnly
{
public override int Prop { protected set { } }
}
public class ClassThatImplementsProperty : IInterfaceWithProperty
{
public int Prop { get; set; }
}
public class ClassThatImplementsPropertyExplicitly : IInterfaceWithProperty
{
int IInterfaceWithProperty.Prop { get; set; }
}
public interface IInterfaceWithIndexers
{
int this[int x] { get; set; }
int this[string x] { get; set; }
int this[int x, int y] { get; set; }
}
public interface IGenericInterfaceWithIndexer<T>
{
int this[T x] { get; set; }
}
public interface IInterfaceWithRenamedIndexer
{
[IndexerName("NewName")]
int this[int x] { get; set; }
}
public class ClassThatImplementsIndexers : IInterfaceWithIndexers, IGenericInterfaceWithIndexer<int>
{
public int this[int x] { get { return 0; } set { } }
public int this[string x] { get { return 0; } set { } }
public int this[int x, int y] { get { return 0; } set { } }
}
public class ClassThatImplementsIndexersExplicitly : IInterfaceWithIndexers, IGenericInterfaceWithIndexer<int>, IInterfaceWithRenamedIndexer
{
int IInterfaceWithIndexers.this[int x] { get { return 0; } set { } }
int IGenericInterfaceWithIndexer<int>.this[int x] { get { return 0; } set { } }
int IInterfaceWithIndexers.this[string x] { get { return 0; } set { } }
int IInterfaceWithIndexers.this[int x, int y] { get { return 0; } set { } }
int IInterfaceWithRenamedIndexer.this[int x] { get { return 0; } set { } }
}
public interface IHasEvent
{
event EventHandler Event;
}
public class ClassThatImplementsEvent : IHasEvent
{
public event EventHandler Event;
}
public class ClassThatImplementsEventWithCustomAccessors : IHasEvent
{
public event EventHandler Event { add { } remove { } }
}
public class ClassThatImplementsEventExplicitly : IHasEvent
{
event EventHandler IHasEvent.Event { add { } remove { } }
}
public interface IShadowTestBase
{
void Method();
int this[int i] { get; set; }
int Prop { get; set; }
event EventHandler Evt;
}
public interface IShadowTestDerived : IShadowTestBase
{
new void Method();
new int this[int i] { get; set; }
new int Prop { get; set; }
new event EventHandler Evt;
}
public static class StaticClass
{
public static void Extension(this object inst) { }
}
public abstract class AbstractClass { }
public class IndexerNonDefaultName
{
[IndexerName("Foo")]
public int this[int index] {
get { return 0; }
}
}
public class ClassWithMethodThatHasNullableDefaultParameter
{
public void Foo(int? bar = 42) { }
}
public class AccessibilityTest
{
public void Public() { }
internal void Internal() { }
protected internal void ProtectedInternal() { }
internal protected void InternalProtected() { }
protected void Protected() { }
private void Private() { }
void None() { }
}
public class ConstantFieldTest
{
public const byte Cb = 42;
public const sbyte Csb = 42;
public const char Cc = '\x42';
public const short Cs = 42;
public const ushort Cus = 42;
public const int Ci = 42;
public const uint Cui = 42;
public const long Cl = 42;
public const ulong Cul = 42;
public const double Cd = 42;
public const float Cf = 42;
public const decimal Cm = 42;
public const string S = "hello, world";
public const string NullString = null;
public const MyEnum EnumFromThisAssembly = MyEnum.Second;
public const StringComparison EnumFromAnotherAssembly = StringComparison.OrdinalIgnoreCase;
public const MyEnum DefaultOfEnum = default(MyEnum);
public const int SOsb = sizeof(sbyte);
public const int SOb = sizeof(byte);
public const int SOs = sizeof(short);
public const int SOus = sizeof(ushort);
public const int SOi = sizeof(int);
public const int SOui = sizeof(uint);
public const int SOl = sizeof(long);
public const int SOul = sizeof(ulong);
public const int SOc = sizeof(char);
public const int SOf = sizeof(float);
public const int SOd = sizeof(double);
public const int SObl = sizeof(bool);
public const int SOe = sizeof(MyEnum);
public const byte CNewb = new byte();
public const sbyte CNewsb = new sbyte();
public const char CNewc = new char();
public const short CNews = new short();
public const ushort CNewus = new ushort();
public const int CNewi = new int();
public const uint CNewui = new uint();
public const long CNewl = new long();
public const ulong CNewul = new ulong();
public const double CNewd = new double();
public const float CNewf = new float();
public const decimal CNewm = new decimal();
}
public interface IExplicitImplementationTests
{
void M(int a);
int P { get; set; }
event Action E;
int this[int x] { get; set; }
}
public class ExplicitImplementationTests : IExplicitImplementationTests
{
public void M(int a) { }
public int P { get; set; }
public event Action E;
public int this[int x] { get { return 0; } set { } }
void IExplicitImplementationTests.M(int a) { }
int IExplicitImplementationTests.P { get; set; }
event Action IExplicitImplementationTests.E { add { } remove { } }
int IExplicitImplementationTests.this[int x] { get { return 0; } set { } }
}
[TypeTest(C, typeof(Inner), typeof(int)), My]
public class ClassWithAttributesUsingNestedMembers
{
sealed class MyAttribute : Attribute { }
const int C = 42;
class Inner
{
}
[TypeTest(C, typeof(Inner), typeof(int)), My]
public int P { get; set; }
[TypeTest(C, typeof(Inner), typeof(int)), My]
class AttributedInner
{
}
[TypeTest(C, typeof(Inner), typeof(int)), My]
class AttributedInner2
{
sealed class MyAttribute : Attribute { }
const int C = 43;
class Inner { }
}
}
public class ClassWithAttributeOnTypeParameter<[Double(2)] T> { }
[Guid("790C6E0B-9194-4cc9-9426-A48A63185696"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComImport]
public interface IMarshalAsTests
{
[DispId(48)]
void AliasComponent([MarshalAs(UnmanagedType.BStr)][In] string bstrSrcApplicationIDOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrCLSIDOrProgID, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestApplicationIDOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrNewProgId, [MarshalAs(UnmanagedType.BStr)][In] string bstrNewClsid);
[DispId(33)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool AreApplicationInstancesPaused([MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationInstanceID);
[DispId(19)]
void BackupREGDB([MarshalAs(UnmanagedType.BStr)][In] string bstrBackupFilePath);
[DispId(2)]
[return: MarshalAs(UnmanagedType.Interface)]
object Connect([MarshalAs(UnmanagedType.BStr)][In] string connectStr);
[DispId(45)]
void CopyApplications([MarshalAs(UnmanagedType.BStr)][In] string bstrSourcePartitionIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationID, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestinationPartitionIDOrName);
[DispId(46)]
void CopyComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrSourceApplicationIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarCLSIDOrProgID, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestinationApplicationIDOrName);
[DispId(36)]
void CreateServiceForApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrServiceName, [MarshalAs(UnmanagedType.BStr)][In] string bstrStartType, [MarshalAs(UnmanagedType.BStr)][In] string bstrErrorControl, [MarshalAs(UnmanagedType.BStr)][In] string bstrDependencies, [MarshalAs(UnmanagedType.BStr)][In] string bstrRunAs, [MarshalAs(UnmanagedType.BStr)][In] string bstrPassword, [MarshalAs(UnmanagedType.VariantBool)][In] bool bDesktopOk);
[DispId(40)]
void CurrentPartition([MarshalAs(UnmanagedType.BStr)][In] string bstrPartitionIDOrName);
[DispId(41)]
[return: MarshalAs(UnmanagedType.BStr)]
string CurrentPartitionID();
[DispId(42)]
[return: MarshalAs(UnmanagedType.BStr)]
string CurrentPartitionName();
[DispId(37)]
void DeleteServiceForApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName);
[DispId(34)]
[return: MarshalAs(UnmanagedType.BStr)]
string DumpApplicationInstance([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationInstanceID, [MarshalAs(UnmanagedType.BStr)][In] string bstrDirectory, [MarshalAs(UnmanagedType.I4)][In] int lMaxImages);
[DispId(9)]
void ExportApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationFile, [In] int lOptions);
[DispId(54)]
void ExportPartition([MarshalAs(UnmanagedType.BStr)][In] string bstrPartitionIDOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrPartitionFileName, [MarshalAs(UnmanagedType.I4)][In] int lOptions);
[DispId(44)]
void FlushPartitionCache();
[DispId(28)]
[return: MarshalAs(UnmanagedType.BStr)]
string GetApplicationInstanceIDFromProcessID([MarshalAs(UnmanagedType.I4)][In] int lProcessID);
[DispId(1)]
[return: MarshalAs(UnmanagedType.Interface)]
object GetCollection([MarshalAs(UnmanagedType.BStr)][In] string bstrCollName);
[DispId(5)]
[return: MarshalAs(UnmanagedType.Interface)]
object GetCollectionByQuery([MarshalAs(UnmanagedType.BStr)][In] string collName, [MarshalAs(UnmanagedType.SafeArray)][In] ref object[] aQuery);
[DispId(27)]
[return: MarshalAs(UnmanagedType.Interface)]
object GetCollectionByQuery2([MarshalAs(UnmanagedType.BStr)][In] string bstrCollectionName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarQueryStrings);
[DispId(57)]
[return: MarshalAs(UnmanagedType.I4)]
int GetComponentVersionCount([MarshalAs(UnmanagedType.BStr)][In] string bstrCLSIDOrProgID);
[DispId(26)]
void GetEventClassesForIID([In] string bstrIID, [MarshalAs(UnmanagedType.SafeArray)][In][Out] ref object[] varCLSIDS, [MarshalAs(UnmanagedType.SafeArray)][In][Out] ref object[] varProgIDs, [MarshalAs(UnmanagedType.SafeArray)][In][Out] ref object[] varDescriptions);
[DispId(17)]
void GetMultipleComponentsInfo([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [In] object varFileNames, [MarshalAs(UnmanagedType.SafeArray)] out object[] varCLSIDS, [MarshalAs(UnmanagedType.SafeArray)] out object[] varClassNames, [MarshalAs(UnmanagedType.SafeArray)] out object[] varFileFlags, [MarshalAs(UnmanagedType.SafeArray)] out object[] varComponentFlags);
[DispId(38)]
[return: MarshalAs(UnmanagedType.BStr)]
string GetPartitionID([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName);
[DispId(39)]
[return: MarshalAs(UnmanagedType.BStr)]
string GetPartitionName([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName);
[DispId(43)]
[return: MarshalAs(UnmanagedType.BStr)]
string GlobalPartitionID();
[DispId(6)]
void ImportComponent([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrCLSIDOrProgId);
[DispId(52)]
void ImportComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarCLSIDOrProgID, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarComponentType);
[DispId(50)]
void ImportUnconfiguredComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarCLSIDOrProgID, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarComponentType);
[DispId(10)]
void InstallApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationFile, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestinationDirectory, [In] int lOptions, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserId, [MarshalAs(UnmanagedType.BStr)][In] string bstrPassword, [MarshalAs(UnmanagedType.BStr)][In] string bstrRSN);
[DispId(7)]
void InstallComponent([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrDLL, [MarshalAs(UnmanagedType.BStr)][In] string bstrTLB, [MarshalAs(UnmanagedType.BStr)][In] string bstrPSDLL);
[DispId(25)]
void InstallEventClass([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.BStr)][In] string bstrDLL, [MarshalAs(UnmanagedType.BStr)][In] string bstrTLB, [MarshalAs(UnmanagedType.BStr)][In] string bstrPSDLL);
[DispId(16)]
void InstallMultipleComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)][In] ref object[] fileNames, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)][In] ref object[] CLSIDS);
[DispId(24)]
void InstallMultipleEventClasses([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)][In] ref object[] fileNames, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)][In] ref object[] CLSIDS);
[DispId(55)]
void InstallPartition([MarshalAs(UnmanagedType.BStr)][In] string bstrFileName, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestDirectory, [MarshalAs(UnmanagedType.I4)][In] int lOptions, [MarshalAs(UnmanagedType.BStr)][In] string bstrUserID, [MarshalAs(UnmanagedType.BStr)][In] string bstrPassword, [MarshalAs(UnmanagedType.BStr)][In] string bstrRSN);
[DispId(53)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool Is64BitCatalogServer();
[DispId(35)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsApplicationInstanceDumpSupported();
[DispId(49)]
[return: MarshalAs(UnmanagedType.Interface)]
object IsSafeToDelete([MarshalAs(UnmanagedType.BStr)][In] string bstrDllName);
[DispId(3)]
int MajorVersion();
[DispId(4)]
int MinorVersion();
[DispId(47)]
void MoveComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrSourceApplicationIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarCLSIDOrProgID, [MarshalAs(UnmanagedType.BStr)][In] string bstrDestinationApplicationIDOrName);
[DispId(30)]
void PauseApplicationInstances([MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationInstanceID);
[DispId(51)]
void PromoteUnconfiguredComponents([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationIDOrName, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarCLSIDOrProgID, [MarshalAs(UnmanagedType.LPStruct)][In] object pVarComponentType);
[DispId(21)]
void QueryApplicationFile([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationFile, [MarshalAs(UnmanagedType.BStr)] out string bstrApplicationName, [MarshalAs(UnmanagedType.BStr)] out string bstrApplicationDescription, [MarshalAs(UnmanagedType.VariantBool)] out bool bHasUsers, [MarshalAs(UnmanagedType.VariantBool)] out bool bIsProxy, [MarshalAs(UnmanagedType.SafeArray)] out object[] varFileNames);
[DispId(56)]
[return: MarshalAs(UnmanagedType.IDispatch)]
object QueryApplicationFile2([MarshalAs(UnmanagedType.BStr)][In] string bstrApplicationFile);
[DispId(32)]
void RecycleApplicationInstances([MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationInstanceID, [MarshalAs(UnmanagedType.I4)][In] int lReasonCode);
[DispId(18)]
void RefreshComponents();
[DispId(12)]
void RefreshRouter();
[DispId(14)]
void Reserved1();
[DispId(15)]
void Reserved2();
[DispId(20)]
void RestoreREGDB([MarshalAs(UnmanagedType.BStr)][In] string bstrBackupFilePath);
[DispId(31)]
void ResumeApplicationInstances([MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationInstanceID);
[DispId(23)]
int ServiceCheck([In] int lService);
[DispId(8)]
void ShutdownApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName);
[DispId(29)]
void ShutdownApplicationInstances([MarshalAs(UnmanagedType.LPStruct)][In] object pVarApplicationInstanceID);
[DispId(22)]
void StartApplication([MarshalAs(UnmanagedType.BStr)][In] string bstrApplIdOrName);
[DispId(13)]
void StartRouter();
[DispId(11)]
void StopRouter();
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TypeSystem/TypeSystemTestCase.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TypeSystem/TypeSystemTestCase.cs",
"repo_id": "ILSpy",
"token_count": 8816
} | 215 |
// Copyright (c) 2010-2020 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
using Attribute = ICSharpCode.Decompiler.CSharp.Syntax.Attribute;
namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{
/// <summary>
/// Outputs the AST.
/// </summary>
public class CSharpOutputVisitor : IAstVisitor
{
readonly protected TokenWriter writer;
readonly protected CSharpFormattingOptions policy;
readonly protected Stack<AstNode> containerStack = new Stack<AstNode>();
public CSharpOutputVisitor(TextWriter textWriter, CSharpFormattingOptions formattingPolicy)
{
if (textWriter == null)
{
throw new ArgumentNullException(nameof(textWriter));
}
if (formattingPolicy == null)
{
throw new ArgumentNullException(nameof(formattingPolicy));
}
this.writer = TokenWriter.Create(textWriter, formattingPolicy.IndentationString);
this.policy = formattingPolicy;
}
public CSharpOutputVisitor(TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (formattingPolicy == null)
{
throw new ArgumentNullException(nameof(formattingPolicy));
}
this.writer = new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(writer));
this.policy = formattingPolicy;
}
#region StartNode/EndNode
protected virtual void StartNode(AstNode node)
{
// Ensure that nodes are visited in the proper nested order.
// Jumps to different subtrees are allowed only for the child of a placeholder node.
Debug.Assert(containerStack.Count == 0 || node.Parent == containerStack.Peek() || containerStack.Peek().NodeType == NodeType.Pattern);
containerStack.Push(node);
writer.StartNode(node);
}
protected virtual void EndNode(AstNode node)
{
Debug.Assert(node == containerStack.Peek());
containerStack.Pop();
writer.EndNode(node);
}
#endregion
#region Comma
/// <summary>
/// Writes a comma.
/// </summary>
/// <param name="nextNode">The next node after the comma.</param>
/// <param name="noSpaceAfterComma">When set prevents printing a space after comma.</param>
protected virtual void Comma(AstNode nextNode, bool noSpaceAfterComma = false)
{
Space(policy.SpaceBeforeBracketComma);
// TODO: Comma policy has changed.
writer.WriteToken(Roles.Comma, ",");
isAfterSpace = false;
Space(!noSpaceAfterComma && policy.SpaceAfterBracketComma);
// TODO: Comma policy has changed.
}
/// <summary>
/// Writes an optional comma, e.g. at the end of an enum declaration or in an array initializer
/// </summary>
protected virtual void OptionalComma(AstNode pos)
{
// Look if there's a comma after the current node, and insert it if it exists.
while (pos != null && pos.NodeType == NodeType.Whitespace)
{
pos = pos.NextSibling;
}
if (pos != null && pos.Role == Roles.Comma)
{
Comma(null, noSpaceAfterComma: true);
}
}
/// <summary>
/// Writes an optional semicolon, e.g. at the end of a type or namespace declaration.
/// </summary>
protected virtual void OptionalSemicolon(AstNode pos)
{
// Look if there's a semicolon after the current node, and insert it if it exists.
while (pos != null && pos.NodeType == NodeType.Whitespace)
{
pos = pos.PrevSibling;
}
if (pos != null && pos.Role == Roles.Semicolon)
{
Semicolon();
}
}
protected virtual void WriteCommaSeparatedList(IEnumerable<AstNode> list)
{
bool isFirst = true;
foreach (AstNode node in list)
{
if (isFirst)
{
isFirst = false;
}
else
{
Comma(node);
}
node.AcceptVisitor(this);
}
}
protected virtual void WriteCommaSeparatedListInParenthesis(IEnumerable<AstNode> list, bool spaceWithin)
{
LPar();
if (list.Any())
{
Space(spaceWithin);
WriteCommaSeparatedList(list);
Space(spaceWithin);
}
RPar();
}
protected virtual void WriteCommaSeparatedListInBrackets(IEnumerable<ParameterDeclaration> list, bool spaceWithin)
{
WriteToken(Roles.LBracket);
if (list.Any())
{
Space(spaceWithin);
WriteCommaSeparatedList(list);
Space(spaceWithin);
}
WriteToken(Roles.RBracket);
}
protected virtual void WriteCommaSeparatedListInBrackets(IEnumerable<Expression> list)
{
WriteToken(Roles.LBracket);
if (list.Any())
{
Space(policy.SpacesWithinBrackets);
WriteCommaSeparatedList(list);
Space(policy.SpacesWithinBrackets);
}
WriteToken(Roles.RBracket);
}
#endregion
#region Write tokens
protected bool isAtStartOfLine = true;
protected bool isAfterSpace;
/// <summary>
/// Writes a keyword, and all specials up to
/// </summary>
protected virtual void WriteKeyword(TokenRole tokenRole)
{
WriteKeyword(tokenRole.Token, tokenRole);
}
protected virtual void WriteKeyword(string token, Role tokenRole = null)
{
writer.WriteKeyword(tokenRole, token);
isAtStartOfLine = false;
isAfterSpace = false;
}
protected virtual void WriteIdentifier(Identifier identifier)
{
writer.WriteIdentifier(identifier);
isAtStartOfLine = false;
isAfterSpace = false;
}
protected virtual void WriteIdentifier(string identifier)
{
AstType.Create(identifier).AcceptVisitor(this);
isAtStartOfLine = false;
isAfterSpace = false;
}
protected virtual void WriteToken(TokenRole tokenRole)
{
WriteToken(tokenRole.Token, tokenRole);
}
protected virtual void WriteToken(string token, Role tokenRole)
{
writer.WriteToken(tokenRole, token);
isAtStartOfLine = false;
isAfterSpace = false;
}
protected virtual void LPar()
{
WriteToken(Roles.LPar);
}
protected virtual void RPar()
{
WriteToken(Roles.RPar);
}
/// <summary>
/// Marks the end of a statement
/// </summary>
protected virtual void Semicolon()
{
// get the role of the current node
Role role = containerStack.Peek().Role;
if (!SkipToken())
{
WriteToken(Roles.Semicolon);
if (!SkipNewLine())
NewLine();
else
Space();
}
bool SkipToken()
{
return role == ForStatement.InitializerRole
|| role == ForStatement.IteratorRole
|| role == UsingStatement.ResourceAcquisitionRole;
}
bool SkipNewLine()
{
if (containerStack.Peek() is not Accessor accessor)
return false;
if (!(role == PropertyDeclaration.GetterRole || role == PropertyDeclaration.SetterRole))
return false;
bool isAutoProperty = accessor.Body.IsNull
&& !accessor.Attributes.Any()
&& policy.AutoPropertyFormatting == PropertyFormatting.SingleLine;
return isAutoProperty;
}
}
/// <summary>
/// Writes a space depending on policy.
/// </summary>
protected virtual void Space(bool addSpace = true)
{
if (addSpace && !isAfterSpace)
{
writer.Space();
isAfterSpace = true;
}
}
protected virtual void NewLine()
{
writer.NewLine();
isAtStartOfLine = true;
isAfterSpace = false;
}
int GetCallChainLengthLimited(MemberReferenceExpression expr)
{
int callChainLength = 0;
var node = expr;
while (node.Target is InvocationExpression invocation && invocation.Target is MemberReferenceExpression mre && callChainLength < 4)
{
node = mre;
callChainLength++;
}
return callChainLength;
}
int ShouldInsertNewLineWhenInMethodCallChain(MemberReferenceExpression expr)
{
int callChainLength = GetCallChainLengthLimited(expr);
if (callChainLength < 3)
return 0;
if (expr.GetParent(n => n is Statement || n is LambdaExpression || n is InterpolatedStringContent) is InterpolatedStringContent)
return 0;
return callChainLength;
}
protected virtual bool InsertNewLineWhenInMethodCallChain(MemberReferenceExpression expr)
{
int callChainLength = ShouldInsertNewLineWhenInMethodCallChain(expr);
if (callChainLength == 0)
return false;
if (callChainLength == 3)
writer.Indent();
writer.NewLine();
isAtStartOfLine = true;
isAfterSpace = false;
return true;
}
protected virtual void OpenBrace(BraceStyle style, bool newLine = true)
{
switch (style)
{
case BraceStyle.EndOfLine:
case BraceStyle.BannerStyle:
if (!isAtStartOfLine)
Space();
WriteToken("{", Roles.LBrace);
break;
case BraceStyle.EndOfLineWithoutSpace:
WriteToken("{", Roles.LBrace);
break;
case BraceStyle.NextLine:
if (!isAtStartOfLine)
NewLine();
WriteToken("{", Roles.LBrace);
break;
case BraceStyle.NextLineShifted:
NewLine();
writer.Indent();
WriteToken("{", Roles.LBrace);
NewLine();
return;
case BraceStyle.NextLineShifted2:
NewLine();
writer.Indent();
WriteToken("{", Roles.LBrace);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (newLine)
{
writer.Indent();
NewLine();
}
}
protected virtual void CloseBrace(BraceStyle style, bool unindent = true)
{
switch (style)
{
case BraceStyle.EndOfLine:
case BraceStyle.EndOfLineWithoutSpace:
case BraceStyle.NextLine:
if (unindent)
writer.Unindent();
WriteToken("}", Roles.RBrace);
break;
case BraceStyle.BannerStyle:
case BraceStyle.NextLineShifted:
WriteToken("}", Roles.RBrace);
if (unindent)
writer.Unindent();
break;
case BraceStyle.NextLineShifted2:
if (unindent)
writer.Unindent();
WriteToken("}", Roles.RBrace);
if (unindent)
writer.Unindent();
break;
default:
throw new ArgumentOutOfRangeException();
}
}
#endregion
#region IsKeyword Test
static readonly HashSet<string> unconditionalKeywords = new HashSet<string> {
"abstract", "as", "base", "bool", "break", "byte", "case", "catch",
"char", "checked", "class", "const", "continue", "decimal", "default", "delegate",
"do", "double", "else", "enum", "event", "explicit", "extern", "false",
"finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit",
"in", "int", "interface", "internal", "is", "lock", "long", "namespace",
"new", "null", "object", "operator", "out", "override", "params", "private",
"protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short",
"sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort",
"using", "virtual", "void", "volatile", "while"
};
static readonly HashSet<string> queryKeywords = new HashSet<string> {
"from", "where", "join", "on", "equals", "into", "let", "orderby",
"ascending", "descending", "select", "group", "by"
};
static readonly int maxKeywordLength = unconditionalKeywords.Concat(queryKeywords).Max(s => s.Length);
/// <summary>
/// Determines whether the specified identifier is a keyword in the given context.
/// </summary>
public static bool IsKeyword(string identifier, AstNode context)
{
// only 2-10 char lower-case identifiers can be keywords
if (identifier.Length > maxKeywordLength || identifier.Length < 2 || identifier[0] < 'a')
{
return false;
}
if (unconditionalKeywords.Contains(identifier))
{
return true;
}
if (queryKeywords.Contains(identifier))
{
return context.Ancestors.Any(ancestor => ancestor is QueryExpression);
}
if (identifier == "await")
{
foreach (AstNode ancestor in context.Ancestors)
{
// with lambdas/anonymous methods,
if (ancestor is LambdaExpression)
{
return ((LambdaExpression)ancestor).IsAsync;
}
if (ancestor is AnonymousMethodExpression)
{
return ((AnonymousMethodExpression)ancestor).IsAsync;
}
if (ancestor is EntityDeclaration)
{
return (((EntityDeclaration)ancestor).Modifiers & Modifiers.Async) == Modifiers.Async;
}
}
}
return false;
}
#endregion
#region Write constructs
protected virtual void WriteTypeArguments(IEnumerable<AstType> typeArguments)
{
if (typeArguments.Any())
{
WriteToken(Roles.LChevron);
WriteCommaSeparatedList(typeArguments);
WriteToken(Roles.RChevron);
}
}
public virtual void WriteTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters)
{
if (typeParameters.Any())
{
WriteToken(Roles.LChevron);
WriteCommaSeparatedList(typeParameters);
WriteToken(Roles.RChevron);
}
}
protected virtual void WriteModifiers(IEnumerable<CSharpModifierToken> modifierTokens)
{
foreach (CSharpModifierToken modifier in modifierTokens)
{
modifier.AcceptVisitor(this);
Space();
}
}
protected virtual void WriteQualifiedIdentifier(IEnumerable<Identifier> identifiers)
{
bool first = true;
foreach (Identifier ident in identifiers)
{
if (first)
{
first = false;
}
else
{
writer.WriteToken(Roles.Dot, ".");
}
writer.WriteIdentifier(ident);
}
}
/// <summary>
/// Writes an embedded statement.
/// </summary>
/// <param name="embeddedStatement">The statement to write.</param>
/// <param name="nlp">Determines whether a trailing newline should be written following a block.
/// Non-blocks always write a trailing newline.</param>
/// <remarks>
/// Blocks may or may not write a leading newline depending on StatementBraceStyle.
/// Non-blocks always write a leading newline.
/// </remarks>
protected virtual void WriteEmbeddedStatement(Statement embeddedStatement, NewLinePlacement nlp = NewLinePlacement.NewLine)
{
if (embeddedStatement.IsNull)
{
NewLine();
return;
}
BlockStatement block = embeddedStatement as BlockStatement;
if (block != null)
{
WriteBlock(block, policy.StatementBraceStyle);
if (nlp == NewLinePlacement.SameLine)
{
Space(); // if not a trailing newline, then at least a trailing space
}
else
{
NewLine();
}
}
else
{
NewLine();
writer.Indent();
embeddedStatement.AcceptVisitor(this);
writer.Unindent();
}
}
protected virtual void WriteMethodBody(BlockStatement body, BraceStyle style, bool newLine = true)
{
if (body.IsNull)
{
Semicolon();
}
else
{
WriteBlock(body, style);
NewLine();
}
}
protected virtual void WriteAttributes(IEnumerable<AttributeSection> attributes)
{
foreach (AttributeSection attr in attributes)
{
attr.AcceptVisitor(this);
}
}
protected virtual void WritePrivateImplementationType(AstType privateImplementationType)
{
if (!privateImplementationType.IsNull)
{
privateImplementationType.AcceptVisitor(this);
WriteToken(Roles.Dot);
}
}
#endregion
#region Expressions
public virtual void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
StartNode(anonymousMethodExpression);
if (anonymousMethodExpression.IsAsync)
{
WriteKeyword(AnonymousMethodExpression.AsyncModifierRole);
Space();
}
WriteKeyword(AnonymousMethodExpression.DelegateKeywordRole);
if (anonymousMethodExpression.HasParameterList)
{
Space(policy.SpaceBeforeAnonymousMethodParentheses);
WriteCommaSeparatedListInParenthesis(anonymousMethodExpression.Parameters, policy.SpaceWithinAnonymousMethodParentheses);
}
WriteBlock(anonymousMethodExpression.Body, policy.AnonymousMethodBraceStyle);
EndNode(anonymousMethodExpression);
}
public virtual void VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
{
StartNode(undocumentedExpression);
switch (undocumentedExpression.UndocumentedExpressionType)
{
case UndocumentedExpressionType.ArgList:
case UndocumentedExpressionType.ArgListAccess:
WriteKeyword(UndocumentedExpression.ArglistKeywordRole);
break;
case UndocumentedExpressionType.MakeRef:
WriteKeyword(UndocumentedExpression.MakerefKeywordRole);
break;
case UndocumentedExpressionType.RefType:
WriteKeyword(UndocumentedExpression.ReftypeKeywordRole);
break;
case UndocumentedExpressionType.RefValue:
WriteKeyword(UndocumentedExpression.RefvalueKeywordRole);
break;
}
if (undocumentedExpression.UndocumentedExpressionType != UndocumentedExpressionType.ArgListAccess)
{
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(undocumentedExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
}
EndNode(undocumentedExpression);
}
public virtual void VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
{
StartNode(arrayCreateExpression);
WriteKeyword(ArrayCreateExpression.NewKeywordRole);
arrayCreateExpression.Type.AcceptVisitor(this);
if (arrayCreateExpression.Arguments.Count > 0)
{
WriteCommaSeparatedListInBrackets(arrayCreateExpression.Arguments);
}
foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers)
{
specifier.AcceptVisitor(this);
}
arrayCreateExpression.Initializer.AcceptVisitor(this);
EndNode(arrayCreateExpression);
}
public virtual void VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
{
StartNode(arrayInitializerExpression);
// "new List<int> { { 1 } }" and "new List<int> { 1 }" are the same semantically.
// We also use the same AST for both: we always use two nested ArrayInitializerExpressions
// for collection initializers, even if the user did not write nested brackets.
// The output visitor will output nested braces only if they are necessary,
// or if the braces tokens exist in the AST.
bool bracesAreOptional = arrayInitializerExpression.Elements.Count == 1
&& IsObjectOrCollectionInitializer(arrayInitializerExpression.Parent)
&& !CanBeConfusedWithObjectInitializer(arrayInitializerExpression.Elements.Single());
if (bracesAreOptional && arrayInitializerExpression.LBraceToken.IsNull)
{
arrayInitializerExpression.Elements.Single().AcceptVisitor(this);
}
else
{
PrintInitializerElements(arrayInitializerExpression.Elements);
}
EndNode(arrayInitializerExpression);
}
protected bool CanBeConfusedWithObjectInitializer(Expression expr)
{
// "int a; new List<int> { a = 1 };" is an object initalizers and invalid, but
// "int a; new List<int> { { a = 1 } };" is a valid collection initializer.
AssignmentExpression ae = expr as AssignmentExpression;
return ae != null && ae.Operator == AssignmentOperatorType.Assign;
}
protected bool IsObjectOrCollectionInitializer(AstNode node)
{
if (!(node is ArrayInitializerExpression))
{
return false;
}
if (node.Parent is ObjectCreateExpression)
{
return node.Role == ObjectCreateExpression.InitializerRole;
}
if (node.Parent is NamedExpression)
{
return node.Role == Roles.Expression;
}
return false;
}
protected virtual void PrintInitializerElements(AstNodeCollection<Expression> elements)
{
bool wrapAlways = policy.ArrayInitializerWrapping == Wrapping.WrapAlways
|| (elements.Count > 1 && elements.Any(e => !IsSimpleExpression(e)))
|| elements.Any(IsComplexExpression);
bool wrap = wrapAlways
|| elements.Count > 10;
OpenBrace(wrap ? policy.ArrayInitializerBraceStyle : BraceStyle.EndOfLine, newLine: wrap);
if (!wrap)
Space();
AstNode last = null;
foreach (var (idx, node) in elements.WithIndex())
{
if (idx > 0)
{
Comma(node, noSpaceAfterComma: true);
if (wrapAlways || idx % 10 == 0)
NewLine();
else
Space();
}
last = node;
node.AcceptVisitor(this);
}
if (last != null)
OptionalComma(last.NextSibling);
if (wrap)
NewLine();
else
Space();
CloseBrace(wrap ? policy.ArrayInitializerBraceStyle : BraceStyle.EndOfLine, unindent: wrap);
bool IsSimpleExpression(Expression ex)
{
switch (ex)
{
case NullReferenceExpression _:
case ThisReferenceExpression _:
case PrimitiveExpression _:
case IdentifierExpression _:
case MemberReferenceExpression {
Target: ThisReferenceExpression
or IdentifierExpression
or BaseReferenceExpression
} _:
return true;
default:
return false;
}
}
bool IsComplexExpression(Expression ex)
{
switch (ex)
{
case AnonymousMethodExpression _:
case LambdaExpression _:
case AnonymousTypeCreateExpression _:
case ObjectCreateExpression _:
case NamedExpression _:
return true;
default:
return false;
}
}
}
public virtual void VisitAsExpression(AsExpression asExpression)
{
StartNode(asExpression);
asExpression.Expression.AcceptVisitor(this);
Space();
WriteKeyword(AsExpression.AsKeywordRole);
Space();
asExpression.Type.AcceptVisitor(this);
EndNode(asExpression);
}
public virtual void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
{
StartNode(assignmentExpression);
assignmentExpression.Left.AcceptVisitor(this);
Space(policy.SpaceAroundAssignment);
WriteToken(AssignmentExpression.GetOperatorRole(assignmentExpression.Operator));
Space(policy.SpaceAroundAssignment);
assignmentExpression.Right.AcceptVisitor(this);
EndNode(assignmentExpression);
}
public virtual void VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
{
StartNode(baseReferenceExpression);
WriteKeyword("base", baseReferenceExpression.Role);
EndNode(baseReferenceExpression);
}
public virtual void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
{
StartNode(binaryOperatorExpression);
binaryOperatorExpression.Left.AcceptVisitor(this);
bool spacePolicy;
switch (binaryOperatorExpression.Operator)
{
case BinaryOperatorType.BitwiseAnd:
case BinaryOperatorType.BitwiseOr:
case BinaryOperatorType.ExclusiveOr:
spacePolicy = policy.SpaceAroundBitwiseOperator;
break;
case BinaryOperatorType.ConditionalAnd:
case BinaryOperatorType.ConditionalOr:
spacePolicy = policy.SpaceAroundLogicalOperator;
break;
case BinaryOperatorType.GreaterThan:
case BinaryOperatorType.GreaterThanOrEqual:
case BinaryOperatorType.LessThanOrEqual:
case BinaryOperatorType.LessThan:
spacePolicy = policy.SpaceAroundRelationalOperator;
break;
case BinaryOperatorType.Equality:
case BinaryOperatorType.InEquality:
spacePolicy = policy.SpaceAroundEqualityOperator;
break;
case BinaryOperatorType.Add:
case BinaryOperatorType.Subtract:
spacePolicy = policy.SpaceAroundAdditiveOperator;
break;
case BinaryOperatorType.Multiply:
case BinaryOperatorType.Divide:
case BinaryOperatorType.Modulus:
spacePolicy = policy.SpaceAroundMultiplicativeOperator;
break;
case BinaryOperatorType.ShiftLeft:
case BinaryOperatorType.ShiftRight:
case BinaryOperatorType.UnsignedShiftRight:
spacePolicy = policy.SpaceAroundShiftOperator;
break;
case BinaryOperatorType.NullCoalescing:
case BinaryOperatorType.IsPattern:
spacePolicy = true;
break;
case BinaryOperatorType.Range:
spacePolicy = false;
break;
default:
throw new NotSupportedException("Invalid value for BinaryOperatorType");
}
Space(spacePolicy);
TokenRole tokenRole = BinaryOperatorExpression.GetOperatorRole(binaryOperatorExpression.Operator);
if (tokenRole == BinaryOperatorExpression.IsKeywordRole)
{
WriteKeyword(tokenRole);
}
else
{
WriteToken(tokenRole);
}
Space(spacePolicy);
binaryOperatorExpression.Right.AcceptVisitor(this);
EndNode(binaryOperatorExpression);
}
public virtual void VisitCastExpression(CastExpression castExpression)
{
StartNode(castExpression);
LPar();
Space(policy.SpacesWithinCastParentheses);
castExpression.Type.AcceptVisitor(this);
Space(policy.SpacesWithinCastParentheses);
RPar();
Space(policy.SpaceAfterTypecast);
castExpression.Expression.AcceptVisitor(this);
EndNode(castExpression);
}
public virtual void VisitCheckedExpression(CheckedExpression checkedExpression)
{
StartNode(checkedExpression);
WriteKeyword(CheckedExpression.CheckedKeywordRole);
LPar();
Space(policy.SpacesWithinCheckedExpressionParantheses);
checkedExpression.Expression.AcceptVisitor(this);
Space(policy.SpacesWithinCheckedExpressionParantheses);
RPar();
EndNode(checkedExpression);
}
public virtual void VisitConditionalExpression(ConditionalExpression conditionalExpression)
{
StartNode(conditionalExpression);
conditionalExpression.Condition.AcceptVisitor(this);
Space(policy.SpaceBeforeConditionalOperatorCondition);
WriteToken(ConditionalExpression.QuestionMarkRole);
Space(policy.SpaceAfterConditionalOperatorCondition);
conditionalExpression.TrueExpression.AcceptVisitor(this);
Space(policy.SpaceBeforeConditionalOperatorSeparator);
WriteToken(ConditionalExpression.ColonRole);
Space(policy.SpaceAfterConditionalOperatorSeparator);
conditionalExpression.FalseExpression.AcceptVisitor(this);
EndNode(conditionalExpression);
}
public virtual void VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
{
StartNode(defaultValueExpression);
WriteKeyword(DefaultValueExpression.DefaultKeywordRole);
LPar();
Space(policy.SpacesWithinTypeOfParentheses);
defaultValueExpression.Type.AcceptVisitor(this);
Space(policy.SpacesWithinTypeOfParentheses);
RPar();
EndNode(defaultValueExpression);
}
public virtual void VisitDirectionExpression(DirectionExpression directionExpression)
{
StartNode(directionExpression);
switch (directionExpression.FieldDirection)
{
case FieldDirection.Out:
WriteKeyword(DirectionExpression.OutKeywordRole);
break;
case FieldDirection.Ref:
WriteKeyword(DirectionExpression.RefKeywordRole);
break;
case FieldDirection.In:
WriteKeyword(DirectionExpression.InKeywordRole);
break;
default:
throw new NotSupportedException("Invalid value for FieldDirection");
}
Space();
directionExpression.Expression.AcceptVisitor(this);
EndNode(directionExpression);
}
public virtual void VisitDeclarationExpression(DeclarationExpression declarationExpression)
{
StartNode(declarationExpression);
declarationExpression.Type.AcceptVisitor(this);
Space();
declarationExpression.Designation.AcceptVisitor(this);
EndNode(declarationExpression);
}
public virtual void VisitRecursivePatternExpression(RecursivePatternExpression recursivePatternExpression)
{
StartNode(recursivePatternExpression);
recursivePatternExpression.Type.AcceptVisitor(this);
Space();
if (recursivePatternExpression.IsPositional)
{
WriteToken(Roles.LPar);
}
else
{
WriteToken(Roles.LBrace);
}
Space();
WriteCommaSeparatedList(recursivePatternExpression.SubPatterns);
Space();
if (recursivePatternExpression.IsPositional)
{
WriteToken(Roles.RPar);
}
else
{
WriteToken(Roles.RBrace);
}
if (!recursivePatternExpression.Designation.IsNull)
{
Space();
recursivePatternExpression.Designation.AcceptVisitor(this);
}
EndNode(recursivePatternExpression);
}
public virtual void VisitOutVarDeclarationExpression(OutVarDeclarationExpression outVarDeclarationExpression)
{
StartNode(outVarDeclarationExpression);
WriteKeyword(OutVarDeclarationExpression.OutKeywordRole);
Space();
outVarDeclarationExpression.Type.AcceptVisitor(this);
Space();
outVarDeclarationExpression.Variable.AcceptVisitor(this);
EndNode(outVarDeclarationExpression);
}
public virtual void VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
StartNode(identifierExpression);
WriteIdentifier(identifierExpression.IdentifierToken);
WriteTypeArguments(identifierExpression.TypeArguments);
EndNode(identifierExpression);
}
public virtual void VisitIndexerExpression(IndexerExpression indexerExpression)
{
StartNode(indexerExpression);
indexerExpression.Target.AcceptVisitor(this);
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInBrackets(indexerExpression.Arguments);
EndNode(indexerExpression);
}
public virtual void VisitInvocationExpression(InvocationExpression invocationExpression)
{
StartNode(invocationExpression);
invocationExpression.Target.AcceptVisitor(this);
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(invocationExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
if (!(invocationExpression.Parent is MemberReferenceExpression))
{
if (invocationExpression.Target is MemberReferenceExpression mre)
{
if (ShouldInsertNewLineWhenInMethodCallChain(mre) >= 3)
writer.Unindent();
}
}
EndNode(invocationExpression);
}
public virtual void VisitIsExpression(IsExpression isExpression)
{
StartNode(isExpression);
isExpression.Expression.AcceptVisitor(this);
Space();
WriteKeyword(IsExpression.IsKeywordRole);
isExpression.Type.AcceptVisitor(this);
EndNode(isExpression);
}
public virtual void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
StartNode(lambdaExpression);
WriteAttributes(lambdaExpression.Attributes);
if (lambdaExpression.IsAsync)
{
WriteKeyword(LambdaExpression.AsyncModifierRole);
Space();
}
if (LambdaNeedsParenthesis(lambdaExpression))
{
WriteCommaSeparatedListInParenthesis(lambdaExpression.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
}
else
{
lambdaExpression.Parameters.Single().AcceptVisitor(this);
}
Space();
WriteToken(Roles.Arrow);
if (lambdaExpression.Body is BlockStatement)
{
WriteBlock((BlockStatement)lambdaExpression.Body, policy.AnonymousMethodBraceStyle);
}
else
{
Space();
lambdaExpression.Body.AcceptVisitor(this);
}
EndNode(lambdaExpression);
}
protected bool LambdaNeedsParenthesis(LambdaExpression lambdaExpression)
{
if (lambdaExpression.Parameters.Count != 1)
{
return true;
}
var p = lambdaExpression.Parameters.Single();
return !(p.Type.IsNull && p.ParameterModifier == ParameterModifier.None);
}
public virtual void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
StartNode(memberReferenceExpression);
memberReferenceExpression.Target.AcceptVisitor(this);
bool insertedNewLine = InsertNewLineWhenInMethodCallChain(memberReferenceExpression);
WriteToken(Roles.Dot);
WriteIdentifier(memberReferenceExpression.MemberNameToken);
WriteTypeArguments(memberReferenceExpression.TypeArguments);
if (insertedNewLine && !(memberReferenceExpression.Parent is InvocationExpression))
{
writer.Unindent();
}
EndNode(memberReferenceExpression);
}
public virtual void VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
{
StartNode(namedArgumentExpression);
WriteIdentifier(namedArgumentExpression.NameToken);
WriteToken(Roles.Colon);
Space();
namedArgumentExpression.Expression.AcceptVisitor(this);
EndNode(namedArgumentExpression);
}
public virtual void VisitNamedExpression(NamedExpression namedExpression)
{
StartNode(namedExpression);
WriteIdentifier(namedExpression.NameToken);
Space();
WriteToken(Roles.Assign);
Space();
namedExpression.Expression.AcceptVisitor(this);
EndNode(namedExpression);
}
public virtual void VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
{
StartNode(nullReferenceExpression);
writer.WritePrimitiveValue(null);
isAfterSpace = false;
EndNode(nullReferenceExpression);
}
public virtual void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
{
StartNode(objectCreateExpression);
WriteKeyword(ObjectCreateExpression.NewKeywordRole);
objectCreateExpression.Type.AcceptVisitor(this);
bool useParenthesis = objectCreateExpression.Arguments.Any() || objectCreateExpression.Initializer.IsNull;
// also use parenthesis if there is an '(' token
if (!objectCreateExpression.LParToken.IsNull)
{
useParenthesis = true;
}
if (useParenthesis)
{
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(objectCreateExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
}
objectCreateExpression.Initializer.AcceptVisitor(this);
EndNode(objectCreateExpression);
}
public virtual void VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
{
StartNode(anonymousTypeCreateExpression);
WriteKeyword(AnonymousTypeCreateExpression.NewKeywordRole);
PrintInitializerElements(anonymousTypeCreateExpression.Initializers);
EndNode(anonymousTypeCreateExpression);
}
public virtual void VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
{
StartNode(parenthesizedExpression);
LPar();
Space(policy.SpacesWithinParentheses);
parenthesizedExpression.Expression.AcceptVisitor(this);
Space(policy.SpacesWithinParentheses);
RPar();
EndNode(parenthesizedExpression);
}
public virtual void VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
{
StartNode(pointerReferenceExpression);
pointerReferenceExpression.Target.AcceptVisitor(this);
WriteToken(PointerReferenceExpression.ArrowRole);
WriteIdentifier(pointerReferenceExpression.MemberNameToken);
WriteTypeArguments(pointerReferenceExpression.TypeArguments);
EndNode(pointerReferenceExpression);
}
#region VisitPrimitiveExpression
public virtual void VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
{
StartNode(primitiveExpression);
writer.WritePrimitiveValue(primitiveExpression.Value, primitiveExpression.Format);
isAfterSpace = false;
EndNode(primitiveExpression);
}
public virtual void VisitInterpolatedStringExpression(InterpolatedStringExpression interpolatedStringExpression)
{
StartNode(interpolatedStringExpression);
writer.WriteToken(InterpolatedStringExpression.OpenQuote, "$\"");
foreach (var element in interpolatedStringExpression.Content)
{
element.AcceptVisitor(this);
}
writer.WriteToken(InterpolatedStringExpression.CloseQuote, "\"");
isAfterSpace = false;
EndNode(interpolatedStringExpression);
}
public virtual void VisitInterpolation(Interpolation interpolation)
{
StartNode(interpolation);
writer.WriteToken(Interpolation.LBrace, "{");
interpolation.Expression.AcceptVisitor(this);
if (interpolation.Alignment != 0)
{
writer.WriteToken(Roles.Comma, ",");
writer.WritePrimitiveValue(interpolation.Alignment);
}
if (interpolation.Suffix != null)
{
writer.WriteToken(Roles.Colon, ":");
writer.WriteInterpolatedText(interpolation.Suffix);
}
writer.WriteToken(Interpolation.RBrace, "}");
EndNode(interpolation);
}
public virtual void VisitInterpolatedStringText(InterpolatedStringText interpolatedStringText)
{
StartNode(interpolatedStringText);
writer.WriteInterpolatedText(interpolatedStringText.Text);
EndNode(interpolatedStringText);
}
#endregion
public virtual void VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
{
StartNode(sizeOfExpression);
WriteKeyword(SizeOfExpression.SizeofKeywordRole);
LPar();
Space(policy.SpacesWithinSizeOfParentheses);
sizeOfExpression.Type.AcceptVisitor(this);
Space(policy.SpacesWithinSizeOfParentheses);
RPar();
EndNode(sizeOfExpression);
}
public virtual void VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
{
StartNode(stackAllocExpression);
WriteKeyword(StackAllocExpression.StackallocKeywordRole);
stackAllocExpression.Type.AcceptVisitor(this);
WriteCommaSeparatedListInBrackets(new[] { stackAllocExpression.CountExpression });
stackAllocExpression.Initializer.AcceptVisitor(this);
EndNode(stackAllocExpression);
}
public virtual void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
{
StartNode(thisReferenceExpression);
WriteKeyword("this", thisReferenceExpression.Role);
EndNode(thisReferenceExpression);
}
public virtual void VisitThrowExpression(ThrowExpression throwExpression)
{
StartNode(throwExpression);
WriteKeyword(ThrowExpression.ThrowKeywordRole);
Space();
throwExpression.Expression.AcceptVisitor(this);
EndNode(throwExpression);
}
public virtual void VisitTupleExpression(TupleExpression tupleExpression)
{
Debug.Assert(tupleExpression.Elements.Count >= 2);
StartNode(tupleExpression);
LPar();
WriteCommaSeparatedList(tupleExpression.Elements);
RPar();
EndNode(tupleExpression);
}
public virtual void VisitTypeOfExpression(TypeOfExpression typeOfExpression)
{
StartNode(typeOfExpression);
WriteKeyword(TypeOfExpression.TypeofKeywordRole);
LPar();
Space(policy.SpacesWithinTypeOfParentheses);
typeOfExpression.Type.AcceptVisitor(this);
Space(policy.SpacesWithinTypeOfParentheses);
RPar();
EndNode(typeOfExpression);
}
public virtual void VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
{
StartNode(typeReferenceExpression);
typeReferenceExpression.Type.AcceptVisitor(this);
EndNode(typeReferenceExpression);
}
public virtual void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
{
StartNode(unaryOperatorExpression);
UnaryOperatorType opType = unaryOperatorExpression.Operator;
var opSymbol = UnaryOperatorExpression.GetOperatorRole(opType);
if (opType is UnaryOperatorType.Await or UnaryOperatorType.PatternNot)
{
WriteKeyword(opSymbol);
Space();
}
else if (!IsPostfixOperator(opType) && opSymbol != null)
{
WriteToken(opSymbol);
}
unaryOperatorExpression.Expression.AcceptVisitor(this);
if (IsPostfixOperator(opType))
{
WriteToken(opSymbol);
}
EndNode(unaryOperatorExpression);
}
static bool IsPostfixOperator(UnaryOperatorType op)
{
return op == UnaryOperatorType.PostIncrement
|| op == UnaryOperatorType.PostDecrement
|| op == UnaryOperatorType.NullConditional
|| op == UnaryOperatorType.SuppressNullableWarning;
}
public virtual void VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
{
StartNode(uncheckedExpression);
WriteKeyword(UncheckedExpression.UncheckedKeywordRole);
LPar();
Space(policy.SpacesWithinCheckedExpressionParantheses);
uncheckedExpression.Expression.AcceptVisitor(this);
Space(policy.SpacesWithinCheckedExpressionParantheses);
RPar();
EndNode(uncheckedExpression);
}
public virtual void VisitWithInitializerExpression(WithInitializerExpression withInitializerExpression)
{
StartNode(withInitializerExpression);
withInitializerExpression.Expression.AcceptVisitor(this);
WriteKeyword("with", WithInitializerExpression.WithKeywordRole);
withInitializerExpression.Initializer.AcceptVisitor(this);
EndNode(withInitializerExpression);
}
#endregion
#region Query Expressions
public virtual void VisitQueryExpression(QueryExpression queryExpression)
{
StartNode(queryExpression);
if (queryExpression.Role != QueryContinuationClause.PrecedingQueryRole)
writer.Indent();
bool first = true;
foreach (var clause in queryExpression.Clauses)
{
if (first)
{
first = false;
}
else
{
if (!(clause is QueryContinuationClause))
{
NewLine();
}
}
clause.AcceptVisitor(this);
}
if (queryExpression.Role != QueryContinuationClause.PrecedingQueryRole)
writer.Unindent();
EndNode(queryExpression);
}
public virtual void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
{
StartNode(queryContinuationClause);
queryContinuationClause.PrecedingQuery.AcceptVisitor(this);
Space();
WriteKeyword(QueryContinuationClause.IntoKeywordRole);
Space();
WriteIdentifier(queryContinuationClause.IdentifierToken);
EndNode(queryContinuationClause);
}
public virtual void VisitQueryFromClause(QueryFromClause queryFromClause)
{
StartNode(queryFromClause);
WriteKeyword(QueryFromClause.FromKeywordRole);
queryFromClause.Type.AcceptVisitor(this);
Space();
WriteIdentifier(queryFromClause.IdentifierToken);
Space();
WriteKeyword(QueryFromClause.InKeywordRole);
Space();
queryFromClause.Expression.AcceptVisitor(this);
EndNode(queryFromClause);
}
public virtual void VisitQueryLetClause(QueryLetClause queryLetClause)
{
StartNode(queryLetClause);
WriteKeyword(QueryLetClause.LetKeywordRole);
Space();
WriteIdentifier(queryLetClause.IdentifierToken);
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
queryLetClause.Expression.AcceptVisitor(this);
EndNode(queryLetClause);
}
public virtual void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
{
StartNode(queryWhereClause);
WriteKeyword(QueryWhereClause.WhereKeywordRole);
Space();
queryWhereClause.Condition.AcceptVisitor(this);
EndNode(queryWhereClause);
}
public virtual void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
{
StartNode(queryJoinClause);
WriteKeyword(QueryJoinClause.JoinKeywordRole);
queryJoinClause.Type.AcceptVisitor(this);
Space();
WriteIdentifier(queryJoinClause.JoinIdentifierToken);
Space();
WriteKeyword(QueryJoinClause.InKeywordRole);
Space();
queryJoinClause.InExpression.AcceptVisitor(this);
Space();
WriteKeyword(QueryJoinClause.OnKeywordRole);
Space();
queryJoinClause.OnExpression.AcceptVisitor(this);
Space();
WriteKeyword(QueryJoinClause.EqualsKeywordRole);
Space();
queryJoinClause.EqualsExpression.AcceptVisitor(this);
if (queryJoinClause.IsGroupJoin)
{
Space();
WriteKeyword(QueryJoinClause.IntoKeywordRole);
WriteIdentifier(queryJoinClause.IntoIdentifierToken);
}
EndNode(queryJoinClause);
}
public virtual void VisitQueryOrderClause(QueryOrderClause queryOrderClause)
{
StartNode(queryOrderClause);
WriteKeyword(QueryOrderClause.OrderbyKeywordRole);
Space();
WriteCommaSeparatedList(queryOrderClause.Orderings);
EndNode(queryOrderClause);
}
public virtual void VisitQueryOrdering(QueryOrdering queryOrdering)
{
StartNode(queryOrdering);
queryOrdering.Expression.AcceptVisitor(this);
switch (queryOrdering.Direction)
{
case QueryOrderingDirection.Ascending:
Space();
WriteKeyword(QueryOrdering.AscendingKeywordRole);
break;
case QueryOrderingDirection.Descending:
Space();
WriteKeyword(QueryOrdering.DescendingKeywordRole);
break;
}
EndNode(queryOrdering);
}
public virtual void VisitQuerySelectClause(QuerySelectClause querySelectClause)
{
StartNode(querySelectClause);
WriteKeyword(QuerySelectClause.SelectKeywordRole);
Space();
querySelectClause.Expression.AcceptVisitor(this);
EndNode(querySelectClause);
}
public virtual void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
{
StartNode(queryGroupClause);
WriteKeyword(QueryGroupClause.GroupKeywordRole);
Space();
queryGroupClause.Projection.AcceptVisitor(this);
Space();
WriteKeyword(QueryGroupClause.ByKeywordRole);
Space();
queryGroupClause.Key.AcceptVisitor(this);
EndNode(queryGroupClause);
}
#endregion
#region GeneralScope
public virtual void VisitAttribute(Attribute attribute)
{
StartNode(attribute);
attribute.Type.AcceptVisitor(this);
if (attribute.Arguments.Count != 0 || attribute.HasArgumentList)
{
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(attribute.Arguments, policy.SpaceWithinMethodCallParentheses);
}
EndNode(attribute);
}
public virtual void VisitAttributeSection(AttributeSection attributeSection)
{
StartNode(attributeSection);
WriteToken(Roles.LBracket);
if (!string.IsNullOrEmpty(attributeSection.AttributeTarget))
{
WriteKeyword(attributeSection.AttributeTarget, Roles.Identifier);
WriteToken(Roles.Colon);
Space();
}
WriteCommaSeparatedList(attributeSection.Attributes);
WriteToken(Roles.RBracket);
switch (attributeSection.Parent)
{
case ParameterDeclaration _:
if (attributeSection.NextSibling is AttributeSection)
Space(policy.SpaceBetweenParameterAttributeSections);
else
Space();
break;
case TypeParameterDeclaration _:
case ComposedType _:
case LambdaExpression _:
Space();
break;
default:
NewLine();
break;
}
EndNode(attributeSection);
}
public virtual void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
{
StartNode(delegateDeclaration);
WriteAttributes(delegateDeclaration.Attributes);
WriteModifiers(delegateDeclaration.ModifierTokens);
WriteKeyword(Roles.DelegateKeyword);
delegateDeclaration.ReturnType.AcceptVisitor(this);
Space();
WriteIdentifier(delegateDeclaration.NameToken);
WriteTypeParameters(delegateDeclaration.TypeParameters);
Space(policy.SpaceBeforeDelegateDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(delegateDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
foreach (Constraint constraint in delegateDeclaration.Constraints)
{
constraint.AcceptVisitor(this);
}
Semicolon();
EndNode(delegateDeclaration);
}
public virtual void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
StartNode(namespaceDeclaration);
WriteKeyword(Roles.NamespaceKeyword);
namespaceDeclaration.NamespaceName.AcceptVisitor(this);
if (namespaceDeclaration.IsFileScoped)
{
Semicolon();
NewLine();
}
else
{
OpenBrace(policy.NamespaceBraceStyle);
}
foreach (var member in namespaceDeclaration.Members)
{
member.AcceptVisitor(this);
MaybeNewLinesAfterUsings(member);
}
if (!namespaceDeclaration.IsFileScoped)
{
CloseBrace(policy.NamespaceBraceStyle);
OptionalSemicolon(namespaceDeclaration.LastChild);
NewLine();
}
EndNode(namespaceDeclaration);
}
public virtual void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
StartNode(typeDeclaration);
WriteAttributes(typeDeclaration.Attributes);
WriteModifiers(typeDeclaration.ModifierTokens);
BraceStyle braceStyle;
switch (typeDeclaration.ClassType)
{
case ClassType.Enum:
WriteKeyword(Roles.EnumKeyword);
braceStyle = policy.EnumBraceStyle;
break;
case ClassType.Interface:
WriteKeyword(Roles.InterfaceKeyword);
braceStyle = policy.InterfaceBraceStyle;
break;
case ClassType.Struct:
WriteKeyword(Roles.StructKeyword);
braceStyle = policy.StructBraceStyle;
break;
case ClassType.RecordClass:
WriteKeyword(Roles.RecordKeyword);
braceStyle = policy.ClassBraceStyle;
break;
case ClassType.RecordStruct:
WriteKeyword(Roles.RecordStructKeyword);
WriteKeyword(Roles.StructKeyword);
braceStyle = policy.StructBraceStyle;
break;
default:
WriteKeyword(Roles.ClassKeyword);
braceStyle = policy.ClassBraceStyle;
break;
}
WriteIdentifier(typeDeclaration.NameToken);
WriteTypeParameters(typeDeclaration.TypeParameters);
if (typeDeclaration.PrimaryConstructorParameters.Count > 0)
{
Space(policy.SpaceBeforeMethodDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(typeDeclaration.PrimaryConstructorParameters, policy.SpaceWithinMethodDeclarationParentheses);
}
if (typeDeclaration.BaseTypes.Any())
{
Space();
WriteToken(Roles.Colon);
Space();
WriteCommaSeparatedList(typeDeclaration.BaseTypes);
}
foreach (Constraint constraint in typeDeclaration.Constraints)
{
constraint.AcceptVisitor(this);
}
if (typeDeclaration.ClassType is (ClassType.RecordClass or ClassType.RecordStruct) && typeDeclaration.Members.Count == 0)
{
Semicolon();
}
else
{
OpenBrace(braceStyle);
if (typeDeclaration.ClassType == ClassType.Enum)
{
bool first = true;
AstNode last = null;
foreach (var member in typeDeclaration.Members)
{
if (first)
{
first = false;
}
else
{
Comma(member, noSpaceAfterComma: true);
NewLine();
}
last = member;
member.AcceptVisitor(this);
}
if (last != null)
OptionalComma(last.NextSibling);
NewLine();
}
else
{
bool first = true;
foreach (var member in typeDeclaration.Members)
{
if (!first)
{
for (int i = 0; i < policy.MinimumBlankLinesBetweenMembers; i++)
NewLine();
}
first = false;
member.AcceptVisitor(this);
}
}
CloseBrace(braceStyle);
OptionalSemicolon(typeDeclaration.LastChild);
NewLine();
}
EndNode(typeDeclaration);
}
public virtual void VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration)
{
StartNode(usingAliasDeclaration);
WriteKeyword(UsingAliasDeclaration.UsingKeywordRole);
WriteIdentifier(usingAliasDeclaration.GetChildByRole(UsingAliasDeclaration.AliasRole));
Space(policy.SpaceAroundEqualityOperator);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundEqualityOperator);
usingAliasDeclaration.Import.AcceptVisitor(this);
Semicolon();
EndNode(usingAliasDeclaration);
}
public virtual void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
StartNode(usingDeclaration);
WriteKeyword(UsingDeclaration.UsingKeywordRole);
usingDeclaration.Import.AcceptVisitor(this);
Semicolon();
EndNode(usingDeclaration);
}
public virtual void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
{
StartNode(externAliasDeclaration);
WriteKeyword(Roles.ExternKeyword);
Space();
WriteKeyword(Roles.AliasKeyword);
Space();
WriteIdentifier(externAliasDeclaration.NameToken);
Semicolon();
EndNode(externAliasDeclaration);
}
#endregion
#region Statements
public virtual void VisitBlockStatement(BlockStatement blockStatement)
{
WriteBlock(blockStatement, policy.StatementBraceStyle);
NewLine();
}
/// <summary>
/// Writes a block statement.
/// Similar to VisitBlockStatement() except that:
/// 1) it allows customizing the BraceStyle
/// 2) it does not write a trailing newline after the '}' (this job is left to the caller)
/// </summary>
protected virtual void WriteBlock(BlockStatement blockStatement, BraceStyle style)
{
StartNode(blockStatement);
OpenBrace(style);
foreach (var node in blockStatement.Statements)
{
node.AcceptVisitor(this);
}
CloseBrace(style);
EndNode(blockStatement);
}
public virtual void VisitBreakStatement(BreakStatement breakStatement)
{
StartNode(breakStatement);
WriteKeyword("break", BreakStatement.BreakKeywordRole);
Semicolon();
EndNode(breakStatement);
}
public virtual void VisitCheckedStatement(CheckedStatement checkedStatement)
{
StartNode(checkedStatement);
WriteKeyword(CheckedStatement.CheckedKeywordRole);
checkedStatement.Body.AcceptVisitor(this);
EndNode(checkedStatement);
}
public virtual void VisitContinueStatement(ContinueStatement continueStatement)
{
StartNode(continueStatement);
WriteKeyword("continue", ContinueStatement.ContinueKeywordRole);
Semicolon();
EndNode(continueStatement);
}
public virtual void VisitDoWhileStatement(DoWhileStatement doWhileStatement)
{
StartNode(doWhileStatement);
WriteKeyword(DoWhileStatement.DoKeywordRole);
WriteEmbeddedStatement(doWhileStatement.EmbeddedStatement, policy.WhileNewLinePlacement);
WriteKeyword(DoWhileStatement.WhileKeywordRole);
Space(policy.SpaceBeforeWhileParentheses);
LPar();
Space(policy.SpacesWithinWhileParentheses);
doWhileStatement.Condition.AcceptVisitor(this);
Space(policy.SpacesWithinWhileParentheses);
RPar();
Semicolon();
EndNode(doWhileStatement);
}
public virtual void VisitEmptyStatement(EmptyStatement emptyStatement)
{
StartNode(emptyStatement);
Semicolon();
EndNode(emptyStatement);
}
public virtual void VisitExpressionStatement(ExpressionStatement expressionStatement)
{
StartNode(expressionStatement);
expressionStatement.Expression.AcceptVisitor(this);
Semicolon();
EndNode(expressionStatement);
}
public virtual void VisitFixedStatement(FixedStatement fixedStatement)
{
StartNode(fixedStatement);
WriteKeyword(FixedStatement.FixedKeywordRole);
Space(policy.SpaceBeforeUsingParentheses);
LPar();
Space(policy.SpacesWithinUsingParentheses);
fixedStatement.Type.AcceptVisitor(this);
Space();
WriteCommaSeparatedList(fixedStatement.Variables);
Space(policy.SpacesWithinUsingParentheses);
RPar();
WriteEmbeddedStatement(fixedStatement.EmbeddedStatement);
EndNode(fixedStatement);
}
public virtual void VisitForeachStatement(ForeachStatement foreachStatement)
{
StartNode(foreachStatement);
if (foreachStatement.IsAsync)
WriteKeyword(ForeachStatement.AwaitRole);
WriteKeyword(ForeachStatement.ForeachKeywordRole);
Space(policy.SpaceBeforeForeachParentheses);
LPar();
Space(policy.SpacesWithinForeachParentheses);
foreachStatement.VariableType.AcceptVisitor(this);
Space();
foreachStatement.VariableDesignation.AcceptVisitor(this);
Space();
WriteKeyword(ForeachStatement.InKeywordRole);
Space();
foreachStatement.InExpression.AcceptVisitor(this);
Space(policy.SpacesWithinForeachParentheses);
RPar();
WriteEmbeddedStatement(foreachStatement.EmbeddedStatement);
EndNode(foreachStatement);
}
public virtual void VisitForStatement(ForStatement forStatement)
{
StartNode(forStatement);
WriteKeyword(ForStatement.ForKeywordRole);
Space(policy.SpaceBeforeForParentheses);
LPar();
Space(policy.SpacesWithinForParentheses);
WriteCommaSeparatedList(forStatement.Initializers);
Space(policy.SpaceBeforeForSemicolon);
WriteToken(Roles.Semicolon);
Space(policy.SpaceAfterForSemicolon);
forStatement.Condition.AcceptVisitor(this);
Space(policy.SpaceBeforeForSemicolon);
WriteToken(Roles.Semicolon);
if (forStatement.Iterators.Any())
{
Space(policy.SpaceAfterForSemicolon);
WriteCommaSeparatedList(forStatement.Iterators);
}
Space(policy.SpacesWithinForParentheses);
RPar();
WriteEmbeddedStatement(forStatement.EmbeddedStatement);
EndNode(forStatement);
}
public virtual void VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
{
StartNode(gotoCaseStatement);
WriteKeyword(GotoCaseStatement.GotoKeywordRole);
WriteKeyword(GotoCaseStatement.CaseKeywordRole);
Space();
gotoCaseStatement.LabelExpression.AcceptVisitor(this);
Semicolon();
EndNode(gotoCaseStatement);
}
public virtual void VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
{
StartNode(gotoDefaultStatement);
WriteKeyword(GotoDefaultStatement.GotoKeywordRole);
WriteKeyword(GotoDefaultStatement.DefaultKeywordRole);
Semicolon();
EndNode(gotoDefaultStatement);
}
public virtual void VisitGotoStatement(GotoStatement gotoStatement)
{
StartNode(gotoStatement);
WriteKeyword(GotoStatement.GotoKeywordRole);
WriteIdentifier(gotoStatement.GetChildByRole(Roles.Identifier));
Semicolon();
EndNode(gotoStatement);
}
public virtual void VisitIfElseStatement(IfElseStatement ifElseStatement)
{
StartNode(ifElseStatement);
WriteKeyword(IfElseStatement.IfKeywordRole);
Space(policy.SpaceBeforeIfParentheses);
LPar();
Space(policy.SpacesWithinIfParentheses);
ifElseStatement.Condition.AcceptVisitor(this);
Space(policy.SpacesWithinIfParentheses);
RPar();
if (ifElseStatement.FalseStatement.IsNull)
{
WriteEmbeddedStatement(ifElseStatement.TrueStatement);
}
else
{
WriteEmbeddedStatement(ifElseStatement.TrueStatement, policy.ElseNewLinePlacement);
WriteKeyword(IfElseStatement.ElseKeywordRole);
if (ifElseStatement.FalseStatement is IfElseStatement)
{
// don't put newline between 'else' and 'if'
ifElseStatement.FalseStatement.AcceptVisitor(this);
}
else
{
WriteEmbeddedStatement(ifElseStatement.FalseStatement);
}
}
EndNode(ifElseStatement);
}
public virtual void VisitLabelStatement(LabelStatement labelStatement)
{
StartNode(labelStatement);
WriteIdentifier(labelStatement.GetChildByRole(Roles.Identifier));
WriteToken(Roles.Colon);
bool foundLabelledStatement = false;
for (AstNode tmp = labelStatement.NextSibling; tmp != null; tmp = tmp.NextSibling)
{
if (tmp.Role == labelStatement.Role)
{
foundLabelledStatement = true;
}
}
if (!foundLabelledStatement)
{
// introduce an EmptyStatement so that the output becomes syntactically valid
WriteToken(Roles.Semicolon);
}
NewLine();
EndNode(labelStatement);
}
public virtual void VisitLockStatement(LockStatement lockStatement)
{
StartNode(lockStatement);
WriteKeyword(LockStatement.LockKeywordRole);
Space(policy.SpaceBeforeLockParentheses);
LPar();
Space(policy.SpacesWithinLockParentheses);
lockStatement.Expression.AcceptVisitor(this);
Space(policy.SpacesWithinLockParentheses);
RPar();
WriteEmbeddedStatement(lockStatement.EmbeddedStatement);
EndNode(lockStatement);
}
public virtual void VisitReturnStatement(ReturnStatement returnStatement)
{
StartNode(returnStatement);
WriteKeyword(ReturnStatement.ReturnKeywordRole);
if (!returnStatement.Expression.IsNull)
{
Space();
returnStatement.Expression.AcceptVisitor(this);
}
Semicolon();
EndNode(returnStatement);
}
public virtual void VisitSwitchStatement(SwitchStatement switchStatement)
{
StartNode(switchStatement);
WriteKeyword(SwitchStatement.SwitchKeywordRole);
Space(policy.SpaceBeforeSwitchParentheses);
LPar();
Space(policy.SpacesWithinSwitchParentheses);
switchStatement.Expression.AcceptVisitor(this);
Space(policy.SpacesWithinSwitchParentheses);
RPar();
OpenBrace(policy.StatementBraceStyle);
if (!policy.IndentSwitchBody)
{
writer.Unindent();
}
foreach (var section in switchStatement.SwitchSections)
{
section.AcceptVisitor(this);
}
if (!policy.IndentSwitchBody)
{
writer.Indent();
}
CloseBrace(policy.StatementBraceStyle);
NewLine();
EndNode(switchStatement);
}
public virtual void VisitSwitchSection(SwitchSection switchSection)
{
StartNode(switchSection);
bool first = true;
foreach (var label in switchSection.CaseLabels)
{
if (!first)
{
NewLine();
}
label.AcceptVisitor(this);
first = false;
}
bool isBlock = switchSection.Statements.Count == 1 && switchSection.Statements.Single() is BlockStatement;
if (policy.IndentCaseBody && !isBlock)
{
writer.Indent();
}
if (!isBlock)
NewLine();
foreach (var statement in switchSection.Statements)
{
statement.AcceptVisitor(this);
}
if (policy.IndentCaseBody && !isBlock)
{
writer.Unindent();
}
EndNode(switchSection);
}
public virtual void VisitCaseLabel(CaseLabel caseLabel)
{
StartNode(caseLabel);
if (caseLabel.Expression.IsNull)
{
WriteKeyword(CaseLabel.DefaultKeywordRole);
}
else
{
WriteKeyword(CaseLabel.CaseKeywordRole);
Space();
caseLabel.Expression.AcceptVisitor(this);
}
WriteToken(Roles.Colon);
EndNode(caseLabel);
}
public virtual void VisitSwitchExpression(SwitchExpression switchExpression)
{
StartNode(switchExpression);
switchExpression.Expression.AcceptVisitor(this);
Space();
WriteKeyword(SwitchExpression.SwitchKeywordRole);
OpenBrace(policy.ArrayInitializerBraceStyle);
foreach (AstNode node in switchExpression.SwitchSections)
{
node.AcceptVisitor(this);
Comma(node);
NewLine();
}
CloseBrace(policy.ArrayInitializerBraceStyle);
EndNode(switchExpression);
}
public virtual void VisitSwitchExpressionSection(SwitchExpressionSection switchExpressionSection)
{
StartNode(switchExpressionSection);
switchExpressionSection.Pattern.AcceptVisitor(this);
Space();
WriteToken(Roles.Arrow);
Space();
switchExpressionSection.Body.AcceptVisitor(this);
EndNode(switchExpressionSection);
}
public virtual void VisitThrowStatement(ThrowStatement throwStatement)
{
StartNode(throwStatement);
WriteKeyword(ThrowStatement.ThrowKeywordRole);
if (!throwStatement.Expression.IsNull)
{
Space();
throwStatement.Expression.AcceptVisitor(this);
}
Semicolon();
EndNode(throwStatement);
}
public virtual void VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
{
StartNode(tryCatchStatement);
WriteKeyword(TryCatchStatement.TryKeywordRole);
WriteBlock(tryCatchStatement.TryBlock, policy.StatementBraceStyle);
foreach (var catchClause in tryCatchStatement.CatchClauses)
{
if (policy.CatchNewLinePlacement == NewLinePlacement.SameLine)
Space();
else
NewLine();
catchClause.AcceptVisitor(this);
}
if (!tryCatchStatement.FinallyBlock.IsNull)
{
if (policy.FinallyNewLinePlacement == NewLinePlacement.SameLine)
Space();
else
NewLine();
WriteKeyword(TryCatchStatement.FinallyKeywordRole);
WriteBlock(tryCatchStatement.FinallyBlock, policy.StatementBraceStyle);
}
NewLine();
EndNode(tryCatchStatement);
}
public virtual void VisitCatchClause(CatchClause catchClause)
{
StartNode(catchClause);
WriteKeyword(CatchClause.CatchKeywordRole);
if (!catchClause.Type.IsNull)
{
Space(policy.SpaceBeforeCatchParentheses);
LPar();
Space(policy.SpacesWithinCatchParentheses);
catchClause.Type.AcceptVisitor(this);
if (!string.IsNullOrEmpty(catchClause.VariableName))
{
Space();
WriteIdentifier(catchClause.VariableNameToken);
}
Space(policy.SpacesWithinCatchParentheses);
RPar();
}
if (!catchClause.Condition.IsNull)
{
Space();
WriteKeyword(CatchClause.WhenKeywordRole);
Space(policy.SpaceBeforeIfParentheses);
WriteToken(CatchClause.CondLPar);
Space(policy.SpacesWithinIfParentheses);
catchClause.Condition.AcceptVisitor(this);
Space(policy.SpacesWithinIfParentheses);
WriteToken(CatchClause.CondRPar);
}
WriteBlock(catchClause.Body, policy.StatementBraceStyle);
EndNode(catchClause);
}
public virtual void VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
{
StartNode(uncheckedStatement);
WriteKeyword(UncheckedStatement.UncheckedKeywordRole);
uncheckedStatement.Body.AcceptVisitor(this);
EndNode(uncheckedStatement);
}
public virtual void VisitUnsafeStatement(UnsafeStatement unsafeStatement)
{
StartNode(unsafeStatement);
WriteKeyword(UnsafeStatement.UnsafeKeywordRole);
unsafeStatement.Body.AcceptVisitor(this);
EndNode(unsafeStatement);
}
public virtual void VisitUsingStatement(UsingStatement usingStatement)
{
StartNode(usingStatement);
if (usingStatement.IsAsync)
{
WriteKeyword(UsingStatement.AwaitRole);
}
WriteKeyword(UsingStatement.UsingKeywordRole);
if (usingStatement.IsEnhanced)
{
Space();
}
else
{
Space(policy.SpaceBeforeUsingParentheses);
LPar();
Space(policy.SpacesWithinUsingParentheses);
}
usingStatement.ResourceAcquisition.AcceptVisitor(this);
if (usingStatement.IsEnhanced)
{
Semicolon();
}
else
{
Space(policy.SpacesWithinUsingParentheses);
RPar();
}
if (usingStatement.IsEnhanced)
{
if (usingStatement.EmbeddedStatement is BlockStatement blockStatement)
{
StartNode(blockStatement);
foreach (var node in blockStatement.Statements)
{
node.AcceptVisitor(this);
}
EndNode(blockStatement);
}
else
{
usingStatement.EmbeddedStatement.AcceptVisitor(this);
}
}
else
{
WriteEmbeddedStatement(usingStatement.EmbeddedStatement);
}
EndNode(usingStatement);
}
public virtual void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
{
StartNode(variableDeclarationStatement);
WriteModifiers(variableDeclarationStatement.GetChildrenByRole(VariableDeclarationStatement.ModifierRole));
variableDeclarationStatement.Type.AcceptVisitor(this);
Space();
WriteCommaSeparatedList(variableDeclarationStatement.Variables);
Semicolon();
EndNode(variableDeclarationStatement);
}
public virtual void VisitLocalFunctionDeclarationStatement(LocalFunctionDeclarationStatement localFunctionDeclarationStatement)
{
StartNode(localFunctionDeclarationStatement);
localFunctionDeclarationStatement.Declaration.AcceptVisitor(this);
EndNode(localFunctionDeclarationStatement);
}
public virtual void VisitWhileStatement(WhileStatement whileStatement)
{
StartNode(whileStatement);
WriteKeyword(WhileStatement.WhileKeywordRole);
Space(policy.SpaceBeforeWhileParentheses);
LPar();
Space(policy.SpacesWithinWhileParentheses);
whileStatement.Condition.AcceptVisitor(this);
Space(policy.SpacesWithinWhileParentheses);
RPar();
WriteEmbeddedStatement(whileStatement.EmbeddedStatement);
EndNode(whileStatement);
}
public virtual void VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
{
StartNode(yieldBreakStatement);
WriteKeyword(YieldBreakStatement.YieldKeywordRole);
WriteKeyword(YieldBreakStatement.BreakKeywordRole);
Semicolon();
EndNode(yieldBreakStatement);
}
public virtual void VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement)
{
StartNode(yieldReturnStatement);
WriteKeyword(YieldReturnStatement.YieldKeywordRole);
WriteKeyword(YieldReturnStatement.ReturnKeywordRole);
Space();
yieldReturnStatement.Expression.AcceptVisitor(this);
Semicolon();
EndNode(yieldReturnStatement);
}
#endregion
#region TypeMembers
public virtual void VisitAccessor(Accessor accessor)
{
StartNode(accessor);
WriteAttributes(accessor.Attributes);
WriteModifiers(accessor.ModifierTokens);
BraceStyle style = policy.StatementBraceStyle;
if (accessor.Role == PropertyDeclaration.GetterRole)
{
WriteKeyword("get", PropertyDeclaration.GetKeywordRole);
style = policy.PropertyGetBraceStyle;
}
else if (accessor.Role == PropertyDeclaration.SetterRole)
{
if (accessor.Keyword.Role == PropertyDeclaration.InitKeywordRole)
{
WriteKeyword("init", PropertyDeclaration.InitKeywordRole);
}
else
{
WriteKeyword("set", PropertyDeclaration.SetKeywordRole);
}
style = policy.PropertySetBraceStyle;
}
else if (accessor.Role == CustomEventDeclaration.AddAccessorRole)
{
WriteKeyword("add", CustomEventDeclaration.AddKeywordRole);
style = policy.EventAddBraceStyle;
}
else if (accessor.Role == CustomEventDeclaration.RemoveAccessorRole)
{
WriteKeyword("remove", CustomEventDeclaration.RemoveKeywordRole);
style = policy.EventRemoveBraceStyle;
}
WriteMethodBody(accessor.Body, style);
EndNode(accessor);
}
public virtual void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
StartNode(constructorDeclaration);
WriteAttributes(constructorDeclaration.Attributes);
WriteModifiers(constructorDeclaration.ModifierTokens);
TypeDeclaration type = constructorDeclaration.Parent as TypeDeclaration;
if (type != null && type.Name != constructorDeclaration.Name)
WriteIdentifier((Identifier)type.NameToken.Clone());
else
WriteIdentifier(constructorDeclaration.NameToken);
Space(policy.SpaceBeforeConstructorDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(constructorDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
if (!constructorDeclaration.Initializer.IsNull)
{
NewLine();
writer.Indent();
constructorDeclaration.Initializer.AcceptVisitor(this);
writer.Unindent();
}
WriteMethodBody(constructorDeclaration.Body, policy.ConstructorBraceStyle);
EndNode(constructorDeclaration);
}
public virtual void VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
{
StartNode(constructorInitializer);
WriteToken(Roles.Colon);
Space();
if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.This)
{
WriteKeyword(ConstructorInitializer.ThisKeywordRole);
}
else
{
WriteKeyword(ConstructorInitializer.BaseKeywordRole);
}
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(constructorInitializer.Arguments, policy.SpaceWithinMethodCallParentheses);
EndNode(constructorInitializer);
}
public virtual void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
{
StartNode(destructorDeclaration);
WriteAttributes(destructorDeclaration.Attributes);
WriteModifiers(destructorDeclaration.ModifierTokens);
if (destructorDeclaration.ModifierTokens.Any())
{
Space();
}
WriteToken(DestructorDeclaration.TildeRole);
TypeDeclaration type = destructorDeclaration.Parent as TypeDeclaration;
if (type != null && type.Name != destructorDeclaration.Name)
WriteIdentifier((Identifier)type.NameToken.Clone());
else
WriteIdentifier(destructorDeclaration.NameToken);
Space(policy.SpaceBeforeConstructorDeclarationParentheses);
LPar();
RPar();
WriteMethodBody(destructorDeclaration.Body, policy.DestructorBraceStyle);
EndNode(destructorDeclaration);
}
public virtual void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
{
StartNode(enumMemberDeclaration);
WriteAttributes(enumMemberDeclaration.Attributes);
WriteModifiers(enumMemberDeclaration.ModifierTokens);
WriteIdentifier(enumMemberDeclaration.NameToken);
if (!enumMemberDeclaration.Initializer.IsNull)
{
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
enumMemberDeclaration.Initializer.AcceptVisitor(this);
}
EndNode(enumMemberDeclaration);
}
public virtual void VisitEventDeclaration(EventDeclaration eventDeclaration)
{
StartNode(eventDeclaration);
WriteAttributes(eventDeclaration.Attributes);
WriteModifiers(eventDeclaration.ModifierTokens);
WriteKeyword(EventDeclaration.EventKeywordRole);
eventDeclaration.ReturnType.AcceptVisitor(this);
Space();
WriteCommaSeparatedList(eventDeclaration.Variables);
Semicolon();
EndNode(eventDeclaration);
}
public virtual void VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration)
{
StartNode(customEventDeclaration);
WriteAttributes(customEventDeclaration.Attributes);
WriteModifiers(customEventDeclaration.ModifierTokens);
WriteKeyword(CustomEventDeclaration.EventKeywordRole);
customEventDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(customEventDeclaration.PrivateImplementationType);
WriteIdentifier(customEventDeclaration.NameToken);
OpenBrace(policy.EventBraceStyle);
// output add/remove in their original order
foreach (AstNode node in customEventDeclaration.Children)
{
if (node.Role == CustomEventDeclaration.AddAccessorRole || node.Role == CustomEventDeclaration.RemoveAccessorRole)
{
node.AcceptVisitor(this);
}
}
CloseBrace(policy.EventBraceStyle);
NewLine();
EndNode(customEventDeclaration);
}
public virtual void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
{
StartNode(fieldDeclaration);
WriteAttributes(fieldDeclaration.Attributes);
WriteModifiers(fieldDeclaration.ModifierTokens);
fieldDeclaration.ReturnType.AcceptVisitor(this);
Space();
WriteCommaSeparatedList(fieldDeclaration.Variables);
Semicolon();
EndNode(fieldDeclaration);
}
public virtual void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
{
StartNode(fixedFieldDeclaration);
WriteAttributes(fixedFieldDeclaration.Attributes);
WriteModifiers(fixedFieldDeclaration.ModifierTokens);
WriteKeyword(FixedFieldDeclaration.FixedKeywordRole);
Space();
fixedFieldDeclaration.ReturnType.AcceptVisitor(this);
Space();
WriteCommaSeparatedList(fixedFieldDeclaration.Variables);
Semicolon();
EndNode(fixedFieldDeclaration);
}
public virtual void VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
{
StartNode(fixedVariableInitializer);
WriteIdentifier(fixedVariableInitializer.NameToken);
if (!fixedVariableInitializer.CountExpression.IsNull)
{
WriteToken(Roles.LBracket);
Space(policy.SpacesWithinBrackets);
fixedVariableInitializer.CountExpression.AcceptVisitor(this);
Space(policy.SpacesWithinBrackets);
WriteToken(Roles.RBracket);
}
EndNode(fixedVariableInitializer);
}
public virtual void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
StartNode(indexerDeclaration);
WriteAttributes(indexerDeclaration.Attributes);
WriteModifiers(indexerDeclaration.ModifierTokens);
indexerDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(indexerDeclaration.PrivateImplementationType);
WriteKeyword(IndexerDeclaration.ThisKeywordRole);
Space(policy.SpaceBeforeMethodDeclarationParentheses);
WriteCommaSeparatedListInBrackets(indexerDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
if (indexerDeclaration.ExpressionBody.IsNull)
{
bool isSingleLine =
(policy.AutoPropertyFormatting == PropertyFormatting.SingleLine)
&& (indexerDeclaration.Getter.IsNull || indexerDeclaration.Getter.Body.IsNull)
&& (indexerDeclaration.Setter.IsNull || indexerDeclaration.Setter.Body.IsNull)
&& !indexerDeclaration.Getter.Attributes.Any()
&& !indexerDeclaration.Setter.Attributes.Any();
OpenBrace(isSingleLine ? BraceStyle.EndOfLine : policy.PropertyBraceStyle, newLine: !isSingleLine);
if (isSingleLine)
Space();
// output get/set in their original order
foreach (AstNode node in indexerDeclaration.Children)
{
if (node.Role == IndexerDeclaration.GetterRole || node.Role == IndexerDeclaration.SetterRole)
{
node.AcceptVisitor(this);
}
}
CloseBrace(isSingleLine ? BraceStyle.EndOfLine : policy.PropertyBraceStyle, unindent: !isSingleLine);
NewLine();
}
else
{
Space();
WriteToken(Roles.Arrow);
Space();
indexerDeclaration.ExpressionBody.AcceptVisitor(this);
Semicolon();
}
EndNode(indexerDeclaration);
}
public virtual void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
StartNode(methodDeclaration);
WriteAttributes(methodDeclaration.Attributes);
WriteModifiers(methodDeclaration.ModifierTokens);
methodDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(methodDeclaration.PrivateImplementationType);
WriteIdentifier(methodDeclaration.NameToken);
WriteTypeParameters(methodDeclaration.TypeParameters);
Space(policy.SpaceBeforeMethodDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(methodDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
foreach (Constraint constraint in methodDeclaration.Constraints)
{
constraint.AcceptVisitor(this);
}
WriteMethodBody(methodDeclaration.Body, policy.MethodBraceStyle);
EndNode(methodDeclaration);
}
public virtual void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
StartNode(operatorDeclaration);
WriteAttributes(operatorDeclaration.Attributes);
WriteModifiers(operatorDeclaration.ModifierTokens);
if (operatorDeclaration.OperatorType == OperatorType.Explicit || operatorDeclaration.OperatorType == OperatorType.CheckedExplicit)
{
WriteKeyword(OperatorDeclaration.ExplicitRole);
}
else if (operatorDeclaration.OperatorType == OperatorType.Implicit)
{
WriteKeyword(OperatorDeclaration.ImplicitRole);
}
else
{
operatorDeclaration.ReturnType.AcceptVisitor(this);
}
Space();
WritePrivateImplementationType(operatorDeclaration.PrivateImplementationType);
WriteKeyword(OperatorDeclaration.OperatorKeywordRole);
Space();
if (OperatorDeclaration.IsChecked(operatorDeclaration.OperatorType))
{
WriteKeyword(OperatorDeclaration.CheckedKeywordRole);
Space();
}
if (operatorDeclaration.OperatorType == OperatorType.Explicit
|| operatorDeclaration.OperatorType == OperatorType.CheckedExplicit
|| operatorDeclaration.OperatorType == OperatorType.Implicit)
{
operatorDeclaration.ReturnType.AcceptVisitor(this);
}
else
{
WriteToken(OperatorDeclaration.GetToken(operatorDeclaration.OperatorType), OperatorDeclaration.GetRole(operatorDeclaration.OperatorType));
}
Space(policy.SpaceBeforeMethodDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(operatorDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
WriteMethodBody(operatorDeclaration.Body, policy.MethodBraceStyle);
EndNode(operatorDeclaration);
}
public virtual void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
{
StartNode(parameterDeclaration);
WriteAttributes(parameterDeclaration.Attributes);
if (parameterDeclaration.HasThisModifier)
{
WriteKeyword(ParameterDeclaration.ThisModifierRole);
Space();
}
if (parameterDeclaration.IsScopedRef)
{
WriteKeyword(ParameterDeclaration.ScopedRefRole);
Space();
}
switch (parameterDeclaration.ParameterModifier)
{
case ParameterModifier.Ref:
WriteKeyword(ParameterDeclaration.RefModifierRole);
Space();
break;
case ParameterModifier.Out:
WriteKeyword(ParameterDeclaration.OutModifierRole);
Space();
break;
case ParameterModifier.Params:
WriteKeyword(ParameterDeclaration.ParamsModifierRole);
Space();
break;
case ParameterModifier.In:
WriteKeyword(ParameterDeclaration.InModifierRole);
Space();
break;
}
parameterDeclaration.Type.AcceptVisitor(this);
if (!parameterDeclaration.Type.IsNull && !string.IsNullOrEmpty(parameterDeclaration.Name))
{
Space();
}
if (!string.IsNullOrEmpty(parameterDeclaration.Name))
{
WriteIdentifier(parameterDeclaration.NameToken);
}
if (parameterDeclaration.HasNullCheck)
{
WriteToken(Roles.DoubleExclamation);
}
if (!parameterDeclaration.DefaultExpression.IsNull)
{
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
parameterDeclaration.DefaultExpression.AcceptVisitor(this);
}
EndNode(parameterDeclaration);
}
public virtual void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
StartNode(propertyDeclaration);
WriteAttributes(propertyDeclaration.Attributes);
WriteModifiers(propertyDeclaration.ModifierTokens);
propertyDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(propertyDeclaration.PrivateImplementationType);
WriteIdentifier(propertyDeclaration.NameToken);
if (propertyDeclaration.ExpressionBody.IsNull)
{
bool isSingleLine =
(policy.AutoPropertyFormatting == PropertyFormatting.SingleLine)
&& (propertyDeclaration.Getter.IsNull || propertyDeclaration.Getter.Body.IsNull)
&& (propertyDeclaration.Setter.IsNull || propertyDeclaration.Setter.Body.IsNull)
&& !propertyDeclaration.Getter.Attributes.Any()
&& !propertyDeclaration.Setter.Attributes.Any();
OpenBrace(isSingleLine ? BraceStyle.EndOfLine : policy.PropertyBraceStyle, newLine: !isSingleLine);
if (isSingleLine)
Space();
// output get/set in their original order
foreach (AstNode node in propertyDeclaration.Children)
{
if (node.Role == IndexerDeclaration.GetterRole || node.Role == IndexerDeclaration.SetterRole)
{
node.AcceptVisitor(this);
}
}
CloseBrace(isSingleLine ? BraceStyle.EndOfLine : policy.PropertyBraceStyle, unindent: !isSingleLine);
if (!propertyDeclaration.Initializer.IsNull)
{
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
propertyDeclaration.Initializer.AcceptVisitor(this);
Semicolon();
}
NewLine();
}
else
{
Space();
WriteToken(Roles.Arrow);
Space();
propertyDeclaration.ExpressionBody.AcceptVisitor(this);
Semicolon();
}
EndNode(propertyDeclaration);
}
#endregion
#region Other nodes
public virtual void VisitVariableInitializer(VariableInitializer variableInitializer)
{
StartNode(variableInitializer);
WriteIdentifier(variableInitializer.NameToken);
if (!variableInitializer.Initializer.IsNull)
{
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
variableInitializer.Initializer.AcceptVisitor(this);
}
EndNode(variableInitializer);
}
void MaybeNewLinesAfterUsings(AstNode node)
{
var nextSibling = node.NextSibling;
if ((node is UsingDeclaration || node is UsingAliasDeclaration) && !(nextSibling is UsingDeclaration || nextSibling is UsingAliasDeclaration))
{
for (int i = 0; i < policy.MinimumBlankLinesAfterUsings; i++)
NewLine();
}
}
public virtual void VisitSyntaxTree(SyntaxTree syntaxTree)
{
// don't do node tracking as we visit all children directly
foreach (AstNode node in syntaxTree.Children)
{
node.AcceptVisitor(this);
MaybeNewLinesAfterUsings(node);
}
}
public virtual void VisitSimpleType(SimpleType simpleType)
{
StartNode(simpleType);
WriteIdentifier(simpleType.IdentifierToken);
WriteTypeArguments(simpleType.TypeArguments);
EndNode(simpleType);
}
public virtual void VisitMemberType(MemberType memberType)
{
StartNode(memberType);
memberType.Target.AcceptVisitor(this);
if (memberType.IsDoubleColon)
{
WriteToken(Roles.DoubleColon);
}
else
{
WriteToken(Roles.Dot);
}
WriteIdentifier(memberType.MemberNameToken);
WriteTypeArguments(memberType.TypeArguments);
EndNode(memberType);
}
public virtual void VisitTupleType(TupleAstType tupleType)
{
Debug.Assert(tupleType.Elements.Count >= 2);
StartNode(tupleType);
LPar();
WriteCommaSeparatedList(tupleType.Elements);
RPar();
EndNode(tupleType);
}
public virtual void VisitTupleTypeElement(TupleTypeElement tupleTypeElement)
{
StartNode(tupleTypeElement);
tupleTypeElement.Type.AcceptVisitor(this);
if (!tupleTypeElement.NameToken.IsNull)
{
Space();
tupleTypeElement.NameToken.AcceptVisitor(this);
}
EndNode(tupleTypeElement);
}
public virtual void VisitFunctionPointerType(FunctionPointerAstType functionPointerType)
{
StartNode(functionPointerType);
WriteKeyword(Roles.DelegateKeyword);
WriteToken(FunctionPointerAstType.PointerRole);
if (functionPointerType.HasUnmanagedCallingConvention)
{
Space();
WriteKeyword("unmanaged");
}
if (functionPointerType.CallingConventions.Any())
{
WriteToken(Roles.LBracket);
WriteCommaSeparatedList(functionPointerType.CallingConventions);
WriteToken(Roles.RBracket);
}
WriteToken(Roles.LChevron);
WriteCommaSeparatedList(
functionPointerType.Parameters.Concat<AstNode>(new[] { functionPointerType.ReturnType }));
WriteToken(Roles.RChevron);
EndNode(functionPointerType);
}
public virtual void VisitInvocationType(InvocationAstType invocationType)
{
StartNode(invocationType);
invocationType.BaseType.AcceptVisitor(this);
WriteToken(Roles.LPar);
WriteCommaSeparatedList(invocationType.Arguments);
WriteToken(Roles.RPar);
EndNode(invocationType);
}
public virtual void VisitComposedType(ComposedType composedType)
{
StartNode(composedType);
if (composedType.Attributes.Any())
{
foreach (var attr in composedType.Attributes)
{
attr.AcceptVisitor(this);
}
}
if (composedType.HasRefSpecifier)
{
WriteKeyword(ComposedType.RefRole);
}
if (composedType.HasReadOnlySpecifier)
{
WriteKeyword(ComposedType.ReadonlyRole);
}
composedType.BaseType.AcceptVisitor(this);
if (composedType.HasNullableSpecifier)
{
WriteToken(ComposedType.NullableRole);
}
for (int i = 0; i < composedType.PointerRank; i++)
{
WriteToken(ComposedType.PointerRole);
}
foreach (var node in composedType.ArraySpecifiers)
{
node.AcceptVisitor(this);
}
EndNode(composedType);
}
public virtual void VisitArraySpecifier(ArraySpecifier arraySpecifier)
{
StartNode(arraySpecifier);
WriteToken(Roles.LBracket);
foreach (var comma in arraySpecifier.GetChildrenByRole(Roles.Comma))
{
writer.WriteToken(Roles.Comma, ",");
}
WriteToken(Roles.RBracket);
EndNode(arraySpecifier);
}
public virtual void VisitPrimitiveType(PrimitiveType primitiveType)
{
StartNode(primitiveType);
writer.WritePrimitiveType(primitiveType.Keyword);
isAfterSpace = false;
EndNode(primitiveType);
}
public virtual void VisitSingleVariableDesignation(SingleVariableDesignation singleVariableDesignation)
{
StartNode(singleVariableDesignation);
WriteIdentifier(singleVariableDesignation.IdentifierToken);
EndNode(singleVariableDesignation);
}
public virtual void VisitParenthesizedVariableDesignation(ParenthesizedVariableDesignation parenthesizedVariableDesignation)
{
StartNode(parenthesizedVariableDesignation);
LPar();
WriteCommaSeparatedList(parenthesizedVariableDesignation.VariableDesignations);
RPar();
EndNode(parenthesizedVariableDesignation);
}
public virtual void VisitComment(Comment comment)
{
writer.StartNode(comment);
writer.WriteComment(comment.CommentType, comment.Content);
writer.EndNode(comment);
}
public virtual void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
{
writer.StartNode(preProcessorDirective);
writer.WritePreProcessorDirective(preProcessorDirective.Type, preProcessorDirective.Argument);
writer.EndNode(preProcessorDirective);
}
public virtual void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
{
StartNode(typeParameterDeclaration);
WriteAttributes(typeParameterDeclaration.Attributes);
switch (typeParameterDeclaration.Variance)
{
case VarianceModifier.Invariant:
break;
case VarianceModifier.Covariant:
WriteKeyword(TypeParameterDeclaration.OutVarianceKeywordRole);
break;
case VarianceModifier.Contravariant:
WriteKeyword(TypeParameterDeclaration.InVarianceKeywordRole);
break;
default:
throw new NotSupportedException("Invalid value for VarianceModifier");
}
WriteIdentifier(typeParameterDeclaration.NameToken);
EndNode(typeParameterDeclaration);
}
public virtual void VisitConstraint(Constraint constraint)
{
StartNode(constraint);
Space();
WriteKeyword(Roles.WhereKeyword);
constraint.TypeParameter.AcceptVisitor(this);
Space();
WriteToken(Roles.Colon);
Space();
WriteCommaSeparatedList(constraint.BaseTypes);
EndNode(constraint);
}
public virtual void VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
{
CSharpModifierToken mod = cSharpTokenNode as CSharpModifierToken;
if (mod != null)
{
// ITokenWriter assumes that each node processed between a
// StartNode(parentNode)-EndNode(parentNode)-pair is a child of parentNode.
WriteKeyword(CSharpModifierToken.GetModifierName(mod.Modifier), cSharpTokenNode.Role);
}
else
{
throw new NotSupportedException("Should never visit individual tokens");
}
}
public virtual void VisitIdentifier(Identifier identifier)
{
// Do not call StartNode and EndNode for Identifier, because they are handled by the ITokenWriter.
// ITokenWriter assumes that each node processed between a
// StartNode(parentNode)-EndNode(parentNode)-pair is a child of parentNode.
WriteIdentifier(identifier);
}
void IAstVisitor.VisitNullNode(AstNode nullNode)
{
}
void IAstVisitor.VisitErrorNode(AstNode errorNode)
{
StartNode(errorNode);
EndNode(errorNode);
}
#endregion
#region Pattern Nodes
public virtual void VisitPatternPlaceholder(AstNode placeholder, Pattern pattern)
{
StartNode(placeholder);
VisitNodeInPattern(pattern);
EndNode(placeholder);
}
void VisitAnyNode(AnyNode anyNode)
{
if (!string.IsNullOrEmpty(anyNode.GroupName))
{
WriteIdentifier(anyNode.GroupName);
WriteToken(Roles.Colon);
}
}
void VisitBackreference(Backreference backreference)
{
WriteKeyword("backreference");
LPar();
WriteIdentifier(backreference.ReferencedGroupName);
RPar();
}
void VisitIdentifierExpressionBackreference(IdentifierExpressionBackreference identifierExpressionBackreference)
{
WriteKeyword("identifierBackreference");
LPar();
WriteIdentifier(identifierExpressionBackreference.ReferencedGroupName);
RPar();
}
void VisitChoice(Choice choice)
{
WriteKeyword("choice");
Space();
LPar();
NewLine();
writer.Indent();
foreach (INode alternative in choice)
{
VisitNodeInPattern(alternative);
if (alternative != choice.Last())
{
WriteToken(Roles.Comma);
}
NewLine();
}
writer.Unindent();
RPar();
}
void VisitNamedNode(NamedNode namedNode)
{
if (!string.IsNullOrEmpty(namedNode.GroupName))
{
WriteIdentifier(namedNode.GroupName);
WriteToken(Roles.Colon);
}
VisitNodeInPattern(namedNode.ChildNode);
}
void VisitRepeat(Repeat repeat)
{
WriteKeyword("repeat");
LPar();
if (repeat.MinCount != 0 || repeat.MaxCount != int.MaxValue)
{
WriteIdentifier(repeat.MinCount.ToString());
WriteToken(Roles.Comma);
WriteIdentifier(repeat.MaxCount.ToString());
WriteToken(Roles.Comma);
}
VisitNodeInPattern(repeat.ChildNode);
RPar();
}
void VisitOptionalNode(OptionalNode optionalNode)
{
WriteKeyword("optional");
LPar();
VisitNodeInPattern(optionalNode.ChildNode);
RPar();
}
void VisitNodeInPattern(INode childNode)
{
if (childNode is AstNode)
{
((AstNode)childNode).AcceptVisitor(this);
}
else if (childNode is IdentifierExpressionBackreference)
{
VisitIdentifierExpressionBackreference((IdentifierExpressionBackreference)childNode);
}
else if (childNode is Choice)
{
VisitChoice((Choice)childNode);
}
else if (childNode is AnyNode)
{
VisitAnyNode((AnyNode)childNode);
}
else if (childNode is Backreference)
{
VisitBackreference((Backreference)childNode);
}
else if (childNode is NamedNode)
{
VisitNamedNode((NamedNode)childNode);
}
else if (childNode is OptionalNode)
{
VisitOptionalNode((OptionalNode)childNode);
}
else if (childNode is Repeat)
{
VisitRepeat((Repeat)childNode);
}
else
{
writer.WritePrimitiveValue(childNode);
}
}
#endregion
#region Documentation Reference
public virtual void VisitDocumentationReference(DocumentationReference documentationReference)
{
StartNode(documentationReference);
if (!documentationReference.DeclaringType.IsNull)
{
documentationReference.DeclaringType.AcceptVisitor(this);
if (documentationReference.SymbolKind != SymbolKind.TypeDefinition)
{
WriteToken(Roles.Dot);
}
}
switch (documentationReference.SymbolKind)
{
case SymbolKind.TypeDefinition:
// we already printed the DeclaringType
break;
case SymbolKind.Indexer:
WriteKeyword(IndexerDeclaration.ThisKeywordRole);
break;
case SymbolKind.Operator:
var opType = documentationReference.OperatorType;
if (opType == OperatorType.Explicit || opType == OperatorType.CheckedExplicit)
{
WriteKeyword(OperatorDeclaration.ExplicitRole);
}
else if (opType == OperatorType.Implicit)
{
WriteKeyword(OperatorDeclaration.ImplicitRole);
}
WriteKeyword(OperatorDeclaration.OperatorKeywordRole);
Space();
if (OperatorDeclaration.IsChecked(opType))
{
WriteKeyword(OperatorDeclaration.CheckedKeywordRole);
Space();
}
if (opType == OperatorType.Explicit || opType == OperatorType.Implicit || opType == OperatorType.CheckedExplicit)
{
documentationReference.ConversionOperatorReturnType.AcceptVisitor(this);
}
else
{
WriteToken(OperatorDeclaration.GetToken(opType), OperatorDeclaration.GetRole(opType));
}
break;
default:
WriteIdentifier(documentationReference.GetChildByRole(Roles.Identifier));
break;
}
WriteTypeArguments(documentationReference.TypeArguments);
if (documentationReference.HasParameterList)
{
Space(policy.SpaceBeforeMethodDeclarationParentheses);
if (documentationReference.SymbolKind == SymbolKind.Indexer)
{
WriteCommaSeparatedListInBrackets(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
}
else
{
WriteCommaSeparatedListInParenthesis(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
}
}
EndNode(documentationReference);
}
#endregion
/// <summary>
/// Converts special characters to escape sequences within the given string.
/// </summary>
public static string ConvertString(string text)
{
return TextWriterTokenWriter.ConvertString(text);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs",
"repo_id": "ILSpy",
"token_count": 34598
} | 216 |
// Copyright (c) 2020 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp
{
class RecordDecompiler
{
readonly IDecompilerTypeSystem typeSystem;
readonly ITypeDefinition recordTypeDef;
readonly DecompilerSettings settings;
readonly CancellationToken cancellationToken;
readonly List<IMember> orderedMembers;
readonly bool isInheritedRecord;
readonly bool isStruct;
readonly bool isSealed;
readonly IMethod primaryCtor;
readonly IType baseClass;
readonly Dictionary<IField, IProperty> backingFieldToAutoProperty = new Dictionary<IField, IProperty>();
readonly Dictionary<IProperty, IField> autoPropertyToBackingField = new Dictionary<IProperty, IField>();
readonly Dictionary<IParameter, IProperty> primaryCtorParameterToAutoProperty = new Dictionary<IParameter, IProperty>();
readonly Dictionary<IProperty, IParameter> autoPropertyToPrimaryCtorParameter = new Dictionary<IProperty, IParameter>();
public RecordDecompiler(IDecompilerTypeSystem dts, ITypeDefinition recordTypeDef, DecompilerSettings settings, CancellationToken cancellationToken)
{
this.typeSystem = dts;
this.recordTypeDef = recordTypeDef;
this.settings = settings;
this.cancellationToken = cancellationToken;
this.baseClass = recordTypeDef.DirectBaseTypes.FirstOrDefault(b => b.Kind == TypeKind.Class);
this.isStruct = baseClass?.IsKnownType(KnownTypeCode.ValueType) ?? false;
this.isInheritedRecord = !isStruct && !(baseClass?.IsKnownType(KnownTypeCode.Object) ?? false);
this.isSealed = recordTypeDef.IsSealed;
DetectAutomaticProperties();
this.orderedMembers = DetectMemberOrder(recordTypeDef, backingFieldToAutoProperty);
this.primaryCtor = DetectPrimaryConstructor();
}
void DetectAutomaticProperties()
{
var subst = recordTypeDef.AsParameterizedType().GetSubstitution();
foreach (var property in recordTypeDef.Properties)
{
cancellationToken.ThrowIfCancellationRequested();
var p = (IProperty)property.Specialize(subst);
if (IsAutoProperty(p, out var field))
{
backingFieldToAutoProperty.Add(field, p);
autoPropertyToBackingField.Add(p, field);
}
}
bool IsAutoProperty(IProperty p, out IField field)
{
field = null;
if (p.Parameters.Count != 0)
return false;
if (p.Getter != null)
{
if (!IsAutoGetter(p.Getter, out field))
return false;
}
if (p.Setter != null)
{
if (!IsAutoSetter(p.Setter, out var field2))
return false;
if (field != null)
{
if (!field.Equals(field2))
return false;
}
else
{
field = field2;
}
}
if (field == null)
return false;
if (!IsRecordType(field.DeclaringType))
return false;
return field.Name == $"<{p.Name}>k__BackingField";
}
bool IsAutoGetter(IMethod method, out IField field)
{
field = null;
var body = DecompileBody(method);
if (body == null)
return false;
// return this.field;
if (!body.Instructions[0].MatchReturn(out var retVal))
return false;
if (method.IsStatic)
{
return retVal.MatchLdsFld(out field);
}
else
{
if (!retVal.MatchLdFld(out var target, out field))
return false;
return target.MatchLdThis();
}
}
bool IsAutoSetter(IMethod method, out IField field)
{
field = null;
Debug.Assert(!method.IsStatic);
var body = DecompileBody(method);
if (body == null)
return false;
// this.field = value;
ILInstruction valueInst;
if (method.IsStatic)
{
if (!body.Instructions[0].MatchStsFld(out field, out valueInst))
return false;
}
else
{
if (!body.Instructions[0].MatchStFld(out var target, out field, out valueInst))
return false;
if (!target.MatchLdThis())
return false;
}
if (!valueInst.MatchLdLoc(out var value))
return false;
if (!(value.Kind == VariableKind.Parameter && value.Index == 0))
return false;
return body.Instructions[1].MatchReturn(out var retVal) && retVal.MatchNop();
}
}
IMethod DetectPrimaryConstructor()
{
if (!settings.UsePrimaryConstructorSyntax)
return null;
var subst = recordTypeDef.AsParameterizedType().GetSubstitution();
foreach (var method in recordTypeDef.Methods)
{
cancellationToken.ThrowIfCancellationRequested();
if (method.IsStatic || !method.IsConstructor)
continue;
var m = method.Specialize(subst);
if (IsPrimaryConstructor(m, method))
return method;
primaryCtorParameterToAutoProperty.Clear();
autoPropertyToPrimaryCtorParameter.Clear();
}
return null;
bool IsPrimaryConstructor(IMethod method, IMethod unspecializedMethod)
{
Debug.Assert(method.IsConstructor);
var body = DecompileBody(method);
if (body == null)
return false;
if (method.Parameters.Count == 0)
return false;
var addonInst = isStruct ? 1 : 2;
if (body.Instructions.Count < method.Parameters.Count + addonInst)
return false;
for (int i = 0; i < method.Parameters.Count; i++)
{
if (!body.Instructions[i].MatchStFld(out var target, out var field, out var valueInst))
return false;
if (!target.MatchLdThis())
return false;
if (method.Parameters[i].IsIn)
{
if (!valueInst.MatchLdObj(out valueInst, out _))
return false;
}
if (!valueInst.MatchLdLoc(out var value))
return false;
if (!(value.Kind == VariableKind.Parameter && value.Index == i))
return false;
if (!backingFieldToAutoProperty.TryGetValue(field, out var property))
return false;
primaryCtorParameterToAutoProperty.Add(unspecializedMethod.Parameters[i], property);
autoPropertyToPrimaryCtorParameter.Add(property, unspecializedMethod.Parameters[i]);
}
if (!isStruct)
{
var baseCtorCall = body.Instructions.SecondToLastOrDefault() as CallInstruction;
if (baseCtorCall == null)
return false;
}
var returnInst = body.Instructions.LastOrDefault();
return returnInst != null && returnInst.MatchReturn(out var retVal) && retVal.MatchNop();
}
}
static List<IMember> DetectMemberOrder(ITypeDefinition recordTypeDef, Dictionary<IField, IProperty> backingFieldToAutoProperty)
{
// For records, the order of members is important:
// Equals/GetHashCode/PrintMembers must agree on an order of fields+properties.
// The IL metadata has the order of fields and the order of properties, but we
// need to detect the correct interleaving.
// We could try to detect this from the PrintMembers body, but let's initially
// restrict ourselves to the common case where the record only uses properties.
var subst = recordTypeDef.AsParameterizedType().GetSubstitution();
return recordTypeDef.Properties.Select(p => p.Specialize(subst)).Concat(
recordTypeDef.Fields.Select(f => (IField)f.Specialize(subst)).Where(f => !backingFieldToAutoProperty.ContainsKey(f))
).ToList();
}
/// <summary>
/// Gets the fields and properties of the record type, interleaved as necessary to
/// maintain Equals/ToString/etc. semantics.
/// </summary>
public IEnumerable<IMember> FieldsAndProperties => orderedMembers;
/// <summary>
/// Gets the detected primary constructor. Returns null, if there was no primary constructor detected.
/// </summary>
public IMethod PrimaryConstructor => primaryCtor;
public bool IsInheritedRecord => isInheritedRecord;
bool IsRecordType(IType type)
{
return type.GetDefinition() == recordTypeDef
&& type.TypeArguments.SequenceEqual(recordTypeDef.TypeParameters);
}
/// <summary>
/// Gets whether the member of the record type will be automatically generated by the compiler.
/// </summary>
public bool MethodIsGenerated(IMethod method)
{
if (IsCopyConstructor(method))
{
return IsGeneratedCopyConstructor(method);
}
switch (method.Name)
{
// Some members in records are always compiler-generated and lead to a
// "duplicate definition" error if we emit the generated code.
case "op_Equality":
case "op_Inequality":
{
// Don't emit comparison operators into C# record definition
// Note: user can declare additional operator== as long as they have
// different parameter types.
return method.Parameters.Count == 2
&& method.Parameters.All(p => IsRecordType(p.Type));
}
case "Equals" when method.Parameters.Count == 1:
{
IType paramType = method.Parameters[0].Type;
if (paramType.IsKnownType(KnownTypeCode.Object) && method.IsOverride)
{
// override bool Equals(object? obj): always generated
return true;
}
else if (IsRecordType(paramType))
{
// virtual bool Equals(R? other): generated unless user-declared
return IsGeneratedEquals(method);
}
else if (isInheritedRecord && baseClass != null && NormalizeTypeVisitor.TypeErasure.EquivalentTypes(paramType, baseClass) && method.IsOverride)
{
// override bool Equals(BaseClass? obj): always generated
return true;
}
else
{
return false;
}
}
case "GetHashCode":
return IsGeneratedGetHashCode(method);
case "<Clone>$" when method.Parameters.Count == 0:
// Always generated; Method name cannot be expressed in C#
return true;
case "PrintMembers":
return IsGeneratedPrintMembers(method);
case "ToString" when method.Parameters.Count == 0:
return IsGeneratedToString(method);
case "Deconstruct" when primaryCtor != null && method.Parameters.Count == primaryCtor.Parameters.Count:
return IsGeneratedDeconstruct(method);
default:
return false;
}
}
internal bool PropertyIsGenerated(IProperty property)
{
switch (property.Name)
{
case "EqualityContract" when !isStruct:
return IsGeneratedEqualityContract(property);
default:
return IsPropertyDeclaredByPrimaryConstructor(property);
}
}
public bool IsPropertyDeclaredByPrimaryConstructor(IProperty property)
{
var subst = recordTypeDef.AsParameterizedType().GetSubstitution();
return primaryCtor != null
&& autoPropertyToPrimaryCtorParameter.ContainsKey((IProperty)property.Specialize(subst));
}
internal (IProperty prop, IField field) GetPropertyInfoByPrimaryConstructorParameter(IParameter parameter)
{
var prop = primaryCtorParameterToAutoProperty[parameter];
return (prop, autoPropertyToBackingField[prop]);
}
public bool IsCopyConstructor(IMethod method)
{
if (method == null)
return false;
Debug.Assert(method.DeclaringTypeDefinition == recordTypeDef);
return method.IsConstructor
&& method.Parameters.Count == 1
&& IsRecordType(method.Parameters[0].Type);
}
private bool IsAllowedAttribute(IAttribute attribute)
{
switch (attribute.AttributeType.ReflectionName)
{
case "System.Runtime.CompilerServices.CompilerGeneratedAttribute":
return true;
default:
return false;
}
}
private bool IsGeneratedCopyConstructor(IMethod method)
{
/*
call BaseClass..ctor(ldloc this, ldloc original)
stfld <X>k__BackingField(ldloc this, ldfld <X>k__BackingField(ldloc original))
leave IL_0000 (nop)
*/
Debug.Assert(method.IsConstructor && method.Parameters.Count == 1);
if (method.GetAttributes().Any(attr => !IsAllowedAttribute(attr)) || method.GetReturnTypeAttributes().Any())
return false;
if (method.Accessibility != Accessibility.Protected && (!isSealed || method.Accessibility != Accessibility.Private))
return false;
if (orderedMembers == null)
return false;
var body = DecompileBody(method);
if (body == null)
return false;
var variables = body.Ancestors.OfType<ILFunction>().Single().Variables;
var other = variables.Single(v => v.Kind == VariableKind.Parameter && v.Index == 0);
Debug.Assert(IsRecordType(other.Type));
int pos = 0;
// First instruction is the base constructor call
if (!(body.Instructions[pos] is Call { Method: { IsConstructor: true } } baseCtorCall))
return false;
if (!object.Equals(baseCtorCall.Method.DeclaringType, baseClass))
return false;
if (baseCtorCall.Arguments.Count != (isInheritedRecord ? 2 : 1))
return false;
if (!baseCtorCall.Arguments[0].MatchLdThis())
return false;
if (isInheritedRecord)
{
if (!baseCtorCall.Arguments[1].MatchLdLoc(other))
return false;
}
pos++;
// Then all the fields are copied over
foreach (var member in orderedMembers)
{
if (!(member is IField field))
{
if (!autoPropertyToBackingField.TryGetValue((IProperty)member, out field))
continue;
}
if (pos >= body.Instructions.Count)
return false;
if (!body.Instructions[pos].MatchStFld(out var lhsTarget, out var lhsField, out var valueInst))
return false;
if (!lhsTarget.MatchLdThis())
return false;
if (!lhsField.Equals(field))
return false;
if (!valueInst.MatchLdFld(out var rhsTarget, out var rhsField))
return false;
if (!rhsTarget.MatchLdLoc(other))
return false;
if (!rhsField.Equals(field))
return false;
pos++;
}
return body.Instructions[pos] is Leave;
}
private bool IsGeneratedEqualityContract(IProperty property)
{
// Generated member:
// protected virtual Type EqualityContract {
// [CompilerGenerated] get => typeof(R);
// }
Debug.Assert(!isStruct && property.Name == "EqualityContract");
if (property.Accessibility != Accessibility.Protected && (!isSealed || property.Accessibility != Accessibility.Private))
return false;
if (!(isSealed || property.IsVirtual || property.IsOverride))
return false;
if (property.IsSealed)
return false;
var getter = property.Getter;
if (!(getter != null && !property.CanSet))
return false;
var attrs = property.GetAttributes().ToList();
switch (attrs.Count)
{
case 0:
// Roslyn 3.x does not emit a CompilerGeneratedAttribute on the property itself.
break;
case 1:
// Roslyn 4.4 started doing so.
if (!attrs[0].AttributeType.IsKnownType(KnownAttribute.CompilerGenerated))
return false;
break;
default:
return false;
}
if (getter.GetReturnTypeAttributes().Any())
return false;
attrs = getter.GetAttributes().ToList();
if (attrs.Count != 1)
return false;
if (!attrs[0].AttributeType.IsKnownType(KnownAttribute.CompilerGenerated))
return false;
var body = DecompileBody(getter);
if (body == null || body.Instructions.Count != 1)
return false;
if (!(body.Instructions.Single() is Leave leave))
return false;
// leave IL_0000 (call GetTypeFromHandle(ldtypetoken R))
if (!TransformExpressionTrees.MatchGetTypeFromHandle(leave.Value, out IType ty))
return false;
return IsRecordType(ty);
}
private bool IsGeneratedPrintMembers(IMethod method)
{
Debug.Assert(method.Name == "PrintMembers");
if (method.Parameters.Count != 1)
return false;
if (!isSealed && !method.IsOverridable)
return false;
if (method.GetAttributes().Any(attr => !IsAllowedAttribute(attr)) || method.GetReturnTypeAttributes().Any())
return false;
if (method.Accessibility != Accessibility.Protected && (!isSealed || method.Accessibility != Accessibility.Private))
return false;
if (orderedMembers == null)
return false;
var body = DecompileBody(method);
if (body == null)
return false;
var variables = body.Ancestors.OfType<ILFunction>().Single().Variables;
var builder = variables.Single(v => v.Kind == VariableKind.Parameter && v.Index == 0);
if (builder.Type.ReflectionName != "System.Text.StringBuilder")
return false;
int pos = 0;
//Roslyn 4.0.0-3.final start to insert an call to RuntimeHelpers.EnsureSufficientExecutionStack()
if (!isStruct && !isInheritedRecord && body.Instructions[pos] is Call {
Arguments: { Count: 0 },
Method: { Name: "EnsureSufficientExecutionStack", DeclaringType: { Namespace: "System.Runtime.CompilerServices", Name: "RuntimeHelpers" } }
})
{
pos++;
}
if (isInheritedRecord)
{
// Special case: inherited record adding no new members
if (body.Instructions[pos].MatchReturn(out var returnValue)
&& IsBaseCall(returnValue) && !orderedMembers.Any(IsPrintedMember))
{
return true;
}
// if (call PrintMembers(ldloc this, ldloc builder)) Block IL_000f {
// callvirt Append(ldloc builder, ldstr ", ")
// }
if (!body.Instructions[pos].MatchIfInstruction(out var condition, out var trueInst))
return false;
if (!IsBaseCall(condition))
return false;
// trueInst = callvirt Append(ldloc builder, ldstr ", ")
trueInst = Block.Unwrap(trueInst);
if (!MatchStringBuilderAppend(trueInst, builder, out var val))
return false;
if (!(val.MatchLdStr(out string text) && text == ", "))
return false;
pos++;
bool IsBaseCall(ILInstruction inst)
{
if (!(inst is CallInstruction { Method: { Name: "PrintMembers" } } call))
return false;
if (call.Arguments.Count != 2)
return false;
if (!call.Arguments[0].MatchLdThis())
return false;
if (!call.Arguments[1].MatchLdLoc(builder))
return false;
return true;
}
}
bool needsComma = false;
foreach (var member in orderedMembers)
{
if (!IsPrintedMember(member))
continue;
cancellationToken.ThrowIfCancellationRequested();
/*
callvirt Append(ldloc builder, ldstr "A")
callvirt Append(ldloc builder, ldstr " = ")
callvirt Append(ldloc builder, constrained[System.Int32].callvirt ToString(addressof System.Int32(call get_A(ldloc this))))
callvirt Append(ldloc builder, ldstr ", ")
callvirt Append(ldloc builder, ldstr "B")
callvirt Append(ldloc builder, ldstr " = ")
callvirt Append(ldloc builder, constrained[System.Int32].callvirt ToString(ldflda B(ldloc this)))
leave IL_0000 (ldc.i4 1) */
if (!MatchStringBuilderAppendConstant(out string text))
return false;
string expectedText = (needsComma ? ", " : "") + member.Name + " = ";
if (text != expectedText)
return false;
if (!MatchStringBuilderAppend(body.Instructions[pos], builder, out var val))
return false;
if (val is CallInstruction { Method: { Name: "ToString", IsStatic: false } } toStringCall)
{
if (toStringCall.Arguments.Count != 1)
return false;
val = toStringCall.Arguments[0];
if (val is AddressOf addressOf)
{
val = addressOf.Value;
}
}
else if (val is Box box)
{
if (!NormalizeTypeVisitor.TypeErasure.EquivalentTypes(box.Type, member.ReturnType))
return false;
val = box.Argument;
}
if (val is CallInstruction getterCall && member is IProperty property)
{
if (!getterCall.Method.Equals(property.Getter))
return false;
if (getterCall.Arguments.Count != 1)
return false;
if (!getterCall.Arguments[0].MatchLdThis())
return false;
}
else if (val.MatchLdFld(out var target, out var field) || val.MatchLdFlda(out target, out field))
{
if (!target.MatchLdThis())
return false;
if (!field.Equals(member))
return false;
}
else
{
return false;
}
pos++;
needsComma = true;
}
// leave IL_0000 (ldc.i4 1)
return body.Instructions[pos].MatchReturn(out var retVal)
&& retVal.MatchLdcI4(needsComma ? 1 : 0);
bool IsPrintedMember(IMember member)
{
if (member.IsStatic)
{
return false; // static fields/properties are not printed
}
if (!isStruct && member.Name == "EqualityContract")
{
return false; // EqualityContract is never printed
}
if (member.IsExplicitInterfaceImplementation)
{
return false; // explicit interface impls are not printed
}
if (member.IsOverride)
{
return false; // override is not printed (again), the virtual base property was already printed
}
return true;
}
bool MatchStringBuilderAppendConstant(out string text)
{
text = null;
while (MatchStringBuilderAppend(body.Instructions[pos], builder, out var val) && val.MatchLdStr(out string valText))
{
text += valText;
pos++;
}
return text != null;
}
}
private bool MatchStringBuilderAppend(ILInstruction inst, ILVariable sb, out ILInstruction val)
{
val = null;
if (!(inst is CallVirt { Method: { Name: "Append", DeclaringType: { Namespace: "System.Text", Name: "StringBuilder" } } } call))
return false;
if (call.Arguments.Count != 2)
return false;
if (!call.Arguments[0].MatchLdLoc(sb))
return false;
val = call.Arguments[1];
return true;
}
private bool IsGeneratedToString(IMethod method)
{
Debug.Assert(method.Name == "ToString" && method.Parameters.Count == 0);
if (!method.IsOverride)
return false;
if (method.IsSealed)
return false;
if (method.GetAttributes().Any(attr => !IsAllowedAttribute(attr)) || method.GetReturnTypeAttributes().Any())
return false;
var body = DecompileBody(method);
if (body == null)
return false;
// stloc stringBuilder(newobj StringBuilder..ctor())
if (!body.Instructions[0].MatchStLoc(out var stringBuilder, out var stringBuilderInit))
return false;
if (!(stringBuilderInit is NewObj { Arguments: { Count: 0 }, Method: { DeclaringTypeDefinition: { Name: "StringBuilder", Namespace: "System.Text" } } }))
return false;
// callvirt Append(ldloc stringBuilder, ldstr "R")
if (!MatchAppendCallWithValue(body.Instructions[1], recordTypeDef.Name))
return false;
// callvirt Append(ldloc stringBuilder, ldstr " { ")
if (!MatchAppendCallWithValue(body.Instructions[2], " { "))
return false;
// if (callvirt PrintMembers(ldloc this, ldloc stringBuilder)) { trueInst }
if (!body.Instructions[3].MatchIfInstruction(out var condition, out var trueInst))
return true;
if (!((condition is CallInstruction { Method: { Name: "PrintMembers" } } printMembersCall) &&
(condition is CallVirt || (isSealed && condition is Call))))
return false;
if (printMembersCall.Arguments.Count != 2)
return false;
if (!printMembersCall.Arguments[0].MatchLdThis())
return false;
if (!printMembersCall.Arguments[1].MatchLdLoc(stringBuilder))
return false;
// trueInst: callvirt Append(ldloc stringBuilder, ldstr " ")
if (!MatchAppendCallWithValue(Block.Unwrap(trueInst), " "))
return false;
// callvirt Append(ldloc stringBuilder, ldstr "}")
if (!MatchAppendCallWithValue(body.Instructions[4], "}"))
return false;
// leave IL_0000 (callvirt ToString(ldloc stringBuilder))
if (!(body.Instructions[5] is Leave leave))
return false;
if (!(leave.Value is CallVirt { Method: { Name: "ToString" } } toStringCall))
return false;
if (toStringCall.Arguments.Count != 1)
return false;
return toStringCall.Arguments[0].MatchLdLoc(stringBuilder);
bool MatchAppendCallWithValue(ILInstruction inst, string val)
{
if (!(inst is CallVirt { Method: { Name: "Append" } } call))
return false;
if (call.Arguments.Count != 2)
return false;
if (!call.Arguments[0].MatchLdLoc(stringBuilder))
return false;
//Roslyn 4.0.0-3.final start to use char for 1 length string
if (call.Method.Parameters[0].Type.IsKnownType(KnownTypeCode.Char))
{
return val != null && val.Length == 1 && call.Arguments[1].MatchLdcI4(val[0]);
}
return call.Arguments[1].MatchLdStr(out string val1) && val1 == val;
}
}
private bool IsGeneratedEquals(IMethod method)
{
// virtual bool Equals(R? other) {
// return other != null && EqualityContract == other.EqualityContract && EqualityComparer<int>.Default.Equals(A, other.A) && ...;
// }
// Starting with Roslyn 3.10, it's:
// virtual bool Equals(R? other) {
// return this == other || other != null && EqualityContract == other.EqualityContract && EqualityComparer<int>.Default.Equals(A, other.A) && ...;
// }
Debug.Assert(method.Name == "Equals" && method.Parameters.Count == 1);
if (method.Parameters.Count != 1)
return false;
if (!isSealed && !method.IsOverridable)
return false;
if (method.GetAttributes().Any(attr => !IsAllowedAttribute(attr)) || method.GetReturnTypeAttributes().Any())
return false;
if (orderedMembers == null)
return false;
var body = DecompileBody(method);
if (body == null)
return false;
if (!body.Instructions[0].MatchReturn(out var returnValue))
return false;
// special case for empty record struct; always returns true;
if (returnValue.MatchLdcI4(1))
return true;
var variables = body.Ancestors.OfType<ILFunction>().Single().Variables;
var other = variables.Single(v => v.Kind == VariableKind.Parameter && v.Index == 0);
Debug.Assert(IsRecordType(other.Type));
if (returnValue.MatchLogicOr(out var lhs, out var rhs))
{
// this == other || ...
if (!lhs.MatchCompEquals(out var compLeft, out var compRight))
return false;
if (!compLeft.MatchLdThis())
return false;
if (!compRight.MatchLdLoc(other))
return false;
returnValue = rhs;
}
var conditions = UnpackLogicAndChain(returnValue);
Debug.Assert(conditions.Count >= 1);
int pos = 0;
if (!isStruct)
{
if (isInheritedRecord)
{
// call BaseClass::Equals(ldloc this, ldloc other)
if (pos >= conditions.Count)
return false;
if (!(conditions[pos] is Call { Method: { Name: "Equals" } } call))
return false;
if (baseClass != null && !NormalizeTypeVisitor.TypeErasure.EquivalentTypes(call.Method.DeclaringType, baseClass))
return false;
if (call.Arguments.Count != 2)
return false;
if (!call.Arguments[0].MatchLdThis())
return false;
if (!call.Arguments[1].MatchLdLoc(other))
return false;
pos++;
}
else
{
// comp.o(ldloc other != ldnull)
if (pos >= conditions.Count)
return false;
if (!conditions[pos].MatchCompNotEqualsNull(out var arg))
return false;
if (!arg.MatchLdLoc(other))
return false;
pos++;
// call op_Equality(callvirt get_EqualityContract(ldloc this), callvirt get_EqualityContract(ldloc other))
// Special-cased because Roslyn isn't using EqualityComparer<T> here.
if (pos >= conditions.Count)
return false;
if (!(conditions[pos] is Call { Method: { IsOperator: true, Name: "op_Equality" } } opEqualityCall))
return false;
if (!opEqualityCall.Method.DeclaringType.IsKnownType(KnownTypeCode.Type))
return false;
if (opEqualityCall.Arguments.Count != 2)
return false;
if (!MatchGetEqualityContract(opEqualityCall.Arguments[0], out var target1))
return false;
if (!MatchGetEqualityContract(opEqualityCall.Arguments[1], out var target2))
return false;
if (!target1.MatchLdThis())
return false;
if (!target2.MatchLdLoc(other))
return false;
pos++;
}
}
foreach (var member in orderedMembers)
{
if (!MemberConsideredForEquality(member))
continue;
if (!isStruct && member.Name == "EqualityContract")
{
continue; // already special-cased
}
// EqualityComparer<int>.Default.Equals(A, other.A)
// callvirt Equals(call get_Default(), ldfld <A>k__BackingField(ldloc this), ldfld <A>k__BackingField(ldloc other))
if (pos >= conditions.Count)
return false;
if (!(conditions[pos] is CallVirt { Method: { Name: "Equals" } } equalsCall))
return false;
if (equalsCall.Arguments.Count != 3)
return false;
if (!IsEqualityComparerGetDefaultCall(equalsCall.Arguments[0], member.ReturnType))
return false;
if (!MatchMemberAccess(equalsCall.Arguments[1], out var target1, out var member1))
return false;
if (!MatchMemberAccess(equalsCall.Arguments[2], out var target2, out var member2))
return false;
if (!target1.MatchLdThis())
return false;
if (!member1.Equals(member))
return false;
if (!(isStruct ? target2.MatchLdLoca(other) : target2.MatchLdLoc(other)))
return false;
if (!member2.Equals(member))
return false;
pos++;
}
return pos == conditions.Count;
}
static List<ILInstruction> UnpackLogicAndChain(ILInstruction rootOfChain)
{
var result = new List<ILInstruction>();
Visit(rootOfChain);
return result;
void Visit(ILInstruction inst)
{
if (inst.MatchLogicAnd(out var lhs, out var rhs))
{
Visit(lhs);
Visit(rhs);
}
else
{
result.Add(inst);
}
}
}
private bool MatchGetEqualityContract(ILInstruction inst, out ILInstruction target)
{
target = null;
if (!(inst is CallInstruction { Method: { Name: "get_EqualityContract" } } call))
return false;
if (!(inst is CallVirt || (isSealed && inst is Call)))
return false;
if (call.Arguments.Count != 1)
return false;
target = call.Arguments[0];
return true;
}
private static bool IsEqualityComparerGetDefaultCall(ILInstruction inst, IType type)
{
if (!(inst is Call { Method: { Name: "get_Default", IsStatic: true } } call))
return false;
if (!(call.Method.DeclaringType is { Name: "EqualityComparer", Namespace: "System.Collections.Generic" }))
return false;
if (call.Method.DeclaringType.TypeArguments.Count != 1)
return false;
if (!NormalizeTypeVisitor.TypeErasure.EquivalentTypes(call.Method.DeclaringType.TypeArguments[0], type))
return false;
return call.Arguments.Count == 0;
}
bool MemberConsideredForEquality(IMember member)
{
if (member.IsStatic)
return false;
if (member is IProperty property)
{
if (!isStruct && property.Name == "EqualityContract")
return !isInheritedRecord;
return autoPropertyToBackingField.ContainsKey(property);
}
else
{
return member is IField;
}
}
bool IsGeneratedGetHashCode(IMethod method)
{
/*
return (
(
EqualityComparer<Type>.Default.GetHashCode(EqualityContract) * -1521134295 + EqualityComparer<int>.Default.GetHashCode(A)
) * -1521134295 + EqualityComparer<int>.Default.GetHashCode(B)
) * -1521134295 + EqualityComparer<object>.Default.GetHashCode(C);
*/
Debug.Assert(method.Name == "GetHashCode");
if (method.Parameters.Count != 0)
return false;
if (!method.IsOverride || method.IsSealed)
return false;
if (method.GetAttributes().Any(attr => !IsAllowedAttribute(attr)) || method.GetReturnTypeAttributes().Any())
return false;
if (orderedMembers == null)
return false;
var body = DecompileBody(method);
if (body == null)
return false;
if (!body.Instructions[0].MatchReturn(out var returnValue))
return false;
// special case for empty record struct; always returns false;
if (returnValue.MatchLdcI4(0))
return true;
var hashedMembers = new List<IMember>();
bool foundBaseClassHash = false;
if (!Visit(returnValue))
return false;
if (foundBaseClassHash != isInheritedRecord)
return false;
return orderedMembers.Where(MemberConsideredForEquality).SequenceEqual(hashedMembers);
bool Visit(ILInstruction inst)
{
if (inst is BinaryNumericInstruction {
Operator: BinaryNumericOperator.Add,
CheckForOverflow: false,
Left: BinaryNumericInstruction {
Operator: BinaryNumericOperator.Mul,
CheckForOverflow: false,
Left: var left,
Right: LdcI4 { Value: -1521134295 }
},
Right: var right
})
{
if (!Visit(left))
return false;
return ProcessIndividualHashCode(right);
}
else
{
return ProcessIndividualHashCode(inst);
}
}
bool ProcessIndividualHashCode(ILInstruction inst)
{
// base.GetHashCode(): call GetHashCode(ldloc this)
if (inst is Call { Method: { Name: "GetHashCode" } } baseHashCodeCall)
{
if (baseHashCodeCall.Arguments.Count != 1)
return false;
if (!baseHashCodeCall.Arguments[0].MatchLdThis())
return false;
if (foundBaseClassHash || hashedMembers.Count > 0)
return false; // must be first
foundBaseClassHash = true;
return baseHashCodeCall.Method.DeclaringType.Equals(baseClass);
}
// callvirt GetHashCode(call get_Default(), callvirt get_EqualityContract(ldloc this))
// callvirt GetHashCode(call get_Default(), ldfld <A>k__BackingField(ldloc this)))
if (!(inst is CallVirt { Method: { Name: "GetHashCode" } } getHashCodeCall))
return false;
if (getHashCodeCall.Arguments.Count != 2)
return false;
// getHashCodeCall.Arguments[0] checked later
if (!MatchMemberAccess(getHashCodeCall.Arguments[1], out var target, out var member))
return false;
if (!target.MatchLdThis())
return false;
if (!IsEqualityComparerGetDefaultCall(getHashCodeCall.Arguments[0], member.ReturnType))
return false;
hashedMembers.Add(member);
return true;
}
}
bool IsGeneratedDeconstruct(IMethod method)
{
Debug.Assert(method.Name == "Deconstruct" && method.Parameters.Count == primaryCtor.Parameters.Count);
if (!method.ReturnType.IsKnownType(KnownTypeCode.Void))
return false;
for (int i = 0; i < method.Parameters.Count; i++)
{
var deconstruct = method.Parameters[i];
var ctor = primaryCtor.Parameters[i];
if (!deconstruct.IsOut)
return false;
IType ctorType = ctor.Type;
if (ctor.IsIn)
ctorType = ((ByReferenceType)ctorType).ElementType;
if (!ctorType.Equals(((ByReferenceType)deconstruct.Type).ElementType))
return false;
if (ctor.Name != deconstruct.Name)
return false;
}
var body = DecompileBody(method);
if (body == null || body.Instructions.Count != method.Parameters.Count + 1)
return false;
for (int i = 0; i < body.Instructions.Count - 1; i++)
{
// stobj T(ldloc parameter, call getter(ldloc this))
if (!body.Instructions[i].MatchStObj(out var targetInst, out var getter, out _))
return false;
if (!targetInst.MatchLdLoc(out var target))
return false;
if (!(target.Kind == VariableKind.Parameter && target.Index == i))
return false;
if (getter is not Call call || call.Arguments.Count != 1)
return false;
if (!call.Arguments[0].MatchLdThis())
return false;
if (!call.Method.IsAccessor)
return false;
var autoProperty = (IProperty)call.Method.AccessorOwner;
if (!autoPropertyToBackingField.ContainsKey(autoProperty))
return false;
}
var returnInst = body.Instructions.LastOrDefault();
return returnInst != null && returnInst.MatchReturn(out var retVal) && retVal.MatchNop();
}
bool MatchMemberAccess(ILInstruction inst, out ILInstruction target, out IMember member)
{
target = null;
member = null;
if (inst is CallInstruction {
Method: {
AccessorKind: System.Reflection.MethodSemanticsAttributes.Getter,
AccessorOwner: IProperty property
}
} call && (call is CallVirt || (isSealed && call is Call)))
{
if (call.Arguments.Count != 1)
return false;
target = call.Arguments[0];
member = property;
return true;
}
else if (inst.MatchLdFld(out target, out IField field))
{
if (backingFieldToAutoProperty.TryGetValue(field, out property))
member = property;
else
member = field;
return true;
}
else
{
return false;
}
}
Block DecompileBody(IMethod method)
{
if (method == null || method.MetadataToken.IsNil)
return null;
var metadata = typeSystem.MainModule.metadata;
var methodDefHandle = (MethodDefinitionHandle)method.MetadataToken;
var methodDef = metadata.GetMethodDefinition(methodDefHandle);
if (!methodDef.HasBody())
return null;
var genericContext = new GenericContext(
classTypeParameters: recordTypeDef.TypeParameters,
methodTypeParameters: null);
var body = typeSystem.MainModule.PEFile.Reader.GetMethodBody(methodDef.RelativeVirtualAddress);
var ilReader = new ILReader(typeSystem.MainModule);
var il = ilReader.ReadIL(methodDefHandle, body, genericContext, ILFunctionKind.TopLevelFunction, cancellationToken);
var settings = new DecompilerSettings(LanguageVersion.CSharp1);
var transforms = CSharpDecompiler.GetILTransforms();
// Remove the last couple transforms -- we don't need variable names etc. here
int lastBlockTransform = transforms.FindLastIndex(t => t is BlockILTransform);
transforms.RemoveRange(lastBlockTransform + 1, transforms.Count - (lastBlockTransform + 1));
// Use CombineExitsTransform so that "return other != null && ...;" is a single statement even in release builds
transforms.Add(new CombineExitsTransform());
il.RunTransforms(transforms,
new ILTransformContext(il, typeSystem, debugInfo: null, settings) {
CancellationToken = cancellationToken
});
if (il.Body is BlockContainer container)
{
return container.EntryPoint;
}
else if (il.Body is Block block)
{
return block;
}
else
{
return null;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/RecordDecompiler.cs",
"repo_id": "ILSpy",
"token_count": 14753
} | 217 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp.Resolver
{
/// <summary>
/// C# overload resolution (C# 4.0 spec: §7.5).
/// </summary>
public class OverloadResolution
{
sealed class Candidate
{
public readonly IParameterizedMember Member;
/// <summary>
/// Returns the normal form candidate, if this is an expanded candidate.
/// </summary>
public readonly bool IsExpandedForm;
/// <summary>
/// Gets the parameter types. In the first step, these are the types without any substition.
/// After type inference, substitutions will be performed.
/// </summary>
public readonly IType[] ParameterTypes;
/// <summary>
/// argument index -> parameter index; -1 for arguments that could not be mapped
/// </summary>
public int[] ArgumentToParameterMap;
public OverloadResolutionErrors Errors;
public int ErrorCount;
public bool HasUnmappedOptionalParameters;
public IType[] InferredTypes;
/// <summary>
/// Gets the original member parameters (before any substitution!)
/// </summary>
public readonly IReadOnlyList<IParameter> Parameters;
/// <summary>
/// Gets the original method type parameters (before any substitution!)
/// </summary>
public readonly IReadOnlyList<ITypeParameter> TypeParameters;
/// <summary>
/// Conversions applied to the arguments.
/// This field is set by the CheckApplicability step.
/// </summary>
public Conversion[] ArgumentConversions;
public bool IsGenericMethod {
get {
IMethod method = Member as IMethod;
return method != null && method.TypeParameters.Count > 0;
}
}
public int ArgumentsPassedToParamsArray {
get {
int count = 0;
if (IsExpandedForm)
{
int paramsParameterIndex = this.Parameters.Count - 1;
foreach (int parameterIndex in ArgumentToParameterMap)
{
if (parameterIndex == paramsParameterIndex)
count++;
}
}
return count;
}
}
public Candidate(IParameterizedMember member, bool isExpanded)
{
this.Member = member;
this.IsExpandedForm = isExpanded;
IParameterizedMember memberDefinition = (IParameterizedMember)member.MemberDefinition;
// For specificialized methods, go back to the original parameters:
// (without any type parameter substitution, not even class type parameters)
// We'll re-substitute them as part of RunTypeInference().
this.Parameters = memberDefinition.Parameters;
IMethod methodDefinition = memberDefinition as IMethod;
if (methodDefinition != null && methodDefinition.TypeParameters.Count > 0)
{
this.TypeParameters = methodDefinition.TypeParameters;
}
this.ParameterTypes = new IType[this.Parameters.Count];
}
public void AddError(OverloadResolutionErrors newError)
{
this.Errors |= newError;
if (!IsApplicable(newError))
this.ErrorCount++;
}
}
readonly ICompilation compilation;
readonly ResolveResult[] arguments;
readonly string[] argumentNames;
readonly CSharpConversions conversions;
//List<Candidate> candidates = new List<Candidate>();
Candidate bestCandidate;
Candidate bestCandidateAmbiguousWith;
IType[] explicitlyGivenTypeArguments;
bool bestCandidateWasValidated;
OverloadResolutionErrors bestCandidateValidationResult;
#region Constructor
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
if (argumentNames == null)
argumentNames = new string[arguments.Length];
else if (argumentNames.Length != arguments.Length)
throw new ArgumentException("argumentsNames.Length must be equal to arguments.Length");
this.compilation = compilation;
this.arguments = arguments;
this.argumentNames = argumentNames;
// keep explicitlyGivenTypeArguments==null when no type arguments were specified
if (typeArguments != null && typeArguments.Length > 0)
this.explicitlyGivenTypeArguments = typeArguments;
this.conversions = conversions ?? CSharpConversions.Get(compilation);
this.AllowExpandingParams = true;
this.AllowOptionalParameters = true;
}
#endregion
#region Input Properties
/// <summary>
/// Gets/Sets whether the methods are extension methods that are being called using extension method syntax.
/// </summary>
/// <remarks>
/// Setting this property to true restricts the possible conversions on the first argument to
/// implicit identity, reference, or boxing conversions.
/// </remarks>
public bool IsExtensionMethodInvocation { get; set; }
/// <summary>
/// Gets/Sets whether expanding 'params' into individual elements is allowed.
/// The default value is true.
/// </summary>
public bool AllowExpandingParams { get; set; }
/// <summary>
/// Gets/Sets whether optional parameters may be left at their default value.
/// The default value is true.
/// If this property is set to false, optional parameters will be treated like regular parameters.
/// </summary>
public bool AllowOptionalParameters { get; set; }
/// <summary>
/// Gets/Sets whether a value argument can be passed to an `in` reference parameter.
/// </summary>
public bool AllowImplicitIn { get; set; } = true;
/// <summary>
/// Gets/Sets whether ConversionResolveResults created by this OverloadResolution
/// instance apply overflow checking.
/// The default value is false.
/// </summary>
public bool CheckForOverflow { get; set; }
/// <summary>
/// Gets the arguments for which this OverloadResolution instance was created.
/// </summary>
public IList<ResolveResult> Arguments {
get { return arguments; }
}
#endregion
#region AddCandidate
/// <summary>
/// Adds a candidate to overload resolution.
/// </summary>
/// <param name="member">The candidate member to add.</param>
/// <returns>The errors that prevent the member from being applicable, if any.
/// Note: this method does not return errors that do not affect applicability.</returns>
public OverloadResolutionErrors AddCandidate(IParameterizedMember member)
{
return AddCandidate(member, OverloadResolutionErrors.None);
}
/// <summary>
/// Adds a candidate to overload resolution.
/// </summary>
/// <param name="member">The candidate member to add.</param>
/// <param name="additionalErrors">Additional errors that apply to the candidate.
/// This is used to represent errors during member lookup (e.g. OverloadResolutionErrors.Inaccessible)
/// in overload resolution.</param>
/// <returns>The errors that prevent the member from being applicable, if any.
/// Note: this method does not return errors that do not affect applicability.</returns>
public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors)
{
if (member == null)
throw new ArgumentNullException(nameof(member));
Candidate c = new Candidate(member, false);
c.AddError(additionalErrors);
if (CalculateCandidate(c))
{
//candidates.Add(c);
}
if (this.AllowExpandingParams && member.Parameters.Count > 0
&& member.Parameters[member.Parameters.Count - 1].IsParams)
{
Candidate expandedCandidate = new Candidate(member, true);
expandedCandidate.AddError(additionalErrors);
// consider expanded form only if it isn't obviously wrong
if (CalculateCandidate(expandedCandidate))
{
//candidates.Add(expandedCandidate);
if (expandedCandidate.ErrorCount < c.ErrorCount)
return expandedCandidate.Errors;
}
}
return c.Errors;
}
/// <summary>
/// Calculates applicability etc. for the candidate.
/// </summary>
/// <returns>True if the calculation was successful, false if the candidate should be removed without reporting an error</returns>
bool CalculateCandidate(Candidate candidate)
{
if (!ResolveParameterTypes(candidate, false))
return false;
MapCorrespondingParameters(candidate);
RunTypeInference(candidate);
CheckApplicability(candidate);
ConsiderIfNewCandidateIsBest(candidate);
return true;
}
bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters)
{
for (int i = 0; i < candidate.Parameters.Count; i++)
{
IType type;
if (useSpecializedParameters)
{
// Use the parameter type of the specialized non-generic method or indexer
Debug.Assert(!candidate.IsGenericMethod);
type = candidate.Member.Parameters[i].Type;
}
else
{
// Use the type of the original formal parameter
type = candidate.Parameters[i].Type;
}
if (candidate.IsExpandedForm && i == candidate.Parameters.Count - 1)
{
ArrayType arrayType = type as ArrayType;
if (arrayType != null && arrayType.Dimensions == 1)
type = arrayType.ElementType;
else
return false; // error: cannot unpack params-array. abort considering the expanded form for this candidate
}
candidate.ParameterTypes[i] = type;
}
return true;
}
#endregion
#region AddMethodLists
/// <summary>
/// Adds all candidates from the method lists.
///
/// This method implements the logic that causes applicable methods in derived types to hide
/// all methods in base types.
/// </summary>
/// <param name="methodLists">The methods, grouped by declaring type. Base types must come first in the list.</param>
public void AddMethodLists(IReadOnlyList<MethodListWithDeclaringType> methodLists)
{
if (methodLists == null)
throw new ArgumentNullException(nameof(methodLists));
// Base types come first, so go through the list backwards (derived types first)
bool[] isHiddenByDerivedType;
if (methodLists.Count > 1)
isHiddenByDerivedType = new bool[methodLists.Count];
else
isHiddenByDerivedType = null;
for (int i = methodLists.Count - 1; i >= 0; i--)
{
if (isHiddenByDerivedType != null && isHiddenByDerivedType[i])
{
Log.WriteLine(" Skipping methods in {0} because they are hidden by an applicable method in a derived type", methodLists[i].DeclaringType);
continue;
}
MethodListWithDeclaringType methodList = methodLists[i];
bool foundApplicableCandidateInCurrentList = false;
for (int j = 0; j < methodList.Count; j++)
{
IParameterizedMember method = methodList[j];
Log.Indent();
OverloadResolutionErrors errors = AddCandidate(method);
Log.Unindent();
LogCandidateAddingResult(" Candidate", method, errors);
foundApplicableCandidateInCurrentList |= IsApplicable(errors);
}
if (foundApplicableCandidateInCurrentList && i > 0)
{
foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes())
{
for (int j = 0; j < i; j++)
{
if (!isHiddenByDerivedType[j] && baseType.Equals(methodLists[j].DeclaringType))
isHiddenByDerivedType[j] = true;
}
}
}
}
}
[Conditional("DEBUG")]
internal void LogCandidateAddingResult(string text, IParameterizedMember method, OverloadResolutionErrors errors)
{
#if DEBUG
Log.WriteLine(string.Format("{0} {1} = {2}{3}",
text, method,
errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(),
this.BestCandidate == method ? " (best candidate so far)" :
this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : ""
));
#endif
}
#endregion
#region MapCorrespondingParameters
void MapCorrespondingParameters(Candidate candidate)
{
// C# 4.0 spec: §7.5.1.1 Corresponding parameters
// Updated for C# 7.2 non-trailing named arguments
candidate.ArgumentToParameterMap = new int[arguments.Length];
bool hasPositionalArgument = false;
// go backwards, so that hasPositionalArgument tells us whether there
// are non-trailing named arguments
for (int i = arguments.Length - 1; i >= 0; i--)
{
candidate.ArgumentToParameterMap[i] = -1;
if (argumentNames[i] == null || hasPositionalArgument)
{
hasPositionalArgument = true;
// positional argument or non-trailing named argument
if (i < candidate.ParameterTypes.Length)
{
candidate.ArgumentToParameterMap[i] = i;
if (argumentNames[i] != null && argumentNames[i] != candidate.Parameters[i].Name)
{
// non-trailing named argument must match name
candidate.AddError(OverloadResolutionErrors.NoParameterFoundForNamedArgument);
}
}
else if (candidate.IsExpandedForm)
{
candidate.ArgumentToParameterMap[i] = candidate.ParameterTypes.Length - 1;
if (argumentNames[i] != null)
{
// can't use non-trailing named argument here
candidate.AddError(OverloadResolutionErrors.NoParameterFoundForNamedArgument);
}
}
else
{
candidate.AddError(OverloadResolutionErrors.TooManyPositionalArguments);
}
}
else
{
// (trailing) named argument
for (int j = 0; j < candidate.Parameters.Count; j++)
{
if (argumentNames[i] == candidate.Parameters[j].Name)
{
candidate.ArgumentToParameterMap[i] = j;
}
}
if (candidate.ArgumentToParameterMap[i] < 0)
candidate.AddError(OverloadResolutionErrors.NoParameterFoundForNamedArgument);
}
}
}
#endregion
#region RunTypeInference
void RunTypeInference(Candidate candidate)
{
if (candidate.TypeParameters == null)
{
if (explicitlyGivenTypeArguments != null)
{
// method does not expect type arguments, but was given some
candidate.AddError(OverloadResolutionErrors.WrongNumberOfTypeArguments);
}
// Grab new parameter types:
ResolveParameterTypes(candidate, true);
return;
}
ParameterizedType parameterizedDeclaringType = candidate.Member.DeclaringType as ParameterizedType;
IReadOnlyList<IType> classTypeArguments;
if (parameterizedDeclaringType != null)
{
classTypeArguments = parameterizedDeclaringType.TypeArguments;
}
else
{
classTypeArguments = null;
}
// The method is generic:
if (explicitlyGivenTypeArguments != null)
{
if (explicitlyGivenTypeArguments.Length == candidate.TypeParameters.Count)
{
candidate.InferredTypes = explicitlyGivenTypeArguments;
}
else
{
candidate.AddError(OverloadResolutionErrors.WrongNumberOfTypeArguments);
// wrong number of type arguments given, so truncate the list or pad with UnknownType
candidate.InferredTypes = new IType[candidate.TypeParameters.Count];
for (int i = 0; i < candidate.InferredTypes.Length; i++)
{
if (i < explicitlyGivenTypeArguments.Length)
candidate.InferredTypes[i] = explicitlyGivenTypeArguments[i];
else
candidate.InferredTypes[i] = SpecialType.UnknownType;
}
}
}
else
{
TypeInference ti = new TypeInference(compilation, conversions);
IType[] parameterTypes = candidate.ArgumentToParameterMap
.SelectReadOnlyArray(parameterIndex => parameterIndex >= 0 ? candidate.ParameterTypes[parameterIndex] : SpecialType.UnknownType);
bool success;
candidate.InferredTypes = ti.InferTypeArguments(candidate.TypeParameters, arguments, parameterTypes, out success, classTypeArguments);
if (!success)
candidate.AddError(OverloadResolutionErrors.TypeInferenceFailed);
}
// Now substitute in the formal parameters:
var substitution = new ConstraintValidatingSubstitution(classTypeArguments, candidate.InferredTypes, this);
for (int i = 0; i < candidate.ParameterTypes.Length; i++)
{
candidate.ParameterTypes[i] = candidate.ParameterTypes[i].AcceptVisitor(substitution);
}
if (!substitution.ConstraintsValid)
candidate.AddError(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint);
}
sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution
{
readonly CSharpConversions conversions;
public bool ConstraintsValid = true;
public ConstraintValidatingSubstitution(IReadOnlyList<IType> classTypeArguments, IReadOnlyList<IType> methodTypeArguments, OverloadResolution overloadResolution)
: base(classTypeArguments, methodTypeArguments)
{
this.conversions = overloadResolution.conversions;
}
public override IType VisitParameterizedType(ParameterizedType type)
{
IType newType = base.VisitParameterizedType(type);
if (newType != type && ConstraintsValid)
{
// something was changed, so we need to validate the constraints
ParameterizedType newParameterizedType = newType as ParameterizedType;
if (newParameterizedType != null)
{
// C# 4.0 spec: §4.4.4 Satisfying constraints
var typeParameters = newParameterizedType.TypeParameters;
var substitution = newParameterizedType.GetSubstitution();
for (int i = 0; i < typeParameters.Count; i++)
{
if (!ValidateConstraints(typeParameters[i], newParameterizedType.GetTypeArgument(i), substitution, conversions))
{
ConstraintsValid = false;
break;
}
}
}
}
return newType;
}
}
#endregion
#region Validate Constraints
OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate)
{
// If type inference already failed, we won't check the constraints:
if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0)
return OverloadResolutionErrors.None;
if (candidate.TypeParameters == null || candidate.TypeParameters.Count == 0)
return OverloadResolutionErrors.None; // the method isn't generic
var substitution = GetSubstitution(candidate);
for (int i = 0; i < candidate.TypeParameters.Count; i++)
{
if (!ValidateConstraints(candidate.TypeParameters[i], substitution.MethodTypeArguments[i], substitution))
return OverloadResolutionErrors.MethodConstraintsNotSatisfied;
}
return OverloadResolutionErrors.None;
}
/// <summary>
/// Validates whether the given type argument satisfies the constraints for the given type parameter.
/// </summary>
/// <param name="typeParameter">The type parameter.</param>
/// <param name="typeArgument">The type argument.</param>
/// <param name="substitution">The substitution that defines how type parameters are replaced with type arguments.
/// The substitution is used to check constraints that depend on other type parameters (or recursively on the same type parameter).
/// May be null if no substitution should be used.</param>
/// <returns>True if the constraints are satisfied; false otherwise.</returns>
public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null)
{
if (typeParameter == null)
throw new ArgumentNullException(nameof(typeParameter));
if (typeArgument == null)
throw new ArgumentNullException(nameof(typeArgument));
return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation));
}
internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution, CSharpConversions conversions)
{
switch (typeArgument.Kind)
{ // void, null, and pointers cannot be used as type arguments
case TypeKind.Void:
case TypeKind.Null:
case TypeKind.Pointer:
return false;
}
if (typeParameter.HasReferenceTypeConstraint)
{
if (typeArgument.IsReferenceType != true)
return false;
}
if (typeParameter.HasValueTypeConstraint)
{
if (!NullableType.IsNonNullableValueType(typeArgument))
return false;
}
if (typeParameter.HasDefaultConstructorConstraint)
{
ITypeDefinition def = typeArgument.GetDefinition();
if (def != null && def.IsAbstract)
return false;
var ctors = typeArgument.GetConstructors(
m => m.Parameters.Count == 0 && m.Accessibility == Accessibility.Public,
GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
);
if (!ctors.Any())
return false;
}
foreach (IType constraintType in typeParameter.DirectBaseTypes)
{
IType c = constraintType;
if (substitution != null)
c = c.AcceptVisitor(substitution);
if (!conversions.IsConstraintConvertible(typeArgument, c))
return false;
}
return true;
}
#endregion
#region CheckApplicability
/// <summary>
/// Returns whether a candidate with the given errors is still considered to be applicable.
/// </summary>
public static bool IsApplicable(OverloadResolutionErrors errors)
{
const OverloadResolutionErrors errorsThatDoNotMatterForApplicability =
OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied;
return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None;
}
void CheckApplicability(Candidate candidate)
{
// C# 4.0 spec: §7.5.3.1 Applicable function member
// Test whether parameters were mapped the correct number of arguments:
int[] argumentCountPerParameter = new int[candidate.ParameterTypes.Length];
foreach (int parameterIndex in candidate.ArgumentToParameterMap)
{
if (parameterIndex >= 0)
argumentCountPerParameter[parameterIndex]++;
}
for (int i = 0; i < argumentCountPerParameter.Length; i++)
{
if (candidate.IsExpandedForm && i == argumentCountPerParameter.Length - 1)
continue; // any number of arguments is fine for the params-array
if (argumentCountPerParameter[i] == 0)
{
if (this.AllowOptionalParameters && candidate.Parameters[i].IsOptional)
candidate.HasUnmappedOptionalParameters = true;
else
candidate.AddError(OverloadResolutionErrors.MissingArgumentForRequiredParameter);
}
else if (argumentCountPerParameter[i] > 1)
{
candidate.AddError(OverloadResolutionErrors.MultipleArgumentsForSingleParameter);
}
}
candidate.ArgumentConversions = new Conversion[arguments.Length];
// Test whether argument passing mode matches the parameter passing mode
for (int i = 0; i < arguments.Length; i++)
{
int parameterIndex = candidate.ArgumentToParameterMap[i];
if (parameterIndex < 0)
{
candidate.ArgumentConversions[i] = Conversion.None;
continue;
}
ReferenceKind paramRefKind = candidate.Parameters[parameterIndex].ReferenceKind;
if (arguments[i] is ByReferenceResolveResult brrr)
{
if (brrr.ReferenceKind != paramRefKind)
candidate.AddError(OverloadResolutionErrors.ParameterPassingModeMismatch);
}
else if (arguments[i] is OutVarResolveResult)
{
if (paramRefKind != ReferenceKind.Out)
candidate.AddError(OverloadResolutionErrors.ParameterPassingModeMismatch);
// 'out var decl' arguments are compatible with any out parameter
continue;
}
else
{
// AllowImplicitIn: `in` parameters can be filled implicitly without `in` DirectionExpression
// IsExtensionMethodInvocation: `this ref` and `this in` parameters can be filled implicitly
if (((paramRefKind == ReferenceKind.In && AllowImplicitIn)
|| (IsExtensionMethodInvocation && parameterIndex == 0 && (paramRefKind == ReferenceKind.In || paramRefKind == ReferenceKind.Ref))
) && candidate.ParameterTypes[parameterIndex].SkipModifiers() is ByReferenceType brt)
{
// Treat the parameter as if it was not declared "in" for the following steps
// (applicability + better function member)
candidate.ParameterTypes[parameterIndex] = brt.ElementType;
}
else if (paramRefKind != ReferenceKind.None)
{
candidate.AddError(OverloadResolutionErrors.ParameterPassingModeMismatch);
}
}
IType parameterType = candidate.ParameterTypes[parameterIndex];
Conversion c = conversions.ImplicitConversion(arguments[i], parameterType);
candidate.ArgumentConversions[i] = c;
if (IsExtensionMethodInvocation && parameterIndex == 0)
{
// First parameter to extension method must be an identity, reference or boxing conversion
if (!(c == Conversion.IdentityConversion || c == Conversion.ImplicitReferenceConversion || c == Conversion.BoxingConversion))
candidate.AddError(OverloadResolutionErrors.ArgumentTypeMismatch);
}
else
{
if ((!c.IsValid && !c.IsUserDefined && !c.IsMethodGroupConversion) && parameterType.Kind != TypeKind.Unknown)
candidate.AddError(OverloadResolutionErrors.ArgumentTypeMismatch);
}
}
}
#endregion
#region BetterFunctionMember
/// <summary>
/// Returns 1 if c1 is better than c2; 2 if c2 is better than c1; or 0 if neither is better.
/// </summary>
int BetterFunctionMember(Candidate c1, Candidate c2)
{
// prefer applicable members (part of heuristic that produces a best candidate even if none is applicable)
if (c1.ErrorCount == 0 && c2.ErrorCount > 0)
return 1;
if (c1.ErrorCount > 0 && c2.ErrorCount == 0)
return 2;
// C# 4.0 spec: §7.5.3.2 Better function member
bool c1IsBetter = false;
bool c2IsBetter = false;
bool parameterTypesEqual = true;
for (int i = 0; i < arguments.Length; i++)
{
int p1 = c1.ArgumentToParameterMap[i];
int p2 = c2.ArgumentToParameterMap[i];
if (p1 >= 0 && p2 < 0)
{
c1IsBetter = true;
}
else if (p1 < 0 && p2 >= 0)
{
c2IsBetter = true;
}
else if (p1 >= 0 && p2 >= 0)
{
if (!conversions.IdentityConversion(c1.ParameterTypes[p1], c2.ParameterTypes[p2]))
parameterTypesEqual = false;
switch (conversions.BetterConversion(arguments[i], c1.ParameterTypes[p1], c2.ParameterTypes[p2]))
{
case 1:
c1IsBetter = true;
break;
case 2:
c2IsBetter = true;
break;
}
}
}
if (c1IsBetter && !c2IsBetter)
return 1;
if (!c1IsBetter && c2IsBetter)
return 2;
// prefer members with less errors (part of heuristic that produces a best candidate even if none is applicable)
if (c1.ErrorCount < c2.ErrorCount)
return 1;
if (c1.ErrorCount > c2.ErrorCount)
return 2;
if (!c1IsBetter && !c2IsBetter && parameterTypesEqual)
{
// we need the tie-breaking rules
// non-generic methods are better
if (!c1.IsGenericMethod && c2.IsGenericMethod)
return 1;
else if (c1.IsGenericMethod && !c2.IsGenericMethod)
return 2;
// non-expanded members are better
if (!c1.IsExpandedForm && c2.IsExpandedForm)
return 1;
else if (c1.IsExpandedForm && !c2.IsExpandedForm)
return 2;
// prefer the member with less arguments mapped to the params-array
int r = c1.ArgumentsPassedToParamsArray.CompareTo(c2.ArgumentsPassedToParamsArray);
if (r < 0)
return 1;
else if (r > 0)
return 2;
// prefer the member where no default values need to be substituted
if (!c1.HasUnmappedOptionalParameters && c2.HasUnmappedOptionalParameters)
return 1;
else if (c1.HasUnmappedOptionalParameters && !c2.HasUnmappedOptionalParameters)
return 2;
// compare the formal parameters
r = MoreSpecificFormalParameters(c1, c2);
if (r != 0)
return r;
// prefer non-lifted operators
ILiftedOperator lift1 = c1.Member as ILiftedOperator;
ILiftedOperator lift2 = c2.Member as ILiftedOperator;
if (lift1 == null && lift2 != null)
return 1;
if (lift1 != null && lift2 == null)
return 2;
}
return 0;
}
int MoreSpecificFormalParameters(Candidate c1, Candidate c2)
{
// prefer the member with more formal parmeters (in case both have different number of optional parameters)
int r = c1.Parameters.Count.CompareTo(c2.Parameters.Count);
if (r > 0)
return 1;
else if (r < 0)
return 2;
return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type));
}
static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2)
{
bool c1IsBetter = false;
bool c2IsBetter = false;
foreach (var pair in t1.Zip(t2, (a, b) => new { Item1 = a, Item2 = b }))
{
switch (MoreSpecificFormalParameter(pair.Item1, pair.Item2))
{
case 1:
c1IsBetter = true;
break;
case 2:
c2IsBetter = true;
break;
}
}
if (c1IsBetter && !c2IsBetter)
return 1;
if (!c1IsBetter && c2IsBetter)
return 2;
return 0;
}
static int MoreSpecificFormalParameter(IType t1, IType t2)
{
if ((t1 is ITypeParameter) && !(t2 is ITypeParameter))
return 2;
if ((t2 is ITypeParameter) && !(t1 is ITypeParameter))
return 1;
ParameterizedType p1 = t1 as ParameterizedType;
ParameterizedType p2 = t2 as ParameterizedType;
if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount)
{
int r = MoreSpecificFormalParameters(p1.TypeArguments, p2.TypeArguments);
if (r > 0)
return r;
}
TypeWithElementType tew1 = t1 as TypeWithElementType;
TypeWithElementType tew2 = t2 as TypeWithElementType;
if (tew1 != null && tew2 != null)
{
return MoreSpecificFormalParameter(tew1.ElementType, tew2.ElementType);
}
return 0;
}
#endregion
#region ConsiderIfNewCandidateIsBest
void ConsiderIfNewCandidateIsBest(Candidate candidate)
{
if (bestCandidate == null)
{
bestCandidate = candidate;
bestCandidateWasValidated = false;
}
else
{
switch (BetterFunctionMember(candidate, bestCandidate))
{
case 0:
// Overwrite 'bestCandidateAmbiguousWith' so that API users can
// detect the set of all ambiguous methods if they look at
// bestCandidateAmbiguousWith after each step.
bestCandidateAmbiguousWith = candidate;
break;
case 1:
bestCandidate = candidate;
bestCandidateWasValidated = false;
bestCandidateAmbiguousWith = null;
break;
// case 2: best candidate stays best
}
}
}
#endregion
#region Output Properties
public IParameterizedMember BestCandidate {
get { return bestCandidate != null ? bestCandidate.Member : null; }
}
/// <summary>
/// Returns the errors that apply to the best candidate.
/// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied)
/// </summary>
public OverloadResolutionErrors BestCandidateErrors {
get {
if (bestCandidate == null)
return OverloadResolutionErrors.None;
if (!bestCandidateWasValidated)
{
bestCandidateValidationResult = ValidateMethodConstraints(bestCandidate);
bestCandidateWasValidated = true;
}
OverloadResolutionErrors err = bestCandidate.Errors | bestCandidateValidationResult;
if (bestCandidateAmbiguousWith != null)
err |= OverloadResolutionErrors.AmbiguousMatch;
return err;
}
}
public bool FoundApplicableCandidate {
get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); }
}
public IParameterizedMember BestCandidateAmbiguousWith {
get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; }
}
public bool BestCandidateIsExpandedForm {
get { return bestCandidate != null ? bestCandidate.IsExpandedForm : false; }
}
public bool IsAmbiguous {
get { return bestCandidateAmbiguousWith != null; }
}
public IReadOnlyList<IType> InferredTypeArguments {
get {
if (bestCandidate != null && bestCandidate.InferredTypes != null)
return bestCandidate.InferredTypes;
else
return EmptyList<IType>.Instance;
}
}
/// <summary>
/// Gets the implicit conversions that are being applied to the arguments.
/// </summary>
public IList<Conversion> ArgumentConversions {
get {
if (bestCandidate != null && bestCandidate.ArgumentConversions != null)
return bestCandidate.ArgumentConversions;
else
return Enumerable.Repeat(Conversion.None, arguments.Length).ToList();
}
}
/// <summary>
/// Gets an array that maps argument indices to parameter indices.
/// For arguments that could not be mapped to any parameter, the value will be -1.
///
/// parameterIndex = GetArgumentToParameterMap()[argumentIndex]
/// </summary>
public IReadOnlyList<int> GetArgumentToParameterMap()
{
if (bestCandidate != null)
return bestCandidate.ArgumentToParameterMap;
else
return null;
}
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
/// to them when calling the method.
/// </summary>
public IList<ResolveResult> GetArgumentsWithConversions()
{
if (bestCandidate == null)
return arguments;
else
return GetArgumentsWithConversions(null, null);
}
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
/// to them when calling the method.
/// For arguments where an explicit argument name was provided, the argument will
/// be wrapped in a <see cref="NamedArgumentResolveResult"/>.
/// </summary>
public IList<ResolveResult> GetArgumentsWithConversionsAndNames()
{
if (bestCandidate == null)
return arguments;
else
return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments());
}
IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments)
{
var conversions = this.ArgumentConversions;
ResolveResult[] args = new ResolveResult[arguments.Length];
for (int i = 0; i < args.Length; i++)
{
var argument = arguments[i];
if (this.IsExtensionMethodInvocation && i == 0 && targetResolveResult != null)
argument = targetResolveResult;
int parameterIndex = bestCandidate.ArgumentToParameterMap[i];
if (parameterIndex >= 0 && conversions[i] != Conversion.IdentityConversion)
{
// Wrap argument in ConversionResolveResult
IType parameterType = bestCandidate.ParameterTypes[parameterIndex];
if (parameterType.Kind != TypeKind.Unknown)
{
if (arguments[i].IsCompileTimeConstant && conversions[i].IsValid && !conversions[i].IsUserDefined)
{
argument = new CSharpResolver(compilation).WithCheckForOverflow(CheckForOverflow).ResolveCast(parameterType, argument);
}
else
{
argument = new ConversionResolveResult(parameterType, argument, conversions[i], CheckForOverflow);
}
}
}
if (bestCandidateForNamedArguments != null && argumentNames[i] != null)
{
// Wrap argument in NamedArgumentResolveResult
if (parameterIndex >= 0)
{
argument = new NamedArgumentResolveResult(bestCandidateForNamedArguments.Parameters[parameterIndex], argument, bestCandidateForNamedArguments);
}
else
{
argument = new NamedArgumentResolveResult(argumentNames[i], argument);
}
}
args[i] = argument;
}
return args;
}
public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments()
{
if (bestCandidate == null)
return null;
IMethod method = bestCandidate.Member as IMethod;
if (method != null && method.TypeParameters.Count > 0)
{
return ((IMethod)method.MemberDefinition).Specialize(GetSubstitution(bestCandidate));
}
else
{
return bestCandidate.Member;
}
}
TypeParameterSubstitution GetSubstitution(Candidate candidate)
{
// Do not compose the substitutions, but merge them.
// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
return new TypeParameterSubstitution(candidate.Member.Substitution.ClassTypeArguments, candidate.InferredTypes);
}
/// <summary>
/// Creates a ResolveResult representing the result of overload resolution.
/// </summary>
/// <param name="targetResolveResult">
/// The target expression of the call. May be <c>null</c> for static methods/constructors.
/// </param>
/// <param name="initializerStatements">
/// Statements for Objects/Collections initializer.
/// <see cref="InvocationResolveResult.InitializerStatements"/>
/// </param>
/// <param name="returnTypeOverride">
/// If not null, use this instead of the ReturnType of the member as the type of the created resolve result.
/// </param>
public CSharpInvocationResolveResult CreateResolveResult(ResolveResult targetResolveResult, IList<ResolveResult> initializerStatements = null, IType returnTypeOverride = null)
{
IParameterizedMember member = GetBestCandidateWithSubstitutedTypeArguments();
if (member == null)
throw new InvalidOperationException();
return new CSharpInvocationResolveResult(
this.IsExtensionMethodInvocation ? new TypeResolveResult(member.DeclaringType ?? SpecialType.UnknownType) : targetResolveResult,
member,
GetArgumentsWithConversions(targetResolveResult, member),
this.BestCandidateErrors,
this.IsExtensionMethodInvocation,
this.BestCandidateIsExpandedForm,
isDelegateInvocation: false,
argumentToParameterMap: this.GetArgumentToParameterMap(),
initializerStatements: initializerStatements,
returnTypeOverride: returnTypeOverride);
}
#endregion
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs",
"repo_id": "ILSpy",
"token_count": 13772
} | 218 |
//
// ArrayInitializerExpression.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// { Elements }
/// </summary>
public class ArrayInitializerExpression : Expression
{
/// <summary>
/// For ease of use purposes in the resolver the ast representation
/// of { a, b, c } is { {a}, {b}, {c} }.
/// If IsSingleElement is true then this array initializer expression is a generated one.
/// That has no meaning in the source code (and contains no brace tokens).
/// </summary>
public virtual bool IsSingleElement {
get {
return false;
}
}
public ArrayInitializerExpression()
{
}
public ArrayInitializerExpression(IEnumerable<Expression> elements)
{
this.Elements.AddRange(elements);
}
public ArrayInitializerExpression(params Expression[] elements)
{
this.Elements.AddRange(elements);
}
#region Null
public new static readonly ArrayInitializerExpression Null = new NullArrayInitializerExpression();
sealed class NullArrayInitializerExpression : ArrayInitializerExpression
{
public override bool IsNull {
get {
return true;
}
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitNullNode(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitNullNode(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitNullNode(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return other == null || other.IsNull;
}
}
#endregion
public CSharpTokenNode LBraceToken {
get { return GetChildByRole(Roles.LBrace); }
}
public AstNodeCollection<Expression> Elements {
get { return GetChildrenByRole(Roles.Expression); }
}
public CSharpTokenNode RBraceToken {
get { return GetChildByRole(Roles.RBrace); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitArrayInitializerExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitArrayInitializerExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitArrayInitializerExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
ArrayInitializerExpression o = other as ArrayInitializerExpression;
return o != null && this.Elements.DoMatch(o.Elements, match);
}
public static ArrayInitializerExpression CreateSingleElementInitializer()
{
return new SingleArrayInitializerExpression();
}
/// <summary>
/// Single elements in array initializers are represented with this special class.
/// </summary>
class SingleArrayInitializerExpression : ArrayInitializerExpression
{
public override bool IsSingleElement {
get {
return true;
}
}
}
#region PatternPlaceholder
public static implicit operator ArrayInitializerExpression(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : ArrayInitializerExpression, PatternMatching.INode
{
readonly PatternMatching.Pattern child;
public PatternPlaceholder(PatternMatching.Pattern child)
{
this.child = child;
}
public override NodeType NodeType {
get { return NodeType.Pattern; }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitPatternPlaceholder(this, child);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitPatternPlaceholder(this, child);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitPatternPlaceholder(this, child, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return child.DoMatch(other, match);
}
bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
{
return child.DoMatchCollection(role, pos, match, backtrackingInfo);
}
}
#endregion
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/ArrayInitializerExpression.cs",
"repo_id": "ILSpy",
"token_count": 1822
} | 219 |
// Copyright (c) 2020 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// Expression switch { SwitchSections }
/// </summary>
public class SwitchExpression : Expression
{
public static readonly TokenRole SwitchKeywordRole = new TokenRole("switch");
public static readonly Role<SwitchExpressionSection> SwitchSectionRole = new Role<SwitchExpressionSection>("SwitchSection", null);
public Expression Expression {
get { return GetChildByRole(Roles.Expression); }
set { SetChildByRole(Roles.Expression, value); }
}
public CSharpTokenNode SwitchToken {
get { return GetChildByRole(SwitchKeywordRole); }
}
public CSharpTokenNode LBraceToken {
get { return GetChildByRole(Roles.LBrace); }
}
public AstNodeCollection<SwitchExpressionSection> SwitchSections {
get { return GetChildrenByRole(SwitchSectionRole); }
}
public CSharpTokenNode RBraceToken {
get { return GetChildByRole(Roles.RBrace); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitSwitchExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitSwitchExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitSwitchExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
SwitchExpression o = other as SwitchExpression;
return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match);
}
}
/// <summary>
/// Pattern => Expression
/// </summary>
public class SwitchExpressionSection : AstNode
{
public static readonly Role<Expression> PatternRole = new Role<Expression>("Pattern", Expression.Null);
public static readonly Role<Expression> BodyRole = new Role<Expression>("Body", Expression.Null);
public Expression Pattern {
get { return GetChildByRole(PatternRole); }
set { SetChildByRole(PatternRole, value); }
}
public CSharpTokenNode ArrowToken {
get { return GetChildByRole(Roles.Arrow); }
}
public Expression Body {
get { return GetChildByRole(BodyRole); }
set { SetChildByRole(BodyRole, value); }
}
public override NodeType NodeType => NodeType.Unknown;
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitSwitchExpressionSection(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitSwitchExpressionSection(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitSwitchExpressionSection(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
SwitchExpressionSection o = other as SwitchExpressionSection;
return o != null && this.Pattern.DoMatch(o.Pattern, match) && this.Body.DoMatch(o.Body, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/SwitchExpression.cs",
"repo_id": "ILSpy",
"token_count": 1259
} | 220 |
//
// ExternAliasDeclaration.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// extern alias IDENTIFIER;
/// </summary>
public class ExternAliasDeclaration : AstNode
{
public override NodeType NodeType {
get {
return NodeType.Unknown;
}
}
public CSharpTokenNode ExternToken {
get { return GetChildByRole(Roles.ExternKeyword); }
}
public CSharpTokenNode AliasToken {
get { return GetChildByRole(Roles.AliasKeyword); }
}
public string Name {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Identifier.Create(value));
}
}
public Identifier NameToken {
get {
return GetChildByRole(Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public CSharpTokenNode SemicolonToken {
get { return GetChildByRole(Roles.Semicolon); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitExternAliasDeclaration(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitExternAliasDeclaration(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitExternAliasDeclaration(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
var o = other as ExternAliasDeclaration;
return o != null && MatchString(this.Name, o.Name);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/ExternAliasDeclaration.cs",
"repo_id": "ILSpy",
"token_count": 903
} | 221 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Xml;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.Documentation;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Transforms
{
/// <summary>
/// Adds XML documentation for member definitions.
/// </summary>
public class AddXmlDocumentationTransform : IAstTransform
{
public void Run(AstNode rootNode, TransformContext context)
{
if (!context.Settings.ShowXmlDocumentation || context.DecompileRun.DocumentationProvider == null)
return;
try
{
var provider = context.DecompileRun.DocumentationProvider;
foreach (var entityDecl in rootNode.DescendantsAndSelf.OfType<EntityDeclaration>())
{
if (!(entityDecl.GetSymbol() is IEntity entity))
continue;
string doc = provider.GetDocumentation(entity);
if (doc != null)
{
InsertXmlDocumentation(entityDecl, new StringReader(doc));
}
}
}
catch (XmlException ex)
{
string[] msg = (" Exception while reading XmlDoc: " + ex).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var insertionPoint = rootNode.FirstChild;
for (int i = 0; i < msg.Length; i++)
rootNode.InsertChildBefore(insertionPoint, new Comment(msg[i], CommentType.Documentation), Roles.Comment);
}
}
static void InsertXmlDocumentation(AstNode node, StringReader r)
{
// Find the first non-empty line:
string firstLine;
do
{
firstLine = r.ReadLine();
if (firstLine == null)
return;
} while (string.IsNullOrWhiteSpace(firstLine));
string indentation = firstLine.Substring(0, firstLine.Length - firstLine.TrimStart().Length);
string line = firstLine;
int skippedWhitespaceLines = 0;
// Copy all lines from input to output, except for empty lines at the end.
while (line != null)
{
if (string.IsNullOrWhiteSpace(line))
{
skippedWhitespaceLines++;
}
else
{
while (skippedWhitespaceLines > 0)
{
Comment emptyLine = new Comment(string.Empty, CommentType.Documentation);
emptyLine.AddAnnotation(node.GetResolveResult());
node.Parent.InsertChildBefore(node, emptyLine, Roles.Comment);
skippedWhitespaceLines--;
}
if (line.StartsWith(indentation, StringComparison.Ordinal))
line = line.Substring(indentation.Length);
Comment comment = new Comment(" " + line, CommentType.Documentation);
comment.AddAnnotation(node.GetResolveResult());
node.Parent.InsertChildBefore(node, comment, Roles.Comment);
}
line = r.ReadLine();
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs",
"repo_id": "ILSpy",
"token_count": 1300
} | 222 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp.Transforms
{
/// <summary>
/// Simplifies "x = x op y" into "x op= y" where possible.
/// </summary>
/// <remarks>
/// Because the two "x" in "x = x op y" may refer to different ILVariables,
/// this transform must run after DeclareVariables.
///
/// It must also run after ReplaceMethodCallsWithOperators (so that it can work for custom operator, too);
/// and after AddCheckedBlocks (because "for (;; x = unchecked(x op y))" cannot be transformed into "x += y").
/// </remarks>
class PrettifyAssignments : DepthFirstAstVisitor, IAstTransform
{
TransformContext context;
public override void VisitAssignmentExpression(AssignmentExpression assignment)
{
base.VisitAssignmentExpression(assignment);
// Combine "x = x op y" into "x op= y"
// Also supports "x = (T)(x op y)" -> "x op= y", if x.GetType() == T
// and y is implicitly convertible to T.
Expression rhs = assignment.Right;
IType expectedType = null;
if (assignment.Right is CastExpression { Type: var astType } cast)
{
rhs = cast.Expression;
expectedType = astType.GetResolveResult().Type;
}
if (rhs is BinaryOperatorExpression binary && assignment.Operator == AssignmentOperatorType.Assign)
{
if (CanConvertToCompoundAssignment(assignment.Left) && assignment.Left.IsMatch(binary.Left)
&& IsImplicitlyConvertible(binary.Right, expectedType))
{
assignment.Operator = GetAssignmentOperatorForBinaryOperator(binary.Operator);
if (assignment.Operator != AssignmentOperatorType.Assign)
{
// If we found a shorter operator, get rid of the BinaryOperatorExpression:
assignment.CopyAnnotationsFrom(binary);
assignment.Right = binary.Right;
}
}
}
if (context.Settings.IntroduceIncrementAndDecrement && assignment.Operator == AssignmentOperatorType.Add || assignment.Operator == AssignmentOperatorType.Subtract)
{
// detect increment/decrement
var rr = assignment.Right.GetResolveResult();
if (rr.IsCompileTimeConstant && rr.Type.IsCSharpPrimitiveIntegerType() && CSharpPrimitiveCast.Cast(rr.Type.GetTypeCode(), 1, false).Equals(rr.ConstantValue))
{
// only if it's not a custom operator
if (assignment.Annotation<IL.CallInstruction>() == null && assignment.Annotation<IL.UserDefinedCompoundAssign>() == null && assignment.Annotation<IL.DynamicCompoundAssign>() == null)
{
UnaryOperatorType type;
// When the parent is an expression statement, pre- or post-increment doesn't matter;
// so we can pick post-increment which is more commonly used (for (int i = 0; i < x; i++))
if (assignment.Parent is ExpressionStatement)
type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement;
else
type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.Increment : UnaryOperatorType.Decrement;
assignment.ReplaceWith(new UnaryOperatorExpression(type, assignment.Left.Detach()).CopyAnnotationsFrom(assignment));
}
}
}
bool IsImplicitlyConvertible(Expression rhs, IType expectedType)
{
if (expectedType == null)
return true;
var conversions = CSharpConversions.Get(context.TypeSystem);
return conversions.ImplicitConversion(rhs.GetResolveResult(), expectedType).IsImplicit;
}
}
public static AssignmentOperatorType GetAssignmentOperatorForBinaryOperator(BinaryOperatorType bop)
{
switch (bop)
{
case BinaryOperatorType.Add:
return AssignmentOperatorType.Add;
case BinaryOperatorType.Subtract:
return AssignmentOperatorType.Subtract;
case BinaryOperatorType.Multiply:
return AssignmentOperatorType.Multiply;
case BinaryOperatorType.Divide:
return AssignmentOperatorType.Divide;
case BinaryOperatorType.Modulus:
return AssignmentOperatorType.Modulus;
case BinaryOperatorType.ShiftLeft:
return AssignmentOperatorType.ShiftLeft;
case BinaryOperatorType.ShiftRight:
return AssignmentOperatorType.ShiftRight;
case BinaryOperatorType.UnsignedShiftRight:
return AssignmentOperatorType.UnsignedShiftRight;
case BinaryOperatorType.BitwiseAnd:
return AssignmentOperatorType.BitwiseAnd;
case BinaryOperatorType.BitwiseOr:
return AssignmentOperatorType.BitwiseOr;
case BinaryOperatorType.ExclusiveOr:
return AssignmentOperatorType.ExclusiveOr;
default:
return AssignmentOperatorType.Assign;
}
}
static bool CanConvertToCompoundAssignment(Expression left)
{
MemberReferenceExpression mre = left as MemberReferenceExpression;
if (mre != null)
return IsWithoutSideEffects(mre.Target);
IndexerExpression ie = left as IndexerExpression;
if (ie != null)
return IsWithoutSideEffects(ie.Target) && ie.Arguments.All(IsWithoutSideEffects);
UnaryOperatorExpression uoe = left as UnaryOperatorExpression;
if (uoe != null && uoe.Operator == UnaryOperatorType.Dereference)
return IsWithoutSideEffects(uoe.Expression);
return IsWithoutSideEffects(left);
}
static bool IsWithoutSideEffects(Expression left)
{
return left is ThisReferenceExpression || left is IdentifierExpression || left is TypeReferenceExpression || left is BaseReferenceExpression;
}
void IAstTransform.Run(AstNode node, TransformContext context)
{
this.context = context;
try
{
node.AcceptVisitor(this);
}
finally
{
this.context = null;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/PrettifyAssignments.cs",
"repo_id": "ILSpy",
"token_count": 2341
} | 223 |
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.DebugInfo
{
/// <summary>
/// Visitor that generates debug information.
///
/// The intended usage is to create a new instance for each source file,
/// and call syntaxTree.AcceptVisitor(debugInfoGenerator) to fill the internal debug info tables.
/// This can happen concurrently for multiple source files.
/// Then the main thread calls Generate() to write out the results into the PDB.
/// </summary>
class DebugInfoGenerator : DepthFirstAstVisitor
{
static readonly KeyComparer<ILVariable, int> ILVariableKeyComparer = new KeyComparer<ILVariable, int>(l => l.Index.Value, Comparer<int>.Default, EqualityComparer<int>.Default);
IDecompilerTypeSystem typeSystem;
readonly ImportScopeInfo globalImportScope = new ImportScopeInfo();
ImportScopeInfo currentImportScope;
List<ImportScopeInfo> importScopes = new List<ImportScopeInfo>();
internal List<(MethodDefinitionHandle Method, ImportScopeInfo Import, int Offset, int Length, HashSet<ILVariable> Locals)> LocalScopes { get; } = new List<(MethodDefinitionHandle Method, ImportScopeInfo Import, int Offset, int Length, HashSet<ILVariable> Locals)>();
List<ILFunction> functions = new List<ILFunction>();
/// <summary>
/// Gets all functions with bodies that were seen by the visitor so far.
/// </summary>
public IReadOnlyList<ILFunction> Functions {
get => functions;
}
public DebugInfoGenerator(IDecompilerTypeSystem typeSystem)
{
this.typeSystem = typeSystem ?? throw new ArgumentNullException(nameof(typeSystem));
this.currentImportScope = globalImportScope;
}
public void GenerateImportScopes(MetadataBuilder metadata, ImportScopeHandle globalImportScope)
{
foreach (var scope in importScopes)
{
var blob = EncodeImports(metadata, scope);
scope.Handle = metadata.AddImportScope(scope.Parent == null ? globalImportScope : scope.Parent.Handle, blob);
}
}
static BlobHandle EncodeImports(MetadataBuilder metadata, ImportScopeInfo scope)
{
var writer = new BlobBuilder();
foreach (var import in scope.Imports)
{
writer.WriteByte((byte)ImportDefinitionKind.ImportNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(metadata.GetOrAddBlobUTF8(import)));
}
return metadata.GetOrAddBlob(writer);
}
public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
var parentImportScope = currentImportScope;
currentImportScope = new ImportScopeInfo(parentImportScope);
importScopes.Add(currentImportScope);
base.VisitNamespaceDeclaration(namespaceDeclaration);
currentImportScope = parentImportScope;
}
public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
currentImportScope.Imports.Add(usingDeclaration.Namespace);
}
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
HandleMethod(methodDeclaration);
}
public override void VisitAccessor(Accessor accessor)
{
HandleMethod(accessor);
}
public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
HandleMethod(constructorDeclaration);
}
public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
{
HandleMethod(destructorDeclaration);
}
public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
HandleMethod(operatorDeclaration);
}
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
HandleMethod(lambdaExpression);
}
public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
HandleMethod(anonymousMethodExpression);
}
public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
if (!propertyDeclaration.ExpressionBody.IsNull)
{
HandleMethod(propertyDeclaration.ExpressionBody, propertyDeclaration.Annotation<ILFunction>());
}
else
{
base.VisitPropertyDeclaration(propertyDeclaration);
}
}
public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
if (!indexerDeclaration.ExpressionBody.IsNull)
{
HandleMethod(indexerDeclaration.ExpressionBody, indexerDeclaration.Annotation<ILFunction>());
}
else
{
base.VisitIndexerDeclaration(indexerDeclaration);
}
}
public override void VisitQueryFromClause(QueryFromClause queryFromClause)
{
if (queryFromClause.Parent.FirstChild != queryFromClause)
{
HandleMethod(queryFromClause);
}
else
{
base.VisitQueryFromClause(queryFromClause);
}
}
public override void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
{
var annotation = queryGroupClause.Annotation<QueryGroupClauseAnnotation>();
if (annotation == null)
{
base.VisitQueryGroupClause(queryGroupClause);
return;
}
HandleMethod(queryGroupClause.Projection, annotation.ProjectionLambda);
HandleMethod(queryGroupClause.Key, annotation.KeyLambda);
}
public override void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
{
var annotation = queryJoinClause.Annotation<QueryJoinClauseAnnotation>();
if (annotation == null)
{
base.VisitQueryJoinClause(queryJoinClause);
return;
}
HandleMethod(queryJoinClause.OnExpression, annotation.OnLambda);
HandleMethod(queryJoinClause.EqualsExpression, annotation.EqualsLambda);
}
public override void VisitQueryLetClause(QueryLetClause queryLetClause)
{
HandleMethod(queryLetClause);
}
public override void VisitQueryOrdering(QueryOrdering queryOrdering)
{
HandleMethod(queryOrdering);
}
public override void VisitQuerySelectClause(QuerySelectClause querySelectClause)
{
HandleMethod(querySelectClause);
}
public override void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
{
HandleMethod(queryWhereClause);
}
void HandleMethod(AstNode node)
{
HandleMethod(node, node.Annotation<ILFunction>());
}
void HandleMethod(AstNode node, ILFunction function)
{
// Look into method body, e.g. in order to find lambdas
VisitChildren(node);
if (function == null || function.Method == null || function.Method.MetadataToken.IsNil)
return;
this.functions.Add(function);
var method = function.MoveNextMethod ?? function.Method;
MethodDefinitionHandle handle = (MethodDefinitionHandle)method.MetadataToken;
var file = typeSystem.MainModule.PEFile;
MethodDefinition md = file.Metadata.GetMethodDefinition(handle);
if (md.HasBody())
{
HandleMethodBody(function, file.Reader.GetMethodBody(md.RelativeVirtualAddress));
}
}
void HandleMethodBody(ILFunction function, MethodBodyBlock methodBody)
{
var method = function.MoveNextMethod ?? function.Method;
var localVariables = new HashSet<ILVariable>(ILVariableKeyComparer);
if (!methodBody.LocalSignature.IsNil)
{
#if DEBUG
var types = typeSystem.MainModule.DecodeLocalSignature(methodBody.LocalSignature,
new TypeSystem.GenericContext(method));
#endif
foreach (var v in function.Variables)
{
if (v.Index != null && v.Kind.IsLocal())
{
#if DEBUG
Debug.Assert(v.Index < types.Length && NormalizeTypeVisitor.TypeErasure.EquivalentTypes(v.Type, types[v.Index.Value]));
#endif
localVariables.Add(v);
}
}
}
LocalScopes.Add(((MethodDefinitionHandle)method.MetadataToken, currentImportScope,
0, methodBody.GetCodeSize(), localVariables));
}
}
}
| ILSpy/ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs",
"repo_id": "ILSpy",
"token_count": 2910
} | 224 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using ICSharpCode.Decompiler.DebugInfo;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.Disassembler
{
/// <summary>
/// Disassembles a method body.
/// </summary>
public class MethodBodyDisassembler
{
readonly ITextOutput output;
readonly CancellationToken cancellationToken;
/// <summary>
/// Show .try/finally as blocks in IL code; indent loops.
/// </summary>
public bool DetectControlStructure { get; set; } = true;
/// <summary>
/// Show sequence points if debug information is loaded in Cecil.
/// </summary>
public bool ShowSequencePoints { get; set; }
/// <summary>
/// Show metadata tokens for instructions with token operands.
/// </summary>
public bool ShowMetadataTokens { get; set; }
/// <summary>
/// Show metadata tokens for instructions with token operands in base 10.
/// </summary>
public bool ShowMetadataTokensInBase10 { get; set; }
/// <summary>
/// Show raw RVA offset and bytes before each instruction.
/// </summary>
public bool ShowRawRVAOffsetAndBytes { get; set; }
/// <summary>
/// Optional provider for sequence points.
/// </summary>
public IDebugInfoProvider DebugInfo { get; set; }
IList<DebugInfo.SequencePoint> sequencePoints;
int nextSequencePointIndex;
// cache info
PEFile module;
MetadataReader metadata;
MetadataGenericContext genericContext;
DisassemblerSignatureTypeProvider signatureDecoder;
public MethodBodyDisassembler(ITextOutput output, CancellationToken cancellationToken)
{
this.output = output ?? throw new ArgumentNullException(nameof(output));
this.cancellationToken = cancellationToken;
}
public virtual void Disassemble(PEFile module, MethodDefinitionHandle handle)
{
this.module = module ?? throw new ArgumentNullException(nameof(module));
metadata = module.Metadata;
genericContext = new MetadataGenericContext(handle, module);
signatureDecoder = new DisassemblerSignatureTypeProvider(module, output);
var methodDefinition = metadata.GetMethodDefinition(handle);
// start writing IL code
output.WriteLine("// Method begins at RVA 0x{0:x4}", methodDefinition.RelativeVirtualAddress);
if (methodDefinition.RelativeVirtualAddress == 0)
{
output.WriteLine("// Header size: {0}", 0);
output.WriteLine("// Code size: {0} (0x{0:x})", 0);
output.WriteLine(".maxstack {0}", 0);
output.WriteLine();
return;
}
MethodBodyBlock body;
BlobReader bodyBlockReader;
try
{
body = module.Reader.GetMethodBody(methodDefinition.RelativeVirtualAddress);
bodyBlockReader = module.Reader.GetSectionData(methodDefinition.RelativeVirtualAddress).GetReader();
}
catch (BadImageFormatException ex)
{
output.WriteLine("// {0}", ex.Message);
return;
}
var blob = body.GetILReader();
int headerSize = ILParser.GetHeaderSize(bodyBlockReader);
output.WriteLine("// Header size: {0}", headerSize);
output.WriteLine("// Code size: {0} (0x{0:x})", blob.Length);
output.WriteLine(".maxstack {0}", body.MaxStack);
var entrypointHandle = MetadataTokens.MethodDefinitionHandle(module.Reader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress);
if (handle == entrypointHandle)
output.WriteLine(".entrypoint");
DisassembleLocalsBlock(handle, body);
output.WriteLine();
sequencePoints = DebugInfo?.GetSequencePoints(handle) ?? EmptyList<DebugInfo.SequencePoint>.Instance;
nextSequencePointIndex = 0;
if (DetectControlStructure && blob.Length > 0)
{
blob.Reset();
BitSet branchTargets = new(blob.Length);
ILParser.SetBranchTargets(ref blob, branchTargets);
blob.Reset();
WriteStructureBody(new ILStructure(module, handle, genericContext, body), branchTargets, ref blob, methodDefinition.RelativeVirtualAddress + headerSize);
}
else
{
while (blob.RemainingBytes > 0)
{
cancellationToken.ThrowIfCancellationRequested();
WriteInstruction(output, metadata, handle, ref blob, methodDefinition.RelativeVirtualAddress);
}
WriteExceptionHandlers(module, handle, body);
}
sequencePoints = null;
}
void DisassembleLocalsBlock(MethodDefinitionHandle method, MethodBodyBlock body)
{
if (body.LocalSignature.IsNil)
return;
output.Write(".locals");
WriteMetadataToken(body.LocalSignature, spaceBefore: true);
if (body.LocalVariablesInitialized)
output.Write(" init");
var blob = metadata.GetStandaloneSignature(body.LocalSignature);
var signature = ImmutableArray<Action<ILNameSyntax>>.Empty;
try
{
if (blob.GetKind() == StandaloneSignatureKind.LocalVariables)
{
signature = blob.DecodeLocalSignature(signatureDecoder, genericContext);
}
else
{
output.Write(" /* wrong signature kind */");
}
}
catch (BadImageFormatException ex)
{
output.Write($" /* {ex.Message} */");
}
output.Write(' ');
output.WriteLine("(");
output.Indent();
int index = 0;
foreach (var v in signature)
{
output.WriteLocalReference("[" + index + "]", "loc_" + index, isDefinition: true);
output.Write(' ');
v(ILNameSyntax.TypeName);
if (DebugInfo != null && DebugInfo.TryGetName(method, index, out var name))
{
output.Write(" " + DisassemblerHelpers.Escape(name));
}
if (index + 1 < signature.Length)
output.Write(',');
output.WriteLine();
index++;
}
output.Unindent();
output.WriteLine(")");
}
internal void WriteExceptionHandlers(PEFile module, MethodDefinitionHandle handle, MethodBodyBlock body)
{
this.module = module;
metadata = module.Metadata;
genericContext = new MetadataGenericContext(handle, module);
signatureDecoder = new DisassemblerSignatureTypeProvider(module, output);
var handlers = body.ExceptionRegions;
if (!handlers.IsEmpty)
{
output.WriteLine();
foreach (var eh in handlers)
{
eh.WriteTo(module, genericContext, output);
output.WriteLine();
}
}
}
void WriteStructureHeader(ILStructure s)
{
switch (s.Type)
{
case ILStructureType.Loop:
output.Write("// loop start");
if (s.LoopEntryPointOffset >= 0)
{
output.Write(" (head: ");
DisassemblerHelpers.WriteOffsetReference(output, s.LoopEntryPointOffset);
output.Write(')');
}
output.WriteLine();
break;
case ILStructureType.Try:
output.WriteLine(".try");
output.WriteLine("{");
break;
case ILStructureType.Handler:
switch (s.ExceptionHandler.Kind)
{
case ExceptionRegionKind.Filter:
// handler block of filter block has no header
break;
case ExceptionRegionKind.Catch:
output.Write("catch");
if (!s.ExceptionHandler.CatchType.IsNil)
{
output.Write(' ');
s.ExceptionHandler.CatchType.WriteTo(s.Module, output, s.GenericContext, ILNameSyntax.TypeName);
}
output.WriteLine();
break;
case ExceptionRegionKind.Finally:
output.WriteLine("finally");
break;
case ExceptionRegionKind.Fault:
output.WriteLine("fault");
break;
default:
throw new ArgumentOutOfRangeException();
}
output.WriteLine("{");
break;
case ILStructureType.Filter:
output.WriteLine("filter");
output.WriteLine("{");
break;
default:
throw new ArgumentOutOfRangeException();
}
output.Indent();
}
void WriteStructureBody(ILStructure s, BitSet branchTargets, ref BlobReader body, int methodRva)
{
bool isFirstInstructionInStructure = true;
bool prevInstructionWasBranch = false;
int childIndex = 0;
while (body.RemainingBytes > 0 && body.Offset < s.EndOffset)
{
cancellationToken.ThrowIfCancellationRequested();
int offset = body.Offset;
if (childIndex < s.Children.Count && s.Children[childIndex].StartOffset <= offset && offset < s.Children[childIndex].EndOffset)
{
ILStructure child = s.Children[childIndex++];
WriteStructureHeader(child);
WriteStructureBody(child, branchTargets, ref body, methodRva);
WriteStructureFooter(child);
}
else
{
if (!isFirstInstructionInStructure && (prevInstructionWasBranch || branchTargets[offset]))
{
output.WriteLine(); // put an empty line after branches, and in front of branch targets
}
var currentOpCode = ILParser.DecodeOpCode(ref body);
body.Offset = offset; // reset IL stream
WriteInstruction(output, metadata, s.MethodHandle, ref body, methodRva);
prevInstructionWasBranch = currentOpCode.IsBranch()
|| currentOpCode.IsReturn()
|| currentOpCode == ILOpCode.Throw
|| currentOpCode == ILOpCode.Rethrow
|| currentOpCode == ILOpCode.Switch;
}
isFirstInstructionInStructure = false;
}
}
void WriteStructureFooter(ILStructure s)
{
output.Unindent();
switch (s.Type)
{
case ILStructureType.Loop:
output.WriteLine("// end loop");
break;
case ILStructureType.Try:
output.WriteLine("} // end .try");
break;
case ILStructureType.Handler:
output.WriteLine("} // end handler");
break;
case ILStructureType.Filter:
output.WriteLine("} // end filter");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
protected virtual void WriteInstruction(ITextOutput output, MetadataReader metadata, MethodDefinitionHandle methodHandle, ref BlobReader blob, int methodRva)
{
int offset = blob.Offset;
if (ShowSequencePoints && nextSequencePointIndex < sequencePoints?.Count)
{
var sp = sequencePoints[nextSequencePointIndex];
if (sp.Offset <= offset)
{
output.Write("// sequence point: ");
if (sp.Offset != offset)
{
output.Write("!! at " + DisassemblerHelpers.OffsetToString(sp.Offset) + " !!");
}
if (sp.IsHidden)
{
output.WriteLine("hidden");
}
else
{
output.WriteLine($"(line {sp.StartLine}, col {sp.StartColumn}) to (line {sp.EndLine}, col {sp.EndColumn}) in {sp.DocumentUrl}");
}
nextSequencePointIndex++;
}
}
ILOpCode opCode = ILParser.DecodeOpCode(ref blob);
if (opCode.IsDefined())
{
WriteRVA(blob, offset + methodRva, opCode);
output.WriteLocalReference(DisassemblerHelpers.OffsetToString(offset), offset, isDefinition: true);
output.Write(": ");
WriteOpCode(opCode);
switch (opCode.GetOperandType())
{
case OperandType.BrTarget:
case OperandType.ShortBrTarget:
output.Write(' ');
int targetOffset = ILParser.DecodeBranchTarget(ref blob, opCode);
output.WriteLocalReference($"IL_{targetOffset:x4}", targetOffset);
break;
case OperandType.Field:
case OperandType.Method:
case OperandType.Sig:
case OperandType.Type:
output.Write(' ');
int metadataToken = blob.ReadInt32();
EntityHandle? handle = MetadataTokenHelpers.TryAsEntityHandle(metadataToken);
try
{
handle?.WriteTo(module, output, genericContext);
}
catch (BadImageFormatException)
{
handle = null;
}
WriteMetadataToken(handle, metadataToken, spaceBefore: true);
break;
case OperandType.Tok:
output.Write(' ');
metadataToken = blob.ReadInt32();
handle = MetadataTokenHelpers.TryAsEntityHandle(metadataToken);
switch (handle?.Kind)
{
case HandleKind.MemberReference:
switch (metadata.GetMemberReference((MemberReferenceHandle)handle).GetKind())
{
case MemberReferenceKind.Method:
output.Write("method ");
break;
case MemberReferenceKind.Field:
output.Write("field ");
break;
}
break;
case HandleKind.FieldDefinition:
output.Write("field ");
break;
case HandleKind.MethodDefinition:
output.Write("method ");
break;
}
try
{
handle?.WriteTo(module, output, genericContext);
}
catch (BadImageFormatException)
{
handle = null;
}
WriteMetadataToken(handle, metadataToken, spaceBefore: true);
break;
case OperandType.ShortI:
output.Write(' ');
DisassemblerHelpers.WriteOperand(output, blob.ReadSByte());
break;
case OperandType.I:
output.Write(' ');
DisassemblerHelpers.WriteOperand(output, blob.ReadInt32());
break;
case OperandType.I8:
output.Write(' ');
DisassemblerHelpers.WriteOperand(output, blob.ReadInt64());
break;
case OperandType.ShortR:
output.Write(' ');
DisassemblerHelpers.WriteOperand(output, blob.ReadSingle());
break;
case OperandType.R:
output.Write(' ');
DisassemblerHelpers.WriteOperand(output, blob.ReadDouble());
break;
case OperandType.String:
metadataToken = blob.ReadInt32();
output.Write(' ');
UserStringHandle? userString;
string text;
try
{
userString = MetadataTokens.UserStringHandle(metadataToken);
text = metadata.GetUserString(userString.Value);
}
catch (BadImageFormatException)
{
userString = null;
text = null;
}
if (userString != null)
{
DisassemblerHelpers.WriteOperand(output, text);
}
WriteMetadataToken(userString, metadataToken, spaceBefore: true);
break;
case OperandType.Switch:
var tmp = blob;
int[] targets = ILParser.DecodeSwitchTargets(ref blob);
if (ShowRawRVAOffsetAndBytes)
{
output.WriteLine(" (");
}
else
{
output.Write(" (");
}
tmp.ReadInt32();
for (int i = 0; i < targets.Length; i++)
{
if (i > 0)
{
if (ShowRawRVAOffsetAndBytes)
{
output.WriteLine(",");
}
else
{
output.Write(", ");
}
}
if (ShowRawRVAOffsetAndBytes)
{
output.Write("/* ");
output.Write($"{tmp.ReadByte():X2}{tmp.ReadByte():X2}{tmp.ReadByte():X2}{tmp.ReadByte():X2}");
output.Write(" */ ");
}
if (ShowRawRVAOffsetAndBytes)
{
output.Write(" ");
}
output.WriteLocalReference($"IL_{targets[i]:x4}", targets[i]);
}
output.Write(")");
break;
case OperandType.Variable:
output.Write(' ');
int index = blob.ReadUInt16();
if (opCode == ILOpCode.Ldloc || opCode == ILOpCode.Ldloca || opCode == ILOpCode.Stloc)
{
DisassemblerHelpers.WriteVariableReference(output, metadata, methodHandle, index);
}
else
{
DisassemblerHelpers.WriteParameterReference(output, metadata, methodHandle, index);
}
break;
case OperandType.ShortVariable:
output.Write(' ');
index = blob.ReadByte();
if (opCode == ILOpCode.Ldloc_s || opCode == ILOpCode.Ldloca_s || opCode == ILOpCode.Stloc_s)
{
DisassemblerHelpers.WriteVariableReference(output, metadata, methodHandle, index);
}
else
{
DisassemblerHelpers.WriteParameterReference(output, metadata, methodHandle, index);
}
break;
}
}
else
{
ushort opCodeValue = (ushort)opCode;
if (opCodeValue > 0xFF)
{
if (ShowRawRVAOffsetAndBytes)
{
output.Write("/* ");
output.Write($"0x{offset + methodRva:X8} {(ushort)opCode >> 8:X2}");
output.Write(" */ ");
}
output.WriteLocalReference(DisassemblerHelpers.OffsetToString(offset), offset, isDefinition: true);
output.Write(": ");
// split 16-bit value into two emitbyte directives
output.WriteLine($".emitbyte 0x{(byte)(opCodeValue >> 8):x}");
if (ShowRawRVAOffsetAndBytes)
{
output.Write("/* ");
output.Write($"0x{offset + methodRva + 1:X8} {(ushort)opCode & 0xFF:X2}");
output.Write(" */ ");
}
// add label
output.WriteLocalReference(DisassemblerHelpers.OffsetToString(offset + 1), offset + 1, isDefinition: true);
output.Write(": ");
output.Write($".emitbyte 0x{(byte)(opCodeValue & 0xFF):x}");
}
else
{
if (ShowRawRVAOffsetAndBytes)
{
output.Write("/* ");
output.Write($"0x{offset + methodRva:X8} {(ushort)opCode & 0xFF:X2}");
output.Write(" */ ");
}
output.WriteLocalReference(DisassemblerHelpers.OffsetToString(offset), offset, isDefinition: true);
output.Write(": ");
output.Write($".emitbyte 0x{(byte)opCodeValue:x}");
}
}
output.WriteLine();
}
void WriteRVA(BlobReader blob, int offset, ILOpCode opCode)
{
if (ShowRawRVAOffsetAndBytes)
{
output.Write("/* ");
var tmp = blob;
if (opCode == ILOpCode.Switch)
{
tmp.ReadInt32();
}
else
{
ILParser.SkipOperand(ref tmp, opCode);
}
output.Write($"0x{offset:X8} {(ushort)opCode:X2}");
int appendSpaces = (ushort)opCode > 0xFF ? 14 : 16;
while (blob.Offset < tmp.Offset)
{
output.Write($"{blob.ReadByte():X2}");
appendSpaces -= 2;
}
if (appendSpaces > 0)
{
output.Write(new string(' ', appendSpaces));
}
output.Write(" */ ");
}
}
private void WriteOpCode(ILOpCode opCode)
{
var opCodeInfo = new OpCodeInfo(opCode, opCode.GetDisplayName());
string index;
switch (opCode)
{
case ILOpCode.Ldarg_0:
case ILOpCode.Ldarg_1:
case ILOpCode.Ldarg_2:
case ILOpCode.Ldarg_3:
output.WriteReference(opCodeInfo, omitSuffix: true);
index = opCodeInfo.Name.Substring(6);
output.WriteLocalReference(index, "param_" + index);
break;
case ILOpCode.Ldloc_0:
case ILOpCode.Ldloc_1:
case ILOpCode.Ldloc_2:
case ILOpCode.Ldloc_3:
case ILOpCode.Stloc_0:
case ILOpCode.Stloc_1:
case ILOpCode.Stloc_2:
case ILOpCode.Stloc_3:
output.WriteReference(opCodeInfo, omitSuffix: true);
index = opCodeInfo.Name.Substring(6);
output.WriteLocalReference(index, "loc_" + index);
break;
default:
output.WriteReference(opCodeInfo);
break;
}
}
private void WriteMetadataToken(EntityHandle handle, bool spaceBefore)
{
WriteMetadataToken(handle, MetadataTokens.GetToken(handle), spaceBefore);
}
private void WriteMetadataToken(Handle? handle, int metadataToken, bool spaceBefore)
{
ReflectionDisassembler.WriteMetadataToken(output, module, handle, metadataToken,
spaceAfter: false, spaceBefore, ShowMetadataTokens, ShowMetadataTokensInBase10);
}
}
}
| ILSpy/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/MethodBodyDisassembler.cs",
"repo_id": "ILSpy",
"token_count": 8278
} | 225 |
using System;
using System.Threading;
namespace Humanizer.Inflections
{
/// <summary>
/// Container for registered Vocabularies. At present, only a single vocabulary is supported: Default.
/// </summary>
internal static class Vocabularies
{
private static readonly Lazy<Vocabulary> Instance;
static Vocabularies()
{
Instance = new Lazy<Vocabulary>(BuildDefault, LazyThreadSafetyMode.PublicationOnly);
}
/// <summary>
/// The default vocabulary used for singular/plural irregularities.
/// Rules can be added to this vocabulary and will be picked up by called to Singularize() and Pluralize().
/// At this time, multiple vocabularies and removing existing rules are not supported.
/// </summary>
public static Vocabulary Default => Instance.Value;
private static Vocabulary BuildDefault()
{
var _default = new Vocabulary();
_default.AddPlural("$", "s");
_default.AddPlural("s$", "s");
_default.AddPlural("(ax|test)is$", "$1es");
_default.AddPlural("(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)us$", "$1i");
_default.AddPlural("(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)$", "$1es");
_default.AddPlural("(buffal|tomat|volcan|ech|embarg|her|mosquit|potat|torped|vet)o$", "$1oes");
_default.AddPlural("([dti])um$", "$1a");
_default.AddPlural("sis$", "ses");
_default.AddPlural("(?:([^f])fe|([lr])f)$", "$1$2ves");
_default.AddPlural("(hive)$", "$1s");
_default.AddPlural("([^aeiouy]|qu)y$", "$1ies");
_default.AddPlural("(x|ch|ss|sh)$", "$1es");
_default.AddPlural("(matr|vert|ind|d)ix|ex$", "$1ices");
_default.AddPlural("(^[m|l])ouse$", "$1ice");
_default.AddPlural("^(ox)$", "$1en");
_default.AddPlural("(quiz)$", "$1zes");
_default.AddPlural("(buz|blit|walt)z$", "$1zes");
_default.AddPlural("(hoo|lea|loa|thie)f$", "$1ves");
_default.AddPlural("(alumn|alg|larv|vertebr)a$", "$1ae");
_default.AddPlural("(criteri|phenomen)on$", "$1a");
_default.AddSingular("s$", "");
_default.AddSingular("(n)ews$", "$1ews");
_default.AddSingular("([dti])a$", "$1um");
_default.AddSingular("(analy|ba|diagno|parenthe|progno|synop|the|ellip|empha|neuro|oa|paraly)ses$", "$1sis");
_default.AddSingular("([^f])ves$", "$1fe");
_default.AddSingular("(hive)s$", "$1");
_default.AddSingular("(tive)s$", "$1");
_default.AddSingular("([lr]|hoo|lea|loa|thie)ves$", "$1f");
_default.AddSingular("(^zomb)?([^aeiouy]|qu)ies$", "$2y");
_default.AddSingular("(s)eries$", "$1eries");
_default.AddSingular("(m)ovies$", "$1ovie");
_default.AddSingular("(x|ch|ss|sh)es$", "$1");
_default.AddSingular("(^[m|l])ice$", "$1ouse");
_default.AddSingular("(o)es$", "$1");
_default.AddSingular("(shoe)s$", "$1");
_default.AddSingular("(cris|ax|test)es$", "$1is");
_default.AddSingular("(octop|vir|alumn|fung|cact|foc|hippopotam|radi|stimul|syllab|nucle)i$", "$1us");
_default.AddSingular("(alias|bias|iris|status|campus|apparatus|virus|walrus|trellis)es$", "$1");
_default.AddSingular("^(ox)en", "$1");
_default.AddSingular("(matr|d)ices$", "$1ix");
_default.AddSingular("(vert|ind)ices$", "$1ex");
_default.AddSingular("(quiz)zes$", "$1");
_default.AddSingular("(buz|blit|walt)zes$", "$1z");
_default.AddSingular("(alumn|alg|larv|vertebr)ae$", "$1a");
_default.AddSingular("(criteri|phenomen)a$", "$1on");
_default.AddSingular("([b|r|c]ook|room|smooth)ies$", "$1ie");
_default.AddIrregular("person", "people");
_default.AddIrregular("man", "men");
_default.AddIrregular("human", "humans");
_default.AddIrregular("child", "children");
_default.AddIrregular("sex", "sexes");
_default.AddIrregular("glove", "gloves");
_default.AddIrregular("move", "moves");
_default.AddIrregular("goose", "geese");
_default.AddIrregular("wave", "waves");
_default.AddIrregular("die", "dice");
_default.AddIrregular("foot", "feet");
_default.AddIrregular("tooth", "teeth");
_default.AddIrregular("curriculum", "curricula");
_default.AddIrregular("database", "databases");
_default.AddIrregular("zombie", "zombies");
_default.AddIrregular("personnel", "personnel");
//Fix #789
_default.AddIrregular("cache", "caches");
//Fix 975
_default.AddIrregular("ex", "exes", matchEnding: false);
_default.AddIrregular("is", "are", matchEnding: false);
_default.AddIrregular("that", "those", matchEnding: false);
_default.AddIrregular("this", "these", matchEnding: false);
_default.AddIrregular("bus", "buses", matchEnding: false);
_default.AddIrregular("staff", "staff", matchEnding: false);
_default.AddIrregular("training", "training", matchEnding: false);
_default.AddUncountable("equipment");
_default.AddUncountable("information");
_default.AddUncountable("corn");
_default.AddUncountable("milk");
_default.AddUncountable("rice");
_default.AddUncountable("money");
_default.AddUncountable("species");
_default.AddUncountable("series");
_default.AddUncountable("fish");
_default.AddUncountable("sheep");
_default.AddUncountable("deer");
_default.AddUncountable("aircraft");
_default.AddUncountable("oz");
_default.AddUncountable("tsp");
_default.AddUncountable("tbsp");
_default.AddUncountable("ml");
_default.AddUncountable("l");
_default.AddUncountable("water");
_default.AddUncountable("waters");
_default.AddUncountable("semen");
_default.AddUncountable("sperm");
_default.AddUncountable("bison");
_default.AddUncountable("grass");
_default.AddUncountable("hair");
_default.AddUncountable("mud");
_default.AddUncountable("elk");
_default.AddUncountable("luggage");
_default.AddUncountable("moose");
_default.AddUncountable("offspring");
_default.AddUncountable("salmon");
_default.AddUncountable("shrimp");
_default.AddUncountable("someone");
_default.AddUncountable("swine");
_default.AddUncountable("trout");
_default.AddUncountable("tuna");
_default.AddUncountable("corps");
_default.AddUncountable("scissors");
_default.AddUncountable("means");
_default.AddUncountable("mail");
return _default;
}
}
} | ILSpy/ICSharpCode.Decompiler/Humanizer/Vocabularies.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Humanizer/Vocabularies.cs",
"repo_id": "ILSpy",
"token_count": 2560
} | 226 |
// Copyright (c) Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System.Linq;
using ICSharpCode.Decompiler.IL.Transforms;
namespace ICSharpCode.Decompiler.IL.ControlFlow
{
/// <summary>
/// Similar to <see cref="DetectExitPoints"/>, but acts only on <c>leave</c> instructions
/// leaving the whole function (<c>return</c>/<c>yield break</c>) that can be made implicit
/// without using goto.
/// </summary>
class RemoveRedundantReturn : IILTransform
{
public void Run(ILFunction function, ILTransformContext context)
{
foreach (var lambda in function.Descendants.OfType<ILFunction>())
{
if (lambda.Body is BlockContainer c && ((lambda.AsyncReturnType ?? lambda.ReturnType).Kind == TypeSystem.TypeKind.Void || lambda.IsIterator))
{
Block lastBlock = c.Blocks.Last();
if (lastBlock.Instructions.Last() is Leave { IsLeavingFunction: true })
{
ConvertReturnToFallthrough(lastBlock.Instructions.SecondToLastOrDefault());
}
else
{
if (ConvertReturnToFallthrough(lastBlock.Instructions.Last()))
{
lastBlock.Instructions.Add(new Leave(c));
}
}
}
}
}
private static bool ConvertReturnToFallthrough(ILInstruction? inst)
{
bool result = false;
switch (inst)
{
case BlockContainer c when c.Kind == ContainerKind.Normal:
// body of try block, or similar: recurse into last instruction in container
// Note: no need to handle loops/switches here; those already were handled by DetectExitPoints
Block lastBlock = c.Blocks.Last();
if (lastBlock.Instructions.Last() is Leave { IsLeavingFunction: true, Value: Nop } leave)
{
leave.TargetContainer = c;
result = true;
}
else if (ConvertReturnToFallthrough(lastBlock.Instructions.Last()))
{
lastBlock.Instructions.Add(new Leave(c));
result = true;
}
break;
case TryCatch tryCatch:
result |= ConvertReturnToFallthrough(tryCatch.TryBlock);
foreach (var h in tryCatch.Handlers)
{
result |= ConvertReturnToFallthrough(h.Body);
}
break;
case TryFinally tryFinally:
result |= ConvertReturnToFallthrough(tryFinally.TryBlock);
break;
case LockInstruction lockInst:
result |= ConvertReturnToFallthrough(lockInst.Body);
break;
case UsingInstruction usingInst:
result |= ConvertReturnToFallthrough(usingInst.Body);
break;
case PinnedRegion pinnedRegion:
result |= ConvertReturnToFallthrough(pinnedRegion.Body);
break;
case IfInstruction ifInstruction:
result |= ConvertReturnToFallthrough(ifInstruction.TrueInst);
result |= ConvertReturnToFallthrough(ifInstruction.FalseInst);
break;
case Block block when block.Kind == BlockKind.ControlFlow:
{
var lastInst = block.Instructions.LastOrDefault();
if (lastInst is Leave { IsLeavingFunction: true, Value: Nop })
{
block.Instructions.RemoveAt(block.Instructions.Count - 1);
result = true;
lastInst = block.Instructions.LastOrDefault();
}
result |= ConvertReturnToFallthrough(lastInst);
break;
}
}
return result;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/RemoveRedundantReturn.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/RemoveRedundantReturn.cs",
"repo_id": "ILSpy",
"token_count": 1488
} | 227 |
#nullable enable
// Copyright (c) 2014 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL
{
public enum BinaryNumericOperator : byte
{
None,
Add,
Sub,
Mul,
Div,
Rem,
BitAnd,
BitOr,
BitXor,
ShiftLeft,
ShiftRight
}
public partial class BinaryNumericInstruction : BinaryInstruction, ILiftableInstruction
{
/// <summary>
/// Gets whether the instruction checks for overflow.
/// </summary>
public readonly bool CheckForOverflow;
/// <summary>
/// For integer operations that depend on the sign, specifies whether the operation
/// is signed or unsigned.
/// For instructions that produce the same result for either sign, returns Sign.None.
/// </summary>
public readonly Sign Sign;
public readonly StackType LeftInputType;
public readonly StackType RightInputType;
/// <summary>
/// The operator used by this binary operator instruction.
/// </summary>
public readonly BinaryNumericOperator Operator;
/// <summary>
/// Gets whether this is a lifted nullable operation.
/// </summary>
/// <remarks>
/// A lifted binary operation allows its arguments to be a value of type Nullable{T}, where
/// T.GetStackType() == [Left|Right]InputType.
/// If both input values are non-null:
/// * they are sign/zero-extended to the corresponding InputType (based on T's sign)
/// * the underlying numeric operator is applied
/// * the result is wrapped in a Nullable{UnderlyingResultType}.
/// If either input is null, the instruction evaluates to default(UnderlyingResultType?).
/// (this result type is underspecified, since there may be multiple C# types for the stack type)
/// </remarks>
public bool IsLifted { get; }
readonly StackType resultType;
public BinaryNumericInstruction(BinaryNumericOperator op, ILInstruction left, ILInstruction right, bool checkForOverflow, Sign sign)
: this(op, left, right, left.ResultType, right.ResultType, checkForOverflow, sign)
{
}
public BinaryNumericInstruction(BinaryNumericOperator op, ILInstruction left, ILInstruction right, StackType leftInputType, StackType rightInputType, bool checkForOverflow, Sign sign, bool isLifted = false)
: base(OpCode.BinaryNumericInstruction, left, right)
{
this.CheckForOverflow = checkForOverflow;
this.Sign = sign;
this.Operator = op;
this.LeftInputType = leftInputType;
this.RightInputType = rightInputType;
this.IsLifted = isLifted;
this.resultType = ComputeResultType(op, LeftInputType, RightInputType);
}
internal static StackType ComputeResultType(BinaryNumericOperator op, StackType left, StackType right)
{
// Based on Table 2: Binary Numeric Operations
// also works for Table 5: Integer Operations
// and for Table 7: Overflow Arithmetic Operations
if (left == right || op == BinaryNumericOperator.ShiftLeft || op == BinaryNumericOperator.ShiftRight)
{
// Shift op codes use Table 6
return left;
}
if (left == StackType.Ref || right == StackType.Ref)
{
if (left == StackType.Ref && right == StackType.Ref)
{
// sub(&, &) = I
Debug.Assert(op == BinaryNumericOperator.Sub);
return StackType.I;
}
else
{
// add/sub with I or I4 and &
Debug.Assert(op == BinaryNumericOperator.Add || op == BinaryNumericOperator.Sub);
return StackType.Ref;
}
}
return StackType.Unknown;
}
public StackType UnderlyingResultType { get => resultType; }
public sealed override StackType ResultType {
get => IsLifted ? StackType.O : resultType;
}
internal override void CheckInvariant(ILPhase phase)
{
base.CheckInvariant(phase);
if (!IsLifted)
{
Debug.Assert(LeftInputType == Left.ResultType);
Debug.Assert(RightInputType == Right.ResultType);
}
}
protected override InstructionFlags ComputeFlags()
{
var flags = base.ComputeFlags();
if (CheckForOverflow || (Operator == BinaryNumericOperator.Div || Operator == BinaryNumericOperator.Rem))
flags |= InstructionFlags.MayThrow;
return flags;
}
public override InstructionFlags DirectFlags {
get {
if (CheckForOverflow || (Operator == BinaryNumericOperator.Div || Operator == BinaryNumericOperator.Rem))
return base.DirectFlags | InstructionFlags.MayThrow;
return base.DirectFlags;
}
}
internal static string GetOperatorName(BinaryNumericOperator @operator)
{
switch (@operator)
{
case BinaryNumericOperator.Add:
return "add";
case BinaryNumericOperator.Sub:
return "sub";
case BinaryNumericOperator.Mul:
return "mul";
case BinaryNumericOperator.Div:
return "div";
case BinaryNumericOperator.Rem:
return "rem";
case BinaryNumericOperator.BitAnd:
return "bit.and";
case BinaryNumericOperator.BitOr:
return "bit.or";
case BinaryNumericOperator.BitXor:
return "bit.xor";
case BinaryNumericOperator.ShiftLeft:
return "bit.shl";
case BinaryNumericOperator.ShiftRight:
return "bit.shr";
default:
throw new ArgumentOutOfRangeException();
}
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
output.Write("." + GetOperatorName(Operator));
if (CheckForOverflow)
{
output.Write(".ovf");
}
if (Sign == Sign.Unsigned)
{
output.Write(".unsigned");
}
else if (Sign == Sign.Signed)
{
output.Write(".signed");
}
output.Write('.');
output.Write(resultType.ToString().ToLowerInvariant());
if (IsLifted)
{
output.Write(".lifted");
}
output.Write('(');
Left.WriteTo(output, options);
output.Write(", ");
Right.WriteTo(output, options);
output.Write(')');
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/BinaryNumericInstruction.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/BinaryNumericInstruction.cs",
"repo_id": "ILSpy",
"token_count": 2376
} | 228 |
#nullable enable
// Copyright (c) 2016 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ICSharpCode.Decompiler.IL
{
/// <summary>
/// The collection of variables in a <c>ILFunction</c>.
/// </summary>
public class ILVariableCollection : ICollection<ILVariable>, IReadOnlyList<ILVariable>
{
readonly ILFunction scope;
readonly List<ILVariable> list = new List<ILVariable>();
internal ILVariableCollection(ILFunction scope)
{
this.scope = scope;
}
/// <summary>
/// Gets a variable given its <c>IndexInFunction</c>.
/// </summary>
public ILVariable this[int index] {
get {
return list[index];
}
}
public bool Add(ILVariable item)
{
if (item.Function != null)
{
if (item.Function == scope)
return false;
else
throw new ArgumentException("Variable already belongs to another scope");
}
item.Function = scope;
item.IndexInFunction = list.Count;
list.Add(item);
return true;
}
void ICollection<ILVariable>.Add(ILVariable item)
{
Add(item);
}
public void Clear()
{
foreach (var v in list)
{
v.Function = null;
}
list.Clear();
}
public bool Contains(ILVariable item)
{
Debug.Assert(item.Function != scope || list[item.IndexInFunction] == item);
return item.Function == scope;
}
public bool Remove(ILVariable item)
{
if (item.Function != scope)
return false;
Debug.Assert(list[item.IndexInFunction] == item);
RemoveAt(item.IndexInFunction);
return true;
}
void RemoveAt(int index)
{
list[index].Function = null;
// swap-remove index
list[index] = list[list.Count - 1];
list[index].IndexInFunction = index;
list.RemoveAt(list.Count - 1);
}
/// <summary>
/// Remove variables that have StoreCount == LoadCount == AddressCount == 0.
/// </summary>
public void RemoveDead()
{
for (int i = 0; i < list.Count;)
{
if (ShouldRemoveVariable(list[i]))
{
RemoveAt(i);
}
else
{
i++;
}
}
static bool ShouldRemoveVariable(ILVariable v)
{
if (!v.IsDead)
return false;
// Note: we cannot remove display-class locals from the collection,
// even if they are unused - which is always the case, if TDCU succeeds,
// because they are necessary for PDB generation to produce correct results.
if (v.Kind == VariableKind.DisplayClassLocal)
return false;
// Do not remove parameter variables, as these are defined even if unused.
if (v.Kind == VariableKind.Parameter)
{
// However, remove unused this-parameters of delegates, expression trees, etc.
// These will be replaced with the top-level function's this-parameter.
if (v.Index == -1 && v.Function!.Kind != ILFunctionKind.TopLevelFunction)
return true;
return false;
}
return true;
}
}
public int Count {
get { return list.Count; }
}
public void CopyTo(ILVariable[] array, int arrayIndex)
{
list.CopyTo(array, arrayIndex);
}
bool ICollection<ILVariable>.IsReadOnly {
get { return false; }
}
public List<ILVariable>.Enumerator GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator<ILVariable> IEnumerable<ILVariable>.GetEnumerator()
{
return GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/ILVariableCollection.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/ILVariableCollection.cs",
"repo_id": "ILSpy",
"token_count": 1587
} | 229 |
#nullable enable
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL
{
/// <summary>
/// Generalization of IL switch-case: like a VB switch over integers, this instruction
/// supports integer value ranges as labels.
///
/// The section labels are using 'long' as integer type.
/// If the Value instruction produces StackType.I4 or I, the value is implicitly sign-extended to I8.
/// </summary>
partial class SwitchInstruction
{
public static readonly SlotInfo ValueSlot = new SlotInfo("Value", canInlineInto: true);
public static readonly SlotInfo SectionSlot = new SlotInfo("Section", isCollection: true);
/// <summary>
/// If the switch instruction is lifted, the value instruction produces a value of type <c>Nullable{T}</c> for some
/// integral type T. The section with <c>SwitchSection.HasNullLabel</c> is called if the value is null.
/// </summary>
public bool IsLifted;
/// <summary>
/// Additional type information used to interpret the value instruction.
/// Set by ILInlining to preserve stack information that would otherwise be lost.
/// </summary>
public IType? Type;
public SwitchInstruction(ILInstruction value)
: base(OpCode.SwitchInstruction)
{
this.Value = value;
this.Sections = new InstructionCollection<SwitchSection>(this, 1);
}
ILInstruction value = null!;
public ILInstruction Value {
get { return this.value; }
set {
ValidateChild(value);
SetChildInstruction(ref this.value, value, 0);
}
}
public readonly InstructionCollection<SwitchSection> Sections;
protected override InstructionFlags ComputeFlags()
{
var sectionFlags = InstructionFlags.EndPointUnreachable; // neutral element for CombineBranches()
foreach (var section in Sections)
{
sectionFlags = SemanticHelper.CombineBranches(sectionFlags, section.Flags);
}
return value.Flags | InstructionFlags.ControlFlow | sectionFlags;
}
public override InstructionFlags DirectFlags {
get {
return InstructionFlags.ControlFlow;
}
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write("switch");
if (IsLifted)
output.Write(".lifted");
output.Write(' ');
Type?.WriteTo(output);
output.Write('(');
value.WriteTo(output, options);
output.Write(") ");
output.MarkFoldStart("{...}");
output.WriteLine("{");
output.Indent();
foreach (var section in this.Sections)
{
section.WriteTo(output, options);
output.WriteLine();
}
output.Unindent();
output.Write('}');
output.MarkFoldEnd();
}
protected override int GetChildCount()
{
return 1 + Sections.Count;
}
protected override ILInstruction GetChild(int index)
{
if (index == 0)
return value;
return Sections[index - 1];
}
protected override void SetChild(int index, ILInstruction value)
{
if (index == 0)
Value = value;
else
Sections[index - 1] = (SwitchSection)value;
}
protected override SlotInfo GetChildSlot(int index)
{
if (index == 0)
return ValueSlot;
return SectionSlot;
}
public override ILInstruction Clone()
{
var clone = new SwitchInstruction(value.Clone());
clone.AddILRange(this);
clone.Value = value.Clone();
clone.Sections.AddRange(this.Sections.Select(h => (SwitchSection)h.Clone()));
return clone;
}
StackType resultType = StackType.Void;
public override StackType ResultType => resultType;
public void SetResultType(StackType resultType)
{
this.resultType = resultType;
}
internal override void CheckInvariant(ILPhase phase)
{
base.CheckInvariant(phase);
bool expectNullSection = this.IsLifted;
LongSet sets = LongSet.Empty;
foreach (var section in Sections)
{
if (section.HasNullLabel)
{
Debug.Assert(expectNullSection, "Duplicate 'case null' or 'case null' in non-lifted switch.");
expectNullSection = false;
}
Debug.Assert(!section.Labels.IsEmpty || section.HasNullLabel);
Debug.Assert(!section.Labels.Overlaps(sets));
Debug.Assert(section.Body.ResultType == this.ResultType);
sets = sets.UnionWith(section.Labels);
}
Debug.Assert(sets.SetEquals(LongSet.Universe), "switch does not handle all possible cases");
Debug.Assert(!expectNullSection, "Lifted switch is missing 'case null'");
Debug.Assert(this.IsLifted ? (value.ResultType == StackType.O) : (value.ResultType == StackType.I4 || value.ResultType == StackType.I8));
}
public SwitchSection GetDefaultSection()
{
// Pick the section with the most labels as default section.
IL.SwitchSection defaultSection = Sections.First();
foreach (var section in Sections)
{
if (section.Labels.Count() > defaultSection.Labels.Count())
{
defaultSection = section;
}
}
return defaultSection;
}
}
partial class SwitchSection
{
public SwitchSection()
: base(OpCode.SwitchSection)
{
this.Labels = LongSet.Empty;
}
/// <summary>
/// If true, serves as 'case null' in a lifted switch.
/// </summary>
public bool HasNullLabel { get; set; }
/// <summary>
/// The set of labels that cause execution to jump to this switch section.
/// </summary>
public LongSet Labels { get; set; }
protected override InstructionFlags ComputeFlags()
{
return body.Flags;
}
public override InstructionFlags DirectFlags {
get {
return InstructionFlags.None;
}
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.WriteLocalReference("case", this, isDefinition: true);
output.Write(' ');
if (HasNullLabel)
{
output.Write("null");
if (!Labels.IsEmpty)
{
output.Write(", ");
output.Write(Labels.ToString());
}
}
else
{
output.Write(Labels.ToString());
}
output.Write(": ");
body.WriteTo(output, options);
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/SwitchInstruction.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/SwitchInstruction.cs",
"repo_id": "ILSpy",
"token_count": 2451
} | 230 |
// Copyright (c) 2011-2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
/// <summary>
/// Runs a very simple form of copy propagation.
/// Copy propagation is used in two cases:
/// 1) assignments from arguments to local variables
/// If the target variable is assigned to only once (so always is that argument) and the argument is never changed (no ldarga/starg),
/// then we can replace the variable with the argument.
/// 2) assignments of address-loading instructions to local variables
/// </summary>
public class CopyPropagation : IILTransform
{
public static void Propagate(StLoc store, ILTransformContext context)
{
Debug.Assert(store.Variable.IsSingleDefinition);
Block block = (Block)store.Parent;
int i = store.ChildIndex;
DoPropagate(store.Variable, store.Value, block, ref i, context);
}
public void Run(ILFunction function, ILTransformContext context)
{
var splitVariables = new HashSet<ILVariable>(ILVariableEqualityComparer.Instance);
foreach (var g in function.Variables.GroupBy(v => v, ILVariableEqualityComparer.Instance))
{
if (g.Count() > 1)
{
splitVariables.Add(g.Key);
}
}
foreach (var block in function.Descendants.OfType<Block>())
{
if (block.Kind != BlockKind.ControlFlow)
continue;
RunOnBlock(block, context, splitVariables);
}
}
static void RunOnBlock(Block block, ILTransformContext context, HashSet<ILVariable> splitVariables = null)
{
for (int i = 0; i < block.Instructions.Count; i++)
{
if (block.Instructions[i].MatchStLoc(out ILVariable v, out ILInstruction copiedExpr))
{
if (v.IsSingleDefinition && v.LoadCount == 0 && v.Kind == VariableKind.StackSlot)
{
// dead store to stack
if (SemanticHelper.IsPure(copiedExpr.Flags))
{
// no-op -> delete
context.Step("remove dead store to stack: no-op -> delete", block.Instructions[i]);
block.Instructions.RemoveAt(i);
// This can open up new inlining opportunities:
int c = ILInlining.InlineInto(block, i, InliningOptions.None, context: context);
i -= c + 1;
}
else
{
// evaluate the value for its side-effects
context.Step("remove dead store to stack: evaluate the value for its side-effects", block.Instructions[i]);
copiedExpr.AddILRange(block.Instructions[i]);
block.Instructions[i] = copiedExpr;
}
}
else if (v.IsSingleDefinition && CanPerformCopyPropagation(v, copiedExpr, splitVariables))
{
DoPropagate(v, copiedExpr, block, ref i, context);
}
}
}
}
static bool CanPerformCopyPropagation(ILVariable target, ILInstruction value, HashSet<ILVariable> splitVariables)
{
Debug.Assert(target.StackType == value.ResultType);
if (target.Type.IsSmallIntegerType())
return false;
if (splitVariables != null && splitVariables.Contains(target))
{
return false; // non-local code move might change semantics when there's split variables
}
switch (value.OpCode)
{
case OpCode.LdLoca:
// case OpCode.LdElema:
// case OpCode.LdFlda:
case OpCode.LdsFlda:
// All address-loading instructions always return the same value for a given operand/argument combination,
// so they can be safely copied.
// ... except for LdElema and LdFlda, because those might throw an exception, and we don't want to
// change the place where the exception is thrown.
return true;
case OpCode.LdLoc:
var v = ((LdLoc)value).Variable;
if (splitVariables != null && splitVariables.Contains(v))
{
return false; // non-local code move might change semantics when there's split variables
}
switch (v.Kind)
{
case VariableKind.Parameter:
// Parameters can be copied only if they aren't assigned to (directly or indirectly via ldarga)
// note: the initialization by the caller is the first store -> StoreCount must be 1
return v.IsSingleDefinition;
default:
// Variables can be copied if both are single-definition.
// To avoid removing too many variables, we do this only if the target
// is either a stackslot or a ref local.
Debug.Assert(target.IsSingleDefinition);
return v.IsSingleDefinition && (target.Kind == VariableKind.StackSlot || target.StackType == StackType.Ref);
}
default:
// All instructions without special behavior that target a stack-variable can be copied.
return value.Flags == InstructionFlags.None && value.Children.Count == 0 && target.Kind == VariableKind.StackSlot;
}
}
static void DoPropagate(ILVariable v, ILInstruction copiedExpr, Block block, ref int i, ILTransformContext context)
{
context.Step($"Copy propagate {v.Name}", copiedExpr);
// un-inline the arguments of the ldArg instruction
ILVariable[] uninlinedArgs = new ILVariable[copiedExpr.Children.Count];
for (int j = 0; j < uninlinedArgs.Length; j++)
{
var arg = copiedExpr.Children[j];
var type = context.TypeSystem.FindType(arg.ResultType);
uninlinedArgs[j] = new ILVariable(VariableKind.StackSlot, type, arg.ResultType) {
Name = "C_" + arg.StartILOffset,
HasGeneratedName = true,
};
block.Instructions.Insert(i++, new StLoc(uninlinedArgs[j], arg));
}
v.Function.Variables.AddRange(uninlinedArgs);
// perform copy propagation:
foreach (var expr in v.LoadInstructions.ToArray())
{
var clone = copiedExpr.Clone();
for (int j = 0; j < uninlinedArgs.Length; j++)
{
clone.Children[j].ReplaceWith(new LdLoc(uninlinedArgs[j]));
}
expr.ReplaceWith(clone);
}
block.Instructions.RemoveAt(i);
int c = ILInlining.InlineInto(block, i, InliningOptions.None, context: context);
i -= c + 1;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/CopyPropagation.cs",
"repo_id": "ILSpy",
"token_count": 2492
} | 231 |
// Copyright (c) 2021 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL.Transforms
{
public class InterpolatedStringTransform : IStatementTransform
{
void IStatementTransform.Run(Block block, int pos, StatementTransformContext context)
{
if (!context.Settings.StringInterpolation)
return;
int interpolationStart = pos;
int interpolationEnd;
ILInstruction insertionPoint;
// stloc v(newobj DefaultInterpolatedStringHandler..ctor(ldc.i4 literalLength, ldc.i4 formattedCount))
if (block.Instructions[pos] is StLoc {
Variable: ILVariable { Kind: VariableKind.Local } v,
Value: NewObj { Arguments: { Count: 2 } } newObj
} stloc
&& v.Type.IsKnownType(KnownTypeCode.DefaultInterpolatedStringHandler)
&& newObj.Method.DeclaringType.IsKnownType(KnownTypeCode.DefaultInterpolatedStringHandler)
&& newObj.Arguments[0].MatchLdcI4(out _)
&& newObj.Arguments[1].MatchLdcI4(out _))
{
// { call MethodName(ldloca v, ...) }
do
{
pos++;
}
while (IsKnownCall(block, pos, v));
interpolationEnd = pos;
// ... call ToStringAndClear(ldloca v) ...
if (!FindToStringAndClear(block, pos, interpolationStart, interpolationEnd, v, out insertionPoint))
{
return;
}
if (!(v.StoreCount == 1 && v.AddressCount == interpolationEnd - interpolationStart && v.LoadCount == 0))
{
return;
}
}
else
{
return;
}
context.Step($"Transform DefaultInterpolatedStringHandler {v.Name}", stloc);
v.Kind = VariableKind.InitializerTarget;
var replacement = new Block(BlockKind.InterpolatedString);
for (int i = interpolationStart; i < interpolationEnd; i++)
{
replacement.Instructions.Add(block.Instructions[i]);
}
var callToStringAndClear = insertionPoint;
insertionPoint.ReplaceWith(replacement);
replacement.FinalInstruction = callToStringAndClear;
block.Instructions.RemoveRange(interpolationStart, interpolationEnd - interpolationStart);
}
private bool IsKnownCall(Block block, int pos, ILVariable v)
{
if (pos >= block.Instructions.Count - 1)
return false;
if (!(block.Instructions[pos] is Call call))
return false;
if (!(call.Arguments.Count > 1))
return false;
if (!call.Arguments[0].MatchLdLoca(v))
return false;
if (call.Method.IsStatic)
return false;
if (!call.Method.DeclaringType.IsKnownType(KnownTypeCode.DefaultInterpolatedStringHandler))
return false;
switch (call.Method.Name)
{
case "AppendLiteral" when call.Arguments.Count == 2 && call.Arguments[1] is LdStr:
case "AppendFormatted" when call.Arguments.Count == 2:
case "AppendFormatted" when call.Arguments.Count == 3 && call.Arguments[2] is LdStr:
case "AppendFormatted" when call.Arguments.Count == 3 && call.Arguments[2] is LdcI4:
case "AppendFormatted" when call.Arguments.Count == 4 && call.Arguments[2] is LdcI4 && call.Arguments[3] is LdStr:
break;
default:
return false;
}
return true;
}
private bool FindToStringAndClear(Block block, int pos, int interpolationStart, int interpolationEnd, ILVariable v, out ILInstruction insertionPoint)
{
insertionPoint = null;
if (pos >= block.Instructions.Count)
return false;
// find
// ... call ToStringAndClear(ldloca v) ...
// in block.Instructions[pos]
for (int i = interpolationStart; i < interpolationEnd; i++)
{
var result = ILInlining.FindLoadInNext(block.Instructions[pos], v, block.Instructions[i], InliningOptions.None);
if (result.Type != ILInlining.FindResultType.Found)
return false;
insertionPoint ??= result.LoadInst.Parent;
Debug.Assert(insertionPoint == result.LoadInst.Parent);
}
return insertionPoint is Call {
Arguments: { Count: 1 },
Method: { Name: "ToStringAndClear", IsStatic: false }
};
}
}
} | ILSpy/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/InterpolatedStringTransform.cs",
"repo_id": "ILSpy",
"token_count": 1760
} | 232 |
// Copyright (c) 2021 Daniel Grunwald, Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace ICSharpCode.Decompiler.IL.Transforms
{
/// <summary>
/// Block IL_0018 (incoming: *) {
/// stloc s(ldc.i4 1)
/// br IL_0019
/// }
///
/// Block IL_0019 (incoming: > 1) {
/// if (logic.not(ldloc s)) br IL_0027
/// br IL_001d
/// }
///
/// replace br IL_0019 with br IL_0027
/// </summary>
class RemoveInfeasiblePathTransform : IILTransform
{
void IILTransform.Run(ILFunction function, ILTransformContext context)
{
foreach (var container in function.Descendants.OfType<BlockContainer>())
{
bool changed = false;
foreach (var block in container.Blocks)
{
changed |= DoTransform(block, context);
}
if (changed)
{
container.SortBlocks(deleteUnreachableBlocks: true);
}
}
}
private bool DoTransform(Block block, ILTransformContext context)
{
if (!MatchBlock1(block, out var s, out int value, out var br))
return false;
if (!MatchBlock2(br.TargetBlock, s, value, out var exitInst))
return false;
context.Step("RemoveInfeasiblePath", br);
br.ReplaceWith(exitInst.Clone());
s.RemoveIfRedundant = true;
return true;
}
// Block IL_0018 (incoming: *) {
// stloc s(ldc.i4 1)
// br IL_0019
// }
private bool MatchBlock1(Block block, [NotNullWhen(true)] out ILVariable? variable, out int constantValue, [NotNullWhen(true)] out Branch? branch)
{
variable = null;
constantValue = 0;
branch = null;
if (block.Instructions.Count != 2)
return false;
if (block.Instructions[0] is not StLoc {
Variable: { Kind: VariableKind.StackSlot } s,
Value: LdcI4 { Value: 0 or 1 } valueInst
})
{
return false;
}
if (block.Instructions[1] is not Branch br)
return false;
variable = s;
constantValue = valueInst.Value;
branch = br;
return true;
}
// Block IL_0019 (incoming: > 1) {
// if (logic.not(ldloc s)) br IL_0027
// br IL_001d
// }
bool MatchBlock2(Block block, ILVariable s, int constantValue, [NotNullWhen(true)] out ILInstruction? exitInst)
{
exitInst = null;
if (block.Instructions.Count != 2)
return false;
if (block.IncomingEdgeCount <= 1)
return false;
if (!block.MatchIfAtEndOfBlock(out var load, out var trueInst, out var falseInst))
return false;
if (!load.MatchLdLoc(s))
return false;
exitInst = constantValue != 0 ? trueInst : falseInst;
return exitInst is Branch or Leave { Value: Nop };
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/RemoveInfeasiblePathTransform.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/RemoveInfeasiblePathTransform.cs",
"repo_id": "ILSpy",
"token_count": 1327
} | 233 |
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Reflection.Metadata;
namespace ICSharpCode.Decompiler.Metadata
{
/// <summary>
/// Describes which parts of the (compiler-generated) code belong to which user code.
/// A part could be:
/// - the body (method) of a lambda.
/// - the MoveNext method of async/yield state machines.
/// </summary>
public class CodeMappingInfo
{
/// <summary>
/// The module containing the code.
/// </summary>
public PEFile Module { get; }
/// <summary>
/// The (parent) TypeDef containing the code.
/// </summary>
public TypeDefinitionHandle TypeDefinition { get; }
readonly Dictionary<MethodDefinitionHandle, List<MethodDefinitionHandle>> parts;
readonly Dictionary<MethodDefinitionHandle, MethodDefinitionHandle> parents;
/// <summary>
/// Creates a <see cref="CodeMappingInfo"/> instance using the given <paramref name="module"/> and <paramref name="type"/>.
/// </summary>
public CodeMappingInfo(PEFile module, TypeDefinitionHandle type)
{
this.Module = module;
this.TypeDefinition = type;
this.parts = new Dictionary<MethodDefinitionHandle, List<MethodDefinitionHandle>>();
this.parents = new Dictionary<MethodDefinitionHandle, MethodDefinitionHandle>();
}
/// <summary>
/// Returns all parts of a method.
/// A method has at least one part, that is, the method itself.
/// If no parts are found, only the method itself is returned.
/// </summary>
public IEnumerable<MethodDefinitionHandle> GetMethodParts(MethodDefinitionHandle method)
{
if (parts.TryGetValue(method, out var p))
return p;
return new[] { method };
}
/// <summary>
/// Returns the parent of a part.
/// The parent is usually the "calling method" of lambdas, async and yield state machines.
/// The "calling method" has itself as parent.
/// If no parent is found, the method itself is returned.
/// </summary>
public MethodDefinitionHandle GetParentMethod(MethodDefinitionHandle method)
{
if (parents.TryGetValue(method, out var p))
return p;
return method;
}
/// <summary>
/// Adds a bidirectional mapping between <paramref name="parent"/> and <paramref name="part"/>.
/// </summary>
public void AddMapping(MethodDefinitionHandle parent, MethodDefinitionHandle part)
{
//Debug.Print("Parent: " + MetadataTokens.GetRowNumber(parent) + " Part: " + MetadataTokens.GetRowNumber(part));
if (parents.ContainsKey(part))
return;
parents.Add(part, parent);
if (!parts.TryGetValue(parent, out var list))
{
list = new List<MethodDefinitionHandle>();
parts.Add(parent, list);
}
list.Add(part);
}
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/CodeMappingInfo.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/CodeMappingInfo.cs",
"repo_id": "ILSpy",
"token_count": 1128
} | 234 |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace LightJson.Serialization
{
/// <summary>
/// Represents a position within a plain text resource.
/// </summary>
internal struct TextPosition
{
/// <summary>
/// The column position, 0-based.
/// </summary>
public long Column;
/// <summary>
/// The line position, 0-based.
/// </summary>
public long Line;
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/TextPosition.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/LightJson/Serialization/TextPosition.cs",
"repo_id": "ILSpy",
"token_count": 160
} | 235 |
// Copyright (c) 2015 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler.Documentation;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler
{
public static class NRExtensions
{
public static bool IsCompilerGenerated(this IEntity entity)
{
if (entity != null)
{
return entity.HasAttribute(KnownAttribute.CompilerGenerated);
}
return false;
}
public static bool IsCompilerGeneratedOrIsInCompilerGeneratedClass(this IEntity entity)
{
if (entity == null)
return false;
if (entity.IsCompilerGenerated())
return true;
return IsCompilerGeneratedOrIsInCompilerGeneratedClass(entity.DeclaringTypeDefinition);
}
public static bool HasGeneratedName(this IMember member)
{
return member.Name.StartsWith("<", StringComparison.Ordinal);
}
public static bool HasGeneratedName(this IType type)
{
return type.Name.StartsWith("<", StringComparison.Ordinal) || type.Name.Contains("<");
}
public static bool IsAnonymousType(this IType type)
{
if (type == null)
return false;
if (string.IsNullOrEmpty(type.Namespace) && type.HasGeneratedName()
&& (type.Name.Contains("AnonType") || type.Name.Contains("AnonymousType")))
{
ITypeDefinition td = type.GetDefinition();
return td != null && td.IsCompilerGenerated();
}
return false;
}
public static bool ContainsAnonymousType(this IType type)
{
var visitor = new ContainsAnonTypeVisitor();
type.AcceptVisitor(visitor);
return visitor.ContainsAnonType;
}
class ContainsAnonTypeVisitor : TypeVisitor
{
public bool ContainsAnonType;
public override IType VisitOtherType(IType type)
{
if (IsAnonymousType(type))
ContainsAnonType = true;
return base.VisitOtherType(type);
}
public override IType VisitTypeDefinition(ITypeDefinition type)
{
if (IsAnonymousType(type))
ContainsAnonType = true;
return base.VisitTypeDefinition(type);
}
}
internal static string GetDocumentation(this IEntity entity)
{
var docProvider = XmlDocLoader.LoadDocumentation(entity.ParentModule.PEFile);
if (docProvider == null)
return null;
return docProvider.GetDocumentation(entity);
}
}
}
| ILSpy/ICSharpCode.Decompiler/NRExtensions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/NRExtensions.cs",
"repo_id": "ILSpy",
"token_count": 1087
} | 236 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
namespace ICSharpCode.Decompiler.TypeSystem
{
public sealed class ByReferenceType : TypeWithElementType
{
public ByReferenceType(IType elementType) : base(elementType)
{
}
public override TypeKind Kind {
get { return TypeKind.ByReference; }
}
public override string NameSuffix {
get {
return "&";
}
}
public override bool? IsReferenceType {
get { return null; }
}
public override bool IsByRefLike => true;
public override int GetHashCode()
{
return elementType.GetHashCode() ^ 91725813;
}
public override bool Equals(IType other)
{
ByReferenceType a = other as ByReferenceType;
return a != null && elementType.Equals(a.elementType);
}
public override IType AcceptVisitor(TypeVisitor visitor)
{
return visitor.VisitByReferenceType(this);
}
public override IType VisitChildren(TypeVisitor visitor)
{
IType e = elementType.AcceptVisitor(visitor);
if (e == elementType)
return this;
else
return new ByReferenceType(e);
}
}
[Serializable]
public sealed class ByReferenceTypeReference : ITypeReference, ISupportsInterning
{
readonly ITypeReference elementType;
public ByReferenceTypeReference(ITypeReference elementType)
{
if (elementType == null)
throw new ArgumentNullException(nameof(elementType));
this.elementType = elementType;
}
public ITypeReference ElementType {
get { return elementType; }
}
public IType Resolve(ITypeResolveContext context)
{
return new ByReferenceType(elementType.Resolve(context));
}
public override string ToString()
{
return elementType.ToString() + "&";
}
int ISupportsInterning.GetHashCodeForInterning()
{
return elementType.GetHashCode() ^ 91725814;
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
ByReferenceTypeReference brt = other as ByReferenceTypeReference;
return brt != null && this.elementType == brt.elementType;
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/ByReferenceType.cs",
"repo_id": "ILSpy",
"token_count": 1004
} | 237 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.TypeSystem
{
public interface IMemberReference
{
/// <summary>
/// Gets the declaring type reference for the member.
/// </summary>
ITypeReference DeclaringTypeReference { get; }
/// <summary>
/// Resolves the member.
/// </summary>
/// <param name="context">
/// Context to use for resolving this member reference.
/// Which kind of context is required depends on the which kind of member reference this is;
/// please consult the documentation of the method that was used to create this member reference,
/// or that of the class implementing this method.
/// </param>
/// <returns>
/// Returns the resolved member, or <c>null</c> if the member could not be found.
/// </returns>
IMember? Resolve(ITypeResolveContext context);
}
/// <summary>
/// Method/field/property/event.
/// </summary>
public interface IMember : IEntity
{
/// <summary>
/// Gets the original member definition for this member.
/// Returns <c>this</c> if this is not a specialized member.
/// Specialized members are the result of overload resolution with type substitution.
/// </summary>
IMember MemberDefinition { get; }
/// <summary>
/// Gets the return type of this member.
/// This property never returns <c>null</c>.
/// </summary>
IType ReturnType { get; }
/// <summary>
/// Gets/Sets the declaring type (incl. type arguments, if any).
/// If this is not a specialized member, the value returned is equal to <see cref="IEntity.DeclaringTypeDefinition"/>.
/// </summary>
new IType DeclaringType { get; }
/// <summary>
/// Gets the interface members explicitly implemented by this member.
/// </summary>
/// <remarks>
/// For methods, equivalent to (
/// from impl in DeclaringTypeDefinition.GetExplicitInterfaceImplementations()
/// where impl.Implementation == this
/// select impl.InterfaceMethod
/// ),
/// but may be more efficient than searching the whole list.
///
/// Note that it is possible for a class to implement an interface using members in a
/// base class unrelated to that interface:
/// class BaseClass { public void Dispose() {} }
/// class C : BaseClass, IDisposable { }
/// In this case, the interface member will not show up in (BaseClass.Dispose).ImplementedInterfaceMembers,
/// so use (C).GetInterfaceImplementations() instead to handle this case.
/// </remarks>
IEnumerable<IMember> ExplicitlyImplementedInterfaceMembers { get; }
/// <summary>
/// Gets whether this member is explicitly implementing an interface.
/// </summary>
bool IsExplicitInterfaceImplementation { get; }
/// <summary>
/// Gets if the member is virtual. Is true only if the "virtual" modifier was used, but non-virtual
/// members can be overridden, too; if they are abstract or overriding a method.
/// </summary>
bool IsVirtual { get; }
/// <summary>
/// Gets whether this member is overriding another member.
/// </summary>
bool IsOverride { get; }
/// <summary>
/// Gets if the member can be overridden. Returns true when the member is "abstract", "virtual" or "override" but not "sealed".
/// </summary>
bool IsOverridable { get; }
/// <summary>
/// Gets the substitution belonging to this specialized member.
/// Returns TypeParameterSubstitution.Identity for not specialized members.
/// </summary>
TypeParameterSubstitution Substitution {
get;
}
/// <summary>
/// Specializes this member with the given substitution.
/// If this member is already specialized, the new substitution is composed with the existing substition.
/// </summary>
IMember Specialize(TypeParameterSubstitution substitution);
/// <summary>
/// Gets whether the members are considered equal when applying the specified type normalization.
/// </summary>
bool Equals(IMember? obj, TypeVisitor typeNormalization);
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/IMember.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/IMember.cs",
"repo_id": "ILSpy",
"token_count": 1449
} | 238 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// Default implementation for IType interface.
/// </summary>
[Serializable]
public abstract class AbstractType : IType
{
public virtual string FullName {
get {
string ns = this.Namespace;
string name = this.Name;
if (string.IsNullOrEmpty(ns))
{
return name;
}
else
{
return ns + "." + name;
}
}
}
public abstract string Name { get; }
public virtual string Namespace {
get { return string.Empty; }
}
public virtual string ReflectionName {
get { return this.FullName; }
}
public abstract bool? IsReferenceType { get; }
public virtual bool IsByRefLike => false;
public virtual Nullability Nullability => Nullability.Oblivious;
public virtual IType ChangeNullability(Nullability nullability)
{
// Only some types support nullability, in the default implementation
// we just ignore the nullability change.
return this;
}
public abstract TypeKind Kind { get; }
public virtual int TypeParameterCount {
get { return 0; }
}
public virtual IReadOnlyList<ITypeParameter> TypeParameters {
get { return EmptyList<ITypeParameter>.Instance; }
}
public virtual IReadOnlyList<IType> TypeArguments {
get { return EmptyList<IType>.Instance; }
}
public virtual IType DeclaringType {
get { return null; }
}
public virtual ITypeDefinition GetDefinition()
{
return null;
}
public virtual ITypeDefinitionOrUnknown GetDefinitionOrUnknown()
{
return null;
}
public virtual IEnumerable<IType> DirectBaseTypes {
get { return EmptyList<IType>.Instance; }
}
public virtual IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IType>.Instance;
}
public virtual IEnumerable<IType> GetNestedTypes(IReadOnlyList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IType>.Instance;
}
public virtual IEnumerable<IMethod> GetMethods(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IMethod>.Instance;
}
public virtual IEnumerable<IMethod> GetMethods(IReadOnlyList<IType> typeArguments, Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IMethod>.Instance;
}
public virtual IEnumerable<IMethod> GetConstructors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
{
return EmptyList<IMethod>.Instance;
}
public virtual IEnumerable<IProperty> GetProperties(Predicate<IProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IProperty>.Instance;
}
public virtual IEnumerable<IField> GetFields(Predicate<IField> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IField>.Instance;
}
public virtual IEnumerable<IEvent> GetEvents(Predicate<IEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IEvent>.Instance;
}
public virtual IEnumerable<IMember> GetMembers(Predicate<IMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
IEnumerable<IMember> members = GetMethods(filter, options);
return members
.Concat(GetProperties(filter, options))
.Concat(GetFields(filter, options))
.Concat(GetEvents(filter, options));
}
public virtual IEnumerable<IMethod> GetAccessors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return EmptyList<IMethod>.Instance;
}
public TypeParameterSubstitution GetSubstitution()
{
return TypeParameterSubstitution.Identity;
}
public TypeParameterSubstitution GetSubstitution(IReadOnlyList<IType> methodTypeArguments)
{
return TypeParameterSubstitution.Identity;
}
public override sealed bool Equals(object obj)
{
return Equals(obj as IType);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public virtual bool Equals(IType other)
{
return this == other; // use reference equality by default
}
public override string ToString()
{
return this.ReflectionName;
}
public virtual IType AcceptVisitor(TypeVisitor visitor)
{
return visitor.VisitOtherType(this);
}
public virtual IType VisitChildren(TypeVisitor visitor)
{
return this;
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/AbstractType.cs",
"repo_id": "ILSpy",
"token_count": 1878
} | 239 |
// Copyright (c) 2010-2018 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ICSharpCode.Decompiler.TypeSystem
{
public enum KnownAttribute
{
/// <summary>
/// Not a known attribute
/// </summary>
None,
CompilerGenerated,
CompilerFeatureRequired,
/// <summary>
/// Marks a method as extension method; or a class as containing extension methods.
/// </summary>
Extension,
Dynamic,
TupleElementNames,
Nullable,
NullableContext,
NullablePublicOnly,
Conditional,
Obsolete,
Embedded,
IsReadOnly,
SpecialName,
DebuggerHidden,
DebuggerStepThrough,
DebuggerBrowsable,
// Assembly attributes:
AssemblyVersion,
InternalsVisibleTo,
TypeForwardedTo,
ReferenceAssembly,
// Type attributes:
Serializable,
Flags,
ComImport,
CoClass,
StructLayout,
DefaultMember,
IsByRefLike,
IteratorStateMachine,
AsyncStateMachine,
AsyncMethodBuilder,
AsyncIteratorStateMachine,
// Field attributes:
FieldOffset,
NonSerialized,
DecimalConstant,
FixedBuffer,
// Method attributes:
DllImport,
PreserveSig,
MethodImpl,
// Property attributes:
IndexerName,
// Parameter attributes:
ParamArray,
In,
Out,
Optional,
DefaultParameterValue,
CallerMemberName,
CallerFilePath,
CallerLineNumber,
ScopedRef,
// Type parameter attributes:
IsUnmanaged,
// Marshalling attributes:
MarshalAs,
// Security attributes:
PermissionSet,
// C# 9 attributes:
NativeInteger,
PreserveBaseOverrides,
// C# 11 attributes:
RequiredAttribute,
}
public static class KnownAttributes
{
internal const int Count = (int)KnownAttribute.RequiredAttribute + 1;
static readonly TopLevelTypeName[] typeNames = new TopLevelTypeName[Count]{
default,
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(CompilerGeneratedAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", "CompilerFeatureRequiredAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(ExtensionAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(DynamicAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(TupleElementNamesAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", "NullableAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", "NullableContextAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", "NullablePublicOnlyAttribute"),
new TopLevelTypeName("System.Diagnostics", nameof(ConditionalAttribute)),
new TopLevelTypeName("System", nameof(ObsoleteAttribute)),
new TopLevelTypeName("Microsoft.CodeAnalysis", "EmbeddedAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", "IsReadOnlyAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(SpecialNameAttribute)),
new TopLevelTypeName("System.Diagnostics", nameof(DebuggerHiddenAttribute)),
new TopLevelTypeName("System.Diagnostics", nameof(DebuggerStepThroughAttribute)),
new TopLevelTypeName("System.Diagnostics", nameof(DebuggerBrowsableAttribute)),
// Assembly attributes:
new TopLevelTypeName("System.Reflection", nameof(AssemblyVersionAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(InternalsVisibleToAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(TypeForwardedToAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(ReferenceAssemblyAttribute)),
// Type attributes:
new TopLevelTypeName("System", nameof(SerializableAttribute)),
new TopLevelTypeName("System", nameof(FlagsAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(ComImportAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(CoClassAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(StructLayoutAttribute)),
new TopLevelTypeName("System.Reflection", nameof(DefaultMemberAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", "IsByRefLikeAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(IteratorStateMachineAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(AsyncStateMachineAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", "AsyncMethodBuilderAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute"),
// Field attributes:
new TopLevelTypeName("System.Runtime.InteropServices", nameof(FieldOffsetAttribute)),
new TopLevelTypeName("System", nameof(NonSerializedAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(DecimalConstantAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(FixedBufferAttribute)),
// Method attributes:
new TopLevelTypeName("System.Runtime.InteropServices", nameof(DllImportAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(PreserveSigAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(MethodImplAttribute)),
// Property attributes:
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(IndexerNameAttribute)),
// Parameter attributes:
new TopLevelTypeName("System", nameof(ParamArrayAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(InAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(OutAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(OptionalAttribute)),
new TopLevelTypeName("System.Runtime.InteropServices", nameof(DefaultParameterValueAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(CallerMemberNameAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(CallerFilePathAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", nameof(CallerLineNumberAttribute)),
new TopLevelTypeName("System.Runtime.CompilerServices", "ScopedRefAttribute"),
// Type parameter attributes:
new TopLevelTypeName("System.Runtime.CompilerServices", "IsUnmanagedAttribute"),
// Marshalling attributes:
new TopLevelTypeName("System.Runtime.InteropServices", nameof(MarshalAsAttribute)),
// Security attributes:
new TopLevelTypeName("System.Security.Permissions", "PermissionSetAttribute"),
// C# 9 attributes:
new TopLevelTypeName("System.Runtime.CompilerServices", "NativeIntegerAttribute"),
new TopLevelTypeName("System.Runtime.CompilerServices", "PreserveBaseOverridesAttribute"),
// C# 11 attributes:
new TopLevelTypeName("System.Runtime.CompilerServices", "RequiredMemberAttribute"),
};
public static ref readonly TopLevelTypeName GetTypeName(this KnownAttribute attr)
{
Debug.Assert(attr != KnownAttribute.None);
return ref typeNames[(int)attr];
}
public static IType FindType(this ICompilation compilation, KnownAttribute attrType)
{
return compilation.FindType(attrType.GetTypeName());
}
public static KnownAttribute IsKnownAttributeType(this ITypeDefinition attributeType)
{
if (!attributeType.GetNonInterfaceBaseTypes().Any(t => t.IsKnownType(KnownTypeCode.Attribute)))
return KnownAttribute.None;
for (int i = 1; i < typeNames.Length; i++)
{
if (typeNames[i] == attributeType.FullTypeName)
return (KnownAttribute)i;
}
return KnownAttribute.None;
}
public static bool IsCustomAttribute(this KnownAttribute knownAttribute)
{
switch (knownAttribute)
{
case KnownAttribute.Serializable:
case KnownAttribute.ComImport:
case KnownAttribute.StructLayout:
case KnownAttribute.DllImport:
case KnownAttribute.PreserveSig:
case KnownAttribute.MethodImpl:
case KnownAttribute.FieldOffset:
case KnownAttribute.NonSerialized:
case KnownAttribute.MarshalAs:
case KnownAttribute.PermissionSet:
case KnownAttribute.Optional:
case KnownAttribute.DefaultParameterValue:
case KnownAttribute.In:
case KnownAttribute.Out:
case KnownAttribute.IndexerName:
case KnownAttribute.SpecialName:
return false;
default:
return true;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/KnownAttributes.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/KnownAttributes.cs",
"repo_id": "ILSpy",
"token_count": 2868
} | 240 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// Simple compilation implementation.
/// </summary>
public class SimpleCompilation : ICompilation
{
readonly CacheManager cacheManager = new CacheManager();
IModule mainModule;
KnownTypeCache knownTypeCache;
IReadOnlyList<IModule> assemblies;
IReadOnlyList<IModule> referencedAssemblies;
bool initialized;
INamespace rootNamespace;
public SimpleCompilation(IModuleReference mainAssembly, params IModuleReference[] assemblyReferences)
{
Init(mainAssembly, assemblyReferences);
}
public SimpleCompilation(IModuleReference mainAssembly, IEnumerable<IModuleReference> assemblyReferences)
{
Init(mainAssembly, assemblyReferences);
}
protected SimpleCompilation()
{
}
protected void Init(IModuleReference mainAssembly, IEnumerable<IModuleReference> assemblyReferences)
{
if (mainAssembly == null)
throw new ArgumentNullException(nameof(mainAssembly));
if (assemblyReferences == null)
throw new ArgumentNullException(nameof(assemblyReferences));
var context = new SimpleTypeResolveContext(this);
this.mainModule = mainAssembly.Resolve(context);
List<IModule> assemblies = new List<IModule>();
assemblies.Add(this.mainModule);
List<IModule> referencedAssemblies = new List<IModule>();
foreach (var asmRef in assemblyReferences)
{
IModule asm;
try
{
asm = asmRef.Resolve(context);
}
catch (InvalidOperationException)
{
throw new InvalidOperationException("Tried to initialize compilation with an invalid assembly reference. (Forgot to load the assembly reference ? - see CecilLoader)");
}
if (asm != null && !assemblies.Contains(asm))
assemblies.Add(asm);
if (asm != null && !referencedAssemblies.Contains(asm))
referencedAssemblies.Add(asm);
}
this.assemblies = assemblies.AsReadOnly();
this.referencedAssemblies = referencedAssemblies.AsReadOnly();
this.knownTypeCache = new KnownTypeCache(this);
this.initialized = true;
}
public IModule MainModule {
get {
if (!initialized)
throw new InvalidOperationException("Compilation isn't initialized yet");
return mainModule;
}
}
public IReadOnlyList<IModule> Modules {
get {
if (!initialized)
throw new InvalidOperationException("Compilation isn't initialized yet");
return assemblies;
}
}
public IReadOnlyList<IModule> ReferencedModules {
get {
if (!initialized)
throw new InvalidOperationException("Compilation isn't initialized yet");
return referencedAssemblies;
}
}
public INamespace RootNamespace {
get {
INamespace ns = LazyInit.VolatileRead(ref this.rootNamespace);
if (ns != null)
{
return ns;
}
else
{
if (!initialized)
throw new InvalidOperationException("Compilation isn't initialized yet");
return LazyInit.GetOrSet(ref this.rootNamespace, CreateRootNamespace());
}
}
}
protected virtual INamespace CreateRootNamespace()
{
// SimpleCompilation does not support extern aliases; but derived classes might.
// CreateRootNamespace() is virtual so that derived classes can change the global namespace.
INamespace[] namespaces = new INamespace[referencedAssemblies.Count + 1];
namespaces[0] = mainModule.RootNamespace;
for (int i = 0; i < referencedAssemblies.Count; i++)
{
namespaces[i + 1] = referencedAssemblies[i].RootNamespace;
}
return new MergedNamespace(this, namespaces);
}
public CacheManager CacheManager {
get { return cacheManager; }
}
public virtual INamespace GetNamespaceForExternAlias(string alias)
{
if (string.IsNullOrEmpty(alias))
return this.RootNamespace;
// SimpleCompilation does not support extern aliases; but derived classes might.
return null;
}
public IType FindType(KnownTypeCode typeCode)
{
return knownTypeCache.FindType(typeCode);
}
public StringComparer NameComparer {
get { return StringComparer.Ordinal; }
}
public override string ToString()
{
return "[" + GetType().Name + " " + mainModule.AssemblyName + "]";
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SimpleCompilation.cs",
"repo_id": "ILSpy",
"token_count": 1767
} | 241 |
// Copyright (c) 2018 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// Represents a modopt or modreq type.
/// </summary>
public class ModifiedType : TypeWithElementType, IType
{
readonly TypeKind kind;
readonly IType modifier;
public ModifiedType(IType modifier, IType unmodifiedType, bool isRequired) : base(unmodifiedType)
{
this.kind = isRequired ? TypeKind.ModReq : TypeKind.ModOpt;
this.modifier = modifier ?? throw new ArgumentNullException(nameof(modifier));
}
public IType Modifier => modifier;
public override TypeKind Kind => kind;
public override string NameSuffix => (kind == TypeKind.ModReq ? " modreq" : " modopt") + $"({modifier.FullName})";
public override bool? IsReferenceType => elementType.IsReferenceType;
public override bool IsByRefLike => elementType.IsByRefLike;
public override Nullability Nullability => elementType.Nullability;
public override IType ChangeNullability(Nullability nullability)
{
IType newElementType = elementType.ChangeNullability(nullability);
if (newElementType == elementType)
return this;
else
return new ModifiedType(modifier, newElementType, kind == TypeKind.ModReq);
}
public override ITypeDefinition GetDefinition()
{
return elementType.GetDefinition();
}
public override ITypeDefinitionOrUnknown GetDefinitionOrUnknown()
{
return elementType.GetDefinitionOrUnknown();
}
public override IEnumerable<IMethod> GetAccessors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetAccessors(filter, options);
}
public override IEnumerable<IMethod> GetConstructors(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
{
return elementType.GetConstructors(filter, options);
}
public override IEnumerable<IEvent> GetEvents(Predicate<IEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetEvents(filter, options);
}
public override IEnumerable<IField> GetFields(Predicate<IField> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetFields(filter, options);
}
public override IEnumerable<IMember> GetMembers(Predicate<IMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetMembers(filter, options);
}
public override IEnumerable<IMethod> GetMethods(IReadOnlyList<IType> typeArguments, Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetMethods(typeArguments, filter, options);
}
public override IEnumerable<IMethod> GetMethods(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetMethods(filter, options);
}
public override IEnumerable<IType> GetNestedTypes(IReadOnlyList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetNestedTypes(typeArguments, filter, options);
}
public override IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetNestedTypes(filter, options);
}
public override IEnumerable<IProperty> GetProperties(Predicate<IProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return elementType.GetProperties(filter, options);
}
public override IType VisitChildren(TypeVisitor visitor)
{
var newElementType = elementType.AcceptVisitor(visitor);
var newModifier = modifier.AcceptVisitor(visitor);
if (newModifier != modifier || newElementType != elementType)
{
return new ModifiedType(newModifier, newElementType, kind == TypeKind.ModReq);
}
return this;
}
public override IType AcceptVisitor(TypeVisitor visitor)
{
if (kind == TypeKind.ModReq)
return visitor.VisitModReq(this);
else
return visitor.VisitModOpt(this);
}
public override bool Equals(IType other)
{
return other is ModifiedType o && kind == o.kind && modifier.Equals(o.modifier) && elementType.Equals(o.elementType);
}
public override int GetHashCode()
{
unchecked
{
return (int)kind ^ (elementType.GetHashCode() * 1344795899) ^ (modifier.GetHashCode() * 901375117);
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/ModifiedType.cs",
"repo_id": "ILSpy",
"token_count": 1734
} | 242 |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Text;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Substitutes class and method type parameters.
/// </summary>
public class TypeParameterSubstitution : TypeVisitor
{
/// <summary>
/// The identity function.
/// </summary>
public static readonly TypeParameterSubstitution Identity = new TypeParameterSubstitution(null, null);
readonly IReadOnlyList<IType> classTypeArguments;
readonly IReadOnlyList<IType> methodTypeArguments;
/// <summary>
/// Creates a new type parameter substitution.
/// </summary>
/// <param name="classTypeArguments">
/// The type arguments to substitute for class type parameters.
/// Pass <c>null</c> to keep class type parameters unmodified.
/// </param>
/// <param name="methodTypeArguments">
/// The type arguments to substitute for method type parameters.
/// Pass <c>null</c> to keep method type parameters unmodified.
/// </param>
public TypeParameterSubstitution(IReadOnlyList<IType> classTypeArguments, IReadOnlyList<IType> methodTypeArguments)
{
this.classTypeArguments = classTypeArguments;
this.methodTypeArguments = methodTypeArguments;
}
/// <summary>
/// Gets the list of class type arguments.
/// Returns <c>null</c> if this substitution keeps class type parameters unmodified.
/// </summary>
public IReadOnlyList<IType> ClassTypeArguments {
get { return classTypeArguments; }
}
/// <summary>
/// Gets the list of method type arguments.
/// Returns <c>null</c> if this substitution keeps method type parameters unmodified.
/// </summary>
public IReadOnlyList<IType> MethodTypeArguments {
get { return methodTypeArguments; }
}
#region Compose
/// <summary>
/// Computes a single TypeParameterSubstitution so that for all types <c>t</c>:
/// <c>t.AcceptVisitor(Compose(g, f)) equals t.AcceptVisitor(f).AcceptVisitor(g)</c>
/// </summary>
/// <remarks>If you consider type parameter substitution to be a function, this is function composition.</remarks>
public static TypeParameterSubstitution Compose(TypeParameterSubstitution g, TypeParameterSubstitution f)
{
if (g == null)
return f;
if (f == null || (f.classTypeArguments == null && f.methodTypeArguments == null))
return g;
// The composition is a copy of 'f', with 'g' applied on the array elements.
// If 'f' has a null list (keeps type parameters unmodified), we have to treat it as
// the identity function, and thus use the list from 'g'.
var classTypeArguments = f.classTypeArguments != null ? GetComposedTypeArguments(f.classTypeArguments, g) : g.classTypeArguments;
var methodTypeArguments = f.methodTypeArguments != null ? GetComposedTypeArguments(f.methodTypeArguments, g) : g.methodTypeArguments;
return new TypeParameterSubstitution(classTypeArguments, methodTypeArguments);
}
static IReadOnlyList<IType> GetComposedTypeArguments(IReadOnlyList<IType> input, TypeParameterSubstitution substitution)
{
IType[] result = new IType[input.Count];
for (int i = 0; i < result.Length; i++)
{
result[i] = input[i].AcceptVisitor(substitution);
}
return result;
}
#endregion
#region Equals and GetHashCode implementation
public bool Equals(TypeParameterSubstitution other, TypeVisitor normalization)
{
if (other == null)
return false;
return TypeListEquals(classTypeArguments, other.classTypeArguments, normalization)
&& TypeListEquals(methodTypeArguments, other.methodTypeArguments, normalization);
}
public override bool Equals(object obj)
{
TypeParameterSubstitution other = obj as TypeParameterSubstitution;
if (other == null)
return false;
return TypeListEquals(classTypeArguments, other.classTypeArguments)
&& TypeListEquals(methodTypeArguments, other.methodTypeArguments);
}
public override int GetHashCode()
{
unchecked
{
return 1124131 * TypeListHashCode(classTypeArguments) + 1821779 * TypeListHashCode(methodTypeArguments);
}
}
static bool TypeListEquals(IReadOnlyList<IType> a, IReadOnlyList<IType> b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
{
if (!a[i].Equals(b[i]))
return false;
}
return true;
}
static bool TypeListEquals(IReadOnlyList<IType> a, IReadOnlyList<IType> b, TypeVisitor normalization)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
{
var an = a[i].AcceptVisitor(normalization);
var bn = b[i].AcceptVisitor(normalization);
if (!an.Equals(bn))
return false;
}
return true;
}
static int TypeListHashCode(IReadOnlyList<IType> obj)
{
if (obj == null)
return 0;
unchecked
{
int hashCode = 1;
foreach (var element in obj)
{
hashCode *= 27;
hashCode += element.GetHashCode();
}
return hashCode;
}
}
#endregion
public override IType VisitTypeParameter(ITypeParameter type)
{
int index = type.Index;
if (classTypeArguments != null && type.OwnerType == SymbolKind.TypeDefinition)
{
if (index >= 0 && index < classTypeArguments.Count)
return classTypeArguments[index];
else
return SpecialType.UnknownType;
}
else if (methodTypeArguments != null && type.OwnerType == SymbolKind.Method)
{
if (index >= 0 && index < methodTypeArguments.Count)
return methodTypeArguments[index];
else
return SpecialType.UnknownType;
}
else
{
return base.VisitTypeParameter(type);
}
}
public override IType VisitNullabilityAnnotatedType(NullabilityAnnotatedType type)
{
if (type is NullabilityAnnotatedTypeParameter tp)
{
if (tp.Nullability == Nullability.Nullable)
{
return VisitTypeParameter(tp).ChangeNullability(Nullability.Nullable);
}
else
{
// T! substituted with T=oblivious string should result in oblivious string
return VisitTypeParameter(tp);
}
}
else
{
return base.VisitNullabilityAnnotatedType(type);
}
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append('[');
bool first = true;
if (classTypeArguments != null)
{
for (int i = 0; i < classTypeArguments.Count; i++)
{
if (first)
first = false;
else
b.Append(", ");
b.Append('`');
b.Append(i);
b.Append(" -> ");
b.Append(classTypeArguments[i].ReflectionName);
}
if (classTypeArguments.Count == 0)
{
if (first)
first = false;
else
b.Append(", ");
b.Append("[]");
}
}
if (methodTypeArguments != null)
{
for (int i = 0; i < methodTypeArguments.Count; i++)
{
if (first)
first = false;
else
b.Append(", ");
b.Append("``");
b.Append(i);
b.Append(" -> ");
b.Append(methodTypeArguments[i].ReflectionName);
}
if (methodTypeArguments.Count == 0)
{
if (first)
first = false;
else
b.Append(", ");
b.Append("[]");
}
}
b.Append(']');
return b.ToString();
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeParameterSubstitution.cs",
"repo_id": "ILSpy",
"token_count": 3133
} | 243 |
// Copyright (c) 2023 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System;
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.Util;
static class GraphTraversal
{
/// <summary>
/// Depth-first-search of an graph data structure.
/// The two callbacks (successorFunc + postorderAction) will be called exactly once for each node reachable from startNodes.
/// </summary>
/// <param name="startNodes">The start nodes.</param>
/// <param name="visitedFunc">Called multiple times per node. The first call should return true, subsequent calls must return false.
/// The first calls to this function occur in pre-order.
/// If null, normal Equals/GetHashCode will be used to compare nodes.</param>
/// <param name="successorFunc">The function that gets the successors of an element. Called in pre-order.</param>
/// <param name="postorderAction">Called in post-order.</param>
/// <param name="reverseSuccessors">
/// With reverse_successors=True, the start_nodes and each list of successors will be handled in reverse order.
/// This is useful if the post-order will be reversed later (e.g. for a topological sort)
/// so that blocks which could be output in either order (e.g. then-block and else-block of an if)
/// will maintain the order of the edges (then-block before else-block).
/// </param>
public static void DepthFirstSearch<T>(IEnumerable<T> startNodes, Func<T, bool>? visitedFunc, Func<T, IEnumerable<T>?> successorFunc, Action<T>? postorderAction = null, bool reverseSuccessors = false)
{
/*
Pseudocode:
def dfs_walk(start_nodes, successor_func, visited, postorder_func, reverse_successors):
if reverse_successors:
start_nodes = reversed(start_nodes)
for node in start_nodes:
if node in visited: continue
visited.insert(node)
children = successor_func(node)
dfs_walk(children, successor_func, visited, postorder_action, reverse_successors)
postorder_action(node)
The actual implementation here is equivalent but does not use recursion,
so that we don't blow the stack on large graphs.
A single stack holds the "continuations" of work that needs to be done.
These can be either "visit continuations" (=execute the body of the pseudocode
loop for the given node) or "postorder continuations" (=execute postorder_action)
*/
// Use a List as stack (but allowing for the Reverse() usage)
var worklist = new List<(T node, bool isPostOrderContinuation)>();
visitedFunc ??= new HashSet<T>().Add;
foreach (T node in startNodes)
{
worklist.Add((node, false));
}
if (!reverseSuccessors)
{
// Our use of a stack will reverse the order of the nodes.
// If that's not desired, restore original order by reversing twice.
worklist.Reverse();
}
// Process outstanding continuations:
while (worklist.Count > 0)
{
var (node, isPostOrderContinuation) = worklist.Last();
if (isPostOrderContinuation)
{
// Execute postorder_action
postorderAction?.Invoke(node);
worklist.RemoveAt(worklist.Count - 1);
continue;
}
// Execute body of loop
if (!visitedFunc(node))
{
// Already visited
worklist.RemoveAt(worklist.Count - 1);
continue;
}
// foreach-loop-iteration will end with postorder_func call,
// so switch the type of continuation for this node
int oldWorkListSize = worklist.Count;
worklist[oldWorkListSize - 1] = (node, true);
// Create "visit continuations" for all successor nodes:
IEnumerable<T>? children = successorFunc(node);
if (children != null)
{
foreach (T child in children)
{
worklist.Add((child, false));
}
}
// Our use of a stack will reverse the order of the nodes.
// If that's not desired, restore original order by reversing twice.
if (!reverseSuccessors)
{
worklist.Reverse(oldWorkListSize, worklist.Count - oldWorkListSize);
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/Util/GraphTraversal.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Util/GraphTraversal.cs",
"repo_id": "ILSpy",
"token_count": 1735
} | 244 |
// Copyright (c) 2014 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.Util
{
/// <summary>
/// Union-Find data structure.
/// </summary>
public class UnionFind<T> where T : notnull
{
Dictionary<T, Node> mapping;
class Node
{
public int rank;
public Node parent;
public T value;
internal Node(T value)
{
this.value = value;
this.parent = this;
}
}
public UnionFind()
{
mapping = new Dictionary<T, Node>();
}
Node GetNode(T element)
{
if (!mapping.TryGetValue(element, out Node? node))
{
node = new Node(element);
node.parent = node;
mapping.Add(element, node);
}
return node;
}
public T Find(T element)
{
return FindRoot(GetNode(element)).value;
}
Node FindRoot(Node node)
{
if (node.parent != node)
node.parent = FindRoot(node.parent);
return node.parent;
}
public void Merge(T a, T b)
{
var rootA = FindRoot(GetNode(a));
var rootB = FindRoot(GetNode(b));
if (rootA == rootB)
return;
if (rootA.rank < rootB.rank)
rootA.parent = rootB;
else if (rootA.rank > rootB.rank)
rootB.parent = rootA;
else
{
rootB.parent = rootA;
rootA.rank++;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/Util/UnionFind.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Util/UnionFind.cs",
"repo_id": "ILSpy",
"token_count": 829
} | 245 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Util;
using ICSharpCode.ILSpyX.Extensions;
namespace ICSharpCode.ILSpyX
{
class AssemblyListSnapshot
{
readonly ImmutableArray<LoadedAssembly> assemblies;
Dictionary<string, PEFile>? asmLookupByFullName;
Dictionary<string, PEFile>? asmLookupByShortName;
Dictionary<string, List<(PEFile module, Version version)>>? asmLookupByShortNameGrouped;
public ImmutableArray<LoadedAssembly> Assemblies => assemblies;
public AssemblyListSnapshot(ImmutableArray<LoadedAssembly> assemblies)
{
this.assemblies = assemblies;
}
public async Task<PEFile?> TryGetModuleAsync(IAssemblyReference reference, string tfm)
{
bool isWinRT = reference.IsWindowsRuntime;
if (tfm.StartsWith(".NETFramework,Version=v4.", StringComparison.Ordinal))
{
tfm = ".NETFramework,Version=v4";
}
string key = tfm + ";" + (isWinRT ? reference.Name : reference.FullName);
var lookup = LazyInit.VolatileRead(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName);
if (lookup == null)
{
lookup = await CreateLoadedAssemblyLookupAsync(shortNames: isWinRT).ConfigureAwait(false);
lookup = LazyInit.GetOrSet(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName, lookup);
}
if (lookup.TryGetValue(key, out PEFile? module))
return module;
return null;
}
public async Task<PEFile?> TryGetSimilarModuleAsync(IAssemblyReference reference)
{
var lookup = LazyInit.VolatileRead(ref asmLookupByShortNameGrouped);
if (lookup == null)
{
lookup = await CreateLoadedAssemblyShortNameGroupLookupAsync().ConfigureAwait(false);
lookup = LazyInit.GetOrSet(ref asmLookupByShortNameGrouped, lookup);
}
if (!lookup.TryGetValue(reference.Name, out var candidates))
return null;
return candidates.FirstOrDefault(c => c.version >= reference.Version).module ?? candidates.Last().module;
}
private async Task<Dictionary<string, PEFile>> CreateLoadedAssemblyLookupAsync(bool shortNames)
{
var result = new Dictionary<string, PEFile>(StringComparer.OrdinalIgnoreCase);
foreach (LoadedAssembly loaded in assemblies)
{
try
{
var module = await loaded.GetPEFileOrNullAsync().ConfigureAwait(false);
if (module == null)
continue;
var reader = module.Metadata;
if (reader == null || !reader.IsAssembly)
continue;
string tfm = await loaded.GetTargetFrameworkIdAsync().ConfigureAwait(false);
if (tfm.StartsWith(".NETFramework,Version=v4.", StringComparison.Ordinal))
{
tfm = ".NETFramework,Version=v4";
}
string key = tfm + ";"
+ (shortNames ? module.Name : module.FullName);
if (!result.ContainsKey(key))
{
result.Add(key, module);
}
}
catch (BadImageFormatException)
{
continue;
}
}
return result;
}
private async Task<Dictionary<string, List<(PEFile module, Version version)>>> CreateLoadedAssemblyShortNameGroupLookupAsync()
{
var result = new Dictionary<string, List<(PEFile module, Version version)>>(StringComparer.OrdinalIgnoreCase);
foreach (LoadedAssembly loaded in assemblies)
{
try
{
var module = await loaded.GetPEFileOrNullAsync().ConfigureAwait(false);
var reader = module?.Metadata;
if (reader == null || !reader.IsAssembly)
continue;
var asmDef = reader.GetAssemblyDefinition();
var asmDefName = reader.GetString(asmDef.Name);
var line = (module!, version: asmDef.Version);
if (!result.TryGetValue(asmDefName, out var existing))
{
existing = new List<(PEFile module, Version version)>();
result.Add(asmDefName, existing);
existing.Add(line);
continue;
}
int index = existing.BinarySearch(line.version, l => l.version);
index = index < 0 ? ~index : index + 1;
existing.Insert(index, line);
}
catch (BadImageFormatException)
{
continue;
}
}
return result;
}
/// <summary>
/// Gets all loaded assemblies recursively, including assemblies found in bundles or packages.
/// </summary>
public async Task<IList<LoadedAssembly>> GetAllAssembliesAsync()
{
var results = new List<LoadedAssembly>(assemblies.Length);
foreach (var asm in assemblies)
{
LoadedAssembly.LoadResult result;
try
{
result = await asm.GetLoadResultAsync().ConfigureAwait(false);
}
catch
{
results.Add(asm);
continue;
}
if (result.Package != null)
{
AddDescendants(result.Package.RootFolder);
}
else if (result.PEFile != null)
{
results.Add(asm);
}
}
void AddDescendants(PackageFolder folder)
{
foreach (var subFolder in folder.Folders)
{
AddDescendants(subFolder);
}
foreach (var entry in folder.Entries)
{
if (!entry.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
continue;
var asm = folder.ResolveFileName(entry.Name);
if (asm == null)
continue;
results.Add(asm);
}
}
return results;
}
}
}
| ILSpy/ICSharpCode.ILSpyX/AssemblyListSnapshot.cs/0 | {
"file_path": "ILSpy/ICSharpCode.ILSpyX/AssemblyListSnapshot.cs",
"repo_id": "ILSpy",
"token_count": 2353
} | 246 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
using ICSharpCode.ILSpyX.Abstractions;
using static System.Reflection.Metadata.PEReaderExtensions;
using ILOpCode = System.Reflection.Metadata.ILOpCode;
namespace ICSharpCode.ILSpyX.Search
{
public class LiteralSearchStrategy : AbstractEntitySearchStrategy
{
readonly TypeCode searchTermLiteralType = TypeCode.Empty;
readonly object? searchTermLiteralValue;
public LiteralSearchStrategy(ILanguage language, ApiVisibility apiVisibility, SearchRequest request,
IProducerConsumerCollection<SearchResult> resultQueue)
: base(language, apiVisibility, request, resultQueue)
{
var terms = request.Keywords;
if (terms.Length == 1)
{
var lexer = new Lexer(new LATextReader(new System.IO.StringReader(terms[0])));
var value = lexer.NextToken();
var following = lexer.NextToken();
if (value != null && value.LiteralValue != null && following != null && following.TokenKind == TokenKind.EOF)
{
TypeCode valueType = Type.GetTypeCode(value.LiteralValue.GetType());
switch (valueType)
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
searchTermLiteralType = TypeCode.Int64;
searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, value.LiteralValue, false);
break;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
searchTermLiteralType = valueType;
searchTermLiteralValue = value.LiteralValue;
break;
}
}
}
// Note: if searchTermLiteralType remains TypeCode.Empty, we'll do a substring search via base.IsMatch
}
public override void Search(PEFile module, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var metadata = module.Metadata;
var typeSystem = module.GetTypeSystemWithDecompilerSettingsOrNull(searchRequest.DecompilerSettings);
if (typeSystem == null)
return;
foreach (var handle in metadata.MethodDefinitions)
{
cancellationToken.ThrowIfCancellationRequested();
var md = metadata.GetMethodDefinition(handle);
if (!md.HasBody() || !MethodIsLiteralMatch(module, md))
continue;
var method = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle);
var result = method.AccessorOwner ?? method;
if (!CheckVisibility(result) || !IsInNamespaceOrAssembly(result))
continue;
OnFoundResult(result);
}
foreach (var handle in metadata.FieldDefinitions)
{
cancellationToken.ThrowIfCancellationRequested();
var fd = metadata.GetFieldDefinition(handle);
if (!fd.HasFlag(System.Reflection.FieldAttributes.Literal))
continue;
var constantHandle = fd.GetDefaultValue();
if (constantHandle.IsNil)
continue;
var constant = metadata.GetConstant(constantHandle);
var blob = metadata.GetBlobReader(constant.Value);
if (!IsLiteralMatch(metadata, blob.ReadConstant(constant.TypeCode)))
continue;
IField field = ((MetadataModule)typeSystem.MainModule).GetDefinition(handle);
if (!CheckVisibility(field) || !IsInNamespaceOrAssembly(field))
continue;
OnFoundResult(field);
}
}
bool IsLiteralMatch(MetadataReader metadata, object? val)
{
if (val == null)
return false;
switch (searchTermLiteralType)
{
case TypeCode.Int64:
TypeCode tc = Type.GetTypeCode(val.GetType());
if (tc >= TypeCode.SByte && tc <= TypeCode.UInt64)
return CSharpPrimitiveCast.Cast(TypeCode.Int64, val, false).Equals(searchTermLiteralValue);
else
return false;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
Debug.Assert(searchTermLiteralValue != null);
return searchTermLiteralValue.Equals(val);
default:
// substring search with searchTerm
string? valAsString = val.ToString();
return valAsString != null && IsMatch(valAsString);
}
}
bool MethodIsLiteralMatch(PEFile module, MethodDefinition methodDefinition)
{
var blob = module.Reader.GetMethodBody(methodDefinition.RelativeVirtualAddress).GetILReader();
if (searchTermLiteralType == TypeCode.Int64)
{
Debug.Assert(searchTermLiteralValue != null);
long val = (long)searchTermLiteralValue;
while (blob.RemainingBytes > 0)
{
ILOpCode code;
switch (code = ILParser.DecodeOpCode(ref blob))
{
case ILOpCode.Ldc_i8:
if (val == blob.ReadInt64())
return true;
break;
case ILOpCode.Ldc_i4:
if (val == blob.ReadInt32())
return true;
break;
case ILOpCode.Ldc_i4_s:
if (val == blob.ReadSByte())
return true;
break;
case ILOpCode.Ldc_i4_m1:
if (val == -1)
return true;
break;
case ILOpCode.Ldc_i4_0:
if (val == 0)
return true;
break;
case ILOpCode.Ldc_i4_1:
if (val == 1)
return true;
break;
case ILOpCode.Ldc_i4_2:
if (val == 2)
return true;
break;
case ILOpCode.Ldc_i4_3:
if (val == 3)
return true;
break;
case ILOpCode.Ldc_i4_4:
if (val == 4)
return true;
break;
case ILOpCode.Ldc_i4_5:
if (val == 5)
return true;
break;
case ILOpCode.Ldc_i4_6:
if (val == 6)
return true;
break;
case ILOpCode.Ldc_i4_7:
if (val == 7)
return true;
break;
case ILOpCode.Ldc_i4_8:
if (val == 8)
return true;
break;
default:
ILParser.SkipOperand(ref blob, code);
break;
}
}
}
else if (searchTermLiteralType != TypeCode.Empty)
{
Debug.Assert(searchTermLiteralValue != null);
ILOpCode expectedCode;
switch (searchTermLiteralType)
{
case TypeCode.Single:
expectedCode = ILOpCode.Ldc_r4;
break;
case TypeCode.Double:
expectedCode = ILOpCode.Ldc_r8;
break;
case TypeCode.String:
expectedCode = ILOpCode.Ldstr;
break;
default:
throw new InvalidOperationException();
}
while (blob.RemainingBytes > 0)
{
var code = ILParser.DecodeOpCode(ref blob);
if (code != expectedCode)
{
ILParser.SkipOperand(ref blob, code);
continue;
}
switch (code)
{
case ILOpCode.Ldc_r4:
if ((float)searchTermLiteralValue == blob.ReadSingle())
return true;
break;
case ILOpCode.Ldc_r8:
if ((double)searchTermLiteralValue == blob.ReadDouble())
return true;
break;
case ILOpCode.Ldstr:
if ((string)searchTermLiteralValue == ILParser.DecodeUserString(ref blob, module.Metadata))
return true;
break;
}
}
}
else
{
while (blob.RemainingBytes > 0)
{
var code = ILParser.DecodeOpCode(ref blob);
if (code != ILOpCode.Ldstr)
{
ILParser.SkipOperand(ref blob, code);
continue;
}
if (IsMatch(ILParser.DecodeUserString(ref blob, module.Metadata)))
return true;
}
}
return false;
}
}
}
| ILSpy/ICSharpCode.ILSpyX/Search/LiteralSearchStrategy.cs/0 | {
"file_path": "ILSpy/ICSharpCode.ILSpyX/Search/LiteralSearchStrategy.cs",
"repo_id": "ILSpy",
"token_count": 3642
} | 247 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
namespace ICSharpCode.ILSpy.AddIn.Commands
{
class OpenCodeItemCommand : ILSpyCommand
{
static OpenCodeItemCommand instance;
public OpenCodeItemCommand(ILSpyAddInPackage owner)
: base(owner, PkgCmdIDList.cmdidOpenCodeItemInILSpy)
{
ThreadHelper.ThrowIfNotOnUIThread();
}
protected override void OnBeforeQueryStatus(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (sender is OleMenuCommand menuItem)
{
menuItem.Visible = false;
// Enable this item only if this is a .cs file!
if (Utils.GetCurrentViewHost(owner, f => f.EndsWith(".cs")) == null)
return;
// Enable this item only if this is a Roslyn document
if (GetRoslynDocument() == null)
return;
var document = owner.DTE.ActiveDocument;
menuItem.Visible =
(document?.ProjectItem?.ContainingProject?.ConfigurationManager != null) &&
!string.IsNullOrEmpty(document.ProjectItem.ContainingProject.FileName);
}
}
Document GetRoslynDocument()
{
ThreadHelper.ThrowIfNotOnUIThread();
var document = owner.DTE.ActiveDocument;
var id = owner.Workspace.CurrentSolution.GetDocumentIdsWithFilePath(document.FullName).FirstOrDefault();
if (id == null)
return null;
return owner.Workspace.CurrentSolution.GetDocument(id);
}
protected override async void OnExecute(object sender, EventArgs e)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var textView = Utils.GetCurrentViewHost(owner)?.TextView;
if (textView == null)
return;
SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
var roslynDocument = GetRoslynDocument();
if (roslynDocument == null)
{
owner.ShowMessage("This element is not analyzable in current view.");
return;
}
var ast = await roslynDocument.GetSyntaxRootAsync().ConfigureAwait(false);
var model = await roslynDocument.GetSemanticModelAsync().ConfigureAwait(false);
var node = ast.FindNode(new TextSpan(caretPosition.Position, 0), false, true);
if (node == null)
{
owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!");
return;
}
var symbol = GetSymbolResolvableByILSpy(model, node);
if (symbol == null)
{
owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!");
return;
}
var roslynProject = roslynDocument.Project;
var refsmap = GetReferences(roslynProject);
var symbolAssemblyName = symbol.ContainingAssembly?.Identity?.Name;
// Add our own project as well (not among references)
var project = FindProject(owner.DTE.Solution.Projects.OfType<EnvDTE.Project>(), roslynProject.FilePath);
if (project == null)
{
owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING, "Can't show ILSpy for this code element!");
return;
}
string assemblyName = roslynDocument.Project.AssemblyName;
string projectOutputPath = Utils.GetProjectOutputAssembly(project, roslynProject);
refsmap.Add(assemblyName, new DetectedReference(assemblyName, projectOutputPath, true));
// Divide into valid and invalid (= not found) referenced assemblies
CheckAssemblies(refsmap, out var validRefs, out var invalidRefs);
var invalidSymbolReference = invalidRefs.FirstOrDefault(r => r.IsProjectReference && (r.Name == symbolAssemblyName));
if (invalidSymbolReference != null)
{
if (string.IsNullOrEmpty(invalidSymbolReference.AssemblyFile))
{
// No assembly file given at all. This has been seen while project is still loading after opening...
owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING,
"Symbol can't be opened. This might happen while project is loading.",
Environment.NewLine, invalidSymbolReference.AssemblyFile);
}
else if (invalidSymbolReference.IsProjectReference)
{
// Some project references don't have assemblies, maybe not compiled yet?
if (owner.ShowMessage(
OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_WARNING,
"The project output for '{1}' could not be found for analysis.{0}{0}Expected path:{0}{0}{2}{0}{0}Would you like to build the solution?",
Environment.NewLine, symbolAssemblyName, invalidSymbolReference.AssemblyFile
) == (int)MessageButtonResult.IDYES)
{
owner.DTE.ExecuteCommand("Build.BuildSolution");
}
}
else
{
// External assembly is missing, we should abort
owner.ShowMessage(OLEMSGICON.OLEMSGICON_WARNING,
"Referenced assembly{0}{0}'{1}'{0}{0} could not be found.",
Environment.NewLine, invalidSymbolReference.AssemblyFile);
}
return;
}
OpenAssembliesInILSpy(new ILSpyParameters(validRefs.Select(r => r.AssemblyFile), "/navigateTo:" +
(symbol.OriginalDefinition ?? symbol).GetDocumentationCommentId()));
}
void CheckAssemblies(Dictionary<string, DetectedReference> inputReferenceList,
out List<DetectedReference> validRefs,
out List<DetectedReference> invalidRefs)
{
validRefs = new List<DetectedReference>();
invalidRefs = new List<DetectedReference>();
foreach (var reference in inputReferenceList.Select(r => r.Value))
{
if ((reference.AssemblyFile == null) || !File.Exists(reference.AssemblyFile))
{
invalidRefs.Add(reference);
}
else
{
validRefs.Add(reference);
}
}
}
ISymbol GetSymbolResolvableByILSpy(SemanticModel model, SyntaxNode node)
{
var current = node;
while (current != null)
{
var symbol = model.GetSymbolInfo(current).Symbol;
if (symbol == null)
{
symbol = model.GetDeclaredSymbol(current);
}
// ILSpy can only resolve some symbol types, so allow them, discard everything else
if (symbol != null)
{
switch (symbol.Kind)
{
case SymbolKind.ArrayType:
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.NamedType:
case SymbolKind.Namespace:
case SymbolKind.PointerType:
case SymbolKind.Property:
break;
default:
symbol = null;
break;
}
}
if (symbol != null)
return symbol;
current = current is IStructuredTriviaSyntax
? ((IStructuredTriviaSyntax)current).ParentTrivia.Token.Parent
: current.Parent;
}
return null;
}
internal static void Register(ILSpyAddInPackage owner)
{
ThreadHelper.ThrowIfNotOnUIThread();
instance = new OpenCodeItemCommand(owner);
}
}
}
| ILSpy/ILSpy.AddIn.Shared/Commands/OpenCodeItemCommand.cs/0 | {
"file_path": "ILSpy/ILSpy.AddIn.Shared/Commands/OpenCodeItemCommand.cs",
"repo_id": "ILSpy",
"token_count": 2569
} | 248 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace ICSharpCode.ILSpy.AddIn
{
public enum MessageButtonResult : int
{
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDTRYAGAIN = 10,
IDCONTINUE = 11,
}
static class Utils
{
public static byte[] HexStringToBytes(string hex)
{
if (hex == null)
throw new ArgumentNullException(nameof(hex));
var result = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length / 2; i++)
{
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return result;
}
public static bool TryGetProjectFileName(dynamic referenceObject, out string fileName)
{
try
{
fileName = referenceObject.Project.FileName;
return true;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
fileName = null;
return false;
}
}
public static object[] GetProperties(EnvDTE.Properties properties, params string[] names)
{
ThreadHelper.ThrowIfNotOnUIThread();
var values = new object[names.Length];
foreach (object p in properties)
{
try
{
if (p is Property property)
{
for (int i = 0; i < names.Length; i++)
{
if (names[i] == property.Name)
{
values[i] = property.Value;
break;
}
}
}
}
catch
{
continue;
}
}
return values;
}
public static List<(string, object)> GetAllProperties(EnvDTE.Properties properties)
{
ThreadHelper.ThrowIfNotOnUIThread();
var result = new List<(string, object)>();
for (int i = 0; i < properties.Count; i++)
{
try
{
if (properties.Item(i) is Property p)
{
result.Add((p.Name, p.Value));
}
}
catch
{
continue;
}
}
return result;
}
public static ITextSelection GetSelectionInCurrentView(IServiceProvider serviceProvider, Func<string, bool> predicate)
{
IWpfTextViewHost viewHost = GetCurrentViewHost(serviceProvider, predicate);
if (viewHost == null)
return null;
return viewHost.TextView.Selection;
}
public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider, Func<string, bool> predicate)
{
IWpfTextViewHost viewHost = GetCurrentViewHost(serviceProvider);
if (viewHost == null)
return null;
ITextDocument textDocument = viewHost.GetTextDocument();
if (textDocument == null || !predicate(textDocument.FilePath))
return null;
return viewHost;
}
public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider)
{
IVsTextManager txtMgr = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
if (txtMgr == null)
{
return null;
}
IVsTextView vTextView = null;
int mustHaveFocus = 1;
txtMgr.GetActiveView(mustHaveFocus, null, out vTextView);
IVsUserData userData = vTextView as IVsUserData;
if (userData == null)
return null;
object holder;
Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out holder);
return holder as IWpfTextViewHost;
}
public static ITextDocument GetTextDocument(this IWpfTextViewHost viewHost)
{
ITextDocument textDocument = null;
viewHost.TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out textDocument);
return textDocument;
}
public static VisualStudioWorkspace GetWorkspace(IServiceProvider serviceProvider)
{
return (VisualStudioWorkspace)serviceProvider.GetService(typeof(VisualStudioWorkspace));
}
public static string GetProjectOutputAssembly(Project project, Microsoft.CodeAnalysis.Project roslynProject)
{
ThreadHelper.ThrowIfNotOnUIThread();
string outputFileName = Path.GetFileName(roslynProject.OutputFilePath);
// Get the directory path based on the project file.
string projectPath = Path.GetDirectoryName(project.FullName);
// Get the output path based on the active configuration
string projectOutputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
// Combine the project path and output path to get the bin path
if ((projectPath != null) && (projectOutputPath != null) && (outputFileName != null))
return Path.Combine(projectPath, projectOutputPath, outputFileName);
return null;
}
}
}
| ILSpy/ILSpy.AddIn.Shared/Utils.cs/0 | {
"file_path": "ILSpy/ILSpy.AddIn.Shared/Utils.cs",
"repo_id": "ILSpy",
"token_count": 1798
} | 249 |
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="ebf12ca7-a1fd-4aee-a894-4a0c5682fc2f" Version="$INSERTVERSION$" Language="en-US" Publisher="SharpDevelop Team" />
<DisplayName>ILSpy 2022</DisplayName>
<Description xml:space="preserve">Integrates the ILSpy decompiler into Visual Studio.</Description>
<MoreInfo>https://ilspy.net</MoreInfo>
<License>license.txt</License>
<Icon>ILSpy-Large.ico</Icon>
<Tags>ILSpy;IL;decompile;decompiler;decompilation;C#;CSharp;.NET;Productivity;Open Source;Free</Tags>
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version ="[17.0, 18.0)">
<ProductArchitecture>amd64</ProductArchitecture>
</InstallationTarget>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version ="[17.0, 18.0)">
<ProductArchitecture>arm64</ProductArchitecture>
</InstallationTarget>
</Installation>
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.5,)" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="ILSpy.AddIn.VS2022" Path="|ILSpy.AddIn.VS2022|"/>
</Assets>
<Prerequisites>
<Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,)" DisplayName="Visual Studio core editor" />
<Prerequisite Id="Microsoft.VisualStudio.Component.Roslyn.LanguageServices" Version="[17.0,)" DisplayName="Roslyn Language Services" />
</Prerequisites>
</PackageManifest>
| ILSpy/ILSpy.AddIn.VS2022/source.extension.vsixmanifest.template/0 | {
"file_path": "ILSpy/ILSpy.AddIn.VS2022/source.extension.vsixmanifest.template",
"repo_id": "ILSpy",
"token_count": 611
} | 250 |
// Copyright (c) 2020 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using ICSharpCode.BamlDecompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Tests.Helpers;
using ICSharpCode.Decompiler.Util;
using NUnit.Framework;
namespace ILSpy.BamlDecompiler.Tests
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class BamlTestRunner
{
[Test]
public void Simple()
{
RunTest("cases/simple");
}
[Test]
public void SimpleDictionary()
{
RunTest("cases/simpledictionary");
}
[Test]
public void Resources()
{
RunTest("cases/resources");
}
[Test]
public void SimpleNames()
{
RunTest("cases/simplenames");
}
[Test]
public void AvalonDockBrushes()
{
RunTest("cases/avalondockbrushes");
}
[Test]
public void AvalonDockCommon()
{
RunTest("cases/avalondockcommon");
}
[Test]
public void AttachedEvent()
{
RunTest("cases/attachedevent");
}
[Test]
public void Dictionary1()
{
RunTest("cases/dictionary1");
}
[Test]
public void Issue775()
{
RunTest("cases/issue775");
}
[Test]
public void MarkupExtension()
{
RunTest("cases/markupextension");
}
[Test]
public void SimplePropertyElement()
{
RunTest("cases/simplepropertyelement");
}
[Test]
public void Issue445()
{
RunTest("cases/issue445");
}
[Test]
public void NamespacePrefix()
{
RunTest("cases/namespaceprefix");
}
[Test]
public void EscapeSequence()
{
RunTest("cases/escapesequence");
}
[Test]
public void Issue1435()
{
RunTest("cases/issue1435");
}
[Test]
public void Issue1546()
{
RunTest("cases/issue1546");
}
[Test]
public void Issue1547()
{
RunTest("cases/issue1547");
}
[Test]
public void Issue2052()
{
RunTest("cases/issue2052");
}
[Test]
public void Issue2097()
{
RunTest("cases/issue2097");
}
[Test]
public void Issue2116()
{
RunTest("cases/issue2116");
}
[Test]
public void ReadonlyProperty()
{
RunTest("cases/readonlyproperty");
}
#region RunTest
void RunTest(string name)
{
RunTest(name, typeof(BamlTestRunner).Assembly.Location,
Path.Combine(
Path.GetDirectoryName(typeof(BamlTestRunner).Assembly.Location),
"../../../..", name + ".xaml"));
}
void RunTest(string name, string asmPath, string sourcePath)
{
using (var fileStream = new FileStream(asmPath, FileMode.Open, FileAccess.Read))
{
var module = new PEFile(asmPath, fileStream);
var resolver = new UniversalAssemblyResolver(asmPath, false, module.Metadata.DetectTargetFrameworkId());
resolver.RemoveSearchDirectory(".");
resolver.AddSearchDirectory(Path.GetDirectoryName(asmPath));
var res = module.Resources.First();
Stream bamlStream = LoadBaml(res, name + ".baml");
Assert.That(bamlStream, Is.Not.Null);
BamlDecompilerTypeSystem typeSystem = new BamlDecompilerTypeSystem(module, resolver);
var decompiler = new XamlDecompiler(typeSystem, new BamlDecompilerSettings());
XDocument document = decompiler.Decompile(bamlStream).Xaml;
XamlIsEqual(File.ReadAllText(sourcePath), document.ToString());
}
}
void XamlIsEqual(string input1, string input2)
{
var diff = new StringWriter();
if (!CodeComparer.Compare(input1, input2, diff, NormalizeLine))
{
Assert.Fail(diff.ToString());
}
}
string NormalizeLine(string line)
{
return line.Trim();
}
Stream LoadBaml(Resource res, string name)
{
if (res.ResourceType != ResourceType.Embedded)
return null;
Stream s = res.TryOpenStream();
if (s == null)
return null;
s.Position = 0;
ResourcesFile resources;
try
{
resources = new ResourcesFile(s);
}
catch (ArgumentException)
{
return null;
}
foreach (var entry in resources.OrderBy(e => e.Key))
{
if (entry.Key == name)
{
if (entry.Value is Stream)
return (Stream)entry.Value;
if (entry.Value is byte[])
return new MemoryStream((byte[])entry.Value);
}
}
return null;
}
#endregion
}
}
| ILSpy/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/BamlTestRunner.cs",
"repo_id": "ILSpy",
"token_count": 2008
} | 251 |
namespace ILSpy.BamlDecompiler.Tests.Cases
{
using System.Windows;
using System.Windows.Controls;
public partial class Issue2116 : UserControl
{
public static ComponentResourceKey StyleKey1 => new ComponentResourceKey(typeof(Issue2116), "TestStyle1");
public static ComponentResourceKey StyleKey2 => new ComponentResourceKey(typeof(Issue2116), "TestStyle2");
public Issue2116()
{
InitializeComponent();
}
}
}
| ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2116.xaml.cs/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue2116.xaml.cs",
"repo_id": "ILSpy",
"token_count": 141
} | 252 |
<Label xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Content="Blah">
<FrameworkElement.Style>
<Style />
</FrameworkElement.Style>
</Label> | ILSpy/ILSpy.BamlDecompiler.Tests/Cases/SimplePropertyElement.xaml/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/SimplePropertyElement.xaml",
"repo_id": "ILSpy",
"token_count": 85
} | 253 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ILSpy.ReadyToRun.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ILSpy.ReadyToRun.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Disassembly Format.
/// </summary>
public static string DisassemblyFormat {
get {
return ResourceManager.GetString("DisassemblyFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ReadyToRun.
/// </summary>
public static string ReadyToRun {
get {
return ResourceManager.GetString("ReadyToRun", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Debug Info.
/// </summary>
public static string ShowDebugInfo {
get {
return ResourceManager.GetString("ShowDebugInfo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Unwind Info.
/// </summary>
public static string ShowStackUnwindInfo {
get {
return ResourceManager.GetString("ShowStackUnwindInfo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show GC Info.
/// </summary>
public static string ShowGCInfo {
get {
return ResourceManager.GetString("ShowGCInfo", resourceCulture);
}
}
}
}
| ILSpy/ILSpy.ReadyToRun/Properties/Resources.Designer.cs/0 | {
"file_path": "ILSpy/ILSpy.ReadyToRun/Properties/Resources.Designer.cs",
"repo_id": "ILSpy",
"token_count": 1643
} | 254 |
{
"solution": {
"path": "ILSpy.sln",
"projects": [
"ICSharpCode.Decompiler.TestRunner\\ICSharpCode.Decompiler.TestRunner.csproj",
"ICSharpCode.Decompiler.Tests\\ICSharpCode.Decompiler.Tests.csproj",
"ICSharpCode.Decompiler\\ICSharpCode.Decompiler.csproj",
"ICSharpCode.ILSpyX\\ICSharpCode.ILSpyX.csproj",
"ILSpy.BamlDecompiler.Tests\\ILSpy.BamlDecompiler.Tests.csproj",
"ILSpy.BamlDecompiler\\ILSpy.BamlDecompiler.csproj",
"ILSpy.ReadyToRun\\ILSpy.ReadyToRun.csproj",
"ILSpy.Tests\\ILSpy.Tests.csproj",
"ILSpy\\ILSpy.csproj",
"SharpTreeView\\ICSharpCode.TreeView.csproj",
"TestPlugin\\TestPlugin.csproj"
]
}
} | ILSpy/ILSpy.Wpf.slnf/0 | {
"file_path": "ILSpy/ILSpy.Wpf.slnf",
"repo_id": "ILSpy",
"token_count": 316
} | 255 |
// Copyright (c) 2022 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.ILSpy.Analyzers.Builtin
{
public enum TokenSearchResult : byte
{
NoResult = 0,
Byte = PrimitiveTypeCode.Byte,
SByte = PrimitiveTypeCode.SByte,
Int16 = PrimitiveTypeCode.Int16,
UInt16 = PrimitiveTypeCode.UInt16,
Int32 = PrimitiveTypeCode.Int32,
UInt32 = PrimitiveTypeCode.UInt32,
Int64 = PrimitiveTypeCode.Int64,
UInt64 = PrimitiveTypeCode.UInt64,
IntPtr = PrimitiveTypeCode.IntPtr,
UIntPtr = PrimitiveTypeCode.UIntPtr,
// lowest PrimitiveTypeCode is 1
// highest PrimitiveTypeCode is 28 (0b0001_1100)
// TokenSearchResult with a PrimitiveTypeCode set is only used when decoding an enum-type.
// It is used for GetUnderlyingEnumType and should be masked out in all other uses.
// MSB = Found
// 127 = System.Type
TypeCodeMask = 0b0111_1111,
Found = 0b1000_0000,
SystemType = 127,
}
class FindTypeInAttributeDecoder : ICustomAttributeTypeProvider<TokenSearchResult>
{
readonly PEFile declaringModule;
readonly MetadataModule currentModule;
readonly TypeDefinitionHandle handle;
readonly PrimitiveTypeCode primitiveType;
/// <summary>
/// Constructs a FindTypeInAttributeDecoder that can be used to find <paramref name="type"/> in signatures from <paramref name="currentModule"/>.
/// </summary>
public FindTypeInAttributeDecoder(MetadataModule currentModule, ITypeDefinition type)
{
this.currentModule = currentModule;
this.declaringModule = type.ParentModule?.PEFile ?? throw new InvalidOperationException("Cannot use MetadataModule without PEFile as context.");
this.handle = (TypeDefinitionHandle)type.MetadataToken;
this.primitiveType = type.KnownTypeCode == KnownTypeCode.None ? 0 : type.KnownTypeCode.ToPrimitiveTypeCode();
}
public TokenSearchResult GetPrimitiveType(PrimitiveTypeCode typeCode)
{
return typeCode == primitiveType ? TokenSearchResult.Found : 0;
}
public TokenSearchResult GetSystemType() => TokenSearchResult.SystemType;
public TokenSearchResult GetSZArrayType(TokenSearchResult elementType) => elementType & TokenSearchResult.Found;
public TokenSearchResult GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
TokenSearchResult result = TokenSearchResult.NoResult;
if (handle.IsEnum(reader, out PrimitiveTypeCode underlyingType))
{
result = (TokenSearchResult)underlyingType;
}
else if (((EntityHandle)handle).IsKnownType(reader, KnownTypeCode.Type))
{
result = TokenSearchResult.SystemType;
}
if (this.handle == handle && reader == declaringModule.Metadata)
{
result |= TokenSearchResult.Found;
}
return result;
}
public TokenSearchResult GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var t = currentModule.ResolveType(handle, default);
return GetResultFromResolvedType(t);
}
public TokenSearchResult GetTypeFromSerializedName(string name)
{
if (name == null)
{
return TokenSearchResult.NoResult;
}
try
{
IType type = ReflectionHelper.ParseReflectionName(name)
.Resolve(new SimpleTypeResolveContext(currentModule));
return GetResultFromResolvedType(type);
}
catch (ReflectionNameParseException)
{
return TokenSearchResult.NoResult;
}
}
private TokenSearchResult GetResultFromResolvedType(IType type)
{
var td = type.GetDefinition();
if (td == null)
return TokenSearchResult.NoResult;
TokenSearchResult result = TokenSearchResult.NoResult;
var underlyingType = td.EnumUnderlyingType?.GetDefinition();
if (underlyingType != null)
{
result = (TokenSearchResult)underlyingType.KnownTypeCode.ToPrimitiveTypeCode();
}
else if (td.KnownTypeCode == KnownTypeCode.Type)
{
result = TokenSearchResult.SystemType;
}
if (td.MetadataToken == this.handle && td.ParentModule?.PEFile == declaringModule)
{
result |= TokenSearchResult.Found;
}
return result;
}
public PrimitiveTypeCode GetUnderlyingEnumType(TokenSearchResult type)
{
TokenSearchResult typeCode = type & TokenSearchResult.TypeCodeMask;
if (typeCode == 0 || typeCode == TokenSearchResult.SystemType)
throw new EnumUnderlyingTypeResolveException();
return (PrimitiveTypeCode)typeCode;
}
public bool IsSystemType(TokenSearchResult type) => (type & TokenSearchResult.TypeCodeMask) == TokenSearchResult.SystemType;
}
}
| ILSpy/ILSpy/Analyzers/Builtin/FindTypeInAttributeDecoder.cs/0 | {
"file_path": "ILSpy/ILSpy/Analyzers/Builtin/FindTypeInAttributeDecoder.cs",
"repo_id": "ILSpy",
"token_count": 1821
} | 256 |
// Copyright (c) 2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Linq;
namespace ICSharpCode.ILSpy.Analyzers
{
[ExportContextMenuEntry(Header = "Remove", Icon = "images/Delete", Category = "Analyze", Order = 200)]
internal sealed class RemoveAnalyzeContextMenuEntry : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.TreeView is AnalyzerTreeView && context.SelectedTreeNodes != null && context.SelectedTreeNodes.All(n => n.Parent.IsRoot))
return true;
return false;
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes != null)
{
foreach (var node in context.SelectedTreeNodes)
{
node.Parent.Children.Remove(node);
}
}
}
}
}
| ILSpy/ILSpy/Analyzers/RemoveAnalyzeContextMenuEntry.cs/0 | {
"file_path": "ILSpy/ILSpy/Analyzers/RemoveAnalyzeContextMenuEntry.cs",
"repo_id": "ILSpy",
"token_count": 573
} | 257 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#if DEBUG
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpy.TreeNodes;
using Microsoft.DiaSymReader.Tools;
namespace ICSharpCode.ILSpy
{
[ExportMainMenuCommand(ParentMenuID = nameof(Resources._File), Header = nameof(Resources.DEBUGDumpPDBAsXML), MenuCategory = nameof(Resources.Open), MenuOrder = 2.6)]
sealed class Pdb2XmlCommand : SimpleCommand
{
public override bool CanExecute(object parameter)
{
var selectedNodes = MainWindow.Instance.SelectedNodes;
return selectedNodes?.Any() == true
&& selectedNodes.All(n => n is AssemblyTreeNode asm && !asm.LoadedAssembly.HasLoadError);
}
public override void Execute(object parameter)
{
Execute(MainWindow.Instance.SelectedNodes.OfType<AssemblyTreeNode>());
}
internal static void Execute(IEnumerable<AssemblyTreeNode> nodes)
{
var highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
var options = PdbToXmlOptions.IncludeEmbeddedSources | PdbToXmlOptions.IncludeMethodSpans | PdbToXmlOptions.IncludeTokens;
Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => {
AvalonEditTextOutput output = new AvalonEditTextOutput();
var writer = new TextOutputWriter(output);
foreach (var node in nodes)
{
string pdbFileName = Path.ChangeExtension(node.LoadedAssembly.FileName, ".pdb");
if (!File.Exists(pdbFileName))
continue;
using (var pdbStream = File.OpenRead(pdbFileName))
using (var peStream = File.OpenRead(node.LoadedAssembly.FileName))
PdbToXmlConverter.ToXml(writer, pdbStream, peStream, options);
}
return output;
}, ct)).Then(output => Docking.DockWorkspace.Instance.ShowNodes(output, null, highlighting)).HandleExceptions();
}
}
[ExportContextMenuEntry(Header = nameof(Resources.DEBUGDumpPDBAsXML))]
class Pdb2XmlCommandContextMenuEntry : IContextMenuEntry
{
public void Execute(TextViewContext context)
{
Pdb2XmlCommand.Execute(context.SelectedTreeNodes.OfType<AssemblyTreeNode>());
}
public bool IsEnabled(TextViewContext context) => true;
public bool IsVisible(TextViewContext context)
{
var selectedNodes = context.SelectedTreeNodes;
return selectedNodes?.Any() == true
&& selectedNodes.All(n => n is AssemblyTreeNode asm && asm.LoadedAssembly.IsLoadedAsValidAssembly);
}
}
}
#endif
| ILSpy/ILSpy/Commands/Pdb2XmlCommand.cs/0 | {
"file_path": "ILSpy/ILSpy/Commands/Pdb2XmlCommand.cs",
"repo_id": "ILSpy",
"token_count": 1208
} | 258 |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Threading;
namespace ICSharpCode.ILSpy.Controls
{
/// <summary>
/// Allows animated collapsing of the content of this panel.
/// </summary>
public class CollapsiblePanel : ContentControl
{
static CollapsiblePanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(typeof(CollapsiblePanel)));
FocusableProperty.OverrideMetadata(typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(false));
}
public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.Register(
"IsCollapsed", typeof(bool), typeof(CollapsiblePanel),
new UIPropertyMetadata(false, new PropertyChangedCallback(OnIsCollapsedChanged)));
public bool IsCollapsed {
get { return (bool)GetValue(IsCollapsedProperty); }
set { SetValue(IsCollapsedProperty, value); }
}
public static readonly DependencyProperty CollapseOrientationProperty =
DependencyProperty.Register("CollapseOrientation", typeof(Orientation), typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(Orientation.Vertical));
public Orientation CollapseOrientation {
get { return (Orientation)GetValue(CollapseOrientationProperty); }
set { SetValue(CollapseOrientationProperty, value); }
}
public static readonly DependencyProperty DurationProperty = DependencyProperty.Register(
"Duration", typeof(TimeSpan), typeof(CollapsiblePanel),
new UIPropertyMetadata(TimeSpan.FromMilliseconds(250)));
/// <summary>
/// The duration in milliseconds of the animation.
/// </summary>
public TimeSpan Duration {
get { return (TimeSpan)GetValue(DurationProperty); }
set { SetValue(DurationProperty, value); }
}
protected internal static readonly DependencyProperty AnimationProgressProperty = DependencyProperty.Register(
"AnimationProgress", typeof(double), typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(1.0));
/// <summary>
/// Value between 0 and 1 specifying how far the animation currently is.
/// </summary>
protected internal double AnimationProgress {
get { return (double)GetValue(AnimationProgressProperty); }
set { SetValue(AnimationProgressProperty, value); }
}
protected internal static readonly DependencyProperty AnimationProgressXProperty = DependencyProperty.Register(
"AnimationProgressX", typeof(double), typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(1.0));
/// <summary>
/// Value between 0 and 1 specifying how far the animation currently is.
/// </summary>
protected internal double AnimationProgressX {
get { return (double)GetValue(AnimationProgressXProperty); }
set { SetValue(AnimationProgressXProperty, value); }
}
protected internal static readonly DependencyProperty AnimationProgressYProperty = DependencyProperty.Register(
"AnimationProgressY", typeof(double), typeof(CollapsiblePanel),
new FrameworkPropertyMetadata(1.0));
/// <summary>
/// Value between 0 and 1 specifying how far the animation currently is.
/// </summary>
protected internal double AnimationProgressY {
get { return (double)GetValue(AnimationProgressYProperty); }
set { SetValue(AnimationProgressYProperty, value); }
}
static void OnIsCollapsedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((CollapsiblePanel)d).SetupAnimation((bool)e.NewValue);
}
void SetupAnimation(bool isCollapsed)
{
if (this.IsLoaded)
{
// If the animation is already running, calculate remaining portion of the time
double currentProgress = AnimationProgress;
if (!isCollapsed)
{
currentProgress = 1.0 - currentProgress;
}
DoubleAnimation animation = new DoubleAnimation();
animation.To = isCollapsed ? 0.0 : 1.0;
animation.Duration = TimeSpan.FromSeconds(Duration.TotalSeconds * currentProgress);
animation.FillBehavior = FillBehavior.HoldEnd;
this.BeginAnimation(AnimationProgressProperty, animation);
if (CollapseOrientation == Orientation.Horizontal)
{
this.BeginAnimation(AnimationProgressXProperty, animation);
this.AnimationProgressY = 1.0;
}
else
{
this.AnimationProgressX = 1.0;
this.BeginAnimation(AnimationProgressYProperty, animation);
}
}
else
{
this.AnimationProgress = isCollapsed ? 0.0 : 1.0;
this.AnimationProgressX = (CollapseOrientation == Orientation.Horizontal) ? this.AnimationProgress : 1.0;
this.AnimationProgressY = (CollapseOrientation == Orientation.Vertical) ? this.AnimationProgress : 1.0;
}
}
}
sealed class CollapsiblePanelProgressToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
return (double)value > 0 ? Visibility.Visible : Visibility.Collapsed;
else
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class SelfCollapsingPanel : CollapsiblePanel
{
public static readonly DependencyProperty CanCollapseProperty =
DependencyProperty.Register("CanCollapse", typeof(bool), typeof(SelfCollapsingPanel),
new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnCanCollapseChanged)));
public bool CanCollapse {
get { return (bool)GetValue(CanCollapseProperty); }
set { SetValue(CanCollapseProperty, value); }
}
static void OnCanCollapseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SelfCollapsingPanel panel = (SelfCollapsingPanel)d;
if ((bool)e.NewValue)
{
if (!panel.HeldOpenByMouse)
panel.IsCollapsed = true;
}
else
{
panel.IsCollapsed = false;
}
}
bool HeldOpenByMouse {
get { return IsMouseOver || IsMouseCaptureWithin; }
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
if (CanCollapse && !HeldOpenByMouse)
IsCollapsed = true;
}
protected override void OnLostMouseCapture(MouseEventArgs e)
{
base.OnLostMouseCapture(e);
if (CanCollapse && !HeldOpenByMouse)
IsCollapsed = true;
}
}
}
| ILSpy/ILSpy/Controls/CollapsiblePanel.cs/0 | {
"file_path": "ILSpy/ILSpy/Controls/CollapsiblePanel.cs",
"repo_id": "ILSpy",
"token_count": 2394
} | 259 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:ICSharpCode.ILSpy.Controls">
<Style TargetType="{x:Type Controls:ZoomScrollViewer}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Controls:ZoomScrollViewer}">
<Grid Background="{TemplateBinding Panel.Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Controls:SelfCollapsingPanel Grid.Column="0" Grid.Row="1" CollapseOrientation="Horizontal" CanCollapse="{Binding Path=ComputedZoomButtonCollapsed, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}">
<Controls:ZoomButtons x:Name="zoomButtons" Value="{Binding Path=CurrentZoom, RelativeSource={RelativeSource Mode=TemplatedParent}}" Minimum="{TemplateBinding MinimumZoom}" Maximum="{TemplateBinding MaximumZoom}" />
</Controls:SelfCollapsingPanel>
<Rectangle Grid.Column="2" Grid.Row="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<ScrollContentPresenter Name="PART_Presenter" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Margin="{TemplateBinding Control.Padding}" Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" CanContentScroll="{TemplateBinding ScrollViewer.CanContentScroll}">
<ScrollContentPresenter.LayoutTransform>
<ScaleTransform ScaleX="{Binding Path=CurrentZoom, RelativeSource={RelativeSource Mode=TemplatedParent}}" ScaleY="{Binding Path=CurrentZoom, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
</ScrollContentPresenter.LayoutTransform>
</ScrollContentPresenter>
<ScrollBar Name="PART_VerticalScrollBar" Grid.Column="2" Grid.Row="0" Minimum="0" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Value="{TemplateBinding VerticalOffset}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" />
<ScrollBar Name="PART_HorizontalScrollBar" Orientation="Horizontal" Grid.Column="1" Grid.Row="1" Minimum="0" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Value="{TemplateBinding HorizontalOffset}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Template for CollapsiblePanel -->
<Style TargetType="{x:Type Controls:CollapsiblePanel}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Controls:CollapsiblePanel">
<ControlTemplate.Resources>
<Controls:CollapsiblePanelProgressToVisibilityConverter x:Key="visibilityConverter"/>
</ControlTemplate.Resources>
<Border
BorderThickness="{TemplateBinding Border.BorderThickness}"
BorderBrush="{TemplateBinding Border.BorderBrush}"
Background="{TemplateBinding Panel.Background}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"
Name="PART_Border"
Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=AnimationProgress, Converter={StaticResource visibilityConverter}}"
>
<Border.LayoutTransform>
<ScaleTransform ScaleX="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=AnimationProgressX}"
ScaleY="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=AnimationProgressY}"/>
</Border.LayoutTransform>
<ContentPresenter
Margin="{TemplateBinding Control.Padding}"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ZoomButtonStyle"
TargetType="RepeatButton">
<Setter Property="Delay" Value="0" />
<Setter Property="Focusable" Value="False" />
<Setter Property="Opacity" Value="0.5" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RepeatButton">
<ContentPresenter />
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="1" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type Controls:ZoomButtons}">
<Setter Property="Minimum" Value="0.2"/>
<Setter Property="Maximum" Value="10"/>
<Setter Property="Value" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Controls:ZoomButtons}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel Orientation="Horizontal"
Background="#3000">
<RepeatButton x:Name="uxPlus"
Width="16" Height="16" Padding="0" BorderThickness="0"
Style="{StaticResource ZoomButtonStyle}">
<Image Source="{Controls:XamlResource Images/ZoomIn}"
Stretch="Uniform"/>
</RepeatButton>
<RepeatButton x:Name="uxMinus"
Width="16" Height="16" Padding="0" BorderThickness="0"
Style="{StaticResource ZoomButtonStyle}">
<Image Source="{Controls:XamlResource Images/ZoomOut}"
Stretch="Uniform" />
</RepeatButton>
<RepeatButton x:Name="uxReset"
Width="16" Height="16" Padding="0" BorderThickness="0"
Style="{StaticResource ZoomButtonStyle}">
<Border Background="#5000">
<TextBlock Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center">1</TextBlock>
</Border>
</RepeatButton>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary> | ILSpy/ILSpy/Controls/ZoomScrollViewer.xaml/0 | {
"file_path": "ILSpy/ILSpy/Controls/ZoomScrollViewer.xaml",
"repo_id": "ILSpy",
"token_count": 2530
} | 260 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpy.Themes;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Adds additional WPF-specific output features to <see cref="ITextOutput"/>.
/// </summary>
public interface ISmartTextOutput : ITextOutput
{
/// <summary>
/// Inserts an interactive UI element at the current position in the text output.
/// </summary>
void AddUIElement(Func<UIElement> element);
void BeginSpan(HighlightingColor highlightingColor);
void EndSpan();
/// <summary>
/// Gets/sets the title displayed in the document tab's header.
/// </summary>
string Title { get; set; }
}
public static class SmartTextOutputExtensions
{
/// <summary>
/// Creates a button.
/// </summary>
public static void AddButton(this ISmartTextOutput output, ImageSource icon, string text, RoutedEventHandler click)
{
output.AddUIElement(
delegate {
Button button = ThemeManager.Current.CreateButton();
button.Cursor = Cursors.Arrow;
button.Margin = new Thickness(2);
button.Padding = new Thickness(9, 1, 9, 1);
button.MinWidth = 73;
if (icon != null)
{
button.Content = new StackPanel {
Orientation = Orientation.Horizontal,
Children = {
new Image { Width = 16, Height = 16, Source = icon, Margin = new Thickness(0, 0, 4, 0) },
new TextBlock { Text = text }
}
};
}
else
{
button.Content = text;
}
button.Click += click;
return button;
});
}
}
}
| ILSpy/ILSpy/ISmartTextOutput.cs/0 | {
"file_path": "ILSpy/ILSpy/ISmartTextOutput.cs",
"repo_id": "ILSpy",
"token_count": 935
} | 261 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg
version="1.1"
x="0px"
y="0px"
viewBox="0 0 16 16"
style="enable-background:new 0 0 16 16;"
xml:space="preserve"
id="svg8"
sodipodi:docname="ExportOverlay.svg"
inkscape:version="1.3.2 (091e20e, 2023-11-25, custom)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"><defs
id="defs8" /><sodipodi:namedview
id="namedview8"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="51.3125"
inkscape:cx="10.98173"
inkscape:cy="8"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="2552"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:current-layer="svg8" />
<style
type="text/css"
id="style1">
.icon_x002D_canvas_x002D_transparent{opacity:0;fill:#F6F6F6;}
.icon_x002D_vs_x002D_out{fill:#F6F6F6;}
.icon_x002D_vs_x002D_action_x002D_blue{fill:#00539C;}
</style>
<g
id="canvas"
transform="matrix(0.5625,0,0,1,7,12.444445)">
<path
class="icon_x002D_canvas_x002D_transparent"
d="M 16,-12.444444 V 3.5555556 H -12.444444 V -12.444444 Z"
id="path1"
style="stroke-width:1.33333" />
</g>
<g
id="outline"
transform="matrix(0.5625,0,0,0.5625,7,7)">
<path
class="icon_x002D_vs_x002D_out"
d="M 5.793,0.879 8.621,3.707 7.328,5 H 10.5 c 3.033,0 5.5,2.467 5.5,5.5 0,3.032 -2.467,5.5 -5.5,5.5 h -1 v -4 h 1 C 11.327,12 12,11.327 12,10.5 12,9.673 11.327,9 10.5,9 H 7.328 L 8.621,10.293 5.793,13.121 0,7.328 V 6.672 Z"
id="path2" />
</g>
<g
id="iconBg"
transform="matrix(0.5625,0,0,0.5625,7,7)">
<path
class="icon_x002D_vs_x002D_action_x002D_blue"
d="M 5.793,2.293 7.207,3.707 4.914,6 H 10.5 C 12.981,6 15,8.019 15,10.5 15,12.981 12.981,15 10.5,15 V 13 C 11.878,13 13,11.879 13,10.5 13,9.121 11.878,8 10.5,8 H 4.914 L 7.207,10.293 5.793,11.707 1.086,7 Z"
id="path3" />
<g
id="g3">
</g>
<g
id="g4">
</g>
<g
id="g5">
</g>
<g
id="g6">
</g>
<g
id="g7">
</g>
<g
id="g8">
</g>
</g>
</svg>
| ILSpy/ILSpy/Images/ExportOverlay.svg/0 | {
"file_path": "ILSpy/ILSpy/Images/ExportOverlay.svg",
"repo_id": "ILSpy",
"token_count": 1293
} | 262 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="16"
height="16"
version="1.1"
id="svg8"
sodipodi:docname="OverlayProtected.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata14">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs12" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="2048"
inkscape:window-height="1089"
id="namedview10"
showgrid="false"
showguides="true"
inkscape:guide-bbox="true"
inkscape:zoom="10.429825"
inkscape:cx="6.2997664"
inkscape:cy="-5.261887"
inkscape:window-x="1912"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:current-layer="svg8" />
<style
type="text/css"
id="style2">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-action-orange{fill:#C27D1A;}</style>
<path
class="icon-canvas-transparent"
d="M16 16h-16v-16h16v16z"
id="canvas" />
<path
class="icon-vs-out"
d="m 15.98242,12.5 -1.393,1.045 0.737,2.455 h -1.677 l -1.167,-0.875 -1.167,0.875 H 9.6384205 L 10.37442,13.545 8.9824205,12.5 V 11 H 11.137402 L 11.737051,8.9998111 13.22642,9 l 0.6,2 h 2.156 z"
id="outline"
inkscape:connector-curvature="0"
style="fill:#f6f6f6"
sodipodi:nodetypes="cccccccccccccccc" />
<path
class="icon-vs-bg"
d="m 13.98242,15 -1.5,-1.125 -1.5,1.125 0.551,-1.837 L 9.9824205,12 H 11.88242 l 0.6,-2 0.6,2 h 1.9 l -1.551,1.163 z"
id="notificationBg"
inkscape:connector-curvature="0"
style="fill:#424242" />
</svg>
| ILSpy/ILSpy/Images/OverlayProtected.svg/0 | {
"file_path": "ILSpy/ILSpy/Images/OverlayProtected.svg",
"repo_id": "ILSpy",
"token_count": 1261
} | 263 |
<DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ClipGeometry="M0,0 V16 H16 V0 H0 Z">
<DrawingGroup Opacity="1">
<GeometryDrawing Geometry="F1 M16,16z M0,0z M0,0L16,0 16,16 0,16z">
<GeometryDrawing.Brush>
<SolidColorBrush Color="#FFF6F6F6" Opacity="0" />
</GeometryDrawing.Brush>
</GeometryDrawing>
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1 M16,16z M0,0z M9,9L9,16 16,16 16,9z" />
</DrawingGroup>
<GeometryDrawing Brush="#FF424242" Geometry="F1 M16,16z M0,0z M10,10L10,15 15,15 15,10 10,10z M14,13L13,14 13,12.5 11.5,14 11,13.5 12.5,12 11,12 12,11 14,11 14,13z" />
<GeometryDrawing Brush="#FFF0EFF1" Geometry="F1 M16,16z M0,0z M14,11L14,13 13,14 13,12.5 11.5,14 11,13.5 12.5,12 11,12 12,11z" />
</DrawingGroup> | ILSpy/ILSpy/Images/ReferenceOverlay.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/ReferenceOverlay.xaml",
"repo_id": "ILSpy",
"token_count": 379
} | 264 |
<!-- This file was generated by the AiToXaml tool.-->
<!-- Tool Version: 14.0.22307.0 -->
<DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<DrawingGroup.Children>
<GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" />
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M9,14L9,8 7,8 7,14 1,14 1,2 15,2 15,14z" />
<GeometryDrawing Brush="#FF00529C" Geometry="F1M2,7L14,7 14,3 2,3z M2,13L6,13 6,9 2,9z M10,9L14,9 14,13 10,13z" />
</DrawingGroup.Children>
</DrawingGroup> | ILSpy/ILSpy/Images/Struct.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/Struct.xaml",
"repo_id": "ILSpy",
"token_count": 241
} | 265 |
// Copyright (c) 2018 Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.ILSpy.TextView;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Searches matching brackets for C#.
/// </summary>
class CSharpBracketSearcher : IBracketSearcher
{
string openingBrackets = "([{";
string closingBrackets = ")]}";
public BracketSearchResult SearchBracket(IDocument document, int offset)
{
if (offset > 0)
{
char c = document.GetCharAt(offset - 1);
int index = openingBrackets.IndexOf(c);
int otherOffset = -1;
if (index > -1)
otherOffset = SearchBracketForward(document, offset, openingBrackets[index], closingBrackets[index]);
index = closingBrackets.IndexOf(c);
if (index > -1)
otherOffset = SearchBracketBackward(document, offset - 2, openingBrackets[index], closingBrackets[index]);
if (otherOffset > -1)
{
var result = new BracketSearchResult(Math.Min(offset - 1, otherOffset), 1,
Math.Max(offset - 1, otherOffset), 1);
return result;
}
}
return null;
}
#region SearchBracket helper functions
static int ScanLineStart(IDocument document, int offset)
{
for (int i = offset - 1; i > 0; --i)
{
if (document.GetCharAt(i) == '\n')
return i + 1;
}
return 0;
}
/// <summary>
/// Gets the type of code at offset.<br/>
/// 0 = Code,<br/>
/// 1 = Comment,<br/>
/// 2 = String<br/>
/// Block comments and multiline strings are not supported.
/// </summary>
static int GetStartType(IDocument document, int linestart, int offset)
{
bool inString = false;
bool inChar = false;
bool verbatim = false;
int result = 0;
for (int i = linestart; i < offset; i++)
{
switch (document.GetCharAt(i))
{
case '/':
if (!inString && !inChar && i + 1 < document.TextLength)
{
if (document.GetCharAt(i + 1) == '/')
{
result = 1;
}
}
break;
case '"':
if (!inChar)
{
if (inString && verbatim)
{
if (i + 1 < document.TextLength && document.GetCharAt(i + 1) == '"')
{
++i; // skip escaped quote
inString = false; // let the string go on
}
else
{
verbatim = false;
}
}
else if (!inString && i > 0 && document.GetCharAt(i - 1) == '@')
{
verbatim = true;
}
inString = !inString;
}
break;
case '\'':
if (!inString)
inChar = !inChar;
break;
case '\\':
if ((inString && !verbatim) || inChar)
++i; // skip next character
break;
}
}
return (inString || inChar) ? 2 : result;
}
#endregion
#region SearchBracketBackward
int SearchBracketBackward(IDocument document, int offset, char openBracket, char closingBracket)
{
if (offset + 1 >= document.TextLength)
return -1;
// this method parses a c# document backwards to find the matching bracket
// first try "quick find" - find the matching bracket if there is no string/comment in the way
int quickResult = QuickSearchBracketBackward(document, offset, openBracket, closingBracket);
if (quickResult >= 0)
return quickResult;
// we need to parse the line from the beginning, so get the line start position
int linestart = ScanLineStart(document, offset + 1);
// we need to know where offset is - in a string/comment or in normal code?
// ignore cases where offset is in a block comment
int starttype = GetStartType(document, linestart, offset + 1);
if (starttype == 1)
{
return -1; // start position is in a comment
}
// I don't see any possibility to parse a C# document backwards...
// We have to do it forwards and push all bracket positions on a stack.
Stack<int> bracketStack = new Stack<int>();
bool blockComment = false;
bool lineComment = false;
bool inChar = false;
bool inString = false;
bool verbatim = false;
for (int i = 0; i <= offset; ++i)
{
char ch = document.GetCharAt(i);
switch (ch)
{
case '\r':
case '\n':
lineComment = false;
inChar = false;
if (!verbatim)
inString = false;
break;
case '/':
if (blockComment)
{
Debug.Assert(i > 0);
if (document.GetCharAt(i - 1) == '*')
{
blockComment = false;
}
}
if (!inString && !inChar && i + 1 < document.TextLength)
{
if (!blockComment && document.GetCharAt(i + 1) == '/')
{
lineComment = true;
}
if (!lineComment && document.GetCharAt(i + 1) == '*')
{
blockComment = true;
}
}
break;
case '"':
if (!(inChar || lineComment || blockComment))
{
if (inString && verbatim)
{
if (i + 1 < document.TextLength && document.GetCharAt(i + 1) == '"')
{
++i; // skip escaped quote
inString = false; // let the string go
}
else
{
verbatim = false;
}
}
else if (!inString && offset > 0 && document.GetCharAt(i - 1) == '@')
{
verbatim = true;
}
inString = !inString;
}
break;
case '\'':
if (!(inString || lineComment || blockComment))
{
inChar = !inChar;
}
break;
case '\\':
if ((inString && !verbatim) || inChar)
++i; // skip next character
break;
default:
if (ch == openBracket)
{
if (!(inString || inChar || lineComment || blockComment))
{
bracketStack.Push(i);
}
}
else if (ch == closingBracket)
{
if (!(inString || inChar || lineComment || blockComment))
{
if (bracketStack.Count > 0)
bracketStack.Pop();
}
}
break;
}
}
if (bracketStack.Count > 0)
return (int)bracketStack.Pop();
return -1;
}
#endregion
#region SearchBracketForward
int SearchBracketForward(IDocument document, int offset, char openBracket, char closingBracket)
{
bool inString = false;
bool inChar = false;
bool verbatim = false;
bool lineComment = false;
bool blockComment = false;
if (offset < 0)
return -1;
// first try "quick find" - find the matching bracket if there is no string/comment in the way
int quickResult = QuickSearchBracketForward(document, offset, openBracket, closingBracket);
if (quickResult >= 0)
return quickResult;
// we need to parse the line from the beginning, so get the line start position
int linestart = ScanLineStart(document, offset);
// we need to know where offset is - in a string/comment or in normal code?
// ignore cases where offset is in a block comment
int starttype = GetStartType(document, linestart, offset);
if (starttype != 0)
return -1; // start position is in a comment/string
int brackets = 1;
while (offset < document.TextLength)
{
char ch = document.GetCharAt(offset);
switch (ch)
{
case '\r':
case '\n':
lineComment = false;
inChar = false;
if (!verbatim)
inString = false;
break;
case '/':
if (blockComment)
{
Debug.Assert(offset > 0);
if (document.GetCharAt(offset - 1) == '*')
{
blockComment = false;
}
}
if (!inString && !inChar && offset + 1 < document.TextLength)
{
if (!blockComment && document.GetCharAt(offset + 1) == '/')
{
lineComment = true;
}
if (!lineComment && document.GetCharAt(offset + 1) == '*')
{
blockComment = true;
}
}
break;
case '"':
if (!(inChar || lineComment || blockComment))
{
if (inString && verbatim)
{
if (offset + 1 < document.TextLength && document.GetCharAt(offset + 1) == '"')
{
++offset; // skip escaped quote
inString = false; // let the string go
}
else
{
verbatim = false;
}
}
else if (!inString && offset > 0 && document.GetCharAt(offset - 1) == '@')
{
verbatim = true;
}
inString = !inString;
}
break;
case '\'':
if (!(inString || lineComment || blockComment))
{
inChar = !inChar;
}
break;
case '\\':
if ((inString && !verbatim) || inChar)
++offset; // skip next character
break;
default:
if (ch == openBracket)
{
if (!(inString || inChar || lineComment || blockComment))
{
++brackets;
}
}
else if (ch == closingBracket)
{
if (!(inString || inChar || lineComment || blockComment))
{
--brackets;
if (brackets == 0)
{
return offset;
}
}
}
break;
}
++offset;
}
return -1;
}
#endregion
int QuickSearchBracketBackward(IDocument document, int offset, char openBracket, char closingBracket)
{
int brackets = -1;
// first try "quick find" - find the matching bracket if there is no string/comment in the way
for (int i = offset; i >= 0; --i)
{
char ch = document.GetCharAt(i);
if (ch == openBracket)
{
++brackets;
if (brackets == 0)
return i;
}
else if (ch == closingBracket)
{
--brackets;
}
else if (ch == '"')
{
break;
}
else if (ch == '\'')
{
break;
}
else if (ch == '/' && i > 0)
{
if (document.GetCharAt(i - 1) == '/')
break;
if (document.GetCharAt(i - 1) == '*')
break;
}
}
return -1;
}
int QuickSearchBracketForward(IDocument document, int offset, char openBracket, char closingBracket)
{
int brackets = 1;
// try "quick find" - find the matching bracket if there is no string/comment in the way
for (int i = offset; i < document.TextLength; ++i)
{
char ch = document.GetCharAt(i);
if (ch == openBracket)
{
++brackets;
}
else if (ch == closingBracket)
{
--brackets;
if (brackets == 0)
return i;
}
else if (ch == '"')
{
break;
}
else if (ch == '\'')
{
break;
}
else if (ch == '/' && i > 0)
{
if (document.GetCharAt(i - 1) == '/')
break;
}
else if (ch == '*' && i > 0)
{
if (document.GetCharAt(i - 1) == '/')
break;
}
}
return -1;
}
}
}
| ILSpy/ILSpy/Languages/CSharpBracketSearcher.cs/0 | {
"file_path": "ILSpy/ILSpy/Languages/CSharpBracketSearcher.cs",
"repo_id": "ILSpy",
"token_count": 5271
} | 266 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.ViewModels;
namespace ICSharpCode.ILSpy.Metadata
{
internal class ConstantTableTreeNode : MetadataTableTreeNode
{
public ConstantTableTreeNode(MetadataFile metadataFile)
: base((HandleKind)0x0B, metadataFile)
{
}
public override object Text => $"0B Constant ({metadataFile.Metadata.GetTableRowCount(TableIndex.Constant)})";
public override bool View(TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
var metadata = metadataFile.Metadata;
var list = new List<ConstantEntry>();
ConstantEntry scrollTargetEntry = default;
for (int row = 1; row <= metadata.GetTableRowCount(TableIndex.Constant); row++)
{
ConstantEntry entry = new ConstantEntry(metadataFile, MetadataTokens.ConstantHandle(row));
if (scrollTarget == row)
{
scrollTargetEntry = entry;
}
list.Add(entry);
}
view.ItemsSource = list;
tabPage.Content = view;
if (scrollTargetEntry.RID > 0)
{
ScrollItemIntoView(view, scrollTargetEntry);
}
return true;
}
struct ConstantEntry
{
readonly MetadataFile metadataFile;
readonly EntityHandle handle;
readonly Constant constant;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.Constant)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.Constant) * (RID - 1);
[ColumnInfo("X8", Kind = ColumnKind.Other)]
public ConstantTypeCode Type => constant.TypeCode;
public string TypeTooltip => constant.TypeCode.ToString();
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Parent => MetadataTokens.GetToken(constant.Parent);
public void OnParentClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, constant.Parent, protocol: "metadata"));
}
string parentTooltip;
public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, constant.Parent);
[ColumnInfo("X8", Kind = ColumnKind.HeapOffset)]
public int Value => MetadataTokens.GetHeapOffset(constant.Value);
public string ValueTooltip {
get {
return null;
}
}
public ConstantEntry(MetadataFile metadataFile, ConstantHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.constant = metadataFile.Metadata.GetConstant(handle);
this.parentTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "Constants");
}
}
}
| ILSpy/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/ConstantTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1310
} | 267 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.ILSpy.Metadata
{
internal class MemberRefTableTreeNode : MetadataTableTreeNode
{
public MemberRefTableTreeNode(MetadataFile metadataFile)
: base(HandleKind.MemberReference, metadataFile)
{
}
public override object Text => $"0A MemberRef ({metadataFile.Metadata.GetTableRowCount(TableIndex.MemberRef)})";
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
var metadata = metadataFile.Metadata;
var list = new List<MemberRefEntry>();
MemberRefEntry scrollTargetEntry = default;
foreach (var row in metadata.MemberReferences)
{
MemberRefEntry entry = new MemberRefEntry(metadataFile, row);
if (entry.RID == this.scrollTarget)
{
scrollTargetEntry = entry;
}
list.Add(entry);
}
view.ItemsSource = list;
tabPage.Content = view;
if (scrollTargetEntry.RID > 0)
{
ScrollItemIntoView(view, scrollTargetEntry);
}
return true;
}
struct MemberRefEntry
{
readonly MetadataFile metadataFile;
readonly MemberReferenceHandle handle;
readonly MemberReference memberRef;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.MemberRef)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.MemberRef) * (RID - 1);
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Parent => MetadataTokens.GetToken(memberRef.Parent);
public void OnParentClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, memberRef.Parent, protocol: "metadata"));
}
string parentTooltip;
public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, memberRef.Parent);
public string Name => metadataFile.Metadata.GetString(memberRef.Name);
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(memberRef.Name):X} \"{Name}\"";
[ColumnInfo("X8", Kind = ColumnKind.HeapOffset)]
public int Signature => MetadataTokens.GetHeapOffset(memberRef.Signature);
string signatureTooltip;
public string SignatureTooltip => GenerateTooltip(ref signatureTooltip, metadataFile, handle);
public MemberRefEntry(MetadataFile metadataFile, MemberReferenceHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.memberRef = metadataFile.Metadata.GetMemberReference(handle);
this.signatureTooltip = null;
this.parentTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "MemberRefs");
}
}
}
| ILSpy/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/MemberRefTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1313
} | 268 |
<Control x:Class="ICSharpCode.ILSpy.Metadata.FlagsTooltip"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ICSharpCode.ILSpy.Metadata"
x:Name="root"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Control.Resources>
<local:NullVisibilityConverter x:Key="nullVisConv" />
<DataTemplate DataType="{x:Type local:MultipleChoiceGroup}">
<StackPanel Orientation="Vertical" Margin="3">
<TextBlock Text="{Binding Header}" FontWeight="Bold" Margin="0 0 0 3" Visibility="{Binding Header, Converter={StaticResource nullVisConv}}" />
<ListBox ItemsSource="{Binding Flags}" BorderThickness="0" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox DockPanel.Dock="Left" Margin="3,2" Content="{Binding Name}" IsChecked="{Binding IsSelected, Mode=OneWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:SingleChoiceGroup}">
<StackPanel Orientation="Horizontal" Margin="3">
<TextBlock Text="{Binding Header}" FontWeight="Bold" Visibility="{Binding Header, Converter={StaticResource nullVisConv}}" />
<TextBlock Text="{Binding SelectedFlag.Name}" />
</StackPanel>
</DataTemplate>
</Control.Resources>
<Control.Template>
<ControlTemplate>
<ItemsControl ItemsSource="{Binding Groups, ElementName=root}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ControlTemplate>
</Control.Template>
</Control>
| ILSpy/ILSpy/Metadata/FlagsTooltip.xaml/0 | {
"file_path": "ILSpy/ILSpy/Metadata/FlagsTooltip.xaml",
"repo_id": "ILSpy",
"token_count": 706
} | 269 |
// Copyright (c) 2021 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.ViewModels;
namespace ICSharpCode.ILSpy.Metadata
{
class MetadataTablesTreeNode : ILSpyTreeNode
{
readonly MetadataFile metadataFile;
public MetadataTablesTreeNode(MetadataFile metadataFile)
{
this.metadataFile = metadataFile;
this.LazyLoading = true;
}
public override object Text => "Tables";
public override object Icon => Images.MetadataTableGroup;
protected override void LoadChildren()
{
foreach (var table in Enum.GetValues<TableIndex>())
{
if (ShowTable(table, metadataFile.Metadata))
this.Children.Add(CreateTableTreeNode(table, metadataFile));
}
}
internal static bool ShowTable(TableIndex table, MetadataReader metadata) => !MainWindow.Instance.CurrentDisplaySettings.HideEmptyMetadataTables || metadata.GetTableRowCount(table) > 0;
internal static MetadataTableTreeNode CreateTableTreeNode(TableIndex table, MetadataFile metadataFile)
{
switch (table)
{
case TableIndex.Module:
return new ModuleTableTreeNode(metadataFile);
case TableIndex.TypeRef:
return new TypeRefTableTreeNode(metadataFile);
case TableIndex.TypeDef:
return new TypeDefTableTreeNode(metadataFile);
case TableIndex.Field:
return new FieldTableTreeNode(metadataFile);
case TableIndex.MethodDef:
return new MethodTableTreeNode(metadataFile);
case TableIndex.Param:
return new ParamTableTreeNode(metadataFile);
case TableIndex.InterfaceImpl:
return new InterfaceImplTableTreeNode(metadataFile);
case TableIndex.MemberRef:
return new MemberRefTableTreeNode(metadataFile);
case TableIndex.Constant:
return new ConstantTableTreeNode(metadataFile);
case TableIndex.CustomAttribute:
return new CustomAttributeTableTreeNode(metadataFile);
case TableIndex.FieldMarshal:
return new FieldMarshalTableTreeNode(metadataFile);
case TableIndex.DeclSecurity:
return new DeclSecurityTableTreeNode(metadataFile);
case TableIndex.ClassLayout:
return new ClassLayoutTableTreeNode(metadataFile);
case TableIndex.FieldLayout:
return new FieldLayoutTableTreeNode(metadataFile);
case TableIndex.StandAloneSig:
return new StandAloneSigTableTreeNode(metadataFile);
case TableIndex.EventMap:
return new EventMapTableTreeNode(metadataFile);
case TableIndex.Event:
return new EventTableTreeNode(metadataFile);
case TableIndex.PropertyMap:
return new PropertyMapTableTreeNode(metadataFile);
case TableIndex.Property:
return new PropertyTableTreeNode(metadataFile);
case TableIndex.MethodSemantics:
return new MethodSemanticsTableTreeNode(metadataFile);
case TableIndex.MethodImpl:
return new MethodImplTableTreeNode(metadataFile);
case TableIndex.ModuleRef:
return new ModuleRefTableTreeNode(metadataFile);
case TableIndex.TypeSpec:
return new TypeSpecTableTreeNode(metadataFile);
case TableIndex.ImplMap:
return new ImplMapTableTreeNode(metadataFile);
case TableIndex.FieldRva:
return new FieldRVATableTreeNode(metadataFile);
case TableIndex.Assembly:
return new AssemblyTableTreeNode(metadataFile);
case TableIndex.AssemblyRef:
return new AssemblyRefTableTreeNode(metadataFile);
case TableIndex.File:
return new FileTableTreeNode(metadataFile);
case TableIndex.ExportedType:
return new ExportedTypeTableTreeNode(metadataFile);
case TableIndex.ManifestResource:
return new ManifestResourceTableTreeNode(metadataFile);
case TableIndex.NestedClass:
return new NestedClassTableTreeNode(metadataFile);
case TableIndex.GenericParam:
return new GenericParamTableTreeNode(metadataFile);
case TableIndex.MethodSpec:
return new MethodSpecTableTreeNode(metadataFile);
case TableIndex.GenericParamConstraint:
return new GenericParamConstraintTableTreeNode(metadataFile);
case TableIndex.Document:
return new DocumentTableTreeNode(metadataFile);
case TableIndex.MethodDebugInformation:
return new MethodDebugInformationTableTreeNode(metadataFile);
case TableIndex.LocalScope:
return new LocalScopeTableTreeNode(metadataFile);
case TableIndex.LocalVariable:
return new LocalVariableTableTreeNode(metadataFile);
case TableIndex.LocalConstant:
return new LocalConstantTableTreeNode(metadataFile);
case TableIndex.ImportScope:
return new ImportScopeTableTreeNode(metadataFile);
case TableIndex.StateMachineMethod:
return new StateMachineMethodTableTreeNode(metadataFile);
case TableIndex.CustomDebugInformation:
return new CustomDebugInformationTableTreeNode(metadataFile);
default:
throw new ArgumentException($"Unsupported table index: {table}");
}
}
public override bool View(TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
return false;
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "Metadata Tables");
}
}
}
| ILSpy/ILSpy/Metadata/MetadataTablesTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/MetadataTablesTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 2051
} | 270 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Xml.Linq;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpyX.Settings;
namespace ICSharpCode.ILSpy.Options
{
public class TabItemViewModel
{
public TabItemViewModel(string header, UIElement content)
{
Header = header;
Content = content;
}
public string Header { get; }
public UIElement Content { get; }
}
/// <summary>
/// Interaction logic for OptionsDialog.xaml
/// </summary>
public partial class OptionsDialog : Window
{
readonly Lazy<UIElement, IOptionsMetadata>[] optionPages;
public OptionsDialog()
{
InitializeComponent();
// These used to have [ImportMany(..., RequiredCreationPolicy = CreationPolicy.NonShared)], so they use their own
// ExportProvider instance.
// FIXME: Ideally, the export provider should be disposed when it's no longer needed.
var ep = App.ExportProviderFactory.CreateExportProvider();
this.optionPages = ep.GetExports<UIElement, IOptionsMetadata>("OptionPages").ToArray();
ILSpySettings settings = ILSpySettings.Load();
foreach (var optionPage in optionPages.OrderBy(p => p.Metadata.Order))
{
var tabItem = new TabItemViewModel(MainWindow.GetResourceString(optionPage.Metadata.Title), optionPage.Value);
tabControl.Items.Add(tabItem);
IOptionPage page = optionPage.Value as IOptionPage;
if (page != null)
page.Load(settings);
}
}
void OKButton_Click(object sender, RoutedEventArgs e)
{
ILSpySettings.Update(
delegate (XElement root) {
foreach (var optionPage in optionPages)
{
IOptionPage page = optionPage.Value as IOptionPage;
if (page != null)
page.Save(root);
}
});
this.DialogResult = true;
Close();
}
private void DefaultsButton_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show(Properties.Resources.ResetToDefaultsConfirmationMessage, "ILSpy", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
var page = tabControl.SelectedValue as IOptionPage;
if (page != null)
page.LoadDefaults();
}
}
}
public interface IOptionsMetadata
{
string Title { get; }
int Order { get; }
}
public interface IOptionPage
{
void Load(ILSpySettings settings);
void Save(XElement root);
void LoadDefaults();
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportOptionPageAttribute : ExportAttribute
{
public ExportOptionPageAttribute() : base("OptionPages", typeof(UIElement))
{ }
public string Title { get; set; }
public int Order { get; set; }
}
[ExportMainMenuCommand(ParentMenuID = nameof(Resources._View), Header = nameof(Resources._Options), MenuCategory = nameof(Resources.Options), MenuOrder = 999)]
sealed class ShowOptionsCommand : SimpleCommand
{
public override void Execute(object parameter)
{
OptionsDialog dlg = new OptionsDialog();
dlg.Owner = MainWindow.Instance;
if (dlg.ShowDialog() == true)
{
new RefreshCommand().Execute(parameter);
}
}
}
} | ILSpy/ILSpy/Options/OptionsDialog.xaml.cs/0 | {
"file_path": "ILSpy/ILSpy/Options/OptionsDialog.xaml.cs",
"repo_id": "ILSpy",
"token_count": 1406
} | 271 |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
namespace ICSharpCode.ILSpy.TextView
{
/// <summary>
/// Allows language specific search for matching brackets.
/// </summary>
public interface IBracketSearcher
{
/// <summary>
/// Searches for a matching bracket from the given offset to the start of the document.
/// </summary>
/// <returns>A BracketSearchResult that contains the positions and lengths of the brackets. Return null if there is nothing to highlight.</returns>
BracketSearchResult SearchBracket(IDocument document, int offset);
}
public class DefaultBracketSearcher : IBracketSearcher
{
public static readonly DefaultBracketSearcher DefaultInstance = new DefaultBracketSearcher();
public BracketSearchResult SearchBracket(IDocument document, int offset)
{
return null;
}
}
/// <summary>
/// Describes a pair of matching brackets found by <see cref="IBracketSearcher"/>.
/// </summary>
public class BracketSearchResult
{
public int OpeningBracketOffset { get; private set; }
public int OpeningBracketLength { get; private set; }
public int ClosingBracketOffset { get; private set; }
public int ClosingBracketLength { get; private set; }
public BracketSearchResult(int openingBracketOffset, int openingBracketLength,
int closingBracketOffset, int closingBracketLength)
{
this.OpeningBracketOffset = openingBracketOffset;
this.OpeningBracketLength = openingBracketLength;
this.ClosingBracketOffset = closingBracketOffset;
this.ClosingBracketLength = closingBracketLength;
}
}
public class BracketHighlightRenderer : IBackgroundRenderer
{
BracketSearchResult result;
Pen borderPen;
Brush backgroundBrush;
ICSharpCode.AvalonEdit.Rendering.TextView textView;
public void SetHighlight(BracketSearchResult result)
{
if (this.result != result)
{
this.result = result;
this.borderPen = (Pen)textView.FindResource(Themes.ResourceKeys.BracketHighlightBorderPen);
this.backgroundBrush = (SolidColorBrush)textView.FindResource(Themes.ResourceKeys.BracketHighlightBackgroundBrush);
textView.InvalidateLayer(this.Layer);
}
}
public BracketHighlightRenderer(ICSharpCode.AvalonEdit.Rendering.TextView textView)
{
if (textView == null)
throw new ArgumentNullException("textView");
this.borderPen = (Pen)textView.FindResource(Themes.ResourceKeys.BracketHighlightBorderPen);
this.backgroundBrush = (SolidColorBrush)textView.FindResource(Themes.ResourceKeys.BracketHighlightBackgroundBrush);
this.textView = textView;
this.textView.BackgroundRenderers.Add(this);
}
public KnownLayer Layer {
get {
return KnownLayer.Selection;
}
}
public void Draw(ICSharpCode.AvalonEdit.Rendering.TextView textView, DrawingContext drawingContext)
{
if (this.result == null)
return;
BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder();
builder.CornerRadius = 1;
builder.AlignToWholePixels = true;
builder.BorderThickness = borderPen?.Thickness ?? 0;
builder.AddSegment(textView, new TextSegment() { StartOffset = result.OpeningBracketOffset, Length = result.OpeningBracketLength });
builder.CloseFigure(); // prevent connecting the two segments
builder.AddSegment(textView, new TextSegment() { StartOffset = result.ClosingBracketOffset, Length = result.ClosingBracketLength });
Geometry geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(backgroundBrush, borderPen, geometry);
}
}
}
} | ILSpy/ILSpy/TextView/BracketHighlightRenderer.cs/0 | {
"file_path": "ILSpy/ILSpy/TextView/BracketHighlightRenderer.cs",
"repo_id": "ILSpy",
"token_count": 1463
} | 272 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:styles="urn:TomsToolbox.Wpf.Styles"
xmlns:themes="clr-namespace:ICSharpCode.ILSpy.Themes">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/AvalonDock.Themes.VS2013;component/darktheme.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.TextBackgroundBrush}" Color="Black" />
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.TextForegroundBrush}" Color="White" />
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.SearchResultBackgroundBrush}" Color="#995A23" />
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.LineNumbersForegroundBrush}" Color="Gray" />
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.CurrentLineBackgroundBrush}" Color="#1614DCE0" />
<Pen x:Key="{x:Static themes:ResourceKeys.CurrentLineBorderPen}" Brush="#3400FF6E" Thickness="1" />
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.BracketHighlightBackgroundBrush}" Color="#443399FF" />
<Pen x:Key="{x:Static themes:ResourceKeys.BracketHighlightBorderPen}" Brush="#883399FF" Thickness="1" />
<Color x:Key="{x:Static SystemColors.ControlLightLightColorKey}">#333337</Color>
<Color x:Key="{x:Static SystemColors.ControlLightColorKey}">#464646</Color>
<Color x:Key="{x:Static SystemColors.ControlColorKey}">#252526</Color>
<Color x:Key="{x:Static SystemColors.ControlDarkColorKey}">#686868</Color>
<Color x:Key="{x:Static SystemColors.ControlDarkDarkColorKey}">#9E9E9E</Color>
<Color x:Key="{x:Static SystemColors.ControlTextColorKey}">#F1F1F1</Color>
<Color x:Key="{x:Static SystemColors.GrayTextColorKey}">#999999</Color>
<Color x:Key="{x:Static SystemColors.HighlightColorKey}">#3399FF</Color>
<Color x:Key="{x:Static SystemColors.HighlightTextColorKey}">#FFFFFF</Color>
<Color x:Key="{x:Static SystemColors.InfoTextColorKey}">#F1F1F1</Color>
<Color x:Key="{x:Static SystemColors.InfoColorKey}">#333337</Color>
<Color x:Key="{x:Static SystemColors.MenuColorKey}">#1B1B1C</Color>
<Color x:Key="{x:Static SystemColors.MenuBarColorKey}">#1B1B1C</Color>
<Color x:Key="{x:Static SystemColors.MenuTextColorKey}">#F1F1F1</Color>
<Color x:Key="{x:Static SystemColors.WindowColorKey}">#333337</Color>
<Color x:Key="{x:Static SystemColors.WindowTextColorKey}">#F1F1F1</Color>
<Color x:Key="{x:Static SystemColors.ActiveCaptionColorKey}">#2D2D30</Color>
<Color x:Key="{x:Static SystemColors.ActiveBorderColorKey}">#007ACC</Color>
<Color x:Key="{x:Static SystemColors.ActiveCaptionTextColorKey}">#F1F1F1</Color>
<Color x:Key="{x:Static SystemColors.InactiveCaptionColorKey}">#2D2D30</Color>
<Color x:Key="{x:Static SystemColors.InactiveBorderColorKey}">#434346</Color>
<Color x:Key="{x:Static SystemColors.InactiveCaptionTextColorKey}">#808080</Color>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlLightLightBrushKey}" Color="#333337" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlLightBrushKey}" Color="#464646" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#252526" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkBrushKey}" Color="#686868" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlDarkDarkBrushKey}" Color="#9E9E9E" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="#F1F1F1" />
<SolidColorBrush x:Key="{x:Static SystemColors.GrayTextBrushKey}" Color="#999999" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#3399FF" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="#FFFFFF" />
<SolidColorBrush x:Key="{x:Static SystemColors.InfoTextBrushKey}" Color="#F1F1F1" />
<SolidColorBrush x:Key="{x:Static SystemColors.InfoBrushKey}" Color="#333337" />
<SolidColorBrush x:Key="{x:Static SystemColors.MenuBrushKey}" Color="#1B1B1C" />
<SolidColorBrush x:Key="{x:Static SystemColors.MenuBarBrushKey}" Color="#1B1B1C" />
<SolidColorBrush x:Key="{x:Static SystemColors.MenuTextBrushKey}" Color="#F1F1F1" />
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="#333337" />
<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="#F1F1F1" />
<SolidColorBrush x:Key="{x:Static SystemColors.ActiveCaptionBrushKey}" Color="#2D2D30" />
<SolidColorBrush x:Key="{x:Static SystemColors.ActiveBorderBrushKey}" Color="#007ACC" />
<SolidColorBrush x:Key="{x:Static SystemColors.ActiveCaptionTextBrushKey}" Color="#F1F1F1" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveCaptionBrushKey}" Color="#2D2D30" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveBorderBrushKey}" Color="#434346" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveCaptionTextBrushKey}" Color="#808080" />
<SolidColorBrush x:Key="{x:Static styles:ResourceKeys.BorderBrush}" Color="#464646" />
<SolidColorBrush x:Key="{x:Static styles:ResourceKeys.DisabledBrush}" Color="#2D2D30" />
<Color x:Key="{x:Static themes:ResourceKeys.TextMarkerBackgroundColor}">MediumVioletRed</Color>
<SolidColorBrush x:Key="{x:Static themes:ResourceKeys.LinkTextForegroundBrush}">CornflowerBlue</SolidColorBrush>
<styles:InvertGrayEffect x:Key="{x:Static themes:ResourceKeys.ThemeAwareButtonEffect}" />
</ResourceDictionary>
| ILSpy/ILSpy/Themes/Base.Dark.xaml/0 | {
"file_path": "ILSpy/ILSpy/Themes/Base.Dark.xaml",
"repo_id": "ILSpy",
"token_count": 2041
} | 273 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp.ProjectDecompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpy.Metadata;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpy.ViewModels;
using ICSharpCode.ILSpyX;
using ICSharpCode.ILSpyX.PdbProvider;
using ICSharpCode.TreeView;
using Microsoft.Win32;
using TypeDefinitionHandle = System.Reflection.Metadata.TypeDefinitionHandle;
namespace ICSharpCode.ILSpy.TreeNodes
{
/// <summary>
/// Tree node representing an assembly.
/// This class is responsible for loading both namespace and type nodes.
/// </summary>
public sealed class AssemblyTreeNode : ILSpyTreeNode
{
readonly Dictionary<string, NamespaceTreeNode> namespaces = new Dictionary<string, NamespaceTreeNode>();
readonly Dictionary<TypeDefinitionHandle, TypeTreeNode> typeDict = new Dictionary<TypeDefinitionHandle, TypeTreeNode>();
ICompilation typeSystem;
public AssemblyTreeNode(LoadedAssembly assembly) : this(assembly, null)
{
}
internal AssemblyTreeNode(LoadedAssembly assembly, PackageEntry packageEntry)
{
this.LoadedAssembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
this.LazyLoading = true;
this.PackageEntry = packageEntry;
Init();
}
public AssemblyList AssemblyList {
get { return LoadedAssembly.AssemblyList; }
}
public LoadedAssembly LoadedAssembly { get; }
/// <summary>
/// If this assembly was loaded from a bundle; this property returns the bundle entry that the
/// assembly was loaded from.
/// </summary>
public PackageEntry PackageEntry { get; }
public override bool IsAutoLoaded {
get {
return LoadedAssembly.IsAutoLoaded;
}
}
public override object Text => LoadedAssembly.Text;
public override object Icon {
get {
if (LoadedAssembly.IsLoaded)
{
if (LoadedAssembly.HasLoadError)
return Images.AssemblyWarning;
var loadResult = LoadedAssembly.GetLoadResultAsync().GetAwaiter().GetResult();
if (loadResult.Package != null)
{
return loadResult.Package.Kind switch {
LoadedPackage.PackageKind.Zip => Images.NuGet,
_ => Images.Library,
};
}
if (loadResult.MetadataFile != null)
{
return loadResult.MetadataFile.Kind switch {
MetadataFile.MetadataFileKind.PortableExecutable => Images.Assembly,
MetadataFile.MetadataFileKind.ProgramDebugDatabase => Images.ProgramDebugDatabase,
_ => Images.MetadataFile,
};
}
else
{
return Images.Assembly;
}
}
else
{
return Images.FindAssembly;
}
}
}
TextBlock tooltip;
public override object ToolTip {
get {
if (LoadedAssembly.HasLoadError)
return "Assembly could not be loaded. Click here for details.";
if (tooltip == null && LoadedAssembly.IsLoaded)
{
tooltip = new TextBlock();
var module = LoadedAssembly.GetPEFileOrNull();
var metadata = module?.Metadata;
if (metadata?.IsAssembly == true && metadata.TryGetFullAssemblyName(out var assemblyName))
{
tooltip.Inlines.Add(new Bold(new Run("Name: ")));
tooltip.Inlines.Add(new Run(assemblyName));
tooltip.Inlines.Add(new LineBreak());
}
tooltip.Inlines.Add(new Bold(new Run("Location: ")));
tooltip.Inlines.Add(new Run(LoadedAssembly.FileName));
if (module != null)
{
tooltip.Inlines.Add(new LineBreak());
tooltip.Inlines.Add(new Bold(new Run("Architecture: ")));
tooltip.Inlines.Add(new Run(Language.GetPlatformDisplayName(module)));
string runtimeName = Language.GetRuntimeDisplayName(module);
if (runtimeName != null)
{
tooltip.Inlines.Add(new LineBreak());
tooltip.Inlines.Add(new Bold(new Run("Runtime: ")));
tooltip.Inlines.Add(new Run(runtimeName));
}
var debugInfo = LoadedAssembly.GetDebugInfoOrNull();
tooltip.Inlines.Add(new LineBreak());
tooltip.Inlines.Add(new Bold(new Run("Debug info: ")));
tooltip.Inlines.Add(new Run(debugInfo?.Description ?? "none"));
}
}
return tooltip;
}
}
public override bool ShowExpander {
get { return !LoadedAssembly.HasLoadError; }
}
async void Init()
{
try
{
await this.LoadedAssembly.GetLoadResultAsync();
RaisePropertyChanged(nameof(Text)); // shortname might have changed
}
catch
{
RaisePropertyChanged(nameof(ShowExpander)); // cannot expand assemblies with load error
}
// change from "Loading" icon to final icon
RaisePropertyChanged(nameof(Icon));
RaisePropertyChanged(nameof(ExpandedIcon));
RaisePropertyChanged(nameof(ToolTip));
}
protected override void LoadChildren()
{
LoadedAssembly.LoadResult loadResult;
try
{
loadResult = LoadedAssembly.GetLoadResultAsync().GetAwaiter().GetResult();
}
catch
{
// if we crashed on loading, then we don't have any children
return;
}
try
{
if (loadResult.PEFile != null)
{
LoadChildrenForPEFile(loadResult.PEFile);
}
else if (loadResult.Package != null)
{
var package = loadResult.Package;
this.Children.AddRange(PackageFolderTreeNode.LoadChildrenForFolder(package.RootFolder));
}
else if (loadResult.MetadataFile != null)
{
var metadata = loadResult.MetadataFile;
this.Children.Add(new MetadataTablesTreeNode(metadata));
this.Children.Add(new StringHeapTreeNode(metadata));
this.Children.Add(new UserStringHeapTreeNode(metadata));
this.Children.Add(new GuidHeapTreeNode(metadata));
this.Children.Add(new BlobHeapTreeNode(metadata));
}
}
catch (Exception ex)
{
App.UnhandledException(ex);
}
}
void LoadChildrenForPEFile(PEFile module)
{
typeSystem = LoadedAssembly.GetTypeSystemOrNull();
var assembly = (MetadataModule)typeSystem.MainModule;
this.Children.Add(new MetadataTreeNode(module, Resources.Metadata));
Decompiler.DebugInfo.IDebugInfoProvider debugInfo = LoadedAssembly.GetDebugInfoOrNull();
if (debugInfo is PortableDebugInfoProvider ppdb
&& ppdb.GetMetadataReader() is System.Reflection.Metadata.MetadataReader reader)
{
this.Children.Add(new MetadataTreeNode(ppdb.ToMetadataFile(), $"Debug Metadata ({(ppdb.IsEmbedded ? "Embedded" : "From portable PDB")})"));
}
this.Children.Add(new ReferenceFolderTreeNode(module, this));
if (module.Resources.Any())
this.Children.Add(new ResourceListTreeNode(module));
foreach (NamespaceTreeNode ns in namespaces.Values)
{
ns.Children.Clear();
}
namespaces.Clear();
bool useNestedStructure = MainWindow.Instance.CurrentDisplaySettings.UseNestedNamespaceNodes;
foreach (var type in assembly.TopLevelTypeDefinitions.OrderBy(t => t.ReflectionName, NaturalStringComparer.Instance))
{
var ns = GetOrCreateNamespaceTreeNode(type.Namespace);
TypeTreeNode node = new TypeTreeNode(type, this);
typeDict[(TypeDefinitionHandle)type.MetadataToken] = node;
ns.Children.Add(node);
}
foreach (NamespaceTreeNode ns in namespaces.Values
.Where(ns => ns.Children.Count > 0 && ns.Parent == null)
.OrderBy(n => n.Name, NaturalStringComparer.Instance))
{
this.Children.Add(ns);
SetPublicAPI(ns);
}
NamespaceTreeNode GetOrCreateNamespaceTreeNode(string @namespace)
{
if (!namespaces.TryGetValue(@namespace, out NamespaceTreeNode ns))
{
if (useNestedStructure)
{
int decimalIndex = @namespace.LastIndexOf('.');
if (decimalIndex < 0)
{
var escapedNamespace = Language.EscapeName(@namespace);
ns = new NamespaceTreeNode(escapedNamespace);
}
else
{
var parentNamespaceTreeNode = GetOrCreateNamespaceTreeNode(@namespace.Substring(0, decimalIndex));
var escapedInnerNamespace = Language.EscapeName(@namespace.Substring(decimalIndex + 1));
ns = new NamespaceTreeNode(escapedInnerNamespace);
parentNamespaceTreeNode.Children.Add(ns);
}
}
else
{
var escapedNamespace = Language.EscapeName(@namespace);
ns = new NamespaceTreeNode(escapedNamespace);
}
namespaces.Add(@namespace, ns);
}
return ns;
}
}
private static void SetPublicAPI(NamespaceTreeNode ns)
{
foreach (NamespaceTreeNode innerNamespace in ns.Children.OfType<NamespaceTreeNode>())
{
SetPublicAPI(innerNamespace);
}
ns.SetPublicAPI(ns.Children.OfType<ILSpyTreeNode>().Any(n => n.IsPublicAPI));
}
/// <summary>
/// Finds the node for a top-level type.
/// </summary>
public TypeTreeNode FindTypeNode(ITypeDefinition type)
{
if (type == null)
return null;
EnsureLazyChildren();
TypeTreeNode node;
if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node))
return node;
else
return null;
}
/// <summary>
/// Finds the node for a namespace.
/// </summary>
public NamespaceTreeNode FindNamespaceNode(string namespaceName)
{
if (string.IsNullOrEmpty(namespaceName))
return null;
EnsureLazyChildren();
NamespaceTreeNode node;
if (namespaces.TryGetValue(namespaceName, out node))
return node;
else
return null;
}
public override bool CanDrag(SharpTreeNode[] nodes)
{
// prohibit dragging assemblies nested in nuget packages
return nodes.All(n => n is AssemblyTreeNode { PackageEntry: null });
}
public override void StartDrag(DependencyObject dragSource, SharpTreeNode[] nodes)
{
DragDrop.DoDragDrop(dragSource, Copy(nodes), DragDropEffects.All);
}
public override bool CanDelete()
{
// prohibit deleting assemblies nested in nuget packages
return PackageEntry == null;
}
public override void Delete()
{
DeleteCore();
}
public override void DeleteCore()
{
LoadedAssembly.AssemblyList.Unload(LoadedAssembly);
}
internal const string DataFormat = "ILSpyAssemblies";
public override IDataObject Copy(SharpTreeNode[] nodes)
{
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormat, nodes.OfType<AssemblyTreeNode>().Select(n => n.LoadedAssembly.FileName).ToArray());
return dataObject;
}
public override FilterResult Filter(FilterSettings settings)
{
if (settings.SearchTermMatches(LoadedAssembly.ShortName))
return FilterResult.Match;
else
return FilterResult.Recurse;
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
void HandleException(Exception ex, string message)
{
language.WriteCommentLine(output, message);
output.WriteLine();
output.MarkFoldStart("Exception details", true);
output.Write(ex.ToString());
output.MarkFoldEnd();
}
try
{
var loadResult = LoadedAssembly.GetLoadResultAsync().GetAwaiter().GetResult();
if (loadResult.PEFile != null)
{
language.DecompileAssembly(LoadedAssembly, output, options);
}
else if (loadResult.Package != null)
{
output.WriteLine("// " + LoadedAssembly.FileName);
DecompilePackage(loadResult.Package, output);
}
else if (loadResult.MetadataFile != null)
{
output.WriteLine("// " + LoadedAssembly.FileName);
}
else
{
LoadedAssembly.GetPEFileOrNullAsync().GetAwaiter().GetResult();
}
}
catch (BadImageFormatException badImage)
{
HandleException(badImage, "This file does not contain a managed assembly.");
}
catch (FileNotFoundException fileNotFound) when (options.SaveAsProjectDirectory == null)
{
HandleException(fileNotFound, "The file was not found.");
}
catch (DirectoryNotFoundException dirNotFound) when (options.SaveAsProjectDirectory == null)
{
HandleException(dirNotFound, "The directory was not found.");
}
catch (PEFileNotSupportedException notSupported)
{
HandleException(notSupported, notSupported.Message);
}
}
private void DecompilePackage(LoadedPackage package, ITextOutput output)
{
switch (package.Kind)
{
case LoadedPackage.PackageKind.Zip:
output.WriteLine("// File format: .zip file");
break;
case LoadedPackage.PackageKind.Bundle:
var header = package.BundleHeader;
output.WriteLine($"// File format: .NET bundle {header.MajorVersion}.{header.MinorVersion}");
break;
}
output.WriteLine();
output.WriteLine("Entries:");
foreach (var entry in package.Entries)
{
output.WriteLine($" {entry.Name} ({entry.TryGetLength()} bytes)");
}
}
public override bool Save(TabPageModel tabPage)
{
if (!LoadedAssembly.IsLoadedAsValidAssembly)
return false;
Language language = this.Language;
if (string.IsNullOrEmpty(language.ProjectFileExtension))
return false;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = WholeProjectDecompiler.CleanUpFileName(LoadedAssembly.ShortName) + language.ProjectFileExtension;
dlg.Filter = language.Name + " project|*" + language.ProjectFileExtension + "|" + language.Name + " single file|*" + language.FileExtension + "|All files|*.*";
if (dlg.ShowDialog() == true)
{
DecompilationOptions options = MainWindow.Instance.CreateDecompilationOptions();
options.FullDecompilation = true;
if (dlg.FilterIndex == 1)
{
options.SaveAsProjectDirectory = Path.GetDirectoryName(dlg.FileName);
foreach (string entry in Directory.GetFileSystemEntries(options.SaveAsProjectDirectory))
{
if (!string.Equals(entry, dlg.FileName, StringComparison.OrdinalIgnoreCase))
{
var result = MessageBox.Show(
Resources.AssemblySaveCodeDirectoryNotEmpty,
Resources.AssemblySaveCodeDirectoryNotEmptyTitle,
MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (result == MessageBoxResult.No)
return true; // don't save, but mark the Save operation as handled
break;
}
}
}
tabPage.ShowTextView(textView => textView.SaveToDisk(language, new[] { this }, options, dlg.FileName));
}
return true;
}
public override string ToString()
{
// ToString is used by FindNodeByPath/GetPathForNode
// Fixes #821 - Reload All Assemblies Should Point to the Correct Assembly
return LoadedAssembly.FileName;
}
}
[ExportContextMenuEntry(Header = nameof(Resources._Remove), Icon = "images/Delete")]
sealed class RemoveAssembly : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var node in context.SelectedTreeNodes)
{
node.Delete();
}
}
}
[ExportContextMenuEntry(Header = nameof(Resources._Reload), Icon = "images/Refresh")]
sealed class ReloadAssembly : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
var paths = new List<string[]>();
using (context.TreeView.LockUpdates())
{
foreach (var node in context.SelectedTreeNodes)
{
paths.Add(MainWindow.GetPathForNode(node));
var la = ((AssemblyTreeNode)node).LoadedAssembly;
la.AssemblyList.ReloadAssembly(la.FileName);
}
}
MainWindow.Instance.SelectNodes(paths.Select(p => MainWindow.Instance.FindNodeByPath(p, true)).ToArray());
MainWindow.Instance.RefreshDecompiledView();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._LoadDependencies), Category = nameof(Resources.Dependencies))]
sealed class LoadDependencies : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode asm && asm.LoadedAssembly.IsLoadedAsValidAssembly);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public async void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
var tasks = new List<Task>();
foreach (var node in context.SelectedTreeNodes)
{
var la = ((AssemblyTreeNode)node).LoadedAssembly;
var resolver = la.GetAssemblyResolver();
var module = la.GetPEFileOrNull();
if (module != null)
{
var metadata = module.Metadata;
foreach (var assyRef in metadata.AssemblyReferences)
{
tasks.Add(resolver.ResolveAsync(new AssemblyReference(module, assyRef)));
}
}
}
await Task.WhenAll(tasks);
MainWindow.Instance.RefreshDecompiledView();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._AddMainList), Category = nameof(Resources.Dependencies))]
sealed class AddToMainList : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.Where(n => n is AssemblyTreeNode).Any(n => ((AssemblyTreeNode)n).IsAutoLoaded);
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.Any(n => n is AssemblyTreeNode);
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var node in context.SelectedTreeNodes)
{
var loadedAssm = ((AssemblyTreeNode)node).LoadedAssembly;
if (!loadedAssm.HasLoadError)
{
loadedAssm.IsAutoLoaded = false;
node.RaisePropertyChanged(nameof(ILSpyTreeNode.IsAutoLoaded));
}
}
MainWindow.Instance.CurrentAssemblyList.RefreshSave();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._OpenContainingFolder), Category = nameof(Resources.Shell))]
sealed class OpenContainingFolder : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
internal static AssemblyTreeNode GetAssemblyTreeNode(SharpTreeNode node)
{
while (node != null)
{
if (node is AssemblyTreeNode a)
return a;
node = node.Parent;
}
return null;
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var n in context.SelectedTreeNodes)
{
var node = GetAssemblyTreeNode(n);
var path = node.LoadedAssembly.FileName;
if (File.Exists(path))
{
MainWindow.ExecuteCommand("explorer.exe", $"/select,\"{path}\"");
}
}
}
}
[ExportContextMenuEntry(Header = nameof(Resources._OpenCommandLineHere), Category = nameof(Resources.Shell))]
sealed class OpenCmdHere : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = OpenContainingFolder.GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = OpenContainingFolder.GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var n in context.SelectedTreeNodes)
{
var node = OpenContainingFolder.GetAssemblyTreeNode(n);
var path = Path.GetDirectoryName(node.LoadedAssembly.FileName);
if (Directory.Exists(path))
{
MainWindow.ExecuteCommand("cmd.exe", $"/k \"cd {path}\"");
}
}
}
}
}
| ILSpy/ILSpy/TreeNodes/AssemblyTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/AssemblyTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 8113
} | 274 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpyX;
using ICSharpCode.TreeView;
namespace ICSharpCode.ILSpy.TreeNodes
{
/// <summary>
/// Lists the embedded resources in an assembly.
/// </summary>
sealed class PackageFolderTreeNode : ILSpyTreeNode
{
readonly PackageFolder folder;
public PackageFolderTreeNode(PackageFolder folder, string text = null)
{
this.folder = folder;
this.Text = text ?? folder.Name;
this.LazyLoading = true;
}
public override object Text { get; }
public override object Icon => Images.FolderClosed;
public override object ExpandedIcon => Images.FolderOpen;
protected override void LoadChildren()
{
this.Children.AddRange(LoadChildrenForFolder(folder));
}
internal static IEnumerable<SharpTreeNode> LoadChildrenForFolder(PackageFolder root)
{
foreach (var folder in root.Folders.OrderBy(f => f.Name))
{
string newName = folder.Name;
var subfolder = folder;
while (subfolder.Folders.Count == 1 && subfolder.Entries.Count == 0)
{
// special case: a folder that only contains a single sub-folder
subfolder = subfolder.Folders[0];
newName = $"{newName}/{subfolder.Name}";
}
yield return new PackageFolderTreeNode(subfolder, newName);
}
foreach (var entry in root.Entries.OrderBy(e => e.Name))
{
if (entry.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
var asm = root.ResolveFileName(entry.Name);
if (asm != null)
{
yield return new AssemblyTreeNode(asm, entry);
}
else
{
yield return ResourceTreeNode.Create(entry);
}
}
else
{
yield return ResourceTreeNode.Create(entry);
}
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
}
}
}
| ILSpy/ILSpy/TreeNodes/PackageFolderTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/PackageFolderTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1008
} | 275 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
using System.Windows.Media;
using ICSharpCode.Decompiler;
using SRM = System.Reflection.Metadata;
namespace ICSharpCode.ILSpy.TreeNodes
{
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpyX;
public sealed class TypeTreeNode : ILSpyTreeNode, IMemberTreeNode
{
public TypeTreeNode(ITypeDefinition typeDefinition, AssemblyTreeNode parentAssemblyNode)
{
this.ParentAssemblyNode = parentAssemblyNode ?? throw new ArgumentNullException(nameof(parentAssemblyNode));
this.TypeDefinition = typeDefinition ?? throw new ArgumentNullException(nameof(typeDefinition));
this.LazyLoading = true;
}
public ITypeDefinition TypeDefinition { get; }
public AssemblyTreeNode ParentAssemblyNode { get; }
public override object Text => this.Language.TypeToString(GetTypeDefinition(), includeNamespace: false)
+ GetSuffixString(TypeDefinition.MetadataToken);
private ITypeDefinition GetTypeDefinition()
{
return ((MetadataModule)ParentAssemblyNode.LoadedAssembly
.GetPEFileOrNull()
?.GetTypeSystemWithCurrentOptionsOrNull()
?.MainModule).GetDefinition((SRM.TypeDefinitionHandle)TypeDefinition.MetadataToken);
}
public override bool IsPublicAPI {
get {
switch (GetTypeDefinition().Accessibility)
{
case Accessibility.Public:
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
return true;
default:
return false;
}
}
}
public override FilterResult Filter(FilterSettings settings)
{
if (settings.ShowApiLevel == ApiVisibility.PublicOnly && !IsPublicAPI)
return FilterResult.Hidden;
if (settings.SearchTermMatches(TypeDefinition.Name))
{
if (settings.ShowApiLevel == ApiVisibility.All || settings.Language.ShowMember(TypeDefinition))
return FilterResult.Match;
else
return FilterResult.Hidden;
}
else
{
return FilterResult.Recurse;
}
}
protected override void LoadChildren()
{
if (TypeDefinition.DirectBaseTypes.Any())
this.Children.Add(new BaseTypesTreeNode(ParentAssemblyNode.LoadedAssembly.GetPEFileOrNull(), TypeDefinition));
if (!TypeDefinition.IsSealed)
this.Children.Add(new DerivedTypesTreeNode(ParentAssemblyNode.AssemblyList, TypeDefinition));
foreach (var nestedType in TypeDefinition.NestedTypes.OrderBy(t => t.Name, NaturalStringComparer.Instance))
{
this.Children.Add(new TypeTreeNode(nestedType, ParentAssemblyNode));
}
if (TypeDefinition.Kind == TypeKind.Enum)
{
// if the type is an enum, it's better to not sort by field name.
foreach (var field in TypeDefinition.Fields)
{
this.Children.Add(new FieldTreeNode(field));
}
}
else
{
foreach (var field in TypeDefinition.Fields.OrderBy(f => f.Name, NaturalStringComparer.Instance))
{
this.Children.Add(new FieldTreeNode(field));
}
}
foreach (var property in TypeDefinition.Properties.OrderBy(p => p.Name, NaturalStringComparer.Instance))
{
this.Children.Add(new PropertyTreeNode(property));
}
foreach (var ev in TypeDefinition.Events.OrderBy(e => e.Name, NaturalStringComparer.Instance))
{
this.Children.Add(new EventTreeNode(ev));
}
foreach (var method in TypeDefinition.Methods.OrderBy(m => m.Name, NaturalStringComparer.Instance))
{
if (method.MetadataToken.IsNil)
continue;
this.Children.Add(new MethodTreeNode(method));
}
}
public override bool CanExpandRecursively => true;
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.DecompileType(GetTypeDefinition(), output, options);
}
public override object Icon => GetIcon(TypeDefinition);
public static ImageSource GetIcon(ITypeDefinition type)
{
return Images.GetIcon(GetTypeIcon(type, out bool isStatic), GetOverlayIcon(type), isStatic);
}
internal static TypeIcon GetTypeIcon(IType type, out bool isStatic)
{
isStatic = false;
switch (type.Kind)
{
case TypeKind.Interface:
return TypeIcon.Interface;
case TypeKind.Struct:
case TypeKind.Void:
return TypeIcon.Struct;
case TypeKind.Delegate:
return TypeIcon.Delegate;
case TypeKind.Enum:
return TypeIcon.Enum;
default:
isStatic = type.GetDefinition()?.IsStatic == true;
return TypeIcon.Class;
}
}
static AccessOverlayIcon GetOverlayIcon(ITypeDefinition type)
{
switch (type.Accessibility)
{
case Accessibility.Public:
return AccessOverlayIcon.Public;
case Accessibility.Internal:
return AccessOverlayIcon.Internal;
case Accessibility.ProtectedAndInternal:
return AccessOverlayIcon.PrivateProtected;
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
return AccessOverlayIcon.Protected;
case Accessibility.Private:
return AccessOverlayIcon.Private;
default:
return AccessOverlayIcon.CompilerControlled;
}
}
IEntity IMemberTreeNode.Member => TypeDefinition;
public override string ToString()
{
return TypeDefinition.ReflectionName;
}
}
}
| ILSpy/ILSpy/TreeNodes/TypeTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/TypeTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 2110
} | 276 |
using System.Windows;
using System.Windows.Controls;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Interaction logic for Create.xaml
/// </summary>
public partial class CreateListDialog : Window
{
public CreateListDialog(string title)
{
InitializeComponent();
this.Title = title;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
okButton.IsEnabled = !string.IsNullOrWhiteSpace(ListNameBox.Text);
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(ListNameBox.Text))
{
this.DialogResult = true;
}
}
public string ListName {
get => ListNameBox.Text;
set => ListNameBox.Text = value;
}
}
} | ILSpy/ILSpy/Views/CreateListDialog.xaml.cs/0 | {
"file_path": "ILSpy/ILSpy/Views/CreateListDialog.xaml.cs",
"repo_id": "ILSpy",
"token_count": 268
} | 277 |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under MIT X11 license (for details please see \doc\license.txt)
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.ILSpy;
namespace TestPlugin
{
[Export(typeof(IAboutPageAddition))]
public class AboutPageAddition : IAboutPageAddition
{
public void Write(ISmartTextOutput textOutput)
{
textOutput.WriteLine();
textOutput.Write("This is a test.");
textOutput.WriteLine();
textOutput.WriteLine();
textOutput.BeginSpan(new HighlightingColor {
Background = new SimpleHighlightingBrush(Colors.Black),
FontStyle = FontStyles.Italic,
Foreground = new SimpleHighlightingBrush(Colors.Aquamarine)
});
textOutput.Write("DO NOT PRESS THIS BUTTON --> ");
textOutput.AddButton(null, "Test!", (sender, args) => MessageBox.Show("Naughty Naughty!", "Naughty!", MessageBoxButton.OK, MessageBoxImage.Exclamation));
textOutput.Write(" <--");
textOutput.WriteLine();
textOutput.EndSpan();
textOutput.WriteLine();
}
}
}
| ILSpy/TestPlugin/AboutPageAddition.cs/0 | {
"file_path": "ILSpy/TestPlugin/AboutPageAddition.cs",
"repo_id": "ILSpy",
"token_count": 407
} | 278 |
// 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 Unity.Collections;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEditor.U2D.SpritePacking
{
[RequiredByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct SpritePackInfoInternal
{
public int guid;
public int texIndex;
public int indexCount;
public int vertexCount;
public RectInt rect;
public IntPtr indices;
public IntPtr vertices;
};
[RequiredByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct SpritePackTextureInfoInternal
{
public int width;
public int height;
public IntPtr buffer;
};
[RequiredByNativeCode]
[StructLayout(LayoutKind.Sequential)]
internal struct SpritePackDatasetInternal
{
public SpritePackInfoInternal spriteData;
public SpritePackTextureInfoInternal textureData;
};
[StructLayout(LayoutKind.Sequential)]
internal struct SpritePackInfo
{
public int guid;
public int texIndex;
public int indexCount;
public int vertexCount;
public RectInt rect;
public NativeArray<int> indices;
public NativeArray<Vector3> vertices;
};
[StructLayout(LayoutKind.Sequential)]
internal struct SpritePackTextureInfo
{
public int width;
public int height;
public NativeArray<Color32> buffer;
};
internal struct SpritePackDataset
{
public List<SpritePackInfo> spriteData;
public List<SpritePackTextureInfo> textureData;
};
internal struct SpritePackConfig
{
public int padding;
};
[NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlas.h")]
[NativeHeader("Editor/Src/2D/SpriteAtlas/SpriteAtlasPackingUtilities.h")]
internal class SpritePackUtility
{
internal unsafe static SpritePackDataset PackCustomSpritesWrapper(SpritePackDataset input, SpritePackConfig packConfig, Allocator alloc)
{
var output = new SpritePackDataset();
var spriteCount = input.spriteData.Count;
if (0 == spriteCount)
return output;
var data = new NativeArray<SpritePackDatasetInternal>(spriteCount, Allocator.Temp, NativeArrayOptions.ClearMemory);
for (int i = 0; i < spriteCount; ++i)
{
SpritePackDatasetInternal rawData = data[i];
rawData.spriteData.guid = input.spriteData[i].guid;
int texIndex = input.spriteData[i].texIndex;
if (texIndex >= input.textureData.Count)
{
data.Dispose();
throw new ArgumentOutOfRangeException("texIndex", "texIndex must point to a valid index in textureData list.");
}
rawData.spriteData.texIndex = texIndex;
rawData.spriteData.indexCount = input.spriteData[i].indexCount;
rawData.spriteData.vertexCount = input.spriteData[i].vertexCount;
rawData.spriteData.rect = input.spriteData[i].rect;
rawData.spriteData.indices = input.spriteData[i].indices.IsCreated ? (IntPtr)input.spriteData[i].indices.GetUnsafePtr() : (IntPtr)0;
rawData.spriteData.vertices = input.spriteData[i].vertices.IsCreated ? (IntPtr)input.spriteData[i].vertices.GetUnsafePtr() : (IntPtr)0;
rawData.textureData.width = input.textureData[texIndex].width;
rawData.textureData.height = input.textureData[texIndex].height;
rawData.textureData.buffer = input.textureData[texIndex].buffer.IsCreated ? (IntPtr)input.textureData[texIndex].buffer.GetUnsafePtr() : (IntPtr)0;
data[i] = rawData;
}
var spriteOutput = (SpritePackDatasetInternal*)PackCustomSpritesInternal(spriteCount, (SpritePackDatasetInternal*)data.GetUnsafePtr(), packConfig);
if (null != spriteOutput)
{
var colorBufferArray = new SpritePackTextureInfo[spriteCount];
for (int i = 0; i < spriteCount; ++i)
{
SpritePackTextureInfoInternal rawBuffer = spriteOutput[i].textureData;
int index = spriteOutput[i].spriteData.texIndex;
SpritePackTextureInfo outputBuffer = colorBufferArray[index];
// New Texture. Copy.
if (!outputBuffer.buffer.IsCreated)
{
outputBuffer.width = rawBuffer.width;
outputBuffer.height = rawBuffer.height;
Color32* rawColor = (Color32*)rawBuffer.buffer;
if (null != rawColor)
{
outputBuffer.buffer = new NativeArray<Color32>(rawBuffer.width * rawBuffer.height, alloc);
UnsafeUtility.MemCpy(outputBuffer.buffer.GetUnsafePtr(), rawColor, rawBuffer.width * rawBuffer.height * sizeof(Color32));
}
UnsafeUtility.Free((void*)rawBuffer.buffer, Allocator.Persistent);
}
colorBufferArray[index] = outputBuffer;
}
output.textureData = new List<SpritePackTextureInfo>(colorBufferArray);
var spriteDataArray = new SpritePackInfo[spriteCount];
for (int i = 0; i < spriteCount; ++i)
{
SpritePackInfo spriteData = spriteDataArray[i];
spriteData.guid = spriteOutput[i].spriteData.guid;
spriteData.indexCount = spriteOutput[i].spriteData.indexCount;
spriteData.vertexCount = spriteOutput[i].spriteData.vertexCount;
spriteData.rect = spriteOutput[i].spriteData.rect;
if (0 != spriteData.indexCount && 0 != spriteData.vertexCount)
{
int* rawIndices = (int*)spriteOutput[i].spriteData.indices;
if (null != rawIndices)
{
spriteData.indices = new NativeArray<int>(spriteOutput[i].spriteData.indexCount, alloc);
UnsafeUtility.MemCpy(spriteData.indices.GetUnsafePtr(), rawIndices, spriteOutput[i].spriteData.indexCount * sizeof(int));
}
Vector3* rawVertices = (Vector3*)spriteOutput[i].spriteData.vertices;
if (null != rawVertices)
{
spriteData.vertices = new NativeArray<Vector3>(spriteOutput[i].spriteData.vertexCount, alloc);
UnsafeUtility.MemCpy(spriteData.vertices.GetUnsafePtr(), rawVertices, spriteOutput[i].spriteData.vertexCount * sizeof(Vector3));
}
UnsafeUtility.Free((void*)spriteOutput[i].spriteData.indices, Allocator.Persistent);
UnsafeUtility.Free((void*)spriteOutput[i].spriteData.vertices, Allocator.Persistent);
}
spriteData.texIndex = spriteOutput[i].spriteData.texIndex;
spriteDataArray[i] = spriteData;
}
output.spriteData = new List<SpritePackInfo>(spriteDataArray);
UnsafeUtility.Free((void*)spriteOutput, Allocator.Persistent);
}
data.Dispose();
return output;
}
internal static SpritePackDataset PackCustomSprites(SpritePackDataset spriteDataInput, SpritePackConfig packConfig, Allocator outputAlloc)
{
return PackCustomSpritesWrapper(spriteDataInput, packConfig, outputAlloc);
}
[NativeThrows]
[FreeFunction("PackCustomSprites")]
extern internal unsafe static IntPtr PackCustomSpritesInternal(int spriteCount, SpritePackDatasetInternal* data, SpritePackConfig packConfig);
}
}
| UnityCsReference/Editor/Mono/2D/SpriteAtlas/EditorSpritePacking.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/2D/SpriteAtlas/EditorSpritePacking.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 3832
} | 279 |
// 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 UnityEditor;
using System.Collections;
using System.Collections.Generic;
using UnityEditorInternal;
using Object = UnityEngine.Object;
namespace UnityEditorInternal
{
[System.Serializable]
internal class AnimEditorOverlay
{
[SerializeReference] public AnimationWindowState state;
private TimeCursorManipulator m_PlayHeadCursor;
private Rect m_Rect;
private Rect m_ContentRect;
public Rect rect { get { return m_Rect; } }
public Rect contentRect { get { return m_ContentRect; } }
public void Initialize()
{
if (m_PlayHeadCursor == null)
{
m_PlayHeadCursor = new TimeCursorManipulator(AnimationWindowStyles.playHead);
m_PlayHeadCursor.onStartDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
if (evt.mousePosition.y <= (m_Rect.yMin + 20))
return OnStartDragPlayHead(evt);
return false;
};
m_PlayHeadCursor.onDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
return OnDragPlayHead(evt);
};
m_PlayHeadCursor.onEndDrag += (AnimationWindowManipulator manipulator, Event evt) =>
{
return OnEndDragPlayHead(evt);
};
}
}
public void OnGUI(Rect rect, Rect contentRect)
{
if (Event.current.type != EventType.Repaint)
return;
m_Rect = rect;
m_ContentRect = contentRect;
Initialize();
m_PlayHeadCursor.OnGUI(m_Rect, m_Rect.xMin + TimeToPixel(state.currentTime));
}
public void HandleEvents()
{
Initialize();
m_PlayHeadCursor.HandleEvents();
}
private bool OnStartDragPlayHead(Event evt)
{
state.playing = false;
state.controlInterface.time = MousePositionToTime(evt);
return true;
}
private bool OnDragPlayHead(Event evt)
{
state.controlInterface.time = MousePositionToTime(evt);
return true;
}
private bool OnEndDragPlayHead(Event evt)
{
return true;
}
public float MousePositionToTime(Event evt)
{
float width = m_ContentRect.width;
float time = Mathf.Max(((evt.mousePosition.x / width) * state.visibleTimeSpan + state.minVisibleTime), 0);
time = state.SnapToFrame(time, AnimationWindowState.SnapMode.SnapToFrame);
return time;
}
public float MousePositionToValue(Event evt)
{
float height = m_ContentRect.height;
float valuePixel = height - evt.mousePosition.y;
TimeArea timeArea = state.timeArea;
float pixelPerValue = timeArea.m_Scale.y * -1f;
float zeroValuePixel = timeArea.shownArea.yMin * pixelPerValue * -1f;
float value = (valuePixel - zeroValuePixel) / pixelPerValue;
return value;
}
public float TimeToPixel(float time)
{
return state.TimeToPixel(time);
}
public float ValueToPixel(float value)
{
TimeArea timeArea = state.timeArea;
float pixelPerValue = timeArea.m_Scale.y * -1f;
float zeroValuePixel = timeArea.shownArea.yMin * pixelPerValue * -1f;
float pixelValue = value * pixelPerValue + zeroValuePixel;
return pixelValue;
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimEditorOverlay.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimEditorOverlay.cs",
"repo_id": "UnityCsReference",
"token_count": 1807
} | 280 |
// 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;
using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
namespace UnityEditorInternal
{
internal class AnimationWindowHierarchyNode : TreeViewItem
{
public string path;
public System.Type animatableObjectType;
public string propertyName;
public EditorCurveBinding? binding;
public AnimationWindowCurve[] curves;
public float? topPixel = null;
public int indent = 0;
public AnimationWindowHierarchyNode(int instanceID, int depth, TreeViewItem parent, System.Type animatableObjectType, string propertyName, string path, string displayName)
: base(instanceID, depth, parent, displayName)
{
this.displayName = displayName;
this.animatableObjectType = animatableObjectType;
this.propertyName = propertyName;
this.path = path;
}
}
internal class AnimationWindowHierarchyPropertyGroupNode : AnimationWindowHierarchyNode
{
public AnimationWindowHierarchyPropertyGroupNode(System.Type animatableObjectType, int setId, string propertyName, string path, TreeViewItem parent, string displayName)
: base(AnimationWindowUtility.GetPropertyNodeID(setId, path, animatableObjectType, propertyName), parent != null ? parent.depth + 1 : -1, parent, animatableObjectType, AnimationWindowUtility.GetPropertyGroupName(propertyName), path, displayName)
{}
}
internal class AnimationWindowHierarchyPropertyNode : AnimationWindowHierarchyNode
{
public bool isPptrNode;
public AnimationWindowHierarchyPropertyNode(System.Type animatableObjectType, int setId, string propertyName, string path, TreeViewItem parent, EditorCurveBinding binding, bool isPptrNode, string displayName)
: base(AnimationWindowUtility.GetPropertyNodeID(setId, path, animatableObjectType, propertyName), parent != null ? parent.depth + 1 : -1, parent, animatableObjectType, propertyName, path, displayName)
{
this.binding = binding;
this.isPptrNode = isPptrNode;
}
}
internal class AnimationWindowHierarchyClipNode : AnimationWindowHierarchyNode
{
public AnimationWindowHierarchyClipNode(TreeViewItem parent, int setId, string name)
: base(setId, parent != null ? parent.depth + 1 : -1, parent, null, null, null, name)
{}
}
internal class AnimationWindowHierarchyMasterNode : AnimationWindowHierarchyNode
{
public AnimationWindowHierarchyMasterNode()
: base(0, -1, null, null, null, null, "")
{}
}
// A special node to put "Add Curve" button in bottom of the tree
internal class AnimationWindowHierarchyAddButtonNode : AnimationWindowHierarchyNode
{
public AnimationWindowHierarchyAddButtonNode()
: base(0, -1, null, null, null, null, "")
{}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyNode.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyNode.cs",
"repo_id": "UnityCsReference",
"token_count": 1085
} | 281 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditorInternal;
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using TangentMode = UnityEditor.AnimationUtility.TangentMode;
namespace UnityEditor
{
internal class ChangedCurve
{
public AnimationCurve curve;
public int curveId;
public EditorCurveBinding binding;
public ChangedCurve(AnimationCurve curve, int curveId, EditorCurveBinding binding)
{
this.curve = curve;
this.curveId = curveId;
this.binding = binding;
}
public override int GetHashCode()
{
int hash = 0;
unchecked
{
hash = curve.GetHashCode();
hash = 33 * hash + binding.GetHashCode();
}
return hash;
}
}
internal class KeyIdentifier
{
public AnimationCurve curve;
public int curveId;
public int key;
// Used by dopesheet
public EditorCurveBinding binding;
public KeyIdentifier(AnimationCurve _curve, int _curveId, int _keyIndex)
{
curve = _curve;
curveId = _curveId;
key = _keyIndex;
}
public KeyIdentifier(AnimationCurve _curve, int _curveId, int _keyIndex, EditorCurveBinding _binding)
{
curve = _curve;
curveId = _curveId;
key = _keyIndex;
binding = _binding;
}
public Keyframe keyframe { get { return curve[key]; } }
}
internal interface CurveUpdater
{
void UpdateCurves(List<ChangedCurve> curve, string undoText);
}
internal class CurveMenuManager
{
CurveUpdater updater;
public CurveMenuManager(CurveUpdater updater)
{
this.updater = updater;
}
public void AddTangentMenuItems(GenericMenu menu, List<KeyIdentifier> keyList)
{
bool anyKeys = (keyList.Count > 0);
// Find out which qualities apply to all the keys
bool allClampedAuto = anyKeys;
bool allAuto = anyKeys;
bool allFreeSmooth = anyKeys;
bool allFlat = anyKeys;
bool allBroken = anyKeys;
bool allLeftWeighted = anyKeys;
bool allLeftFree = anyKeys;
bool allLeftLinear = anyKeys;
bool allLeftConstant = anyKeys;
bool allRightWeighted = anyKeys;
bool allRightFree = anyKeys;
bool allRightLinear = anyKeys;
bool allRightConstant = anyKeys;
foreach (KeyIdentifier sel in keyList)
{
Keyframe key = sel.keyframe;
TangentMode leftMode = AnimationUtility.GetKeyLeftTangentMode(key);
TangentMode rightMode = AnimationUtility.GetKeyRightTangentMode(key);
bool broken = AnimationUtility.GetKeyBroken(key);
if (leftMode != TangentMode.ClampedAuto || rightMode != TangentMode.ClampedAuto) allClampedAuto = false;
if (leftMode != TangentMode.Auto || rightMode != TangentMode.Auto) allAuto = false;
if (broken || leftMode != TangentMode.Free || rightMode != TangentMode.Free) allFreeSmooth = false;
if (broken || leftMode != TangentMode.Free || key.inTangent != 0 || rightMode != TangentMode.Free || key.outTangent != 0) allFlat = false;
if (!broken) allBroken = false;
if (!broken || leftMode != TangentMode.Free) allLeftFree = false;
if (!broken || leftMode != TangentMode.Linear) allLeftLinear = false;
if (!broken || leftMode != TangentMode.Constant) allLeftConstant = false;
if (!broken || rightMode != TangentMode.Free) allRightFree = false;
if (!broken || rightMode != TangentMode.Linear) allRightLinear = false;
if (!broken || rightMode != TangentMode.Constant) allRightConstant = false;
if ((key.weightedMode & WeightedMode.In) == WeightedMode.None) allLeftWeighted = false;
if ((key.weightedMode & WeightedMode.Out) == WeightedMode.None) allRightWeighted = false;
}
if (anyKeys)
{
menu.AddItem(EditorGUIUtility.TrTextContent("Clamped Auto"), allClampedAuto, SetClampedAuto, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Auto"), allAuto, SetAuto, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Free Smooth"), allFreeSmooth, SetEditable, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Flat"), allFlat, SetFlat, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Broken"), allBroken, SetBroken, keyList);
menu.AddSeparator("");
menu.AddItem(EditorGUIUtility.TrTextContent("Left Tangent/Free"), allLeftFree, SetLeftEditable, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Left Tangent/Linear"), allLeftLinear, SetLeftLinear, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Left Tangent/Constant"), allLeftConstant, SetLeftConstant, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Left Tangent/Weighted"), allLeftWeighted, ToggleLeftWeighted, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Right Tangent/Free"), allRightFree, SetRightEditable, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Right Tangent/Linear"), allRightLinear, SetRightLinear, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Right Tangent/Constant"), allRightConstant, SetRightConstant, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Right Tangent/Weighted"), allRightWeighted, ToggleRightWeighted, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Both Tangents/Free"), allRightFree && allLeftFree, SetBothEditable, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Both Tangents/Linear"), allRightLinear && allLeftLinear, SetBothLinear, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Both Tangents/Constant"), allRightConstant && allLeftConstant, SetBothConstant, keyList);
menu.AddItem(EditorGUIUtility.TrTextContent("Both Tangents/Weighted"), allRightWeighted && allLeftWeighted, ToggleBothWeighted, keyList);
}
else
{
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Weighted"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Auto"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Free Smooth"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Flat"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Broken"));
menu.AddSeparator("");
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Left Tangent/Free"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Left Tangent/Linear"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Left Tangent/Constant"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Left Tangent/Weighted"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Right Tangent/Free"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Right Tangent/Linear"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Right Tangent/Constant"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Right Tangent/Weighted"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Both Tangents/Free"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Both Tangents/Linear"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Both Tangents/Constant"));
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Both Tangents/Weighted"));
}
}
public void ToggleLeftWeighted(object keysToSet) { ToggleWeighted(WeightedMode.In, (List<KeyIdentifier>)keysToSet); }
public void ToggleRightWeighted(object keysToSet) { ToggleWeighted(WeightedMode.Out, (List<KeyIdentifier>)keysToSet); }
public void ToggleBothWeighted(object keysToSet) { ToggleWeighted(WeightedMode.Both, (List<KeyIdentifier>)keysToSet); }
public void ToggleWeighted(WeightedMode weightedMode, List<KeyIdentifier> keysToSet)
{
bool allWeighted = keysToSet.TrueForAll(key => (key.keyframe.weightedMode & weightedMode) == weightedMode);
List<ChangedCurve> changedCurves = new List<ChangedCurve>();
foreach (KeyIdentifier keyToSet in keysToSet)
{
AnimationCurve animationCurve = keyToSet.curve;
Keyframe key = keyToSet.keyframe;
bool weighted = (key.weightedMode & weightedMode) == weightedMode;
if (weighted == allWeighted)
{
WeightedMode lastWeightedMode = key.weightedMode;
key.weightedMode = weighted ? key.weightedMode & ~weightedMode : key.weightedMode | weightedMode;
if (key.weightedMode != WeightedMode.None)
{
TangentMode rightTangentMode = AnimationUtility.GetKeyRightTangentMode(key);
TangentMode leftTangentMode = AnimationUtility.GetKeyLeftTangentMode(key);
if ((lastWeightedMode & WeightedMode.Out) == WeightedMode.None && (key.weightedMode & WeightedMode.Out) == WeightedMode.Out)
{
if (rightTangentMode == TangentMode.Linear || rightTangentMode == TangentMode.Constant)
AnimationUtility.SetKeyRightTangentMode(ref key, TangentMode.Free);
if (keyToSet.key < (animationCurve.length - 1))
key.outWeight = 1 / 3.0f;
}
if ((lastWeightedMode & WeightedMode.In) == WeightedMode.None && (key.weightedMode & WeightedMode.In) == WeightedMode.In)
{
if (leftTangentMode == TangentMode.Linear || leftTangentMode == TangentMode.Constant)
AnimationUtility.SetKeyLeftTangentMode(ref key, TangentMode.Free);
if (keyToSet.key > 0)
key.inWeight = 1 / 3.0f;
}
}
animationCurve.MoveKey(keyToSet.key, key);
AnimationUtility.UpdateTangentsFromModeSurrounding(animationCurve, keyToSet.key);
ChangedCurve changedCurve = new ChangedCurve(animationCurve, keyToSet.curveId, keyToSet.binding);
if (!changedCurves.Contains(changedCurve))
changedCurves.Add(changedCurve);
}
}
updater.UpdateCurves(changedCurves, "Toggle Weighted");
}
public void SetClampedAuto(object keysToSet) { SetBoth(TangentMode.ClampedAuto, (List<KeyIdentifier>)keysToSet); }
public void SetAuto(object keysToSet) { SetBoth(TangentMode.Auto, (List<KeyIdentifier>)keysToSet); }
public void SetEditable(object keysToSet) { SetBoth(TangentMode.Free, (List<KeyIdentifier>)keysToSet); }
public void SetFlat(object keysToSet) { SetBoth(TangentMode.Free, (List<KeyIdentifier>)keysToSet); Flatten((List<KeyIdentifier>)keysToSet); }
public void SetBoth(TangentMode mode, List<KeyIdentifier> keysToSet)
{
List<ChangedCurve> changedCurves = new List<ChangedCurve>();
foreach (KeyIdentifier keyToSet in keysToSet)
{
AnimationCurve animationCurve = keyToSet.curve;
Keyframe key = keyToSet.keyframe;
AnimationUtility.SetKeyBroken(ref key, false);
AnimationUtility.SetKeyRightTangentMode(ref key, mode);
AnimationUtility.SetKeyLeftTangentMode(ref key, mode);
// Smooth Tangents based on neighboring nodes
// Note: not needed since the UpdateTangentsFromModeSurrounding call below will handle it
//if (mode == TangentMode.ClampedAuto) animationCurve.SmoothTangents(keyToSet.key, 0.0F);
// Smooth tangents based on existing tangents
if (mode == TangentMode.Free)
{
float slope = CurveUtility.CalculateSmoothTangent(key);
key.inTangent = slope;
key.outTangent = slope;
}
animationCurve.MoveKey(keyToSet.key, key);
AnimationUtility.UpdateTangentsFromModeSurrounding(animationCurve, keyToSet.key);
ChangedCurve changedCurve = new ChangedCurve(animationCurve, keyToSet.curveId, keyToSet.binding);
if (!changedCurves.Contains(changedCurve))
changedCurves.Add(changedCurve);
}
updater.UpdateCurves(changedCurves, "Set Tangents");
}
public void Flatten(List<KeyIdentifier> keysToSet)
{
List<ChangedCurve> changedCurves = new List<ChangedCurve>();
foreach (KeyIdentifier keyToSet in keysToSet)
{
AnimationCurve animationCurve = keyToSet.curve;
Keyframe key = keyToSet.keyframe;
key.inTangent = 0;
key.outTangent = 0;
animationCurve.MoveKey(keyToSet.key, key);
AnimationUtility.UpdateTangentsFromModeSurrounding(animationCurve, keyToSet.key);
ChangedCurve changedCurve = new ChangedCurve(animationCurve, keyToSet.curveId, keyToSet.binding);
if (!changedCurves.Contains(changedCurve))
changedCurves.Add(changedCurve);
}
updater.UpdateCurves(changedCurves, "Set Tangents");
}
public void SetBroken(object _keysToSet)
{
List<ChangedCurve> changedCurves = new List<ChangedCurve>();
List<KeyIdentifier> keysToSet = (List<KeyIdentifier>)_keysToSet;
foreach (KeyIdentifier keyToSet in keysToSet)
{
AnimationCurve animationCurve = keyToSet.curve;
Keyframe key = keyToSet.keyframe;
AnimationUtility.SetKeyBroken(ref key, true);
if (AnimationUtility.GetKeyRightTangentMode(key) == TangentMode.ClampedAuto || AnimationUtility.GetKeyRightTangentMode(key) == TangentMode.Auto)
AnimationUtility.SetKeyRightTangentMode(ref key, TangentMode.Free);
if (AnimationUtility.GetKeyLeftTangentMode(key) == TangentMode.ClampedAuto || AnimationUtility.GetKeyLeftTangentMode(key) == TangentMode.Auto)
AnimationUtility.SetKeyLeftTangentMode(ref key, TangentMode.Free);
animationCurve.MoveKey(keyToSet.key, key);
AnimationUtility.UpdateTangentsFromModeSurrounding(animationCurve, keyToSet.key);
ChangedCurve changedCurve = new ChangedCurve(animationCurve, keyToSet.curveId, keyToSet.binding);
if (!changedCurves.Contains(changedCurve))
changedCurves.Add(changedCurve);
}
updater.UpdateCurves(changedCurves, "Set Tangents");
}
public void SetLeftEditable(object keysToSet) { SetTangent(0, TangentMode.Free, (List<KeyIdentifier>)keysToSet); }
public void SetLeftLinear(object keysToSet) { SetTangent(0, TangentMode.Linear, (List<KeyIdentifier>)keysToSet); }
public void SetLeftConstant(object keysToSet) { SetTangent(0, TangentMode.Constant, (List<KeyIdentifier>)keysToSet); }
public void SetRightEditable(object keysToSet) { SetTangent(1, TangentMode.Free, (List<KeyIdentifier>)keysToSet); }
public void SetRightLinear(object keysToSet) { SetTangent(1, TangentMode.Linear, (List<KeyIdentifier>)keysToSet); }
public void SetRightConstant(object keysToSet) { SetTangent(1, TangentMode.Constant, (List<KeyIdentifier>)keysToSet); }
public void SetBothEditable(object keysToSet) { SetTangent(2, TangentMode.Free, (List<KeyIdentifier>)keysToSet); }
public void SetBothLinear(object keysToSet) { SetTangent(2, TangentMode.Linear, (List<KeyIdentifier>)keysToSet); }
public void SetBothConstant(object keysToSet) { SetTangent(2, TangentMode.Constant, (List<KeyIdentifier>)keysToSet); }
public void SetTangent(int leftRight, TangentMode mode, List<KeyIdentifier> keysToSet)
{
List<ChangedCurve> changedCurves = new List<ChangedCurve>();
foreach (KeyIdentifier keyToSet in keysToSet)
{
AnimationCurve animationCurve = keyToSet.curve;
Keyframe key = keyToSet.keyframe;
AnimationUtility.SetKeyBroken(ref key, true);
if (leftRight == 2)
{
AnimationUtility.SetKeyLeftTangentMode(ref key, mode);
AnimationUtility.SetKeyRightTangentMode(ref key, mode);
}
else
{
if (leftRight == 0)
{
AnimationUtility.SetKeyLeftTangentMode(ref key, mode);
// Make sure other tangent is handled correctly
if (AnimationUtility.GetKeyRightTangentMode(key) == TangentMode.ClampedAuto || AnimationUtility.GetKeyRightTangentMode(key) == TangentMode.Auto)
AnimationUtility.SetKeyRightTangentMode(ref key, TangentMode.Free);
}
else //if (leftRight == 1)
{
AnimationUtility.SetKeyRightTangentMode(ref key, mode);
// Make sure other tangent is handled correctly
if (AnimationUtility.GetKeyLeftTangentMode(key) == TangentMode.ClampedAuto || AnimationUtility.GetKeyLeftTangentMode(key) == TangentMode.Auto)
AnimationUtility.SetKeyLeftTangentMode(ref key, TangentMode.Free);
}
}
if (mode == TangentMode.Constant && (leftRight == 0 || leftRight == 2))
key.inTangent = Mathf.Infinity;
if (mode == TangentMode.Constant && (leftRight == 1 || leftRight == 2))
key.outTangent = Mathf.Infinity;
animationCurve.MoveKey(keyToSet.key, key);
AnimationUtility.UpdateTangentsFromModeSurrounding(animationCurve, keyToSet.key);
// Debug.Log ("Before " + DebKey (key) + " after: " + DebKey (animationCurve[keyToSet.key]));
ChangedCurve changedCurve = new ChangedCurve(animationCurve, keyToSet.curveId, keyToSet.binding);
if (!changedCurves.Contains(changedCurve))
changedCurves.Add(changedCurve);
}
updater.UpdateCurves(changedCurves, "Set Tangents");
}
/*
string DebKey (Keyframe key) {
return System.String.Format ("time:{0} value:{1} inTangent:{2} outTangent{3}", key.time, key.value, key.inTangent, key.outTangent);
}
*/
}
} // namespace
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveMenuManager.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveMenuManager.cs",
"repo_id": "UnityCsReference",
"token_count": 9053
} | 282 |
// 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;
using Object = UnityEngine.Object;
namespace UnityEditorInternal
{
// Compatibility implementation of IAnimationWindowController.
abstract class IAnimationWindowControl : ScriptableObject, IAnimationWindowController
{
[SerializeReference] AnimationWindowState m_State;
public virtual void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
}
public abstract void OnSelectionChanged();
public void Init(AnimationWindowState state)
{
m_State = state;
}
void IAnimationWindowController.OnCreate(AnimationWindow animationWindow, UnityEngine.Component component)
{
}
void IAnimationWindowController.OnDestroy()
{
// Animation Window has ownership of `IAnimationWindowControl` in legacy workflow.
Object.DestroyImmediate(this);
}
float IAnimationWindowController.time
{
get => time.time;
set => GoToTime(value);
}
int IAnimationWindowController.frame
{
get => time.frame;
set => GoToFrame(value);
}
public abstract AnimationKeyTime time { get; }
public abstract void GoToTime(float time);
public abstract void GoToFrame(int frame);
// Not used anymore. This was not used by either the AnimationWindow nor Timeline.
// Replaced by setting IAnimationWindowController.time.
public abstract void StartScrubTime();
public abstract void ScrubTime(float time);
public abstract void EndScrubTime();
// Not used anymore. Required internal knowledge of the Animation Window and
// default implementation should suffice.
public abstract void GoToPreviousFrame();
public abstract void GoToNextFrame();
public abstract void GoToPreviousKeyframe();
public abstract void GoToNextKeyframe();
public abstract void GoToFirstKeyframe();
public abstract void GoToLastKeyframe();
public abstract bool canPlay { get; }
bool IAnimationWindowController.playing
{
get => playing;
set
{
if (value)
StartPlayback();
else
StopPlayback();
}
}
public abstract bool playing { get; }
public abstract bool StartPlayback();
public abstract void StopPlayback();
public abstract bool PlaybackUpdate();
public abstract bool canPreview { get; }
bool IAnimationWindowController.previewing
{
get => previewing;
set
{
if (value)
StartPreview();
else
StopPreview();
}
}
public abstract bool previewing { get; }
public abstract bool StartPreview();
public abstract void StopPreview();
public abstract bool canRecord { get; }
bool IAnimationWindowController.recording
{
get => recording;
set
{
if (value)
StartRecording(null);
else
StopRecording();
}
}
public abstract bool recording { get; }
// targetObject parameter is not used.
public abstract bool StartRecording(Object targetObject);
public abstract void StopRecording();
public abstract void ResampleAnimation();
public abstract void ProcessCandidates();
public abstract void ClearCandidates();
EditorCurveBinding[] IAnimationWindowController.GetAnimatableBindings()
{
if (m_State == null)
return Array.Empty<EditorCurveBinding>();
var rootGameObject = m_State.activeRootGameObject;
var scriptableObject = m_State.activeScriptableObject;
if (rootGameObject != null)
{
return AnimationWindowUtility.GetAnimatableBindings(rootGameObject);
}
if (scriptableObject != null)
{
return AnimationUtility.GetAnimatableBindings(scriptableObject);
}
return Array.Empty<EditorCurveBinding>();
}
EditorCurveBinding[] IAnimationWindowController.GetAnimatableBindings(GameObject gameObject)
{
if (m_State == null)
return Array.Empty<EditorCurveBinding>();
var rootGameObject = m_State.activeRootGameObject;
return AnimationUtility.GetAnimatableBindings(gameObject, rootGameObject);
}
System.Type IAnimationWindowController.GetValueType(EditorCurveBinding binding)
{
if (m_State == null)
return default;
var rootGameObject = m_State.activeRootGameObject;
var scriptableObject = m_State.activeScriptableObject;
if (rootGameObject != null)
{
return AnimationUtility.GetEditorCurveValueType(rootGameObject, binding);
}
else if (scriptableObject != null)
{
return AnimationUtility.GetEditorCurveValueType(scriptableObject, binding);
}
else
{
if (binding.isPPtrCurve)
{
// Cannot extract type of PPtrCurve.
return null;
}
else
{
// Cannot extract type of AnimationCurve. Default to float.
return typeof(float);
}
}
}
float IAnimationWindowController.GetFloatValue(EditorCurveBinding binding)
{
if (m_State == null)
return default;
AnimationUtility.GetFloatValue(m_State.activeRootGameObject, binding, out var value);
return value;
}
int IAnimationWindowController.GetIntValue(EditorCurveBinding binding)
{
if (m_State == null)
return default;
AnimationUtility.GetDiscreteIntValue(m_State.activeRootGameObject, binding, out var value);
return value;
}
UnityEngine.Object IAnimationWindowController.GetObjectReferenceValue(EditorCurveBinding binding)
{
if (m_State == null)
return default;
AnimationUtility.GetObjectReferenceValue(m_State.activeRootGameObject, binding, out var value);
return value;
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationWindowControl.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/IAnimationWindowControl.cs",
"repo_id": "UnityCsReference",
"token_count": 3049
} | 283 |
// 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.Collections;
using UnityEditor;
using System.Collections.Generic;
using UnityEditor.Animations;
namespace UnityEditor
{
internal class TransitionPreview
{
private AvatarPreview m_AvatarPreview;
private TimelineControl m_Timeline;
private AnimatorController m_Controller;
private AnimatorStateMachine m_StateMachine;
private List<Vector2> m_ParameterMinMax = new List<Vector2>();
private List<ParameterInfo> m_ParameterInfoList;
private AnimatorStateTransition m_RefTransition;
private TransitionInfo m_RefTransitionInfo = new TransitionInfo();
private AnimatorStateTransition m_Transition;
private AnimatorState m_SrcState;
private AnimatorState m_DstState;
private AnimatorState m_RefSrcState;
private AnimatorState m_RefDstState;
private Motion m_SrcMotion;
private Motion m_DstMotion;
private bool m_ShowBlendValue = false;
private bool m_MustResample = true;
private bool m_MustSampleMotions = false;
private bool m_MustResetParameterInfoList = false;
public bool mustResample { set { m_MustResample = value; } get { return m_MustResample; } }
private float m_LastEvalTime = -1.0f;
private bool m_IsResampling = false;
private AvatarMask m_LayerMask;
private int m_LayerIndex;
private bool m_ValidTransition = true;
class ParameterInfo
{
public string m_Name;
public float m_Value;
}
int FindParameterInfo(List<ParameterInfo> parameterInfoList, string name)
{
int ret = -1;
for (int i = 0; i < parameterInfoList.Count && ret == -1; i++)
{
if (parameterInfoList[i].m_Name == name)
{
ret = i;
}
}
return ret;
}
class TransitionInfo
{
AnimatorState m_SrcState;
AnimatorState m_DstState;
float m_TransitionDuration;
float m_TransitionOffset;
float m_ExitTime;
public bool IsEqual(TransitionInfo info)
{
return m_SrcState == info.m_SrcState &&
m_DstState == info.m_DstState &&
Mathf.Approximately(m_TransitionDuration, info.m_TransitionDuration) &&
Mathf.Approximately(m_TransitionOffset, info.m_TransitionOffset) &&
Mathf.Approximately(m_ExitTime, info.m_ExitTime);
}
public TransitionInfo()
{
Init();
}
void Init()
{
m_SrcState = null;
m_DstState = null;
m_TransitionDuration = 0.0f;
m_TransitionOffset = 0.0f;
m_ExitTime = 0.5f;
}
public void Set(AnimatorStateTransition transition, AnimatorState srcState, AnimatorState dstState)
{
if (transition != null)
{
m_SrcState = srcState;
m_DstState = dstState;
m_TransitionDuration = transition.duration;
m_TransitionOffset = transition.offset;
m_ExitTime = transition.exitTime;
}
else
{
Init();
}
}
}
private void CopyStateForPreview(AnimatorState src, ref AnimatorState dst)
{
dst.iKOnFeet = src.iKOnFeet;
dst.speed = src.speed;
dst.mirror = src.mirror;
dst.motion = src.motion;
}
private void CopyTransitionForPreview(AnimatorStateTransition src, ref AnimatorStateTransition dst)
{
if (src != null)
{
dst.duration = src.duration;
dst.offset = src.offset;
dst.exitTime = src.exitTime;
dst.hasFixedDuration = src.hasFixedDuration;
}
}
float m_LeftStateWeightA = 0;
float m_LeftStateWeightB = 1;
float m_LeftStateTimeA = 0;
float m_LeftStateTimeB = 1;
float m_RightStateWeightA = 0;
float m_RightStateWeightB = 1;
float m_RightStateTimeA = 0;
float m_RightStateTimeB = 1;
List<TimelineControl.PivotSample> m_SrcPivotList = new List<TimelineControl.PivotSample>();
List<TimelineControl.PivotSample> m_DstPivotList = new List<TimelineControl.PivotSample>();
private bool MustResample(TransitionInfo info)
{
bool isInPlayback = m_AvatarPreview != null && m_AvatarPreview.Animator != null && m_AvatarPreview.Animator.recorderMode == AnimatorRecorderMode.Playback;
return !isInPlayback || mustResample || !info.IsEqual(m_RefTransitionInfo);
}
private void WriteParametersInController()
{
if (m_Controller)
{
int parameterCount = m_Controller.parameters.Length;
for (int i = 0; i < parameterCount; i++)
{
string parameterName = m_Controller.parameters[i].name;
int parameterInfoIndex = FindParameterInfo(m_ParameterInfoList, parameterName);
if (parameterInfoIndex != -1)
{
m_AvatarPreview.Animator.SetFloat(parameterName, m_ParameterInfoList[parameterInfoIndex].m_Value);
}
}
}
}
private void ResampleTransition(AnimatorStateTransition transition, AvatarMask layerMask, TransitionInfo info, Animator previewObject)
{
m_IsResampling = true;
m_MustResample = false;
m_ValidTransition = true;
bool resetTimeSettings = m_RefTransition != transition;
m_RefTransition = transition;
m_RefTransitionInfo = info;
m_LayerMask = layerMask;
if (m_AvatarPreview != null)
{
m_AvatarPreview.OnDisable();
m_AvatarPreview = null;
}
ClearController();
Motion sourceStateMotion = m_RefSrcState.motion;
Init(previewObject, sourceStateMotion != null ? sourceStateMotion : m_RefDstState.motion);
if (m_Controller == null) // did not create controller
{
m_IsResampling = false;
return;
}
// since transform might change during sampling, and could alter the default valuesarray, and break recording
m_AvatarPreview.Animator.allowConstantClipSamplingOptimization = false;
// sample all frames
m_StateMachine.defaultState = m_DstState;
m_Transition.mute = true;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_AvatarPreview.Animator.Update(0.00001f);
WriteParametersInController();
m_AvatarPreview.Animator.SetLayerWeight(m_LayerIndex, 1);
float nextStateDuration = m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(m_LayerIndex).length;
m_StateMachine.defaultState = m_SrcState;
m_Transition.mute = false;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_AvatarPreview.Animator.Update(0.00001f);
WriteParametersInController();
m_AvatarPreview.Animator.SetLayerWeight(m_LayerIndex, 1);
float currentStateDuration = m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(m_LayerIndex).length;
if (m_LayerIndex > 0)
m_AvatarPreview.Animator.stabilizeFeet = false;
float maxDuration = (currentStateDuration * m_RefTransition.exitTime) + (m_Transition.duration * (m_RefTransition.hasFixedDuration ? 1.0f : currentStateDuration)) + nextStateDuration;
// case 546812 disable previewer if the duration is too big, otherwise it hang Unity. 2000.0f is an arbitrary choice, it can be increase if needed.
// in some case we got a m_Transition.duration == Infinity, bail out before unity hang.
if (maxDuration > 2000.0f)
{
Debug.LogWarning("Transition duration is longer than 2000 second, Disabling previewer.");
m_ValidTransition = false;
m_IsResampling = false;
return;
}
float effectiveCurrentStatetime = m_RefTransition.exitTime > 0 ? currentStateDuration * m_RefTransition.exitTime : currentStateDuration;
// We want 30 samples/sec, maxed at 300 sample for very long state, and very short animation like 1 frame should at least get 5 sample
float currentStateStepTime = effectiveCurrentStatetime > 0 ? Mathf.Min(Mathf.Max(effectiveCurrentStatetime / 300.0f, 1.0f / 30.0f), effectiveCurrentStatetime / 5.0f) : 1.0f / 30.0f;
float nextStateStepTime = nextStateDuration > 0 ? Mathf.Min(Mathf.Max(nextStateDuration / 300.0f, 1.0f / 30.0f), nextStateDuration / 5.0f) : 1.0f / 30.0f;
currentStateStepTime = Mathf.Max(currentStateStepTime, maxDuration / 600.0f);
nextStateStepTime = Mathf.Max(nextStateStepTime, maxDuration / 600.0f);
float stepTime = currentStateStepTime;
float currentTime = 0.0f;
bool hasStarted = false;
bool hasTransitioned = false;
bool hasFinished = false;
//For transitions with exit time == 0, skip to end of clip so transition happens on first frame
if (m_RefTransition.exitTime == 0)
{
m_AvatarPreview.Animator.CrossFade(0, 0f, 0, 0.9f);
}
m_AvatarPreview.Animator.StartRecording(-1);
m_AvatarPreview.Animator.Update(0.0f);
AnimatorStateInfo currentState = m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(m_LayerIndex);
m_LeftStateWeightA = currentState.normalizedTime;
m_LeftStateTimeA = currentTime;
while (!hasFinished)
{
m_AvatarPreview.Animator.Update(stepTime);
currentState = m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(m_LayerIndex);
currentTime += stepTime;
if (!hasStarted)
{
m_LeftStateWeightB = currentState.normalizedTime;
m_LeftStateTimeB = currentTime;
hasStarted = true;
}
if (hasTransitioned && currentTime >= maxDuration)
{
hasFinished = true;
}
if (!hasTransitioned && currentState.IsName(m_DstState.name))
{
m_RightStateWeightA = currentState.normalizedTime;
m_RightStateTimeA = currentTime;
hasTransitioned = true;
}
if (!hasTransitioned)
{
m_LeftStateWeightB = currentState.normalizedTime;
m_LeftStateTimeB = currentTime;
}
if (hasTransitioned || hasFinished)
{
m_RightStateWeightB = currentState.normalizedTime;
m_RightStateTimeB = currentTime;
}
if (m_AvatarPreview.Animator.IsInTransition(m_LayerIndex))
{
stepTime = nextStateStepTime;
}
}
float endTime = currentTime;
m_AvatarPreview.Animator.StopRecording();
if (Mathf.Approximately(m_LeftStateWeightB, m_LeftStateWeightA) || Mathf.Approximately(m_RightStateWeightB, m_RightStateWeightA))
{
Debug.LogWarning("Difference in effective length between states is too big. Transition preview will be disabled.");
m_ValidTransition = false;
m_IsResampling = false;
return;
}
float leftDuration = (m_LeftStateTimeB - m_LeftStateTimeA) / (m_LeftStateWeightB - m_LeftStateWeightA);
float rightDuration = (m_RightStateTimeB - m_RightStateTimeA) / (m_RightStateWeightB - m_RightStateWeightA);
// Ensure step times make sense based on these timings
// If step time is too small, the samping will take too long
currentStateStepTime = Mathf.Max(currentStateStepTime, leftDuration / 600.0f);
nextStateStepTime = Mathf.Max(nextStateStepTime, rightDuration / 600.0f);
if (m_MustSampleMotions)
{
// Do this as infrequently as possible
m_MustSampleMotions = false;
m_SrcPivotList.Clear();
m_DstPivotList.Clear();
stepTime = nextStateStepTime;
m_StateMachine.defaultState = m_DstState;
m_Transition.mute = true;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_AvatarPreview.Animator.Update(0.0f);
m_AvatarPreview.Animator.SetLayerWeight(m_LayerIndex, 1);
m_AvatarPreview.Animator.Update(0.0000001f);
WriteParametersInController();
currentTime = 0.0f;
while (currentTime <= rightDuration)
{
TimelineControl.PivotSample sample = new TimelineControl.PivotSample();
sample.m_Time = currentTime;
sample.m_Weight = m_AvatarPreview.Animator.pivotWeight;
m_DstPivotList.Add(sample);
m_AvatarPreview.Animator.Update(stepTime * 2);
currentTime += stepTime * 2;
}
stepTime = currentStateStepTime;
m_StateMachine.defaultState = m_SrcState;
m_Transition.mute = true;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_AvatarPreview.Animator.Update(0.0000001f);
WriteParametersInController();
m_AvatarPreview.Animator.SetLayerWeight(m_LayerIndex, 1);
currentTime = 0.0f;
while (currentTime <= leftDuration)
{
TimelineControl.PivotSample sample = new TimelineControl.PivotSample();
sample.m_Time = currentTime;
sample.m_Weight = m_AvatarPreview.Animator.pivotWeight;
m_SrcPivotList.Add(sample);
m_AvatarPreview.Animator.Update(stepTime * 2);
currentTime += stepTime * 2;
}
m_Transition.mute = false;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_AvatarPreview.Animator.Update(0.0000001f);
WriteParametersInController();
}
m_Timeline.StopTime = m_AvatarPreview.timeControl.stopTime = endTime;
m_AvatarPreview.timeControl.currentTime = m_Timeline.Time;
if (resetTimeSettings)
{
m_Timeline.Time = m_Timeline.StartTime = m_AvatarPreview.timeControl.currentTime = m_AvatarPreview.timeControl.startTime = 0;
m_Timeline.ResetRange();
}
m_AvatarPreview.Animator.StartPlayback();
m_AvatarPreview.Animator.playbackTime = 0f;
m_AvatarPreview.Animator.Update(0f);
m_AvatarPreview.ResetPreviewFocus();
m_IsResampling = false;
}
public void SetTransition(AnimatorStateTransition transition, AnimatorState sourceState, AnimatorState destinationState, AnimatorControllerLayer srcLayer, Animator previewObject)
{
m_RefSrcState = sourceState;
m_MustResetParameterInfoList = m_RefDstState != destinationState;
m_RefDstState = destinationState;
TransitionInfo info = new TransitionInfo();
info.Set(transition, sourceState, destinationState);
if (MustResample(info))
{
ResampleTransition(transition, srcLayer.avatarMask, info, previewObject);
}
}
private void OnPreviewAvatarChanged()
{
m_RefTransitionInfo = new TransitionInfo();
ClearController();
CreateController();
CreateParameterInfoList();
}
void ClearController()
{
if (m_AvatarPreview != null && m_AvatarPreview.Animator != null)
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, null);
Object.DestroyImmediate(m_Controller);
Object.DestroyImmediate(m_SrcState);
Object.DestroyImmediate(m_DstState);
Object.DestroyImmediate(m_Transition);
m_StateMachine = null;
m_Controller = null;
m_SrcState = null;
m_DstState = null;
m_Transition = null;
}
void CreateParameterInfoList()
{
m_ParameterInfoList = new List<ParameterInfo>();
if (m_Controller && m_Controller.parameters != null)
{
int parameterCount = m_Controller.parameters.Length;
for (int i = 0; i < parameterCount; i++)
{
ParameterInfo parameterInfo = new ParameterInfo();
parameterInfo.m_Name = m_Controller.parameters[i].name;
m_ParameterInfoList.Add(parameterInfo);
}
}
}
void CreateController()
{
if (m_Controller == null && m_AvatarPreview != null && m_AvatarPreview.Animator != null && m_RefTransition != null)
{
// controller
m_LayerIndex = 0;
m_Controller = new AnimatorController();
m_Controller.pushUndo = false;
m_Controller.hideFlags = HideFlags.HideAndDontSave;
m_Controller.AddLayer("preview");
bool isDefaultMask = true;
if (m_LayerMask != null)
{
for (AvatarMaskBodyPart i = 0; i < AvatarMaskBodyPart.LastBodyPart && isDefaultMask; i++)
if (!m_LayerMask.GetHumanoidBodyPartActive(i)) isDefaultMask = false;
if (!isDefaultMask)
{
m_Controller.AddLayer("Additionnal");
m_LayerIndex++;
AnimatorControllerLayer[] layers = m_Controller.layers;
layers[m_LayerIndex].avatarMask = m_LayerMask;
m_Controller.layers = layers;
}
}
m_StateMachine = m_Controller.layers[m_LayerIndex].stateMachine;
m_StateMachine.pushUndo = false;
m_StateMachine.hideFlags = HideFlags.HideAndDontSave;
m_SrcMotion = m_RefSrcState.motion;
m_DstMotion = m_RefDstState.motion;
/// Add parameters
m_ParameterMinMax.Clear();
if (m_SrcMotion && m_SrcMotion is BlendTree)
{
BlendTree leftBlendTree = m_SrcMotion as BlendTree;
for (int i = 0; i < leftBlendTree.recursiveBlendParameterCount; i++)
{
string blendValueName = leftBlendTree.GetRecursiveBlendParameter(i);
if (m_Controller.IndexOfParameter(blendValueName) == -1)
{
m_Controller.AddParameter(blendValueName, AnimatorControllerParameterType.Float);
m_ParameterMinMax.Add(new Vector2(leftBlendTree.GetRecursiveBlendParameterMin(i), leftBlendTree.GetRecursiveBlendParameterMax(i)));
}
}
}
if (m_DstMotion && m_DstMotion is BlendTree)
{
BlendTree rightBlendTree = m_DstMotion as BlendTree;
for (int i = 0; i < rightBlendTree.recursiveBlendParameterCount; i++)
{
string blendValueName = rightBlendTree.GetRecursiveBlendParameter(i);
int parameterIndex = m_Controller.IndexOfParameter(blendValueName);
if (parameterIndex == -1)
{
m_Controller.AddParameter(blendValueName, AnimatorControllerParameterType.Float);
m_ParameterMinMax.Add(new Vector2(rightBlendTree.GetRecursiveBlendParameterMin(i), rightBlendTree.GetRecursiveBlendParameterMax(i)));
}
else
{
m_ParameterMinMax[parameterIndex] =
new Vector2(Mathf.Min(rightBlendTree.GetRecursiveBlendParameterMin(i), m_ParameterMinMax[parameterIndex][0]),
Mathf.Max(rightBlendTree.GetRecursiveBlendParameterMax(i), m_ParameterMinMax[parameterIndex][1]));
}
}
}
// states
m_SrcState = m_StateMachine.AddState(m_RefSrcState.name);
m_SrcState.pushUndo = false;
m_SrcState.hideFlags = HideFlags.HideAndDontSave;
m_DstState = m_StateMachine.AddState(m_RefDstState.name);
m_DstState.pushUndo = false;
m_DstState.hideFlags = HideFlags.HideAndDontSave;
CopyStateForPreview(m_RefSrcState, ref m_SrcState);
CopyStateForPreview(m_RefDstState, ref m_DstState);
// transition
m_Transition = m_SrcState.AddTransition(m_DstState, true);
m_Transition.pushUndo = false;
m_Transition.hideFlags = HideFlags.DontSave;
CopyTransitionForPreview(m_RefTransition, ref m_Transition);
DisableIKOnFeetIfNeeded();
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_Controller.OnAnimatorControllerDirty += ControllerDirty;
}
}
private void ControllerDirty()
{
if (!m_IsResampling)
m_MustResample = true;
}
private void DisableIKOnFeetIfNeeded()
{
bool disable = m_SrcMotion == null || m_DstMotion == null;
if (m_LayerIndex > 0)
{
disable = !m_LayerMask.hasFeetIK;
}
if (disable)
{
m_SrcState.iKOnFeet = false;
m_DstState.iKOnFeet = false;
}
}
private void Init(Animator scenePreviewObject, Motion motion)
{
if (m_AvatarPreview == null)
{
m_AvatarPreview = new AvatarPreview(scenePreviewObject, motion);
m_AvatarPreview.OnAvatarChangeFunc = OnPreviewAvatarChanged;
m_AvatarPreview.ShowIKOnFeetButton = false;
m_AvatarPreview.ResetPreviewFocus();
}
if (m_Timeline == null)
{
m_Timeline = new TimelineControl();
m_MustSampleMotions = true;
}
CreateController();
if(m_ParameterInfoList == null || m_MustResetParameterInfoList)
{
m_MustResetParameterInfoList = false;
CreateParameterInfoList();
}
}
public void DoTransitionPreview()
{
if (m_Controller == null)
return;
DoTimeline();
// Draw the blend values
AnimatorControllerParameter[] parameters = m_Controller.parameters;
if (parameters.Length > 0)
{
m_ShowBlendValue = EditorGUILayout.Foldout(m_ShowBlendValue, "BlendTree Parameters", true);
if (m_ShowBlendValue)
{
for (int i = 0; i < parameters.Length; i++)
{
AnimatorControllerParameter parameter = m_Controller.parameters[i];
float value = m_ParameterInfoList[i].m_Value;
float newValue = EditorGUILayout.Slider(parameter.name, value, m_ParameterMinMax[i][0], m_ParameterMinMax[i][1]);
if (newValue != value)
{
m_ParameterInfoList[i].m_Value = newValue;
mustResample = true;
m_MustSampleMotions = true;
}
}
}
}
}
private void DoTimeline()
{
if (!m_ValidTransition)
{
return;
}
// get local durations
float srcStateDuration = (m_LeftStateTimeB - m_LeftStateTimeA) / (m_LeftStateWeightB - m_LeftStateWeightA);
float dstStateDuration = (m_RightStateTimeB - m_RightStateTimeA) / (m_RightStateWeightB - m_RightStateWeightA);
float transitionDuration = m_Transition.duration * (m_RefTransition.hasFixedDuration ? 1.0f : srcStateDuration);
// Set the timeline values
m_Timeline.SrcStartTime = 0f;
m_Timeline.SrcStopTime = srcStateDuration;
m_Timeline.SrcName = m_RefSrcState.name;
m_Timeline.HasExitTime = m_RefTransition.hasExitTime;
m_Timeline.srcLoop = m_SrcMotion ? m_SrcMotion.isLooping : false;
m_Timeline.dstLoop = m_DstMotion ? m_DstMotion.isLooping : false;
m_Timeline.TransitionStartTime = m_RefTransition.exitTime * srcStateDuration;
m_Timeline.TransitionStopTime = m_Timeline.TransitionStartTime + transitionDuration;
m_Timeline.Time = m_AvatarPreview.timeControl.currentTime;
m_Timeline.DstStartTime = m_Timeline.TransitionStartTime - m_RefTransition.offset * dstStateDuration;
m_Timeline.DstStopTime = m_Timeline.DstStartTime + dstStateDuration;
m_Timeline.SampleStopTime = m_AvatarPreview.timeControl.stopTime;
if (m_Timeline.TransitionStopTime == Mathf.Infinity)
m_Timeline.TransitionStopTime = Mathf.Min(m_Timeline.DstStopTime, m_Timeline.SrcStopTime);
m_Timeline.DstName = m_RefDstState.name;
m_Timeline.SrcPivotList = m_SrcPivotList;
m_Timeline.DstPivotList = m_DstPivotList;
// Do the timeline
Rect previewRect = EditorGUILayout.GetControlRect(false, 150, EditorStyles.label);
EditorGUI.BeginChangeCheck();
bool changedData = m_Timeline.DoTimeline(previewRect);
if (EditorGUI.EndChangeCheck())
{
if (changedData)
{
Undo.RegisterCompleteObjectUndo(m_RefTransition, "Edit Transition");
m_RefTransition.exitTime = m_Timeline.TransitionStartTime / m_Timeline.SrcDuration;
m_RefTransition.duration = m_Timeline.TransitionDuration / (m_RefTransition.hasFixedDuration ? 1.0f : m_Timeline.SrcDuration);
m_RefTransition.offset = (m_Timeline.TransitionStartTime - m_Timeline.DstStartTime) / m_Timeline.DstDuration;
}
m_AvatarPreview.timeControl.nextCurrentTime = Mathf.Clamp(m_Timeline.Time, 0, m_AvatarPreview.timeControl.stopTime);
}
}
public void OnDisable()
{
ClearController();
if (m_Timeline != null)
{
m_Timeline = null;
}
if (m_AvatarPreview != null)
{
m_AvatarPreview.OnDisable();
m_AvatarPreview = null;
}
}
public bool HasPreviewGUI()
{
return true;
}
public void OnPreviewSettings()
{
if (m_AvatarPreview != null)
m_AvatarPreview.DoPreviewSettings();
}
public void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
if (m_AvatarPreview != null && m_Controller != null)
{
bool isRepaint = (Event.current.type == EventType.Repaint);
if (isRepaint)
m_AvatarPreview.timeControl.Update();
if (m_LastEvalTime != m_AvatarPreview.timeControl.currentTime && isRepaint)
{
m_AvatarPreview.Animator.playbackTime = m_AvatarPreview.timeControl.currentTime;
m_AvatarPreview.Animator.Update(0);
m_LastEvalTime = m_AvatarPreview.timeControl.currentTime;
}
m_AvatarPreview.DoAvatarPreview(r, background);
}
}
}
}//namespace UnityEditor
| UnityCsReference/Editor/Mono/Animation/TransitionPreview.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/TransitionPreview.cs",
"repo_id": "UnityCsReference",
"token_count": 14821
} | 284 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Scripting;
namespace UnityEditor
{
public static class AssemblyReloadEvents
{
public delegate void AssemblyReloadCallback();
public static event AssemblyReloadCallback beforeAssemblyReload
{
add => m_BeforeAssemblyReloadEvent.Add(value);
remove => m_BeforeAssemblyReloadEvent.Remove(value);
}
private static EventWithPerformanceTracker<AssemblyReloadCallback> m_BeforeAssemblyReloadEvent =
new EventWithPerformanceTracker<AssemblyReloadCallback>($"{nameof(AssemblyReloadEvents)}.{nameof(beforeAssemblyReload)}");
public static event AssemblyReloadCallback afterAssemblyReload
{
add => m_AfterAssemblyReloadEvent.Add(value);
remove => m_AfterAssemblyReloadEvent.Remove(value);
}
private static EventWithPerformanceTracker<AssemblyReloadCallback> m_AfterAssemblyReloadEvent =
new EventWithPerformanceTracker<AssemblyReloadCallback>($"{nameof(AssemblyReloadEvents)}.{nameof(afterAssemblyReload)}");
[RequiredByNativeCode]
static void OnBeforeAssemblyReload()
{
foreach (var evt in m_BeforeAssemblyReloadEvent)
evt();
}
[RequiredByNativeCode]
static void OnAfterAssemblyReload()
{
foreach (var evt in m_AfterAssemblyReloadEvent)
evt();
}
}
}
| UnityCsReference/Editor/Mono/AssemblyReloadEvents.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssemblyReloadEvents.cs",
"repo_id": "UnityCsReference",
"token_count": 612
} | 285 |
// 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.Bindings;
namespace UnityEditor
{
[StaticAccessor("BumpMapSettings::Get()", StaticAccessorType.Dot)]
[NativeHeader("Editor/Src/AssetPipeline/TextureImporting/BumpMapSettings.h")]
internal class BumpMapSettings
{
public static extern bool silentMode { get; set; }
public static extern void PerformBumpMapCheck([NotNull] Material material);
}
public static class MaterialEditorExtensions
{
public static void PerformBumpMapCheck(this Material material)
{
BumpMapSettings.PerformBumpMapCheck(material);
}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/BumpMapSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/BumpMapSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 275
} | 286 |
// 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 UnityEngine.Rendering;
using UnityEditor.AnimatedValues;
namespace UnityEditor.SpeedTree.Importer
{
class SpeedTreeConstants
{
internal static readonly float kFeetToMetersRatio = 0.3048f;
internal static readonly float kCentimetersToMetersRatio = 0.01f;
internal static readonly float kInchesToMetersRatio = 0.0254f;
internal static readonly float kAlphaTestRef = 0.33f;
internal static readonly string kBillboardMaterialName = "Billboard";
}
static class SpeedTreeImporterCommon
{
internal enum STRenderPipeline
{
Legacy,
URP,
HDRP
}
internal enum STUnitConversion
{
kLeaveAsIs = 0,
kFeetToMeters,
kCentimetersToMeters,
kInchesToMeters,
kCustomConversion
};
internal static class MaterialProperties
{
internal static readonly int MainTexID = Shader.PropertyToID("_MainTex");
internal static readonly int ColorTintID = Shader.PropertyToID("_ColorTint");
internal static readonly int NormalMapKwToggleID = Shader.PropertyToID("_NormalMapKwToggle");
internal static readonly int NormalMapID = Shader.PropertyToID("_NormalMap");
internal static readonly int ExtraMapKwToggleID = Shader.PropertyToID("_ExtraMapKwToggle");
internal static readonly int ExtraTexID = Shader.PropertyToID("_ExtraTex");
internal static readonly int GlossinessID = Shader.PropertyToID("_Glossiness");
internal static readonly int MetallicID = Shader.PropertyToID("_Metallic");
internal static readonly int SubsurfaceKwToggleID = Shader.PropertyToID("_SubsurfaceKwToggle");
internal static readonly int SubsurfaceTexID = Shader.PropertyToID("_SubsurfaceTex");
internal static readonly int SubsurfaceColorID = Shader.PropertyToID("_SubsurfaceColor");
internal static readonly int AlphaClipThresholdID = Shader.PropertyToID("_AlphaClipThreshold");
internal static readonly int TransmissionScaleID = Shader.PropertyToID("_TransmissionScale");
internal static readonly int DiffusionProfileAssetID = Shader.PropertyToID("_Diffusion_Profile_Asset");
internal static readonly int DiffusionProfileID = Shader.PropertyToID("_DiffusionProfile");
internal static readonly int HueVariationKwToggleID = Shader.PropertyToID("_HueVariationKwToggle");
internal static readonly int HueVariationColorID = Shader.PropertyToID("_HueVariationColor");
internal static readonly int LeafFacingKwToggleID = Shader.PropertyToID("_LeafFacingKwToggle");
internal static readonly int BillboardKwToggleID = Shader.PropertyToID("_BillboardKwToggle");
internal static readonly int DoubleSidedToggleID = Shader.PropertyToID("_DoubleSidedKwToggle");
internal static readonly int DoubleSidedNormalModeID = Shader.PropertyToID("_DoubleSidedNormalMode");
internal static readonly int BackfaceNormalModeID = Shader.PropertyToID("_BackfaceNormalMode");
internal static readonly int TwoSidedID = Shader.PropertyToID("_TwoSided");
internal static readonly int WindSharedKwToggle = Shader.PropertyToID("_WIND_SHARED");
internal static readonly int WindBranch2KwToggle = Shader.PropertyToID("_WIND_BRANCH2");
internal static readonly int WindBranch1KwToggle = Shader.PropertyToID("_WIND_BRANCH1");
internal static readonly int WindRippleKwToggle = Shader.PropertyToID("_WIND_RIPPLE");
internal static readonly int WindShimmerKwToggle = Shader.PropertyToID("_WIND_SHIMMER");
}
internal static class MaterialKeywords
{
internal static readonly string VBSetupStandardID = "VB_SETUP_STANDARD";
internal static readonly string VBSetupBranch2ID = "VB_SETUP_BRANCH2";
internal static readonly string VBSetupCameraFacingID = "VB_SETUP_CAMERA_FACING";
internal static readonly string VBSetupBranch2AndCameraFacingID = "VB_SETUP_BRANCH2_AND_CAMERA_FACING";
internal static readonly string VBSetupBillboardID = "VB_SETUP_BILLBOARD";
internal static readonly string VBSetupID = "VB_SETUP";
internal static readonly string BillboardID = "_BILLBOARD";
}
internal static STRenderPipeline GetCurrentRenderPipelineType()
{
var renderPipelineAsset = GraphicsSettings.renderPipelineAsset;
if (renderPipelineAsset != null)
{
if (renderPipelineAsset.name.Contains("UniversalRP") ||
renderPipelineAsset.name.Contains("URP"))
{
return STRenderPipeline.URP;
}
else if (renderPipelineAsset.name.Contains("HDRenderPipeline") ||
renderPipelineAsset.name.Contains("HDRP"))
{
return STRenderPipeline.HDRP;
}
}
renderPipelineAsset = QualitySettings.renderPipeline;
if (renderPipelineAsset != null)
{
if (renderPipelineAsset.name.Contains("UniversalRP") ||
renderPipelineAsset.name.Contains("URP"))
{
return STRenderPipeline.URP;
}
else if (renderPipelineAsset.name.Contains("HDRenderPipeline") ||
renderPipelineAsset.name.Contains("HDRP"))
{
return STRenderPipeline.HDRP;
}
}
return STRenderPipeline.Legacy;
}
}
static class SpeedTreeImporterCommonEditor
{
internal class Styles
{
// Meshes labels
public static GUIContent MeshesHeader = EditorGUIUtility.TrTextContent("Meshes");
public static GUIContent UnitConversion = EditorGUIUtility.TrTextContent("Unit Conversion", "Select the unit conversion to apply to the imported SpeedTree asset.");
public static GUIContent ScaleFactor = EditorGUIUtility.TrTextContent("Scale Factor", "How much to scale the tree model, interpreting the exported units as meters");
public static GUIContent[] UnitConversionNames =
{
new GUIContent("Leave As Is")
, new GUIContent("ft to m")
, new GUIContent("cm to m")
, new GUIContent("inch to m")
, new GUIContent("Custom")
};
// Materials labels
public static GUIContent MaterialHeader = EditorGUIUtility.TrTextContent("Material");
public static GUIContent MainColor = EditorGUIUtility.TrTextContent("Main Color", "The color modulating the diffuse lighting component.");
public static GUIContent EnableColorVariation = EditorGUIUtility.TrTextContent("Color Variation", "Color is determined by linearly interpolating between the Main Color & Color Variation values based on the world position X, Y and Z values");
public static GUIContent EnableBump = EditorGUIUtility.TrTextContent("Normal Map", "Enable normal (Bump) mapping.");
public static GUIContent EnableSubsurface = EditorGUIUtility.TrTextContent("Subsurface Scattering", "Enable subsurface scattering effects.");
public static GUIContent HueVariation = EditorGUIUtility.TrTextContent("Variation Color (RGB), Intensity (A)", "Tint the tree with the Variation Color");
public static GUIContent AlphaTestRef = EditorGUIUtility.TrTextContent("Alpha Cutoff", "The alpha-test reference value.");
public static GUIContent TransmissionScale = EditorGUIUtility.TrTextContent("Transmission Scale", "The transmission scale value.");
// Lighting labels
public static GUIContent LightingHeader = EditorGUIUtility.TrTextContent("Lighting");
public static GUIContent CastShadows = EditorGUIUtility.TrTextContent("Cast Shadows", "The tree casts shadow");
public static GUIContent ReceiveShadows = EditorGUIUtility.TrTextContent("Receive Shadows", "The tree receives shadow");
public static GUIContent UseLightProbes = EditorGUIUtility.TrTextContent("Light Probes", "The tree uses light probe for lighting"); // TODO: update help text
public static GUIContent UseReflectionProbes = EditorGUIUtility.TrTextContent("Reflection Probes", "The tree uses reflection probe for rendering"); // TODO: update help text
public static GUIContent[] ReflectionProbeUsageNames = GetReflectionProbeUsageNames();
public static GUIContent[] GetReflectionProbeUsageNames()
{
string[] names = Enum.GetNames(typeof(ReflectionProbeUsage));
GUIContent[] probUsageNames = new GUIContent[names.Length];
for (int i = 0; i < names.Length; ++i)
{
string varName = ObjectNames.NicifyVariableName(names[i]);
probUsageNames[i] = (new GUIContent(varName));
}
return probUsageNames;
}
// Additional Settings labels
public static GUIContent AdditionalSettingsHeader = EditorGUIUtility.TrTextContent("Additional Settings");
public static GUIContent MotionVectorMode = EditorGUIUtility.TrTextContent("Motion Vectors", "Motion vector mode to set for the mesh renderer of each LOD object");
// Wind labels
public static GUIContent WindHeader = EditorGUIUtility.TrTextContent("Wind");
public static GUIContent WindQuality = EditorGUIUtility.TrTextContent("Wind Quality", "Controls the wind effect's quality.");
public static GUIContent[] MotionVectorModeNames = // Match SharedRendererDataTypes.h / enum MotionVectorGenerationMode
{
new GUIContent("Camera Motion Only") // kMotionVectorCamera = 0, // Use camera motion for motion vectors
, new GUIContent("Per Object Motion") // kMotionVectorObject, // Use a per object motion vector pass for this object
, new GUIContent("Force No Motion") // kMotionVectorForceNoMotion, // Force no motion for this object (0 into motion buffer)
};
public static GUIContent[] GetWindQualityNames()
{
GUIContent[] windQualityNames = new GUIContent[SpeedTreeImporter.windQualityNames.Length];
for (int i = 0; i < SpeedTreeImporter.windQualityNames.Length; ++i)
{
windQualityNames[i] = new GUIContent(SpeedTreeImporter.windQualityNames[i]);
}
return windQualityNames;
}
// LOD labels
public static GUIContent LODHeader = EditorGUIUtility.TrTextContent("LOD");
public static GUIContent ResetLOD = EditorGUIUtility.TrTextContent("Reset LOD to...", "Unify the LOD settings for all selected assets");
public static GUIContent SmoothLOD = EditorGUIUtility.TrTextContent("Smooth Transitions", "Toggles smooth LOD transitions");
public static GUIContent AnimateCrossFading = EditorGUIUtility.TrTextContent("Animate Cross-fading", "Cross-fading is animated instead of being calculated by distance");
public static GUIContent CrossFadeWidth = EditorGUIUtility.TrTextContent("Crossfade Width", "Proportion of the last 3D mesh LOD region width which is used for cross-fading to billboard tree");
public static GUIContent FadeOutWidth = EditorGUIUtility.TrTextContent("Fade Out Width", "The proportion of the billboard LOD region width that is used to fade out the billboard.");
public static GUIContent EnableLodCustomizationsWarn = EditorGUIUtility.TrTextContent("Customizing LOD options may help with tuning the GPU performance but will likely negatively impact the instanced draw batching, i.e. CPU performance.\nPlease use the per-LOD customizations with careful memory and performance profiling for both CPU and GPU and remember that these options are a trade-off rather than a free win.");
public static GUIContent BillboardSettingsHelp = EditorGUIUtility.TrTextContent("Billboard options are separate from the 3D model options shown above.\nChange the options below for influencing billboard rendering.");
public static GUIContent MultiSelectionLODNotSupported = EditorGUIUtility.TrTextContent("Multi-selection is not supported for LOD settings.");
public static GUIContent ApplyAndGenerate = EditorGUIUtility.TrTextContent("Apply & Generate Materials", "Apply current importer settings and generate asset materials with the new settings.");
}
static internal void ShowMeshGUI(
ref SerializedProperty unitConversionEnumValue,
ref SerializedProperty scaleFactor)
{
GUILayout.Label(Styles.MeshesHeader, EditorStyles.boldLabel);
EditorGUILayout.Popup(unitConversionEnumValue, Styles.UnitConversionNames, Styles.UnitConversion);
bool bShowCustomScaleFactor = unitConversionEnumValue.intValue == Styles.UnitConversionNames.Length - 1;
if (bShowCustomScaleFactor)
{
EditorGUILayout.PropertyField(scaleFactor, Styles.ScaleFactor);
}
}
static internal void ShowMaterialGUI(
ref SerializedProperty mainColor,
ref SerializedProperty enableHueVariation,
ref SerializedProperty hueVariation,
ref SerializedProperty alphaTestRef,
ref SerializedProperty enableBumpMapping,
ref SerializedProperty enableSubsurfaceScattering,
bool renderHueVariationDropdown = false,
bool renderAlphaTestRef = false)
{
EditorGUILayout.LabelField(Styles.MaterialHeader, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(mainColor, Styles.MainColor);
EditorGUILayout.PropertyField(enableHueVariation, Styles.EnableColorVariation);
if (renderHueVariationDropdown)
{
EditorGUILayout.PropertyField(hueVariation, Styles.HueVariation);
}
if (renderAlphaTestRef)
EditorGUILayout.Slider(alphaTestRef, 0f, 1f, Styles.AlphaTestRef);
EditorGUILayout.PropertyField(enableBumpMapping, Styles.EnableBump);
EditorGUILayout.PropertyField(enableSubsurfaceScattering, Styles.EnableSubsurface);
}
static internal void ShowLightingGUI(
ref SerializedProperty enableShadowCasting,
ref SerializedProperty enableShadowReceiving,
ref SerializedProperty enableLightProbeUsage,
ref SerializedProperty reflectionProbeUsage)
{
GUILayout.Label(Styles.LightingHeader, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(enableShadowCasting, Styles.CastShadows);
// from the docs page: https://docs.unity3d.com/Manual/SpeedTree.html
// Known issues: As with any other renderer, the Receive Shadows option has no effect while using deferred rendering.
// TODO: test and conditionally expose this field
using (new EditorGUI.DisabledScope(!UnityEngine.Rendering.SupportedRenderingFeatures.active.receiveShadows))
{
EditorGUILayout.PropertyField(enableShadowReceiving, Styles.ReceiveShadows);
}
EditorGUILayout.PropertyField(enableLightProbeUsage, Styles.UseLightProbes);
}
static internal void ShowAdditionalSettingsGUI(
ref SerializedProperty motionVectorModeEnumValue,
ref SerializedProperty generateColliders,
ref SerializedProperty generateRigidbody)
{
GUILayout.Label(Styles.AdditionalSettingsHeader, EditorStyles.boldLabel);
EditorGUILayout.Popup(motionVectorModeEnumValue, Styles.MotionVectorModeNames, Styles.MotionVectorMode);
EditorGUILayout.PropertyField(generateColliders);
EditorGUILayout.PropertyField(generateRigidbody);
}
static internal void ShowWindGUI(
ref SerializedProperty bestWindQuality,
ref SerializedProperty selectedWindQuality)
{
GUILayout.Label(Styles.WindHeader, EditorStyles.boldLabel);
int NumAvailableWindQualityOptions = 1 + bestWindQuality.intValue; // 0 is None, we want at least 1 value
ArraySegment<GUIContent> availableWindQualityOptions = new ArraySegment<GUIContent>(Styles.GetWindQualityNames(), 0, NumAvailableWindQualityOptions);
EditorGUILayout.Popup(selectedWindQuality, availableWindQualityOptions.ToArray(), Styles.WindQuality);
}
static internal void ShowLODGUI(
ref SerializedProperty enableSmoothLOD,
ref SerializedProperty animateCrossFading,
ref SerializedProperty billboardTransitionCrossFadeWidth,
ref SerializedProperty fadeOutWidth,
ref AnimBool showSmoothLODOptions,
ref AnimBool showCrossFadeWidthOptions)
{
showSmoothLODOptions.target = enableSmoothLOD.hasMultipleDifferentValues || enableSmoothLOD.boolValue;
showCrossFadeWidthOptions.target = animateCrossFading.hasMultipleDifferentValues || !animateCrossFading.boolValue;
GUILayout.Label(Styles.LODHeader, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(enableSmoothLOD, Styles.SmoothLOD);
using (new EditorGUI.IndentLevelScope())
{
// Note: FadeGroupScope doesn't work here, as if the 'faded' is not updated correctly.
if (EditorGUILayout.BeginFadeGroup(showSmoothLODOptions.faded))
{
EditorGUILayout.PropertyField(animateCrossFading, Styles.AnimateCrossFading);
if (EditorGUILayout.BeginFadeGroup(showCrossFadeWidthOptions.faded))
{
EditorGUILayout.Slider(billboardTransitionCrossFadeWidth, 0.0f, 1.0f, Styles.CrossFadeWidth);
EditorGUILayout.Slider(fadeOutWidth, 0.0f, 1.0f, Styles.FadeOutWidth);
}
EditorGUILayout.EndFadeGroup();
}
EditorGUILayout.EndFadeGroup();
}
}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterCommon.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterCommon.cs",
"repo_id": "UnityCsReference",
"token_count": 7468
} | 287 |
// 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.UIElements;
using UnityEditor.Connect;
using UnityEditor.PackageManager.UI;
using UnityEditor.UIElements;
namespace UnityEditor
{
[EditorWindowTitle(title = "Asset Store", icon = "Asset Store")]
internal class AssetStoreWindow : EditorWindow
{
public static AssetStoreWindow Init()
{
if (EditorPrefs.GetBool("AlwaysOpenAssetStoreInBrowser", false))
{
OpenAssetStoreInBrowser();
return null;
}
else
{
AssetStoreWindow window = GetWindow<AssetStoreWindow>(typeof(SceneView));
window.SetMinMaxSizes();
window.Show();
return window;
}
}
[MenuItem("Window/Asset Store", false, 1497)]
public static void OpenAssetStoreInBrowser()
{
string assetStoreUrl = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudAssetStoreUrl);
assetStoreUrl += "?utm_source=unity-editor-window-menu&utm_medium=desktop-app";
if (UnityConnect.instance.loggedIn)
UnityConnect.instance.OpenAuthorizedURLInWebBrowser(assetStoreUrl);
else Application.OpenURL(assetStoreUrl);
}
[MenuItem("Window/My Assets", false, 1498)]
public static void OpenMyAssetsInPackageManager()
{
PackageManagerWindow.SelectPackageAndPageStatic(pageId: PackageManager.UI.Internal.MyAssetsPage.k_Id);
}
public void OnEnable()
{
this.antiAliasing = 4;
titleContent = GetLocalizedTitleContent();
var windowResource = EditorGUIUtility.Load("UXML/AssetStore/AssetStoreWindow.uxml") as VisualTreeAsset;
if (windowResource != null)
{
var root = windowResource.CloneTree();
var lightStyleSheet = EditorGUIUtility.Load(UIElementsEditorUtility.s_DefaultCommonLightStyleSheetPath) as StyleSheet;
var assetStoreStyleSheet = EditorGUIUtility.Load("StyleSheets/AssetStore/AssetStoreWindow.uss") as StyleSheet;
var styleSheet = CreateInstance<StyleSheet>();
styleSheet.isDefaultStyleSheet = true;
var resolver = new StyleSheets.StyleSheetResolver();
resolver.AddStyleSheets(lightStyleSheet, assetStoreStyleSheet);
resolver.ResolveTo(styleSheet);
root.styleSheets.Add(styleSheet);
rootVisualElement.Add(root);
root.StretchToParentSize();
visitWebsiteButton.clickable.clicked += OnVisitWebsiteButtonClicked;
launchPackageManagerButton.clickable.clicked += OnLaunchPackageManagerButtonClicked;
alwaysOpenInBrowserToggle.SetValueWithoutNotify(EditorPrefs.GetBool("AlwaysOpenAssetStoreInBrowser", false));
alwaysOpenInBrowserToggle.RegisterValueChangedCallback(changeEvent =>
{
EditorPrefs.SetBool("AlwaysOpenAssetStoreInBrowser", changeEvent.newValue);
});
}
}
public void OnDisable()
{
visitWebsiteButton.clickable.clicked -= OnVisitWebsiteButtonClicked;
launchPackageManagerButton.clickable.clicked -= OnLaunchPackageManagerButtonClicked;
}
public static void OpenURL(string url)
{
string assetStoreUrl = $"{UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudAssetStoreUrl)}/packages/{url}";
if (UnityEditor.Connect.UnityConnect.instance.loggedIn)
UnityEditor.Connect.UnityConnect.instance.OpenAuthorizedURLInWebBrowser(assetStoreUrl);
else Application.OpenURL(assetStoreUrl);
}
private void OnVisitWebsiteButtonClicked()
{
OpenAssetStoreInBrowser();
}
private void OnLaunchPackageManagerButtonClicked()
{
PackageManagerWindow.OpenPackageManager(null);
}
private void SetMinMaxSizes()
{
this.minSize = new Vector2(455, 354);
this.maxSize = new Vector2(4000, 4000);
}
private Button visitWebsiteButton { get { return rootVisualElement.Q<Button>("visitWebsiteButton"); } }
private Button launchPackageManagerButton { get { return rootVisualElement.Q<Button>("launchPackageManagerButton"); } }
private Toggle alwaysOpenInBrowserToggle { get { return rootVisualElement.Q<Toggle>("alwaysOpenInBrowserToggle"); } }
}
}
| UnityCsReference/Editor/Mono/AssetStore/AssetStoreWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetStore/AssetStoreWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 2006
} | 288 |
// 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.UIElements;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor;
sealed class AudioContainerWindowState
{
AudioRandomContainer m_AudioContainer;
AudioSource m_PreviewAudioSource;
SerializedObject m_SerializedObject;
VisualElement m_ResourceTrackerElement;
AudioSource m_TrackedSource;
// Need this flag to track transport state changes immediately, as there could be a
// one-frame delay to get the correct value from AudioSource.isContainerPlaying.
bool m_IsPlayingOrPausedLocalFlag;
bool m_IsSuspended;
internal event EventHandler TargetChanged;
internal event EventHandler TransportStateChanged;
internal event EventHandler EditorPauseStateChanged;
internal AudioContainerWindowState()
{
EditorApplication.playModeStateChanged += OnEditorPlayModeStateChanged;
EditorApplication.pauseStateChanged += OnEditorPauseStateChanged;
Selection.selectionChanged += OnSelectionChanged;
}
internal AudioRandomContainer AudioContainer
{
get
{
if (m_AudioContainer == null && m_TrackedSource == null)
UpdateTarget();
return m_AudioContainer;
}
}
internal SerializedObject SerializedObject
{
get
{
if (m_AudioContainer != null && (m_SerializedObject == null || m_SerializedObject.targetObject != m_AudioContainer))
m_SerializedObject = new SerializedObject(m_AudioContainer);
return m_SerializedObject;
}
}
internal string TargetPath { get; private set; }
internal void Reset()
{
Stop();
m_AudioContainer = null;
m_SerializedObject = null;
m_IsPlayingOrPausedLocalFlag = false;
TargetPath = null;
}
internal VisualElement GetResourceTrackerElement()
{
m_ResourceTrackerElement = new VisualElement();
return m_ResourceTrackerElement;
}
internal void OnDestroy()
{
Stop();
if (m_PreviewAudioSource != null)
Object.DestroyImmediate(m_PreviewAudioSource.gameObject);
EditorApplication.playModeStateChanged -= OnEditorPlayModeStateChanged;
Selection.selectionChanged -= OnSelectionChanged;
EditorApplication.pauseStateChanged -= OnEditorPauseStateChanged;
}
internal void Suspend()
{
m_IsSuspended = true;
Stop();
if (m_PreviewAudioSource != null)
Object.DestroyImmediate(m_PreviewAudioSource.gameObject);
}
internal void Resume()
{
m_IsSuspended = false;
UpdateTarget();
}
/// <summary>
/// Updates the current target based on the currently selected object in the editor.
/// </summary>
void UpdateTarget()
{
if (m_IsSuspended)
return;
AudioRandomContainer newTarget = null;
AudioSource audioSource = null;
var selectedObject = Selection.activeObject;
// The logic below deals with selecting our new ARC target, whatever we set m_AudioContainer to below will be
// used by AudioContainerWindow to display the ARC if the target is valid or a day0 state if the target is null.
// If the selection is a GameObject, we always want to swap the target, a user selecting GameObjects in the
// scene hierarchy should always see what ARC is on a particular object, this includes the scenario of not
// having an AudioSource and the value of the resource property on an AudioSource being null/not an ARC.
// If the selected object is not a GameObject, we only swap targets if it is an ARC - meaning if you are
// selecting objects in the project browser it holds on to the last ARC selected.
if (selectedObject != null)
{
if (selectedObject is GameObject go)
{
audioSource = go.GetComponent<AudioSource>();
if (audioSource != null)
{
newTarget = audioSource.resource as AudioRandomContainer;
}
}
else
{
if (selectedObject is AudioRandomContainer container)
{
newTarget = container;
}
else
{
newTarget = m_AudioContainer;
}
}
}
else
{
newTarget = m_AudioContainer;
}
var targetChanged = m_AudioContainer != newTarget;
var trackedSourceChanged = m_TrackedSource != audioSource;
if (!targetChanged && !trackedSourceChanged)
{
return;
}
Reset();
m_AudioContainer = newTarget;
m_TrackedSource = audioSource;
if (m_AudioContainer != null)
{
TargetPath = AssetDatabase.GetAssetPath(m_AudioContainer);
}
if (targetChanged)
{
TargetChanged?.Invoke(this, EventArgs.Empty);
}
if (trackedSourceChanged)
{
if (m_ResourceTrackerElement != null)
{
m_ResourceTrackerElement.Unbind();
}
if (m_TrackedSource != null)
{
var trackedSourceSO = new SerializedObject(m_TrackedSource);
var trackedSourceResourceProperty = trackedSourceSO.FindProperty("m_Resource");
m_ResourceTrackerElement.TrackPropertyValue(trackedSourceResourceProperty, OnResourceChanged);
}
}
}
void OnResourceChanged(SerializedProperty property)
{
var container = property.objectReferenceValue as AudioRandomContainer;
if (m_AudioContainer == container)
return;
Reset();
m_AudioContainer = container;
if (m_AudioContainer != null)
TargetPath = AssetDatabase.GetAssetPath(m_AudioContainer);
TargetChanged?.Invoke(this, EventArgs.Empty);
}
internal void Play()
{
var canNotPlay = m_IsSuspended || IsPlayingOrPaused() || !IsReadyToPlay();
if (canNotPlay)
return;
if (m_PreviewAudioSource == null)
{
// Create a hidden game object in the scene with an AudioSource for editor previewing purposes.
// The preview object is created on play and destroyed on stop.
// This means that this object is a hidden part of the user's scene during play/pause.
var gameObject = new GameObject
{
name = "PreviewAudioSource595651",
hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild
};
m_PreviewAudioSource = gameObject.AddComponent<AudioSource>();
m_PreviewAudioSource.playOnAwake = false;
}
m_PreviewAudioSource.resource = m_AudioContainer;
m_PreviewAudioSource.Play();
m_IsPlayingOrPausedLocalFlag = true;
TransportStateChanged?.Invoke(this, EventArgs.Empty);
EditorApplication.update += OnEditorApplicationUpdate;
}
internal void Stop()
{
var canNotStop = m_IsSuspended || !IsPlayingOrPaused();
if (canNotStop)
return;
m_PreviewAudioSource.Stop();
m_PreviewAudioSource.resource = null;
m_IsPlayingOrPausedLocalFlag = false;
TransportStateChanged?.Invoke(this, EventArgs.Empty);
EditorApplication.update -= OnEditorApplicationUpdate;
}
internal void Skip()
{
var canNotSkip = m_IsSuspended || !IsPlayingOrPaused();
if (canNotSkip)
return;
m_PreviewAudioSource.SkipToNextElementIfHasContainer();
}
internal bool IsPlayingOrPaused()
{
return m_IsPlayingOrPausedLocalFlag || (m_PreviewAudioSource != null && m_PreviewAudioSource.isContainerPlaying);
}
/// <summary>
/// Checks if the window has a current target with at least one enabled audio clip assigned.
/// </summary>
/// <returns>Whether or not there are valid audio clips to play</returns>
internal bool IsReadyToPlay()
{
if (m_AudioContainer == null)
return false;
var elements = m_AudioContainer.elements;
for (var i = 0; i < elements.Length; ++i)
if (elements[i] != null && elements[i].audioClip != null && elements[i].enabled)
return true;
return false;
}
internal ActivePlayable[] GetActivePlayables()
{
return IsPlayingOrPaused() ? m_PreviewAudioSource.containerActivePlayables : null;
}
internal float GetMeterValue()
{
return m_PreviewAudioSource.GetAudioRandomContainerRuntimeMeterValue();
}
internal bool IsDirty()
{
return m_AudioContainer != null && EditorUtility.IsDirty(m_AudioContainer);
}
void OnEditorApplicationUpdate()
{
if (m_PreviewAudioSource != null && m_PreviewAudioSource.isContainerPlaying)
return;
m_IsPlayingOrPausedLocalFlag = false;
TransportStateChanged?.Invoke(this, EventArgs.Empty);
EditorApplication.update -= OnEditorApplicationUpdate;
}
void OnEditorPlayModeStateChanged(PlayModeStateChange state)
{
if (state is PlayModeStateChange.ExitingEditMode or PlayModeStateChange.ExitingPlayMode)
{
Stop();
if (m_PreviewAudioSource != null)
{
Object.DestroyImmediate(m_PreviewAudioSource.gameObject);
}
}
}
void OnEditorPauseStateChanged(PauseState state)
{
EditorPauseStateChanged?.Invoke(this, EventArgs.Empty);
}
void OnSelectionChanged()
{
UpdateTarget();
}
}
| UnityCsReference/Editor/Mono/Audio/AudioContainerWindowState.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/AudioContainerWindowState.cs",
"repo_id": "UnityCsReference",
"token_count": 4056
} | 289 |
// 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.Collections.Generic;
using System.Linq;
using System;
using UnityEditor.Audio;
namespace UnityEditor
{
class AudioMixerEffectView
{
private const float kMinPitch = 0.01f;
private const float kMaxPitch = 10.0f;
private const int kLabelWidth = 170;
private const int kTextboxWidth = 70;
private AudioMixerGroupController m_PrevGroup = null;
private readonly EffectDragging m_EffectDragging;
private int m_LastNumChannels = 0;
private AudioMixerEffectPlugin m_SharedPlugin = new AudioMixerEffectPlugin();
private Dictionary<string, IAudioEffectPluginGUI> m_CustomEffectGUIs = new Dictionary<string, IAudioEffectPluginGUI>();
static class Texts
{
public static GUIContent editInPlaymode = EditorGUIUtility.TrTextContent("Edit in Playmode");
public static GUIContent pitch = EditorGUIUtility.TrTextContent("Pitch");
public static GUIContent addEffect = EditorGUIUtility.TrTextContent("Add Effect");
public static GUIContent volume = EditorGUIUtility.TrTextContent("Volume");
public static GUIContent sendLevel = EditorGUIUtility.TrTextContent("Send level");
public static GUIContent bus = EditorGUIUtility.TrTextContent("Receive");
public static GUIContent none = EditorGUIUtility.TrTextContent("None");
public static GUIContent wet = EditorGUIUtility.TrTextContent("Wet", "Enables/disables wet/dry ratio on this effect. Note that this makes the DSP graph more complex and requires additional CPU and memory, so use it only when necessary.");
public static string dB = "dB";
public static string percentage = "%";
public static string cpuFormatString = " - CPU: {0:#0.00}%";
}
public AudioMixerEffectView()
{
m_EffectDragging = new EffectDragging();
Type pluginType = typeof(IAudioEffectPluginGUI);
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
//Debug.Log("Assembly: " + assembly.FullName);
try
{
var types = assembly.GetTypes();
//Debug.Log("Contained types: " + types.ToString());
foreach (Type t in types.Where(t => !t.IsAbstract && pluginType.IsAssignableFrom(t)))
{
//Debug.Log("Instantiating type: " + t.FullName);
RegisterCustomGUI(Activator.CreateInstance(t) as IAudioEffectPluginGUI);
}
}
catch (System.Exception)
{
//Debug.Log("Failed getting types in assembly: " + assembly.FullName);
}
}
}
public bool RegisterCustomGUI(IAudioEffectPluginGUI gui)
{
string name = gui.Name;
if (m_CustomEffectGUIs.ContainsKey(name))
{
var oldGUI = m_CustomEffectGUIs[name];
Debug.LogError("Attempt to register custom GUI for plugin " + name + " failed as another plugin is already registered under this name.");
Debug.LogError("Plugin trying to register itself: " + gui.Description + " (Vendor: " + gui.Vendor + ")");
Debug.LogError("Plugin already registered: " + oldGUI.Description + " (Vendor: " + oldGUI.Vendor + ")");
return false;
}
m_CustomEffectGUIs[name] = gui;
return true;
}
public void OnGUI(AudioMixerGroupController group)
{
if (group == null)
return;
Rect totalRect = EditorGUILayout.BeginVertical();
if (EditorApplication.isPlaying)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUI.BeginChangeCheck();
GUILayout.Toggle(AudioSettings.editingInPlaymode, Texts.editInPlaymode, EditorStyles.miniButton, GUILayout.Width(120));
if (EditorGUI.EndChangeCheck())
AudioSettings.editingInPlaymode = !AudioSettings.editingInPlaymode;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
using (new EditorGUI.DisabledScope(!AudioMixerController.EditingTargetSnapshot()))
{
var controller = group.controller;
if (group != m_PrevGroup)
{
m_PrevGroup = group;
controller.m_HighlightEffectIndex = -1;
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
// Do Effect modules
var allGroups = controller.GetAllAudioGroupsSlow();
var effectMap = AudioMixerGroupController.GetEffectMapSlow(allGroups);
DoInitialModule(group, controller, allGroups);
for (int effectIndex = 0; effectIndex < group.effects.Length; effectIndex++)
{
DoEffectGUI(effectIndex, group, allGroups, effectMap, ref controller.m_HighlightEffectIndex);
}
m_EffectDragging.HandleDragging(totalRect, group, controller);
GUILayout.Space(10f);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (EditorGUILayout.DropdownButton(Texts.addEffect, FocusType.Passive, GUISkin.current.button))
{
GenericMenu pm = new GenericMenu();
Rect buttonRect = GUILayoutUtility.topLevel.GetLast();
AudioMixerGroupController[] groupArray = new AudioMixerGroupController[] { group };
AudioMixerChannelStripView.AddEffectItemsToMenu(controller, groupArray, group.effects.Length, string.Empty, pm);
pm.DropDown(buttonRect);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
}
public static float DoInitialModule(AudioMixerGroupController group, AudioMixerController controller, List<AudioMixerGroupController> allGroups)
{
Rect totalRect = EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins);
// Pitch
float value = group.GetValueForPitch(controller, controller.TargetSnapshot);
if (AudioMixerEffectGUI.Slider(Texts.pitch, ref value, 100.0f, 1.0f, Texts.percentage, kMinPitch, kMaxPitch, controller, new AudioGroupParameterPath(group, group.GetGUIDForPitch())))
{
Undo.RecordObject(controller.TargetSnapshot, "Change Pitch");
group.SetValueForPitch(controller, controller.TargetSnapshot, value);
}
GUILayout.Space(5f);
EditorGUILayout.EndVertical();
AudioMixerDrawUtils.DrawSplitter();
return totalRect.height;
}
public void DoEffectGUI(int effectIndex, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap, ref int highlightEffectIndex)
{
Event evt = Event.current;
AudioMixerController controller = group.controller;
AudioMixerEffectController effect = group.effects[effectIndex];
MixerParameterDefinition[] paramDefs = MixerEffectDefinitions.GetEffectParameters(effect.effectName);
// This rect is valid after every layout event
Rect totalRect = EditorGUILayout.BeginVertical();
bool hovering = totalRect.Contains(evt.mousePosition);
EventType evtType = evt.GetTypeForControl(m_EffectDragging.dragControlID);
if (evtType == EventType.MouseMove && hovering && highlightEffectIndex != effectIndex)
{
highlightEffectIndex = effectIndex;
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
// Header
const float colorCodeWidth = 6f;
var gearSize = EditorStyles.iconButton.CalcSize(EditorGUI.GUIContents.titleSettingsIcon);
Rect headerRect = GUILayoutUtility.GetRect(1, 17f);
Rect colorCodeRect = new Rect(headerRect.x + 6f, headerRect.y + 5f, colorCodeWidth, colorCodeWidth);
Rect labelRect = new Rect(headerRect.x + 8f + colorCodeWidth, headerRect.y, headerRect.width - 8f - colorCodeWidth - gearSize.x - 5f, headerRect.height);
Rect gearRect = new Rect(labelRect.xMax, headerRect.y, gearSize.x, gearSize.y);
Rect dragRect = new Rect(headerRect.x, headerRect.y, headerRect.width - gearSize.x - 5f, headerRect.height);
{
bool showCPU = EditorPrefs.GetBool(AudioMixerGroupEditor.kPrefKeyForShowCpuUsage, false) && EditorUtility.audioProfilingEnabled;
float val = EditorGUIUtility.isProSkin ? 0.1f : 1.0f;
Color headerColor = new Color(val, val, val, 0.2f);
Color origColor = GUI.color;
GUI.color = headerColor;
GUI.DrawTexture(headerRect, EditorGUIUtility.whiteTexture);
GUI.color = origColor;
Color effectColorCode = AudioMixerDrawUtils.GetEffectColor(effect);
EditorGUI.DrawRect(colorCodeRect, effectColorCode);
GUI.Label(labelRect, showCPU ? effect.effectName + string.Format(Texts.cpuFormatString, effect.GetCPUUsage(controller)) : effect.effectName, EditorStyles.boldLabel);
if (EditorGUI.DropdownButton(gearRect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Passive, EditorStyles.iconButton))
{
ShowEffectContextMenu(group, effect, effectIndex, controller, gearRect);
}
// Show context menu if right clicking in header rect (for convenience)
if (evt.type == EventType.ContextClick && headerRect.Contains(evt.mousePosition))
{
ShowEffectContextMenu(group, effect, effectIndex, controller, new Rect(evt.mousePosition.x, headerRect.y, 1, headerRect.height));
evt.Use();
}
if (evtType == EventType.Repaint)
EditorGUIUtility.AddCursorRect(dragRect, MouseCursor.ResizeVertical, m_EffectDragging.dragControlID);
}
using (new EditorGUI.DisabledScope(effect.bypass || group.bypassEffects))
{
EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins);
if (effect.IsAttenuation())
{
EditorGUILayout.BeginVertical();
float value = group.GetValueForVolume(controller, controller.TargetSnapshot);
if (AudioMixerEffectGUI.Slider(Texts.volume, ref value, 1.0f, 1.0f, Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume(), controller, new AudioGroupParameterPath(group, group.GetGUIDForVolume())))
{
Undo.RecordObject(controller.TargetSnapshot, "Change Volume Fader");
group.SetValueForVolume(controller, controller.TargetSnapshot, value);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
//FIXME
// 1) The VUMeter used is not in the same style that fits the rest of the Audio UI
// 2) The layout of the VU meters is hacked together and a lot of magic numbers are used.
int numChannels = 0;
float[] vuinfo_level = new float[9];
float[] vuinfo_peak = new float[9];
numChannels = group.controller.GetGroupVUInfo(group.groupID, true, vuinfo_level, vuinfo_peak);
if (evt.type == EventType.Layout)
{
m_LastNumChannels = numChannels;
}
else
{
if (numChannels != m_LastNumChannels)
HandleUtility.Repaint(); // Repaint to ensure correct rendered num channels
// Ensure same num channels as in layout event to not break IMGUI controlID handling
numChannels = m_LastNumChannels;
}
GUILayout.Space(4f);
for (int c = 0; c < numChannels; ++c)
{
float level = 1 - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(vuinfo_level[c], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1, true);
float peak = 1 - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(vuinfo_peak[c], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1, true);
EditorGUILayout.VUMeterHorizontal(level, peak, GUILayout.Height(10));
//This allows the meters to drop to 0 after PlayMode has stopped.
if (!EditorApplication.isPlaying && peak > 0.0F)
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
GUILayout.Space(4f);
EditorGUILayout.EndVertical();
}
if (effect.IsSend())
{
Rect buttonRect;
GUIContent buttonContent = (effect.sendTarget == null) ? Texts.none : GUIContent.Temp(effect.GetSendTargetDisplayString(effectMap));
if (AudioMixerEffectGUI.PopupButton(Texts.bus, buttonContent, EditorStyles.popup, out buttonRect))
ShowBusPopupMenu(effectIndex, @group, allGroups, effectMap, effect, buttonRect);
if (effect.sendTarget != null)
{
var wetLevel = effect.GetValueForMixLevel(controller, controller.TargetSnapshot);
var sendGuid = effect.GetGUIDForMixLevel();
if (AudioMixerEffectGUI.Slider(Texts.sendLevel, ref wetLevel, 1.0f, 1.0f, Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect, controller, new AudioEffectParameterPath(group, effect, sendGuid)))
{
Undo.RecordObject(controller.TargetSnapshot, "Change Send Level");
effect.SetValueForMixLevel(controller, controller.TargetSnapshot, wetLevel);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
}
}
if (MixerEffectDefinitions.EffectCanBeSidechainTarget(effect))
{
bool anyTargetsFound = false;
foreach (var g in allGroups)
{
foreach (var e in g.effects)
{
if (e.IsSend() && e.sendTarget == effect)
{
anyTargetsFound = true;
break;
}
}
if (anyTargetsFound)
break;
}
if (!anyTargetsFound)
{
GUILayout.Label(EditorGUIUtility.TrTextContent("No Send sources connected.", EditorGUIUtility.warningIcon));
}
}
// Wet mix
if (effect.enableWetMix && !effect.IsReceive() && !effect.IsDuckVolume() && !effect.IsAttenuation() && !effect.IsSend())
{
float wetLevel = effect.GetValueForMixLevel(controller, controller.TargetSnapshot);
if (AudioMixerEffectGUI.Slider(Texts.wet, ref wetLevel, 1.0f, 1.0f, Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect, controller, new AudioEffectParameterPath(group, effect, effect.GetGUIDForMixLevel())))
{
Undo.RecordObject(controller.TargetSnapshot, "Change Mix Level");
effect.SetValueForMixLevel(controller, controller.TargetSnapshot, wetLevel);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
}
}
// All other effects
bool drawDefaultGUI = true;
if (m_CustomEffectGUIs.ContainsKey(effect.effectName))
{
var customGUI = m_CustomEffectGUIs[effect.effectName];
m_SharedPlugin.m_Controller = controller;
m_SharedPlugin.m_Effect = effect;
m_SharedPlugin.m_ParamDefs = paramDefs;
drawDefaultGUI = customGUI.OnGUI(m_SharedPlugin);
}
if (drawDefaultGUI)
{
foreach (var p in paramDefs)
{
float value = effect.GetValueForParameter(controller, controller.TargetSnapshot, p.name);
if (AudioMixerEffectGUI.Slider(GUIContent.Temp(p.name, p.description), ref value, p.displayScale, p.displayExponent, p.units, p.minRange, p.maxRange, controller, new AudioEffectParameterPath(group, effect, effect.GetGUIDForParameter(p.name))))
{
Undo.RecordObject(controller.TargetSnapshot, "Change " + p.name);
effect.SetValueForParameter(controller, controller.TargetSnapshot, p.name, value);
}
}
if (paramDefs.Length > 0)
GUILayout.Space(6f);
}
}
m_EffectDragging.HandleDragElement(effectIndex, totalRect, dragRect, group, allGroups);
EditorGUILayout.EndVertical(); // indented effect contents
EditorGUILayout.EndVertical(); // calc total size
AudioMixerDrawUtils.DrawSplitter();
}
private static void ShowEffectContextMenu(AudioMixerGroupController group, AudioMixerEffectController effect, int effectIndex, AudioMixerController controller, Rect buttonRect)
{
GenericMenu menu = new GenericMenu();
if (!effect.IsReceive())
{
if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsDuckVolume())
{
menu.AddItem(EditorGUIUtility.TrTextContent("Allow Wet Mixing (causes higher memory usage)"), effect.enableWetMix, delegate { AudioMixerUtility.ToggleEffectWetMix(effect); });
menu.AddItem(EditorGUIUtility.TrTextContent("Bypass"), effect.bypass, delegate()
{
Undo.RecordObject(effect, "Bypass Effect");
effect.bypass = !effect.bypass;
controller.UpdateBypass();
AudioMixerUtility.RepaintAudioMixerAndInspectors();
});
menu.AddSeparator("");
}
menu.AddItem(EditorGUIUtility.TrTextContent("Copy effect settings to all snapshots"), false, delegate()
{
Undo.RecordObject(controller, "Copy effect settings to all snapshots");
if (effect.IsAttenuation())
controller.CopyAttenuationToAllSnapshots(group, controller.TargetSnapshot);
else
controller.CopyEffectSettingsToAllSnapshots(group, effectIndex, controller.TargetSnapshot, effect.IsSend());
AudioMixerUtility.RepaintAudioMixerAndInspectors();
});
if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsDuckVolume() && effect.enableWetMix)
{
menu.AddItem(EditorGUIUtility.TrTextContent("Copy effect settings to all snapshots, including wet level"), false, delegate()
{
Undo.RecordObject(controller, "Copy effect settings to all snapshots, including wet level");
controller.CopyEffectSettingsToAllSnapshots(group, effectIndex, controller.TargetSnapshot, true);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
});
}
menu.AddSeparator("");
}
AudioMixerGroupController[] groupArray = new AudioMixerGroupController[] { group };
AudioMixerChannelStripView.AddEffectItemsToMenu(controller, groupArray, effectIndex, "Add effect before/", menu);
AudioMixerChannelStripView.AddEffectItemsToMenu(controller, groupArray, effectIndex + 1, "Add effect after/", menu);
if (!effect.IsAttenuation())
{
menu.AddSeparator("");
menu.AddItem(EditorGUIUtility.TrTextContent("Remove this effect"), false, delegate()
{
controller.RemoveEffect(effect, group);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
});
}
menu.DropDown(buttonRect);
}
private static void ShowBusPopupMenu(int effectIndex, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups, Dictionary<AudioMixerEffectController, AudioMixerGroupController> effectMap, AudioMixerEffectController effect, Rect buttonRect)
{
GenericMenu pm = new GenericMenu();
var sendContext = new AudioMixerChannelStripView.ConnectSendContext(group.controller, effect, null);
pm.AddItem(EditorGUIUtility.TrTextContent("None"), false, AudioMixerChannelStripView.ConnectSendPopupCallback, sendContext);
pm.AddSeparator("");
AudioMixerChannelStripView.AddMenuItemsForReturns(pm, string.Empty, effectIndex, group, allGroups, effectMap, effect, true);
if (pm.GetItemCount() == 2)
{
pm.AddDisabledItem(EditorGUIUtility.TrTextContent("No valid Receive targets found"));
}
pm.DropDown(buttonRect);
}
// -----------------------------------
// Effect dragging logic and rendering
// -----------------------------------
class EffectDragging
{
public EffectDragging()
{
m_DragControlID = GUIUtility.GetPermanentControlID();
}
public bool IsDraggingIndex(int effectIndex)
{
return m_MovingSrcIndex == effectIndex && GUIUtility.hotControl == m_DragControlID;
}
public int dragControlID
{
get { return m_DragControlID; }
}
private bool isDragging
{
get { return m_MovingSrcIndex != -1 && GUIUtility.hotControl == m_DragControlID; }
}
private readonly Color kMoveColorBorderAllowed = new Color(1.0f, 1.0f, 1.0f, 1.0f);
private readonly Color kMoveColorHiAllowed = new Color(1.0f, 1.0f, 1.0f, 0.3f);
private readonly Color kMoveColorLoAllowed = new Color(1.0f, 1.0f, 1.0f, 0.0f);
private readonly Color kMoveColorBorderDisallowed = new Color(0.8f, 0.0f, 0.0f, 1.0f);
private readonly Color kMoveColorHiDisallowed = new Color(1.0f, 0.0f, 0.0f, 0.3f);
private readonly Color kMoveColorLoDisallowed = new Color(1.0f, 0.0f, 0.0f, 0.0f);
private readonly int m_DragControlID = 0;
private int m_MovingSrcIndex = -1;
private int m_MovingDstIndex = -1;
private bool m_MovingEffectAllowed = false;
private float m_MovingPos = 0;
private Rect m_MovingRect = new Rect(0, 0, 0, 0);
private float m_DragHighlightPos = -1.0f;
private float m_DragHighlightHeight = 2f;
// Called per effect
public void HandleDragElement(int effectIndex, Rect effectRect, Rect dragRect, AudioMixerGroupController group, List<AudioMixerGroupController> allGroups)
{
Event evt = Event.current;
switch (evt.GetTypeForControl(m_DragControlID))
{
case EventType.MouseDown:
if (evt.button == 0 && dragRect.Contains(evt.mousePosition) && GUIUtility.hotControl == 0)
{
m_MovingSrcIndex = effectIndex;
m_MovingPos = evt.mousePosition.y;
m_MovingRect = new Rect(effectRect.x, effectRect.y - m_MovingPos, effectRect.width, effectRect.height);
GUIUtility.hotControl = m_DragControlID;
EditorGUIUtility.SetWantsMouseJumping(1);
evt.Use();
}
break;
case EventType.Repaint:
if (effectIndex == m_MovingSrcIndex)
{
using (new EditorGUI.DisabledScope(true))
{
AudioMixerDrawUtils.styles.channelStripAreaBackground.Draw(effectRect, false, false, false, false);
}
}
break;
}
if (isDragging)
{
float h2 = effectRect.height * 0.5f;
float dy = evt.mousePosition.y - effectRect.y - h2;
if (Mathf.Abs(dy) <= h2)
{
int newMovingDstIndex = (dy < 0.0f) ? effectIndex : (effectIndex + 1);
if (newMovingDstIndex != m_MovingDstIndex)
{
m_DragHighlightPos = (dy < 0.0f) ? effectRect.y : (effectRect.y + effectRect.height);
m_MovingDstIndex = newMovingDstIndex;
m_MovingEffectAllowed = !AudioMixerController.WillMovingEffectCauseFeedback(allGroups, group, m_MovingSrcIndex, group, newMovingDstIndex, null);
}
}
// Do not draw drag highlight line for positions where no change will happen
if (m_MovingDstIndex == m_MovingSrcIndex || m_MovingDstIndex == m_MovingSrcIndex + 1)
{
m_DragHighlightPos = 0;
}
}
}
// Called once per OnGUI
public void HandleDragging(Rect totalRect, AudioMixerGroupController group, AudioMixerController controller)
{
// Early out if we are not dragging
if (!isDragging)
return;
Event evt = Event.current;
const float kMoveRange = 15;
switch (evt.GetTypeForControl(m_DragControlID))
{
case EventType.MouseDrag:
m_MovingPos = evt.mousePosition.y;
evt.Use();
break;
case EventType.MouseUp:
evt.Use();
if (m_MovingSrcIndex != -1)
{
if (m_MovingDstIndex != -1 && m_MovingEffectAllowed)
{
var effects = group.effects.ToList();
if (AudioMixerController.MoveEffect(ref effects, m_MovingSrcIndex, ref effects, m_MovingDstIndex))
group.effects = effects.ToArray();
}
m_MovingSrcIndex = -1;
m_MovingDstIndex = -1;
controller.m_HighlightEffectIndex = -1;
if (GUIUtility.hotControl == m_DragControlID)
GUIUtility.hotControl = 0;
EditorGUIUtility.SetWantsMouseJumping(0);
AudioMixerUtility.RepaintAudioMixerAndInspectors();
EditorGUIUtility.ExitGUI(); // Exit because we changed order of effects
}
break;
case EventType.Repaint:
if (m_DragHighlightPos > 0.0f)
{
float w = totalRect.width;
Color moveColorLo = (m_MovingEffectAllowed) ? kMoveColorLoAllowed : kMoveColorLoDisallowed;
Color moveColorHi = (m_MovingEffectAllowed) ? kMoveColorHiAllowed : kMoveColorHiDisallowed;
Color moveColorBorder = (m_MovingEffectAllowed) ? kMoveColorBorderAllowed : kMoveColorBorderDisallowed;
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingRect.x, m_DragHighlightPos - kMoveRange, w, kMoveRange), moveColorLo, moveColorHi);
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingRect.x, m_DragHighlightPos, w, kMoveRange), moveColorHi, moveColorLo);
AudioMixerDrawUtils.DrawGradientRect(new Rect(m_MovingRect.x, m_DragHighlightPos - m_DragHighlightHeight / 2, w, m_DragHighlightHeight), moveColorBorder, moveColorBorder);
}
break;
}
}
}
}
}
| UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectView.cs",
"repo_id": "UnityCsReference",
"token_count": 14894
} | 290 |
// 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.UIElements;
namespace UnityEditor.Audio.UIElements
{
internal class OnAudioFilterReadLevelMeter : IMGUIContainer
{
AudioFilterGUI m_IMGUI_AudioFilterGUI = new AudioFilterGUI();
public OnAudioFilterReadLevelMeter(MonoBehaviour behaviour)
{
onGUIHandler = () =>
{
if (GUIView.current != null)
{
m_IMGUI_AudioFilterGUI.DrawAudioFilterGUI(behaviour);
}
};
}
}
}
| UnityCsReference/Editor/Mono/Audio/UIElements/OnAudioFilterReadLevelMeter.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/UIElements/OnAudioFilterReadLevelMeter.cs",
"repo_id": "UnityCsReference",
"token_count": 311
} | 291 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
// #define DOLOG
using System;
using System.Runtime.InteropServices;
using Mono.Cecil;
using UnityEngine.Bindings;
namespace UnityEditor
{
using GenericInstanceTypeMap = System.Collections.Generic.Dictionary<TypeReference, TypeReference>;
[NativeHeader("Modules/BuildPipeline/Editor/Public/TypeDB.h")]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct FieldInfoManaged
{
public string name;
public string type;
public int flags;
public int fixedBufferLength;
public string fixedBufferTypename;
}
[NativeHeader("Modules/BuildPipeline/Editor/Public/TypeDB.h")]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct TypeInformationManaged
{
public string className;
public FieldInfoManaged[] fieldInfos;
}
[NativeHeader("Modules/BuildPipeline/Editor/Public/TypeDB.h")]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct AssemblyInfoManaged
{
public string name;
public string path;
public TypeInformationManaged[] types;
}
[Serializable]
internal class ExtractRoot<T>
{
public T[] root;
}
}
| UnityCsReference/Editor/Mono/BuildPipeline/AssemblyTypeInfoGenerator.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipeline/AssemblyTypeInfoGenerator.cs",
"repo_id": "UnityCsReference",
"token_count": 501
} | 292 |
// 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;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEditor.Compilation;
using UnityEditor.Scripting.ScriptCompilation;
using UnityEngine.Scripting;
using System.Diagnostics;
namespace UnityEditor
{
/// <summary>
/// Registry for Unity native-managed class dependencies. Aimed to make native and managed code stripping possible.
/// Note: only UnityEngine.dll content is covered there.
/// </summary>
internal class RuntimeClassRegistry
{
protected Dictionary<string, HashSet<string>> serializedClassesPerAssembly = new Dictionary<string, HashSet<string>>();
protected Dictionary<string, HashSet<string>> m_UsedTypesPerUserAssembly = new Dictionary<string, HashSet<string>>();
protected Dictionary<int, List<string>> classScenes = new Dictionary<int, List<string>>();
protected UnityType objectUnityType = null;
public Dictionary<string, HashSet<string>> UsedTypePerUserAssembly
{
get { return m_UsedTypesPerUserAssembly; }
}
// Store all registered native classes (including managers) here.
// This is a step in the refactor of native code stripping. RuntimeClassRegistry should only be carrying this information to post process scripts rather than doing so much.
protected Dictionary<int, string> allNativeClasses = new Dictionary<int, string>();
public List<string> GetScenesForClass(int ID)
{
if (!classScenes.ContainsKey(ID))
return null;
return classScenes[ID];
}
[RequiredByNativeCode]
public void AddNativeClassID(int ID)
{
string className = UnityType.FindTypeByPersistentTypeID(ID).name;
////System.Console.WriteLine("Looking for ID {0} name {1} --> is manager? {2}", ID, className, functionalityGroups.ContainsValue(className));
// Native class found
if (className.Length > 0)
allNativeClasses[ID] = className;
}
[RequiredByNativeCode]
public void SetUsedTypesInUserAssembly(string[] typeNames, string assemblyName)
{
string assemblyFileName = assemblyName;
if (!assemblyFileName.EndsWith(".dll"))
{
assemblyFileName = assemblyName + ".dll";
}
if (!m_UsedTypesPerUserAssembly.TryGetValue(assemblyFileName, out HashSet<string> types))
{
m_UsedTypesPerUserAssembly[assemblyFileName] = types = new HashSet<string>();
}
foreach (var typeName in typeNames)
types.Add(typeName);
}
[RequiredByNativeCode]
public void SetSerializedTypesInUserAssembly(string[] typeNames, string assemblyName)
{
if (!serializedClassesPerAssembly.TryGetValue(assemblyName, out HashSet<string> types))
serializedClassesPerAssembly[assemblyName] = types = new HashSet<string>();
foreach (var typeName in typeNames)
types.Add(typeName);
}
private static readonly string[] s_TreatedAsUserAssemblies =
{
// Treat analytics as we user assembly. If it is not used, it won't be in the directory,
// so this should not add to the build size unless it is really used.
"Unity.Analytics.dll",
};
private static string[] GetTargetUserAssemblyNames()
{
EditorCompilation.TargetAssemblyInfo[] allTargetAssemblies = EditorCompilationInterface.GetTargetAssemblyInfos();
string[] targetAssemblyNames = new string[allTargetAssemblies.Length + s_TreatedAsUserAssemblies.Length];
for (int i = 0; i < allTargetAssemblies.Length; ++i)
{
targetAssemblyNames[i] = allTargetAssemblies[i].Name;
}
for (int i = 0; i < s_TreatedAsUserAssemblies.Length; ++i)
{
targetAssemblyNames[allTargetAssemblies.Length + i] = s_TreatedAsUserAssemblies[i];
}
for (int i=0; i<targetAssemblyNames.Length; ++i)
{
if (!targetAssemblyNames[i].EndsWith(".dll"))
targetAssemblyNames[i] += ".dll";
}
return targetAssemblyNames;
}
private bool IsAssemblyDLLUsed(string assemblyName, string[] userAssemblyNames)
{
Debug.Assert(assemblyName.EndsWith(".dll"));
if (m_UsedTypesPerUserAssembly == null)
return true;
if (Array.IndexOf(userAssemblyNames, assemblyName) != -1)
{
// Don't treat code in packages as used automatically (case 1003047).
var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);
if (asmdefPath == null || !EditorCompilationInterface.Instance.IsPathInPackageDirectory(asmdefPath))
return true;
}
bool isUsed = m_UsedTypesPerUserAssembly.ContainsKey(assemblyName);
return isUsed;
}
protected void AddUsedClass(string assemblyName, string className)
{
if (string.IsNullOrEmpty(assemblyName))
throw new ArgumentException(nameof(assemblyName));
if (string.IsNullOrEmpty(className))
throw new ArgumentException(nameof(className));
string assemblyFileName = assemblyName;
if (!assemblyFileName.EndsWith(".dll"))
{
assemblyFileName = assemblyName + ".dll";
}
if (!m_UsedTypesPerUserAssembly.TryGetValue(assemblyFileName, out HashSet<string> types))
{
m_UsedTypesPerUserAssembly[assemblyFileName] = types = new HashSet<string>();
}
types.Add(className);
}
[RequiredByNativeCode]
protected void AddSerializedClass(string assemblyName, string className)
{
if (string.IsNullOrEmpty(assemblyName))
throw new ArgumentException(nameof(assemblyName));
if (string.IsNullOrEmpty(className))
throw new ArgumentException(nameof(className));
if (!serializedClassesPerAssembly.TryGetValue(assemblyName, out HashSet<string> types))
serializedClassesPerAssembly[assemblyName] = types = new HashSet<string>();
types.Add(className);
}
public void AddNativeClassFromName(string className)
{
if (objectUnityType == null)
objectUnityType = UnityType.FindTypeByName("Object");
var t = UnityType.FindTypeByName(className);
////System.Console.WriteLine("Looking for name {1} ID {0}", classID, className);
if (t != null && t.persistentTypeID != objectUnityType.persistentTypeID)
allNativeClasses[t.persistentTypeID] = className;
}
public Dictionary<string, string[]> GetAllManagedTypesInScenes()
{
var items = new Dictionary<string, string[]>();
// Use a hashset to remove duplicate types.
// Duplicates of UnityEngine.Object will happen because native types without a managed type will come back as
// UnityEngine.Object
var engineModuleTypes = new HashSet<string>();
foreach (var nativeClassID in allNativeClasses.Keys)
{
var managedName = RuntimeClassMetadataUtils.ScriptingWrapperTypeNameForNativeID(nativeClassID);
if (string.IsNullOrEmpty(managedName))
continue;
engineModuleTypes.Add(managedName);
}
bool engineModuleTypesAdded = false;
foreach (var userAssembly in m_UsedTypesPerUserAssembly)
{
if (userAssembly.Key == "UnityEngine.dll" && !engineModuleTypesAdded)
{
engineModuleTypes.UnionWith(userAssembly.Value);
items.Add(userAssembly.Key, engineModuleTypes.ToArray());
engineModuleTypesAdded = true;
continue;
}
items.Add(userAssembly.Key, userAssembly.Value.ToArray());
}
if (!engineModuleTypesAdded)
{
items.Add("UnityEngine.dll", engineModuleTypes.ToArray());
}
return items;
}
public List<string> GetAllNativeClassesIncludingManagersAsString()
{
return new List<string>(allNativeClasses.Values);
}
public IEnumerable<KeyValuePair<string, string[]>> GetAllSerializedClassesAsString()
{
foreach (var pair in serializedClassesPerAssembly)
{
yield return new KeyValuePair<string, string[]>(pair.Key, pair.Value.ToArray());
}
}
[RequiredByNativeCode]
public MethodDescription[] GetAllMethodsToPreserve()
{
return m_MethodsToPreserve.ToArray();
}
[RequiredByNativeCode]
public string[] GetAllSerializedClassesAssemblies()
{
return serializedClassesPerAssembly.Keys.ToArray();
}
[RequiredByNativeCode]
public string[] GetAllSerializedClassesForAssembly(string assembly)
{
return serializedClassesPerAssembly[assembly].ToArray();
}
[RequiredByNativeCode]
public static RuntimeClassRegistry Create()
{
return new RuntimeClassRegistry();
}
[RequiredByNativeCode]
public void Initialize(int[] nativeClassIDs)
{
foreach (int ID in nativeClassIDs)
AddNativeClassID(ID);
}
[RequiredByNativeCode]
public void SetSceneClasses(int[] nativeClassIDs, string scene)
{
foreach (int ID in nativeClassIDs)
{
AddNativeClassID(ID);
if (!classScenes.ContainsKey(ID))
classScenes[ID] = new List<string>();
classScenes[ID].Add(scene);
}
}
// Needs to stay in sync with MethodDescription in Editor/Src/BuildPipeline/BuildSerialization.h
[StructLayout(LayoutKind.Sequential)]
internal class MethodDescription
{
public string assembly;
public string fullTypeName;
public string methodName;
}
internal List<MethodDescription> m_MethodsToPreserve = new List<MethodDescription>();
//invoked by native code
[RequiredByNativeCode]
public void AddMethodToPreserve(string assembly, string ns, string klassName, string methodName)
{
m_MethodsToPreserve.Add(new MethodDescription()
{
assembly = assembly,
fullTypeName = ns + (ns.Length > 0 ? "." : "") + klassName,
methodName = methodName
});
}
[RequiredByNativeCode]
public void AddMethodToPreserveWithFullTypeName(string assembly, string fullTypeName, string methodName)
{
m_MethodsToPreserve.Add(new MethodDescription()
{
assembly = assembly,
fullTypeName = fullTypeName,
methodName = methodName
});
}
internal List<MethodDescription> GetMethodsToPreserve()
{
return m_MethodsToPreserve;
}
internal List<string> m_UserAssemblies = new List<string>();
//invoked by native code
[RequiredByNativeCode]
internal void AddUserAssembly(string assembly)
{
if (!m_UserAssemblies.Contains(assembly))
m_UserAssemblies.Add(assembly);
}
internal string[] GetUsedUserAssemblies()
{
var userAssemblyNames = GetTargetUserAssemblyNames();
return m_UserAssemblies.Where(s => IsAssemblyDLLUsed(s, userAssemblyNames)).ToArray();
}
}
}
| UnityCsReference/Editor/Mono/BuildPipeline/RuntimeClassMetadata.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipeline/RuntimeClassMetadata.cs",
"repo_id": "UnityCsReference",
"token_count": 5389
} | 293 |
// 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 UnityEditor.IMGUI.Controls;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.SceneManagement;
namespace UnityEditor.Build.Profile
{
/// <summary>
/// Handles mapping the existing <see cref="BuildPlayerSceneTreeView"/> component
/// to build profile. Classic platforms specifically target scenes stored in
/// <see cref="EditorBuildSettings"/>.
/// </summary>
[VisibleToOtherModules("UnityEditor.BuildProfileModule")]
internal class BuildProfileSceneTreeView : BuildPlayerSceneTreeView
{
readonly bool m_IsEditorBuildSettingsSceneList;
readonly BuildProfile m_Target;
public BuildProfileSceneTreeView(TreeViewState state, BuildProfile target) : base(state)
{
m_Target = target;
m_IsEditorBuildSettingsSceneList = target == null;
}
/// <summary>
/// Exported from <see cref="BuildPlayerWindow"/>.
/// </summary>
public void AddOpenScenes()
{
List<EditorBuildSettingsScene> list = new List<EditorBuildSettingsScene>(GetScenes());
bool isSceneAdded = false;
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene scene = SceneManager.GetSceneAt(i);
if (EditorSceneManager.IsAuthoringScene(scene))
continue;
if (scene.path.Length == 0 && !EditorSceneManager.SaveScene(scene, "", false))
continue;
if (list.Exists(s => s.path == scene.path))
continue;
GUID newGUID;
GUID.TryParse(scene.guid, out newGUID);
var buildSettingsScene = (newGUID == default(GUID)) ?
new EditorBuildSettingsScene(scene.path, true) :
new EditorBuildSettingsScene(newGUID, true);
list.Add(buildSettingsScene);
isSceneAdded = true;
}
if (!isSceneAdded)
return;
SetScenes(list.ToArray());
Reload();
GUIUtility.ExitGUI();
}
protected override EditorBuildSettingsScene[] GetScenes() => (m_IsEditorBuildSettingsSceneList)
? EditorBuildSettings.GetEditorBuildSettingsSceneIgnoreProfile()
: m_Target.scenes;
protected override void SetScenes(EditorBuildSettingsScene[] scenes)
{
if (!m_IsEditorBuildSettingsSceneList)
{
Undo.RecordObject(m_Target, "Scene list");
m_Target.scenes = scenes;
EditorUtility.SetDirty(m_Target);
return;
}
// Classic platforms scene list can only be changed through this component
// and write data directly to EditorBuildSettings.
EditorBuildSettings.SetEditorBuildSettingsSceneIgnoreProfile(scenes);
if (BuildProfileContext.instance.activeProfile is null)
EditorBuildSettings.SceneListChanged();
}
}
}
| UnityCsReference/Editor/Mono/BuildProfile/BuildProfileSceneListTreeView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildProfile/BuildProfileSceneListTreeView.cs",
"repo_id": "UnityCsReference",
"token_count": 1406
} | 294 |
// 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 JetBrains.Annotations;
using UnityEngine;
using UnityEngine.Scripting;
namespace UnityEditor.Experimental.Rendering
{
[RequiredByNativeCode]
public static class ScriptableBakedReflectionSystemSettings
{
public static IScriptableBakedReflectionSystem system
{
get { return Internal_ScriptableBakedReflectionSystemSettings_system; }
set { Internal_ScriptableBakedReflectionSystemSettings_system = value; }
}
static IScriptableBakedReflectionSystem Internal_ScriptableBakedReflectionSystemSettings_system
{
[RequiredByNativeCode] get { return s_Instance?.implementation; }
[RequiredByNativeCode] set
{
if (s_Instance == null)
{
Console.WriteLine("[WARNING] ScriptableBakedReflectionSystemWrapper instance must be initialized from CPP before InitializeOnLoad");
return;
}
if (value == null || value.Equals(null))
{
Debug.LogError("'null' cannot be assigned to ScriptableBakedReflectionSystemSettings.system");
return;
}
// We always allow the BuiltinBakedReflectionSystem, it is set by Unity on domain reload
// However, we issue a warning when multiple different IScriptableBakedReflectionSystem have been assigned.
if (!(system is BuiltinBakedReflectionSystem)
&& !(value is BuiltinBakedReflectionSystem)
&& system != value)
Debug.LogWarningFormat("ScriptableBakedReflectionSystemSettings.system is assigned more than once. Only a the last instance will be used. (Last instance {0}, New instance {1})", system, value);
if (s_Instance.implementation != value)
{
if (s_Instance.implementation != null)
s_Instance.implementation.Dispose();
s_Instance.implementation = value;
}
}
}
static ScriptableBakedReflectionSystemWrapper s_Instance = null;
[UsedImplicitly, RequiredByNativeCode]
static ScriptableBakedReflectionSystemWrapper Internal_ScriptableBakedReflectionSystemSettings_InitializeWrapper(IntPtr ptr)
{
s_Instance = new ScriptableBakedReflectionSystemWrapper(ptr);
return s_Instance;
}
}
}
| UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystemSettings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystemSettings.cs",
"repo_id": "UnityCsReference",
"token_count": 1128
} | 295 |
// 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.Security.Cryptography;
using System.Text;
using UnityEngine.Scripting;
namespace UnityEditor
{
internal class SyncVS
{
[RequiredByNativeCode]
public static void SyncSolution()
{
// Ensure that the mono islands are up-to-date
AssetDatabase.Refresh();
// TODO: Rider and possibly other code editors, use reflection to call this method.
// To avoid conflicts and null reference exception, this is left as a dummy method.
Unity.CodeEditor.CodeEditor.Editor.CurrentCodeEditor.SyncAll();
}
}
namespace VisualStudioIntegration
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static class SolutionGuidGenerator
{
public static string GuidForProject(string projectName)
{
return ComputeGuidHashFor(projectName + "salt");
}
public static string GuidForSolution(string projectName, string sourceFileExtension)
{
if (sourceFileExtension.ToLower() == "cs")
// GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs
return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
return ComputeGuidHashFor(projectName);
}
private static string ComputeGuidHashFor(string input)
{
var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input));
return HashAsGuid(HashToString(hash));
}
private static string HashAsGuid(string hash)
{
var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12);
return guid.ToUpper();
}
private static string HashToString(byte[] bs)
{
var sb = new StringBuilder();
foreach (byte b in bs)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
}
}
| UnityCsReference/Editor/Mono/CodeEditor/SyncVS.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/CodeEditor/SyncVS.cs",
"repo_id": "UnityCsReference",
"token_count": 1088
} | 296 |
// 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.Scripting;
namespace UnityEditor;
internal partial class CustomEditorAttributes
{
[RequiredByNativeCode]
internal static Type FindCustomEditorType(Object obj, bool multiEdit)
{
return obj == null ? null : FindCustomEditorTypeByType(obj.GetType(), multiEdit);
}
[RequiredByNativeCode]
internal static Type FindCustomEditorTypeByType(Type type, bool multiEdit)
{
return instance.GetCustomEditorType(type, multiEdit);
}
}
| UnityCsReference/Editor/Mono/CustomEditorAttributes.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/CustomEditorAttributes.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 207
} | 297 |
// 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;
namespace UnityEditor
{
internal class DropInfo
{
internal enum Type
{
// The window will be inserted as a tab into dropArea
Tab = 0,
// The window will be a new pane (inside a scrollView)
Pane = 1,
// A new window should be created.
Window
}
public DropInfo(IDropArea source)
{
dropArea = source;
}
// Who claimed the drop?
public IDropArea dropArea;
// Extra data for the recipient to communicate between DragOVer and PerformDrop
public object userData = null;
// Which type of dropzone are we looking for?
public Type type = Type.Window;
// Where should the preview end up on screen.
public Rect rect;
}
}
| UnityCsReference/Editor/Mono/DropInfo.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/DropInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 412
} | 298 |
// 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 UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using UnityEditorInternal;
using UnityEngine.Events;
using UnityEngine.Internal;
using UnityEngine.Scripting;
using UnityEngineInternal;
using UnityEditor.StyleSheets;
using UnityEditor.Experimental;
using UnityEditor.SceneManagement;
using UnityEngine.Bindings;
using UnityEngine.Pool;
using UnityEngine.UIElements;
using UnityObject = UnityEngine.Object;
namespace UnityEditor
{
public sealed partial class EditorGUIUtility : GUIUtility
{
internal static void RegisterResourceForCleanupOnDomainReload(UnityObject obj)
{
AppDomain.CurrentDomain.DomainUnload += (object sender, EventArgs e) => { UnityObject.DestroyImmediate(obj); };
}
public class PropertyCallbackScope : IDisposable
{
Action<Rect, SerializedProperty> m_Callback;
public PropertyCallbackScope(Action<Rect, SerializedProperty> callback)
{
m_Callback = callback;
if (m_Callback != null)
EditorGUIUtility.beginProperty += callback;
}
public void Dispose()
{
if (m_Callback != null)
EditorGUIUtility.beginProperty -= m_Callback;
}
}
public class IconSizeScope : GUI.Scope
{
private readonly Vector2 m_OriginalIconSize;
public IconSizeScope(Vector2 iconSizeWithinScope)
{
m_OriginalIconSize = GetIconSize();
SetIconSize(iconSizeWithinScope);
}
protected override void CloseScope()
{
SetIconSize(m_OriginalIconSize);
}
}
internal static Material s_GUITextureBlit2SRGBMaterial;
internal static Material GUITextureBlit2SRGBMaterial
{
get
{
if (!s_GUITextureBlit2SRGBMaterial)
{
Shader shader = LoadRequired("SceneView/GUITextureBlit2SRGB.shader") as Shader;
s_GUITextureBlit2SRGBMaterial = new Material(shader);
s_GUITextureBlit2SRGBMaterial.hideFlags |= HideFlags.DontSaveInEditor;
RegisterResourceForCleanupOnDomainReload(s_GUITextureBlit2SRGBMaterial);
}
s_GUITextureBlit2SRGBMaterial.SetFloat("_ManualTex2SRGB", QualitySettings.activeColorSpace == ColorSpace.Linear ? 1.0f : 0.0f);
return s_GUITextureBlit2SRGBMaterial;
}
}
internal static Material s_GUITextureBlitSceneGUI;
internal static Material GUITextureBlitSceneGUIMaterial
{
get
{
if (!s_GUITextureBlitSceneGUI)
{
Shader shader = LoadRequired("SceneView/GUITextureBlitSceneGUI.shader") as Shader;
s_GUITextureBlitSceneGUI = new Material(shader);
s_GUITextureBlitSceneGUI.hideFlags |= HideFlags.DontSaveInEditor;
RegisterResourceForCleanupOnDomainReload(s_GUITextureBlitSceneGUI);
}
return s_GUITextureBlitSceneGUI;
}
}
internal static int s_FontIsBold = -1;
internal static int s_LastControlID = 0;
private static float s_LabelWidth = 0f;
private static ScalableGUIContent s_InfoIcon;
private static ScalableGUIContent s_WarningIcon;
private static ScalableGUIContent s_ErrorIcon;
private static GUIStyle s_WhiteTextureStyle;
private static GUIStyle s_BasicTextureStyle;
static Hashtable s_TextGUIContents = new Hashtable();
static Hashtable s_GUIContents = new Hashtable();
static Hashtable s_IconGUIContents = new Hashtable();
static Hashtable s_SkinnedIcons = new Hashtable();
private static readonly GUIContent s_ObjectContent = new GUIContent();
private static readonly GUIContent s_Text = new GUIContent();
private static readonly GUIContent s_Image = new GUIContent();
private static readonly GUIContent s_TextImage = new GUIContent();
private static GUIContent s_SceneMismatch = TrTextContent("Scene mismatch (cross scene references not supported)");
private static GUIContent s_TypeMismatch = TrTextContent("Type mismatch");
internal static readonly SVC<Color> kViewBackgroundColor = new SVC<Color>("view", StyleCatalogKeyword.backgroundColor, GetDefaultBackgroundColor);
/// The current UI scaling factor for high-DPI displays. For instance, 2.0 on a retina display
public new static float pixelsPerPoint => GUIUtility.pixelsPerPoint;
static EditorGUIUtility()
{
GUISkin.m_SkinChanged += SkinChanged;
s_HasCurrentWindowKeyFocusFunc = HasCurrentWindowKeyFocus;
}
// this method gets called on right clicking a property regardless of GUI.enable value.
internal static event Action<GenericMenu, SerializedProperty> contextualPropertyMenu;
internal static event Action<Rect, SerializedProperty> beginProperty;
internal static void BeginPropertyCallback(Rect totalRect, SerializedProperty property)
{
beginProperty?.Invoke(totalRect, property);
}
internal static void ContextualPropertyMenuCallback(GenericMenu gm, SerializedProperty prop)
{
if (contextualPropertyMenu != null)
{
if (gm.GetItemCount() > 0)
gm.AddSeparator("");
contextualPropertyMenu(gm, prop);
}
}
// returns position and size of the main Unity Editor window
public static Rect GetMainWindowPosition()
{
foreach (var win in ContainerWindow.windows)
{
if (win.IsMainWindow())
return win.position;
}
return new Rect(0, 0, 1000, 600);
}
// sets position and size of the main Unity Editor window
public static void SetMainWindowPosition(Rect position)
{
foreach (var win in ContainerWindow.windows)
{
if (win.IsMainWindow())
{
win.position = position;
break;
}
}
}
internal static Rect GetCenteredWindowPosition(Rect parentWindowPosition, Vector2 size)
{
var pos = new Rect
{
x = 0,
y = 0,
width = Mathf.Min(size.x, parentWindowPosition.width * 0.90f),
height = Mathf.Min(size.y, parentWindowPosition.height * 0.90f)
};
var w = (parentWindowPosition.width - pos.width) * 0.5f;
var h = (parentWindowPosition.height - pos.height) * 0.5f;
pos.x = parentWindowPosition.x + w;
pos.y = parentWindowPosition.y + h;
return pos;
}
internal static void RepaintCurrentWindow()
{
CheckOnGUI();
GUIView.current.Repaint();
}
internal static bool HasCurrentWindowKeyFocus()
{
CheckOnGUI();
return GUIView.current != null && GUIView.current.hasFocus;
}
public static Rect PointsToPixels(Rect rect)
{
var cachedPixelsPerPoint = pixelsPerPoint;
rect.x *= cachedPixelsPerPoint;
rect.y *= cachedPixelsPerPoint;
rect.width *= cachedPixelsPerPoint;
rect.height *= cachedPixelsPerPoint;
return rect;
}
public static Rect PixelsToPoints(Rect rect)
{
var cachedInvPixelsPerPoint = 1f / pixelsPerPoint;
rect.x *= cachedInvPixelsPerPoint;
rect.y *= cachedInvPixelsPerPoint;
rect.width *= cachedInvPixelsPerPoint;
rect.height *= cachedInvPixelsPerPoint;
return rect;
}
public static Vector2 PointsToPixels(Vector2 position)
{
var cachedPixelsPerPoint = pixelsPerPoint;
position.x *= cachedPixelsPerPoint;
position.y *= cachedPixelsPerPoint;
return position;
}
public static Vector2 PixelsToPoints(Vector2 position)
{
var cachedInvPixelsPerPoint = 1f / pixelsPerPoint;
position.x *= cachedInvPixelsPerPoint;
position.y *= cachedInvPixelsPerPoint;
return position;
}
// Given a rectangle, GUI style and a list of items, lay them out sequentially;
// left to right, top to bottom.
public static List<Rect> GetFlowLayoutedRects(Rect rect, GUIStyle style, float horizontalSpacing, float verticalSpacing, List<string> items)
{
var result = new List<Rect>(items.Count);
var curPos = rect.position;
foreach (string item in items)
{
var gc = TempContent(item);
var itemSize = style.CalcSize(gc);
var itemRect = new Rect(curPos, itemSize);
// Reached right side, go to next row
if (curPos.x + itemSize.x + horizontalSpacing >= rect.xMax)
{
curPos.x = rect.x;
curPos.y += itemSize.y + verticalSpacing;
itemRect.position = curPos;
}
result.Add(itemRect);
// Move next item to the left
curPos.x += itemSize.x + horizontalSpacing;
}
return result;
}
internal class SkinnedColor
{
Color normalColor;
Color proColor;
public SkinnedColor(Color color, Color proColor)
{
normalColor = color;
this.proColor = proColor;
}
public SkinnedColor(Color color)
{
normalColor = color;
proColor = color;
}
public Color color
{
get { return isProSkin ? proColor : normalColor; }
set
{
if (isProSkin)
proColor = value;
else
normalColor = value;
}
}
public static implicit operator Color(SkinnedColor colorSkin)
{
return colorSkin.color;
}
}
private delegate bool HeaderItemDelegate(Rect rectangle, UnityObject[] targets);
private static List<HeaderItemDelegate> s_EditorHeaderItemsMethods = null;
internal static Rect DrawEditorHeaderItems(Rect rectangle, UnityObject[] targetObjs, float spacing = 0)
{
if (targetObjs.Length == 0 || (targetObjs.Length == 1 && targetObjs[0].GetType() == typeof(System.Object)))
return rectangle;
if (comparisonViewMode != ComparisonViewMode.None)
return rectangle;
if (s_EditorHeaderItemsMethods == null)
{
List<Type> targetObjTypes = new List<Type>();
var type = targetObjs[0].GetType();
while (type.BaseType != null)
{
targetObjTypes.Add(type);
type = type.BaseType;
}
AttributeHelper.MethodInfoSorter methods = AttributeHelper.GetMethodsWithAttribute<EditorHeaderItemAttribute>(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
Func<EditorHeaderItemAttribute, bool> filter = (a) => targetObjTypes.Any(c => a.TargetType == c);
var methodInfos = methods.FilterAndSortOnAttribute(filter, (a) => a.callbackOrder);
s_EditorHeaderItemsMethods = new List<HeaderItemDelegate>();
foreach (MethodInfo methodInfo in methodInfos)
{
s_EditorHeaderItemsMethods.Add((HeaderItemDelegate)Delegate.CreateDelegate(typeof(HeaderItemDelegate), methodInfo));
}
}
float spacingToRemove = 0;
foreach (HeaderItemDelegate @delegate in s_EditorHeaderItemsMethods)
{
if (@delegate(rectangle, targetObjs))
{
rectangle.x -= rectangle.width + spacing;
spacingToRemove = rectangle.width + spacing;
}
}
rectangle.x += spacingToRemove; // the spacing after a delegate is used to position the next element to draw but the last one is not used so we must remove it before exiting the method
return rectangle;
}
/// <summary>
/// Use this container and helper class when implementing lock behaviour on a window.
/// </summary>
[Serializable]
internal class EditorLockTracker
{
[Serializable] public class LockStateEvent : UnityEvent<bool> {}
[HideInInspector]
internal LockStateEvent lockStateChanged = new LockStateEvent();
const string k_LockMenuText = "Lock";
static readonly GUIContent k_LockMenuGUIContent = TextContent(k_LockMenuText);
/// <summary>
/// don't set or get this directly unless from within the <see cref="isLocked"/> property,
/// as that property also keeps track of the potentially existing tracker in <see cref="EditorLockTrackerWithActiveEditorTracker"/>
/// </summary>
[SerializeField, HideInInspector]
bool m_IsLocked;
PingData m_Ping = new PingData();
internal virtual bool isLocked
{
get
{
return m_IsLocked;
}
set
{
bool wasLocked = m_IsLocked;
m_IsLocked = value;
if (wasLocked != m_IsLocked)
{
lockStateChanged.Invoke(m_IsLocked);
}
}
}
internal virtual void AddItemsToMenu(GenericMenu menu, bool disabled = false)
{
if (disabled)
{
menu.AddDisabledItem(k_LockMenuGUIContent);
}
else
{
menu.AddItem(k_LockMenuGUIContent, isLocked, FlipLocked);
}
}
internal virtual void PingIcon()
{
m_Ping.isPinging = true;
if (m_Ping.m_PingStyle == null)
{
m_Ping.m_PingStyle = new GUIStyle("TV Ping");
// The default padding is too high for such a small icon and causes the animation to become offset to the left.
m_Ping.m_PingStyle.padding = new RectOffset(8, 0, 0, 0);
}
}
internal virtual void StopPingIcon()
{
m_Ping.isPinging = false;
}
internal bool ShowButton(Rect position, GUIStyle lockButtonStyle, bool disabled = false)
{
using (new EditorGUI.DisabledScope(disabled))
{
EditorGUI.BeginChangeCheck();
bool newLock = GUI.Toggle(position, isLocked, GUIContent.none, lockButtonStyle);
if (m_Ping.isPinging && Event.current.type == EventType.Layout)
{
m_Ping.m_ContentRect = position;
m_Ping.m_ContentRect.width *= 2f;
m_Ping.m_AvailableWidth = GUIView.current.position.width;
m_Ping.m_ContentDraw = r =>
{
GUI.Toggle(r, newLock, GUIContent.none, lockButtonStyle);
};
}
m_Ping.HandlePing();
if (EditorGUI.EndChangeCheck())
{
if (newLock != isLocked)
{
FlipLocked();
m_Ping.isPinging = false;
}
}
}
return m_Ping.isPinging;
}
void FlipLocked()
{
isLocked = !isLocked;
}
}
// Get a texture from its source filename
public static Texture2D FindTexture(string name)
{
return FindTextureByName(name);
}
// Get texture from managed type
internal static Texture2D FindTexture(Type type)
{
return FindTextureByType(type);
}
public static GUIContent TrTextContent(string key, string text, string tooltip, Texture icon)
{
GUIContent gc = (GUIContent)s_GUIContents[key];
if (gc == null)
{
gc = new GUIContent(L10n.Tr(text));
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
}
if (icon != null)
{
gc.image = icon;
}
s_GUIContents[key] = gc;
}
return gc;
}
public static GUIContent TrTextContent(string text, string tooltip = null, Texture icon = null)
{
string key = string.Format("{0}|{1}", text ?? "", tooltip ?? "");
return TrTextContent(key, text, tooltip, icon);
}
public static GUIContent TrTextContent(string text, string tooltip, string iconName)
{
string key = iconName == null ? string.Format("{0}|{1}", text ?? "", tooltip ?? "") :
string.Format("{0}|{1}|{2}|{3}", text ?? "", tooltip ?? "", iconName, pixelsPerPoint);
return TrTextContent(key, text, tooltip, LoadIconRequired(iconName));
}
public static GUIContent TrTextContent(string text, Texture icon)
{
return TrTextContent(text, null, icon);
}
public static GUIContent TrTextContentWithIcon(string text, Texture icon)
{
return TrTextContent(text, null, icon);
}
public static GUIContent TrTextContentWithIcon(string text, string iconName)
{
return TrTextContent(text, null, iconName);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, string iconName)
{
return TrTextContent(text, tooltip, iconName);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, Texture icon)
{
return TrTextContent(text, tooltip, icon);
}
public static GUIContent TrTextContentWithIcon(string text, string tooltip, MessageType messageType)
{
return TrTextContent(text, tooltip, GetHelpIcon(messageType));
}
public static GUIContent TrTextContentWithIcon(string text, MessageType messageType)
{
return TrTextContentWithIcon(text, null, messageType);
}
internal static Texture2D LightenTexture(Texture2D texture)
{
if (!texture)
return texture;
Texture2D outTexture = new Texture2D(texture.width, texture.height);
var outColorArray = outTexture.GetPixels();
var colorArray = texture.GetPixels();
for (var i = 0; i < colorArray.Length; ++i)
outColorArray[i] = LightenColor(colorArray[i]);
outTexture.hideFlags = HideFlags.HideAndDontSave;
outTexture.SetPixels(outColorArray);
outTexture.Apply();
return outTexture;
}
internal static Color LightenColor(Color color)
{
Color.RGBToHSV(color, out var h, out _, out _);
var outColor = Color.HSVToRGB((h + 0.5f) % 1, 0f, 0.8f);
outColor.a = color.a;
return outColor;
}
public static GUIContent TrIconContent(string iconName, string tooltip = null)
{
return TrIconContent(iconName, tooltip, false);
}
internal static GUIContent TrIconContent(string iconName, string tooltip, bool lightenTexture)
{
string key = tooltip == null ? string.Format("{0}|{1}", iconName, pixelsPerPoint) :
string.Format("{0}|{1}|{2}", iconName, tooltip, pixelsPerPoint);
GUIContent gc = (GUIContent)s_IconGUIContents[key];
if (gc != null)
{
return gc;
}
gc = new GUIContent();
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
}
gc.image = LoadIconRequired(iconName);
if (lightenTexture && gc.image is Texture2D tex2D)
gc.image = LightenTexture(tex2D);
s_IconGUIContents[key] = gc;
return gc;
}
public static GUIContent TrIconContent(Texture icon, string tooltip = null)
{
GUIContent gc = (tooltip != null) ? (GUIContent)s_IconGUIContents[tooltip] : null;
if (gc != null)
{
return gc;
}
gc = new GUIContent { image = icon };
if (tooltip != null)
{
gc.tooltip = L10n.Tr(tooltip);
s_IconGUIContents[tooltip] = gc;
}
return gc;
}
[ExcludeFromDocs]
public static GUIContent TrTempContent(string t)
{
return TempContent(L10n.Tr(t));
}
[ExcludeFromDocs]
public static GUIContent[] TrTempContent(string[] texts)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(L10n.Tr(texts[i]));
return retval;
}
[ExcludeFromDocs]
public static GUIContent[] TrTempContent(string[] texts, string[] tooltips)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(L10n.Tr(texts[i]), L10n.Tr(tooltips[i]));
return retval;
}
internal static GUIContent TrIconContent<T>(string tooltip = null) where T : UnityObject
{
return TrIconContent(FindTexture(typeof(T)), tooltip);
}
public static float singleLineHeight => EditorGUI.kSingleLineHeight;
public static float standardVerticalSpacing => EditorGUI.kControlVerticalSpacing;
internal static SliderLabels sliderLabels = new SliderLabels();
internal static GUIContent TextContent(string textAndTooltip)
{
if (textAndTooltip == null)
textAndTooltip = "";
string key = textAndTooltip;
GUIContent gc = (GUIContent)s_TextGUIContents[key];
if (gc == null)
{
string[] strings = GetNameAndTooltipString(textAndTooltip);
gc = new GUIContent(strings[1]);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_TextGUIContents[key] = gc;
}
return gc;
}
internal static GUIContent TextContentWithIcon(string textAndTooltip, string icon)
{
if (textAndTooltip == null)
textAndTooltip = "";
if (icon == null)
icon = "";
string key = string.Format("{0}|{1}|{2}", textAndTooltip, icon, pixelsPerPoint);
GUIContent gc = (GUIContent)s_TextGUIContents[key];
if (gc == null)
{
string[] strings = GetNameAndTooltipString(textAndTooltip);
gc = new GUIContent(strings[1]) { image = LoadIconRequired(icon) };
// We want to catch missing icons so we can fix them (therefore using LoadIconRequired)
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_TextGUIContents[key] = gc;
}
return gc;
}
private static Color GetDefaultBackgroundColor()
{
float kViewBackgroundIntensity = isProSkin ? 0.22f : 0.76f;
return new Color(kViewBackgroundIntensity, kViewBackgroundIntensity, kViewBackgroundIntensity, 1f);
}
// [0] original name, [1] localized name, [2] localized tooltip
internal static string[] GetNameAndTooltipString(string nameAndTooltip)
{
string[] retval = new string[3];
string[] s1 = nameAndTooltip.Split('|');
switch (s1.Length)
{
case 0:
retval[0] = "";
retval[1] = "";
break;
case 1:
retval[0] = s1[0].Trim();
retval[1] = retval[0];
break;
case 2:
retval[0] = s1[0].Trim();
retval[1] = retval[0];
retval[2] = s1[1].Trim();
break;
default:
Debug.LogError("Error in Tooltips: Too many strings in line beginning with '" + s1[0] + "'");
break;
}
return retval;
}
internal static Texture2D LoadIconRequired(string name)
{
Texture2D tex = LoadIcon(name);
if (!tex)
Debug.LogErrorFormat("Unable to load the icon: '{0}'.\nNote that either full project path should be used (with extension) " +
"or just the icon name if the icon is located in the following location: '{1}' (without extension, since png is assumed)",
name, EditorResources.editorDefaultResourcesPath + EditorResources.iconsPath);
return tex;
}
// Automatically loads version of icon that matches current skin.
// Equivalent to Texture2DNamed in ObjectImages.cpp
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static Texture2D LoadIcon(string name)
{
return LoadIconForSkin(name, skinIndex);
}
static readonly List<string> k_UserSideSupportedImageExtensions = new List<string> {".png"};
// Attempts to load a higher resolution icon if needed
internal static Texture2D LoadGeneratedIconOrNormalIcon(string name)
{
Texture2D icon = null;
if (GUIUtility.pixelsPerPoint > 1.0f)
{
var imageExtension = Path.GetExtension(name);
if (k_UserSideSupportedImageExtensions.Contains(imageExtension))
{
var newName = $"{Path.GetFileNameWithoutExtension(name)}@2x{imageExtension}";
var dirName = Path.GetDirectoryName(name);
if (!string.IsNullOrEmpty(dirName))
newName = $"{dirName}/{newName}";
icon = InnerLoadGeneratedIconOrNormalIcon(newName);
}
else
{
icon = InnerLoadGeneratedIconOrNormalIcon(name + "@2x");
}
if (icon != null)
icon.pixelsPerPoint = 2.0f;
}
if (icon == null)
{
icon = InnerLoadGeneratedIconOrNormalIcon(name);
}
if (icon != null &&
!Mathf.Approximately(icon.pixelsPerPoint, GUIUtility.pixelsPerPoint) && //scaling are different
!Mathf.Approximately(GUIUtility.pixelsPerPoint % 1, 0)) //screen scaling is non-integer
{
icon.filterMode = FilterMode.Bilinear;
}
return icon;
}
// Takes a name that already includes d_ if dark skin version is desired.
// Equivalent to Texture2DSkinNamed in ObjectImages.cpp
static Texture2D InnerLoadGeneratedIconOrNormalIcon(string name)
{
Texture2D tex = Load(EditorResources.generatedIconsPath + name + ".asset") as Texture2D;
if (!tex)
{
tex = Load(EditorResources.iconsPath + name + ".png") as Texture2D;
}
if (!tex)
{
tex = Load(name) as Texture2D; // Allow users to specify their own project path to an icon (e.g see EditorWindowTitleAttribute)
}
return tex;
}
internal static Texture2D LoadIconForSkin(string name, int in_SkinIndex)
{
if (String.IsNullOrEmpty(name))
return null;
if (in_SkinIndex == 0)
return LoadGeneratedIconOrNormalIcon(name);
//Remap file name for dark skin
var newName = "d_" + Path.GetFileName(name);
var dirName = Path.GetDirectoryName(name);
if (!string.IsNullOrEmpty(dirName))
newName = $"{dirName}/{newName}";
Texture2D tex = LoadGeneratedIconOrNormalIcon(newName);
if (!tex)
tex = LoadGeneratedIconOrNormalIcon(name);
return tex;
}
[UsedByNativeCode]
internal static string GetIconPathFromAttribute(Type type)
{
if (Attribute.IsDefined(type, typeof(IconAttribute)))
{
var attributes = type.GetCustomAttributes(typeof(IconAttribute), true);
for (int i = 0, c = attributes.Length; i < c; i++)
if (attributes[i] is IconAttribute)
return ((IconAttribute)attributes[i]).path;
}
return null;
}
internal static GUIContent IconContent<T>(string text = null) where T : UnityObject
{
return IconContent(FindTexture(typeof(T)), text);
}
[ExcludeFromDocs]
public static GUIContent IconContent(string name)
{
return IconContent(name, null, true);
}
internal static GUIContent IconContent(string name, bool logError)
{
return IconContent(name, null, logError);
}
public static GUIContent IconContent(string name, [DefaultValue("null")] string text)
{
return IconContent(name, text, true);
}
internal static GUIContent IconContent(string name, [DefaultValue("null")] string text, bool logError)
{
GUIContent gc = (GUIContent)s_IconGUIContents[name];
if (gc != null)
{
return gc;
}
gc = new GUIContent();
if (text != null)
{
string[] strings = GetNameAndTooltipString(text);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
}
gc.image = logError ? LoadIconRequired(name) : LoadIcon(name);
s_IconGUIContents[name] = gc;
return gc;
}
static GUIContent IconContent(Texture icon, string text)
{
GUIContent gc = text != null ? (GUIContent)s_IconGUIContents[text] : null;
if (gc != null)
{
return gc;
}
gc = new GUIContent { image = icon };
if (text != null)
{
string[] strings = GetNameAndTooltipString(text);
if (strings[2] != null)
{
gc.tooltip = strings[2];
}
s_IconGUIContents[text] = gc;
}
return gc;
}
// Is the user currently using the pro skin? (RO)
public static bool isProSkin => skinIndex == 1;
internal static void Internal_SwitchSkin()
{
skinIndex = 1 - skinIndex;
}
// Return a GUIContent object with the name and icon of an Object.
public static GUIContent ObjectContent(UnityObject obj, Type type)
{
return ObjectContent(obj, type, ReferenceEquals(obj, null) ? 0 : obj.GetInstanceID());
}
internal static GUIContent ObjectContent(UnityObject obj, Type type, int instanceID)
{
if (obj)
{
s_ObjectContent.text = GetObjectNameWithInfo(obj);
s_ObjectContent.image = AssetPreview.GetMiniThumbnail(obj);
}
else if (type != null)
{
s_ObjectContent.text = GetTypeNameWithInfo(type.Name, instanceID);
s_ObjectContent.image = AssetPreview.GetMiniTypeThumbnail(type);
}
else
{
s_ObjectContent.text = "<no type>";
s_ObjectContent.image = null;
}
return s_ObjectContent;
}
internal static GUIContent ObjectContent(UnityObject obj, Type type, SerializedProperty property, EditorGUI.ObjectFieldValidator validator = null)
{
if (validator == null)
validator = EditorGUI.ValidateObjectFieldAssignment;
GUIContent temp;
// If obj or objType are both null, we have to rely on
// property.objectReferenceStringValue to display None/Missing and the
// correct type. But if not, EditorGUIUtility.ObjectContent is more reliable.
// It can take a more specific object type specified as argument into account,
// and it gets the icon at the same time.
if (obj == null && type == null && property != null && property.isValid)
{
temp = TempContent(property.objectReferenceStringValue);
}
else
{
// In order for ObjectContext to be able to distinguish between None/Missing,
// we need to supply an instanceID. For some reason, getting the instanceID
// from property.objectReferenceValue is not reliable, so we have to
// explicitly check property.objectReferenceInstanceIDValue if a property exists.
if (property != null && property.isValid)
temp = ObjectContent(obj, type, property.objectReferenceInstanceIDValue);
else
temp = ObjectContent(obj, type);
}
if (property != null && property.isValid)
{
if (obj != null)
{
UnityObject[] references = { obj };
if (EditorSceneManager.preventCrossSceneReferences && EditorGUI.CheckForCrossSceneReferencing(obj, property.serializedObject.targetObject))
{
if (!EditorApplication.isPlaying)
temp = s_SceneMismatch;
else
temp.text = temp.text + string.Format(" ({0})", EditorGUI.GetGameObjectFromObject(obj).scene.name);
}
else if (validator(references, type, property, EditorGUI.ObjectFieldValidatorOptions.ExactObjectTypeValidation) == null)
temp = s_TypeMismatch;
}
}
return temp;
}
internal static GUIContent TempContent(string t)
{
s_Text.image = null;
s_Text.text = t;
s_Text.tooltip = null;
return s_Text;
}
internal static GUIContent TempContent(string text, string tip)
{
s_Text.image = null;
s_Text.text = text;
s_Text.tooltip = tip;
return s_Text;
}
internal static GUIContent TempContent(Texture i)
{
s_Image.image = i;
s_Image.text = null;
s_Image.tooltip = null;
return s_Image;
}
internal static GUIContent TempContent(string t, Texture i)
{
s_TextImage.image = i;
s_TextImage.text = t;
s_TextImage.tooltip = null;
return s_TextImage;
}
internal static GUIContent[] TempContent(string[] texts)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(texts[i]);
return retval;
}
internal static GUIContent[] TempContent(string[] texts, string[] tooltips)
{
GUIContent[] retval = new GUIContent[texts.Length];
for (int i = 0; i < texts.Length; i++)
retval[i] = new GUIContent(texts[i], tooltips[i]);
return retval;
}
internal static bool HasHolddownKeyModifiers(Event evt)
{
return evt.shift | evt.control | evt.alt | evt.command;
}
// Does a given class have per-object thumbnails?
public static bool HasObjectThumbnail(Type objType)
{
return objType != null && (objType.IsSubclassOf(typeof(Texture)) || objType == typeof(Texture) || objType == typeof(Sprite));
}
// Get the size that has been set using ::ref::SetIconSize.
public static Vector2 GetIconSize()
{
//FIXME: this is how it really should be, but right now it seems to fail badly (unrelated null ref exceptions and then crash)
return Internal_GetIconSize();
}
internal static Texture2D infoIcon
{
get
{
if (s_InfoIcon == null)
s_InfoIcon = new ScalableGUIContent("console.infoicon");
return s_InfoIcon.image as Texture2D;
}
}
internal static Texture2D warningIcon
{
get
{
if (s_WarningIcon == null)
s_WarningIcon = new ScalableGUIContent("console.warnicon");
return s_WarningIcon.image as Texture2D;
}
}
internal static Texture2D errorIcon
{
get
{
if (s_ErrorIcon == null)
s_ErrorIcon = new ScalableGUIContent("console.erroricon");
return s_ErrorIcon.image as Texture2D;
}
}
internal static Texture2D GetHelpIcon(MessageType type)
{
switch (type)
{
case MessageType.Info:
return infoIcon;
case MessageType.Warning:
return warningIcon;
case MessageType.Error:
return errorIcon;
}
return null;
}
// An invisible GUIContent that is not the same as GUIContent.none
internal static GUIContent blankContent { get; } = new GUIContent(" ");
internal static GUIStyle whiteTextureStyle => s_WhiteTextureStyle ??
(s_WhiteTextureStyle = new GUIStyle {normal = {background = whiteTexture}});
internal static GUIStyle GetBasicTextureStyle(Texture2D tex)
{
if (s_BasicTextureStyle == null)
s_BasicTextureStyle = new GUIStyle();
s_BasicTextureStyle.normal.background = tex;
return s_BasicTextureStyle;
}
internal static void NotifyLanguageChanged(SystemLanguage newLanguage)
{
s_TextGUIContents = new Hashtable();
s_GUIContents = new Hashtable();
s_IconGUIContents = new Hashtable();
L10n.ClearCache();
EditorUtility.Internal_UpdateMenuTitleForLanguage(newLanguage);
LocalizationDatabase.currentEditorLanguage = newLanguage;
EditorTextSettings.UpdateLocalizationFontAsset();
EditorApplication.RequestRepaintAllViews();
}
// Get one of the built-in GUI skins, which can be the game view, inspector or scene view skin as chosen by the parameter.
public static GUISkin GetBuiltinSkin(EditorSkin skin)
{
return GUIUtility.GetBuiltinSkin((int)skin);
}
// Load a built-in resource that has to be there.
public static UnityObject LoadRequired(string path)
{
var o = Load(path, typeof(UnityObject));
if (!o)
Debug.LogError("Unable to find required resource at " + path);
return o;
}
// Load a built-in resource
public static UnityObject Load(string path)
{
return Load(path, typeof(UnityObject));
}
[TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)]
private static UnityObject Load(string filename, Type type)
{
var asset = EditorResources.Load(filename, type);
if (asset != null)
return asset;
AssetBundle bundle = GetEditorAssetBundle();
if (bundle == null)
{
// If in batch mode, loading any Editor UI items shouldn't be needed
if (Application.isBatchMode)
return null;
throw new NullReferenceException("Failure to load editor resource asset bundle.");
}
asset = bundle.LoadAsset(filename, type);
if (asset != null)
{
asset.hideFlags |= HideFlags.HideAndDontSave;
return asset;
}
return AssetDatabase.LoadAssetAtPath(filename, type);
}
public static void PingObject(UnityObject obj)
{
if (obj != null)
PingObject(obj.GetInstanceID());
}
// Ping an object in a window like clicking it in an inspector
public static void PingObject(int targetInstanceID)
{
foreach (SceneHierarchyWindow shw in SceneHierarchyWindow.GetAllSceneHierarchyWindows())
{
shw.FrameObject(targetInstanceID, true);
}
foreach (ProjectBrowser pb in ProjectBrowser.GetAllProjectBrowsers())
{
pb.FrameObject(targetInstanceID, true);
}
}
// Same as PingObject, but renamed to avoid ambiguity when calling externally (i.e. using CallStaticMonoMethod)
[RequiredByNativeCode]
private static void PingObjectFromCPP(int targetInstanceID)
{
PingObject(targetInstanceID);
}
internal static void MoveFocusAndScroll(bool forward)
{
int prev = keyboardControl;
Internal_MoveKeyboardFocus(forward);
if (prev != keyboardControl)
RefreshScrollPosition();
}
internal static void RefreshScrollPosition()
{
Rect r;
if (Internal_GetKeyboardRect(keyboardControl, out r))
{
GUI.ScrollTo(r);
}
}
internal static void ScrollForTabbing(bool forward)
{
Rect r;
if (Internal_GetKeyboardRect(Internal_GetNextKeyboardControlID(forward), out r))
{
GUI.ScrollTo(r);
}
}
internal static void ResetGUIState()
{
GUI.skin = null;
GUI.backgroundColor = GUI.contentColor = Color.white;
GUI.color = EditorApplication.isPlayingOrWillChangePlaymode ? HostView.kPlayModeDarken : Color.white;
GUI.enabled = true;
GUI.changed = false;
EditorGUI.indentLevel = 0;
EditorGUI.ClearStacks();
fieldWidth = 0;
labelWidth = 0;
currentViewWidth = -1f;
SetBoldDefaultFont(false);
UnlockContextWidth();
hierarchyMode = false;
wideMode = false;
comparisonViewMode = ComparisonViewMode.None;
leftMarginCoord = 0;
//Clear the cache, so it uses the global one
ScriptAttributeUtility.propertyHandlerCache = null;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("RenderGameViewCameras is no longer supported.Consider rendering cameras manually.", true)]
public static void RenderGameViewCameras(Rect cameraRect, bool gizmos, bool gui) {}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("RenderGameViewCameras is no longer supported.Consider rendering cameras manually.", true)]
public static void RenderGameViewCameras(Rect cameraRect, Rect statsRect, bool gizmos, bool gui) {}
// Called from C++ GetControlID method when run from the Editor.
// Editor GUI needs some additional things to happen when calling GetControlID.
// While this will also be called for runtime code running in Play mode in the Editor,
// it won't have any effect. EditorGUIUtility.s_LastControlID will be set to the id,
// but this is only used inside the handling of a single control
// (see DoPropertyFieldKeyboardHandling).
// EditorGUI.s_PrefixLabel.text will only be not null when EditorGUI.PrefixLabel
// has been called without a specified controlID. The control following the PrefixLabel clears this.
[RequiredByNativeCode]
internal static void HandleControlID(int id)
{
s_LastControlID = id;
EditorGUI.PrepareCurrentPrefixLabel(s_LastControlID);
}
public static bool editingTextField
{
get { return EditorGUI.RecycledTextEditor.s_ActuallyEditing; }
set { EditorGUI.RecycledTextEditor.s_ActuallyEditing = value; }
}
public static bool textFieldHasSelection
{
get { return EditorGUI.s_RecycledEditor.hasSelection; }
}
// hierarchyMode changes how foldouts are drawn so the foldout triangle is drawn to the left,
// outside the rect of the control, rather than inside the rect.
// This way the text of the foldout lines up with the labels of other controls.
// hierarchyMode is primarily enabled for editors in the Inspector.
public static bool hierarchyMode { get; set; } = false;
// wideMode is used when the Inspector is wide and uses a more tidy and vertically compact layout for certain controls.
public static bool wideMode { get; set; } = false;
internal enum ComparisonViewMode
{
None, Original, Modified
}
// ComparisonViewMode is used when editors are drawn in the context of showing differences between different objects.
// Controls that must not be used in this context can be hidden or disabled.
private static ComparisonViewMode s_ComparisonViewMode = ComparisonViewMode.None;
internal static ComparisonViewMode comparisonViewMode
{
get { return s_ComparisonViewMode; }
set { s_ComparisonViewMode = value; }
}
private static float s_LeftMarginCoord;
internal static float leftMarginCoord
{
get { return s_LeftMarginCoord; }
set { s_LeftMarginCoord = value; }
}
// Context width is used for calculating the label width for various editor controls.
// In most cases the top level clip rect is a perfect context width.
private static Stack<float> s_ContextWidthStack = new Stack<float>(10);
private static float CalcContextWidth()
{
float output = GUIClip.GetTopRect().width;
// If there's no top clip rect, fallback to using screen width.
if (output < 1f || output >= 40000)
output = currentViewWidth;
return output;
}
internal static void LockContextWidth()
{
s_ContextWidthStack.Push(CalcContextWidth());
}
internal static void UnlockContextWidth()
{
if (s_ContextWidthStack.Count > 0)
{
s_ContextWidthStack.Pop();
}
}
internal static float contextWidth
{
get
{
if (s_ContextWidthStack.Count > 0 && s_ContextWidthStack.Peek() > 0f)
return s_ContextWidthStack.Peek();
return CalcContextWidth();
}
}
private static float s_OverriddenViewWidth = -1f;
public static float currentViewWidth
{
get
{
if (s_OverriddenViewWidth > 0f)
return s_OverriddenViewWidth;
CheckOnGUI();
return GUIView.current ? GUIView.current.position.width : 0;
}
internal set
{
s_OverriddenViewWidth = value;
}
}
public static float labelWidth
{
get
{
if (s_LabelWidth > 0)
return s_LabelWidth;
if (hierarchyMode)
return Mathf.Max(contextWidth * EditorGUI.kLabelWidthRatio - EditorGUI.kLabelWidthMargin, EditorGUI.kMinLabelWidth);
return 150;
}
set { s_LabelWidth = value; }
}
private static float s_FieldWidth = 0f;
public static float fieldWidth
{
get
{
if (s_FieldWidth > 0)
return s_FieldWidth;
return 50;
}
set { s_FieldWidth = value; }
}
// Make all ref::EditorGUI look like regular controls.
private const string k_LookLikeControlsObsoleteMessage = "LookLikeControls and LookLikeInspector modes are deprecated.Use EditorGUIUtility.labelWidth and EditorGUIUtility.fieldWidth to control label and field widths.";
[Obsolete(k_LookLikeControlsObsoleteMessage, false)]
public static void LookLikeControls(float _labelWidth, float _fieldWidth)
{
fieldWidth = _fieldWidth;
labelWidth = _labelWidth;
}
[ExcludeFromDocs, Obsolete(k_LookLikeControlsObsoleteMessage, false)] public static void LookLikeControls(float _labelWidth) { LookLikeControls(_labelWidth, 0); }
[ExcludeFromDocs, Obsolete(k_LookLikeControlsObsoleteMessage, false)] public static void LookLikeControls() { LookLikeControls(0, 0); }
// Make all ::ref::EditorGUI look like simplified outline view controls.
[Obsolete("LookLikeControls and LookLikeInspector modes are deprecated.", false)]
public static void LookLikeInspector()
{
fieldWidth = 0;
labelWidth = 0;
}
[Obsolete("This field is no longer used by any builtin controls. If passing this field to GetControlID, explicitly use the FocusType enum instead.", false)]
public static FocusType native = FocusType.Keyboard;
internal static void SkinChanged()
{
EditorStyles.UpdateSkinCache();
}
internal static Rect DragZoneRect(Rect position, bool hasLabel = true)
{
return new Rect(position.x, position.y, hasLabel ? labelWidth : 0, position.height);
}
internal static void MoveArrayExpandedState(SerializedProperty elements, int oldActiveElement, int newActiveElement)
{
SerializedProperty prop1 = elements.GetArrayElementAtIndex(oldActiveElement);
SerializedProperty prop2;
int depth;
List<bool> tempIsExpanded = ListPool<bool>.Get();
var tempProp = prop1;
tempIsExpanded.Add(prop1.isExpanded);
bool clearGradientCache = false;
int next = (oldActiveElement < newActiveElement) ? 1 : -1;
for (int i = oldActiveElement + next;
(oldActiveElement < newActiveElement) ? i <= newActiveElement : i >= newActiveElement;
i += next)
{
prop2 = elements.GetArrayElementAtIndex(i);
var cprop1 = prop1.Copy();
var cprop2 = prop2.Copy();
depth = Math.Min(cprop1.depth, cprop2.depth);
while (cprop1.NextVisible(true) && cprop1.depth > depth && cprop2.NextVisible(true) && cprop2.depth > depth)
{
if (cprop1.hasVisibleChildren && cprop2.hasVisibleChildren)
{
tempIsExpanded.Add(cprop1.isExpanded);
cprop1.isExpanded = cprop2.isExpanded;
}
}
prop1.isExpanded = prop2.isExpanded;
if (prop1.propertyType == SerializedPropertyType.Gradient)
clearGradientCache = true;
prop1 = prop2;
}
prop1.isExpanded = tempIsExpanded[0];
depth = Math.Min(prop1.depth, tempProp.depth);
int k = 1;
while (prop1.NextVisible(true) && prop1.depth > depth && tempProp.NextVisible(true) && tempProp.depth > depth)
{
if (prop1.hasVisibleChildren && tempProp.hasVisibleChildren && tempIsExpanded.Count > k)
{
prop1.isExpanded = tempIsExpanded[k];
k++;
}
}
ListPool<bool>.Release(tempIsExpanded);
if (clearGradientCache)
GradientPreviewCache.ClearCache();
}
internal static void SetBoldDefaultFont(bool isBold)
{
int wantsBold = isBold ? 1 : 0;
if (wantsBold != s_FontIsBold)
{
SetDefaultFont(isBold ? EditorStyles.boldFont : EditorStyles.standardFont);
s_FontIsBold = wantsBold;
}
}
internal static bool GetBoldDefaultFont() { return s_FontIsBold == 1; }
// Creates an event
public static Event CommandEvent(string commandName)
{
Event e = new Event();
Internal_SetupEventValues(e);
e.type = EventType.ExecuteCommand;
e.commandName = commandName;
return e;
}
// Draw a color swatch.
public static void DrawColorSwatch(Rect position, Color color)
{
DrawColorSwatch(position, color, true);
}
internal static void DrawColorSwatch(Rect position, Color color, bool showAlpha)
{
DrawColorSwatch(position, color, showAlpha, false);
}
internal static void DrawColorSwatch(Rect position, Color color, bool showAlpha, bool hdr)
{
if (Event.current.type != EventType.Repaint)
return;
Color oldColor = GUI.color;
Color oldBackgroundColor = GUI.backgroundColor;
float a = GUI.enabled ? 1 : 2;
GUI.color = EditorGUI.showMixedValue ? new Color(0.82f, 0.82f, 0.82f, a) * oldColor : new Color(color.r, color.g, color.b, a);
if (hdr)
GUI.color = GUI.color.gamma;
GUI.backgroundColor = Color.white;
GUIStyle gs = whiteTextureStyle;
gs.Draw(position, false, false, false, false);
// Render LDR -> HDR gradients on the sides when having HDR values (to let the user see what the normalized color looks like)
if (hdr)
{
Color32 baseColor;
float exposure;
ColorMutator.DecomposeHdrColor(GUI.color.linear, out baseColor, out exposure);
if (!Mathf.Approximately(exposure, 0f))
{
float gradientWidth = position.width / 3f;
Rect leftRect = new Rect(position.x, position.y, gradientWidth, position.height);
Rect rightRect = new Rect(position.xMax - gradientWidth, position.y, gradientWidth,
position.height);
Color orgColor = GUI.color;
GUI.color = ((Color)baseColor).gamma;
GUIStyle basicStyle = GetBasicTextureStyle(whiteTexture);
basicStyle.Draw(leftRect, false, false, false, false);
basicStyle.Draw(rightRect, false, false, false, false);
GUI.color = orgColor;
basicStyle = GetBasicTextureStyle(ColorPicker.GetGradientTextureWithAlpha0To1());
basicStyle.Draw(leftRect, false, false, false, false);
basicStyle = GetBasicTextureStyle(ColorPicker.GetGradientTextureWithAlpha1To0());
basicStyle.Draw(rightRect, false, false, false, false);
}
}
if (!EditorGUI.showMixedValue)
{
if (showAlpha)
{
GUI.color = new Color(0, 0, 0, a);
float alphaHeight = Mathf.Clamp(position.height * .2f, 2, 20);
Rect alphaBarRect = new Rect(position.x, position.yMax - alphaHeight, position.width, alphaHeight);
gs.Draw(alphaBarRect, false, false, false, false);
GUI.color = new Color(1, 1, 1, a);
alphaBarRect.width *= Mathf.Clamp01(color.a);
gs.Draw(alphaBarRect, false, false, false, false);
}
}
else
{
EditorGUI.BeginHandleMixedValueContentColor();
gs.Draw(position, EditorGUI.mixedValueContent, false, false, false, false);
EditorGUI.EndHandleMixedValueContentColor();
}
GUI.color = oldColor;
GUI.backgroundColor = oldBackgroundColor;
// HDR label overlay
if (hdr)
{
GUI.Label(new Rect(position.x, position.y, position.width - 3, position.height), "HDR", EditorStyles.centeredGreyMiniLabel);
}
}
internal static void DrawRegionSwatch(Rect position, SerializedProperty property, SerializedProperty property2, Color color, Color bgColor)
{
DrawCurveSwatchInternal(position, null, null, property, property2, color, bgColor, false, new Rect(), Color.clear, Color.clear);
}
public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor)
{
DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, false, new Rect(), Color.clear, Color.clear);
}
public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor, Color topFillColor, Color bottomFillColor)
{
DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, false, new Rect(), topFillColor, bottomFillColor);
}
// Draw a curve swatch.
public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor, Color topFillColor, Color bottomFillColor, Rect curveRanges)
{
DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, true, curveRanges, topFillColor, bottomFillColor);
}
public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor, Rect curveRanges)
{
DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, true, curveRanges, Color.clear, Color.clear);
}
// Draw swatch with a filled region between two SerializedProperty curves.
public static void DrawRegionSwatch(Rect position, SerializedProperty property, SerializedProperty property2, Color color, Color bgColor, Rect curveRanges)
{
DrawCurveSwatchInternal(position, null, null, property, property2, color, bgColor, true, curveRanges, Color.clear, Color.clear);
}
// Draw swatch with a filled region between two curves.
public static void DrawRegionSwatch(Rect position, AnimationCurve curve, AnimationCurve curve2, Color color, Color bgColor, Rect curveRanges)
{
DrawCurveSwatchInternal(position, curve, curve2, null, null, color, bgColor, true, curveRanges, Color.clear, Color.clear);
}
private static void DrawCurveSwatchInternal(Rect position, AnimationCurve curve, AnimationCurve curve2, SerializedProperty property, SerializedProperty property2, Color color, Color bgColor, bool useCurveRanges, Rect curveRanges, Color topFillColor, Color bottomFillColor)
{
if (Event.current.type != EventType.Repaint)
return;
int previewWidth = (int)position.width;
int previewHeight = (int)position.height;
int maxTextureDim = SystemInfo.maxTextureSize;
bool stretchX = previewWidth > maxTextureDim;
bool stretchY = previewHeight > maxTextureDim;
if (stretchX)
previewWidth = Mathf.Min(previewWidth, maxTextureDim);
if (stretchY)
previewHeight = Mathf.Min(previewHeight, maxTextureDim);
// Draw background color
Color oldColor = GUI.color;
GUI.color = EditorApplication.isPlayingOrWillChangePlaymode ? bgColor * HostView.kPlayModeDarken : bgColor;
GUIStyle gs = whiteTextureStyle;
gs.Draw(position, false, false, false, false);
GUI.color = oldColor;
if (property != null && property.hasMultipleDifferentValues)
{
// No obvious way to show that curve field has mixed values so we just draw
// the same content as for text fields since the user at least know what that means.
EditorGUI.BeginHandleMixedValueContentColor();
GUI.Label(position, EditorGUI.mixedValueContent, "PreOverlayLabel");
EditorGUI.EndHandleMixedValueContentColor();
}
else
{
Texture2D preview = null;
if (property != null)
{
if (property2 == null)
preview = useCurveRanges ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, color, topFillColor, bottomFillColor, curveRanges) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, color, topFillColor, bottomFillColor);
else
preview = useCurveRanges ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, property2, color, topFillColor, bottomFillColor, curveRanges) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, property2, color, topFillColor, bottomFillColor);
}
else if (curve != null)
{
if (curve2 == null)
preview = useCurveRanges ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, color, topFillColor, bottomFillColor, curveRanges) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, color, topFillColor, bottomFillColor);
else
preview = useCurveRanges ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, curve2, color, topFillColor, bottomFillColor, curveRanges) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, curve2, color, topFillColor, bottomFillColor);
}
gs = GetBasicTextureStyle(preview);
if (!stretchX && preview)
position.width = preview.width;
if (!stretchY && preview)
position.height = preview.height;
gs.Draw(position, false, false, false, false);
}
}
// Convert a color from RGB to HSV color space.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("EditorGUIUtility.RGBToHSV is obsolete. Use Color.RGBToHSV instead (UnityUpgradable) -> [UnityEngine] UnityEngine.Color.RGBToHSV(*)", true)]
public static void RGBToHSV(Color rgbColor, out float H, out float S, out float V)
{
Color.RGBToHSV(rgbColor, out H, out S, out V);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("EditorGUIUtility.HSVToRGB is obsolete. Use Color.HSVToRGB instead (UnityUpgradable) -> [UnityEngine] UnityEngine.Color.HSVToRGB(*)", true)]
public static Color HSVToRGB(float H, float S, float V)
{
return Color.HSVToRGB(H, S, V);
}
// Convert a set of HSV values to an RGB Color.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("EditorGUIUtility.HSVToRGB is obsolete. Use Color.HSVToRGB instead (UnityUpgradable) -> [UnityEngine] UnityEngine.Color.HSVToRGB(*)", true)]
public static Color HSVToRGB(float H, float S, float V, bool hdr)
{
return Color.HSVToRGB(H, S, V, hdr);
}
// Add a custom mouse pointer to a control
public static void AddCursorRect(Rect position, MouseCursor mouse)
{
AddCursorRect(position, mouse, 0);
}
public static void AddCursorRect(Rect position, MouseCursor mouse, int controlID)
{
if (Event.current.type == EventType.Repaint)
{
Rect r = GUIClip.Unclip(position);
Rect clip = GUIClip.topmostRect;
Rect clipped = Rect.MinMaxRect(Mathf.Max(r.x, clip.x), Mathf.Max(r.y, clip.y), Mathf.Min(r.xMax, clip.xMax), Mathf.Min(r.yMax, clip.yMax));
if (clipped.width <= 0 || clipped.height <= 0)
return;
Internal_AddCursorRect(clipped, mouse, controlID);
}
}
internal static Rect HandleHorizontalSplitter(Rect dragRect, float width, float minLeftSide, float minRightSide)
{
// Add a cursor rect indicating we can drag this area
if (Event.current.type == EventType.Repaint)
AddCursorRect(dragRect, MouseCursor.SplitResizeLeftRight);
// Drag splitter
float deltaX = EditorGUI.MouseDeltaReader(dragRect, true).x;
if (deltaX != 0f)
dragRect.x += deltaX;
float newX = Mathf.Clamp(dragRect.x, minLeftSide, width - minRightSide);
// We might need to move the splitter position if our area/window size has changed
if (dragRect.x > width - minRightSide)
newX = width - minRightSide;
dragRect.x = Mathf.Clamp(newX, minLeftSide, width - minRightSide);
return dragRect;
}
internal static void DrawHorizontalSplitter(Rect dragRect)
{
if (Event.current.type != EventType.Repaint)
return;
Color orgColor = GUI.color;
Color tintColor = (isProSkin) ? new Color(0.12f, 0.12f, 0.12f, 1.333f) : new Color(0.6f, 0.6f, 0.6f, 1.333f);
GUI.color = GUI.color * tintColor;
Rect splitterRect = new Rect(dragRect.x - 1, dragRect.y, 1, dragRect.height);
GUI.DrawTexture(splitterRect, whiteTexture);
GUI.color = orgColor;
}
internal static EventType magnifyGestureEventType => (EventType)1000;
internal static EventType swipeGestureEventType => (EventType)1001;
internal static EventType rotateGestureEventType => (EventType)1002;
public static void ShowObjectPicker<T>(UnityObject obj, bool allowSceneObjects, string searchFilter, int controlID) where T : UnityObject
{
Type objType = typeof(T);
//case 1113046: Delay the show method when it is called while other object picker is closing
if (Event.current?.commandName == "ObjectSelectorClosed")
EditorApplication.delayCall += () => SetupObjectSelector(obj, objType, allowSceneObjects, searchFilter, controlID);
else
SetupObjectSelector(obj, objType, allowSceneObjects, searchFilter, controlID);
}
private static void SetupObjectSelector(UnityObject obj, Type objType, bool allowSceneObjects, string searchFilter, int controlID)
{
ObjectSelector.get.Show(obj, objType, null, allowSceneObjects);
ObjectSelector.get.objectSelectorID = controlID;
ObjectSelector.get.searchFilter = searchFilter;
}
public static UnityObject GetObjectPickerObject()
{
return ObjectSelector.GetCurrentObject();
}
public static int GetObjectPickerControlID()
{
return ObjectSelector.get.objectSelectorID;
}
internal static string GetHyperlinkColorForSkin()
{
return skinIndex == EditorResources.darkSkinIndex ? "#40a0ff" : "#0000FF";
}
// Enum for tracking what styles the editor uses
internal enum EditorLook
{
// Hasn't been set
Uninitialized = 0,
// Looks like regular controls
LikeControls = 1,
// Looks like inspector
LikeInspector = 2
}
}
[StructLayout(LayoutKind.Sequential)]
internal class BuiltinResource
{
public string m_Name;
public int m_InstanceID;
}
internal struct SliderLabels
{
public void SetLabels(GUIContent _leftLabel, GUIContent _rightLabel)
{
if (Event.current.type == EventType.Repaint)
{
leftLabel = _leftLabel;
rightLabel = _rightLabel;
}
}
public bool HasLabels()
{
if (Event.current.type == EventType.Repaint)
{
return leftLabel != null && rightLabel != null;
}
return false;
}
public GUIContent leftLabel;
public GUIContent rightLabel;
}
internal class GUILayoutFadeGroup : GUILayoutGroup
{
public float fadeValue;
public bool wasGUIEnabled;
public Color guiColor;
public override void CalcHeight()
{
base.CalcHeight();
minHeight *= fadeValue;
maxHeight *= fadeValue;
}
}
}
| UnityCsReference/Editor/Mono/EditorGUIUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorGUIUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 33656
} | 299 |
// 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.Scripting;
namespace UnityEditor
{
public partial class EditorUserBuildSettings
{
// Select a new build target to be active.
[Obsolete("Please use SwitchActiveBuildTarget(BuildTargetGroup targetGroup, BuildTarget target)")]
public static bool SwitchActiveBuildTarget(BuildTarget target)
{
return SwitchActiveBuildTarget(BuildPipeline.GetBuildTargetGroup(target), target);
}
// Triggered in response to SwitchActiveBuildTarget.
[Obsolete("UnityEditor.activeBuildTargetChanged has been deprecated.Use UnityEditor.Build.IActiveBuildTargetChanged instead.")]
public static Action activeBuildTargetChanged;
#pragma warning disable 0618
[RequiredByNativeCode]
internal static void Internal_ActiveBuildTargetChanged()
{
if (activeBuildTargetChanged != null)
activeBuildTargetChanged();
}
#pragma warning restore 0618
// Force full optimisations for script complilation in Development builds (OBSOLETE, replaced by "IL2CPP optimization level" Player Setting)
[Obsolete("forceOptimizeScriptCompilation is obsolete - will always return false. Control script optimization using the 'IL2CPP optimization level' configuration in Player Settings / Other.")]
public static bool forceOptimizeScriptCompilation { get { return false; } }
[Obsolete(@"androidDebugMinification is obsolete. Use PlayerSettings.Android.minifyDebug")]
public static AndroidMinification androidDebugMinification
{
get
{
return PlayerSettings.Android.minifyDebug ? AndroidMinification.Gradle : AndroidMinification.None;
}
set
{
PlayerSettings.Android.minifyDebug = value != AndroidMinification.None;
}
}
[Obsolete(@"androidReleaseMinification is obsolete. Use PlayerSettings.Android.minifyRelease")]
public static AndroidMinification androidReleaseMinification
{
get
{
return PlayerSettings.Android.minifyRelease ? AndroidMinification.Gradle : AndroidMinification.None;
}
set
{
PlayerSettings.Android.minifyRelease = value != AndroidMinification.None;
}
}
}
}
| UnityCsReference/Editor/Mono/EditorUserBuildSettings.deprecated.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorUserBuildSettings.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 938
} | 300 |
// 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.Bindings;
using System.IO;
namespace UnityEditor
{
// Lets you do ''move'', ''copy'', ''delete'' operations over files or directories
[NativeHeader("Runtime/Utilities/FileUtilities.h")]
[NativeHeader("Runtime/Utilities/File.h")]
[NativeHeader("Editor/Platform/Interface/EditorUtility.h")]
public partial class FileUtil
{
// Deletes a file or a directory given a path.
public static bool DeleteFileOrDirectory(string path)
{
if (path is null) throw new ArgumentNullException("path");
if (path == string.Empty) throw new ArgumentException("path", "The path cannot be empty.");
return DeleteFileOrDirectoryInternal(path);
}
[FreeFunction("DeleteFileOrDirectory")]
private static extern bool DeleteFileOrDirectoryInternal(string path);
[FreeFunction("IsPathCreated")]
private static extern bool PathExists(string path);
// Copies a file or directory.
public static void CopyFileOrDirectory(string source, string dest)
{
CheckForValidSourceAndDestinationArgumentsAndRaiseAnExceptionWhenNullOrEmpty(source, dest);
if (PathExists(dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Copy File / Directory from '{0}' to '{1}': destination path already exists.", source, dest));
}
if (!CopyFileOrDirectoryInternal(source, dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Copy File / Directory from '{0}' to '{1}'.", source, dest));
}
}
[FreeFunction("CopyFileOrDirectory")]
private static extern bool CopyFileOrDirectoryInternal(string source, string dest);
// Copies the file or directory following symbolic links.
public static void CopyFileOrDirectoryFollowSymlinks(string source, string dest)
{
CheckForValidSourceAndDestinationArgumentsAndRaiseAnExceptionWhenNullOrEmpty(source, dest);
if (PathExists(dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Copy File / Directory from '{0}' to '{1}': destination path already exists.", source, dest));
}
if (!CopyFileOrDirectoryFollowSymlinksInternal(source, dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Copy File / Directory from '{0}' to '{1}'.", source, dest));
}
}
[FreeFunction("CopyFileOrDirectoryFollowSymlinks")]
private static extern bool CopyFileOrDirectoryFollowSymlinksInternal(string source, string dest);
// Moves a file or a directory from a given path to another path.
public static void MoveFileOrDirectory(string source, string dest)
{
CheckForValidSourceAndDestinationArgumentsAndRaiseAnExceptionWhenNullOrEmpty(source, dest);
if (PathExists(dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Copy File / Directory from '{0}' to '{1}': destination path already exists.", source, dest));
}
if (!MoveFileOrDirectoryInternal(source, dest))
{
throw new System.IO.IOException(string.Format(
"Failed to Move File / Directory from '{0}' to '{1}'.", source, dest));
}
}
[FreeFunction("MoveFileOrDirectory")]
private static extern bool MoveFileOrDirectoryInternal(string source, string dest);
private static void CheckForValidSourceAndDestinationArgumentsAndRaiseAnExceptionWhenNullOrEmpty(string source, string dest)
{
if (source == null) throw new ArgumentNullException("source");
if (dest == null) throw new ArgumentNullException("dest");
if (source == string.Empty) throw new ArgumentException("source", "The source path cannot be empty.");
if (dest == string.Empty) throw new ArgumentException("dest", "The destination path cannot be empty.");
}
// Returns a unique path in the Temp folder within your current project.
[FreeFunction]
public static extern string GetUniqueTempPathInProject();
[FreeFunction("GetActualPathSlow")]
internal static extern string GetActualPathName(string path);
//*undocumented*
[FreeFunction]
public static extern string GetProjectRelativePath(string path);
[FreeFunction(Name = "GetLastPathNameComponentManaged")]
internal static extern string GetLastPathNameComponent(string path);
[FreeFunction(Name = "DeleteLastPathNameComponentManaged")]
internal static extern string DeleteLastPathNameComponent(string path);
[FreeFunction("GetPathNameExtensionManaged")]
internal static extern string GetPathExtension(string path);
[FreeFunction("DeletePathNameExtensionManaged")]
internal static extern string GetPathWithoutExtension(string path);
[FreeFunction]
internal static extern string ResolveSymlinks(string path);
[FreeFunction]
internal static extern bool IsSymlink(string path);
[FreeFunction]
public static extern string GetLogicalPath(string path);
[FreeFunction(IsThreadSafe = true)]
public static extern string GetPhysicalPath(string path);
// Replaces a file.
public static void ReplaceFile(string src, string dst)
{
if (File.Exists(dst))
FileUtil.DeleteFileOrDirectory(dst);
FileUtil.CopyFileOrDirectory(src, dst);
}
// Replaces a directory.
public static void ReplaceDirectory(string src, string dst)
{
if (Directory.Exists(dst))
FileUtil.DeleteFileOrDirectory(dst);
FileUtil.CopyFileOrDirectory(src, dst);
}
// transform path to absolute, resolving mount points
[FreeFunction("PathToAbsolutePathFromScript")]
extern internal static string PathToAbsolutePath(string path);
}
}
| UnityCsReference/Editor/Mono/FileUtil.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/FileUtil.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2513
} | 301 |
// 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.SceneManagement;
using UnityEditor.SceneManagement;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using System.Runtime.InteropServices;
using Scene = UnityEngine.SceneManagement.Scene;
using NativeArrayUnsafeUtility = Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility;
using Unity.Collections;
using UnityEditor.LightBaking;
using UnityEngine.Rendering;
namespace UnityEditor
{
[UsedByNativeCode]
[NativeHeader("Editor/Src/GI/Progressive/PVRData.h")]
internal struct LightmapSize
{
[NativeName("m_Width")] public int width;
[NativeName("m_Height")] public int height;
}
[UsedByNativeCode]
[NativeHeader("Editor/Src/GI/Progressive/PVRData.h")]
internal struct RunningBakeInfo
{
[NativeName("m_LightmapSizes")] public LightmapSize[] lightmapSizes;
[NativeName("m_ProbePositions")] public UInt64 probePositions;
}
[UsedByNativeCode]
[NativeHeader("Editor/Src/GI/Progressive/PVRData.h")]
internal struct LightmapMemory
{
[NativeName("m_LightmapDataSizeCPU")] public float lightmapDataSizeCPU;
[NativeName("m_LightmapTexturesSize")] public float lightmapTexturesSize;
[NativeName("m_LightmapDataSizeGPU")] public float lightmapDataSizeGPU;
}
internal struct MemLabels
{
public string[] labels;
public float[] sizes;
}
internal struct GeoMemLabels
{
public string[] labels;
public float[] sizes;
public UInt64[] triCounts;
}
internal struct TetrahedralizationData
{
public int[] indices;
public Vector3[] positions;
}
[NativeHeader("Editor/Src/GI/Progressive/BakeContextManager.h")]
internal struct EnvironmentSamplesData
{
public Vector4[] directions;
public Vector4[] intensities;
}
[NativeHeader("Editor/Src/GI/Progressive/PVRHelpers.h")]
internal struct DeviceAndPlatform
{
public int deviceId;
public int platformId;
public string name;
};
[NativeHeader("Editor/Mono/GI/Lightmapping.bindings.h")]
public static partial class Lightmapping
{
[NativeHeader("Editor/Src/JobManager/QueueJobTypes.h")]
internal enum ConcurrentJobsType
{
Min = 0,
Low = 1,
High = 2,
}
[NativeHeader("Runtime/Graphics/LightmapEnums.h")]
public enum GIWorkflowMode
{
// Data is automatically precomputed for dynamic and static GI.
Iterative = 0,
// Data is only precomputed for dynamic and static GI when the bake button is pressed.
OnDemand = 1,
// Lightmaps are calculated in the same way as in Unity 4.x.
Legacy = 2
}
// Obsolete, please use Actions instead
public delegate void OnStartedFunction();
public delegate void OnCompletedFunction();
[Obsolete("Lightmapping.giWorkflowMode is obsolete.", false)]
public static GIWorkflowMode giWorkflowMode
{
get => GIWorkflowMode.OnDemand;
set { }
}
// [Obsolete("Lightmapping.realtimeGI is obsolete, use LightingSettings.realtimeGI instead. ", false)]
public static bool realtimeGI
{
get { return GetLightingSettingsOrDefaultsFallback().realtimeGI; }
set { GetOrCreateLightingsSettings().realtimeGI = value; }
}
// [Obsolete("Lightmapping.bakedGI is obsolete, use LightingSettings.bakedGI instead. ", false)]
public static bool bakedGI
{
get { return GetLightingSettingsOrDefaultsFallback().bakedGI; }
set { GetOrCreateLightingsSettings().bakedGI = value; }
}
[Obsolete("Lightmapping.indirectOutputScale is obsolete, use LightingSettings.indirectScale instead. ", false)]
public static float indirectOutputScale
{
get { return GetLightingSettingsOrDefaultsFallback().indirectScale; }
set { GetOrCreateLightingsSettings().indirectScale = value; }
}
[Obsolete("Lightmapping.bounceBoost is obsolete, use LightingSettings.albedoBoost instead. ", false)]
public static float bounceBoost
{
get { return GetLightingSettingsOrDefaultsFallback().albedoBoost; }
set { GetOrCreateLightingsSettings().albedoBoost = value; }
}
[RequiredByNativeCode]
internal static bool ShouldBakeInteractively()
{
return SceneView.NeedsInteractiveBaking();
}
internal static bool shouldBakeInteractively
{
get { return ShouldBakeInteractively(); }
}
[RequiredByNativeCode]
internal static void KickSceneViewsOutOfInteractiveMode()
{
foreach (SceneView sv in SceneView.sceneViews)
sv.debugDrawModesUseInteractiveLightBakingData = false;
}
// Set concurrent jobs type. Warning, high priority can impact Editor performance
[StaticAccessor("EnlightenPrecompManager::Get()", StaticAccessorType.Arrow)]
internal static extern ConcurrentJobsType concurrentJobsType { get; set; }
// Clears disk cache and recreates cache directories.
[StaticAccessor("GICache", StaticAccessorType.DoubleColon)]
public static extern void ClearDiskCache();
// Updates cache path from Editor preferences.
[StaticAccessor("GICache", StaticAccessorType.DoubleColon)]
internal static extern void UpdateCachePath();
// Get the disk cache size in Mb.
[StaticAccessor("GICache", StaticAccessorType.DoubleColon)]
[NativeName("LastKnownCacheSize")]
internal static extern long diskCacheSize { get; }
// Get the disk cache path.
[StaticAccessor("GICache", StaticAccessorType.DoubleColon)]
[NativeName("CachePath")]
internal static extern string diskCachePath { get; }
[Obsolete("Lightmapping.enlightenForceWhiteAlbedo is obsolete, use LightingSettings.realtimeForceWhiteAlbedo instead. ", false)]
internal static bool enlightenForceWhiteAlbedo
{
get { return GetLightingSettingsOrDefaultsFallback().realtimeForceWhiteAlbedo; }
set { GetOrCreateLightingsSettings().realtimeForceWhiteAlbedo = value; }
}
[Obsolete("Lightmapping.enlightenForceUpdates is obsolete, use LightingSettings.realtimeForceUpdates instead. ", false)]
internal static bool enlightenForceUpdates
{
get { return GetLightingSettingsOrDefaultsFallback().realtimeForceUpdates; }
set { GetOrCreateLightingsSettings().realtimeForceUpdates = value; }
}
[Obsolete("Lightmapping.filterMode is obsolete, use LightingSettings.lightmapFilterMode instead. ", false)]
internal static FilterMode filterMode
{
get { return GetLightingSettingsOrDefaultsFallback().lightmapFilterMode; }
set { GetOrCreateLightingsSettings().lightmapFilterMode = value; }
}
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern bool isProgressiveLightmapperDone {[NativeName("IsBakedGIDone")] get; }
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern RunningBakeInfo GetRunningBakeInfo();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern float ComputeTotalGPUMemoryUsageInBytes();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern void LogGPUMemoryStatistics();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern float GetLightmapBakeTimeTotal();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
[NativeName("GetLightmapBakePerformance")]
internal static extern float GetLightmapBakePerformanceTotal();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern string GetLightmapBakeGPUDeviceName();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern int GetLightmapBakeGPUDeviceIndex();
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
internal static extern DeviceAndPlatform[] GetLightmappingGpuDevices();
// Exports the current state of the scene to the dynamic GI workflow.
[FreeFunction]
internal static extern void PrintStateToConsole();
// Starts an asynchronous bake job.
[FreeFunction]
public static extern bool BakeAsync();
// Stars a synchronous bake job.
[FreeFunction]
public static extern bool Bake();
// Cancels the currently running asynchronous bake job.
[FreeFunction("CancelLightmapping")]
public static extern void Cancel();
// Stops the current bake at the state it has reached so far.
[FreeFunction]
[System.Obsolete("ForceStop is no longer available, use Cancel instead to stop a bake.", false)]
public static extern void ForceStop();
// Returns true when the bake job is running, false otherwise (RO).
public static extern bool isRunning {[FreeFunction("IsRunningLightmapping")] get; }
[System.Obsolete("OnStartedFunction.started is obsolete, please use bakeStarted instead. ", false)]
public static event OnStartedFunction started;
public static event Action bakeStarted;
private static void OpenNestedSubScenes()
{
if (SceneHierarchyHooks.provideSubScenes == null)
return;
var subSceneInfos = SceneHierarchyHooks.provideSubScenes();
if (subSceneInfos != null)
{
// Open all nested sub scenes.
int subSceneCount = subSceneInfos.Length;
foreach (var subSceneInfo in subSceneInfos)
{
if (subSceneInfo.scene.isLoaded)
continue;
var path = AssetDatabase.GetAssetPath(subSceneInfo.sceneAsset);
var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
scene.isSubScene = true;
}
// Keep going deeper until sub scene count has stabilized.
subSceneInfos = SceneHierarchyHooks.provideSubScenes();
if (subSceneCount != subSceneInfos.Length)
OpenNestedSubScenes();
}
}
[RequiredByNativeCode]
private static void Internal_CallBakeStartedFunctions()
{
if (bakeStarted != null)
bakeStarted();
// Open all sub scenes before the bake so they can participate in the GI calculations.
OpenNestedSubScenes();
#pragma warning disable 0618
if (started != null)
started();
#pragma warning restore 0618
}
internal static event Action startedRendering;
[RequiredByNativeCode]
internal static void Internal_CallStartedRenderingFunctions()
{
if (startedRendering != null)
startedRendering();
}
public static event Action lightingDataUpdated;
[RequiredByNativeCode]
internal static void Internal_CallLightingDataUpdatedFunctions()
{
if (lightingDataUpdated != null)
lightingDataUpdated();
}
public static event Action lightingDataCleared;
[RequiredByNativeCode]
internal static void Internal_CallLightingDataCleared()
{
if (lightingDataCleared != null)
lightingDataCleared();
}
public static event Action lightingDataAssetCleared;
[RequiredByNativeCode]
internal static void Internal_CallLightingDataAssetCleared()
{
if (lightingDataAssetCleared != null)
lightingDataAssetCleared();
}
internal static event Action wroteLightingDataAsset;
[RequiredByNativeCode]
internal static void Internal_CallOnWroteLightingDataAsset()
{
if (wroteLightingDataAsset != null)
wroteLightingDataAsset();
}
// This event is fired when BakeInput has been populated, but before passing it to Bake().
// Do not store and access BakeInput beyond the call-back.
internal static event Action<LightBaker.BakeInput, InputExtraction.SourceMap> createdBakeInput;
internal static void Internal_CallOnCreatedBakeInput(IntPtr p_BakeInput, IntPtr p_SourceMap)
{
if (createdBakeInput != null)
{
using var bakeInput = new LightBaker.BakeInput(p_BakeInput);
using var sourceMap = new InputExtraction.SourceMap(p_SourceMap);
createdBakeInput(bakeInput, sourceMap);
}
}
[System.Obsolete("OnCompletedFunction.completed is obsolete, please use event bakeCompleted instead. ", false)]
public static OnCompletedFunction completed;
public static event Action bakeCompleted;
[RequiredByNativeCode]
private static void Internal_CallBakeCompletedFunctions()
{
if (bakeCompleted != null)
bakeCompleted();
#pragma warning disable 0618
if (completed != null)
completed();
#pragma warning restore 0618
}
public static event Action bakeCancelled;
private static void Internal_CallBakeCancelledFunctions()
{
if (bakeCancelled != null)
bakeCancelled();
}
internal static event Action<string> bakeAnalytics;
[RequiredByNativeCode]
private static void Internal_CallBakeAnalyticsFunctions(string analytics)
{
if (bakeAnalytics != null)
bakeAnalytics(analytics);
}
// Returns the progress of a build when the bake job is running, returns 0 when no bake job is running.
public static extern float buildProgress {[FreeFunction] get; }
// Deletes all stored runtime lighting data for the current scene, resets environment lighting to default values.
[FreeFunction]
public static extern void Clear();
// Deletes the lighting data asset for the current scene.
[FreeFunction]
public static extern void ClearLightingDataAsset();
// Calculates a Delaunay Tetrahedralization of the 'positions' point set - the same way the lightmapper
public static void Tetrahedralize(Vector3[] positions, out int[] outIndices, out Vector3[] outPositions)
{
TetrahedralizationData data = TetrahedralizeInternal(positions);
outIndices = data.indices;
outPositions = data.positions;
}
[NativeName("LightProbeUtils::Tetrahedralize")]
[FreeFunction]
private static extern TetrahedralizationData TetrahedralizeInternal(Vector3[] positions);
[FreeFunction]
public static extern bool BakeReflectionProbe(ReflectionProbe probe, string path);
// Used to quickly update baked reflection probes without GI computations.
[FreeFunction]
internal static extern bool BakeReflectionProbeSnapshot(ReflectionProbe probe);
// Used to quickly update all baked reflection probes without GI computations.
[FreeFunction]
internal static extern bool BakeAllReflectionProbesSnapshots();
// Called when the user changes the Lightmap Encoding option:
// - reload shaders to set correct lightmap decoding keyword
// - reimport lightmaps with the new encoding
// - rebake reflection probes because the lightmaps may look different
[FreeFunction]
internal static extern void OnUpdateLightmapEncoding(BuildTargetGroup target);
// Called when the user changes the HDR Cubemap Encoding option,
// will reimport HDR cubemaps with the new encoding.
[FreeFunction]
internal static extern void OnUpdateHDRCubemapEncoding(BuildTargetGroup target);
// Called when the user changes the Lightmap streaming settings:
[FreeFunction]
internal static extern void OnUpdateLightmapStreaming(BuildTargetGroup target);
[FreeFunction]
public static extern void GetTerrainGIChunks([NotNull] Terrain terrain, ref int numChunksX, ref int numChunksY);
[StaticAccessor("GetLightmapSettings()")]
public static extern LightingDataAsset lightingDataAsset { get; set; }
public static bool TryGetLightingSettings(out LightingSettings settings)
{
settings = lightingSettingsInternal;
return (settings != null);
}
public static LightingSettings lightingSettings
{
get
{
var settings = lightingSettingsInternal;
if (settings == null)
{
throw new Exception("Lightmapping.lightingSettings is null. Please assign it to an existing asset or a new instance. ");
}
return settings;
}
set
{
lightingSettingsInternal = value;
}
}
[StaticAccessor("GetLightmapSettings()")]
[NativeName("LightingSettings")]
internal static extern LightingSettings lightingSettingsInternal { get; set; }
[StaticAccessor("GetLightmapSettings()")]
[NativeName("LightingSettingsDefaults_Scripting")]
public static extern LightingSettings lightingSettingsDefaults { get; }
// To be used by internal code when just reading settings, not settings them
internal static LightingSettings GetLightingSettingsOrDefaultsFallback()
{
var lightingSettings = Lightmapping.lightingSettingsInternal;
if (lightingSettings != null)
return lightingSettings;
return Lightmapping.lightingSettingsDefaults;
}
// used to make sure that the old APIs work. The user should not be required to manually create an asset, so we do it for them.
internal static LightingSettings GetOrCreateLightingsSettings()
{
if (Lightmapping.lightingSettingsInternal == null)
{
Lightmapping.lightingSettingsInternal = new LightingSettings();
}
return Lightmapping.lightingSettingsInternal;
}
[StaticAccessor("GetLightmapSettingsManager()")]
[NativeName("SetLightingSettingsForScene")]
public static extern void SetLightingSettingsForScene(Scene scene, LightingSettings lightingSettings);
[StaticAccessor("GetLightmapSettingsManager()")]
[NativeName("SetLightingSettingsForScenes")]
public static extern void SetLightingSettingsForScenes(Scene[] scenes, LightingSettings lightingSettings);
[StaticAccessor("GetLightmapSettingsManager()")]
[NativeName("GetLightingSettingsForScene")]
public static extern LightingSettings GetLightingSettingsForScene(Scene scene);
public static void BakeMultipleScenes(string[] paths)
{
if (paths.Length == 0)
return;
for (int i = 0; i < paths.Length; i++)
{
for (int j = i + 1; j < paths.Length; j++)
{
if (paths[i] == paths[j])
throw new System.Exception("no duplication of scenes is allowed");
}
}
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
return;
var sceneSetup = EditorSceneManager.GetSceneManagerSetup();
// Restore old scene setup once the bake finishes
Action OnBakeFinish = null;
OnBakeFinish = () =>
{
EditorSceneManager.SaveOpenScenes();
if (sceneSetup.Length > 0)
EditorSceneManager.RestoreSceneManagerSetup(sceneSetup);
Lightmapping.bakeCompleted -= OnBakeFinish;
};
// Call BakeAsync when all scenes are loaded and attach cleanup delegate
EditorSceneManager.SceneOpenedCallback BakeOnAllOpen = null;
BakeOnAllOpen = (UnityEngine.SceneManagement.Scene scene, SceneManagement.OpenSceneMode loadSceneMode) =>
{
if (SceneManager.loadedSceneCount == paths.Length)
{
BakeAsync();
Lightmapping.bakeCompleted += OnBakeFinish;
EditorSceneManager.sceneOpened -= BakeOnAllOpen;
}
};
EditorSceneManager.sceneOpened += BakeOnAllOpen;
EditorSceneManager.OpenScene(paths[0]);
for (int i = 1; i < paths.Length; i++)
EditorSceneManager.OpenScene(paths[i], OpenSceneMode.Additive);
}
// Reset lightmapping settings
[StaticAccessor("GetLightingSettings()")]
extern internal static void Reset();
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool IsLightmappedOrDynamicLightmappedForRendering([NotNull] Renderer renderer);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool IsOptixDenoiserSupported();
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool IsOpenImageDenoiserSupported();
// Packing for realtime GI may fail of the mesh has zero UV or surface area. This is the outcome for the given renderer.
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool HasZeroAreaMesh([NotNull] Renderer renderer);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool HasUVOverlaps([NotNull] Renderer renderer);
// Packing for realtime GI may clamp the output resolution. This is the outcome for the given renderer.
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool HasClampedResolution([NotNull] Renderer renderer);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetSystemResolution([NotNull] Renderer renderer, out int width, out int height);
[FreeFunction("GetSystemResolution")]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetTerrainSystemResolution([NotNull] Terrain terrain, out int width, out int height, out int numChunksInX, out int numChunksInY);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetInstanceResolution([NotNull] Renderer renderer, out int width, out int height);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetInputSystemHash(int instanceID, out Hash128 inputSystemHash);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetLightmapIndex(int instanceID, out int lightmapIndex);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal Hash128[] GetMainSystemHashes();
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetInstanceHash([NotNull] Renderer renderer, out Hash128 instanceHash);
[FreeFunction]
[NativeHeader("Editor/Src/GI/EditorHelpers.h")]
extern static internal bool GetGeometryHash([NotNull] Renderer renderer, out Hash128 geometryHash);
[FreeFunction]
[NativeHeader("Editor/Src/GI/ExtractInstances.h")]
extern static internal bool IsRendererValid([NotNull] Renderer renderer);
public delegate void AdditionalBakeDelegate(ref float progress, ref bool done);
[RequiredByNativeCode]
public static void SetAdditionalBakeDelegate(AdditionalBakeDelegate del) { s_AdditionalBakeDelegate = del != null ? del : s_DefaultAdditionalBakeDelegate; }
[RequiredByNativeCode]
public static AdditionalBakeDelegate GetAdditionalBakeDelegate() { return s_AdditionalBakeDelegate; }
[RequiredByNativeCode]
public static void ResetAdditionalBakeDelegate() { s_AdditionalBakeDelegate = s_DefaultAdditionalBakeDelegate; }
[RequiredByNativeCode]
internal static void AdditionalBake(ref float progress, ref bool done)
{
s_AdditionalBakeDelegate(ref progress, ref done);
}
[RequiredByNativeCode]
private static readonly AdditionalBakeDelegate s_DefaultAdditionalBakeDelegate = (ref float progress, ref bool done) =>
{
progress = 100.0f;
done = true;
};
[RequiredByNativeCode]
private static AdditionalBakeDelegate s_AdditionalBakeDelegate = s_DefaultAdditionalBakeDelegate;
}
}
namespace UnityEditor.Experimental
{
public sealed partial class Lightmapping
{
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
public static extern bool probesIgnoreDirectEnvironment { get; set; }
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
public static extern bool probesIgnoreIndirectEnvironment { get; set; }
public static void SetCustomBakeInputs(Vector4[] inputData, int sampleCount)
{
SetCustomBakeInputs(inputData.AsSpan(), sampleCount);
}
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
public static extern void SetCustomBakeInputs(ReadOnlySpan<Vector4> inputData, int sampleCount);
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
private static extern unsafe bool GetCustomBakeResultsCopy(Span<Vector4> results);
public static bool GetCustomBakeResults(Span<Vector4> results)
{
return GetCustomBakeResultsCopy(results);
}
public static bool GetCustomBakeResults([Out] Vector4[] results)
{
return GetCustomBakeResults(results.AsSpan());
}
[StaticAccessor("BakedGISceneManager::Get()", StaticAccessorType.Arrow)]
public static extern ReadOnlySpan<Vector4> GetCustomBakeResultsNoCopy();
[Obsolete("UnityEditor.Experimental.Lightmapping.extractAmbientOcclusion is obsolete, use LightingSettings.extractAO instead. ", false)]
public static bool extractAmbientOcclusion
{
get { return UnityEditor.Lightmapping.GetLightingSettingsOrDefaultsFallback().extractAO; }
set { UnityEditor.Lightmapping.GetOrCreateLightingsSettings().extractAO = value; }
}
public static bool BakeAsync(Scene targetScene)
{
return BakeSceneAsync(targetScene);
}
[NativeThrows]
[FreeFunction]
[NativeName("BakeAsync")]
static extern bool BakeSceneAsync(Scene targetScene);
public static bool Bake(Scene targetScene)
{
return BakeScene(targetScene);
}
[NativeThrows]
[FreeFunction]
[NativeName("Bake")]
static extern bool BakeScene(Scene targetScene);
public static event Action additionalBakedProbesCompleted;
[RequiredByNativeCode]
internal static void Internal_CallAdditionalBakedProbesCompleted()
{
if (additionalBakedProbesCompleted != null)
additionalBakedProbesCompleted();
}
[FreeFunction]
internal unsafe static extern bool GetAdditionalBakedProbes(int id, void* outBakedProbeSH, void* outBakedProbeValidity, void* outBakedProbeOctahedralDepth, int outBakedProbeCount);
[Obsolete("Please use the new GetAdditionalBakedProbes with added octahedral depth map data.", false)]
public unsafe static bool GetAdditionalBakedProbes(int id, NativeArray<SphericalHarmonicsL2> outBakedProbeSH, NativeArray<float> outBakedProbeValidity)
{
const int octahedralDepthMapTexelCount = 64; // 8*8
var outBakedProbeOctahedralDepth = new NativeArray<float>(outBakedProbeSH.Length * octahedralDepthMapTexelCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
bool success = GetAdditionalBakedProbes(id, outBakedProbeSH, outBakedProbeValidity, outBakedProbeOctahedralDepth);
outBakedProbeOctahedralDepth.Dispose();
return success;
}
public unsafe static bool GetAdditionalBakedProbes(int id, Span<SphericalHarmonicsL2> outBakedProbeSH, Span<float> outBakedProbeValidity, Span<float> outBakedProbeOctahedralDepth)
{
const int octahedralDepthMapTexelCount = 64; // 8*8
int numEntries = outBakedProbeSH.Length;
if (outBakedProbeOctahedralDepth.Length != numEntries * octahedralDepthMapTexelCount)
{
Debug.LogError("Octahedral array must provide " + numEntries * octahedralDepthMapTexelCount + " floats.");
return false;
}
if (outBakedProbeValidity.Length != numEntries)
{
Debug.LogError("All output arrays must have equal size.");
return false;
}
fixed (void* shPtr = outBakedProbeSH)
fixed (void* validityPtr = outBakedProbeValidity)
fixed (void* octahedralDepthPtr = outBakedProbeOctahedralDepth)
{
return GetAdditionalBakedProbes(id, shPtr, validityPtr, octahedralDepthPtr, outBakedProbeSH.Length);
}
}
public unsafe static bool GetAdditionalBakedProbes(int id, NativeArray<SphericalHarmonicsL2> outBakedProbeSH, NativeArray<float> outBakedProbeValidity, NativeArray<float> outBakedProbeOctahedralDepth)
{
if (outBakedProbeSH == null || !outBakedProbeSH.IsCreated ||
outBakedProbeValidity == null || !outBakedProbeValidity.IsCreated ||
outBakedProbeOctahedralDepth == null || !outBakedProbeOctahedralDepth.IsCreated)
{
Debug.LogError("Output arrays need to be properly initialized.");
return false;
}
const int octahedralDepthMapTexelCount = 64; // 8*8
int numEntries = outBakedProbeSH.Length;
if (outBakedProbeOctahedralDepth.Length != numEntries * octahedralDepthMapTexelCount)
{
Debug.LogError("Octahedral array must provide " + numEntries * octahedralDepthMapTexelCount + " floats.");
return false;
}
if (outBakedProbeValidity.Length != numEntries)
{
Debug.LogError("All output arrays must have equal size.");
return false;
}
void* shPtr = NativeArrayUnsafeUtility.GetUnsafePtr(outBakedProbeSH);
void* validityPtr = NativeArrayUnsafeUtility.GetUnsafePtr(outBakedProbeValidity);
void* octahedralDepthPtr = NativeArrayUnsafeUtility.GetUnsafePtr(outBakedProbeOctahedralDepth);
return GetAdditionalBakedProbes(id, shPtr, validityPtr, octahedralDepthPtr, outBakedProbeSH.Length);
}
public static void SetAdditionalBakedProbes(int id, Vector3[] positions)
{
SetAdditionalBakedProbes(id, positions.AsSpan(), true);
}
public static void SetAdditionalBakedProbes(int id, ReadOnlySpan<Vector3> positions)
{
SetAdditionalBakedProbes(id, positions, true);
}
[FreeFunction]
public static extern void SetAdditionalBakedProbes(int id, ReadOnlySpan<Vector3> positions, bool dering);
[FreeFunction]
public static extern void SetLightDirty(Light light);
}
}
| UnityCsReference/Editor/Mono/GI/Lightmapping.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GI/Lightmapping.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 13045
} | 302 |
// 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 UnityEditorInternal;
using UnityEditor.Scripting;
using System.Collections.Generic;
using System.IO;
namespace UnityEditor
{
internal class AssetSaveDialog : EditorWindow
{
class Styles
{
public GUIStyle selected = "OL SelectedRow";
public GUIStyle box = "OL Box";
public GUIStyle button = "LargeButton";
public GUIStyle labelHeight = "Label";
public GUIContent saveSelected = EditorGUIUtility.TrTextContent("Save Selected");
public GUIContent saveAll = EditorGUIUtility.TrTextContent("Save All");
public GUIContent dontSave = EditorGUIUtility.TrTextContent("Don't Save");
public GUIContent close = EditorGUIUtility.TrTextContent("Close");
public float buttonWidth;
public Styles()
{
labelHeight = new GUIStyle(GUI.skin.label);
labelHeight.fixedHeight = 64;
buttonWidth = Mathf.Max(Mathf.Max(button.CalcSize(saveSelected).x, button.CalcSize(saveAll).x), button.CalcSize(dontSave).x);
}
}
static Styles s_Styles = null;
List<string> m_Assets;
List<string> m_AssetsToSave;
ListViewState m_LV = new ListViewState();
int m_InitialSelectedItem = -1;
bool[] m_SelectedItems;
List<GUIContent> m_Content;
void SetAssets(string[] assets)
{
m_Assets = new List<string>(assets);
RebuildLists(true);
m_AssetsToSave = new List<string>();
}
public static void ShowWindow(string[] inAssets, out string[] assetsThatShouldBeSaved)
{
int numMetaFiles = 0;
foreach (string path in inAssets)
{
if (path.EndsWith("meta"))
numMetaFiles++;
}
int numAssets = inAssets.Length - numMetaFiles;
if (numAssets == 0)
{
assetsThatShouldBeSaved = inAssets;
return;
}
string[] assets = new string[numAssets];
string[] metaFiles = new string[numMetaFiles];
numAssets = 0;
numMetaFiles = 0;
foreach (string path in inAssets)
{
if (path.EndsWith("meta"))
metaFiles[numMetaFiles++] = path;
else
assets[numAssets++] = path;
}
AssetSaveDialog win = EditorWindow.GetWindowDontShow<AssetSaveDialog>();
win.titleContent = EditorGUIUtility.TrTextContent("Save Assets");
win.SetAssets(assets);
win.minSize = new Vector2(400, 100);
win.maxSize = new Vector2(550, 550);
win.ShowModal();
assetsThatShouldBeSaved = new string[win.m_AssetsToSave.Count + numMetaFiles];
win.m_AssetsToSave.CopyTo(assetsThatShouldBeSaved, 0);
metaFiles.CopyTo(assetsThatShouldBeSaved, win.m_AssetsToSave.Count);
}
public static GUIContent GetContentForAsset(string path)
{
Texture icon = AssetDatabase.GetCachedIcon(path);
if (path.StartsWith("Library/"))
path = ObjectNames.NicifyVariableName(AssetDatabase.LoadMainAssetAtPath(path).name);
if (path.StartsWith("Assets/"))
path = path.Substring(7);
return new GUIContent(path, icon);
}
void OnGUI()
{
if (s_Styles == null)
{
s_Styles = new Styles();
minSize = new Vector2(500, 300);
position = new Rect(position.x, position.y, minSize.x, minSize.y);
}
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.Label("Unity is about to save the following modified files. Unsaved changes will be lost!");
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
int prevSelectedRow = m_LV.row;
int numSelected = 0;
foreach (ListViewElement el in ListViewGUILayout.ListView(m_LV, s_Styles.box))
{
if (m_SelectedItems[el.row] && Event.current.type == EventType.Repaint)
{
Rect box = el.position;
box.x += 1;
box.y += 1;
box.width -= 1;
box.height -= 1;
s_Styles.selected.Draw(box, false, false, false, false);
}
GUILayout.Label(m_Content[el.row], s_Styles.labelHeight);
if (ListViewGUILayout.HasMouseUp(el.position))
{
Event.current.command = true;
Event.current.control = true;
ListViewGUILayout.MultiSelection(prevSelectedRow, el.row, ref m_InitialSelectedItem, ref m_SelectedItems);
}
if (m_SelectedItems[el.row])
numSelected++;
}
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
if (GUILayout.Button(s_Styles.close, s_Styles.button, GUILayout.Width(s_Styles.buttonWidth)))
{
CloseWindow();
}
GUILayout.FlexibleSpace();
GUI.enabled = numSelected > 0;
bool allSelected = numSelected == m_Assets.Count;
if (GUILayout.Button(s_Styles.dontSave, s_Styles.button, GUILayout.Width(s_Styles.buttonWidth)))
{
IgnoreSelectedAssets();
}
if (GUILayout.Button(allSelected ? s_Styles.saveAll : s_Styles.saveSelected,
s_Styles.button, GUILayout.Width(s_Styles.buttonWidth)))
{
SaveSelectedAssets();
}
GUI.enabled = true;
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(10);
if (m_Assets.Count == 0)
CloseWindow();
}
void Cancel()
{
Close();
GUIUtility.ExitGUI();
}
void CloseWindow()
{
Close();
GUIUtility.ExitGUI();
}
void SaveSelectedAssets()
{
List<string> newAssets = new List<string>();
for (int i = 0; i < m_SelectedItems.Length; i++)
{
if (m_SelectedItems[i])
m_AssetsToSave.Add(m_Assets[i]);
else
newAssets.Add(m_Assets[i]);
}
m_Assets = newAssets;
RebuildLists(false);
}
void IgnoreSelectedAssets()
{
List<string> newAssets = new List<string>();
for (int i = 0; i < m_SelectedItems.Length; i++)
{
if (!m_SelectedItems[i])
newAssets.Add(m_Assets[i]);
}
m_Assets = newAssets;
RebuildLists(false);
if (m_Assets.Count == 0)
CloseWindow();
}
void RebuildLists(bool selected)
{
m_LV.totalRows = m_Assets.Count;
m_SelectedItems = new bool[m_Assets.Count];
m_Content = new List<GUIContent>(m_Assets.Count);
for (int i = 0; i < m_Assets.Count; i++)
{
m_SelectedItems[i] = selected;
m_Content.Add(GetContentForAsset(m_Assets[i]));
}
}
}
}
| UnityCsReference/Editor/Mono/GUI/AssetSaveDialog.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/AssetSaveDialog.cs",
"repo_id": "UnityCsReference",
"token_count": 4244
} | 303 |
// 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 Object = UnityEngine.Object;
namespace UnityEditor
{
//@todo This should be handled through friend assemblies instead
internal sealed class EditorGUIInternal : GUI
{
// Choose how toggles appear when showing mixed values
static internal GUIStyle mixedToggleStyle
{
get { return s_MixedToggleStyle; }
set { s_MixedToggleStyle = value; }
}
private static GUIStyle s_MixedToggleStyle = EditorStyles.toggleMixed;
const float kExposureSliderAbsoluteMax = 23.0f;
static readonly GUIContent s_ExposureIcon = EditorGUIUtility.TrIconContent("Exposure", "Controls the number of stops to over or under expose the texture.");
static internal Rect GetTooltipRect() { return tooltipRect; }
static internal string GetMouseTooltip() { return mouseTooltip; }
internal static bool DoToggleForward(Rect position, int id, bool value, GUIContent content, GUIStyle style, bool expandWidth = true)
{
Event evt = Event.current;
if (EditorGUI.showMixedValue)
style = mixedToggleStyle;
// Ignore mouse clicks that are not with the primary (left) mouse button so those can be grabbed by other things later.
EventType origType = evt.type;
bool nonLeftClick = (evt.type == EventType.MouseDown && evt.button != 0);
if (nonLeftClick)
evt.type = EventType.Ignore;
bool returnValue;
bool computedValue = EditorGUI.showMixedValue ? false : value;
if (expandWidth)
{
returnValue = DoToggle(position, id, computedValue, content, style);
}
else
{
var toggleSize = style.CalcSize(content);
var visibleRect = new Rect(position.position.x, position.position.y, toggleSize.x, position.height);
returnValue = DoToggle(visibleRect, id, computedValue, content, style);
}
if (nonLeftClick)
evt.type = origType;
else if (evt.type != origType)
EditorGUIUtility.keyboardControl = id; // If control used event, give it keyboard focus.
return returnValue;
}
internal static Vector2 DoBeginScrollViewForward(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background)
{
return DoBeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background);
}
internal static void BeginWindowsForward(int skinMode, int editorWindowInstanceID)
{
BeginWindows(skinMode, editorWindowInstanceID);
}
internal static void AssetPopup<T>(SerializedProperty serializedProperty, GUIContent content, string fileExtension) where T : Object, new()
{
AssetPopup<T>(serializedProperty, content, fileExtension, "Default");
}
internal static void AssetPopup<T>(SerializedProperty serializedProperty, GUIContent content, string fileExtension, string defaultFieldName) where T : Object, new()
{
AssetPopupBackend.AssetPopup<T>(serializedProperty, content, fileExtension, defaultFieldName);
}
internal static float ExposureSlider(float value, ref float maxValue, GUIStyle style)
{
float labelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 20;
value = EditorGUILayout.Slider(s_ExposureIcon, value, -maxValue, maxValue, -kExposureSliderAbsoluteMax, kExposureSliderAbsoluteMax, style, GUILayout.MaxWidth(64));
// This will allow the user to set a new max value for the current session
if (value >= 0)
maxValue = Mathf.Max(maxValue, value);
else
maxValue = Mathf.Max(maxValue, value * -1);
EditorGUIUtility.labelWidth = labelWidth;
return value;
}
}
//@todo This should be handled through friend assemblies instead
internal sealed class EditorGUILayoutUtilityInternal : GUILayoutUtility
{
internal new static GUILayoutGroup BeginLayoutArea(GUIStyle style, System.Type LayoutType)
{
return GUILayoutUtility.DoBeginLayoutArea(style, LayoutType);
}
internal new static GUILayoutGroup topLevel
{
get { return GUILayoutUtility.topLevel; }
}
}
}
| UnityCsReference/Editor/Mono/GUI/EditorGUIInternal.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/EditorGUIInternal.cs",
"repo_id": "UnityCsReference",
"token_count": 1905
} | 304 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Linq;
using UnityEngine;
using System.Collections.Generic;
// NOTE:
// This file should only contain internal functions of the EditorGUI class
//
namespace UnityEditor
{
public sealed partial class EditorGUI
{
internal static int s_DropdownButtonHash = "DropdownButton".GetHashCode();
static int s_MouseDeltaReaderHash = "MouseDeltaReader".GetHashCode();
internal static bool Button(Rect position, GUIContent content)
{
return Button(position, content, EditorStyles.miniButton);
}
// We need an EditorGUI.Button that only reacts to left mouse button (GUI.Button reacts to all mouse buttons), so we
// can handle context click events for button areas etc.
internal static bool Button(Rect position, GUIContent content, GUIStyle style)
{
Event evt = Event.current;
switch (evt.type)
{
case EventType.MouseDown:
case EventType.MouseUp:
if (evt.button != 0)
return false; // ignore all input from other buttons than the left mouse button
break;
}
return GUI.Button(position, content, style);
}
// Button used for the icon selector where an icon can be selected by pressing and dragging the
// mouse cursor around to select different icons
internal static bool IconButton(int id, Rect position, GUIContent content, GUIStyle style)
{
GUIUtility.CheckOnGUI();
switch (Event.current.GetTypeForControl(id))
{
case EventType.MouseDown:
// If the mouse is inside the button, we say that we're the hot control
if (position.Contains(Event.current.mousePosition))
{
GUIUtility.hotControl = id;
Event.current.Use();
return true;
}
return false;
case EventType.MouseUp:
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
// If we got the mousedown, the mouseup is ours as well
// (no matter if the click was in the button or not)
Event.current.Use();
// But we only return true if the button was actually clicked
return position.Contains(Event.current.mousePosition);
}
return false;
case EventType.MouseDrag:
if (position.Contains(Event.current.mousePosition))
{
GUIUtility.hotControl = id;
Event.current.Use();
return true;
}
break;
case EventType.Repaint:
style.Draw(position, content, id);
break;
}
return false;
}
internal static float WidthResizer(Rect position, float width, float minWidth, float maxWidth)
{
bool hasControl;
return Resizer.Resize(position, width, minWidth, maxWidth, true, out hasControl);
}
internal static float WidthResizer(Rect position, float width, float minWidth, float maxWidth, out bool hasControl)
{
return Resizer.Resize(position, width, minWidth, maxWidth, true, out hasControl);
}
internal static float HeightResizer(Rect position, float height, float minHeight, float maxHeight)
{
bool hasControl;
return Resizer.Resize(position, height, minHeight, maxHeight, false, out hasControl);
}
internal static float HeightResizer(Rect position, float height, float minHeight, float maxHeight, out bool hasControl)
{
return Resizer.Resize(position, height, minHeight, maxHeight, false, out hasControl);
}
static class Resizer
{
static float s_StartSize;
static Vector2 s_MouseDeltaReaderStartPos;
internal static float Resize(Rect position, float size, float minSize, float maxSize, bool horizontal, out bool hasControl)
{
int id = EditorGUIUtility.GetControlID(s_MouseDeltaReaderHash, FocusType.Passive, position);
Event evt = Event.current;
switch (evt.GetTypeForControl(id))
{
case EventType.MouseDown:
if (GUIUtility.hotControl == 0 && position.Contains(evt.mousePosition) && evt.button == 0)
{
GUIUtility.hotControl = id;
GUIUtility.keyboardControl = 0;
s_MouseDeltaReaderStartPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews
s_StartSize = size;
evt.Use();
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == id)
{
evt.Use();
Vector2 screenPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews
float delta = horizontal ? (screenPos - s_MouseDeltaReaderStartPos).x : (screenPos - s_MouseDeltaReaderStartPos).y;
float newSize = s_StartSize + delta;
if (newSize >= minSize && newSize <= maxSize)
size = newSize;
else
size = Mathf.Clamp(newSize, minSize, maxSize);
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id && evt.button == 0)
{
GUIUtility.hotControl = 0;
evt.Use();
}
break;
case EventType.Repaint:
var cursor = horizontal ? MouseCursor.SplitResizeLeftRight : MouseCursor.SplitResizeUpDown;
EditorGUIUtility.AddCursorRect(position, cursor, id);
break;
}
hasControl = GUIUtility.hotControl == id;
return size;
}
}
// Get mouse delta values in different situations when click-dragging
static Vector2 s_MouseDeltaReaderLastPos;
internal static Vector2 MouseDeltaReader(Rect position, bool activated)
{
int id = EditorGUIUtility.GetControlID(s_MouseDeltaReaderHash, FocusType.Passive, position);
Event evt = Event.current;
switch (evt.GetTypeForControl(id))
{
case EventType.MouseDown:
if (activated && GUIUtility.hotControl == 0 && GUIUtility.HitTest(position, evt) && evt.button == 0)
{
GUIUtility.hotControl = id;
GUIUtility.keyboardControl = 0;
s_MouseDeltaReaderLastPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews
evt.Use();
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == id)
{
Vector2 screenPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews
Vector2 delta = (screenPos - s_MouseDeltaReaderLastPos);
s_MouseDeltaReaderLastPos = screenPos;
evt.Use();
return delta;
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id && evt.button == 0)
{
GUIUtility.hotControl = 0;
evt.Use();
}
break;
}
return Vector2.zero;
}
private static GUIStyle s_LargeSplitLeftStyle;
private static GUIStyle s_LargeSplitRightStyle;
public static bool LargeSplitButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback)
{
// Load required styles
if (s_LargeSplitLeftStyle == null)
s_LargeSplitLeftStyle = new GUIStyle(EditorStyles.miniButtonLeft) { fixedHeight = kLargeButtonHeight };
if (s_LargeSplitRightStyle == null)
s_LargeSplitRightStyle = new GUIStyle(EditorStyles.miniButtonRight) { fixedHeight = kLargeButtonHeight };
if (s_IconDropDown == null)
s_IconDropDown = EditorGUIUtility.IconContent("icon dropdown");
EditorGUILayout.BeginHorizontal();
// Main button
bool clicked = GUILayout.Button(content, s_LargeSplitLeftStyle);
// Dropdown
const int dropdownAreaWidth = 18;
if (GUILayout.Button(s_IconDropDown, s_LargeSplitRightStyle, GUILayout.Width(dropdownAreaWidth)))
{
var menu = new GenericMenu();
for (int i = 0; i != buttonNames.Length; i++)
menu.AddItem(new GUIContent(buttonNames[i]), false, callback, i);
menu.DropDown(GUILayoutUtility.current.topLevel.GetLast());
}
EditorGUILayout.EndHorizontal();
return clicked;
}
public static bool LargeSplitButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, bool disableMainButton)
{
// Load required styles
if (s_LargeSplitLeftStyle == null)
s_LargeSplitLeftStyle = new GUIStyle(EditorStyles.miniButtonLeft) { fixedHeight = kLargeButtonHeight };
if (s_LargeSplitRightStyle == null)
s_LargeSplitRightStyle = new GUIStyle(EditorStyles.miniButtonRight) { fixedHeight = kLargeButtonHeight };
if (s_IconDropDown == null)
s_IconDropDown = EditorGUIUtility.IconContent("icon dropdown");
EditorGUILayout.BeginHorizontal();
// Main button
bool clicked;
using (new EditorGUI.DisabledScope(disableMainButton))
{
clicked = GUILayout.Button(content, s_LargeSplitLeftStyle);
}
// Dropdown
const int dropdownAreaWidth = 18;
if (GUILayout.Button(s_IconDropDown, s_LargeSplitRightStyle, GUILayout.Width(dropdownAreaWidth)))
{
var menu = new GenericMenu();
for (int i = 0; i != buttonNames.Length; i++)
menu.AddItem(new GUIContent(buttonNames[i]), false, callback, i);
menu.DropDown(GUILayoutUtility.current.topLevel.GetLast());
}
EditorGUILayout.EndHorizontal();
return clicked;
}
// Shows an active button and a triangle button on the right, which expands the dropdown list
// Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked.
internal static bool ButtonWithDropdownList(string buttonName, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options)
{
var content = EditorGUIUtility.TempContent(buttonName);
return ButtonWithDropdownList(content, buttonNames, callback, options);
}
// Shows an active button and a triangle button on the right, which expands the dropdown list
// Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked.
internal static bool ButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options)
{
var rect = GUILayoutUtility.GetRect(content, GUI.skin.button, options);
var dropDownRect = rect;
const float kDropDownButtonWidth = 20f;
dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth;
if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition))
{
var menu = new GenericMenu();
for (int i = 0; i != buttonNames.Length; i++)
menu.AddItem(new GUIContent(buttonNames[i]), false, callback, i);
menu.DropDown(rect);
Event.current.Use();
return false;
}
return GUI.Button(rect, content, EditorStyles.dropDownList);
}
internal static void GameViewSizePopup(Rect buttonRect, GameViewSizeGroupType groupType, int selectedIndex, IGameViewSizeMenuUser gameView, GUIStyle guiStyle)
{
var group = GameViewSizes.instance.GetGroup(groupType);
var text = "";
if (selectedIndex >= 0 && selectedIndex < group.GetTotalCount())
text = group.GetGameViewSize(selectedIndex).displayText;
if (EditorGUI.DropdownButton(buttonRect, GUIContent.Temp(text), FocusType.Passive, guiStyle))
{
var menuData = new GameViewSizesMenuItemProvider(groupType);
var flexibleMenu = new GameViewSizeMenu(menuData, selectedIndex, new GameViewSizesMenuModifyItemUI(), gameView);
PopupWindow.Show(buttonRect, flexibleMenu);
}
}
public static void DrawRect(Rect rect, Color color)
{
if (Event.current.type != EventType.Repaint)
return;
Color orgColor = GUI.color;
GUI.color = GUI.color * color;
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
GUI.color = orgColor;
}
internal static void DrawDelimiterLine(Rect rect)
{
DrawRect(rect, kSplitLineSkinnedColor.color);
}
internal static void DrawOutline(Rect rect, float size, Color color)
{
if (Event.current.type != EventType.Repaint)
return;
Color orgColor = GUI.color;
GUI.color = GUI.color * color;
GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, size), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(rect.x, rect.yMax - size, rect.width, size), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(rect.x, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(rect.xMax - size, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture);
GUI.color = orgColor;
}
}
internal struct PropertyGUIData
{
public SerializedProperty property;
public Rect totalPosition;
public bool wasBoldDefaultFont;
public bool wasEnabled;
public Color color;
public PropertyGUIData(SerializedProperty property, Rect totalPosition, bool wasBoldDefaultFont, bool wasEnabled, Color color)
{
this.property = property;
this.totalPosition = totalPosition;
this.wasBoldDefaultFont = wasBoldDefaultFont;
this.wasEnabled = wasEnabled;
this.color = color;
}
}
internal class DebugUtils
{
internal static string ListToString<T>(IEnumerable<T> list)
{
if (list == null)
return "[null list]";
string r = "[";
int count = 0;
foreach (T item in list)
{
if (count != 0)
r += ", ";
if (item != null)
r += item.ToString();
else
r += "'null'";
count++;
}
r += "]";
if (count == 0)
return "[empty list]";
return "(" + count + ") " + r;
}
}
}
| UnityCsReference/Editor/Mono/GUI/InternalEditorGUI.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/InternalEditorGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 8066
} | 305 |
// 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;
using UnityEditor.IMGUI.Controls;
using UnityEditor.Utils;
using UnityEngine;
using UnityEditorInternal;
using UnityEditor.Experimental;
namespace UnityEditor
{
internal class PackageExportTreeView
{
TreeViewController m_TreeView;
List<PackageExportTreeViewItem> m_Selection = new List<PackageExportTreeViewItem>();
static readonly bool s_UseFoldouts = true;
public enum EnabledState
{
NotSet = -1,
None = 0,
All = 1,
Mixed = 2
}
private PackageExport m_PackageExport;
public ExportPackageItem[] items { get { return m_PackageExport.items; } }
public PackageExportTreeView(PackageExport packageExport, TreeViewState treeViewState, Rect startRect)
{
m_PackageExport = packageExport;
m_TreeView = new TreeViewController(m_PackageExport, treeViewState);
var dataSource = new PackageExportTreeViewDataSource(m_TreeView, this);
var gui = new PackageExportTreeViewGUI(m_TreeView, this);
m_TreeView.Init(startRect, dataSource, gui, null);
m_TreeView.ReloadData();
m_TreeView.selectionChangedCallback += SelectionChanged;
gui.itemWasToggled += ItemWasToggled;
ComputeEnabledStateForFolders();
}
void ComputeEnabledStateForFolders()
{
var root = m_TreeView.data.root as PackageExportTreeViewItem;
var done = new HashSet<PackageExportTreeViewItem>();
done.Add(root); // Dont compute for root: mark it as done
RecursiveComputeEnabledStateForFolders(root, done);
}
void RecursiveComputeEnabledStateForFolders(PackageExportTreeViewItem pitem, HashSet<PackageExportTreeViewItem> done)
{
if (!pitem.isFolder)
return;
// Depth first recursion to allow parent folders be dependant on child folders
// Recurse
if (pitem.hasChildren)
{
foreach (var child in pitem.children)
{
RecursiveComputeEnabledStateForFolders(child as PackageExportTreeViewItem, done);
}
}
// Now do logic
if (!done.Contains(pitem))
{
EnabledState enabledState = GetFolderChildrenEnabledState(pitem);
pitem.enabledState = enabledState;
// If 'item' is mixed then all of its parents will also be mixed
if (enabledState == EnabledState.Mixed)
{
done.Add(pitem);
var current = pitem.parent as PackageExportTreeViewItem;
while (current != null)
{
if (!done.Contains(current))
{
current.enabledState = EnabledState.Mixed;
done.Add(current);
}
current = current.parent as PackageExportTreeViewItem;
}
}
}
}
EnabledState GetFolderChildrenEnabledState(PackageExportTreeViewItem folder)
{
if (!folder.isFolder)
Debug.LogError("Should be a folder item!");
if (!folder.hasChildren)
return EnabledState.None;
EnabledState amount = EnabledState.NotSet;
var firstChild = folder.children[0] as PackageExportTreeViewItem;
EnabledState initial = firstChild.enabledState;
for (int i = 1; i < folder.children.Count; ++i)
{
var child = folder.children[i] as PackageExportTreeViewItem;
if (initial != child.enabledState)
{
amount = EnabledState.Mixed;
break;
}
}
if (amount == EnabledState.NotSet)
{
amount = initial == EnabledState.All ? EnabledState.All : EnabledState.None;
}
return amount;
}
void SelectionChanged(int[] selectedIDs)
{
// Cache selected tree view items (from ids)
m_Selection = new List<PackageExportTreeViewItem>();
var visibleItems = m_TreeView.data.GetRows();
foreach (var visibleItem in visibleItems)
{
if (selectedIDs.Contains(visibleItem.id))
{
var pitem = visibleItem as PackageExportTreeViewItem;
if (pitem != null)
m_Selection.Add(pitem);
}
}
}
public void OnGUI(Rect rect)
{
int keyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard);
m_TreeView.OnGUI(rect, keyboardControlID);
// Keyboard space toggles selection enabledness
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Space &&
m_Selection != null && m_Selection.Count > 0 && GUIUtility.keyboardControl == keyboardControlID)
{
EnabledState newEnabled = m_Selection[0].enabledState != EnabledState.All ? EnabledState.All : EnabledState.None;
m_Selection[0].enabledState = newEnabled;
ItemWasToggled(m_Selection[0]);
Event.current.Use();
}
}
public void SetAllEnabled(EnabledState enabled)
{
EnableChildrenRecursive(m_TreeView.data.root, enabled);
ComputeEnabledStateForFolders();
}
void ItemWasToggled(PackageExportTreeViewItem pitem)
{
if (m_Selection.Count <= 1)
{
EnableChildrenRecursive(pitem, pitem.enabledState);
}
else
{
foreach (var i in m_Selection)
i.enabledState = pitem.enabledState;
}
ComputeEnabledStateForFolders();
}
void EnableChildrenRecursive(TreeViewItem parentItem, EnabledState enabled)
{
if (!parentItem.hasChildren)
return;
foreach (TreeViewItem tvitem in parentItem.children)
{
var pitem = tvitem as PackageExportTreeViewItem;
pitem.enabledState = enabled;
EnableChildrenRecursive(pitem, enabled);
}
}
// Item
private class PackageExportTreeViewItem : TreeViewItem
{
public ExportPackageItem item { get; set; }
private EnabledState m_EnabledState = EnabledState.NotSet;
public EnabledState enabledState
{
get { return item != null ? (EnabledState)item.enabledStatus : m_EnabledState; }
set { if (item != null) item.enabledStatus = (int)value; else m_EnabledState = value; }
}
// We assume that items that don't have ExportPackageItem assigned, are folders.
public bool isFolder
{
get { return item != null ? item.isFolder : true; }
}
public PackageExportTreeViewItem(ExportPackageItem itemIn, int id, int depth, TreeViewItem parent, string displayName)
: base(id, depth, parent, displayName)
{
item = itemIn;
}
}
// Gui
private class PackageExportTreeViewGUI : TreeViewGUI
{
internal static class Constants
{
public static Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResources.folderIconName);
}
public Action<PackageExportTreeViewItem> itemWasToggled;
public int showPreviewForID { get; set; }
private PackageExportTreeView m_PackageExportView;
protected float k_FoldoutWidth = 12f;
public PackageExportTreeViewGUI(TreeViewController treeView, PackageExportTreeView view)
: base(treeView)
{
m_PackageExportView = view;
k_BaseIndent = 4f;
if (!s_UseFoldouts)
k_FoldoutWidth = 0f;
}
override public void OnRowGUI(Rect rowRect, TreeViewItem tvItem, int row, bool selected, bool focused)
{
k_IndentWidth = 18;
k_FoldoutWidth = 18;
const float k_ToggleWidth = 18f;
var pitem = tvItem as PackageExportTreeViewItem;
bool repainting = Event.current.type == EventType.Repaint;
// 0. Selection row rect
if (selected && repainting)
selectionStyle.Draw(rowRect, false, false, true, focused);
// 1. Foldout
if (m_TreeView.data.IsExpandable(tvItem))
DoFoldout(rowRect, tvItem, row);
// 2. Toggle only for items that are actually in the package.
Rect toggleRect = new Rect(k_BaseIndent + tvItem.depth * indentWidth + k_FoldoutWidth, rowRect.y, k_ToggleWidth, rowRect.height);
DoToggle(pitem, toggleRect);
// 3. Icon & Text
// Display folders that will not be included into the package as disabled.
using (new EditorGUI.DisabledScope(pitem.item == null))
{
Rect contentRect = new Rect(toggleRect.xMax, rowRect.y, rowRect.width, rowRect.height);
DoIconAndText(pitem, contentRect, selected, focused);
}
}
static void Toggle(ExportPackageItem[] items, PackageExportTreeViewItem pitem, Rect toggleRect)
{
bool enabled = pitem.enabledState > EnabledState.None;
GUIStyle style = EditorStyles.toggle;
bool setMixed = pitem.isFolder && (pitem.enabledState == EnabledState.Mixed);
if (setMixed)
style = EditorStyles.toggleMixed;
bool newEnabled = GUI.Toggle(toggleRect, enabled, GUIContent.none, style);
if (newEnabled != enabled)
pitem.enabledState = newEnabled ? EnabledState.All : EnabledState.None;
}
void DoToggle(PackageExportTreeViewItem pitem, Rect toggleRect)
{
// Toggle on/off
EditorGUI.BeginChangeCheck();
Toggle(m_PackageExportView.items, pitem, toggleRect);
if (EditorGUI.EndChangeCheck())
{
// Only change selection if we already have single selection (Keep multi-selection when toggling)
if (m_TreeView.GetSelection().Length <= 1 || !m_TreeView.GetSelection().Contains(pitem.id))
{
m_TreeView.SetSelection(new int[] { pitem.id }, false);
m_TreeView.NotifyListenersThatSelectionChanged();
}
if (itemWasToggled != null)
itemWasToggled(pitem);
Event.current.Use();
}
}
void DoIconAndText(PackageExportTreeViewItem item, Rect contentRect, bool selected, bool focused)
{
EditorGUIUtility.SetIconSize(new Vector2(k_IconWidth, k_IconWidth)); // If not set we see icons scaling down if text is being cropped
lineStyle = Styles.lineStyle;
lineStyle.padding.left = 0; // padding could have been set by other tree views
contentRect.height += 5; // with the default row height, underscore and lower parts of characters like g, p, etc. were not visible
if (Event.current.type == EventType.Repaint)
lineStyle.Draw(contentRect, GUIContent.Temp(item.displayName, GetIconForItem(item)), false, false, selected, focused);
EditorGUIUtility.SetIconSize(Vector2.zero);
}
protected override Texture GetIconForItem(TreeViewItem tItem)
{
var pItem = tItem as PackageExportTreeViewItem;
var item = pItem.item;
// Undefined items are always folders.
if (item == null || item.isFolder)
{
return Constants.folderIcon;
}
// We are using this TreeViewGUI when importing and exporting a package, so handle both situations:
// Exporting a package can use cached icons (icons we generate on import)
Texture cachedIcon = AssetDatabase.GetCachedIcon(item.assetPath);
if (cachedIcon != null)
return cachedIcon;
// Importing a package have to use icons based on file extension
return InternalEditorUtility.GetIconForFile(item.assetPath);
}
protected override void RenameEnded()
{
}
}
// Datasource
private class PackageExportTreeViewDataSource : TreeViewDataSource
{
private PackageExportTreeView m_PackageExportView;
public PackageExportTreeViewDataSource(TreeViewController treeView, PackageExportTreeView view)
: base(treeView)
{
m_PackageExportView = view;
rootIsCollapsable = false;
showRootItem = false;
}
public override bool IsRenamingItemAllowed(TreeViewItem item)
{
return false;
}
public override bool IsExpandable(TreeViewItem item)
{
if (!s_UseFoldouts)
return false;
return base.IsExpandable(item);
}
public override void FetchData()
{
int rootDepth = -1; // -1 so its children will have 0 depth
m_RootItem = new PackageExportTreeViewItem(null, "Assets".GetHashCode(), rootDepth, null, "InvisibleAssetsFolder");
bool initExpandedState = true;
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(m_RootItem.id);
ExportPackageItem[] items = m_PackageExportView.items;
Dictionary<string, PackageExportTreeViewItem> treeViewFolders = new Dictionary<string, PackageExportTreeViewItem>();
for (int i = 0; i < items.Length; i++)
{
var item = items[i];
if (PackageImport.HasInvalidCharInFilePath(item.assetPath))
continue; // Do not add invalid paths (we already warn the user with a dialog in PackageImport.cs)
string filename = Path.GetFileName(item.assetPath).ConvertSeparatorsToUnity();
string folderPath = Path.GetDirectoryName(item.assetPath).ConvertSeparatorsToUnity();
// Ensure folders. This is for when installed packages have been moved to other folders.
TreeViewItem targetFolder = EnsureFolderPath(folderPath, treeViewFolders, initExpandedState);
// Add file to folder
if (targetFolder != null)
{
int id = item.assetPath.GetHashCode();
var newItem = new PackageExportTreeViewItem(item, id, targetFolder.depth + 1, targetFolder, filename);
targetFolder.AddChild(newItem);
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(id);
// We need to ensure that the folder is available for
// EnsureFolderPath on subsequent iterations.
if (item.isFolder)
treeViewFolders[item.assetPath] = newItem;
}
}
if (initExpandedState)
m_TreeView.state.expandedIDs.Sort();
}
TreeViewItem EnsureFolderPath(string folderPath, Dictionary<string, PackageExportTreeViewItem> treeViewFolders, bool initExpandedState)
{
// We're in the root folder, so just return the root item as the parent.
if (folderPath == "")
return m_RootItem;
// Does folder path exist?
int id = folderPath.GetHashCode();
TreeViewItem item = TreeViewUtility.FindItem(id, m_RootItem);
if (item != null)
return item;
// Add folders as needed
string[] splitPath = folderPath.Split('/');
string currentPath = "";
TreeViewItem currentItem = m_RootItem;
int folderDepth = -1; // Will be incremented to the right depth in the loop.
for (int depth = 0; depth < splitPath.Length; ++depth)
{
string folder = splitPath[depth];
if (currentPath != "")
currentPath += '/';
currentPath += folder;
// Dont create a 'Assets' folder (we already have that as a hidden root)
if (depth == 0 && currentPath == "Assets")
continue;
// Only increment the folder depth if we are past the root "Assets" folder.
++folderDepth;
id = currentPath.GetHashCode();
PackageExportTreeViewItem foundItem;
if (treeViewFolders.TryGetValue(currentPath, out foundItem))
{
currentItem = foundItem;
}
else
{
// If we do not have a tree view item for this folder we create one
var folderItem = new PackageExportTreeViewItem(null, id, folderDepth, currentItem, folder);
// Add to children array of the parent
currentItem.AddChild(folderItem);
currentItem = folderItem;
// Auto expand all folder items
if (initExpandedState)
m_TreeView.state.expandedIDs.Add(id);
// For faster finding of folders
treeViewFolders[currentPath] = folderItem;
}
}
return currentItem;
}
}
}
}
| UnityCsReference/Editor/Mono/GUI/PackageExportTreeView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/PackageExportTreeView.cs",
"repo_id": "UnityCsReference",
"token_count": 9352
} | 306 |
// 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;
namespace UnityEditor
{
/// orders all children along an axis. Resizing, splitting, etc..
class SplitView : View, ICleanuppable, IDropArea
{
const float kRootDropZoneThickness = 70f;
const float kRootDropZoneOffset = 50f;
const float kRootDropDestinationThickness = 200f;
const float kMaxViewDropZoneThickness = 300f;
const float kMinViewDropDestinationThickness = 100f;
public bool vertical = false;
public int controlID = 0;
[Flags] internal enum ViewEdge
{
None = 0,
Left = 1 << 0,
Bottom = 1 << 1,
Top = 1 << 2,
Right = 1 << 3,
BottomLeft = Bottom | Left,
BottomRight = Bottom | Right,
TopLeft = Top | Left,
TopRight = Top | Right,
FitsVertical = Top | Bottom,
FitsHorizontal = Left | Right,
Before = Top | Left, // "Before" in SplitView children
After = Bottom | Right // "After" in SplitView children
}
private Rect RectFromEdge(Rect rect, ViewEdge edge, float thickness, float offset)
{
switch (edge)
{
case ViewEdge.Left:
return new Rect(rect.x - offset, rect.y, thickness, rect.height);
case ViewEdge.Right:
return new Rect(rect.xMax - thickness + offset, rect.y, thickness, rect.height);
case ViewEdge.Top:
return new Rect(rect.x, rect.y - offset, rect.width, thickness);
case ViewEdge.Bottom:
return new Rect(rect.x, rect.yMax - thickness + offset, rect.width, thickness);
default:
throw new ArgumentException("Specify exactly one edge");
}
}
// Extra info for dropping.
internal class ExtraDropInfo
{
public bool rootWindow;
public ViewEdge edge;
public int index;
public ExtraDropInfo(bool rootWindow, ViewEdge edge, int index)
{
this.rootWindow = rootWindow;
this.edge = edge;
this.index = index;
}
}
SplitterState splitState = null;
void SetupSplitter()
{
float[] actualSizes = new float[children.Length];
float[] minSizes = new float[children.Length];
for (int j = 0; j < children.Length; j++)
{
View c = (View)children[j];
actualSizes[j] = GUIUtility.RoundToPixelGrid(vertical ? c.position.height : c.position.width);
minSizes[j] = GUIUtility.RoundToPixelGrid(vertical ? c.minSize.y : c.minSize.x);
}
splitState = SplitterState.FromAbsolute(actualSizes, minSizes, null);
splitState.splitSize = 10;
}
void SetupRectsFromSplitter()
{
if (children.Length == 0)
return;
float cursor = 0;
float total = 0;
foreach (float size in splitState.realSizes)
{
total += size;
}
float scale = 1;
if (total > (vertical ? position.height : position.width))
scale = (vertical ? position.height : position.width) / total;
// OSX webviews might trigger nested Repaint events when being resized
// so we protected the GUI state at this level
SavedGUIState state = SavedGUIState.Create();
for (int i = 0; i < children.Length; i++)
cursor += PlaceView(i, cursor, splitState.realSizes[i] * scale);
state.ApplyAndForget();
}
// 2-part process: recalc children sizes bottomup, the reflow top-down
static void RecalcMinMaxAndReflowAll(SplitView start)
{
// search upwards and find the topmost
SplitView root = start, next = start;
do
{
root = next;
next = root.parent as SplitView;
}
while (next);
RecalcMinMaxRecurse(root);
ReflowRecurse(root);
}
static void RecalcMinMaxRecurse(SplitView node)
{
foreach (View i in node.children)
{
SplitView sv = i as SplitView;
if (sv)
RecalcMinMaxRecurse(sv);
}
node.ChildrenMinMaxChanged();
}
static void ReflowRecurse(SplitView node)
{
node.Reflow();
foreach (View i in node.children)
{
SplitView sv = i as SplitView;
if (sv)
RecalcMinMaxRecurse(sv);
}
}
internal override void Reflow()
{
SetupSplitter();
for (int k = 0; k < children.Length - 1; k++)
splitState.DoSplitter(k, k + 1, 0);
splitState.RelativeToRealSizes(vertical ? GUIUtility.RoundToPixelGrid(position.height) : GUIUtility.RoundToPixelGrid(position.width));
SetupRectsFromSplitter();
}
float PlaceView(int i, float pos, float size)
{
float width = position.width;
float height = position.height;
float roundPos = GUIUtility.RoundToPixelGrid(pos);
float roundSize = GUIUtility.RoundToPixelGrid(pos + size) - roundPos;
Rect newRect;
if (vertical)
{
newRect = new Rect(0, roundPos, width, roundSize);
if (i == children.Length - 1)
newRect.height = height - roundPos;
}
else
{
newRect = new Rect(roundPos, 0, roundSize, height);
if (i == children.Length - 1)
newRect.width = width - roundPos;
}
children[i].position = newRect;
return vertical ? newRect.height : newRect.width;
}
public override void AddChild(View child, int idx)
{
base.AddChild(child, idx);
ChildrenMinMaxChanged();
splitState = null;
}
public void RemoveChildNice(View child)
{
if (children.Length != 1)
{
// Make neighbors to grow to take space
int idx = IndexOfChild(child);
float moveToPos = 0;
if (idx == 0)
moveToPos = 0;
else if (idx == children.Length - 1)
moveToPos = 1;
else
moveToPos = .5f;
moveToPos = vertical ?
Mathf.Lerp(child.position.yMin, child.position.yMax, moveToPos) :
Mathf.Lerp(child.position.xMin, child.position.xMax, moveToPos);
if (idx > 0)
{
View c = (View)children[idx - 1];
Rect r = c.position;
if (vertical)
r.yMax = moveToPos;
else
r.xMax = moveToPos;
c.position = r;
if (c is SplitView)
((SplitView)c).Reflow();
}
if (idx < children.Length - 1)
{
View c = (View)children[idx + 1];
Rect r = c.position;
if (vertical)
c.position = new Rect(r.x, moveToPos, r.width, r.yMax - moveToPos);
else
c.position = new Rect(moveToPos, r.y, r.xMax - moveToPos, r.height);
if (c is SplitView)
((SplitView)c).Reflow();
}
}
RemoveChild(child);
}
public override void RemoveChild(View child)
{
splitState = null;
base.RemoveChild(child);
}
DropInfo RootViewDropZone(ViewEdge edge, Vector2 mousePos, Rect screenRect)
{
var offset = (edge & ViewEdge.FitsVertical) != 0 ? kRootDropZoneThickness : kRootDropZoneOffset;
if (!RectFromEdge(screenRect, edge, kRootDropZoneThickness, offset).Contains(mousePos))
return null;
var dropInfo = new DropInfo(this);
dropInfo.type = DropInfo.Type.Pane;
dropInfo.userData = new ExtraDropInfo(true, edge, 0);
dropInfo.rect = RectFromEdge(screenRect, edge, kRootDropDestinationThickness, 0f);
return dropInfo;
}
public DropInfo DragOverRootView(Vector2 mouseScreenPosition)
{
if (children.Length == 1 && DockArea.s_IgnoreDockingForView == children[0])
{
return null; // Prevent dragging the view from a single-view window into itself
}
return RootViewDropZone(ViewEdge.Bottom, mouseScreenPosition, screenPosition)
?? RootViewDropZone(ViewEdge.Top, mouseScreenPosition, screenPosition)
?? RootViewDropZone(ViewEdge.Left, mouseScreenPosition, screenPosition)
?? RootViewDropZone(ViewEdge.Right, mouseScreenPosition, screenPosition);
}
public DropInfo DragOver(EditorWindow w, Vector2 mouseScreenPosition)
{
for (var childIndex = 0; childIndex < children.Length; ++childIndex)
{
var child = children[childIndex];
// skip so you can't dock a view to a subview of itself
if (child == DockArea.s_IgnoreDockingForView)
continue;
// Skip if child is a splitview (it'll handle its rect itself)
if (child is SplitView)
continue;
// Collect flags of which edge zones the mouse is inside
var mouseEdges = ViewEdge.None;
var childRect = child.screenPosition;
var childRectWithoutDock = RectFromEdge(childRect, ViewEdge.Bottom, childRect.height - DockArea.kDockHeight, 0f);
var borderWidth = Mathf.Min(Mathf.Round(childRectWithoutDock.width / 3), kMaxViewDropZoneThickness);
var borderHeight = Mathf.Min(Mathf.Round(childRectWithoutDock.height / 3), kMaxViewDropZoneThickness);
var leftDropZone = RectFromEdge(childRectWithoutDock, ViewEdge.Left, borderWidth, 0f);
var rightDropZone = RectFromEdge(childRectWithoutDock, ViewEdge.Right, borderWidth, 0f);
var bottomDropZone = RectFromEdge(childRectWithoutDock, ViewEdge.Bottom, borderHeight, 0f);
var topDropZone = RectFromEdge(childRectWithoutDock, ViewEdge.Top, borderHeight, 0f);
if (leftDropZone.Contains(mouseScreenPosition))
mouseEdges |= ViewEdge.Left;
if (rightDropZone.Contains(mouseScreenPosition))
mouseEdges |= ViewEdge.Right;
if (bottomDropZone.Contains(mouseScreenPosition))
mouseEdges |= ViewEdge.Bottom;
if (topDropZone.Contains(mouseScreenPosition))
mouseEdges |= ViewEdge.Top;
// If mouse is in more than one zone, it is in a corner. Find the corner and divide it diagonally...
var mouseToCorner = Vector2.zero;
var oppositeToCorner = Vector2.zero;
var ccwEdge = mouseEdges;
var cwEdge = mouseEdges;
switch (mouseEdges)
{
case ViewEdge.BottomLeft:
ccwEdge = ViewEdge.Bottom;
cwEdge = ViewEdge.Left;
mouseToCorner = new Vector2(childRectWithoutDock.x, childRectWithoutDock.yMax) - mouseScreenPosition;
oppositeToCorner = new Vector2(-borderWidth, borderHeight);
break;
case ViewEdge.BottomRight:
ccwEdge = ViewEdge.Right;
cwEdge = ViewEdge.Bottom;
mouseToCorner = new Vector2(childRectWithoutDock.xMax, childRectWithoutDock.yMax) - mouseScreenPosition;
oppositeToCorner = new Vector2(borderWidth, borderHeight);
break;
case ViewEdge.TopLeft:
ccwEdge = ViewEdge.Left;
cwEdge = ViewEdge.Top;
mouseToCorner = new Vector2(childRectWithoutDock.x, childRectWithoutDock.y) - mouseScreenPosition;
oppositeToCorner = new Vector2(-borderWidth, -borderHeight);
break;
case ViewEdge.TopRight:
ccwEdge = ViewEdge.Top;
cwEdge = ViewEdge.Right;
mouseToCorner = new Vector2(childRectWithoutDock.xMax, childRectWithoutDock.y) - mouseScreenPosition;
oppositeToCorner = new Vector2(borderWidth, -borderHeight);
break;
}
// ...then choose the edge based on the half the mouse is in
mouseEdges = mouseToCorner.x * oppositeToCorner.y - mouseToCorner.y * oppositeToCorner.x < 0 ? ccwEdge : cwEdge;
if (mouseEdges != ViewEdge.None) // Valid drop zone
{
var targetThickness = Mathf.Round(((mouseEdges & ViewEdge.FitsHorizontal) != 0 ? childRect.width : childRect.height) / 3);
targetThickness = Mathf.Max(targetThickness, kMinViewDropDestinationThickness);
var dropInfo = new DropInfo(this);
dropInfo.userData = new ExtraDropInfo(false, mouseEdges, childIndex);
dropInfo.type = DropInfo.Type.Pane;
dropInfo.rect = RectFromEdge(childRect, mouseEdges, targetThickness, 0f);
return dropInfo;
}
}
// Claim the drag if we are the root split view, so it doesn't fall through to obscured windows
if (screenPosition.Contains(mouseScreenPosition) && !(parent is SplitView))
{
return new DropInfo(null);
}
return null;
}
/// Notification so other views can respond to this.
protected override void ChildrenMinMaxChanged()
{
Vector2 min = Vector2.zero, max = Vector2.zero;
if (vertical)
{
foreach (View child in children)
{
min.x = Mathf.Max(child.minSize.x, min.x);
max.x = Mathf.Max(child.maxSize.x, max.x);
min.y += child.minSize.y;
max.y += child.maxSize.y;
}
}
else
{
foreach (View child in children)
{
min.x += child.minSize.x;
max.x += child.maxSize.x;
min.y = Mathf.Max(child.minSize.y, min.y);
max.y = Mathf.Max(child.maxSize.y, max.y);
}
}
splitState = null;
SetMinMaxSizes(min, max);
}
public override string ToString()
{
return vertical ? "SplitView (vert)" : "SplitView (horiz)";
}
public bool PerformDrop(EditorWindow dropWindow, DropInfo dropInfo, Vector2 screenPos)
{
var extraInfo = dropInfo.userData as ExtraDropInfo;
var rootWindow = extraInfo.rootWindow;
var edge = extraInfo.edge;
var dropIndex = extraInfo.index;
var dropRect = dropInfo.rect;
var beginning = (edge & ViewEdge.Before) != 0;
var wantsVertical = (edge & ViewEdge.FitsVertical) != 0;
SplitView parentForDrop = null;
if (vertical == wantsVertical || children.Length < 2)
{ // Current view can accommodate desired drop
if (!beginning)
{
if (rootWindow)
dropIndex = children.Length;
else
++dropIndex;
}
parentForDrop = this;
}
else if (rootWindow)
{ // Docking to a window: need to insert a parent
var newParent = ScriptableObject.CreateInstance<SplitView>();
newParent.position = position;
if (window.rootView == this)
window.rootView = newParent;
else // Main window has MainView as its root
parent.AddChild(newParent, parent.IndexOfChild(this));
newParent.AddChild(this);
position = new Rect(Vector2.zero, position.size);
dropIndex = beginning ? 0 : 1;
parentForDrop = newParent;
}
else
{ // Docking in a view: need to insert a child
var newChild = ScriptableObject.CreateInstance<SplitView>();
newChild.AddChild(children[dropIndex]);
AddChild(newChild, dropIndex);
newChild.position = newChild.children[0].position;
newChild.children[0].position = new Rect(Vector2.zero, newChild.position.size);
dropIndex = beginning ? 0 : 1;
parentForDrop = newChild;
}
dropRect.position = dropRect.position - screenPosition.position;
var newDockArea = ScriptableObject.CreateInstance<DockArea>();
parentForDrop.vertical = wantsVertical;
parentForDrop.MakeRoomForRect(dropRect);
parentForDrop.AddChild(newDockArea, dropIndex);
newDockArea.position = dropRect;
DockArea.s_OriginalDragSource.RemoveTab(dropWindow, killIfEmpty: true, sendEvents: false);
dropWindow.m_Parent = newDockArea;
newDockArea.AddTab(dropWindow, sendPaneEvents: false);
Reflow();
RecalcMinMaxAndReflowAll(this);
newDockArea.MakeVistaDWMHappyDance();
dropWindow.Focus();
return true;
}
void MakeRoomForRect(Rect r)
{
Rect[] sources = new Rect[children.Length];
for (int i = 0; i < sources.Length; i++)
sources[i] = children[i].position;
CalcRoomForRect(sources, r);
for (int i = 0; i < sources.Length; i++)
children[i].position = sources[i];
}
void CalcRoomForRect(Rect[] sources, Rect r)
{
float start = vertical ? r.y : r.x;
float end = start + (vertical ? r.height : r.width);
float mid = (start + end) * .5f;
// Find out where we should split
int splitPos;
for (splitPos = 0; splitPos < sources.Length; splitPos++)
{
float midPos = vertical ?
(sources[splitPos].y + sources[splitPos].height * .5f) :
(sources[splitPos].x + sources[splitPos].width * .5f);
if (midPos > mid)
break;
}
float p2 = start;
for (int i = splitPos - 1; i >= 0; i--)
{
if (vertical)
{
sources[i].yMax = p2;
if (sources[i].height < children[i].minSize.y)
p2 = sources[i].yMin = sources[i].yMax - children[i].minSize.y;
else
break;
}
else
{
sources[i].xMax = p2;
if (sources[i].width < children[i].minSize.x)
p2 = sources[i].xMin = sources[i].xMax - children[i].minSize.x;
else
break;
}
}
// if we're below zero, move everything forward
if (p2 < 0)
{
float delta = -p2;
for (int i = 0; i < splitPos - 1; i++)
{
if (vertical)
sources[i].y += delta;
else
sources[i].x += delta;
}
end += delta;
}
p2 = end;
for (int i = splitPos; i < sources.Length; i++)
{
if (vertical)
{
float tmp = sources[i].yMax;
sources[i].yMin = p2;
sources[i].yMax = tmp;
if (sources[i].height < children[i].minSize.y)
p2 = sources[i].yMax = sources[i].yMin + children[i].minSize.y;
else
break;
}
else
{
float tmp = sources[i].xMax;
sources[i].xMin = p2;
sources[i].xMax = tmp;
if (sources[i].width < children[i].minSize.x)
p2 = sources[i].xMax = sources[i].xMin + children[i].minSize.x;
else
break;
}
}
// if we're above max, move everything forward
float limit = vertical ? position.height : position.width;
if (p2 > limit)
{
float delta = limit - p2;
for (int i = 0; i < splitPos - 1; i++)
{
if (vertical)
sources[i].y += delta;
else
sources[i].x += delta;
}
end += delta;
}
}
/// clean up this view & propagate down
public void Cleanup()
{
// if I'm a one-view splitview, I can propagate my child up and kill myself
SplitView sp = parent as SplitView;
if (children.Length == 1 && sp != null)
{
View c = children[0];
c.position = position;
if (parent != null)
{
parent.AddChild(c, parent.IndexOfChild(this));
parent.RemoveChild(this);
if (sp)
sp.Cleanup();
if (!Unsupported.IsDestroyScriptableObject(this))
DestroyImmediate(this);
return;
}
else if (c is SplitView)
{
RemoveChild(c);
window.rootView = c;
c.position = new Rect(0, 0, c.window.position.width, window.position.height);
c.Reflow();
if (!Unsupported.IsDestroyScriptableObject(this))
DestroyImmediate(this);
return;
}
}
if (sp != null)
{
sp.Cleanup();
// the parent might have moved US up and gotten rid of itself
sp = parent as SplitView;
if (sp)
{
// If the parent has the same orientation as us, we can move our views up and kill ourselves
if (sp.vertical == vertical)
{
int idx = new List<View>(parent.children).IndexOf(this);
foreach (View child in children)
{
sp.AddChild(child, idx++);
child.position = new Rect(position.x + child.position.x, position.y + child.position.y, child.position.width, child.position.height);
}
// don't let this fall through to the `children == 0` case because we don't want to be removed
// "nicely." our children have already been merged to the parent with correct positions, so
// there is no need to recalculate sibling dimensions (and may incorrectly resize views that
// have been recursively cleaned up).
sp.RemoveChild(this);
if (!Unsupported.IsDestroyScriptableObject(this))
DestroyImmediate(this, true);
sp.Cleanup();
return;
}
}
}
if (children.Length == 0)
{
if (parent == null && window != null)
{
// if we're root in the window, we'll remove ourselves
window.Close();
}
else
{
ICleanuppable ic = parent as ICleanuppable;
if (parent is SplitView)
{
((SplitView)parent).RemoveChildNice(this);
if (!Unsupported.IsDestroyScriptableObject(this))
DestroyImmediate(this, true);
}
else
{
// This is we're root in the main window.
// We want to stay, but tell the parent (MainWindow) to Cleanup, so he can reduce us to zero-size
/* parent.RemoveChild (this);*/
}
ic?.Cleanup();
}
}
else
{
splitState = null;
Reflow();
}
}
internal const float kGrabDist = 5;
public void SplitGUI(Event evt)
{
if (splitState == null)
SetupSplitter();
SplitView sp = parent as SplitView;
if (sp)
{
Event e = new Event(evt);
e.mousePosition += new Vector2(position.x, position.y);
sp.SplitGUI(e);
if (e.type == EventType.Used)
evt.Use();
}
float pos = vertical ? evt.mousePosition.y : evt.mousePosition.x;
int id = GUIUtility.GetControlID(546739, FocusType.Passive);
controlID = id;
switch (evt.GetTypeForControl(id))
{
case EventType.MouseDown:
if (children.Length != 1) // is there a splitter
{
float cursor = vertical ? children[0].position.y : children[0].position.x;
cursor = GUIUtility.RoundToPixelGrid(cursor);
for (int i = 0; i < children.Length - 1; i++)
{
if (i >= splitState.realSizes.Length)
{
DockArea dock = GUIView.current as DockArea;
string name = "Non-dock area " + GUIView.current.GetType();
if (dock && dock.m_Selected < dock.m_Panes.Count && dock.m_Panes[dock.m_Selected])
name = dock.m_Panes[dock.m_Selected].GetType().ToString();
if (Unsupported.IsDeveloperMode())
Debug.LogError("Real sizes out of bounds for: " + name + " index: " + i + " RealSizes: " + splitState.realSizes.Length);
SetupSplitter();
}
Rect splitterRect = vertical ?
new Rect(children[0].position.x, cursor + splitState.realSizes[i] - splitState.splitSize / 2, children[0].position.width, splitState.splitSize) :
new Rect(cursor + splitState.realSizes[i] - splitState.splitSize / 2, children[0].position.y, splitState.splitSize, children[0].position.height);
if (GUIUtility.HitTest(splitterRect, evt))
{
splitState.splitterInitialOffset = GUIUtility.RoundToPixelGrid(pos);
splitState.currentActiveSplitter = i;
GUIUtility.hotControl = id;
evt.Use();
break;
}
cursor += splitState.realSizes[i];
}
}
break;
case EventType.MouseDrag:
if (children.Length > 1 && (GUIUtility.hotControl == id) && (splitState.currentActiveSplitter >= 0))
{
float diff = GUIUtility.RoundToPixelGrid(pos) - splitState.splitterInitialOffset;
if (Mathf.Abs(diff) > 0.01f)
{
splitState.splitterInitialOffset = GUIUtility.RoundToPixelGrid(pos);
splitState.DoSplitter(splitState.currentActiveSplitter, splitState.currentActiveSplitter + 1, diff);
}
SetupRectsFromSplitter();
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id)
GUIUtility.hotControl = 0;
break;
}
}
protected override void SetPosition(Rect newPos)
{
base.SetPosition(newPos);
Reflow();
}
}
} // namespace
| UnityCsReference/Editor/Mono/GUI/SplitView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/SplitView.cs",
"repo_id": "UnityCsReference",
"token_count": 16416
} | 307 |
// 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.Experimental;
using UnityEditor.IMGUI.Controls;
using UnityEditor.SceneManagement;
using UnityEditor.StyleSheets;
using UnityEditor.VersionControl;
using UnityEditorInternal.VersionControl;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class GameObjectTreeViewGUI : TreeViewGUI
{
enum GameObjectColorType
{
Normal = 0,
Prefab = 1,
BrokenPrefab = 2,
Count = 3,
}
internal static class GameObjectStyles
{
public static GUIStyle disabledLabel = new GUIStyle("PR DisabledLabel");
public static GUIStyle prefabLabel = "PR PrefabLabel";
public static GUIStyle disabledPrefabLabel = "PR DisabledPrefabLabel";
public static GUIStyle brokenPrefabLabel = "PR BrokenPrefabLabel";
public static GUIStyle disabledBrokenPrefabLabel = "PR DisabledBrokenPrefabLabel";
public static GUIStyle optionsButtonStyle = "PaneOptions";
public static GUIStyle sceneHeaderBg = "SceneTopBarBg";
public static SVC<float> sceneHeaderWidth = new SVC<float>("SceneTopBarBg", "border-bottom-width", 1f);
public static GUIStyle rightArrow = "ArrowNavigationRight";
public static GUIStyle overridesHoverHighlight = "HoverHighlight";
public static GUIStyle hoveredItemBackgroundStyle = "WhiteBackground";
public static Color hoveredBackgroundColor =
EditorResources.GetStyle("game-object-tree-view").GetColor("-unity-object-tree-hovered-color");
public static Texture2D sceneIcon = (Texture2D)EditorGUIUtility.IconContent("SceneAsset Icon").image;
static GameObjectStyles()
{
disabledLabel.fixedHeight = 0;
disabledLabel.alignment = TextAnchor.UpperLeft;
disabledLabel.padding = Styles.lineBoldStyle.padding;
}
public static readonly int kSceneHeaderIconsInterval = 2;
}
private float m_PrevScollPos;
private float m_PrevTotalHeight;
internal delegate float OnHeaderGUIDelegate(Rect availableRect, string scenePath);
internal static OnHeaderGUIDelegate OnPostHeaderGUI = null;
// Cache asset paths for managed VCS implementations.
private Dictionary<int, string> m_HierarchyPrefabToAssetPathMap;
// Cache Asset instances for native VCS implementations which have different API.
private Dictionary<int, Asset[]> m_HierarchyPrefabToAssetIDMap;
internal event Action<bool, int, string, string> renameEnded;
private static Dictionary<string, int> s_ActiveParentObjectPerSceneGUID;
internal static void UpdateActiveParentObjectValuesForScene(string sceneGUID, int instanceID)
{
if (instanceID == 0)
s_ActiveParentObjectPerSceneGUID.Remove(sceneGUID);
else
s_ActiveParentObjectPerSceneGUID[sceneGUID] = instanceID;
}
internal void GetActiveParentObjectValuesFromSessionInfo()
{
for (int i = 0; i < SceneManager.sceneCount; i++)
{
var key = SceneManager.GetSceneAt(i).guid;
var id = SceneHierarchy.GetDefaultParentForSession(SceneManager.GetSceneAt(i).guid);
if (id != 0)
s_ActiveParentObjectPerSceneGUID.Add(key, id);
}
}
static bool DetectSceneGuidMismatchInActiveParentState(KeyValuePair<string, int> activeParentObject)
{
var go = EditorUtility.InstanceIDToObject(activeParentObject.Value) as GameObject;
if (go != null && go.scene.guid != activeParentObject.Key)
{
SceneHierarchy.SetDefaultParentForSession(activeParentObject.Key, 0);
return true;
}
return false;
}
internal static void RemoveInvalidActiveParentObjects()
{
var itemsToRemove = s_ActiveParentObjectPerSceneGUID.Where(activeParent => DetectSceneGuidMismatchInActiveParentState(activeParent)).ToArray();
foreach (var itemToRemove in itemsToRemove)
{
SceneHierarchy.UpdateSessionStateInfoAndActiveParentObjectValuesForScene(itemToRemove.Key, 0);
}
}
GameObjectTreeViewDataSource dataSource
{
get { return (GameObjectTreeViewDataSource)m_TreeView.data; }
}
bool showingSearchResults
{
get { return !string.IsNullOrEmpty(dataSource.searchString); }
}
public GameObjectTreeViewGUI(TreeViewController treeView, bool useHorizontalScroll)
: base(treeView, useHorizontalScroll)
{
k_TopRowMargin = 0f;
m_TreeView.enableItemHovering = true;
}
public override void OnInitialize()
{
base.OnInitialize();
SceneVisibilityManager.visibilityChanged += SceneVisibilityManagerOnVisibilityChanged;
dataSource.beforeReloading += SubSceneGUI.FetchSubSceneInfo;
m_PrevScollPos = m_TreeView.state.scrollPos.y;
m_PrevTotalHeight = m_TreeView.GetTotalRect().height;
k_BaseIndent = SceneVisibilityHierarchyGUI.utilityBarWidth;
if (!dataSource.ShouldShowSceneHeaders())
{
k_BaseIndent += indentWidth;// Add an extra indent to match GameObjects under a SceneHeader as this makes room for additional UI.
}
s_ActiveParentObjectPerSceneGUID = new Dictionary<string, int>();
GetActiveParentObjectValuesFromSessionInfo();
m_HierarchyPrefabToAssetPathMap = new Dictionary<int, string>();
m_HierarchyPrefabToAssetIDMap = new Dictionary<int, Asset[]>();
}
private void SceneVisibilityManagerOnVisibilityChanged()
{
m_TreeView.Repaint();
}
public bool DetectUserInput()
{
if (DetectScrollChange())
return true;
if (DetectTotalRectChange())
return true;
if (DetectMouseDownInTreeViewRect())
return true;
return false;
}
bool DetectScrollChange()
{
bool changed = false;
float curScroll = m_TreeView.state.scrollPos.y;
if (!Mathf.Approximately(curScroll, m_PrevScollPos))
changed = true;
m_PrevScollPos = curScroll;
return changed;
}
bool DetectTotalRectChange()
{
bool changed = false;
float curHeight = m_TreeView.GetTotalRect().height;
if (!Mathf.Approximately(curHeight, m_PrevTotalHeight))
changed = true;
m_PrevTotalHeight = curHeight;
return changed;
}
bool DetectMouseDownInTreeViewRect()
{
var evt = Event.current;
var mouseEvent = evt.type == EventType.MouseDown || evt.type == EventType.MouseUp;
var keyboardEvent = evt.type == EventType.KeyDown || evt.type == EventType.KeyUp;
if ((mouseEvent && m_TreeView.GetTotalRect().Contains(evt.mousePosition)) || keyboardEvent)
return true;
return false;
}
bool showingStickyHeaders { get { return SceneManager.sceneCount > 1; } }
void DoStickySceneHeaders()
{
int firstRow, lastRow;
GetFirstAndLastRowVisible(out firstRow, out lastRow);
if (firstRow >= 0 && lastRow > firstRow)
{
float scrollY = m_TreeView.state.scrollPos.y;
if (firstRow == 0 && scrollY <= topRowMargin)
return; // Do nothing when first row is 0 since we do not need any sticky headers overlay
var firstItem = (GameObjectTreeViewItem)m_TreeView.data.GetItem(firstRow);
var nextItem = (GameObjectTreeViewItem)m_TreeView.data.GetItem(firstRow + 1);
bool isFirstItemLastInScene = firstItem.scene != nextItem.scene;
float rowWidth = GUIClip.visibleRect.width;
Rect rect = GetRowRect(firstRow, rowWidth);
// Do not do the sticky header if the scene is at top
if (firstItem.isSceneHeader && Mathf.Approximately(scrollY, rect.y))
return;
// Sticky header is achieved by ensuring the header never moves out of
// scroll and is aligned with last item in scene list if needed
if (!isFirstItemLastInScene)
rect.y = scrollY;
var sceneHeaderItem = dataSource.sceneHeaderItems.FirstOrDefault(p => p.scene == firstItem.scene);
if (sceneHeaderItem != null)
{
rect.y = Mathf.Round(rect.y); // Fix vertical render jittering due to fractional scroll values by rounding to nearest whole pixel
bool selected = m_TreeView.IsItemDragSelectedOrSelected(sceneHeaderItem);
bool focused = m_TreeView.HasFocus();
bool boldFont = sceneHeaderItem.scene == SceneManager.GetActiveScene();
DoItemGUI(rect, firstRow, sceneHeaderItem, selected, focused, boldFont);
if (sceneHeaderItem.scene.isLoaded)
DoStickyHeaderItemFoldout(rect, sceneHeaderItem);
m_TreeView.HandleUnusedMouseEventsForItem(rect, sceneHeaderItem, firstRow);
HandleStickyHeaderContextClick(rect, sceneHeaderItem);
float indent = GetContentIndent(sceneHeaderItem);
Rect indentedRect = new Rect(rect.x + indent, rect.y, rect.width - indent, rect.height);
UserCallbackRowGUI(sceneHeaderItem.id, indentedRect);
}
}
}
void HandleStickyHeaderContextClick(Rect rect, GameObjectTreeViewItem sceneHeaderItem)
{
Event evt = Event.current;
// On OSX manually handle context click for sticky headers here to prevent items beneath the sticky header to also handle the event
if (Application.platform == RuntimePlatform.OSXEditor)
{
bool showContextMenu = (evt.type == EventType.MouseDown && evt.button == 1) || evt.type == EventType.ContextClick; // cmd+left click fires a context click event
if (showContextMenu && rect.Contains(Event.current.mousePosition))
{
evt.Use();
m_TreeView.contextClickItemCallback(sceneHeaderItem.id);
}
}
else if (Application.platform == RuntimePlatform.WindowsEditor)
{
if (evt.type == EventType.MouseDown && evt.button == 1 && rect.Contains(Event.current.mousePosition))
{
// On Windows prevent right mouse down to propagate to items beneath (which will select items below this item)
evt.Use();
}
}
}
void DoStickyHeaderItemFoldout(Rect rect, TreeViewItem item)
{
Rect foldoutRect = new Rect(rect.x + GetFoldoutIndent(item), Mathf.Round(rect.y + customFoldoutYOffset), foldoutStyleWidth, k_LineHeight);
var expanded = m_TreeView.data.IsExpanded(item);
var newExpanded = DoFoldoutButton(foldoutRect, expanded, foldoutStyle);
if (expanded != newExpanded)
{
m_TreeView.ChangeExpandedState(item, newExpanded, Event.current.alt);
m_TreeView.ReloadData();
if (!newExpanded)
{
m_TreeView.Frame(item.id, true, false);
}
// The TreeView was reloaded with new expanded state so we should not continue iterating visible rows.
GUIUtility.ExitGUI();
}
}
public override void BeginRowGUI()
{
if (DetectUserInput())
{
dataSource.EnsureFullyInitialized();
}
base.BeginRowGUI();
// Sticky scene headers. Do non repaint events first to receive input first
if (showingStickyHeaders && Event.current.type != EventType.Repaint)
{
DoStickySceneHeaders();
}
}
public override void EndRowGUI()
{
base.EndRowGUI();
// Sticky scene headers. Do repaint events last to render on top.
if (showingStickyHeaders && Event.current.type == EventType.Repaint)
{
DoStickySceneHeaders();
}
}
public override Rect GetRectForFraming(int row)
{
Rect rect = base.GetRectForFraming(row);
if (showingStickyHeaders && row < m_TreeView.data.rowCount)
{
var item = m_TreeView.data.GetItem(row) as GameObjectTreeViewItem;
if (item != null && !item.isSceneHeader)
{
// For game objects under a sceneheader we create a larger frame rect to ensure row is shown
// beneath the sticky header (headers have same lineheight as rows)
rect.y -= k_LineHeight;
rect.height = 2 * k_LineHeight;
}
}
return rect;
}
//-------------------
// Create and Rename GameObject section
override public bool BeginRename(TreeViewItem item, float delay)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem == null)
return false;
if (goItem.isSceneHeader)
return false;
GameObject gameObject = (GameObject)goItem.objectPPTR;
if ((gameObject.hideFlags & HideFlags.NotEditable) != 0)
{
Debug.LogWarning("Unable to rename a GameObject with HideFlags.NotEditable.");
return false;
}
return base.BeginRename(item, delay);
}
override protected void RenameEnded()
{
bool userAcceptedRename = GetRenameOverlay().userAcceptedRename;
int instanceID = GetRenameOverlay().userData;
string name = string.IsNullOrEmpty(GetRenameOverlay().name) ? GetRenameOverlay().originalName : GetRenameOverlay().name;
string originalname = GetRenameOverlay().originalName;
renameEnded?.Invoke(userAcceptedRename, instanceID, name, originalname);
}
private bool isDragging
{
get
{
return m_TreeView.isDragging ||
(m_TreeView.dragging != null && m_TreeView.dragging.GetDropTargetControlID() != -1);
}
}
override protected void DrawItemBackground(Rect rect, int row, TreeViewItem item, bool selected, bool focused)
{
var goItem = (GameObjectTreeViewItem)item;
if (goItem.isSceneHeader)
{
GUI.Label(rect, GUIContent.none, GameObjectStyles.sceneHeaderBg);
}
else
{
// Don't show indented sub scene header backgrounds when searching (as the texts are not indented here)
if (SubSceneGUI.IsUsingSubScenes() && !showingSearchResults)
{
var gameObject = (GameObject)goItem.objectPPTR;
if (gameObject != null && SubSceneGUI.IsSubSceneHeader(gameObject))
{
SubSceneGUI.DrawSubSceneHeaderBackground(rect, k_BaseIndent, k_IndentWidth, gameObject);
}
}
}
if (m_TreeView.hoveredItem != item)
return;
if (isDragging)
return;
using (new GUI.BackgroundColorScope(GameObjectStyles.hoveredBackgroundColor))
{
GUI.Label(rect, GUIContent.none, GameObjectStyles.hoveredItemBackgroundStyle);
}
}
float m_ContentRectRight;
override protected void DoItemGUI(Rect rect, int row, TreeViewItem item, bool selected, bool focused, bool useBoldFont)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem == null)
return;
EnsureLazyInitialization(goItem); // Needed to ensure item is ready for all ui controls
if (goItem.isSceneHeader)
{
useBoldFont = (goItem.scene == SceneManager.GetActiveScene());
}
base.DoItemGUI(rect, row, item, selected, focused, useBoldFont);
SceneVisibilityHierarchyGUI.DoItemGUI(rect, goItem, selected && !IsRenaming(item.id), m_TreeView.hoveredItem == goItem, focused, isDragging);
}
internal static void UserCallbackRowGUI(int itemID, Rect rect)
{
if (EditorApplication.hierarchyWindowItemOnGUI != null)
{
// Adjust rect for the right aligned column for the prefab isolation button
rect.xMax -=
GameObjectStyles.rightArrow.fixedWidth +
GameObjectStyles.rightArrow.margin.horizontal;
EditorApplication.hierarchyWindowItemOnGUI(itemID, rect);
}
}
private void HandlePrefabInstanceOverrideStatus(GameObjectTreeViewItem goItem, Rect rect, bool selected, bool focused)
{
GameObject go = goItem.objectPPTR as GameObject;
if (!go)
return;
if (PrefabUtility.IsOutermostPrefabInstanceRoot(go) && PrefabUtility.HasPrefabInstanceNonDefaultOverridesOrUnusedOverrides_CachedForUI(go))
{
Rect overridesMarkerRect = new Rect(rect.x + SceneVisibilityHierarchyGUI.utilityBarWidth, rect.y + 1, 2, rect.height - 2);
Color clr = (selected && focused) ? EditorGUI.k_OverrideMarginColorSelected : EditorGUI.k_OverrideMarginColor;
EditorGUI.DrawRect(overridesMarkerRect, clr);
}
}
static GameObject[] GetOutermostPrefabInstancesFromSelection()
{
var gos = new List<GameObject>();
var gameObjects = Selection.gameObjects;
for (int i = 0; i < gameObjects.Length; i++)
{
var go = gameObjects[i];
if (go != null && PrefabUtility.IsPartOfNonAssetPrefabInstance(go) && PrefabUtility.IsOutermostPrefabInstanceRoot(go))
gos.Add(go);
}
return gos.ToArray();
}
protected override void OnAdditionalGUI(Rect rect, int row, TreeViewItem item, bool selected, bool focused)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem == null)
return;
m_ContentRectRight = 0;
if (goItem.isSceneHeader)
{
m_ContentRectRight = DoAdditionalSceneHeaderGUI(goItem, rect);
}
else
{
m_ContentRectRight = PrefabModeButton(goItem, rect);
if (SubSceneGUI.IsUsingSubScenes() && !showingSearchResults)
{
SubSceneGUI.DrawVerticalLine(rect, k_BaseIndent, k_IndentWidth, (GameObject)goItem.objectPPTR);
}
HandlePrefabInstanceOverrideStatus(goItem, rect, selected, focused);
}
if (SceneHierarchy.s_Debug)
GUI.Label(new Rect(rect.xMax - 70, rect.y, 70, rect.height), "" + row + " (" + goItem.id + ")", EditorStyles.boldLabel);
}
protected override Rect GetDropTargetRect(Rect rect)
{
rect.xMin += SceneVisibilityHierarchyGUI.utilityBarWidth;
return rect;
}
protected float DoAdditionalSceneHeaderGUI(GameObjectTreeViewItem goItem, Rect rect)
{
const float margin = 4f;
Rect buttonRect;
if (DoOptionsButton(rect, out buttonRect))
{
// Ensure item is selected before using context menu (menu logic is based on selection)
m_TreeView.SelectionClick(goItem, true);
m_TreeView.contextClickItemCallback(goItem.id);
}
float availableRectLeft = buttonRect.xMin;
if (null != OnPostHeaderGUI)
{
float optionsWidth = (rect.width - buttonRect.x);
float width = (rect.width - optionsWidth - margin);
float x = 0;
float y = rect.y;
float height = rect.height;
Rect availableRect = new Rect(x, y, width, height);
availableRectLeft = Math.Min(availableRectLeft, OnPostHeaderGUI(availableRect, goItem.scene.path));
}
return availableRectLeft;
}
internal static bool DoOptionsButton(Rect rect, out Rect buttonRect)
{
const float optionsButtonWidth = 16f;
const float optionsButtonHeight = 16f;
const float margin = 4f;
buttonRect = new Rect(rect.xMax - optionsButtonWidth - margin, rect.y + (rect.height - optionsButtonHeight) * 0.5f, optionsButtonWidth, rect.height);
if (Event.current.type == EventType.Repaint)
GameObjectStyles.optionsButtonStyle.Draw(buttonRect, false, false, false, false);
// We want larger click area than the button icon
buttonRect.y = rect.y;
buttonRect.height = rect.height;
buttonRect.width = 24f;
return EditorGUI.DropdownButton(buttonRect, GUIContent.none, FocusType.Passive, GUIStyle.none);
}
void EnsureLazyInitialization(GameObjectTreeViewItem item)
{
if (!item.lazyInitializationDone)
{
item.lazyInitializationDone = true;
SetItemIcon(item);
SetItemSelectedIcon(item);
SetItemOverlayIcon(item);
SetPrefabModeButtonVisibility(item);
}
}
void SetItemIcon(GameObjectTreeViewItem item)
{
var go = item.objectPPTR as GameObject;
if (go == null)
{
item.icon = GameObjectStyles.sceneIcon;
}
else
{
if (SubSceneGUI.IsSubSceneHeader(go))
item.icon = GameObjectStyles.sceneIcon;
else
item.icon = PrefabUtility.GetIconForGameObject(go);
}
}
void SetItemSelectedIcon(GameObjectTreeViewItem item)
{
if (item.icon != null)
{
item.selectedIcon = EditorUtility.GetIconInActiveState(item.icon) as Texture2D;
}
}
internal override Texture GetIconForSelectedItem(TreeViewItem item)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem != null)
{
return goItem.selectedIcon;
}
return item.icon;
}
void SetItemOverlayIcon(GameObjectTreeViewItem item)
{
item.overlayIcon = null;
var go = item.objectPPTR as GameObject;
if (go == null)
return;
if (PrefabUtility.IsAddedGameObjectOverride(go))
item.overlayIcon = EditorGUIUtility.LoadIcon("PrefabOverlayAdded Icon");
if (!EditorApplication.isPlaying)
{
var vco = VersionControlManager.activeVersionControlObject;
if (vco != null)
{
if (!m_HierarchyPrefabToAssetPathMap.ContainsKey(item.id))
{
var guid = GetAssetGUID(item);
if (!string.IsNullOrEmpty(guid))
{
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
if (!string.IsNullOrEmpty(assetPath))
m_HierarchyPrefabToAssetPathMap.Add(item.id, assetPath);
}
}
}
else
{
var asset = GetAsset(item);
if (asset != null && !m_HierarchyPrefabToAssetIDMap.ContainsKey(item.id))
{
var metaPath = asset.path.Trim('/') + ".meta";
var metaAsset = Provider.GetAssetByPath(metaPath);
var assets = new[] { asset, metaAsset };
m_HierarchyPrefabToAssetIDMap.Add(item.id, assets);
}
}
}
}
void SetPrefabModeButtonVisibility(GameObjectTreeViewItem item)
{
item.showPrefabModeButton = false;
GameObject go = item.objectPPTR as GameObject;
if (go == null)
return;
if (!PrefabUtility.IsPartOfAnyPrefab(go))
return;
if (!PrefabUtility.IsAnyPrefabInstanceRoot(go))
return;
// Don't show button if prefab asset is missing
if (PrefabUtility.GetPrefabInstanceStatus(go) == PrefabInstanceStatus.Connected)
{
var source = PrefabUtility.GetOriginalSourceOrVariantRoot(go);
if (source == null)
return;
// Don't show buttons for model prefabs but allow buttons for other immutables
if (PrefabUtility.IsPartOfModelPrefab(source))
return;
}
else if (PrefabUtility.GetPrefabInstanceHandle(go) == null)
return;
else
{
var assetPath = PrefabUtility.GetAssetPathOfSourcePrefab(go);
var broken = AssetDatabase.LoadMainAssetAtPath(assetPath) as BrokenPrefabAsset;
if (broken == null || !broken.isPrefabFileValid)
return;
}
item.showPrefabModeButton = true;
}
protected override void OnContentGUI(Rect rect, int row, TreeViewItem item, string label, bool selected, bool focused,
bool useBoldFont, bool isPinging)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem == null)
return;
if (Event.current.type != EventType.Repaint)
return;
EnsureLazyInitialization(goItem); // Needed to ensure icon is initialized if reload happens during DoItemGUI
rect.xMax = m_ContentRectRight;
if (goItem.isSceneHeader)
{
if (goItem.scene.isDirty)
label += "*";
switch (goItem.scene.loadingState)
{
case Scene.LoadingState.NotLoaded:
label += " (not loaded)";
break;
case Scene.LoadingState.Loading:
label += " (is loading)";
break;
case Scene.LoadingState.Unloading:
label += " (is unloading)";
break;
}
// Render disabled if scene is unloaded
using (new EditorGUI.DisabledScope(!goItem.scene.isLoaded))
{
base.OnContentGUI(rect, row, item, label, selected, focused, useBoldFont, isPinging);
}
return;
}
if (!isPinging)
{
// The rect is assumed indented and sized after the content when pinging
rect.xMin += GetContentIndent(item) + extraSpaceBeforeIconAndLabel;
}
int colorCode = goItem.colorCode;
bool renderDisabled = colorCode >= 4;
lineStyle = Styles.lineStyle;
if (SubSceneGUI.IsUsingSubScenes())
useBoldFont = SubSceneGUI.UseBoldFontForGameObject((GameObject)goItem.objectPPTR);
if (useBoldFont)
{
lineStyle = Styles.lineBoldStyle;
}
else
{
GameObjectColorType objectColorType = (GameObjectColorType)(colorCode & 3);
if (objectColorType == GameObjectColorType.Normal)
lineStyle = (renderDisabled) ? GameObjectStyles.disabledLabel : Styles.lineStyle;
else if (objectColorType == GameObjectColorType.Prefab)
lineStyle = (renderDisabled) ? GameObjectStyles.disabledPrefabLabel : GameObjectStyles.prefabLabel;
else if (objectColorType == GameObjectColorType.BrokenPrefab)
lineStyle = (renderDisabled) ? GameObjectStyles.disabledBrokenPrefabLabel : GameObjectStyles.brokenPrefabLabel;
}
var sceneGUID = s_ActiveParentObjectPerSceneGUID.FirstOrDefault(x => x.Value == goItem.id).Key;
if (!string.IsNullOrEmpty(sceneGUID) && (EditorSceneManager.GetActiveScene().guid == sceneGUID || PrefabStageUtility.GetCurrentPrefabStage() != null))
{
lineStyle = Styles.lineBoldStyle;
}
lineStyle.padding.left = 0;
Texture icon = GetEffectiveIcon(goItem, selected, focused);
if (icon != null)
{
Rect iconRect = rect;
iconRect.width = k_IconWidth;
Color col = GUI.color;
if (renderDisabled || (CutBoard.hasCutboardData && CutBoard.IsGameObjectPartOfCutAndPaste((GameObject)goItem.objectPPTR)))
col = new Color(1f, 1f, 1f, 0.5f);
GUI.DrawTexture(iconRect, icon, ScaleMode.ScaleToFit, true, 0, col, 0, 0);
if (goItem.overlayIcon != null)
GUI.DrawTexture(iconRect, goItem.overlayIcon, ScaleMode.ScaleToFit, true, 0, col, 0, 0);
if (!EditorApplication.isPlaying)
{
var vco = VersionControlManager.activeVersionControlObject;
if (vco != null)
{
var extension = vco.GetExtension<IIconOverlayExtension>();
if (extension != null && m_HierarchyPrefabToAssetPathMap.TryGetValue(item.id, out var assetPath))
{
iconRect.x -= 10;
iconRect.width += 7 * 2;
extension.DrawOverlay(assetPath, IconOverlayType.Hierarchy, iconRect);
}
}
else
{
Asset[] assets;
m_HierarchyPrefabToAssetIDMap.TryGetValue(item.id, out assets);
if (assets != null)
{
iconRect.x -= 10;
iconRect.width += 7 * 2;
Overlay.DrawHierarchyOverlay(assets[0], assets[1], iconRect);
}
}
}
rect.xMin += iconTotalPadding + k_IconWidth + k_SpaceBetweenIconAndText;
}
// Draw text
lineStyle.Draw(rect, label, false, false, selected, focused);
}
private Asset GetAsset(GameObjectTreeViewItem item)
{
if (!Provider.isActive)
return null;
var guid = GetAssetGUID(item);
Asset vcAsset = string.IsNullOrEmpty(guid) ? null : Provider.GetAssetByGUID(guid);
return vcAsset;
}
static string GetAssetGUID(GameObjectTreeViewItem item)
{
var go = (GameObject)item.objectPPTR;
if (!go || PrefabUtility.GetNearestPrefabInstanceRoot(go) != go)
return null;
var assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go);
return AssetDatabase.AssetPathToGUID(assetPath);
}
public float PrefabModeButton(GameObjectTreeViewItem item, Rect selectionRect)
{
float contentRectRight = selectionRect.xMax;
if (item.showPrefabModeButton)
{
float yOffset = (selectionRect.height - GameObjectStyles.rightArrow.fixedWidth) / 2;
Rect buttonRect = new Rect(
selectionRect.xMax - GameObjectStyles.rightArrow.fixedWidth - GameObjectStyles.rightArrow.margin.right,
selectionRect.y + yOffset,
GameObjectStyles.rightArrow.fixedWidth,
GameObjectStyles.rightArrow.fixedHeight);
int instanceID = item.id;
GUIContent content = buttonRect.Contains(Event.current.mousePosition) ? PrefabStageUtility.GetPrefabButtonContent(instanceID) : GUIContent.none;
if (GUI.Button(buttonRect, content, GameObjectStyles.rightArrow))
{
GameObject go = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go);
if (string.IsNullOrWhiteSpace(assetPath)) //In case its a broken prefab
assetPath = PrefabUtility.GetAssetPathOfSourcePrefab(go);
Object originalSource = AssetDatabase.LoadMainAssetAtPath(assetPath);
if (originalSource != null)
{
var prefabStageMode = PrefabStageUtility.GetPrefabStageModeFromModifierKeys();
PrefabStageUtility.OpenPrefab(assetPath, go, prefabStageMode, StageNavigationManager.Analytics.ChangeType.EnterViaInstanceHierarchyRightArrow);
}
}
contentRectRight = buttonRect.xMin;
}
return contentRectRight;
}
}
}
| UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewGUI.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 16733
} | 308 |
// 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.AnimatedValues;
using UnityEngine;
using UnityEditorInternal;
using UnityEngine.UIElements;
namespace UnityEditor.IMGUI.Controls
{
/*
Description:
The TreeViewController requires implementations from the following three interfaces:
ITreeViewDataSource: Should handle data fetching and data structure
ITreeViewGUI: Should handle visual representation of TreeView and mouse input on row controls
ITreeViewDragging: Should handle dragging, temp expansion of items, allow/disallow dropping
The TreeViewController handles: Navigation, Item selection and initiates dragging
Important concepts:
1) The Item Tree: the DataSource should create the tree structure of items with parent and children references
2) Rows: the DataSource should be able to provide the visible items; a simple list that will become the rows we render.
3) The root item might not be visible; its up to the data source to deliver a set of visible items from the tree
*/
[System.Serializable]
public class TreeViewState
{
public List<int> selectedIDs { get { return m_SelectedIDs; } set { m_SelectedIDs = value; } }
public int lastClickedID { get { return m_LastClickedID; } set { m_LastClickedID = value; } }
public List<int> expandedIDs { get { return m_ExpandedIDs; } set { m_ExpandedIDs = value; } }
internal RenameOverlay renameOverlay { get { return m_RenameOverlay; } set { m_RenameOverlay = value; } }
public string searchString { get { return m_SearchString; } set { m_SearchString = value; } }
public Vector2 scrollPos;
// Selection state
[SerializeField] private List<int> m_SelectedIDs = new List<int>();
[SerializeField] private int m_LastClickedID; // used for navigation
// Expanded state (assumed sorted)
[SerializeField] private List<int> m_ExpandedIDs = new List<int>();
// Rename and create asset state
[SerializeField] private RenameOverlay m_RenameOverlay = new RenameOverlay();
// Search state (can be used by Datasource to filter tree when reloading)
[SerializeField] private string m_SearchString;
internal virtual void OnAwake()
{
// Clear state that should not survive closing/starting Unity (If TreeViewState is in EditorWindow that are serialized in a layout file)
m_RenameOverlay.Clear();
}
}
internal struct TreeViewSelectState
{
public List<int> selectedIDs;
public int lastClickedID;
public bool keepMultiSelection;
public bool useShiftAsActionKey;
}
internal class TreeViewController
{
public System.Action<int[]> selectionChangedCallback { get; set; } // ids
public System.Action<int> itemSingleClickedCallback { get; set; } // id
public System.Action<int> itemDoubleClickedCallback { get; set; } // id
public System.Action<int[], bool> dragEndedCallback { get; set; } // dragged ids, if null then drag was not allowed, bool == true if dragging tree view items from own treeview, false if drag was started outside
public System.Action<int> contextClickItemCallback { get; set; } // clicked item id
public System.Action contextClickOutsideItemsCallback { get; set; }
public System.Action keyboardInputCallback { get; set; }
public System.Action expandedStateChanged { get; set; }
public System.Action<string> searchChanged { get; set; }
public System.Action<Vector2> scrollChanged { get; set; }
public System.Action<int, Rect> onGUIRowCallback { get; set; } // <id, Rect of row>
internal System.Action<int, Rect> onFoldoutButton { get; set; } // <id, Rect of row>
// Main state
GUIView m_GUIView; // Containing view for this tree: used for checking if we have focus and for requesting repaints
public ITreeViewDataSource data { get; set; } // Data provider for this tree: handles data fetching
public ITreeViewDragging dragging { get; set; } // Handle dragging
public ITreeViewGUI gui { get; set; } // Handles GUI (input and rendering)
public TreeViewState state { get; set; } // State that persists script reloads
public GUIStyle horizontalScrollbarStyle { get; set; }
public GUIStyle verticalScrollbarStyle { get; set; }
public GUIStyle scrollViewStyle { get; set; }
public TreeViewItemExpansionAnimator expansionAnimator { get { return m_ExpansionAnimator; } }
readonly TreeViewItemExpansionAnimator m_ExpansionAnimator = new TreeViewItemExpansionAnimator();
AnimFloat m_FramingAnimFloat;
bool m_StopIteratingItems;
public bool deselectOnUnhandledMouseDown { get; set; }
public bool enableItemHovering { get; set; }
IntegerCache m_DragSelection = new IntegerCache();
IntegerCache m_CachedSelection = new IntegerCache();
struct IntegerCache
{
List<int> m_List;
HashSet<int> m_HashSet;
public bool Contains(int id)
{
if (m_HashSet == null)
return false;
return m_HashSet.Contains(id);
}
public void Set(List<int> list)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (!Equals(list))
{
m_List = new List<int>(list);
m_HashSet = new HashSet<int>(list);
}
}
public List<int> Get()
{
return m_List;
}
public void Clear()
{
if (m_List == null)
return;
m_List.Clear();
m_HashSet.Clear();
}
public bool HasValues()
{
if (m_List == null)
return false;
return m_List.Count > 0;
}
bool Equals(List<int> list)
{
if (m_List == null || list == null)
return false;
int count = m_List.Count;
if (count != list.Count)
return false;
for (int i = 0; i < count; ++i)
{
if (list[i] != m_List[i])
return false;
}
return true;
}
}
bool m_UseScrollView = true; // Internal scrollview can be omitted when e.g mulitple tree views in one scrollview is wanted
bool m_ConsumeKeyDownEvents = true;
bool m_AllowRenameOnMouseUp = true;
internal const string kExpansionAnimationPrefKey = "TreeViewExpansionAnimation";
bool m_UseExpansionAnimation = EditorPrefs.GetBool(kExpansionAnimationPrefKey, true);
public bool useExpansionAnimation { get { return m_UseExpansionAnimation; } set { m_UseExpansionAnimation = value; } }
// Cached values during one event (for convenience)
bool m_GrabKeyboardFocus;
Rect m_TotalRect;
Rect m_VisibleRect;
Rect m_ContentRect;
bool m_HadFocusLastEvent; // Cached from last event for keyboard focus changed event
int m_KeyboardControlID;
const double kSlowSelectTimeout = 0.2;
const float kSpaceForScrollBar = 16f;
public TreeViewItem hoveredItem { get; set; }
public TreeViewController(EditorWindow editorWindow, TreeViewState treeViewState)
{
m_GUIView = editorWindow ? editorWindow.m_Parent : GUIView.current;
state = treeViewState;
}
public void Init(Rect rect, ITreeViewDataSource data, ITreeViewGUI gui, ITreeViewDragging dragging)
{
this.data = data;
this.gui = gui;
this.dragging = dragging;
m_VisibleRect = m_TotalRect = rect; // We initialize the total rect because it might be needed for framing selection when reloading data the first time.
// Allow sub systems to set up delegates etc after treeview references have been set up
data.OnInitialize();
gui.OnInitialize();
if (dragging != null)
dragging.OnInitialize();
expandedStateChanged += ExpandedStateHasChanged;
m_FramingAnimFloat = new AnimFloat(state.scrollPos.y, AnimatedScrollChanged);
}
void ExpandedStateHasChanged()
{
m_StopIteratingItems = true;
}
public bool isSearching
{
get { return !string.IsNullOrEmpty(state.searchString); }
}
public bool isDragging
{
get { return m_DragSelection.HasValues(); }
}
public bool IsDraggingItem(TreeViewItem item)
{
return m_DragSelection.Contains(item.id);
}
public bool showingVerticalScrollBar
{
get { return m_VisibleRect.height > 0 && m_ContentRect.height > m_VisibleRect.height; }
}
public bool showingHorizontalScrollBar
{
get { return m_VisibleRect.width > 0 && m_ContentRect.width > m_VisibleRect.width; }
}
public string searchString
{
get
{
return state.searchString;
}
set
{
if (string.ReferenceEquals(state.searchString, value))
return;
if (state.searchString == value)
return;
state.searchString = value;
data.OnSearchChanged();
if (searchChanged != null)
searchChanged(state.searchString);
}
}
public bool useScrollView
{
get { return m_UseScrollView; }
set { m_UseScrollView = value; }
}
public Rect visibleRect
{
get { return m_VisibleRect; }
}
public bool IsSelected(int id)
{
return state.selectedIDs.Contains(id);
}
public bool HasSelection()
{
return state.selectedIDs.Count > 0;
}
public int[] GetSelection()
{
return state.selectedIDs.ToArray();
}
public int[] GetRowIDs()
{
return (from item in data.GetRows() select item.id).ToArray();
}
public void SetSelection(int[] selectedIDs, bool revealSelectionAndFrameLastSelected)
{
const bool animatedFraming = false;
SetSelection(selectedIDs, revealSelectionAndFrameLastSelected, animatedFraming);
}
public void SetSelection(int[] selectedIDs, bool revealSelectionAndFrameLastSelected, bool animatedFraming)
{
// Keep for debugging
//Debug.Log ("SetSelection: new selection: " + DebugUtils.ListToString(new List<int>(selectedIDs)));
// Init new state
if (selectedIDs.Length > 0)
{
if (revealSelectionAndFrameLastSelected)
{
data.RevealItems(selectedIDs);
}
state.selectedIDs = new List<int>(selectedIDs);
// Ensure that our key navigation is setup
bool hasLastClicked = state.selectedIDs.IndexOf(state.lastClickedID) >= 0;
if (!hasLastClicked)
{
// See if we can find a valid id, we check the last selected (selectedids might contain invalid ids e.g scene objects in project browser and vice versa)
int lastSelectedID = selectedIDs.Last();
if (data.GetRow(lastSelectedID) != -1)
{
state.lastClickedID = lastSelectedID;
hasLastClicked = true;
}
else
state.lastClickedID = 0;
}
if (revealSelectionAndFrameLastSelected && hasLastClicked)
Frame(state.lastClickedID, true, false, animatedFraming);
}
else
{
state.selectedIDs.Clear();
state.lastClickedID = 0;
}
// Should not fire callback since this is called from outside
// NotifyListenersThatSelectionChanged ()
}
public TreeViewItem FindItem(int id)
{
return data.FindItem(id);
}
[System.Obsolete("SetUseScrollView has been deprecated. Use property useScrollView instead.")]
public void SetUseScrollView(bool useScrollView)
{
m_UseScrollView = useScrollView;
}
public void SetConsumeKeyDownEvents(bool consume)
{
m_ConsumeKeyDownEvents = consume;
}
public void Repaint()
{
if (m_GUIView != null)
m_GUIView.Repaint();
}
public void ReloadData()
{
// Do not clear rename data here, we could be reloading due to assembly reload
// and we want to let our rename session survive that
data.ReloadData();
Repaint();
m_StopIteratingItems = true;
}
public bool HasFocus()
{
bool hasKeyFocus = (m_GUIView != null) ? m_GUIView.hasFocus : EditorGUIUtility.HasCurrentWindowKeyFocus();
return hasKeyFocus && (GUIUtility.keyboardControl == m_KeyboardControlID);
}
static internal int GetItemControlID(TreeViewItem item)
{
return ((item != null) ? item.id : 0) + 10000000;
}
public void HandleUnusedMouseEventsForItem(Rect rect, TreeViewItem item, int row)
{
int itemControlID = GetItemControlID(item);
Event evt = Event.current;
switch (evt.GetTypeForControl(itemControlID))
{
case EventType.MouseDown:
if (rect.Contains(Event.current.mousePosition))
{
// Handle mouse down on entire line
if (Event.current.button == 0)
{
// Grab keyboard
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint(); // Ensure repaint so we can show we have keyboard focus
// Let client handle double click
if (Event.current.clickCount == 2)
{
if (itemDoubleClickedCallback != null)
itemDoubleClickedCallback(item.id);
}
else
{
double selectStartTime = Time.realtimeSinceStartup;
var dragSelection = GetNewSelection(item, true, false);
bool dragAbortedBySlowSelect = (Time.realtimeSinceStartup - selectStartTime) > kSlowSelectTimeout;
bool canStartDrag = !dragAbortedBySlowSelect && dragging != null && dragSelection.Count != 0 && dragging.CanStartDrag(item, dragSelection, Event.current.mousePosition);
if (canStartDrag)
{
// Prepare drag and drop delay (we start the drag after a couple of pixels mouse drag: See the case MouseDrag below)
m_DragSelection.Set(dragSelection);
DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), GetItemControlID(item));
delay.mouseDownPosition = Event.current.mousePosition;
}
else
{
// If dragging is not supported or not allowed for the drag selection then handle selection on mouse down
// (when dragging is handled we handle selection on mouse up to e.g allow to drag to object fields in the inspector)
m_DragSelection.Clear();
if (m_AllowRenameOnMouseUp)
m_AllowRenameOnMouseUp = (state.selectedIDs.Count == 1 && state.selectedIDs[0] == item.id); // If first time selection then prevent starting a rename on the following mouse up after this mouse down
SelectionClick(item, false);
// Notify about single click
if (itemSingleClickedCallback != null)
itemSingleClickedCallback(item.id);
}
GUIUtility.hotControl = GetItemControlID(item);
}
evt.Use();
}
else if (Event.current.button == 1)
{
// Right mouse down selects;
bool keepMultiSelection = true;
SelectionClick(item, keepMultiSelection);
}
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == itemControlID && dragging != null && m_DragSelection.HasValues())
{
DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), itemControlID);
if (delay.CanStartDrag() && dragging.CanStartDrag(item, m_DragSelection.Get(), delay.mouseDownPosition))
{
dragging.StartDrag(item, m_DragSelection.Get());
GUIUtility.hotControl = 0;
}
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == itemControlID)
{
// When having the temp dragging selection delay the the selection until mouse up
bool useMouseUpSelection = m_DragSelection.HasValues();
// Clear state before SelectionClick since it can ExitGUI early
GUIUtility.hotControl = 0;
m_DragSelection.Clear();
evt.Use();
// On Mouse up either start name editing or change selection (if not done on mouse down)
if (rect.Contains(evt.mousePosition))
{
Rect renameActivationRect = gui.GetRenameRect(rect, row, item);
List<int> selected = state.selectedIDs;
if (m_AllowRenameOnMouseUp && selected != null && selected.Count == 1 && selected[0] == item.id && renameActivationRect.Contains(evt.mousePosition) && !EditorGUIUtility.HasHolddownKeyModifiers(evt))
{
BeginNameEditing(0.5f);
}
else if (useMouseUpSelection)
{
SelectionClick(item, false);
// Notify about single click
if (itemSingleClickedCallback != null)
itemSingleClickedCallback(item.id);
}
}
}
break;
case EventType.DragUpdated:
case EventType.DragPerform:
{
//bool firstItem = row == 0;
if (dragging != null && dragging.DragElement(item, rect, row))
GUIUtility.hotControl = 0;
}
break;
case EventType.ContextClick:
if (rect.Contains(evt.mousePosition))
{
// Do not use the event so the client can react to the context click (here we just handled the treeview selection)
if (contextClickItemCallback != null)
contextClickItemCallback(item.id);
}
break;
}
}
public void GrabKeyboardFocus()
{
m_GrabKeyboardFocus = true;
}
public void NotifyListenersThatSelectionChanged()
{
if (selectionChangedCallback != null)
selectionChangedCallback(state.selectedIDs.ToArray());
}
public void NotifyListenersThatDragEnded(int[] draggedIDs, bool draggedItemsFromOwnTreeView)
{
if (dragEndedCallback != null)
dragEndedCallback(draggedIDs, draggedItemsFromOwnTreeView);
}
public Vector2 GetContentSize()
{
return gui.GetTotalSize();
}
public Rect GetTotalRect()
{
return m_TotalRect;
}
public void SetTotalRect(Rect rect)
{
m_TotalRect = rect;
}
public bool IsItemDragSelectedOrSelected(TreeViewItem item)
{
return m_DragSelection.HasValues() ? m_DragSelection.Contains(item.id) : m_CachedSelection.Contains(item.id);
}
public bool animatingExpansion { get { return m_UseExpansionAnimation && m_ExpansionAnimator.isAnimating; } }
void DoItemGUI(TreeViewItem item, int row, float rowWidth, bool hasFocus)
{
// Check valid row
if (row < 0 || row >= data.rowCount)
{
Debug.LogError("Invalid. Org row: " + (row) + " Num rows " + data.rowCount);
return;
}
bool selected = IsItemDragSelectedOrSelected(item);
Rect rowRect = gui.GetRowRect(row, rowWidth);
// 1. Before row GUI
if (animatingExpansion)
rowRect = m_ExpansionAnimator.OnBeginRowGUI(row, rowRect);
// 2. Do row GUI
if (animatingExpansion)
m_ExpansionAnimator.OnRowGUI(row);
gui.OnRowGUI(rowRect, item, row, selected, hasFocus);
// 3. Draw extra gui callbacks
if (onGUIRowCallback != null)
{
float indent = gui.GetContentIndent(item);
Rect indentedRect = new Rect(rowRect.x + indent, rowRect.y, rowRect.width - indent, rowRect.height);
onGUIRowCallback(item.id, indentedRect);
}
// 4. After row GUI
if (animatingExpansion)
m_ExpansionAnimator.OnEndRowGUI(row);
HandleUnusedMouseEventsForItem(rowRect, item, row);
}
public void OnGUI(Rect rect, int keyboardControlID)
{
m_KeyboardControlID = keyboardControlID;
Event evt = Event.current;
if (evt.type == EventType.Repaint)
{
m_TotalRect = rect;
m_CachedSelection.Set(state.selectedIDs);
}
m_GUIView = GUIView.current;
// End rename if the window do not have focus
if (m_GUIView != null && !m_GUIView.hasFocus && state.renameOverlay.IsRenaming())
{
EndNameEditing(true);
}
// Grab keyboard focus if requested
if (m_GrabKeyboardFocus)
{
m_GrabKeyboardFocus = false;
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint(); // Ensure repaint so we can show we have keyboard focus
}
bool isMouseDownInTotalRect = evt.type == EventType.MouseDown && m_TotalRect.Contains(evt.mousePosition);
if (isMouseDownInTotalRect)
{
m_AllowRenameOnMouseUp = true; // reset value (can be changed later in this event if the TreeView gets focus)
}
// Might change expanded state so call before InitIfNeeded (delayed collapse until animation is done)
if (animatingExpansion)
m_ExpansionAnimator.OnBeforeAllRowsGUI();
data.InitIfNeeded();
// Calc content size
Vector2 contentSize = gui.GetTotalSize();
m_ContentRect = new Rect(0, 0, contentSize.x, contentSize.y);
if (m_UseScrollView)
{
state.scrollPos = GUI.BeginScrollView(m_TotalRect, state.scrollPos, m_ContentRect, false, false,
horizontalScrollbarStyle != null ? horizontalScrollbarStyle : GUI.skin.horizontalScrollbar,
verticalScrollbarStyle != null ? verticalScrollbarStyle : GUI.skin.verticalScrollbar, scrollViewStyle != null ? scrollViewStyle : EditorStyles.scrollViewAlt);
}
else
GUI.BeginClip(m_TotalRect);
if (evt.type == EventType.Repaint)
{
if (m_UseScrollView)
{
m_VisibleRect = GUI.GetTopScrollView().visibleRect;
}
else
{
// We may be inside of a scroll view.
var scrollView = GUI.GetTopScrollView();
if (scrollView != null)
{
// Calculate the visible area of the TreeView inside of the ScrollView taking into account
// that the TreeView may not be contained within the whole ScrollView area.
state.scrollPos = Vector2.Max(Vector2.zero, scrollView.scrollPosition - m_TotalRect.min - scrollView.position.min);
m_VisibleRect = scrollView.visibleRect;
m_VisibleRect.size = Vector2.Max(Vector2.zero, Vector2.Min(m_VisibleRect.size, (m_TotalRect.size - state.scrollPos)));
}
else
{
// If this is contained withing something from UI Toolkit (e.g. the Inspector window), the scroll
// will be controlled by UI Toolkit itself so we need to make sure to only show what we need to
// show, otherwise things can become really slow.
var container = UIElementsUtility.GetCurrentIMGUIContainer();
var uiScrollView = container?.GetFirstAncestorOfType<ScrollView>();
if (uiScrollView != null)
{
// We use the viewport of the UI Toolkit scroll view to calculate the visible area.
var viewport = uiScrollView.Q("unity-content-viewport");
var viewportWorldBound = viewport.worldBound;
var viewportRectWorld = GUIClip.Unclip(viewportWorldBound);
var treeViewRectWindow = GUIClip.UnclipToWindow(m_TotalRect);
float visibleHeight = (viewportRectWorld.y + viewportRectWorld.height) - treeViewRectWindow.y;
float visibleWidth = (viewportRectWorld.x + viewportRectWorld.width) - treeViewRectWindow.x;
float scrollPosY = 0f, scrollPosX = 0f;
if (visibleHeight > viewportRectWorld.height)
{
visibleHeight = viewportRectWorld.height;
scrollPosY = viewportRectWorld.y - treeViewRectWindow.y;
}
if (visibleWidth > viewportRectWorld.width)
{
visibleWidth = viewportRectWorld.width;
scrollPosX = viewportRectWorld.x - treeViewRectWindow.x;
}
if (scrollPosX == 0 && scrollPosY == 0)
{
// Avoids newing a Vector2 if we don't need a scroll position.
state.scrollPos = Vector2.zero;
}
else
{
state.scrollPos = new Vector2(scrollPosX, scrollPosY);
}
m_VisibleRect = new Rect(0f, 0f, visibleWidth, visibleHeight);
}
else
{
m_VisibleRect = m_TotalRect;
}
}
}
}
gui.BeginRowGUI();
// Iterate visible items
int firstRow, lastRow;
gui.GetFirstAndLastRowVisible(out firstRow, out lastRow);
if (lastRow >= 0)
{
int numVisibleRows = lastRow - firstRow + 1;
float rowWidth = Mathf.Max(GUIClip.visibleRect.width, m_ContentRect.width);
IterateVisibleItems(firstRow, numVisibleRows, rowWidth, HasFocus());
}
// Call before gui.EndRowGUI() so stuff we render in EndRowGUI does not end up
// in the the animation clip rect
if (animatingExpansion)
m_ExpansionAnimator.OnAfterAllRowsGUI();
gui.EndRowGUI();
// Keep inside clip region so callbacks that might want to get
// rects of rows have correct context.
KeyboardGUI();
if (m_UseScrollView)
GUI.EndScrollView(showingVerticalScrollBar);
else
GUI.EndClip();
HandleUnusedEvents();
// Call after iterating rows since selecting a row takes keyboard focus
HandleTreeViewGotFocus(isMouseDownInTotalRect);
// Prevent controlID inconsistency for the controls following this tree view: We use the hint parameter of GetControlID to
// fast forward to a fixed entry in the id list so the following controls always start from there regardless of the rows that have been
// culled.
GUIUtility.GetControlID(33243602, FocusType.Passive);
if (Event.current.type == EventType.MouseLeaveWindow)
hoveredItem = null;
}
void HandleTreeViewGotFocus(bool isMouseDownInTotalRect)
{
if (Event.current.type == EventType.Layout)
return;
// Detect if TreeView got keyboard focus (ignore layout event which gets fired infront of mousedown)
bool hasFocus = HasFocus();
if (hasFocus != m_HadFocusLastEvent)
{
m_HadFocusLastEvent = hasFocus;
if (hasFocus && isMouseDownInTotalRect)
{
// If we got focus this event by mouse down then we do not want to begin renaming
// if clicking on an already selected item in the up coming MouseUp event.
m_AllowRenameOnMouseUp = false;
}
}
}
void IterateVisibleItems(int firstRow, int numVisibleRows, float rowWidth, bool hasFocus)
{
// We stop iterating items if datasource state changes while iterating its items.
// This can happen e.g when dragging items or items are expanding/collapsing.
m_StopIteratingItems = false;
TreeViewItem currentHoveredItem = null;
int rowOffset = 0;
for (int i = 0; i < numVisibleRows; ++i)
{
int row = firstRow + i;
if (animatingExpansion)
{
// If we are animating expansion/collapsing then ensure items
// that are culled by the animation clip rect gets 'converted' into
// items after the expanding/collapsing items. When no more items can get culled
// then keep adding the offset (to not handle already handled items).
int endAnimRow = m_ExpansionAnimator.endRow;
if (m_ExpansionAnimator.CullRow(row, gui))
{
rowOffset++;
row = endAnimRow + rowOffset;
}
else
{
row += rowOffset;
}
// Ensure row is still valid after adding the rowOffset?
if (row >= data.rowCount)
{
continue;
}
}
else
{
// When not animating cull rows outside scroll rect
float screenSpaceRowY = gui.GetRowRect(row, rowWidth).y - state.scrollPos.y;
if (screenSpaceRowY > m_TotalRect.height)
{
continue;
}
}
if (enableItemHovering)
{
Rect rowRect = gui.GetRowRect(row, showingVerticalScrollBar ? rowWidth - kSpaceForScrollBar : rowWidth);
if (rowRect.Contains(Event.current.mousePosition) && GUIView.mouseOverView == GUIView.current)
currentHoveredItem = data.GetItem(row);
m_GUIView.MarkHotRegion(GUIClip.UnclipToWindow(rowRect));
}
// Item GUI
// Note that DoItemGUI() needs to be called right before checking m_StopIteratingItems since
// UI in the current row can issue a reload of the TreeView data
DoItemGUI(data.GetItem(row), row, rowWidth, hasFocus);
if (m_StopIteratingItems)
break;
}
hoveredItem = currentHoveredItem;
}
private void ExpansionAnimationEnded(TreeViewAnimationInput setup)
{
// When collapsing we delay the actual collapse until the animation is done
if (!setup.expanding)
{
ChangeExpandedState(setup.item, false, setup.includeChildren);
}
}
float GetAnimationDuration(float height)
{
// Speed up animation linearly for heights below kThreshold.
// We have found from usability testing that for smaller height changes (e.g 3-4 rows)
// we want a faster animation
const float kThreshold = 60f;
const float kMaxDuration = 0.07f;
return (height > kThreshold) ? kMaxDuration : (height * kMaxDuration / kThreshold);
}
public void UserInputChangedExpandedState(TreeViewItem item, int row, bool expand)
{
var includeChildren = Event.current.alt;
if (useExpansionAnimation)
{
// We need to expand prior to starting animation so we have the expanded state ready
if (expand)
ChangeExpandedState(item, true, includeChildren);
int rowStart = row + 1;
int rowEnd = GetLastChildRowUnder(row);
float rowWidth = GUIClip.visibleRect.width;
Rect allRowsRect = GetRectForRows(rowStart, rowEnd, rowWidth);
float duration = GetAnimationDuration(allRowsRect.height);
var input = new TreeViewAnimationInput
{
animationDuration = duration,
startRow = rowStart,
endRow = rowEnd,
startRowRect = gui.GetRowRect(rowStart, rowWidth),
rowsRect = allRowsRect,
expanding = expand,
includeChildren = includeChildren,
animationEnded = ExpansionAnimationEnded,
item = item,
treeView = this
};
expansionAnimator.BeginAnimating(input);
}
else
{
ChangeExpandedState(item, expand, includeChildren);
}
}
internal void ChangeExpandedState(TreeViewItem item, bool expand, bool includeChildren)
{
if (includeChildren)
data.SetExpandedWithChildren(item, expand);
else
data.SetExpanded(item, expand);
}
int GetLastChildRowUnder(int row)
{
var rows = data.GetRows();
int rowDepth = rows[row].depth;
for (int i = row + 1; i < rows.Count; ++i)
if (rows[i].depth <= rowDepth)
return i - 1;
return rows.Count - 1; // end row
}
protected virtual Rect GetRectForRows(int startRow, int endRow, float rowWidth)
{
Rect startRect = gui.GetRowRect(startRow, rowWidth);
Rect endRect = gui.GetRowRect(endRow, rowWidth);
return new Rect(startRect.x, startRect.y, rowWidth, endRect.yMax - startRect.yMin);
}
void HandleUnusedEvents()
{
switch (Event.current.type)
{
case EventType.DragUpdated:
if (dragging != null && m_TotalRect.Contains(Event.current.mousePosition))
{
dragging.DragElement(null, new Rect(), -1);
Repaint();
Event.current.Use();
}
break;
case EventType.DragPerform:
if (dragging != null && m_TotalRect.Contains(Event.current.mousePosition))
{
m_DragSelection.Clear();
dragging.DragElement(null, new Rect(), -1);
Repaint();
Event.current.Use();
}
break;
case EventType.DragExited:
if (dragging != null)
{
m_DragSelection.Clear();
dragging.DragCleanup(true);
Repaint();
}
break;
case EventType.MouseDown:
bool containsMouse = m_TotalRect.Contains(Event.current.mousePosition);
if (containsMouse)
{
GUIUtility.keyboardControl = m_KeyboardControlID;
Repaint();
}
if (deselectOnUnhandledMouseDown && containsMouse && Event.current.button == 0 && state.selectedIDs.Count > 0)
{
SetSelection(new int[0], false);
NotifyListenersThatSelectionChanged();
}
break;
case EventType.ContextClick:
if (m_TotalRect.Contains(Event.current.mousePosition))
{
if (contextClickOutsideItemsCallback != null)
contextClickOutsideItemsCallback();
}
break;
}
}
public void OnEvent()
{
state.renameOverlay.OnEvent();
}
public bool BeginNameEditing(float delay)
{
// No items selected for rename
if (state.selectedIDs.Count == 0)
return false;
var visibleItems = data.GetRows();
TreeViewItem visibleAndSelectedItem = null;
foreach (int id in state.selectedIDs)
{
TreeViewItem item = visibleItems.FirstOrDefault(i => i.id == id);
if (visibleAndSelectedItem == null)
visibleAndSelectedItem = item;
else if (item != null)
return false; // Don't allow rename if more than one item is both visible and selected
}
if (visibleAndSelectedItem != null && data.IsRenamingItemAllowed(visibleAndSelectedItem))
return gui.BeginRename(visibleAndSelectedItem, delay);
return false;
}
// Let client end renaming from outside
public void EndNameEditing(bool acceptChanges)
{
if (state.renameOverlay.IsRenaming())
{
state.renameOverlay.EndRename(acceptChanges);
gui.EndRename();
}
}
TreeViewItem GetItemAndRowIndex(int id, out int row)
{
row = data.GetRow(id);
if (row == -1)
return null;
return data.GetItem(row);
}
void HandleFastCollapse(TreeViewItem item, int row)
{
if (item.depth == 0)
{
// At depth 0 traverse upwards until a parent is found and select that item
for (int i = row - 1; i >= 0; --i)
{
if (data.GetItem(i).hasChildren)
{
OffsetSelection(i - row);
return;
}
}
}
else if (item.depth > 0)
{
// Traverse upwards until parent of item is found and select that parent (users want this behavior)
for (int i = row - 1; i >= 0; --i)
{
if (data.GetItem(i).depth < item.depth)
{
OffsetSelection(i - row);
return;
}
}
}
}
void HandleFastExpand(TreeViewItem item, int row)
{
int rowCount = data.rowCount;
// Traverse downwards until a parent is found and select that parent
for (int i = row + 1; i < rowCount; ++i)
{
if (data.GetItem(i).hasChildren)
{
OffsetSelection(i - row);
break;
}
}
}
private void ChangeFolding(int[] ids, bool expand)
{
// Handle folding of single item and multiple items separately
// Animation is only supported for folding of single item
if (ids.Length == 1)
ChangeFoldingForSingleItem(ids[0], expand);
else if (ids.Length > 1)
ChangeFoldingForMultipleItems(ids, expand);
}
private void ChangeFoldingForSingleItem(int id, bool expand)
{
// Skip any ongoing animation first because it could affect the row count.
// I.e. if the item to be collapsed is in a row that no longer exists after the animation is done and the rows refreshed in InitIfNeeded, skiping the animation later would cause an IndexOufOfBounds in HandleFastCollapse
// if no animation is happening, this is just a null check so moving it later for performance reasons makes little sense.
expansionAnimator.SkipAnimating();
int row;
TreeViewItem item = GetItemAndRowIndex(id, out row);
if (item != null)
{
if (data.IsExpandable(item) && data.IsExpanded(item) != expand)
UserInputChangedExpandedState(item, row, expand);
else
{
if (expand)
HandleFastExpand(item, row); // Move selection to next parent
else
HandleFastCollapse(item, row); // Move selection to parent
}
}
}
private void ChangeFoldingForMultipleItems(int[] ids, bool expand)
{
// Collect items that should be expanded/collapsed
var parents = new HashSet<int>();
foreach (var id in ids)
{
int row;
TreeViewItem item = GetItemAndRowIndex(id, out row);
if (item != null)
{
if (data.IsExpandable(item) && data.IsExpanded(item) != expand)
parents.Add(id);
}
}
// Expand/collapse all collected items
if (Event.current.alt)
{
// Also expand/collapse children of selected items
foreach (var id in parents)
data.SetExpandedWithChildren(id, expand);
}
else
{
var expandedIDs = new HashSet<int>(data.GetExpandedIDs());
if (expand)
expandedIDs.UnionWith(parents);
else
expandedIDs.ExceptWith(parents);
data.SetExpandedIDs(expandedIDs.ToArray());
}
}
void KeyboardGUI()
{
if (m_KeyboardControlID != GUIUtility.keyboardControl || !GUI.enabled)
return;
// Let client handle keyboard first
if (keyboardInputCallback != null)
keyboardInputCallback();
if (!m_ConsumeKeyDownEvents)
return;
if (Event.current.type == EventType.KeyDown)
{
switch (Event.current.keyCode)
{
// Fold in
case KeyCode.LeftArrow:
ChangeFolding(state.selectedIDs.ToArray(), false);
Event.current.Use();
break;
// Fold out
case KeyCode.RightArrow:
ChangeFolding(state.selectedIDs.ToArray(), true);
Event.current.Use();
break;
case KeyCode.UpArrow:
Event.current.Use();
OffsetSelection(-1);
break;
// Select next or first
case KeyCode.DownArrow:
Event.current.Use();
OffsetSelection(1);
break;
case KeyCode.Home:
Event.current.Use();
OffsetSelection(-1000000);
break;
case KeyCode.End:
Event.current.Use();
OffsetSelection(1000000);
break;
case KeyCode.PageUp:
{
Event.current.Use();
TreeViewItem lastClickedItem = data.FindItem(state.lastClickedID);
if (lastClickedItem != null)
{
int numRowsPageUp = gui.GetNumRowsOnPageUpDown(lastClickedItem, true, m_TotalRect.height);
OffsetSelection(-numRowsPageUp);
}
}
break;
case KeyCode.PageDown:
{
Event.current.Use();
TreeViewItem lastClickedItem = data.FindItem(state.lastClickedID);
if (lastClickedItem != null)
{
int numRowsPageDown = gui.GetNumRowsOnPageUpDown(lastClickedItem, true, m_TotalRect.height);
OffsetSelection(numRowsPageDown);
}
}
break;
case KeyCode.Return:
case KeyCode.KeypadEnter:
if (Application.platform == RuntimePlatform.OSXEditor)
if (BeginNameEditing(0f))
Event.current.Use();
break;
case KeyCode.F2:
if (Application.platform != RuntimePlatform.OSXEditor)
if (BeginNameEditing(0f))
Event.current.Use();
break;
default:
if (Event.current.keyCode > KeyCode.A && Event.current.keyCode < KeyCode.Z)
{
// TODO: jump to folder with char?
}
break;
}
}
}
static internal int GetIndexOfID(IList<TreeViewItem> items, int id)
{
for (int i = 0; i < items.Count; ++i)
if (items[i].id == id)
return i;
return -1;
}
public bool IsLastClickedPartOfRows()
{
var visibleRows = data.GetRows();
if (visibleRows.Count == 0)
return false;
return GetIndexOfID(visibleRows, state.lastClickedID) >= 0;
}
public void OffsetSelection(int offset)
{
expansionAnimator.SkipAnimating();
var visibleRows = data.GetRows();
if (visibleRows.Count == 0)
return;
Event.current?.Use();
int index = GetIndexOfID(visibleRows, state.lastClickedID);
int newIndex = Mathf.Clamp(index + offset, 0, visibleRows.Count - 1);
EnsureRowIsVisible(newIndex, false);
SelectionByKey(visibleRows[newIndex]);
}
public Func<TreeViewItem, bool, bool, List<int>> getNewSelectionOverride { private get; set; }
// Returns list of selected ids
List<int> GetNewSelection(TreeViewItem clickedItem, bool keepMultiSelection, bool useShiftAsActionKey)
{
if (getNewSelectionOverride != null)
return getNewSelectionOverride(clickedItem, keepMultiSelection, useShiftAsActionKey);
var selectState = new TreeViewSelectState() {
selectedIDs = state.selectedIDs,
lastClickedID = state.lastClickedID,
keepMultiSelection = keepMultiSelection,
useShiftAsActionKey = useShiftAsActionKey
};
return data.GetNewSelection(clickedItem, selectState);
}
void SelectionByKey(TreeViewItem itemSelected)
{
var newSelection = GetNewSelection(itemSelected, false, true);
NewSelectionFromUserInteraction(newSelection, itemSelected.id);
}
public void SelectionClick(TreeViewItem itemClicked, bool keepMultiSelection)
{
var newSelection = GetNewSelection(itemClicked, keepMultiSelection, false);
NewSelectionFromUserInteraction(newSelection, itemClicked != null ? itemClicked.id : 0);
}
void NewSelectionFromUserInteraction(List<int> newSelection, int itemID)
{
state.lastClickedID = itemID;
bool selectionChanged = !state.selectedIDs.SequenceEqual(newSelection);
if (selectionChanged)
{
state.selectedIDs = newSelection;
NotifyListenersThatSelectionChanged();
Repaint();
}
}
public void RemoveSelection()
{
if (state.selectedIDs.Count > 0)
{
state.selectedIDs.Clear();
NotifyListenersThatSelectionChanged();
}
}
float GetTopPixelOfRow(int row)
{
return gui.GetRowRect(row, 1).y;
}
void EnsureRowIsVisible(int row, bool animated)
{
// We don't want to change the scroll to make the row visible,
// if it's disabled: Causes content to be moved/rendered out of bounds.
if (!m_UseScrollView)
return;
if (row >= 0)
{
// Adjusting for when the horizontal scrollbar is being shown. Before the TreeView has repainted
// once the m_VisibleRect is not valid, then we use m_TotalRect which is passed when initialized
float visibleHeight = m_VisibleRect.height > 0 ? m_VisibleRect.height : m_TotalRect.height;
Rect frameRect = gui.GetRectForFraming(row);
float scrollTop = frameRect.y;
float scrollBottom = frameRect.yMax - visibleHeight;
if (state.scrollPos.y < scrollBottom)
ChangeScrollValue(scrollBottom, animated);
else if (state.scrollPos.y > scrollTop)
ChangeScrollValue(scrollTop, animated);
}
}
void AnimatedScrollChanged()
{
Repaint();
state.scrollPos.y = m_FramingAnimFloat.value;
}
void ChangeScrollValue(float targetScrollPos, bool animated)
{
if (m_UseExpansionAnimation && animated)
{
m_FramingAnimFloat.value = state.scrollPos.y;
m_FramingAnimFloat.target = targetScrollPos;
m_FramingAnimFloat.speed = 3f;
}
else
{
state.scrollPos.y = targetScrollPos;
}
}
public void Frame(int id, bool frame, bool ping)
{
const bool animated = false;
Frame(id, frame, ping, animated);
}
public void Frame(int id, bool frame, bool ping, bool animated)
{
float topPixelOfRow = -1f;
if (frame)
{
data.RevealItem(id);
int row = data.GetRow(id);
if (row >= 0)
{
topPixelOfRow = GetTopPixelOfRow(row);
EnsureRowIsVisible(row, animated);
}
}
if (ping)
{
int row = data.GetRow(id);
if (topPixelOfRow == -1f)
{
// Was not framed first so we need to calc it here
if (row >= 0)
topPixelOfRow = GetTopPixelOfRow(row);
}
if (topPixelOfRow >= 0f && row >= 0 && row < data.rowCount)
{
TreeViewItem item = data.GetRows()[row];
float scrollBarOffset = GetContentSize().y > m_TotalRect.height ? -kSpaceForScrollBar : 0f;
gui.BeginPingItem(item, topPixelOfRow, m_TotalRect.width + scrollBarOffset);
}
}
}
public void EndPing()
{
gui.EndPingItem();
}
// Item holding most basic data for TreeView event handling
// Extend this class to hold your specific tree data and make your DataSource
// create items of your type. During e.g OnGUI you can the cast Item to your own type when needed.
// Hidden items (under collapsed items) are added last
public List<int> SortIDsInVisiblityOrder(IList<int> ids)
{
if (ids.Count <= 1)
return ids.ToList(); // no sorting needed
var visibleRows = data.GetRows();
List<int> sorted = new List<int>();
for (int i = 0; i < visibleRows.Count; ++i)
{
int id = visibleRows[i].id;
for (int j = 0; j < ids.Count; ++j)
{
if (ids[j] == id)
{
sorted.Add(id);
break;
}
}
}
// Some rows with selection are collapsed (not visible) so add those to the end
if (ids.Count != sorted.Count)
{
sorted.AddRange(ids.Except(sorted));
if (ids.Count != sorted.Count)
Debug.LogError("SortIDsInVisiblityOrder failed: " + ids.Count + " != " + sorted.Count);
}
return sorted;
}
}
} // end namespace UnityEditor
| UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewController.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewController.cs",
"repo_id": "UnityCsReference",
"token_count": 29482
} | 309 |
// 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.IMGUI.Controls
{
internal static class TreeViewUtility
{
internal static void SetParentAndChildrenForItems(IList<TreeViewItem> rows, TreeViewItem root)
{
SetChildParentReferences(rows, root);
}
// For setting depths values based on children state of the items
internal static void SetDepthValuesForItems(TreeViewItem root)
{
if (root == null)
throw new ArgumentNullException("root", "The root is null");
Stack<TreeViewItem> stack = new Stack<TreeViewItem>();
stack.Push(root);
while (stack.Count > 0)
{
TreeViewItem current = stack.Pop();
if (current.children != null)
{
foreach (var child in current.children)
{
if (child != null)
{
child.depth = current.depth + 1;
stack.Push(child);
}
}
}
}
}
internal static List<TreeViewItem> FindItemsInList(IEnumerable<int> itemIDs, IList<TreeViewItem> treeViewItems)
{
return (from x in treeViewItems where itemIDs.Contains(x.id) select x).ToList();
}
internal static TreeViewItem FindItemInList<T>(int id, IList<T> treeViewItems) where T : TreeViewItem
{
return treeViewItems.FirstOrDefault(t => t.id == id);
}
// Assumes full tree
internal static TreeViewItem FindItem(int id, TreeViewItem searchFromThisItem)
{
return FindItemRecursive(id, searchFromThisItem);
}
static TreeViewItem FindItemRecursive(int id, TreeViewItem item)
{
if (item == null)
return null;
if (item.id == id)
return item;
if (!item.hasChildren)
return null;
foreach (TreeViewItem child in item.children)
{
TreeViewItem result = FindItemRecursive(id, child);
if (result != null)
return result;
}
return null;
}
// Assumes full tree
internal static void GetParentsAboveItem(TreeViewItem fromItem, HashSet<int> parentsAbove)
{
if (fromItem == null)
throw new ArgumentNullException("fromItem");
TreeViewItem parent = fromItem.parent;
while (parent != null)
{
parentsAbove.Add(parent.id);
parent = parent.parent;
}
}
// Assumes full tree
internal static void GetParentsBelowItem(TreeViewItem fromItem, HashSet<int> parentsBelow)
{
if (fromItem == null)
throw new ArgumentNullException("fromItem");
Stack<TreeViewItem> stack = new Stack<TreeViewItem>();
stack.Push(fromItem);
while (stack.Count > 0)
{
TreeViewItem current = stack.Pop();
if (current.hasChildren)
{
parentsBelow.Add(current.id);
if (LazyTreeViewDataSource.IsChildListForACollapsedParent(current.children))
throw new InvalidOperationException("Invalid tree for finding descendants: Ensure a complete tree when using this utillity method.");
foreach (var foo in current.children)
{
stack.Push(foo);
}
}
}
}
internal static void DebugPrintToEditorLogRecursive(TreeViewItem item)
{
if (item == null)
return;
System.Console.WriteLine(new System.String(' ', item.depth * 3) + item.displayName);
if (!item.hasChildren)
return;
foreach (TreeViewItem child in item.children)
{
DebugPrintToEditorLogRecursive(child);
}
}
// Setup child and parent references based on the depth of the tree view items in 'visibleItems'
internal static void SetChildParentReferences(IList<TreeViewItem> visibleItems, TreeViewItem root)
{
for (int i = 0; i < visibleItems.Count; i++)
visibleItems[i].parent = null;
// Set child and parent references using depth info
int rootChildCount = 0;
for (int i = 0; i < visibleItems.Count; i++)
{
SetChildParentReferences(i, visibleItems);
if (visibleItems[i].parent == null)
rootChildCount++;
}
// Ensure items without a parent gets 'root' as parent
if (rootChildCount > 0)
{
var rootChildren = new List<TreeViewItem>(rootChildCount);
for (int i = 0; i < visibleItems.Count; i++)
{
if (visibleItems[i].parent == null)
{
rootChildren.Add(visibleItems[i]);
visibleItems[i].parent = root;
}
}
root.children = rootChildren;
}
else
root.children = new List<TreeViewItem>();
}
static void SetChildren(TreeViewItem item, List<TreeViewItem> newChildList)
{
// Do not touch children if we have a LazyParent and did not find any children == keep lazy children
if (LazyTreeViewDataSource.IsChildListForACollapsedParent(item.children) && newChildList == null)
return;
item.children = newChildList;
}
static void SetChildParentReferences(int parentIndex, IList<TreeViewItem> visibleItems)
{
TreeViewItem parent = visibleItems[parentIndex];
bool alreadyHasValidChildren = parent.children != null && parent.children.Count > 0 && parent.children[0] != null;
if (alreadyHasValidChildren)
return;
int parentDepth = parent.depth;
int childCount = 0;
// Count children based depth value, we are looking at children until it's the same depth as this object
for (int i = parentIndex + 1; i < visibleItems.Count; i++)
{
if (visibleItems[i].depth == parentDepth + 1)
childCount++;
if (visibleItems[i].depth <= parentDepth)
break;
}
// Fill child array
List<TreeViewItem> childList = null;
if (childCount != 0)
{
childList = new List<TreeViewItem>(childCount); // Allocate once
childCount = 0;
for (int i = parentIndex + 1; i < visibleItems.Count; i++)
{
if (visibleItems[i].depth == parentDepth + 1)
{
visibleItems[i].parent = parent;
childList.Add(visibleItems[i]);
childCount++;
}
if (visibleItems[i].depth <= parentDepth)
break;
}
}
SetChildren(parent, childList);
}
}
}
| UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewUtililty.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewUtililty.cs",
"repo_id": "UnityCsReference",
"token_count": 3855
} | 310 |
// 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.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor
{
[UsedByNativeCode,
NativeHeader("Runtime/Misc/InputEvent.h"),
NativeHeader("Runtime/Graphics/RenderTexture.h"),
NativeHeader("Editor/Src/Windowing/GUIView.bindings.h"),
NativeHeader("Editor/Src/Windowing/ContainerWindow.bindings.h")]
internal partial class GUIView
{
public static extern GUIView current {[NativeMethod("GetCurrentGUIView")] get; }
public static extern GUIView focusedView {[NativeMethod("GetFocusedGUIView")] get; }
public static extern GUIView mouseOverView {[NativeMethod("GetMouseOverGUIView")] get; }
public extern bool hasFocus {[NativeMethod("IsViewFocused")] get; }
public extern void Repaint();
public extern void Focus();
public extern void RepaintImmediately();
public extern void CaptureRenderDocScene();
public extern void CaptureRenderDocFullContent();
public extern void BeginCaptureRenderDoc();
public extern void EndCaptureRenderDoc();
internal extern bool vSyncEnabled {[NativeMethod("IsVSyncEnabled")] get; }
internal extern void RenderCurrentSceneForCapture();
internal extern bool mouseRayInvisible {[NativeMethod("IsMouseRayInvisible")] get; [NativeMethod("SetMouseRayInvisible")] set; }
internal extern bool disableInputEvents {[NativeMethod("AreInputEventsDisabled")] get; [NativeMethod("SetDisableInputEvents")] set; }
internal extern bool hdrActive {[NativeMethod("IsHDRActive")] get; }
internal extern void SetTitle(string title);
internal extern void AddToAuxWindowList();
internal extern void SetInternalGameViewDimensions(Rect rect, Rect clippedRect, Vector2 targetSize);
internal extern void SetMainPlayModeViewSize(Vector2 targetSize);
internal extern void SetDisplayViewSize(int displayId, Vector2 targetSize);
internal extern Vector2 GetDisplayViewSize(int displayId);
internal extern void SetAsStartView();
internal extern void SetAsLastPlayModeView();
internal extern void SetPlayModeView(bool value);
internal extern void ClearStartView();
internal extern void MakeVistaDWMHappyDance();
internal extern void SetEyeDropperOpen(bool isOpen);
internal extern void StealMouseCapture();
internal extern void ClearKeyboardControl();
internal extern void SetKeyboardControl(int id);
internal extern int GetKeyboardControl();
internal extern void GrabPixels(RenderTexture rd, Rect rect);
internal extern float GetBackingScaleFactor();
internal extern void MarkHotRegion(Rect hotRegionRect);
internal extern void EnableVSync(bool value);
internal extern void SetActualViewName(string viewName);
internal extern System.IntPtr nativeHandle
{
[NativeMethod("GetGUIViewHandle")]
get;
}
protected extern void Internal_SetAsActiveWindow();
[NativeMethod(ThrowsException = true)]
private extern void Internal_Init(int depthBits, int antiAliasing, bool isPlayModeView);
private extern void Internal_Recreate(int depthBits, int antiAliasing);
private extern void Internal_Close();
private extern bool Internal_SendEvent(Event e);
private extern void Internal_SetWantsMouseMove(bool wantIt);
private extern void Internal_SetWantsMouseEnterLeaveWindow(bool wantIt);
private extern void Internal_SetAutoRepaint(bool doit);
private extern void Internal_SetWindow(ScriptableObject win);
private extern void Internal_UnsetWindow(ScriptableObject win);
private extern void Internal_SetPosition(Rect windowPosition);
}
}
| UnityCsReference/Editor/Mono/GUIView.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUIView.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1381
} | 311 |
// 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
{
// Determines how a gizmo is drawn or picked in the Unity editor.
[Flags]
public enum GizmoType
{
// The gizmo can be picked in the editor.
Pickable = 1,
// Draw the gizmo if it is not selected or child of the selection.
NotInSelectionHierarchy = 2,
// Draw the gizmo if it is not selected.
NonSelected = 32,
// Draw the gizmo if it is selected.
Selected = 4,
// Draw the gizmo if it is active (shown in the inspector).
Active = 8,
// Draw the gizmo if it is selected or a child of the selection.
InSelectionHierarchy = 16,
[Obsolete("Use NotInSelectionHierarchy instead (UnityUpgradable) -> NotInSelectionHierarchy")]
NotSelected = -127,
[Obsolete("Use InSelectionHierarchy instead (UnityUpgradable) -> InSelectionHierarchy")]
SelectedOrChild = -127,
}
// The DrawGizmo attribute allows you to supply a gizmo renderer for any [[Component]].
public sealed class DrawGizmo : Attribute
{
// Defines when the gizmo should be invoked for drawing.
public DrawGizmo(GizmoType gizmo)
{
drawOptions = gizmo;
}
// Same as above. /drawnGizmoType/ determines of what type the object we are drawing the gizmo of has to be.
public DrawGizmo(GizmoType gizmo, Type drawnGizmoType)
{
drawnType = drawnGizmoType;
drawOptions = gizmo;
}
//*undocumented
public Type drawnType;
//*undocumented
public GizmoType drawOptions;
}
}
| UnityCsReference/Editor/Mono/Gizmos/DrawGizmo.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Gizmos/DrawGizmo.cs",
"repo_id": "UnityCsReference",
"token_count": 739
} | 312 |
// 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.IMGUI.Controls
{
public class CapsuleBoundsHandle : PrimitiveBoundsHandle
{
public enum HeightAxis { X, Y, Z }
private const int k_DirectionX = 0;
private const int k_DirectionY = 1;
private const int k_DirectionZ = 2;
private static readonly Vector3[] s_HeightAxes = new[] { Vector3.right, Vector3.up, Vector3.forward };
private static readonly int[] s_NextAxis = new[] { 1, 2, 0 };
public HeightAxis heightAxis
{
get { return (HeightAxis)m_HeightAxis; }
set
{
int newValue = (int)value;
if (m_HeightAxis == newValue)
return;
Vector3 size = Vector3.one * radius * 2f;
size[newValue] = GetSize()[m_HeightAxis];
m_HeightAxis = newValue;
SetSize(size);
}
}
private int m_HeightAxis = k_DirectionY;
public float height
{
get
{
// zero out height if height axis is disabled
return !IsAxisEnabled(m_HeightAxis) ? 0f : Mathf.Max(GetSize()[m_HeightAxis], 2f * radius);
}
set
{
// height cannot be less than diameter
value = Mathf.Max(Mathf.Abs(value), 2f * radius);
if (height == value)
return;
Vector3 size = GetSize();
size[m_HeightAxis] = value;
SetSize(size);
}
}
public float radius
{
get
{
int radiusAxis;
// return 0 if only enabled axis is a single radius axis
if (GetRadiusAxis(out radiusAxis) || IsAxisEnabled(m_HeightAxis))
return 0.5f * GetSize()[radiusAxis];
else
return 0f;
}
set
{
Vector3 size = GetSize();
float diameter = 2f * value;
// height cannot be less than diameter
for (int axis = 0; axis < 3; ++axis)
size[axis] = axis == m_HeightAxis ? Mathf.Max(size[axis], diameter) : diameter;
SetSize(size);
}
}
[Obsolete("Use parameterless constructor instead.")]
public CapsuleBoundsHandle(int controlIDHint) : base(controlIDHint) {}
public CapsuleBoundsHandle() : base() {}
protected override void DrawWireframe()
{
HeightAxis radAxis1 = HeightAxis.Y;
HeightAxis radAxis2 = HeightAxis.Z;
switch (heightAxis)
{
case HeightAxis.Y:
radAxis1 = HeightAxis.Z;
radAxis2 = HeightAxis.X;
break;
case HeightAxis.Z:
radAxis1 = HeightAxis.X;
radAxis2 = HeightAxis.Y;
break;
}
bool doHeightAxis = IsAxisEnabled((int)heightAxis);
bool doRadiusAxis1 = IsAxisEnabled((int)radAxis1);
bool doRadiusAxis2 = IsAxisEnabled((int)radAxis2);
Vector3 hgtAx = s_HeightAxes[m_HeightAxis];
Vector3 radAx1 = s_HeightAxes[s_NextAxis[m_HeightAxis]];
Vector3 radAx2 = s_HeightAxes[s_NextAxis[s_NextAxis[m_HeightAxis]]];
float rad = radius;
float hgt = height;
Vector3 top = center + hgtAx * (hgt * 0.5f - rad);
Vector3 bottom = center - hgtAx * (hgt * 0.5f - rad);
// draw caps and connecting lines for each enabled axis if height axis is enabled
if (doHeightAxis)
{
if (doRadiusAxis2)
{
Handles.DrawWireArc(top, radAx1, radAx2, 180f, rad);
Handles.DrawWireArc(bottom, radAx1, radAx2, -180f, rad);
Handles.DrawLine(top + radAx2 * rad, bottom + radAx2 * rad);
Handles.DrawLine(top - radAx2 * rad, bottom - radAx2 * rad);
}
if (doRadiusAxis1)
{
Handles.DrawWireArc(top, radAx2, radAx1, -180f, rad);
Handles.DrawWireArc(bottom, radAx2, radAx1, 180f, rad);
Handles.DrawLine(top + radAx1 * rad, bottom + radAx1 * rad);
Handles.DrawLine(top - radAx1 * rad, bottom - radAx1 * rad);
}
}
// do cross-section if both radius axes are enabled
if (doRadiusAxis1 && doRadiusAxis2)
{
Handles.DrawWireArc(top, hgtAx, radAx1, 360f, rad);
Handles.DrawWireArc(bottom, hgtAx, radAx1, -360f, rad);
}
}
protected override Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds)
{
int changedAxis = k_DirectionX;
switch (handle)
{
case HandleDirection.NegativeY:
case HandleDirection.PositiveY:
changedAxis = k_DirectionY;
break;
case HandleDirection.NegativeZ:
case HandleDirection.PositiveZ:
changedAxis = k_DirectionZ;
break;
}
Vector3 upperBound = newBounds.max;
Vector3 lowerBound = newBounds.min;
// ensure height cannot be made less than diameter
if (changedAxis == m_HeightAxis)
{
int radiusAxis;
GetRadiusAxis(out radiusAxis);
float diameter = upperBound[radiusAxis] - lowerBound[radiusAxis];
float newHeight = upperBound[m_HeightAxis] - lowerBound[m_HeightAxis];
if (newHeight < diameter)
{
if (handle == HandleDirection.PositiveX || handle == HandleDirection.PositiveY || handle == HandleDirection.PositiveZ)
upperBound[m_HeightAxis] = lowerBound[m_HeightAxis] + diameter;
else
lowerBound[m_HeightAxis] = upperBound[m_HeightAxis] - diameter;
}
}
// ensure radius changes uniformly and enlarges the height if necessary
else
{
// try to return height to its value at the time handle was clicked
upperBound[m_HeightAxis] = boundsOnClick.center[m_HeightAxis] + 0.5f * boundsOnClick.size[m_HeightAxis];
lowerBound[m_HeightAxis] = boundsOnClick.center[m_HeightAxis] - 0.5f * boundsOnClick.size[m_HeightAxis];
float rad = 0.5f * (upperBound[changedAxis] - lowerBound[changedAxis]);
float halfCurrentHeight = 0.5f * (upperBound[m_HeightAxis] - lowerBound[m_HeightAxis]);
for (int axis = 0; axis < 3; ++axis)
{
if (axis == changedAxis)
continue;
float amt = axis == m_HeightAxis ? Mathf.Max(halfCurrentHeight, rad) : rad;
lowerBound[axis] = center[axis] - amt;
upperBound[axis] = center[axis] + amt;
}
}
return new Bounds((upperBound + lowerBound) * 0.5f, upperBound - lowerBound);
}
// returns true only if both radius axes are enabled
private bool GetRadiusAxis(out int radiusAxis)
{
radiusAxis = s_NextAxis[m_HeightAxis];
if (!IsAxisEnabled(radiusAxis))
{
radiusAxis = s_NextAxis[radiusAxis];
return false;
}
return IsAxisEnabled(s_NextAxis[radiusAxis]);
}
}
}
| UnityCsReference/Editor/Mono/Handles/BoundsHandle/CapsuleBoundsHandle.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/BoundsHandle/CapsuleBoundsHandle.cs",
"repo_id": "UnityCsReference",
"token_count": 4290
} | 313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.