text
stringlengths 7
35.3M
| id
stringlengths 11
185
| metadata
dict | __index_level_0__
int64 0
2.14k
|
---|---|---|---|
// 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 ICSharpCode.Decompiler.Util;
using NUnit.Framework;
namespace ICSharpCode.Decompiler.Tests.Util
{
[TestFixture]
public class FileUtilityTests
{
#region NormalizePath
[Test]
public void NormalizePath()
{
Assert.That(FileUtility.NormalizePath(@"c:\temp\project\..\test.txt"), Is.EqualTo(@"c:\temp\test.txt"));
Assert.That(FileUtility.NormalizePath(@"c:\temp\project\.\..\test.txt"), Is.EqualTo(@"c:\temp\test.txt"));
Assert.That(FileUtility.NormalizePath(@"c:\temp\\test.txt"), Is.EqualTo(@"c:\temp\test.txt")); // normalize double backslash
Assert.That(FileUtility.NormalizePath(@"c:\temp\."), Is.EqualTo(@"c:\temp"));
Assert.That(FileUtility.NormalizePath(@"c:\temp\subdir\.."), Is.EqualTo(@"c:\temp"));
}
[Test]
public void NormalizePath_DriveRoot()
{
Assert.That(FileUtility.NormalizePath(@"C:\"), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:/"), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:"), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:/."), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:/.."), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:/./"), Is.EqualTo(@"C:\"));
Assert.That(FileUtility.NormalizePath(@"C:/..\"), Is.EqualTo(@"C:\"));
}
[Test]
public void NormalizePath_UNC()
{
Assert.That(FileUtility.NormalizePath(@"\\server\share"), Is.EqualTo(@"\\server\share"));
Assert.That(FileUtility.NormalizePath(@"\\server\share\"), Is.EqualTo(@"\\server\share"));
Assert.That(FileUtility.NormalizePath(@"//server/share/"), Is.EqualTo(@"\\server\share"));
Assert.That(FileUtility.NormalizePath(@"//server/share/dir/..\otherdir"), Is.EqualTo(@"\\server\share\otherdir"));
}
[Test]
public void NormalizePath_Web()
{
Assert.That(FileUtility.NormalizePath(@"http://danielgrunwald.de/path/"), Is.EqualTo(@"http://danielgrunwald.de/path/"));
Assert.That(FileUtility.NormalizePath(@"browser://http://danielgrunwald.de/wrongpath/../path/"), Is.EqualTo(@"browser://http://danielgrunwald.de/path/"));
}
[Test]
public void NormalizePath_Relative()
{
Assert.That(FileUtility.NormalizePath(@"..\a\..\b"), Is.EqualTo(@"../b"));
Assert.That(FileUtility.NormalizePath(@"."), Is.EqualTo(@"."));
Assert.That(FileUtility.NormalizePath(@"a\.."), Is.EqualTo(@"."));
}
[Test]
public void NormalizePath_UnixStyle()
{
Assert.That(FileUtility.NormalizePath("/"), Is.EqualTo("/"));
Assert.That(FileUtility.NormalizePath("/a/b"), Is.EqualTo("/a/b"));
Assert.That(FileUtility.NormalizePath("/c/../a/./b"), Is.EqualTo("/a/b"));
Assert.That(FileUtility.NormalizePath("/c/../../a/./b"), Is.EqualTo("/a/b"));
}
#endregion
[Test]
public void TestIsBaseDirectory()
{
Assert.That(FileUtility.IsBaseDirectory(@"C:\a", @"C:\A\b\hello"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a", @"C:\a"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a\", @"C:\a\"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a\", @"C:\a"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a", @"C:\a\"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\A", @"C:\a"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a", @"C:\A"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\a\x\fWufhweoe", @"C:\a\x\fwuFHweoe\a\b\hello"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\b\..\A", @"C:\a"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\HELLO\..\B\..\a", @"C:\b\..\a"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\.\B\..\.\.\a", @"C:\.\.\.\.\.\.\.\a"));
Assert.That(!FileUtility.IsBaseDirectory(@"C:\b", @"C:\a\b\hello"));
Assert.That(!FileUtility.IsBaseDirectory(@"C:\a\b\hello", @"C:\b"));
Assert.That(!FileUtility.IsBaseDirectory(@"C:\a\x\fwufhweoe", @"C:\a\x\fwuFHweoex\a\b\hello"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\", @"C:\"));
Assert.That(FileUtility.IsBaseDirectory(@"C:\", @"C:\a\b\hello"));
Assert.That(!FileUtility.IsBaseDirectory(@"C:\", @"D:\a\b\hello"));
}
[Test]
public void TestIsBaseDirectoryRelative()
{
Assert.That(FileUtility.IsBaseDirectory(@".", @"a\b"));
Assert.That(FileUtility.IsBaseDirectory(@".", @"a"));
Assert.That(!FileUtility.IsBaseDirectory(@".", @"c:\"));
Assert.That(!FileUtility.IsBaseDirectory(@".", @"/"));
}
[Test]
public void TestIsBaseDirectoryUnixStyle()
{
Assert.That(FileUtility.IsBaseDirectory(@"/", @"/"));
Assert.That(FileUtility.IsBaseDirectory(@"/", @"/a"));
Assert.That(FileUtility.IsBaseDirectory(@"/", @"/a/subdir"));
}
[Test]
public void TestIsBaseDirectoryUNC()
{
Assert.That(FileUtility.IsBaseDirectory(@"\\server\share", @"\\server\share\dir\subdir"));
Assert.That(FileUtility.IsBaseDirectory(@"\\server\share", @"\\server\share\dir\subdir"));
Assert.That(!FileUtility.IsBaseDirectory(@"\\server2\share", @"\\server\share\dir\subdir"));
}
[Test]
public void TestGetRelativePath()
{
Assert.That(FileUtility.GetRelativePath(@"C:\hello\.\..\a", @"C:\.\a\blub"), Is.EqualTo(@"blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\.\.\.\.\hello", @"C:\.\blub\.\..\.\a\.\blub"), Is.EqualTo(@"..\a\blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\.\.\.\.\hello\", @"C:\.\blub\.\..\.\a\.\blub"), Is.EqualTo(@"..\a\blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\hello", @"C:\.\hello"), Is.EqualTo(@"."));
Assert.That(FileUtility.GetRelativePath(@"C:\", @"C:\"), Is.EqualTo(@"."));
Assert.That(FileUtility.GetRelativePath(@"C:\", @"C:\blub"), Is.EqualTo(@"blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\", @"D:\"), Is.EqualTo(@"D:\"));
Assert.That(FileUtility.GetRelativePath(@"C:\abc", @"D:\def"), Is.EqualTo(@"D:\def"));
// casing troubles
Assert.That(FileUtility.GetRelativePath(@"C:\hello\.\..\A", @"C:\.\a\blub"), Is.EqualTo(@"blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\.\.\.\.\HELlo", @"C:\.\blub\.\..\.\a\.\blub"), Is.EqualTo(@"..\a\blub"));
Assert.That(FileUtility.GetRelativePath(@"C:\.\.\.\.\heLLo\A\..", @"C:\.\blub\.\..\.\a\.\blub"), Is.EqualTo(@"..\a\blub"));
}
[Test]
public void RelativeGetRelativePath()
{
// Relative path
Assert.That(FileUtility.GetRelativePath(@".", @"a"), Is.EqualTo(@"a"));
Assert.That(FileUtility.GetRelativePath(@"a", @"."), Is.EqualTo(@".."));
Assert.That(FileUtility.GetRelativePath(@"a", @"b"), Is.EqualTo(@"..\b"));
Assert.That(FileUtility.GetRelativePath(@"a", @".."), Is.EqualTo(@"..\.."));
// Getting a path from an absolute path to a relative path isn't really possible;
// so we just keep the existing relative path (don't introduce incorrect '..\').
Assert.That(FileUtility.GetRelativePath(@"C:\abc", @"def"), Is.EqualTo(@"def"));
}
[Test]
public void GetRelativePath_Unix()
{
Assert.That(FileUtility.GetRelativePath("/", "/a"), Is.EqualTo(@"a"));
Assert.That(FileUtility.GetRelativePath("/", "/a/b"), Is.EqualTo(@"a\b"));
Assert.That(FileUtility.GetRelativePath("/a", "/a/b"), Is.EqualTo(@"b"));
}
[Test]
public void TestIsEqualFile()
{
Assert.That(FileUtility.IsEqualFileName(@"C:\.\Hello World.Exe", @"C:\HELLO WOrld.exe"));
Assert.That(FileUtility.IsEqualFileName(@"C:\bla\..\a\my.file.is.this", @"C:\gg\..\.\.\.\.\a\..\a\MY.FILE.IS.THIS"));
Assert.That(!FileUtility.IsEqualFileName(@"C:\.\Hello World.Exe", @"C:\HELLO_WOrld.exe"));
Assert.That(!FileUtility.IsEqualFileName(@"C:\a\my.file.is.this", @"C:\gg\..\.\.\.\.\a\..\b\MY.FILE.IS.THIS"));
}
}
} | ILSpy/ICSharpCode.Decompiler.Tests/Util/FileUtilityTests.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/Util/FileUtilityTests.cs",
"repo_id": "ILSpy",
"token_count": 3773
} | 213 |
// 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.IO;
using ICSharpCode.Decompiler.CSharp.Syntax;
namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{
public abstract class TokenWriter
{
public abstract void StartNode(AstNode node);
public abstract void EndNode(AstNode node);
/// <summary>
/// Writes an identifier.
/// </summary>
public abstract void WriteIdentifier(Identifier identifier);
/// <summary>
/// Writes a keyword to the output.
/// </summary>
public abstract void WriteKeyword(Role role, string keyword);
/// <summary>
/// Writes a token to the output.
/// </summary>
public abstract void WriteToken(Role role, string token);
/// <summary>
/// Writes a primitive/literal value
/// </summary>
public abstract void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None);
public abstract void WritePrimitiveType(string type);
/// <summary>
/// Write a piece of text in an interpolated string literal.
/// </summary>
public abstract void WriteInterpolatedText(string text);
public abstract void Space();
public abstract void Indent();
public abstract void Unindent();
public abstract void NewLine();
public abstract void WriteComment(CommentType commentType, string content);
public abstract void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument);
public static TokenWriter Create(TextWriter writer, string indentation = "\t")
{
return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new TextWriterTokenWriter(writer) { IndentationString = indentation }));
}
public static TokenWriter CreateWriterThatSetsLocationsInAST(TextWriter writer, string indentation = "\t")
{
var target = new TextWriterTokenWriter(writer) { IndentationString = indentation };
return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new InsertMissingTokensDecorator(target, target)));
}
public static TokenWriter InsertRequiredSpaces(TokenWriter writer)
{
return new InsertRequiredSpacesDecorator(writer);
}
public static TokenWriter WrapInWriterThatSetsLocationsInAST(TokenWriter writer)
{
if (!(writer is ILocatable))
throw new InvalidOperationException("writer does not provide locations!");
return new InsertMissingTokensDecorator(writer, (ILocatable)writer);
}
}
public interface ILocatable
{
TextLocation Location { get; }
int Length { get; }
}
public abstract class DecoratingTokenWriter : TokenWriter
{
readonly TokenWriter decoratedWriter;
protected DecoratingTokenWriter(TokenWriter decoratedWriter)
{
if (decoratedWriter == null)
throw new ArgumentNullException(nameof(decoratedWriter));
this.decoratedWriter = decoratedWriter;
}
public override void StartNode(AstNode node)
{
decoratedWriter.StartNode(node);
}
public override void EndNode(AstNode node)
{
decoratedWriter.EndNode(node);
}
public override void WriteIdentifier(Identifier identifier)
{
decoratedWriter.WriteIdentifier(identifier);
}
public override void WriteKeyword(Role role, string keyword)
{
decoratedWriter.WriteKeyword(role, keyword);
}
public override void WriteToken(Role role, string token)
{
decoratedWriter.WriteToken(role, token);
}
public override void WritePrimitiveValue(object value, LiteralFormat format = LiteralFormat.None)
{
decoratedWriter.WritePrimitiveValue(value, format);
}
public override void WritePrimitiveType(string type)
{
decoratedWriter.WritePrimitiveType(type);
}
public override void WriteInterpolatedText(string text)
{
decoratedWriter.WriteInterpolatedText(text);
}
public override void Space()
{
decoratedWriter.Space();
}
public override void Indent()
{
decoratedWriter.Indent();
}
public override void Unindent()
{
decoratedWriter.Unindent();
}
public override void NewLine()
{
decoratedWriter.NewLine();
}
public override void WriteComment(CommentType commentType, string content)
{
decoratedWriter.WriteComment(commentType, content);
}
public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
{
decoratedWriter.WritePreProcessorDirective(type, argument);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs",
"repo_id": "ILSpy",
"token_count": 1633
} | 214 |
// Copyright (c) 2017 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.DebugInfo;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp
{
/// <summary>
/// Given a SyntaxTree that was output from the decompiler, constructs the list of sequence points.
/// </summary>
// Each statement / expression AST node is annotated with the ILInstruction(s) it was constructed from.
// Each ILInstruction has a list of IL offsets corresponding to the original IL range(s). Note that the ILAst
// instructions form a tree.
//
// This visitor constructs a list of sequence points from the syntax tree by visiting each node,
// calling
// 1. StartSequencePoint(AstNode)
// 2. AddToSequencePoint(AstNode) (possibly multiple times)
// 3. EndSequencePoint(TextLocation, TextLocation)
// on each node.
//
// The VisitAsSequencePoint(AstNode) method encapsulates the steps above.
//
// The state we record for each sequence point is decribed in StatePerSequencePoint:
// 1. primary AST node
// 2. IL range intervals
// 3. parent ILFunction (either a method or lambda)
//
// For each statement (at least) one sequence point is created and all expressions and their IL ranges
// are added to it. Currently the debugger seems not to support breakpoints at an expression level, so
// we stop at the statement level and add all sub-expressions to the same sequence point.
//
// LambdaExpression is one exception: we create new sequence points for the expression/statements of the lambda,
// note however, that these are added to a different ILFunction.
//
// AddToSequencePoint(AstNode) handles the list of ILInstructions and visits each ILInstruction and its descendants.
// We do not descend into nested ILFunctions as these create their own list of sequence points.
class SequencePointBuilder : DepthFirstAstVisitor
{
struct StatePerSequencePoint
{
/// <summary>
/// Main AST node associated with this sequence point.
/// </summary>
internal readonly AstNode PrimaryNode;
/// <summary>
/// List of IL intervals that are associated with this sequence point.
/// </summary>
internal readonly List<Interval> Intervals;
/// <summary>
/// The function containing this sequence point.
/// </summary>
internal ILFunction Function;
public StatePerSequencePoint(AstNode primaryNode)
{
this.PrimaryNode = primaryNode;
this.Intervals = new List<Interval>();
this.Function = null;
}
}
readonly List<(ILFunction, DebugInfo.SequencePoint)> sequencePoints = new List<(ILFunction, DebugInfo.SequencePoint)>();
readonly HashSet<ILInstruction> mappedInstructions = new HashSet<ILInstruction>();
// Stack holding information for outer statements.
readonly Stack<StatePerSequencePoint> outerStates = new Stack<StatePerSequencePoint>();
// Collects information for the current sequence point.
StatePerSequencePoint current;
void VisitAsSequencePoint(AstNode node)
{
if (node.IsNull)
return;
StartSequencePoint(node);
node.AcceptVisitor(this);
EndSequencePoint(node.StartLocation, node.EndLocation);
}
protected override void VisitChildren(AstNode node)
{
base.VisitChildren(node);
AddToSequencePoint(node);
}
public override void VisitBlockStatement(BlockStatement blockStatement)
{
// enhanced using variables need special-casing here, because we omit the block syntax from the
// text output, so we cannot use positions of opening/closing braces here.
bool isEnhancedUsing = blockStatement.Parent is UsingStatement us && us.IsEnhanced;
if (!isEnhancedUsing)
{
var blockContainer = blockStatement.Annotation<BlockContainer>();
if (blockContainer != null)
{
StartSequencePoint(blockStatement.LBraceToken);
int intervalStart;
if (blockContainer.Parent is TryCatchHandler handler && !handler.ExceptionSpecifierILRange.IsEmpty)
{
// if this block container is part of a TryCatchHandler, do not steal the
// exception-specifier IL range
intervalStart = handler.ExceptionSpecifierILRange.End;
}
else
{
intervalStart = blockContainer.StartILOffset;
}
// The end will be set to the first sequence point candidate location before the first
// statement of the function when the seqeunce point is adjusted
int intervalEnd = intervalStart + 1;
Interval interval = new Interval(intervalStart, intervalEnd);
List<Interval> intervals = new List<Interval>();
intervals.Add(interval);
current.Intervals.AddRange(intervals);
current.Function = blockContainer.Ancestors.OfType<ILFunction>().FirstOrDefault();
EndSequencePoint(blockStatement.LBraceToken.StartLocation, blockStatement.LBraceToken.EndLocation);
}
else
{
// Ideally, we'd be able to address this case. Blocks that are not the top-level function
// block have no ILInstruction annotations. It isn't clear to me how to determine the il range.
// For now, do not add the opening brace sequence in this case.
}
}
foreach (var stmt in blockStatement.Statements)
{
VisitAsSequencePoint(stmt);
}
var implicitReturn = blockStatement.Annotation<ImplicitReturnAnnotation>();
if (implicitReturn != null && !isEnhancedUsing)
{
StartSequencePoint(blockStatement.RBraceToken);
AddToSequencePoint(implicitReturn.Leave);
EndSequencePoint(blockStatement.RBraceToken.StartLocation, blockStatement.RBraceToken.EndLocation);
}
}
public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
if (!propertyDeclaration.ExpressionBody.IsNull)
{
VisitAsSequencePoint(propertyDeclaration.ExpressionBody);
}
else
{
base.VisitPropertyDeclaration(propertyDeclaration);
}
}
public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
if (!indexerDeclaration.ExpressionBody.IsNull)
{
VisitAsSequencePoint(indexerDeclaration.ExpressionBody);
}
else
{
base.VisitIndexerDeclaration(indexerDeclaration);
}
}
public override void VisitForStatement(ForStatement forStatement)
{
// Every element of a for-statement is its own sequence point.
foreach (var init in forStatement.Initializers)
{
VisitAsSequencePoint(init);
}
VisitAsSequencePoint(forStatement.Condition);
foreach (var inc in forStatement.Iterators)
{
VisitAsSequencePoint(inc);
}
VisitAsSequencePoint(forStatement.EmbeddedStatement);
}
public override void VisitSwitchStatement(SwitchStatement switchStatement)
{
StartSequencePoint(switchStatement);
switchStatement.Expression.AcceptVisitor(this);
foreach (var section in switchStatement.SwitchSections)
{
// note: sections will not contribute to the current sequence point
section.AcceptVisitor(this);
}
// add switch statement itself to sequence point
// (call only after the sections are visited)
AddToSequencePoint(switchStatement);
EndSequencePoint(switchStatement.StartLocation, switchStatement.RParToken.EndLocation);
}
public override void VisitSwitchSection(Syntax.SwitchSection switchSection)
{
// every statement in the switch section is its own sequence point
foreach (var stmt in switchSection.Statements)
{
VisitAsSequencePoint(stmt);
}
}
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
AddToSequencePoint(lambdaExpression);
VisitAsSequencePoint(lambdaExpression.Body);
}
public override void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
{
AddToSequencePoint(queryContinuationClause);
VisitAsSequencePoint(queryContinuationClause.PrecedingQuery);
}
public override void VisitQueryFromClause(QueryFromClause queryFromClause)
{
if (queryFromClause.Parent.FirstChild != queryFromClause)
{
AddToSequencePoint(queryFromClause);
VisitAsSequencePoint(queryFromClause.Expression);
}
else
{
base.VisitQueryFromClause(queryFromClause);
}
}
public override void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
{
AddToSequencePoint(queryGroupClause);
VisitAsSequencePoint(queryGroupClause.Projection);
VisitAsSequencePoint(queryGroupClause.Key);
}
public override void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
{
AddToSequencePoint(queryJoinClause);
VisitAsSequencePoint(queryJoinClause.OnExpression);
VisitAsSequencePoint(queryJoinClause.EqualsExpression);
}
public override void VisitQueryLetClause(QueryLetClause queryLetClause)
{
AddToSequencePoint(queryLetClause);
VisitAsSequencePoint(queryLetClause.Expression);
}
public override void VisitQueryOrdering(QueryOrdering queryOrdering)
{
AddToSequencePoint(queryOrdering);
VisitAsSequencePoint(queryOrdering.Expression);
}
public override void VisitQuerySelectClause(QuerySelectClause querySelectClause)
{
AddToSequencePoint(querySelectClause);
VisitAsSequencePoint(querySelectClause.Expression);
}
public override void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
{
AddToSequencePoint(queryWhereClause);
VisitAsSequencePoint(queryWhereClause.Condition);
}
public override void VisitUsingStatement(UsingStatement usingStatement)
{
StartSequencePoint(usingStatement);
usingStatement.ResourceAcquisition.AcceptVisitor(this);
VisitAsSequencePoint(usingStatement.EmbeddedStatement);
AddToSequencePoint(usingStatement);
if (usingStatement.IsEnhanced)
EndSequencePoint(usingStatement.StartLocation, usingStatement.ResourceAcquisition.EndLocation);
else
EndSequencePoint(usingStatement.StartLocation, usingStatement.RParToken.EndLocation);
}
public override void VisitForeachStatement(ForeachStatement foreachStatement)
{
var foreachInfo = foreachStatement.Annotation<ForeachAnnotation>();
if (foreachInfo == null)
{
base.VisitForeachStatement(foreachStatement);
return;
}
// TODO : Add a sequence point on foreach token (mapped to nop before using instruction).
StartSequencePoint(foreachStatement);
foreachStatement.InExpression.AcceptVisitor(this);
AddToSequencePoint(foreachInfo.GetEnumeratorCall);
EndSequencePoint(foreachStatement.InExpression.StartLocation, foreachStatement.InExpression.EndLocation);
StartSequencePoint(foreachStatement);
AddToSequencePoint(foreachInfo.MoveNextCall);
EndSequencePoint(foreachStatement.InToken.StartLocation, foreachStatement.InToken.EndLocation);
StartSequencePoint(foreachStatement);
AddToSequencePoint(foreachInfo.GetCurrentCall);
EndSequencePoint(foreachStatement.VariableType.StartLocation, foreachStatement.VariableDesignation.EndLocation);
VisitAsSequencePoint(foreachStatement.EmbeddedStatement);
}
public override void VisitLockStatement(LockStatement lockStatement)
{
StartSequencePoint(lockStatement);
lockStatement.Expression.AcceptVisitor(this);
VisitAsSequencePoint(lockStatement.EmbeddedStatement);
AddToSequencePoint(lockStatement);
EndSequencePoint(lockStatement.StartLocation, lockStatement.RParToken.EndLocation);
}
public override void VisitIfElseStatement(IfElseStatement ifElseStatement)
{
StartSequencePoint(ifElseStatement);
ifElseStatement.Condition.AcceptVisitor(this);
VisitAsSequencePoint(ifElseStatement.TrueStatement);
VisitAsSequencePoint(ifElseStatement.FalseStatement);
AddToSequencePoint(ifElseStatement);
EndSequencePoint(ifElseStatement.StartLocation, ifElseStatement.RParToken.EndLocation);
}
public override void VisitWhileStatement(WhileStatement whileStatement)
{
StartSequencePoint(whileStatement);
whileStatement.Condition.AcceptVisitor(this);
VisitAsSequencePoint(whileStatement.EmbeddedStatement);
AddToSequencePoint(whileStatement);
EndSequencePoint(whileStatement.StartLocation, whileStatement.RParToken.EndLocation);
}
public override void VisitDoWhileStatement(DoWhileStatement doWhileStatement)
{
StartSequencePoint(doWhileStatement);
VisitAsSequencePoint(doWhileStatement.EmbeddedStatement);
doWhileStatement.Condition.AcceptVisitor(this);
AddToSequencePoint(doWhileStatement);
EndSequencePoint(doWhileStatement.WhileToken.StartLocation, doWhileStatement.RParToken.EndLocation);
}
public override void VisitFixedStatement(FixedStatement fixedStatement)
{
foreach (var v in fixedStatement.Variables)
{
VisitAsSequencePoint(v);
}
VisitAsSequencePoint(fixedStatement.EmbeddedStatement);
}
public override void VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
{
VisitAsSequencePoint(tryCatchStatement.TryBlock);
foreach (var c in tryCatchStatement.CatchClauses)
{
VisitAsSequencePoint(c);
}
VisitAsSequencePoint(tryCatchStatement.FinallyBlock);
}
public override void VisitCatchClause(CatchClause catchClause)
{
if (catchClause.Condition.IsNull)
{
var tryCatchHandler = catchClause.Annotation<TryCatchHandler>();
if (tryCatchHandler != null && !tryCatchHandler.ExceptionSpecifierILRange.IsEmpty)
{
StartSequencePoint(catchClause.CatchToken);
var function = tryCatchHandler.Ancestors.OfType<ILFunction>().FirstOrDefault();
AddToSequencePointRaw(function, new[] { tryCatchHandler.ExceptionSpecifierILRange });
EndSequencePoint(catchClause.CatchToken.StartLocation, catchClause.RParToken.IsNull ? catchClause.CatchToken.EndLocation : catchClause.RParToken.EndLocation);
}
}
else
{
StartSequencePoint(catchClause.WhenToken);
AddToSequencePoint(catchClause.Condition);
EndSequencePoint(catchClause.WhenToken.StartLocation, catchClause.CondRParToken.EndLocation);
}
VisitAsSequencePoint(catchClause.Body);
}
/// <summary>
/// Start a new C# statement = new sequence point.
/// </summary>
void StartSequencePoint(AstNode primaryNode)
{
outerStates.Push(current);
current = new StatePerSequencePoint(primaryNode);
}
void EndSequencePoint(TextLocation startLocation, TextLocation endLocation)
{
Debug.Assert(!startLocation.IsEmpty, "missing startLocation");
Debug.Assert(!endLocation.IsEmpty, "missing endLocation");
if (current.Intervals.Count > 0 && current.Function != null)
{
// use LongSet to deduplicate and merge the intervals
var longSet = new LongSet(current.Intervals.Select(i => new LongInterval(i.Start, i.End)));
Debug.Assert(!longSet.IsEmpty);
sequencePoints.Add((current.Function, new DebugInfo.SequencePoint {
Offset = (int)longSet.Intervals[0].Start,
EndOffset = (int)longSet.Intervals[0].End,
StartLine = startLocation.Line,
StartColumn = startLocation.Column,
EndLine = endLocation.Line,
EndColumn = endLocation.Column
}));
}
current = outerStates.Pop();
}
void AddToSequencePointRaw(ILFunction function, IEnumerable<Interval> ranges)
{
current.Intervals.AddRange(ranges);
Debug.Assert(current.Function == null || current.Function == function);
current.Function = function;
}
/// <summary>
/// Add the ILAst instruction associated with the AstNode to the sequence point.
/// Also add all its ILAst sub-instructions (unless they were already added to another sequence point).
/// </summary>
void AddToSequencePoint(AstNode node)
{
foreach (var inst in node.Annotations.OfType<ILInstruction>())
{
AddToSequencePoint(inst);
}
}
void AddToSequencePoint(ILInstruction inst)
{
if (!mappedInstructions.Add(inst))
{
// inst was already used by a nested sequence point within this sequence point
return;
}
// Add the IL range associated with this instruction to the current sequence point.
if (HasUsableILRange(inst) && current.Intervals != null)
{
current.Intervals.AddRange(inst.ILRanges);
var function = inst.Parent.Ancestors.OfType<ILFunction>().FirstOrDefault();
Debug.Assert(current.Function == null || current.Function == function);
current.Function = function;
}
// Do not add instructions of lambdas/delegates.
if (inst is ILFunction)
return;
// Also add the child IL instructions, unless they were already processed by
// another C# expression.
foreach (var child in inst.Children)
{
AddToSequencePoint(child);
}
}
internal static bool HasUsableILRange(ILInstruction inst)
{
if (inst.ILRangeIsEmpty)
return false;
if (inst.Parent == null)
return false;
return !(inst is BlockContainer || inst is Block);
}
/// <summary>
/// Called after the visitor is done to return the results.
/// </summary>
internal Dictionary<ILFunction, List<DebugInfo.SequencePoint>> GetSequencePoints()
{
var dict = new Dictionary<ILFunction, List<DebugInfo.SequencePoint>>();
foreach (var (function, sequencePoint) in this.sequencePoints)
{
if (!dict.TryGetValue(function, out var list))
{
dict.Add(function, list = new List<DebugInfo.SequencePoint>());
}
list.Add(sequencePoint);
}
foreach (var (function, list) in dict.ToList())
{
// For each function, sort sequence points and fix overlaps
var newList = new List<DebugInfo.SequencePoint>();
int pos = 0;
IOrderedEnumerable<DebugInfo.SequencePoint> currFunctionSequencePoints = list.OrderBy(sp => sp.Offset).ThenBy(sp => sp.EndOffset);
foreach (DebugInfo.SequencePoint sequencePoint in currFunctionSequencePoints)
{
if (sequencePoint.Offset < pos)
{
// overlapping sequence point?
// delete previous sequence points that are after sequencePoint.Offset
while (newList.Count > 0 && newList.Last().EndOffset > sequencePoint.Offset)
{
var last = newList.Last();
if (last.Offset >= sequencePoint.Offset)
{
newList.RemoveAt(newList.Count - 1);
}
else
{
last.EndOffset = sequencePoint.Offset;
newList[newList.Count - 1] = last;
}
}
}
newList.Add(sequencePoint);
pos = sequencePoint.EndOffset;
}
// Add a hidden sequence point to account for the epilog of the function
if (pos < function.CodeSize)
{
var hidden = new DebugInfo.SequencePoint();
hidden.Offset = pos;
hidden.EndOffset = function.CodeSize;
hidden.SetHidden();
newList.Add(hidden);
}
List<int> sequencePointCandidates = function.SequencePointCandidates;
int currSPCandidateIndex = 0;
for (int i = 0; i < newList.Count - 1; i++)
{
DebugInfo.SequencePoint currSequencePoint = newList[i];
DebugInfo.SequencePoint nextSequencePoint = newList[i + 1];
// Adjust the end offset of the current sequence point to the closest sequence point candidate
// but do not create an overlapping sequence point. Moving the start of the current sequence
// point is not required as it is 0 for the first sequence point and is moved during the last
// iteration for all others.
while (currSPCandidateIndex < sequencePointCandidates.Count &&
sequencePointCandidates[currSPCandidateIndex] < currSequencePoint.EndOffset)
{
currSPCandidateIndex++;
}
if (currSPCandidateIndex < sequencePointCandidates.Count && sequencePointCandidates[currSPCandidateIndex] <= nextSequencePoint.Offset)
{
currSequencePoint.EndOffset = sequencePointCandidates[currSPCandidateIndex];
}
// Adjust the start offset of the next sequence point to the closest previous sequence point candidate
// but do not create an overlapping sequence point.
while (currSPCandidateIndex < sequencePointCandidates.Count &&
sequencePointCandidates[currSPCandidateIndex] < nextSequencePoint.Offset)
{
currSPCandidateIndex++;
}
if (currSPCandidateIndex < sequencePointCandidates.Count && sequencePointCandidates[currSPCandidateIndex - 1] >= currSequencePoint.EndOffset)
{
nextSequencePoint.Offset = sequencePointCandidates[currSPCandidateIndex - 1];
currSPCandidateIndex--;
}
// Fill in any gaps with a hidden sequence point
if (currSequencePoint.EndOffset != nextSequencePoint.Offset)
{
SequencePoint newSP = new SequencePoint() { Offset = currSequencePoint.EndOffset, EndOffset = nextSequencePoint.Offset };
newSP.SetHidden();
newList.Insert(++i, newSP);
}
}
dict[function] = newList;
}
return dict;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/SequencePointBuilder.cs",
"repo_id": "ILSpy",
"token_count": 7275
} | 215 |
//
// BaseReferenceExpression.cs
//
// Author:
// Mike Krüger <[email protected]>
//
// Copyright (c) 2009 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>
/// base
/// </summary>
public class BaseReferenceExpression : Expression
{
public TextLocation Location {
get;
set;
}
public override TextLocation StartLocation {
get {
return Location;
}
}
public override TextLocation EndLocation {
get {
return new TextLocation(Location.Line, Location.Column + "base".Length);
}
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitBaseReferenceExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitBaseReferenceExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitBaseReferenceExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
BaseReferenceExpression o = other as BaseReferenceExpression;
return o != null;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/BaseReferenceExpression.cs",
"repo_id": "ILSpy",
"token_count": 695
} | 216 |
//
// MemberReferenceExpression.cs
//
// Author:
// Mike Krüger <[email protected]>
//
// Copyright (c) 2009 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>
/// Target.MemberName
/// </summary>
public class MemberReferenceExpression : Expression
{
public Expression Target {
get {
return GetChildByRole(Roles.TargetExpression);
}
set {
SetChildByRole(Roles.TargetExpression, value);
}
}
public CSharpTokenNode DotToken {
get { return GetChildByRole(Roles.Dot); }
}
public string MemberName {
get {
return GetChildByRole(Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, Identifier.Create(value));
}
}
public Identifier MemberNameToken {
get {
return GetChildByRole(Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public CSharpTokenNode LChevronToken {
get { return GetChildByRole(Roles.LChevron); }
}
public AstNodeCollection<AstType> TypeArguments {
get { return GetChildrenByRole(Roles.TypeArgument); }
}
public CSharpTokenNode RChevronToken {
get { return GetChildByRole(Roles.RChevron); }
}
public MemberReferenceExpression()
{
}
public MemberReferenceExpression(Expression target, string memberName, IEnumerable<AstType> arguments = null)
{
AddChild(target, Roles.TargetExpression);
MemberName = memberName;
if (arguments != null)
{
foreach (var arg in arguments)
{
AddChild(arg, Roles.TypeArgument);
}
}
}
public MemberReferenceExpression(Expression target, string memberName, params AstType[] arguments) : this(target, memberName, (IEnumerable<AstType>)arguments)
{
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitMemberReferenceExpression(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitMemberReferenceExpression(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitMemberReferenceExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
MemberReferenceExpression o = other as MemberReferenceExpression;
return o != null && this.Target.DoMatch(o.Target, match) && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/Expressions/MemberReferenceExpression.cs",
"repo_id": "ILSpy",
"token_count": 1207
} | 217 |
//
// TypeDeclaration.cs
//
// Author:
// Mike Krüger <[email protected]>
//
// Copyright (c) 2009 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 ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
public enum ClassType
{
Class,
Struct,
Interface,
Enum,
/// <summary>
/// C# 9 'record class'
/// </summary>
RecordClass,
/// <summary>
/// C# 10 'record struct'
/// </summary>
RecordStruct,
}
/// <summary>
/// class Name<TypeParameters> : BaseTypes where Constraints;
/// </summary>
public class TypeDeclaration : EntityDeclaration
{
public override NodeType NodeType {
get { return NodeType.TypeDeclaration; }
}
public override SymbolKind SymbolKind {
get { return SymbolKind.TypeDefinition; }
}
ClassType classType;
public CSharpTokenNode TypeKeyword {
get {
switch (classType)
{
case ClassType.Class:
return GetChildByRole(Roles.ClassKeyword);
case ClassType.Struct:
case ClassType.RecordStruct:
return GetChildByRole(Roles.StructKeyword);
case ClassType.Interface:
return GetChildByRole(Roles.InterfaceKeyword);
case ClassType.Enum:
return GetChildByRole(Roles.EnumKeyword);
case ClassType.RecordClass:
return GetChildByRole(Roles.RecordKeyword);
default:
return CSharpTokenNode.Null;
}
}
}
public ClassType ClassType {
get { return classType; }
set {
ThrowIfFrozen();
classType = value;
}
}
public CSharpTokenNode LChevronToken {
get { return GetChildByRole(Roles.LChevron); }
}
public AstNodeCollection<TypeParameterDeclaration> TypeParameters {
get { return GetChildrenByRole(Roles.TypeParameter); }
}
public CSharpTokenNode RChevronToken {
get { return GetChildByRole(Roles.RChevron); }
}
public CSharpTokenNode ColonToken {
get {
return GetChildByRole(Roles.Colon);
}
}
public AstNodeCollection<AstType> BaseTypes {
get { return GetChildrenByRole(Roles.BaseType); }
}
public AstNodeCollection<ParameterDeclaration> PrimaryConstructorParameters {
get { return GetChildrenByRole(Roles.Parameter); }
}
public AstNodeCollection<Constraint> Constraints {
get { return GetChildrenByRole(Roles.Constraint); }
}
public CSharpTokenNode LBraceToken {
get { return GetChildByRole(Roles.LBrace); }
}
public AstNodeCollection<EntityDeclaration> Members {
get { return GetChildrenByRole(Roles.TypeMemberRole); }
}
public CSharpTokenNode RBraceToken {
get { return GetChildByRole(Roles.RBrace); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitTypeDeclaration(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitTypeDeclaration(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitTypeDeclaration(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
TypeDeclaration o = other as TypeDeclaration;
return o != null && this.ClassType == o.ClassType && MatchString(this.Name, o.Name)
&& this.MatchAttributesAndModifiers(o, match) && this.TypeParameters.DoMatch(o.TypeParameters, match)
&& this.BaseTypes.DoMatch(o.BaseTypes, match) && this.Constraints.DoMatch(o.Constraints, match)
&& this.PrimaryConstructorParameters.DoMatch(o.PrimaryConstructorParameters, match)
&& this.Members.DoMatch(o.Members, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/TypeDeclaration.cs",
"repo_id": "ILSpy",
"token_count": 1604
} | 218 |
//
// EventDeclaration.cs
//
// Author:
// Mike Krüger <[email protected]>
//
// Copyright (c) 2009 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;
using System.ComponentModel;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
public class EventDeclaration : EntityDeclaration
{
public static readonly TokenRole EventKeywordRole = new TokenRole("event");
public override SymbolKind SymbolKind {
get { return SymbolKind.Event; }
}
public CSharpTokenNode EventToken {
get { return GetChildByRole(EventKeywordRole); }
}
public AstNodeCollection<VariableInitializer> Variables {
get { return GetChildrenByRole(Roles.Variable); }
}
// Hide .Name and .NameToken from users; the actual field names
// are stored in the VariableInitializer.
[EditorBrowsable(EditorBrowsableState.Never)]
public override string Name {
get { return string.Empty; }
set { throw new NotSupportedException(); }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override Identifier NameToken {
get { return Identifier.Null; }
set { throw new NotSupportedException(); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitEventDeclaration(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitEventDeclaration(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitEventDeclaration(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
EventDeclaration o = other as EventDeclaration;
return o != null && this.MatchAttributesAndModifiers(o, match)
&& this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match);
}
}
public class CustomEventDeclaration : EntityDeclaration
{
public static readonly TokenRole EventKeywordRole = new TokenRole("event");
public static readonly TokenRole AddKeywordRole = new TokenRole("add");
public static readonly TokenRole RemoveKeywordRole = new TokenRole("remove");
public static readonly Role<Accessor> AddAccessorRole = new Role<Accessor>("AddAccessor", Accessor.Null);
public static readonly Role<Accessor> RemoveAccessorRole = new Role<Accessor>("RemoveAccessor", Accessor.Null);
public override SymbolKind SymbolKind {
get { return SymbolKind.Event; }
}
/// <summary>
/// Gets/Sets the type reference of the interface that is explicitly implemented.
/// Null node if this member is not an explicit interface implementation.
/// </summary>
public AstType PrivateImplementationType {
get { return GetChildByRole(PrivateImplementationTypeRole); }
set { SetChildByRole(PrivateImplementationTypeRole, value); }
}
public CSharpTokenNode LBraceToken {
get { return GetChildByRole(Roles.LBrace); }
}
public Accessor AddAccessor {
get { return GetChildByRole(AddAccessorRole); }
set { SetChildByRole(AddAccessorRole, value); }
}
public Accessor RemoveAccessor {
get { return GetChildByRole(RemoveAccessorRole); }
set { SetChildByRole(RemoveAccessorRole, value); }
}
public CSharpTokenNode RBraceToken {
get { return GetChildByRole(Roles.RBrace); }
}
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitCustomEventDeclaration(this);
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitCustomEventDeclaration(this);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitCustomEventDeclaration(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
CustomEventDeclaration o = other as CustomEventDeclaration;
return o != null && MatchString(this.Name, o.Name)
&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
&& this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match)
&& this.AddAccessor.DoMatch(o.AddAccessor, match) && this.RemoveAccessor.DoMatch(o.RemoveAccessor, match);
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Syntax/TypeMembers/EventDeclaration.cs",
"repo_id": "ILSpy",
"token_count": 1652
} | 219 |
// 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.Syntax;
using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching;
using ICSharpCode.Decompiler.Semantics;
namespace ICSharpCode.Decompiler.CSharp.Transforms
{
sealed class TypePattern : Pattern
{
readonly string ns;
readonly string name;
public TypePattern(Type type)
{
this.ns = type.Namespace;
this.name = type.Name;
}
public override bool DoMatch(INode other, Match match)
{
ComposedType ct = other as ComposedType;
AstType o;
if (ct != null && !ct.HasRefSpecifier && !ct.HasNullableSpecifier && ct.PointerRank == 0 && !ct.ArraySpecifiers.Any())
{
// Special case: ILSpy sometimes produces a ComposedType but then removed all array specifiers
// from it. In that case, we need to look at the base type for the annotations.
o = ct.BaseType;
}
else
{
o = other as AstType;
if (o == null)
return false;
}
var trr = o.GetResolveResult() as TypeResolveResult;
return trr != null && trr.Type.Namespace == ns && trr.Type.Name == name;
}
public override string ToString()
{
return name;
}
}
sealed class LdTokenPattern : Pattern
{
AnyNode childNode;
public LdTokenPattern(string groupName)
{
this.childNode = new AnyNode(groupName);
}
public override bool DoMatch(INode other, Match match)
{
InvocationExpression ie = other as InvocationExpression;
if (ie != null && ie.Annotation<LdTokenAnnotation>() != null && ie.Arguments.Count == 1)
{
return childNode.DoMatch(ie.Arguments.Single(), match);
}
return false;
}
public override string ToString()
{
return "ldtoken(...)";
}
}
/// <summary>
/// typeof-Pattern that applies on the expanded form of typeof (prior to ReplaceMethodCallsWithOperators)
/// </summary>
sealed class TypeOfPattern : Pattern
{
INode childNode;
public TypeOfPattern(string groupName)
{
childNode = new MemberReferenceExpression(
new InvocationExpression(
new MemberReferenceExpression(
new TypeReferenceExpression { Type = new TypePattern(typeof(Type)).ToType() },
"GetTypeFromHandle"),
new TypeOfExpression(new AnyNode(groupName))
), "TypeHandle");
}
public override bool DoMatch(INode other, Match match)
{
return childNode.DoMatch(other, match);
}
public override string ToString()
{
return "typeof(...)";
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/CustomPatterns.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/CustomPatterns.cs",
"repo_id": "ILSpy",
"token_count": 1195
} | 220 |
// 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.Collections.Immutable;
using System.Threading;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.CSharp.Transforms
{
/// <summary>
/// Parameters for IAstTransform.
/// </summary>
public class TransformContext
{
public readonly IDecompilerTypeSystem TypeSystem;
public readonly CancellationToken CancellationToken;
public readonly TypeSystemAstBuilder TypeSystemAstBuilder;
public readonly DecompilerSettings Settings;
internal readonly DecompileRun DecompileRun;
readonly ITypeResolveContext decompilationContext;
/// <summary>
/// Returns the current member; or null if a whole type or module is being decompiled.
/// </summary>
public IMember CurrentMember => decompilationContext.CurrentMember;
/// <summary>
/// Returns the current type definition; or null if a module is being decompiled.
/// </summary>
public ITypeDefinition CurrentTypeDefinition => decompilationContext.CurrentTypeDefinition;
/// <summary>
/// Returns the module that is being decompiled.
/// </summary>
public IModule CurrentModule => decompilationContext.CurrentModule;
/// <summary>
/// Returns the max possible set of namespaces that will be used during decompilation.
/// </summary>
public IImmutableSet<string> RequiredNamespacesSuperset => DecompileRun.Namespaces.ToImmutableHashSet();
internal TransformContext(IDecompilerTypeSystem typeSystem, DecompileRun decompileRun, ITypeResolveContext decompilationContext, TypeSystemAstBuilder typeSystemAstBuilder)
{
this.TypeSystem = typeSystem;
this.DecompileRun = decompileRun;
this.decompilationContext = decompilationContext;
this.TypeSystemAstBuilder = typeSystemAstBuilder;
this.CancellationToken = decompileRun.CancellationToken;
this.Settings = decompileRun.Settings;
}
}
}
| ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/TransformContext.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/CSharp/Transforms/TransformContext.cs",
"repo_id": "ILSpy",
"token_count": 831
} | 221 |
using System;
using System.Collections.Generic;
using System.Text;
namespace ICSharpCode.Decompiler.DebugInfo
{
public static class KnownGuids
{
public static readonly Guid CSharpLanguageGuid = new Guid("3f5162f8-07c6-11d3-9053-00c04fa302a1");
public static readonly Guid VBLanguageGuid = new Guid("3a12d0b8-c26c-11d0-b442-00a0244a1dd2");
public static readonly Guid FSharpLanguageGuid = new Guid("ab4f38c9-b6e6-43ba-be3b-58080b2ccce3");
// https://github.com/dotnet/roslyn/blob/main/src/Dependencies/CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs
public static readonly Guid StateMachineHoistedLocalScopes = new Guid("6DA9A61E-F8C7-4874-BE62-68BC5630DF71");
public static readonly Guid DynamicLocalVariables = new Guid("83C563C4-B4F3-47D5-B824-BA5441477EA8");
public static readonly Guid DefaultNamespaces = new Guid("58b2eab6-209f-4e4e-a22c-b2d0f910c782");
public static readonly Guid EditAndContinueLocalSlotMap = new Guid("755F52A8-91C5-45BE-B4B8-209571E552BD");
public static readonly Guid EditAndContinueLambdaAndClosureMap = new Guid("A643004C-0240-496F-A783-30D64F4979DE");
public static readonly Guid EncStateMachineStateMap = new Guid("8B78CD68-2EDE-420B-980B-E15884B8AAA3");
public static readonly Guid EmbeddedSource = new Guid("0e8a571b-6926-466e-b4ad-8ab04611f5fe");
public static readonly Guid SourceLink = new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A");
public static readonly Guid MethodSteppingInformation = new Guid("54FD2AC5-E925-401A-9C2A-F94F171072F8");
public static readonly Guid CompilationOptions = new Guid("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8");
public static readonly Guid CompilationMetadataReferences = new Guid("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D");
public static readonly Guid TupleElementNames = new Guid("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710");
public static readonly Guid TypeDefinitionDocuments = new Guid("932E74BC-DBA9-4478-8D46-0F32A7BAB3D3");
public static readonly Guid HashAlgorithmSHA1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460");
public static readonly Guid HashAlgorithmSHA256 = new Guid("8829d00f-11b8-4213-878b-770e8597ac16");
}
}
| ILSpy/ICSharpCode.Decompiler/DebugInfo/KnownGuids.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/DebugInfo/KnownGuids.cs",
"repo_id": "ILSpy",
"token_count": 854
} | 222 |
// Copyright (c) 2022 Tom Englert
//
// 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.Linq;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.Decompiler.Disassembler
{
public class SortByNameProcessor : IEntityProcessor
{
public IReadOnlyCollection<InterfaceImplementationHandle> Process(MetadataFile module,
IReadOnlyCollection<InterfaceImplementationHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<TypeDefinitionHandle> Process(MetadataFile module,
IReadOnlyCollection<TypeDefinitionHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<MethodDefinitionHandle> Process(MetadataFile module,
IReadOnlyCollection<MethodDefinitionHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<PropertyDefinitionHandle> Process(MetadataFile module,
IReadOnlyCollection<PropertyDefinitionHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<EventDefinitionHandle> Process(MetadataFile module,
IReadOnlyCollection<EventDefinitionHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<FieldDefinitionHandle> Process(MetadataFile module,
IReadOnlyCollection<FieldDefinitionHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
public IReadOnlyCollection<CustomAttributeHandle> Process(MetadataFile module,
IReadOnlyCollection<CustomAttributeHandle> items)
{
return items.OrderBy(item => GetSortKey(item, module)).ToArray();
}
private static string GetSortKey(TypeDefinitionHandle handle, MetadataFile module) =>
handle.GetFullTypeName(module.Metadata).ToILNameString();
private static string GetSortKey(MethodDefinitionHandle handle, MetadataFile module)
{
PlainTextOutput output = new PlainTextOutput();
MethodDefinition definition = module.Metadata.GetMethodDefinition(handle);
// Start with the methods name, skip return type
output.Write(module.Metadata.GetString(definition.Name));
DisassemblerSignatureTypeProvider signatureProvider = new DisassemblerSignatureTypeProvider(module, output);
MethodSignature<Action<ILNameSyntax>> signature =
definition.DecodeSignature(signatureProvider, new MetadataGenericContext(handle, module));
if (signature.GenericParameterCount > 0)
{
output.Write($"`{signature.GenericParameterCount}");
}
InstructionOutputExtensions.WriteParameterList(output, signature);
return output.ToString();
}
private static string GetSortKey(InterfaceImplementationHandle handle, MetadataFile module) =>
module.Metadata.GetInterfaceImplementation(handle)
.Interface
.GetFullTypeName(module.Metadata)
.ToILNameString();
private static string GetSortKey(FieldDefinitionHandle handle, MetadataFile module) =>
module.Metadata.GetString(module.Metadata.GetFieldDefinition(handle).Name);
private static string GetSortKey(PropertyDefinitionHandle handle, MetadataFile module) =>
module.Metadata.GetString(module.Metadata.GetPropertyDefinition(handle).Name);
private static string GetSortKey(EventDefinitionHandle handle, MetadataFile module) =>
module.Metadata.GetString(module.Metadata.GetEventDefinition(handle).Name);
private static string GetSortKey(CustomAttributeHandle handle, MetadataFile module) =>
module.Metadata.GetCustomAttribute(handle)
.Constructor
.GetDeclaringType(module.Metadata)
.GetFullTypeName(module.Metadata)
.ToILNameString();
}
} | ILSpy/ICSharpCode.Decompiler/Disassembler/SortByNameProcessor.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Disassembler/SortByNameProcessor.cs",
"repo_id": "ILSpy",
"token_count": 1428
} | 223 |
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for ICSharpCode.Decompiler" Description="Code analysis rules for ICSharpCode.Decompiler.csproj." ToolsVersion="15.0">
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1001" Action="Warning" />
<Rule Id="CA1009" Action="Warning" />
<Rule Id="CA1016" Action="Warning" />
<Rule Id="CA1033" Action="Warning" />
<Rule Id="CA1049" Action="Warning" />
<Rule Id="CA1060" Action="Warning" />
<Rule Id="CA1061" Action="Warning" />
<Rule Id="CA1063" Action="Warning" />
<Rule Id="CA1065" Action="Warning" />
<Rule Id="CA1301" Action="Warning" />
<Rule Id="CA1400" Action="Warning" />
<Rule Id="CA1401" Action="Warning" />
<Rule Id="CA1403" Action="Warning" />
<Rule Id="CA1404" Action="Warning" />
<Rule Id="CA1405" Action="Warning" />
<Rule Id="CA1410" Action="Warning" />
<Rule Id="CA1415" Action="Warning" />
<Rule Id="CA1821" Action="Warning" />
<Rule Id="CA1900" Action="Warning" />
<Rule Id="CA1901" Action="Warning" />
<Rule Id="CA2002" Action="Warning" />
<Rule Id="CA2100" Action="Warning" />
<Rule Id="CA2101" Action="Warning" />
<Rule Id="CA2108" Action="Warning" />
<Rule Id="CA2111" Action="Warning" />
<Rule Id="CA2112" Action="Warning" />
<Rule Id="CA2114" Action="Warning" />
<Rule Id="CA2116" Action="Warning" />
<Rule Id="CA2117" Action="Warning" />
<Rule Id="CA2122" Action="Warning" />
<Rule Id="CA2123" Action="Warning" />
<Rule Id="CA2124" Action="Warning" />
<Rule Id="CA2126" Action="Warning" />
<Rule Id="CA2131" Action="Warning" />
<Rule Id="CA2132" Action="Warning" />
<Rule Id="CA2133" Action="Warning" />
<Rule Id="CA2134" Action="Warning" />
<Rule Id="CA2137" Action="Warning" />
<Rule Id="CA2138" Action="Warning" />
<Rule Id="CA2140" Action="Warning" />
<Rule Id="CA2141" Action="Warning" />
<Rule Id="CA2146" Action="Warning" />
<Rule Id="CA2147" Action="Warning" />
<Rule Id="CA2149" Action="Warning" />
<Rule Id="CA2200" Action="Warning" />
<Rule Id="CA2202" Action="Warning" />
<Rule Id="CA2207" Action="Warning" />
<Rule Id="CA2212" Action="Warning" />
<Rule Id="CA2213" Action="Warning" />
<Rule Id="CA2214" Action="Warning" />
<Rule Id="CA2216" Action="Warning" />
<Rule Id="CA2220" Action="Warning" />
<Rule Id="CA2229" Action="Warning" />
<Rule Id="CA2231" Action="Warning" />
<Rule Id="CA2232" Action="Warning" />
<Rule Id="CA2235" Action="Warning" />
<Rule Id="CA2236" Action="Warning" />
<Rule Id="CA2237" Action="Warning" />
<Rule Id="CA2238" Action="Warning" />
<Rule Id="CA2240" Action="Warning" />
<Rule Id="CA2241" Action="Warning" />
<Rule Id="CA2242" Action="Warning" />
</Rules>
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Features" RuleNamespace="Microsoft.CodeAnalysis.CSharp.Features">
<Rule Id="IDE0017" Action="None" />
</Rules>
<Rules AnalyzerId="RefactoringEssentials" RuleNamespace="RefactoringEssentials">
<Rule Id="CS0126ReturnMustBeFollowedByAnyExpression" Action="None" />
<Rule Id="CS0169FieldIsNeverUsedAnalyzer" Action="None" />
<Rule Id="CS0183ExpressionIsAlwaysOfProvidedTypeAnalyzer" Action="None" />
<Rule Id="CS0618UsageOfObsoleteMemberAnalyzer" Action="None" />
<Rule Id="CS1573ParameterHasNoMatchingParamTagAnalyzer" Action="None" />
<Rule Id="CS1717AssignmentMadeToSameVariableAnalyzer" Action="None" />
<Rule Id="CS1729TypeHasNoConstructorWithNArgumentsAnalyzer" Action="None" />
<Rule Id="InconsistentNaming" Action="None" />
<Rule Id="ProhibitedModifiersAnalyzer" Action="None" />
<Rule Id="RECS0001" Action="Info" />
</Rules>
</RuleSet> | ILSpy/ICSharpCode.Decompiler/ICSharpCode.Decompiler.ruleset/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/ICSharpCode.Decompiler.ruleset",
"repo_id": "ILSpy",
"token_count": 1465
} | 224 |
// 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;
using System.Linq;
using ICSharpCode.Decompiler.CSharp.Transforms;
using ICSharpCode.Decompiler.FlowAnalysis;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.ControlFlow
{
/// <summary>
/// C# switch statements are not necessarily compiled into
/// IL switch instructions (e.g. when the integer values are non-contiguous).
///
/// Detect sequences of conditional branches that all test a single integer value,
/// and simplify them into a ILAst switch instruction (which like C# does not require contiguous values).
/// </summary>
public class SwitchDetection : IILTransform
{
private readonly SwitchAnalysis analysis = new SwitchAnalysis();
private ILTransformContext context;
private BlockContainer currentContainer;
private ControlFlowGraph controlFlowGraph;
private LoopContext loopContext;
/// <summary>
/// When detecting a switch, it is important to distinguish Branch instructions which will
/// eventually decompile to continue; statements.
///
/// A LoopContext is constructed for a node and its dominator tree, as for a Branch to be a continue;
/// statement, it must be contained within the target-loop
///
/// This class also supplies the depth of the loop targetted by a continue; statement relative to the
/// context node, to avoid (or eventually support) labelled continues to outer loops
/// </summary>
public class LoopContext
{
private readonly IDictionary<ControlFlowNode, int> continueDepth = new Dictionary<ControlFlowNode, int>();
public LoopContext(ControlFlowGraph cfg, ControlFlowNode contextNode)
{
var loopHeads = new List<ControlFlowNode>();
void Analyze(ControlFlowNode n)
{
if (n.Visited)
return;
n.Visited = true;
if (n.Dominates(contextNode))
loopHeads.Add(n);
else
n.Successors.ForEach(Analyze);
}
contextNode.Successors.ForEach(Analyze);
ResetVisited(cfg.cfg);
int l = 1;
foreach (var loopHead in loopHeads.OrderBy(n => n.PostOrderNumber))
continueDepth[FindContinue(loopHead)] = l++;
}
private static ControlFlowNode FindContinue(ControlFlowNode loopHead)
{
// potential continue target
var pred = loopHead.Predecessors.OnlyOrDefault(p => p != loopHead && loopHead.Dominates(p));
if (pred == null)
return loopHead;
// match for loop increment block
if (pred.Successors.Count == 1)
{
if (HighLevelLoopTransform.MatchIncrementBlock((Block)pred.UserData, out var target) && target == loopHead.UserData)
return pred;
}
// match do-while condition
if (pred.Successors.Count <= 2)
{
if (HighLevelLoopTransform.MatchDoWhileConditionBlock((Block)pred.UserData, out var t1, out var t2) &&
(t1 == loopHead.UserData || t2 == loopHead.UserData))
return pred;
}
return loopHead;
}
public bool MatchContinue(ControlFlowNode node) => MatchContinue(node, out var _);
public bool MatchContinue(ControlFlowNode node, int depth) =>
MatchContinue(node, out int _depth) && depth == _depth;
public bool MatchContinue(ControlFlowNode node, out int depth) => continueDepth.TryGetValue(node, out depth);
public int GetContinueDepth(ControlFlowNode node) => MatchContinue(node, out var depth) ? depth : 0;
/// <summary>
/// Lists all potential targets for break; statements from a domination tree,
/// assuming the domination tree must be exited via either break; or continue;
///
/// First list all nodes in the dominator tree (excluding continue nodes)
/// Then return the all successors not contained within said tree.
///
/// Note that node will be returned once for each outgoing edge.
/// Labelled continue statements (depth > 1) are counted as break targets
/// </summary>
internal IEnumerable<ControlFlowNode> GetBreakTargets(ControlFlowNode dominator) =>
TreeTraversal.PreOrder(dominator, n => n.DominatorTreeChildren.Where(c => !MatchContinue(c)))
.SelectMany(n => n.Successors)
.Where(n => !dominator.Dominates(n) && !MatchContinue(n, 1));
}
public void Run(ILFunction function, ILTransformContext context)
{
if (!context.Settings.SparseIntegerSwitch)
return;
this.context = context;
analysis.AllowUnreachableCases = context.Settings.RemoveDeadCode;
foreach (var container in function.Descendants.OfType<BlockContainer>())
{
currentContainer = container;
controlFlowGraph = null;
bool blockContainerNeedsCleanup = false;
foreach (var block in container.Blocks)
{
context.CancellationToken.ThrowIfCancellationRequested();
ProcessBlock(block, ref blockContainerNeedsCleanup);
}
if (blockContainerNeedsCleanup)
{
Debug.Assert(container.Blocks.All(b => b.Instructions.Count != 0 || b.IncomingEdgeCount == 0));
// if the original code has an unreachable switch-like condition
// eg. if (i >= 0) { ... } else if (i == 2) { unreachable }
// then the 'i == 2' block head gets consumed and the unreachable code needs deleting
if (context.Settings.RemoveDeadCode)
container.SortBlocks(deleteUnreachableBlocks: true);
else
container.Blocks.RemoveAll(b => b.Instructions.Count == 0);
}
}
}
void ProcessBlock(Block block, ref bool blockContainerNeedsCleanup)
{
bool analysisSuccess = analysis.AnalyzeBlock(block);
if (analysisSuccess && UseCSharpSwitch(out _))
{
// complex multi-block switch that can be combined into a single SwitchInstruction
ILInstruction switchValue = new LdLoc(analysis.SwitchVariable);
Debug.Assert(switchValue.ResultType.IsIntegerType() || switchValue.ResultType == StackType.Unknown);
if (!(switchValue.ResultType == StackType.I4 || switchValue.ResultType == StackType.I8))
{
// switchValue must have a result type of either I4 or I8
switchValue = new Conv(switchValue, PrimitiveType.I8, false, Sign.Signed);
}
var sw = new SwitchInstruction(switchValue);
foreach (var section in analysis.Sections)
{
sw.Sections.Add(new SwitchSection {
Labels = section.Key,
Body = section.Value
});
}
if (block.Instructions.Last() is SwitchInstruction)
{
// we'll replace the switch
}
else
{
Debug.Assert(block.Instructions.SecondToLastOrDefault() is IfInstruction);
// Remove branch/leave after if; it's getting moved into a section.
block.Instructions.RemoveAt(block.Instructions.Count - 1);
}
sw.AddILRange(block.Instructions[block.Instructions.Count - 1]);
block.Instructions[block.Instructions.Count - 1] = sw;
// mark all inner blocks that were converted to the switch statement for deletion
foreach (var innerBlock in analysis.InnerBlocks)
{
Debug.Assert(innerBlock.Parent == block.Parent);
Debug.Assert(innerBlock != ((BlockContainer)block.Parent).EntryPoint);
innerBlock.Instructions.Clear();
}
controlFlowGraph = null; // control flow graph is no-longer valid
blockContainerNeedsCleanup = true;
SortSwitchSections(sw);
}
else
{
// 2nd pass of SimplifySwitchInstruction (after duplicating return blocks),
// (1st pass was in ControlFlowSimplification)
SimplifySwitchInstruction(block, context);
}
}
internal static void SimplifySwitchInstruction(Block block, ILTransformContext context)
{
// due to our of of basic blocks at this point,
// switch instructions can only appear as last insturction
var sw = block.Instructions.LastOrDefault() as SwitchInstruction;
if (sw == null)
return;
// ControlFlowSimplification runs early (before any other control flow transforms).
// Any switch instructions will only have branch instructions in the sections.
// Combine sections with identical branch target:
var dict = new Dictionary<Block, SwitchSection>(); // branch target -> switch section
sw.Sections.RemoveAll(
section => {
if (section.Body.MatchBranch(out Block target))
{
if (dict.TryGetValue(target, out SwitchSection primarySection))
{
primarySection.Labels = primarySection.Labels.UnionWith(section.Labels);
primarySection.HasNullLabel |= section.HasNullLabel;
return true; // remove this section
}
else
{
dict.Add(target, section);
}
}
return false;
});
AdjustLabels(sw, context);
SortSwitchSections(sw);
}
static void SortSwitchSections(SwitchInstruction sw)
{
sw.Sections.ReplaceList(sw.Sections.OrderBy(s => s.Body switch {
Branch b => b.TargetILOffset,
Leave l => l.StartILOffset,
_ => (int?)null
}).ThenBy(s => s.Labels.Values.FirstOrDefault()));
}
static void AdjustLabels(SwitchInstruction sw, ILTransformContext context)
{
if (sw.Value is BinaryNumericInstruction bop && !bop.CheckForOverflow && bop.Right.MatchLdcI(out long val))
{
// Move offset into labels:
context.Step("Move offset into switch labels", bop);
long offset;
switch (bop.Operator)
{
case BinaryNumericOperator.Add:
offset = unchecked(-val);
break;
case BinaryNumericOperator.Sub:
offset = val;
break;
default: // unknown bop.Operator
return;
}
sw.Value = bop.Left;
foreach (var section in sw.Sections)
{
section.Labels = section.Labels.AddOffset(offset);
}
}
}
const ulong MaxValuesPerSection = 100;
/// <summary>
/// Tests whether we should prefer a switch statement over an if statement.
/// </summary>
private bool UseCSharpSwitch(out KeyValuePair<LongSet, ILInstruction> defaultSection)
{
if (!analysis.InnerBlocks.Any())
{
defaultSection = default;
return false;
}
defaultSection = analysis.Sections.FirstOrDefault(s => s.Key.Count() > MaxValuesPerSection);
if (defaultSection.Value == null)
{
// no default section found?
// This should never happen, as we'd need 2^64/MaxValuesPerSection sections to hit this case...
return false;
}
var defaultSectionKey = defaultSection.Key;
if (analysis.Sections.Any(s => !s.Key.SetEquals(defaultSectionKey) && s.Key.Count() > MaxValuesPerSection))
{
// Only the default section is allowed to have tons of keys.
// C# doesn't support "case 1 to 100000000", and we don't want to generate
// gigabytes of case labels.
return false;
}
// good enough indicator that the surrounding code also forms a switch statement
if (analysis.ContainsILSwitch || MatchRoslynSwitchOnString())
return true;
// heuristic to determine if a block would be better represented as an if statement rather than switch
int ifCount = analysis.InnerBlocks.Count + 1;
int intervalCount = analysis.Sections.Where(s => !s.Key.SetEquals(defaultSectionKey)).Sum(s => s.Key.Intervals.Length);
if (ifCount < intervalCount)
return false;
(var flowNodes, var caseNodes) = AnalyzeControlFlow();
// don't create switch statements with only one non-default label when the corresponding condition tree is flat
// it may be important that the switch-like conditions be inlined
// for example, a loop condition: while (c == '\n' || c == '\r')
if (analysis.Sections.Count == 2 && IsSingleCondition(flowNodes, caseNodes))
return false;
// if there is no ILSwitch, there's still many control flow patterns that
// match a switch statement but were originally just regular if statements,
// and converting them to switches results in poor quality code with goto statements
//
// If a single break target cannot be identified, then the equivalent switch statement would require goto statements.
// These goto statements may be "goto case x" or "goto default", but these are a hint that the original code was not a switch,
// and that the switch statement may be very poor quality.
// Thus the rule of thumb is no goto statements if the original code didn't include them
if (SwitchUsesGoto(flowNodes, caseNodes, out var breakBlock))
return false;
// valid switch construction, all code can be inlined
if (breakBlock == null)
return true;
// The switch has a single break target and there is one more hint
// The break target cannot be inlined, and should have the highest IL offset of everything targetted by the switch
return breakBlock.StartILOffset >= analysis.Sections.Select(s => s.Value.MatchBranch(out var b) ? b.StartILOffset : -1).Max();
}
/// <summary>
/// stloc switchValueVar(call ComputeStringHash(switchValue))
/// </summary>
private bool MatchRoslynSwitchOnString()
{
var insns = analysis.RootBlock.Instructions;
return insns.Count >= 3 && SwitchOnStringTransform.MatchComputeStringHashCall(insns[insns.Count - 3], analysis.SwitchVariable, out var switchLdLoc);
}
/// <summary>
/// Builds the control flow graph for the current container (if necessary), establishes loopContext
/// and returns the ControlFlowNodes corresponding to the inner flow and case blocks of the potential switch
/// </summary>
private (List<ControlFlowNode> flowNodes, List<ControlFlowNode> caseNodes) AnalyzeControlFlow()
{
if (controlFlowGraph == null)
controlFlowGraph = new ControlFlowGraph(currentContainer, context.CancellationToken);
var switchHead = controlFlowGraph.GetNode(analysis.RootBlock);
loopContext = new LoopContext(controlFlowGraph, switchHead);
var flowNodes = new List<ControlFlowNode> { switchHead };
flowNodes.AddRange(analysis.InnerBlocks.Select(controlFlowGraph.GetNode));
// grab the control flow nodes for blocks targetted by each section
var caseNodes = new List<ControlFlowNode>();
foreach (var s in analysis.Sections)
{
if (!s.Value.MatchBranch(out var block))
continue;
if (block.Parent == currentContainer)
{
var node = controlFlowGraph.GetNode(block);
if (!loopContext.MatchContinue(node))
caseNodes.Add(node);
}
}
AddNullCase(flowNodes, caseNodes);
Debug.Assert(flowNodes.SelectMany(n => n.Successors)
.All(n => flowNodes.Contains(n) || caseNodes.Contains(n) || loopContext.MatchContinue(n)));
return (flowNodes, caseNodes);
}
/// <summary>
/// Determines if the analysed switch can be constructed without any gotos
/// </summary>
private bool SwitchUsesGoto(List<ControlFlowNode> flowNodes, List<ControlFlowNode> caseNodes, out Block breakBlock)
{
// cases with predecessors that aren't part of the switch logic
// must either require "goto case" statements, or consist of a single "break;"
var externalCases = caseNodes.Where(c => c.Predecessors.Any(n => !flowNodes.Contains(n))).ToList();
breakBlock = null;
if (externalCases.Count > 1)
return true; // cannot have more than one break case without gotos
// check that case nodes flow through a single point
var breakTargets = caseNodes.Except(externalCases).SelectMany(n => loopContext.GetBreakTargets(n)).ToHashSet();
// if there are multiple break targets, then gotos are required
// if there are none, then the external case (if any) can be the break target
if (breakTargets.Count != 1)
return breakTargets.Count > 1;
breakBlock = (Block)breakTargets.Single().UserData;
// external case must consist of a single "break;"
return externalCases.Count == 1 && breakBlock != externalCases.Single().UserData;
}
/// <summary>
/// Does some of the analysis of SwitchOnNullableTransform to add the null case control flow
/// to the results of SwitchAnalysis
/// </summary>
private void AddNullCase(List<ControlFlowNode> flowNodes, List<ControlFlowNode> caseNodes)
{
if (analysis.RootBlock.IncomingEdgeCount != 1)
return;
// if (comp(logic.not(call get_HasValue(ldloca nullableVar))) br NullCase
// br RootBlock
var nullableBlock = (Block)controlFlowGraph.GetNode(analysis.RootBlock).Predecessors.SingleOrDefault()?.UserData;
if (nullableBlock == null ||
nullableBlock.Instructions.Count < 2 ||
!nullableBlock.Instructions.Last().MatchBranch(analysis.RootBlock) ||
!nullableBlock.Instructions.SecondToLastOrDefault().MatchIfInstruction(out var cond, out var trueInst) ||
!cond.MatchLogicNot(out var getHasValue) ||
!NullableLiftingTransform.MatchHasValueCall(getHasValue, out ILInstruction nullableInst))
return;
// could check that nullableInst is ldloc or ldloca and that the switch variable matches a GetValueOrDefault
// but the effect of adding an incorrect block to the flowBlock list would only be disasterous if it branched directly
// to a candidate case block
// must branch to a case label, otherwise we can proceed fine and let SwitchOnNullableTransform do all the work
if (!trueInst.MatchBranch(out var nullBlock) || !caseNodes.Exists(n => n.UserData == nullBlock))
return;
//add the null case logic to the incoming flow blocks
flowNodes.Add(controlFlowGraph.GetNode(nullableBlock));
}
/// <summary>
/// Pattern matching for short circuit expressions
/// p
/// |\
/// | n
/// |/ \
/// s c
///
/// where
/// p: if (a) goto n; goto s;
/// n: if (b) goto c; goto s;
///
/// Can simplify to
/// p|n
/// / \
/// s c
///
/// where:
/// p|n: if (a && b) goto c; goto s;
///
/// Note that if n has only 1 successor, but is still a flow node, then a short circuit expression
/// has a target (c) with no corresponding block (leave)
/// </summary>
/// <param name="parent">A node with 2 successors</param>
/// <param name="side">The successor index to consider n (the other successor will be the common sibling)</param>
private static bool IsShortCircuit(ControlFlowNode parent, int side)
{
var node = parent.Successors[side];
var sibling = parent.Successors[side ^ 1];
if (!IsFlowNode(node) || node.Successors.Count > 2 || node.Predecessors.Count != 1)
return false;
return node.Successors.Contains(sibling);
}
/// <summary>
/// A flow node contains only two instructions, the first of which is an IfInstruction
/// A short circuit expression is comprised of a root block ending in an IfInstruction and one or more flow nodes
/// </summary>
static bool IsFlowNode(ControlFlowNode n) => ((Block)n.UserData).Instructions.FirstOrDefault() is IfInstruction;
/// <summary>
/// Determines whether the flowNodes are can be reduced to a single condition via short circuit operators
/// </summary>
private bool IsSingleCondition(List<ControlFlowNode> flowNodes, List<ControlFlowNode> caseNodes)
{
if (flowNodes.Count == 1)
return true;
var rootNode = controlFlowGraph.GetNode(analysis.RootBlock);
rootNode.Visited = true;
// search down the tree, marking nodes as visited while they continue the current condition
var n = rootNode;
while (n.Successors.Count > 0 && (n == rootNode || IsFlowNode(n)))
{
if (n.Successors.Count == 1)
{
// if there is more than one case node, then a flow node with only one successor is not part of the initial condition
if (caseNodes.Count > 1)
break;
n = n.Successors[0];
}
else
{ // 2 successors
if (IsShortCircuit(n, 0))
n = n.Successors[0];
else if (IsShortCircuit(n, 1))
n = n.Successors[1];
else
break;
}
n.Visited = true;
if (loopContext.MatchContinue(n))
break;
}
var ret = flowNodes.All(f => f.Visited);
ResetVisited(controlFlowGraph.cfg);
return ret;
}
private static void ResetVisited(IEnumerable<ControlFlowNode> nodes)
{
foreach (var n in nodes)
n.Visited = false;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs",
"repo_id": "ILSpy",
"token_count": 7092
} | 225 |
#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;
namespace ICSharpCode.Decompiler.IL
{
/// <summary>
/// Unconditional branch. <c>goto target;</c>
/// </summary>
/// <remarks>
/// When jumping to the entrypoint of the current block container, the branch represents a <c>continue</c> statement.
/// </remarks>
partial class Branch : SimpleInstruction, IBranchOrLeaveInstruction
{
readonly int targetILOffset;
Block? targetBlock;
public Branch(int targetILOffset) : base(OpCode.Branch)
{
this.targetILOffset = targetILOffset;
}
public Branch(Block targetBlock) : base(OpCode.Branch)
{
this.targetBlock = targetBlock ?? throw new ArgumentNullException(nameof(targetBlock));
this.targetILOffset = targetBlock.StartILOffset;
}
public int TargetILOffset {
get { return targetBlock != null ? targetBlock.StartILOffset : targetILOffset; }
}
public Block TargetBlock {
get {
// HACK: We treat TargetBlock as non-nullable publicly, because it's only null inside
// the ILReader, and becomes non-null once the BlockBuilder has run.
return targetBlock!;
}
set {
if (targetBlock != null && IsConnected)
targetBlock.IncomingEdgeCount--;
targetBlock = value;
if (targetBlock != null && IsConnected)
targetBlock.IncomingEdgeCount++;
}
}
/// <summary>
/// Gets the BlockContainer that contains the target block.
/// </summary>
public BlockContainer TargetContainer {
get { return (BlockContainer)targetBlock?.Parent!; }
}
protected override void Connected()
{
base.Connected();
if (targetBlock != null)
targetBlock.IncomingEdgeCount++;
}
protected override void Disconnected()
{
base.Disconnected();
if (targetBlock != null)
targetBlock.IncomingEdgeCount--;
}
public string TargetLabel {
get { return targetBlock != null ? targetBlock.Label : string.Format("IL_{0:x4}", TargetILOffset); }
}
/// <summary>
/// Gets whether this branch executes at least one finally block before jumping to the target block.
/// </summary>
public bool TriggersFinallyBlock {
get {
return GetExecutesFinallyBlock(this, TargetContainer);
}
}
internal static bool GetExecutesFinallyBlock(ILInstruction? inst, BlockContainer? container)
{
for (; inst != container && inst != null; inst = inst.Parent)
{
if (inst.Parent is TryFinally && inst.SlotInfo == TryFinally.TryBlockSlot)
return true;
}
return false;
}
internal override void CheckInvariant(ILPhase phase)
{
base.CheckInvariant(phase);
if (phase > ILPhase.InILReader)
{
Debug.Assert(targetBlock?.Parent is BlockContainer);
Debug.Assert(this.IsDescendantOf(targetBlock!.Parent!));
Debug.Assert(targetBlock!.Parent!.Children[targetBlock.ChildIndex] == targetBlock);
}
}
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write(OpCode);
output.Write(' ');
output.WriteLocalReference(TargetLabel, (object?)targetBlock ?? TargetILOffset);
}
}
interface IBranchOrLeaveInstruction
{
BlockContainer TargetContainer { get; }
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/Branch.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/Branch.cs",
"repo_id": "ILSpy",
"token_count": 1372
} | 226 |
#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.Diagnostics;
namespace ICSharpCode.Decompiler.IL
{
public sealed partial class LdFlda
{
internal override void CheckInvariant(ILPhase phase)
{
base.CheckInvariant(phase);
switch (field.DeclaringType.IsReferenceType)
{
case true:
Debug.Assert(target.ResultType == StackType.O,
"Class fields can only be accessed with an object on the stack");
break;
case false:
Debug.Assert(target.ResultType == StackType.I || target.ResultType == StackType.Ref,
"Struct fields can only be accessed with a pointer on the stack");
break;
case null:
// field of unresolved type
Debug.Assert(target.ResultType == StackType.O || target.ResultType == StackType.I
|| target.ResultType == StackType.Ref || target.ResultType == StackType.Unknown,
"Field of unresolved type with invalid target");
break;
}
}
}
public sealed partial class StObj
{
/// <summary>
/// For a store to a field or array element, C# will only throw NullReferenceException/IndexOfBoundsException
/// after the value-to-be-stored has been computed.
/// This means a LdFlda/LdElema used as target for StObj must have DelayExceptions==true to allow a translation to C#
/// without changing the program semantics. See https://github.com/icsharpcode/ILSpy/issues/2050
/// </summary>
public bool CanInlineIntoTargetSlot(ILInstruction inst)
{
switch (inst.OpCode)
{
case OpCode.LdElema:
case OpCode.LdFlda:
Debug.Assert(inst.HasDirectFlag(InstructionFlags.MayThrow));
// If the ldelema/ldflda may throw a non-delayed exception, inlining will cause it
// to turn into a delayed exception after the translation to C#.
// This is only valid if the value computation doesn't involve any side effects.
return SemanticHelper.IsPure(this.Value.Flags);
// Note that after inlining such a ldelema/ldflda, the normal inlining rules will
// prevent us from inlining an effectful instruction into the value slot.
default:
return true;
}
}
/// <summary>
/// called as part of CheckInvariant()
/// </summary>
void CheckTargetSlot()
{
switch (this.Target.OpCode)
{
case OpCode.LdElema:
case OpCode.LdFlda:
if (this.Target.HasDirectFlag(InstructionFlags.MayThrow))
{
Debug.Assert(SemanticHelper.IsPure(this.Value.Flags));
}
break;
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Instructions/LdFlda.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Instructions/LdFlda.cs",
"repo_id": "ILSpy",
"token_count": 1181
} | 227 |
// Copyright (c) 2017 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 ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL.Transforms
{
public class DetectCatchWhenConditionBlocks : IILTransform
{
public void Run(ILFunction function, ILTransformContext context)
{
foreach (var catchBlock in function.Descendants.OfType<TryCatchHandler>())
{
if (catchBlock.Filter is BlockContainer container
&& MatchCatchWhenEntryPoint(catchBlock.Variable, container, container.EntryPoint,
out var exceptionType, out var exceptionSlot, out var whenConditionBlock)
&& exceptionType.GetStackType() == catchBlock.Variable.StackType)
{
// set exceptionType
catchBlock.Variable.Type = exceptionType;
// Block entryPoint (incoming: 1) {
// stloc temp(isinst exceptionType(ldloc exceptionVar))
// if (comp(ldloc temp != ldnull)) br whenConditionBlock
// br falseBlock
// }
// =>
// Block entryPoint (incoming: 1) {
// stloc temp(ldloc exceptionSlot)
// br whenConditionBlock
// }
var instructions = container.EntryPoint.Instructions;
if (instructions.Count == 3)
{
// stloc temp(isinst exceptionType(ldloc exceptionVar))
// if (comp(ldloc temp != ldnull)) br whenConditionBlock
// br falseBlock
context.Step($"Detected catch-when for {catchBlock.Variable.Name} (extra store)", instructions[0]);
((StLoc)instructions[0]).Value = exceptionSlot;
instructions[1].ReplaceWith(new Branch(whenConditionBlock));
instructions.RemoveAt(2);
container.SortBlocks(deleteUnreachableBlocks: true);
}
else if (instructions.Count == 2)
{
// if (comp(isinst exceptionType(ldloc exceptionVar) != ldnull)) br whenConditionBlock
// br falseBlock
context.Step($"Detected catch-when for {catchBlock.Variable.Name}", instructions[0]);
instructions[0].ReplaceWith(new Branch(whenConditionBlock));
instructions.RemoveAt(1);
container.SortBlocks(deleteUnreachableBlocks: true);
}
PropagateExceptionVariable(context, catchBlock);
}
}
}
/// <summary>
/// catch E_189 : 0200007C System.Exception when (BlockContainer {
/// Block IL_0079 (incoming: 1) {
/// stloc S_30(ldloc E_189)
/// br IL_0085
/// }
///
/// Block IL_0085 (incoming: 1) {
/// stloc I_1(ldloc S_30)
/// where S_30 and I_1 are single definition
/// =>
/// copy-propagate E_189 to replace all uses of S_30 and I_1
/// </summary>
static void PropagateExceptionVariable(ILTransformContext context, TryCatchHandler handler)
{
var exceptionVariable = handler.Variable;
if (!exceptionVariable.IsSingleDefinition)
return;
context.StepStartGroup(nameof(PropagateExceptionVariable));
int i = 0;
while (i < exceptionVariable.LoadInstructions.Count)
{
var load = exceptionVariable.LoadInstructions[i];
if (!load.IsDescendantOf(handler))
{
i++;
continue;
}
// We are only interested in store "statements" copying the exception variable
// without modifying it.
var statement = LocalFunctionDecompiler.GetStatement(load);
if (!(statement is StLoc stloc))
{
i++;
continue;
}
// simple copy case:
// stloc b(ldloc a)
if (stloc.Value == load)
{
PropagateExceptionInstance(stloc);
}
// if the type of the cast-class instruction matches the exceptionType,
// this cast can be removed without losing any side-effects.
// Note: this would also hold true iff exceptionType were an exception derived
// from cc.Type, however, we are more restrictive to match the pattern exactly.
// stloc b(castclass exceptionType(ldloc a))
else if (stloc.Value is CastClass cc && cc.Type.Equals(exceptionVariable.Type) && cc.Argument == load)
{
stloc.Value = load;
PropagateExceptionInstance(stloc);
}
else
{
i++;
}
void PropagateExceptionInstance(StLoc store)
{
foreach (var load in store.Variable.LoadInstructions.ToArray())
{
if (!load.IsDescendantOf(handler))
continue;
load.ReplaceWith(new LdLoc(exceptionVariable).WithILRange(load));
}
if (store.Variable.LoadCount == 0 && store.Parent is Block block)
{
block.Instructions.RemoveAt(store.ChildIndex);
}
else
{
i++;
}
}
}
context.StepEndGroup(keepIfEmpty: false);
}
/// <summary>
/// Block entryPoint (incoming: 1) {
/// stloc temp(isinst exceptionType(ldloc exceptionVar))
/// if (comp(ldloc temp != ldnull)) br whenConditionBlock
/// br falseBlock
/// }
/// </summary>
bool MatchCatchWhenEntryPoint(ILVariable exceptionVar, BlockContainer container, Block entryPoint, out IType exceptionType, out ILInstruction exceptionSlot, out Block whenConditionBlock)
{
exceptionType = null;
exceptionSlot = null;
whenConditionBlock = null;
if (entryPoint == null || entryPoint.IncomingEdgeCount != 1)
return false;
if (entryPoint.Instructions.Count == 3)
{
// stloc temp(isinst exceptionType(ldloc exceptionVar))
// if (comp(ldloc temp != ldnull)) br whenConditionBlock
// br falseBlock
if (!entryPoint.Instructions[0].MatchStLoc(out var temp, out var isinst) ||
temp.Kind != VariableKind.StackSlot || !isinst.MatchIsInst(out exceptionSlot, out exceptionType))
return false;
if (!exceptionSlot.MatchLdLoc(exceptionVar))
return false;
if (!entryPoint.Instructions[1].MatchIfInstruction(out var condition, out var branch))
return false;
if (!condition.MatchCompNotEquals(out var left, out var right))
return false;
if (!entryPoint.Instructions[2].MatchBranch(out var falseBlock) || !MatchFalseBlock(container, falseBlock, out var returnVar, out var exitBlock))
return false;
if ((left.MatchLdNull() && right.MatchLdLoc(temp)) || (right.MatchLdNull() && left.MatchLdLoc(temp)))
{
return branch.MatchBranch(out whenConditionBlock);
}
}
else if (entryPoint.Instructions.Count == 2)
{
// if (comp(isinst exceptionType(ldloc exceptionVar) != ldnull)) br whenConditionBlock
// br falseBlock
if (!entryPoint.Instructions[0].MatchIfInstruction(out var condition, out var branch))
return false;
if (!condition.MatchCompNotEquals(out var left, out var right))
return false;
if (!entryPoint.Instructions[1].MatchBranch(out var falseBlock) || !MatchFalseBlock(container, falseBlock, out var returnVar, out var exitBlock))
return false;
if (!left.MatchIsInst(out exceptionSlot, out exceptionType))
return false;
if (!exceptionSlot.MatchLdLoc(exceptionVar))
return false;
if (right.MatchLdNull())
{
return branch.MatchBranch(out whenConditionBlock);
}
}
return false;
}
/// <summary>
/// Block falseBlock (incoming: 1) {
/// stloc returnVar(ldc.i4 0)
/// br exitBlock
/// }
/// </summary>
bool MatchFalseBlock(BlockContainer container, Block falseBlock, out ILVariable returnVar, out Block exitBlock)
{
returnVar = null;
exitBlock = null;
if (falseBlock.IncomingEdgeCount != 1 || falseBlock.Instructions.Count != 2)
return false;
return falseBlock.Instructions[0].MatchStLoc(out returnVar, out var zero) &&
zero.MatchLdcI4(0) && falseBlock.Instructions[1].MatchBranch(out exitBlock) &&
MatchExitBlock(container, exitBlock, returnVar);
}
/// <summary>
/// Block exitBlock(incoming: 2) {
/// leave container(ldloc returnVar)
/// }
/// </summary>
bool MatchExitBlock(BlockContainer container, Block exitBlock, ILVariable returnVar)
{
if (exitBlock.IncomingEdgeCount != 2 || exitBlock.Instructions.Count != 1)
return false;
return exitBlock.Instructions[0].MatchLeave(container, out var value) &&
value.MatchLdLoc(returnVar);
}
}
} | ILSpy/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/DetectCatchWhenConditionBlocks.cs",
"repo_id": "ILSpy",
"token_count": 3278
} | 228 |
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL.Transforms
{
/// <summary>
/// Exception thrown when an IL transform runs into the <see cref="Stepper.StepLimit"/>.
/// </summary>
public class StepLimitReachedException : Exception
{
}
/// <summary>
/// Helper class that manages recording transform steps.
/// </summary>
public class Stepper
{
/// <summary>
/// Gets whether stepping of built-in transforms is supported in this build of ICSharpCode.Decompiler.
/// Usually only debug builds support transform stepping.
/// </summary>
public static bool SteppingAvailable {
get {
#if STEP
return true;
#else
return false;
#endif
}
}
public IList<Node> Steps => steps;
public int StepLimit { get; set; } = int.MaxValue;
public bool IsDebug { get; set; }
public class Node
{
public string Description { get; }
public ILInstruction? Position { get; set; }
/// <summary>
/// BeginStep is inclusive.
/// </summary>
public int BeginStep { get; set; }
/// <summary>
/// EndStep is exclusive.
/// </summary>
public int EndStep { get; set; }
public IList<Node> Children { get; } = new List<Node>();
public Node(string description)
{
Description = description;
}
}
readonly Stack<Node> groups;
readonly IList<Node> steps;
int step = 0;
public Stepper()
{
steps = new List<Node>();
groups = new Stack<Node>();
}
/// <summary>
/// Call this method immediately before performing a transform step.
/// Used for debugging the IL transforms. Has no effect in release mode.
///
/// May throw <see cref="StepLimitReachedException"/> in debug mode.
/// </summary>
public void Step(string description, ILInstruction? near = null)
{
StepInternal(description, near);
}
private Node StepInternal(string description, ILInstruction? near)
{
if (step == StepLimit)
{
if (IsDebug)
Debugger.Break();
else
throw new StepLimitReachedException();
}
var stepNode = new Node($"{step}: {description}") {
Position = near,
BeginStep = step,
EndStep = step + 1
};
var p = groups.PeekOrDefault();
if (p != null)
p.Children.Add(stepNode);
else
steps.Add(stepNode);
step++;
return stepNode;
}
public void StartGroup(string description, ILInstruction? near = null)
{
groups.Push(StepInternal(description, near));
}
public void EndGroup(bool keepIfEmpty = false)
{
var node = groups.Pop();
if (!keepIfEmpty && node.Children.Count == 0)
{
var col = groups.PeekOrDefault()?.Children ?? steps;
Debug.Assert(col.Last() == node);
col.RemoveAt(col.Count - 1);
}
node.EndStep = step;
}
}
}
| ILSpy/ICSharpCode.Decompiler/IL/Transforms/Stepper.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/IL/Transforms/Stepper.cs",
"repo_id": "ILSpy",
"token_count": 1322
} | 229 |
// 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text.RegularExpressions;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.Metadata
{
public static class DotNetCorePathFinderExtensions
{
static readonly string PathPattern =
@"(Reference Assemblies[/\\]Microsoft[/\\]Framework[/\\](?<type>.NETFramework)[/\\]v(?<version>[^/\\]+)[/\\])" +
@"|((?<type>Microsoft\.NET)[/\\]assembly[/\\]GAC_(MSIL|32|64)[/\\])" +
@"|((?<type>Microsoft\.NET)[/\\]Framework(64)?[/\\](?<version>[^/\\]+)[/\\])" +
@"|(NuGetFallbackFolder[/\\](?<type>[^/\\]+)\\(?<version>[^/\\]+)([/\\].*)?[/\\]ref[/\\])" +
@"|(shared[/\\](?<type>[^/\\]+)\\(?<version>[^/\\]+)([/\\].*)?[/\\])" +
@"|(packs[/\\](?<type>[^/\\]+)\\(?<version>[^/\\]+)\\ref([/\\].*)?[/\\])";
static readonly string RefPathPattern =
@"(Reference Assemblies[/\\]Microsoft[/\\]Framework[/\\](?<type>.NETFramework)[/\\]v(?<version>[^/\\]+)[/\\])" +
@"|(NuGetFallbackFolder[/\\](?<type>[^/\\]+)\\(?<version>[^/\\]+)([/\\].*)?[/\\]ref[/\\])" +
@"|(packs[/\\](?<type>[^/\\]+)\\(?<version>[^/\\]+)\\ref([/\\].*)?[/\\])";
public static string DetectTargetFrameworkId(this PEFile assembly)
{
return DetectTargetFrameworkId(assembly.Metadata, assembly.FileName);
}
public static string DetectTargetFrameworkId(this MetadataReader metadata, string assemblyPath = null)
{
if (metadata == null)
throw new ArgumentNullException(nameof(metadata));
const string TargetFrameworkAttributeName = "System.Runtime.Versioning.TargetFrameworkAttribute";
foreach (var h in metadata.GetCustomAttributes(Handle.AssemblyDefinition))
{
try
{
var attribute = metadata.GetCustomAttribute(h);
if (attribute.GetAttributeType(metadata).GetFullTypeName(metadata).ToString() != TargetFrameworkAttributeName)
continue;
var blobReader = metadata.GetBlobReader(attribute.Value);
if (blobReader.ReadUInt16() == 0x0001)
{
return blobReader.ReadSerializedString()?.Replace(" ", "");
}
}
catch (BadImageFormatException)
{
// ignore malformed attributes
}
}
if (metadata.IsAssembly)
{
AssemblyDefinition assemblyDefinition = metadata.GetAssemblyDefinition();
switch (metadata.GetString(assemblyDefinition.Name))
{
case "mscorlib":
return $".NETFramework,Version=v{assemblyDefinition.Version.ToString(2)}";
case "netstandard":
return $".NETStandard,Version=v{assemblyDefinition.Version.ToString(2)}";
}
}
foreach (var h in metadata.AssemblyReferences)
{
try
{
var r = metadata.GetAssemblyReference(h);
if (r.PublicKeyOrToken.IsNil)
continue;
string version;
switch (metadata.GetString(r.Name))
{
case "netstandard":
version = r.Version.ToString(2);
return $".NETStandard,Version=v{version}";
case "System.Runtime":
// System.Runtime.dll uses the following scheme:
// 4.2.0 => .NET Core 2.0
// 4.2.1 => .NET Core 2.1 / 3.0
// 4.2.2 => .NET Core 3.1
if (r.Version >= new Version(4, 2, 0))
{
version = "2.0";
if (r.Version >= new Version(4, 2, 1))
{
version = "3.0";
}
if (r.Version >= new Version(4, 2, 2))
{
version = "3.1";
}
return $".NETCoreApp,Version=v{version}";
}
else
{
continue;
}
case "mscorlib":
version = r.Version.ToString(2);
return $".NETFramework,Version=v{version}";
}
}
catch (BadImageFormatException)
{
// ignore malformed references
}
}
// Optionally try to detect target version through assembly path as a fallback (use case: reference assemblies)
if (assemblyPath != null)
{
/*
* Detected path patterns (examples):
*
* - .NETFramework -> C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\mscorlib.dll
* - .NETCore -> C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.1.0\ref\netcoreapp2.1\System.Console.dll
* - .NETStandard -> C:\Program Files\dotnet\sdk\NuGetFallbackFolder\netstandard.library\2.0.3\build\netstandard2.0\ref\netstandard.dll
*/
var pathMatch = Regex.Match(assemblyPath, PathPattern,
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
string version;
if (pathMatch.Success)
{
var type = pathMatch.Groups["type"].Value;
version = pathMatch.Groups["version"].Value;
if (string.IsNullOrEmpty(version))
version = metadata.MetadataVersion;
if (string.IsNullOrEmpty(version))
version = "4.0";
version = version.TrimStart('v');
if (type == "Microsoft.NET" || type == ".NETFramework")
{
return $".NETFramework,Version=v{version.Substring(0, Math.Min(3, version.Length))}";
}
else if (type.IndexOf("netcore", StringComparison.OrdinalIgnoreCase) >= 0)
{
return $".NETCoreApp,Version=v{version}";
}
else if (type.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) >= 0)
{
return $".NETStandard,Version=v{version}";
}
}
else
{
version = metadata.MetadataVersion;
if (string.IsNullOrEmpty(version))
version = "4.0";
version = version.TrimStart('v');
return $".NETFramework,Version=v{version.Substring(0, Math.Min(3, version.Length))}";
}
}
return string.Empty;
}
public static bool IsReferenceAssembly(this PEFile assembly)
{
return IsReferenceAssembly(assembly.Reader, assembly.FileName);
}
public static bool IsReferenceAssembly(this PEReader assembly, string assemblyPath)
{
if (assembly == null)
throw new ArgumentNullException(nameof(assembly));
var metadata = assembly.GetMetadataReader();
if (metadata.GetCustomAttributes(Handle.AssemblyDefinition).HasKnownAttribute(metadata, KnownAttribute.ReferenceAssembly))
return true;
// Try to detect reference assembly through specific path pattern
var refPathMatch = Regex.Match(assemblyPath, RefPathPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
return refPathMatch.Success;
}
public static string DetectRuntimePack(this PEFile assembly)
{
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
var metadata = assembly.Metadata;
foreach (var r in metadata.AssemblyReferences)
{
var reference = metadata.GetAssemblyReference(r);
if (reference.PublicKeyOrToken.IsNil)
continue;
if (metadata.StringComparer.Equals(reference.Name, "WindowsBase"))
{
return "Microsoft.WindowsDesktop.App";
}
if (metadata.StringComparer.Equals(reference.Name, "PresentationFramework"))
{
return "Microsoft.WindowsDesktop.App";
}
if (metadata.StringComparer.Equals(reference.Name, "PresentationCore"))
{
return "Microsoft.WindowsDesktop.App";
}
// TODO add support for ASP.NET Core
}
return "Microsoft.NETCore.App";
}
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/DotNetCorePathFinderExtensions.cs",
"repo_id": "ILSpy",
"token_count": 3206
} | 230 |
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography;
using System.Text;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
using SRM = System.Reflection.Metadata;
namespace ICSharpCode.Decompiler.Metadata
{
public static class MetadataExtensions
{
static string CalculatePublicKeyToken(BlobHandle blob, MetadataReader reader)
{
// Calculate public key token:
// 1. hash the public key (always use SHA1).
byte[] publicKeyTokenBytes = SHA1.Create().ComputeHash(reader.GetBlobBytes(blob));
// 2. take the last 8 bytes
// 3. according to Cecil we need to reverse them, other sources did not mention this.
return publicKeyTokenBytes.TakeLast(8).Reverse().ToHexString(8);
}
public static string GetPublicKeyToken(this MetadataReader reader)
{
if (!reader.IsAssembly)
return string.Empty;
var asm = reader.GetAssemblyDefinition();
string publicKey = "null";
if (!asm.PublicKey.IsNil)
{
// AssemblyFlags.PublicKey does not apply to assembly definitions
publicKey = CalculatePublicKeyToken(asm.PublicKey, reader);
}
return publicKey;
}
public static string GetFullAssemblyName(this MetadataReader reader)
{
if (!reader.IsAssembly)
return string.Empty;
var asm = reader.GetAssemblyDefinition();
string publicKey = reader.GetPublicKeyToken();
return $"{reader.GetString(asm.Name)}, " +
$"Version={asm.Version}, " +
$"Culture={(asm.Culture.IsNil ? "neutral" : reader.GetString(asm.Culture))}, " +
$"PublicKeyToken={publicKey}";
}
public static bool TryGetFullAssemblyName(this MetadataReader reader, out string assemblyName)
{
try
{
assemblyName = GetFullAssemblyName(reader);
return true;
}
catch (BadImageFormatException)
{
assemblyName = null;
return false;
}
}
public static string GetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader)
{
StringBuilder builder = new StringBuilder();
builder.Append(reader.GetString(reference.Name));
builder.Append(", Version=");
builder.Append(reference.Version);
builder.Append(", Culture=");
if (reference.Culture.IsNil)
{
builder.Append("neutral");
}
else
{
builder.Append(reader.GetString(reference.Culture));
}
if (reference.PublicKeyOrToken.IsNil)
{
builder.Append(", PublicKeyToken=null");
}
else if ((reference.Flags & AssemblyFlags.PublicKey) != 0)
{
builder.Append(", PublicKeyToken=");
builder.Append(CalculatePublicKeyToken(reference.PublicKeyOrToken, reader));
}
else
{
builder.Append(", PublicKeyToken=");
builder.AppendHexString(reader.GetBlobReader(reference.PublicKeyOrToken));
}
if ((reference.Flags & AssemblyFlags.Retargetable) != 0)
{
builder.Append(", Retargetable=true");
}
return builder.ToString();
}
public static bool TryGetFullAssemblyName(this SRM.AssemblyReference reference, MetadataReader reader, out string assemblyName)
{
try
{
assemblyName = GetFullAssemblyName(reference, reader);
return true;
}
catch (BadImageFormatException)
{
assemblyName = null;
return false;
}
}
public static string ToHexString(this IEnumerable<byte> bytes, int estimatedLength)
{
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
StringBuilder sb = new StringBuilder(estimatedLength * 2);
foreach (var b in bytes)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
public static void AppendHexString(this StringBuilder builder, BlobReader reader)
{
for (int i = 0; i < reader.Length; i++)
{
builder.AppendFormat("{0:x2}", reader.ReadByte());
}
}
public static string ToHexString(this BlobReader reader)
{
StringBuilder sb = new StringBuilder(reader.Length * 3);
for (int i = 0; i < reader.Length; i++)
{
if (i == 0)
sb.AppendFormat("{0:X2}", reader.ReadByte());
else
sb.AppendFormat("-{0:X2}", reader.ReadByte());
}
return sb.ToString();
}
public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypeDefinitions(this MetadataReader reader)
{
foreach (var handle in reader.TypeDefinitions)
{
var td = reader.GetTypeDefinition(handle);
if (td.GetDeclaringType().IsNil)
yield return handle;
}
}
public static string ToILNameString(this FullTypeName typeName, bool omitGenerics = false)
{
string name;
if (typeName.IsNested)
{
name = typeName.Name;
if (!omitGenerics)
{
int localTypeParameterCount = typeName.GetNestedTypeAdditionalTypeParameterCount(typeName.NestingLevel - 1);
if (localTypeParameterCount > 0)
name += "`" + localTypeParameterCount;
}
name = Disassembler.DisassemblerHelpers.Escape(name);
return $"{typeName.GetDeclaringType().ToILNameString(omitGenerics)}/{name}";
}
if (!string.IsNullOrEmpty(typeName.TopLevelTypeName.Namespace))
{
name = $"{typeName.TopLevelTypeName.Namespace}.{typeName.Name}";
if (!omitGenerics && typeName.TypeParameterCount > 0)
name += "`" + typeName.TypeParameterCount;
}
else
{
name = typeName.Name;
if (!omitGenerics && typeName.TypeParameterCount > 0)
name += "`" + typeName.TypeParameterCount;
}
return Disassembler.DisassemblerHelpers.Escape(name);
}
[Obsolete("Use MetadataModule.GetDeclaringModule() instead")]
public static IModuleReference GetDeclaringModule(this TypeReferenceHandle handle, MetadataReader reader)
{
var tr = reader.GetTypeReference(handle);
switch (tr.ResolutionScope.Kind)
{
case HandleKind.TypeReference:
return ((TypeReferenceHandle)tr.ResolutionScope).GetDeclaringModule(reader);
case HandleKind.AssemblyReference:
var asmRef = reader.GetAssemblyReference((AssemblyReferenceHandle)tr.ResolutionScope);
return new DefaultAssemblyReference(reader.GetString(asmRef.Name));
case HandleKind.ModuleReference:
var modRef = reader.GetModuleReference((ModuleReferenceHandle)tr.ResolutionScope);
return new DefaultAssemblyReference(reader.GetString(modRef.Name));
default:
return DefaultAssemblyReference.CurrentAssembly;
}
}
internal static readonly TypeProvider minimalCorlibTypeProvider =
new TypeProvider(new SimpleCompilation(MinimalCorlib.Instance));
/// <summary>
/// An attribute type provider that can be used to decode attribute signatures
/// that only mention built-in types.
/// </summary>
public static ICustomAttributeTypeProvider<IType> MinimalAttributeTypeProvider {
get => minimalCorlibTypeProvider;
}
public static ISignatureTypeProvider<IType, TypeSystem.GenericContext> MinimalSignatureTypeProvider {
get => minimalCorlibTypeProvider;
}
/// <summary>
/// Converts <see cref="KnownTypeCode"/> to <see cref="PrimitiveTypeCode"/>.
/// Returns 0 for known types that are not primitive types (such as <see cref="Span{T}"/>).
/// </summary>
public static PrimitiveTypeCode ToPrimitiveTypeCode(this KnownTypeCode typeCode)
{
switch (typeCode)
{
case KnownTypeCode.Object:
return PrimitiveTypeCode.Object;
case KnownTypeCode.Boolean:
return PrimitiveTypeCode.Boolean;
case KnownTypeCode.Char:
return PrimitiveTypeCode.Char;
case KnownTypeCode.SByte:
return PrimitiveTypeCode.SByte;
case KnownTypeCode.Byte:
return PrimitiveTypeCode.Byte;
case KnownTypeCode.Int16:
return PrimitiveTypeCode.Int16;
case KnownTypeCode.UInt16:
return PrimitiveTypeCode.UInt16;
case KnownTypeCode.Int32:
return PrimitiveTypeCode.Int32;
case KnownTypeCode.UInt32:
return PrimitiveTypeCode.UInt32;
case KnownTypeCode.Int64:
return PrimitiveTypeCode.Int64;
case KnownTypeCode.UInt64:
return PrimitiveTypeCode.UInt64;
case KnownTypeCode.Single:
return PrimitiveTypeCode.Single;
case KnownTypeCode.Double:
return PrimitiveTypeCode.Double;
case KnownTypeCode.String:
return PrimitiveTypeCode.String;
case KnownTypeCode.Void:
return PrimitiveTypeCode.Void;
case KnownTypeCode.TypedReference:
return PrimitiveTypeCode.TypedReference;
case KnownTypeCode.IntPtr:
return PrimitiveTypeCode.IntPtr;
case KnownTypeCode.UIntPtr:
return PrimitiveTypeCode.UIntPtr;
default:
return 0;
}
}
public static KnownTypeCode ToKnownTypeCode(this PrimitiveTypeCode typeCode)
{
switch (typeCode)
{
case PrimitiveTypeCode.Boolean:
return KnownTypeCode.Boolean;
case PrimitiveTypeCode.Byte:
return KnownTypeCode.Byte;
case PrimitiveTypeCode.SByte:
return KnownTypeCode.SByte;
case PrimitiveTypeCode.Char:
return KnownTypeCode.Char;
case PrimitiveTypeCode.Int16:
return KnownTypeCode.Int16;
case PrimitiveTypeCode.UInt16:
return KnownTypeCode.UInt16;
case PrimitiveTypeCode.Int32:
return KnownTypeCode.Int32;
case PrimitiveTypeCode.UInt32:
return KnownTypeCode.UInt32;
case PrimitiveTypeCode.Int64:
return KnownTypeCode.Int64;
case PrimitiveTypeCode.UInt64:
return KnownTypeCode.UInt64;
case PrimitiveTypeCode.Single:
return KnownTypeCode.Single;
case PrimitiveTypeCode.Double:
return KnownTypeCode.Double;
case PrimitiveTypeCode.IntPtr:
return KnownTypeCode.IntPtr;
case PrimitiveTypeCode.UIntPtr:
return KnownTypeCode.UIntPtr;
case PrimitiveTypeCode.Object:
return KnownTypeCode.Object;
case PrimitiveTypeCode.String:
return KnownTypeCode.String;
case PrimitiveTypeCode.TypedReference:
return KnownTypeCode.TypedReference;
case PrimitiveTypeCode.Void:
return KnownTypeCode.Void;
default:
return KnownTypeCode.None;
}
}
public static IEnumerable<ModuleReferenceHandle> GetModuleReferences(this MetadataReader metadata)
{
var rowCount = metadata.GetTableRowCount(TableIndex.ModuleRef);
for (int row = 1; row <= rowCount; row++)
{
yield return MetadataTokens.ModuleReferenceHandle(row);
}
}
public static IEnumerable<TypeSpecificationHandle> GetTypeSpecifications(this MetadataReader metadata)
{
var rowCount = metadata.GetTableRowCount(TableIndex.TypeSpec);
for (int row = 1; row <= rowCount; row++)
{
yield return MetadataTokens.TypeSpecificationHandle(row);
}
}
public static IEnumerable<MethodSpecificationHandle> GetMethodSpecifications(this MetadataReader metadata)
{
var rowCount = metadata.GetTableRowCount(TableIndex.MethodSpec);
for (int row = 1; row <= rowCount; row++)
{
yield return MetadataTokens.MethodSpecificationHandle(row);
}
}
public static IEnumerable<(Handle Handle, MethodSemanticsAttributes Semantics, MethodDefinitionHandle Method, EntityHandle Association)> GetMethodSemantics(this MetadataReader metadata)
{
int offset = metadata.GetTableMetadataOffset(TableIndex.MethodSemantics);
int rowSize = metadata.GetTableRowSize(TableIndex.MethodSemantics);
int rowCount = metadata.GetTableRowCount(TableIndex.MethodSemantics);
bool methodSmall = metadata.GetTableRowCount(TableIndex.MethodDef) <= ushort.MaxValue;
bool assocSmall = metadata.GetTableRowCount(TableIndex.Property) <= ushort.MaxValue && metadata.GetTableRowCount(TableIndex.Event) <= ushort.MaxValue;
int assocOffset = (methodSmall ? 2 : 4) + 2;
for (int row = 0; row < rowCount; row++)
{
yield return Read(row);
}
(Handle Handle, MethodSemanticsAttributes Semantics, MethodDefinitionHandle Method, EntityHandle Association) Read(int row)
{
var span = metadata.AsReadOnlySpan();
var methodDefSpan = span.Slice(offset + rowSize * row + 2);
int methodDef = methodSmall ? BinaryPrimitives.ReadUInt16LittleEndian(methodDefSpan) : (int)BinaryPrimitives.ReadUInt32LittleEndian(methodDefSpan);
var assocSpan = span.Slice(assocOffset);
int assocDef = assocSmall ? BinaryPrimitives.ReadUInt16LittleEndian(assocSpan) : (int)BinaryPrimitives.ReadUInt32LittleEndian(assocSpan);
EntityHandle propOrEvent;
if ((assocDef & 0x1) == 1)
{
propOrEvent = MetadataTokens.PropertyDefinitionHandle(assocDef >> 1);
}
else
{
propOrEvent = MetadataTokens.EventDefinitionHandle(assocDef >> 1);
}
return (MetadataTokens.Handle(0x18000000 | (row + 1)), (MethodSemanticsAttributes)(BinaryPrimitives.ReadUInt16LittleEndian(span)), MetadataTokens.MethodDefinitionHandle(methodDef), propOrEvent);
}
}
public static IEnumerable<EntityHandle> GetFieldLayouts(this MetadataReader metadata)
{
var rowCount = metadata.GetTableRowCount(TableIndex.FieldLayout);
for (int row = 1; row <= rowCount; row++)
{
yield return MetadataTokens.EntityHandle(TableIndex.FieldLayout, row);
}
}
public static (int Offset, FieldDefinitionHandle FieldDef) GetFieldLayout(this MetadataReader metadata, EntityHandle fieldLayoutHandle)
{
var startPointer = metadata.AsReadOnlySpan();
int offset = metadata.GetTableMetadataOffset(TableIndex.FieldLayout);
int rowSize = metadata.GetTableRowSize(TableIndex.FieldLayout);
int rowCount = metadata.GetTableRowCount(TableIndex.FieldLayout);
int fieldRowNo = metadata.GetRowNumber(fieldLayoutHandle);
bool small = metadata.GetTableRowCount(TableIndex.Field) <= ushort.MaxValue;
for (int row = rowCount - 1; row >= 0; row--)
{
ReadOnlySpan<byte> ptr = startPointer.Slice(offset + rowSize * row);
var rowNoSpan = ptr.Slice(4);
uint rowNo = small ? BinaryPrimitives.ReadUInt16LittleEndian(rowNoSpan) : BinaryPrimitives.ReadUInt32LittleEndian(rowNoSpan);
if (fieldRowNo == rowNo)
{
return (BinaryPrimitives.ReadInt32LittleEndian(ptr), MetadataTokens.FieldDefinitionHandle(fieldRowNo));
}
}
return (0, default);
}
public static ReadOnlySpan<byte> AsReadOnlySpan(this MetadataReader metadataReader)
{
unsafe
{
return new(metadataReader.MetadataPointer, metadataReader.MetadataLength);
}
}
public static BlobReader AsBlobReader(this MetadataReader metadataReader)
{
unsafe
{
return new(metadataReader.MetadataPointer, metadataReader.MetadataLength);
}
}
}
}
| ILSpy/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs",
"repo_id": "ILSpy",
"token_count": 5272
} | 231 |
// 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.Reflection.Metadata;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler
{
public interface ITextOutput
{
string IndentationString { get; set; }
void Indent();
void Unindent();
void Write(char ch);
void Write(string text);
void WriteLine();
void WriteReference(OpCodeInfo opCode, bool omitSuffix = false);
void WriteReference(MetadataFile metadata, Handle handle, string text, string protocol = "decompile", bool isDefinition = false);
void WriteReference(IType type, string text, bool isDefinition = false);
void WriteReference(IMember member, string text, bool isDefinition = false);
void WriteLocalReference(string text, object reference, bool isDefinition = false);
void MarkFoldStart(string collapsedText = "...", bool defaultCollapsed = false, bool isDefinition = false);
void MarkFoldEnd();
}
public static class TextOutputExtensions
{
public static void Write(this ITextOutput output, string format, params object[] args)
{
output.Write(string.Format(format, args));
}
public static void WriteLine(this ITextOutput output, string text)
{
output.Write(text);
output.WriteLine();
}
public static void WriteLine(this ITextOutput output, string format, params object[] args)
{
output.WriteLine(string.Format(format, args));
}
}
}
| ILSpy/ICSharpCode.Decompiler/Output/ITextOutput.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Output/ITextOutput.cs",
"repo_id": "ILSpy",
"token_count": 730
} | 232 |
// 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.TypeSystem;
namespace ICSharpCode.Decompiler.Semantics
{
/// <summary>
/// Represents an implicit or explicit type conversion.
/// <c>conversionResolveResult.Input.Type</c> is the source type;
/// <c>conversionResolveResult.Type</c> is the target type.
/// The <see cref="Conversion"/> property provides details about the kind of conversion.
/// </summary>
public class ConversionResolveResult : ResolveResult
{
public readonly ResolveResult Input;
public readonly Conversion Conversion;
/// <summary>
/// For numeric conversions, specifies whether overflow checking is enabled.
/// </summary>
public readonly bool CheckForOverflow;
public ConversionResolveResult(IType targetType, ResolveResult input, Conversion conversion)
: base(targetType)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (conversion == null)
throw new ArgumentNullException(nameof(conversion));
this.Input = input;
this.Conversion = conversion;
}
public ConversionResolveResult(IType targetType, ResolveResult input, Conversion conversion, bool checkForOverflow)
: this(targetType, input, conversion)
{
this.CheckForOverflow = checkForOverflow;
}
public override bool IsError {
get { return !Conversion.IsValid; }
}
public override IEnumerable<ResolveResult> GetChildResults()
{
return new[] { Input };
}
}
}
| ILSpy/ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs",
"repo_id": "ILSpy",
"token_count": 751
} | 233 |
// 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.Text;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Holds the full name of a type definition.
/// A full type name uniquely identifies a type definition within a single assembly.
/// </summary>
/// <remarks>
/// A full type name can only represent type definitions, not arbitrary types.
/// It does not include any type arguments, and can not refer to array or pointer types.
///
/// A full type name represented as reflection name has the syntax:
/// <c>NamespaceName '.' TopLevelTypeName ['`'#] { '+' NestedTypeName ['`'#] }</c>
/// </remarks>
[Serializable]
public readonly struct FullTypeName : IEquatable<FullTypeName>
{
[Serializable]
readonly struct NestedTypeName
{
public readonly string Name;
public readonly int AdditionalTypeParameterCount;
public NestedTypeName(string name, int additionalTypeParameterCount)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.AdditionalTypeParameterCount = additionalTypeParameterCount;
}
}
readonly TopLevelTypeName topLevelType;
readonly NestedTypeName[] nestedTypes;
FullTypeName(TopLevelTypeName topLevelTypeName, NestedTypeName[] nestedTypes)
{
this.topLevelType = topLevelTypeName;
this.nestedTypes = nestedTypes;
}
/// <summary>
/// Constructs a FullTypeName representing the given top-level type.
/// </summary>
/// <remarks>
/// FullTypeName has an implicit conversion operator from TopLevelTypeName,
/// so you can simply write:
/// <c>FullTypeName f = new TopLevelTypeName(...);</c>
/// </remarks>
public FullTypeName(TopLevelTypeName topLevelTypeName)
{
this.topLevelType = topLevelTypeName;
this.nestedTypes = null;
}
/// <summary>
/// Constructs a FullTypeName by parsing the given reflection name.
/// Note that FullTypeName can only represent type definition names. If the reflection name
/// might refer to a parameterized type or array etc., use
/// <see cref="ReflectionHelper.ParseReflectionName(string)"/> instead.
/// </summary>
/// <remarks>
/// Expected syntax: <c>NamespaceName '.' TopLevelTypeName ['`'#] { '+' NestedTypeName ['`'#] }</c>
/// where # are type parameter counts
/// </remarks>
public FullTypeName(string reflectionName)
{
int pos = reflectionName.IndexOf('+');
if (pos < 0)
{
// top-level type
this.topLevelType = new TopLevelTypeName(reflectionName);
this.nestedTypes = null;
}
else
{
// nested type
string[] parts = reflectionName.Split('+');
this.topLevelType = new TopLevelTypeName(parts[0]);
this.nestedTypes = new NestedTypeName[parts.Length - 1];
for (int i = 0; i < nestedTypes.Length; i++)
{
int tpc;
string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(parts[i + 1], out tpc);
nestedTypes[i] = new NestedTypeName(name, tpc);
}
}
}
/// <summary>
/// Gets the top-level type name.
/// </summary>
public TopLevelTypeName TopLevelTypeName {
get { return topLevelType; }
}
/// <summary>
/// Gets whether this is a nested type.
/// </summary>
public bool IsNested {
get {
return nestedTypes != null;
}
}
/// <summary>
/// Gets the nesting level.
/// </summary>
public int NestingLevel {
get {
return nestedTypes != null ? nestedTypes.Length : 0;
}
}
/// <summary>
/// Gets the name of the type.
/// For nested types, this is the name of the innermost type.
/// </summary>
public string Name {
get {
if (nestedTypes != null)
return nestedTypes[nestedTypes.Length - 1].Name;
else
return topLevelType.Name;
}
}
public string ReflectionName {
get {
if (nestedTypes == null)
return topLevelType.ReflectionName;
StringBuilder b = new StringBuilder(topLevelType.ReflectionName);
foreach (NestedTypeName nt in nestedTypes)
{
b.Append('+');
b.Append(nt.Name);
if (nt.AdditionalTypeParameterCount > 0)
{
b.Append('`');
b.Append(nt.AdditionalTypeParameterCount);
}
}
return b.ToString();
}
}
public string FullName {
get {
if (nestedTypes == null)
return topLevelType.Namespace + "." + topLevelType.Name;
StringBuilder b = new StringBuilder(topLevelType.Namespace);
b.Append('.');
b.Append(topLevelType.Name);
foreach (NestedTypeName nt in nestedTypes)
{
b.Append('.');
b.Append(nt.Name);
}
return b.ToString();
}
}
/// <summary>
/// Gets the total type parameter count.
/// </summary>
public int TypeParameterCount {
get {
int tpc = topLevelType.TypeParameterCount;
if (nestedTypes != null)
{
foreach (var nt in nestedTypes)
{
tpc += nt.AdditionalTypeParameterCount;
}
}
return tpc;
}
}
/// <summary>
/// Gets the name of the nested type at the given level.
/// </summary>
public string GetNestedTypeName(int nestingLevel)
{
if (nestedTypes == null)
throw new InvalidOperationException();
return nestedTypes[nestingLevel].Name;
}
/// <summary>
/// Gets the number of additional type parameters of the nested type at the given level.
/// </summary>
public int GetNestedTypeAdditionalTypeParameterCount(int nestingLevel)
{
if (nestedTypes == null)
throw new InvalidOperationException();
return nestedTypes[nestingLevel].AdditionalTypeParameterCount;
}
/// <summary>
/// Gets the declaring type name.
/// </summary>
/// <exception cref="InvalidOperationException">This is a top-level type name.</exception>
/// <example><c>new FullTypeName("NS.A+B+C").GetDeclaringType()</c> will return <c>new FullTypeName("NS.A+B")</c></example>
public FullTypeName GetDeclaringType()
{
if (nestedTypes == null)
throw new InvalidOperationException();
if (nestedTypes.Length == 1)
return topLevelType;
NestedTypeName[] outerNestedTypeNames = new NestedTypeName[nestedTypes.Length - 1];
Array.Copy(nestedTypes, 0, outerNestedTypeNames, 0, outerNestedTypeNames.Length);
return new FullTypeName(topLevelType, outerNestedTypeNames);
}
/// <summary>
/// Creates a nested type name.
/// </summary>
/// <example><c>new FullTypeName("NS.A+B").NestedType("C", 1)</c> will return <c>new FullTypeName("NS.A+B+C`1")</c></example>
public FullTypeName NestedType(string name, int additionalTypeParameterCount)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
var newNestedType = new NestedTypeName(name, additionalTypeParameterCount);
if (nestedTypes == null)
return new FullTypeName(topLevelType, new[] { newNestedType });
NestedTypeName[] newNestedTypeNames = new NestedTypeName[nestedTypes.Length + 1];
nestedTypes.CopyTo(newNestedTypeNames, 0);
newNestedTypeNames[newNestedTypeNames.Length - 1] = newNestedType;
return new FullTypeName(topLevelType, newNestedTypeNames);
}
public static implicit operator FullTypeName(TopLevelTypeName topLevelTypeName)
{
return new FullTypeName(topLevelTypeName);
}
public override string ToString()
{
return this.ReflectionName;
}
#region Equals and GetHashCode implementation
public override bool Equals(object obj)
{
return obj is FullTypeName && Equals((FullTypeName)obj);
}
public bool Equals(FullTypeName other)
{
return FullTypeNameComparer.Ordinal.Equals(this, other);
}
public override int GetHashCode()
{
return FullTypeNameComparer.Ordinal.GetHashCode(this);
}
public static bool operator ==(FullTypeName left, FullTypeName right)
{
return left.Equals(right);
}
public static bool operator !=(FullTypeName left, FullTypeName right)
{
return !left.Equals(right);
}
#endregion
}
[Serializable]
public sealed class FullTypeNameComparer : IEqualityComparer<FullTypeName>
{
public static readonly FullTypeNameComparer Ordinal = new FullTypeNameComparer(StringComparer.Ordinal);
public static readonly FullTypeNameComparer OrdinalIgnoreCase = new FullTypeNameComparer(StringComparer.OrdinalIgnoreCase);
public readonly StringComparer NameComparer;
public FullTypeNameComparer(StringComparer nameComparer)
{
this.NameComparer = nameComparer;
}
public bool Equals(FullTypeName x, FullTypeName y)
{
if (x.NestingLevel != y.NestingLevel)
return false;
TopLevelTypeName topX = x.TopLevelTypeName;
TopLevelTypeName topY = y.TopLevelTypeName;
if (topX.TypeParameterCount == topY.TypeParameterCount
&& NameComparer.Equals(topX.Name, topY.Name)
&& NameComparer.Equals(topX.Namespace, topY.Namespace))
{
for (int i = 0; i < x.NestingLevel; i++)
{
if (x.GetNestedTypeAdditionalTypeParameterCount(i) != y.GetNestedTypeAdditionalTypeParameterCount(i))
return false;
if (!NameComparer.Equals(x.GetNestedTypeName(i), y.GetNestedTypeName(i)))
return false;
}
return true;
}
return false;
}
public int GetHashCode(FullTypeName obj)
{
TopLevelTypeName top = obj.TopLevelTypeName;
int hash = NameComparer.GetHashCode(top.Name) ^ NameComparer.GetHashCode(top.Namespace) ^ top.TypeParameterCount;
unchecked
{
for (int i = 0; i < obj.NestingLevel; i++)
{
hash *= 31;
hash += NameComparer.GetHashCode(obj.Name) ^ obj.TypeParameterCount;
}
}
return hash;
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/FullTypeName.cs",
"repo_id": "ILSpy",
"token_count": 3786
} | 234 |
// 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
{
/// <summary>
/// Represents a resolved namespace.
/// </summary>
public interface INamespace : ISymbol, ICompilationProvider
{
// No pointer back to unresolved namespace:
// multiple unresolved namespaces (from different assemblies) get
// merged into one INamespace.
/// <summary>
/// Gets the extern alias for this namespace.
/// Returns an empty string for normal namespaces.
/// </summary>
string ExternAlias { get; }
/// <summary>
/// Gets the full name of this namespace. (e.g. "System.Collections")
/// </summary>
string FullName { get; }
/// <summary>
/// Gets the short name of this namespace (e.g. "Collections").
/// </summary>
new string Name { get; }
/// <summary>
/// Gets the parent namespace.
/// Returns null if this is the root namespace.
/// </summary>
INamespace? ParentNamespace { get; }
/// <summary>
/// Gets the child namespaces in this namespace.
/// </summary>
IEnumerable<INamespace> ChildNamespaces { get; }
/// <summary>
/// Gets the types in this namespace.
/// </summary>
IEnumerable<ITypeDefinition> Types { get; }
/// <summary>
/// Gets the modules that contribute types to this namespace (or to child namespaces).
/// </summary>
IEnumerable<IModule> ContributingModules { get; }
/// <summary>
/// Gets a direct child namespace by its short name.
/// Returns null when the namespace cannot be found.
/// </summary>
/// <remarks>
/// This method uses the compilation's current string comparer.
/// </remarks>
INamespace? GetChildNamespace(string name);
/// <summary>
/// Gets the type with the specified short name and type parameter count.
/// Returns null if the type cannot be found.
/// </summary>
/// <remarks>
/// This method uses the compilation's current string comparer.
/// </remarks>
ITypeDefinition? GetTypeDefinition(string name, int typeParameterCount);
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/INamespace.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/INamespace.cs",
"repo_id": "ILSpy",
"token_count": 918
} | 235 |
// 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;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// Helper class for the GetAllBaseTypes() implementation.
/// </summary>
sealed class BaseTypeCollector : List<IType>
{
readonly Stack<IType> activeTypes = new Stack<IType>();
/// <summary>
/// If this option is enabled, the list will not contain interfaces when retrieving the base types
/// of a class.
/// </summary>
internal bool SkipImplementedInterfaces;
public void CollectBaseTypes(IType type)
{
IType def = type.GetDefinition() ?? type;
// Maintain a stack of currently active type definitions, and avoid having one definition
// multiple times on that stack.
// This is necessary to ensure the output is finite in the presence of cyclic inheritance:
// class C<X> : C<C<X>> {} would not be caught by the 'no duplicate output' check, yet would
// produce infinite output.
if (activeTypes.Contains(def))
return;
activeTypes.Push(def);
// Note that we also need to push non-type definitions, e.g. for protecting against
// cyclic inheritance in type parameters (where T : S where S : T).
// The output check doesn't help there because we call Add(type) only at the end.
// We can't simply call this.Add(type); at the start because that would return in an incorrect order.
// Avoid outputting a type more than once - necessary for "diamond" multiple inheritance
// (e.g. C implements I1 and I2, and both interfaces derive from Object)
if (!this.Contains(type))
{
foreach (IType baseType in type.DirectBaseTypes)
{
if (SkipImplementedInterfaces && def != null && def.Kind != TypeKind.Interface && def.Kind != TypeKind.TypeParameter)
{
if (baseType.Kind == TypeKind.Interface)
{
// skip the interface
continue;
}
}
CollectBaseTypes(baseType);
}
// Add(type) at the end - we want a type to be output only after all its base types were added.
this.Add(type);
// Note that this is not the same as putting the this.Add() call in front and then reversing the list.
// For the diamond inheritance, Add() at the start produces "C, I1, Object, I2",
// while Add() at the end produces "Object, I1, I2, C".
}
activeTypes.Pop();
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/BaseTypeCollector.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/BaseTypeCollector.cs",
"repo_id": "ILSpy",
"token_count": 1061
} | 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 System.Collections.Generic;
using System.Globalization;
using System.Linq;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// A merged namespace.
/// </summary>
public sealed class MergedNamespace : INamespace
{
readonly string externAlias;
readonly ICompilation compilation;
readonly INamespace parentNamespace;
readonly INamespace[] namespaces;
Dictionary<string, INamespace> childNamespaces;
/// <summary>
/// Creates a new merged root namespace.
/// </summary>
/// <param name="compilation">The main compilation.</param>
/// <param name="namespaces">The individual namespaces being merged.</param>
/// <param name="externAlias">The extern alias for this namespace.</param>
public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string externAlias = null)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
if (namespaces == null)
throw new ArgumentNullException(nameof(namespaces));
this.compilation = compilation;
this.namespaces = namespaces;
this.externAlias = externAlias;
}
/// <summary>
/// Creates a new merged child namespace.
/// </summary>
/// <param name="parentNamespace">The parent merged namespace.</param>
/// <param name="namespaces">The individual namespaces being merged.</param>
public MergedNamespace(INamespace parentNamespace, INamespace[] namespaces)
{
if (parentNamespace == null)
throw new ArgumentNullException(nameof(parentNamespace));
if (namespaces == null)
throw new ArgumentNullException(nameof(namespaces));
this.parentNamespace = parentNamespace;
this.namespaces = namespaces;
this.compilation = parentNamespace.Compilation;
this.externAlias = parentNamespace.ExternAlias;
}
public string ExternAlias {
get { return externAlias; }
}
public string FullName {
get { return namespaces[0].FullName; }
}
public string Name {
get { return namespaces[0].Name; }
}
public INamespace ParentNamespace {
get { return parentNamespace; }
}
public IEnumerable<ITypeDefinition> Types {
get {
return namespaces.SelectMany(ns => ns.Types);
}
}
public SymbolKind SymbolKind {
get { return SymbolKind.Namespace; }
}
public ICompilation Compilation {
get { return compilation; }
}
public IEnumerable<IModule> ContributingModules {
get { return namespaces.SelectMany(ns => ns.ContributingModules); }
}
public IEnumerable<INamespace> ChildNamespaces {
get { return GetChildNamespaces().Values; }
}
public INamespace GetChildNamespace(string name)
{
INamespace ns;
if (GetChildNamespaces().TryGetValue(name, out ns))
return ns;
else
return null;
}
Dictionary<string, INamespace> GetChildNamespaces()
{
var result = LazyInit.VolatileRead(ref this.childNamespaces);
if (result != null)
{
return result;
}
else
{
result = new Dictionary<string, INamespace>(compilation.NameComparer);
foreach (var g in namespaces.SelectMany(ns => ns.ChildNamespaces).GroupBy(ns => ns.Name, compilation.NameComparer))
{
result.Add(g.Key, new MergedNamespace(this, g.ToArray()));
}
return LazyInit.GetOrSet(ref this.childNamespaces, result);
}
}
public ITypeDefinition GetTypeDefinition(string name, int typeParameterCount)
{
ITypeDefinition anyTypeDef = null;
foreach (var ns in namespaces)
{
ITypeDefinition typeDef = ns.GetTypeDefinition(name, typeParameterCount);
if (typeDef != null)
{
if (typeDef.Accessibility == Accessibility.Public)
{
// Prefer accessible types over non-accessible types.
return typeDef;
// || (typeDef.IsInternal && typeDef.ParentAssembly.InternalsVisibleTo(...))
// We can't call InternalsVisibleTo() here as we don't know the correct 'current' assembly,
// and using the main assembly can cause a stack overflow if there
// are internal assembly attributes.
}
anyTypeDef = typeDef;
}
}
return anyTypeDef;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[MergedNamespace {0}{1} (from {2} assemblies)]",
externAlias != null ? externAlias + "::" : null, this.FullName, this.namespaces.Length);
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/MergedNamespace.cs",
"repo_id": "ILSpy",
"token_count": 1833
} | 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem.Implementation
{
/// <summary>
/// Represents a SpecializedMember (a member on which type substitution has been performed).
/// </summary>
public abstract class SpecializedMember : IMember
{
protected readonly IMember baseMember;
TypeParameterSubstitution substitution;
IType declaringType;
IType returnType;
protected SpecializedMember(IMember memberDefinition)
{
if (memberDefinition == null)
throw new ArgumentNullException(nameof(memberDefinition));
if (memberDefinition is SpecializedMember)
throw new ArgumentException("Member definition cannot be specialized. Please use IMember.Specialize() instead of directly constructing SpecializedMember instances.");
this.baseMember = memberDefinition;
this.substitution = TypeParameterSubstitution.Identity;
}
/// <summary>
/// Performs a substitution. This method may only be called by constructors in derived classes.
/// </summary>
protected void AddSubstitution(TypeParameterSubstitution newSubstitution)
{
Debug.Assert(declaringType == null);
Debug.Assert(returnType == null);
this.substitution = TypeParameterSubstitution.Compose(newSubstitution, this.substitution);
}
internal IMethod WrapAccessor(ref IMethod cachingField, IMethod accessorDefinition)
{
if (accessorDefinition == null)
return null;
var result = LazyInit.VolatileRead(ref cachingField);
if (result != null)
{
return result;
}
else
{
var sm = accessorDefinition.Specialize(substitution);
//sm.AccessorOwner = this;
return LazyInit.GetOrSet(ref cachingField, sm);
}
}
/// <summary>
/// Gets the substitution belonging to this specialized member.
/// </summary>
public TypeParameterSubstitution Substitution {
get { return substitution; }
}
public IType DeclaringType {
get {
var result = LazyInit.VolatileRead(ref this.declaringType);
if (result != null)
return result;
IType definitionDeclaringType = baseMember.DeclaringType;
ITypeDefinition definitionDeclaringTypeDef = definitionDeclaringType as ITypeDefinition;
if (definitionDeclaringTypeDef != null && definitionDeclaringType.TypeParameterCount > 0)
{
if (substitution.ClassTypeArguments != null && substitution.ClassTypeArguments.Count == definitionDeclaringType.TypeParameterCount)
{
result = new ParameterizedType(definitionDeclaringTypeDef, substitution.ClassTypeArguments);
}
else
{
result = new ParameterizedType(definitionDeclaringTypeDef, definitionDeclaringTypeDef.TypeParameters).AcceptVisitor(substitution);
}
}
else if (definitionDeclaringType != null)
{
result = definitionDeclaringType.AcceptVisitor(substitution);
}
return LazyInit.GetOrSet(ref this.declaringType, result);
}
internal set {
// This setter is used as an optimization when the code constructing
// the SpecializedMember already knows the declaring type.
Debug.Assert(this.declaringType == null);
// As this setter is used only during construction before the member is published
// to other threads, we don't need a volatile write.
this.declaringType = value;
}
}
public IMember MemberDefinition {
get { return baseMember.MemberDefinition; }
}
public IType ReturnType {
get {
var result = LazyInit.VolatileRead(ref this.returnType);
if (result != null)
return result;
else
return LazyInit.GetOrSet(ref this.returnType, baseMember.ReturnType.AcceptVisitor(substitution));
}
protected set {
// This setter is used for LiftedUserDefinedOperator, a special case of specialized member
// (not a normal type parameter substitution).
// As this setter is used only during construction before the member is published
// to other threads, we don't need a volatile write.
this.returnType = value;
}
}
public System.Reflection.Metadata.EntityHandle MetadataToken => baseMember.MetadataToken;
public bool IsVirtual {
get { return baseMember.IsVirtual; }
}
public bool IsOverride {
get { return baseMember.IsOverride; }
}
public bool IsOverridable {
get { return baseMember.IsOverridable; }
}
public SymbolKind SymbolKind {
get { return baseMember.SymbolKind; }
}
public ITypeDefinition DeclaringTypeDefinition {
get { return baseMember.DeclaringTypeDefinition; }
}
IEnumerable<IAttribute> IEntity.GetAttributes() => baseMember.GetAttributes();
bool IEntity.HasAttribute(KnownAttribute attribute) => baseMember.HasAttribute(attribute);
IAttribute IEntity.GetAttribute(KnownAttribute attribute) => baseMember.GetAttribute(attribute);
public IEnumerable<IMember> ExplicitlyImplementedInterfaceMembers {
get {
// Note: if the interface is generic, then the interface members should already be specialized,
// so we only need to append our substitution.
return baseMember.ExplicitlyImplementedInterfaceMembers.Select(m => m.Specialize(substitution));
}
}
public bool IsExplicitInterfaceImplementation {
get { return baseMember.IsExplicitInterfaceImplementation; }
}
public Accessibility Accessibility {
get { return baseMember.Accessibility; }
}
public bool IsStatic {
get { return baseMember.IsStatic; }
}
public bool IsAbstract {
get { return baseMember.IsAbstract; }
}
public bool IsSealed {
get { return baseMember.IsSealed; }
}
public string FullName {
get { return baseMember.FullName; }
}
public string Name {
get { return baseMember.Name; }
}
public string Namespace {
get { return baseMember.Namespace; }
}
public string ReflectionName {
get { return baseMember.ReflectionName; }
}
public ICompilation Compilation {
get { return baseMember.Compilation; }
}
public IModule ParentModule {
get { return baseMember.ParentModule; }
}
public virtual IMember Specialize(TypeParameterSubstitution newSubstitution)
{
return baseMember.Specialize(TypeParameterSubstitution.Compose(newSubstitution, this.substitution));
}
public virtual bool Equals(IMember obj, TypeVisitor typeNormalization)
{
SpecializedMember other = obj as SpecializedMember;
if (other == null)
return false;
return this.baseMember.Equals(other.baseMember, typeNormalization)
&& this.substitution.Equals(other.substitution, typeNormalization);
}
public override bool Equals(object obj)
{
SpecializedMember other = obj as SpecializedMember;
if (other == null)
return false;
return this.baseMember.Equals(other.baseMember) && this.substitution.Equals(other.substitution);
}
public override int GetHashCode()
{
unchecked
{
return 1000000007 * baseMember.GetHashCode() + 1000000009 * substitution.GetHashCode();
}
}
public override string ToString()
{
StringBuilder b = new StringBuilder("[");
b.Append(GetType().Name);
b.Append(' ');
b.Append(this.DeclaringType.ToString());
b.Append('.');
b.Append(this.Name);
b.Append(':');
b.Append(this.ReturnType.ToString());
b.Append(']');
return b.ToString();
}
}
public abstract class SpecializedParameterizedMember : SpecializedMember, IParameterizedMember
{
IReadOnlyList<IParameter> parameters;
protected SpecializedParameterizedMember(IParameterizedMember memberDefinition)
: base(memberDefinition)
{
}
public IReadOnlyList<IParameter> Parameters {
get {
var result = LazyInit.VolatileRead(ref this.parameters);
if (result != null)
return result;
else
return LazyInit.GetOrSet(ref this.parameters, CreateParameters(t => t.AcceptVisitor(this.Substitution)));
}
protected set {
// This setter is used for LiftedUserDefinedOperator, a special case of specialized member
// (not a normal type parameter substitution).
// As this setter is used only during construction before the member is published
// to other threads, we don't need a volatile write.
this.parameters = value;
}
}
protected IParameter[] CreateParameters(Func<IType, IType> substitution)
{
var paramDefs = ((IParameterizedMember)this.baseMember).Parameters;
if (paramDefs.Count == 0)
{
return Empty<IParameter>.Array;
}
else
{
var parameters = new IParameter[paramDefs.Count];
for (int i = 0; i < parameters.Length; i++)
{
var p = paramDefs[i];
IType newType = substitution(p.Type);
parameters[i] = new SpecializedParameter(p, newType, this);
}
return parameters;
}
}
public override string ToString()
{
StringBuilder b = new StringBuilder("[");
b.Append(GetType().Name);
b.Append(' ');
b.Append(this.DeclaringType.ReflectionName);
b.Append('.');
b.Append(this.Name);
b.Append('(');
for (int i = 0; i < this.Parameters.Count; i++)
{
if (i > 0)
b.Append(", ");
b.Append(this.Parameters[i].ToString());
}
b.Append("):");
b.Append(this.ReturnType.ReflectionName);
b.Append(']');
return b.ToString();
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/Implementation/SpecializedMember.cs",
"repo_id": "ILSpy",
"token_count": 3494
} | 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;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Static helper methods for working with nullable types.
/// </summary>
public static class NullableType
{
/// <summary>
/// Gets whether the specified type is a nullable type.
/// </summary>
public static bool IsNullable(IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
ParameterizedType pt = type.SkipModifiers() as ParameterizedType;
return pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT);
}
public static bool IsNonNullableValueType(IType type)
{
return type.IsReferenceType == false && !IsNullable(type);
}
/// <summary>
/// Returns the element type, if <paramref name="type"/> is a nullable type.
/// Otherwise, returns the type itself.
/// </summary>
public static IType GetUnderlyingType(IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
ParameterizedType pt = type.SkipModifiers() as ParameterizedType;
if (pt != null && pt.TypeParameterCount == 1 && pt.GenericType.IsKnownType(KnownTypeCode.NullableOfT))
return pt.GetTypeArgument(0);
else
return type;
}
/// <summary>
/// Creates a nullable type.
/// </summary>
public static IType Create(ICompilation compilation, IType elementType)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
if (elementType == null)
throw new ArgumentNullException(nameof(elementType));
IType nullableType = compilation.FindType(KnownTypeCode.NullableOfT);
ITypeDefinition nullableTypeDef = nullableType.GetDefinition();
if (nullableTypeDef != null)
return new ParameterizedType(nullableTypeDef, new[] { elementType });
else
return nullableType;
}
/// <summary>
/// Creates a nullable type reference.
/// </summary>
public static ParameterizedTypeReference Create(ITypeReference elementType)
{
if (elementType == null)
throw new ArgumentNullException(nameof(elementType));
return new ParameterizedTypeReference(KnownTypeReference.Get(KnownTypeCode.NullableOfT), new[] { elementType });
}
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/NullableType.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/NullableType.cs",
"repo_id": "ILSpy",
"token_count": 1031
} | 239 |
// 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 ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
namespace ICSharpCode.Decompiler.TypeSystem
{
public static class TypeUtils
{
public const int NativeIntSize = 6; // between 4 (Int32) and 8 (Int64)
/// <summary>
/// Gets the size (in bytes) of the input type.
/// Returns <c>NativeIntSize</c> for pointer-sized types.
/// Returns 0 for structs and other types of unknown size.
/// </summary>
public static int GetSize(this IType type)
{
switch (type.Kind)
{
case TypeKind.Pointer:
case TypeKind.ByReference:
case TypeKind.Class:
case TypeKind.NInt:
case TypeKind.NUInt:
return NativeIntSize;
case TypeKind.Enum:
type = type.GetEnumUnderlyingType();
break;
case TypeKind.ModOpt:
case TypeKind.ModReq:
return type.SkipModifiers().GetSize();
}
var typeDef = type.GetDefinition();
if (typeDef == null)
return 0;
switch (typeDef.KnownTypeCode)
{
case KnownTypeCode.Boolean:
case KnownTypeCode.SByte:
case KnownTypeCode.Byte:
return 1;
case KnownTypeCode.Char:
case KnownTypeCode.Int16:
case KnownTypeCode.UInt16:
return 2;
case KnownTypeCode.Int32:
case KnownTypeCode.UInt32:
case KnownTypeCode.Single:
return 4;
case KnownTypeCode.IntPtr:
case KnownTypeCode.UIntPtr:
return NativeIntSize;
case KnownTypeCode.Int64:
case KnownTypeCode.UInt64:
case KnownTypeCode.Double:
return 8;
}
return 0;
}
/// <summary>
/// Gets the size of the input stack type.
/// </summary>
/// <returns>
/// * 4 for <c>I4</c>,
/// * 8 for <c>I8</c>,
/// * <c>NativeIntSize</c> for <c>I</c> and <c>Ref</c>,
/// * 0 otherwise (O, F, Void, Unknown).
/// </returns>
public static int GetSize(this StackType type)
{
switch (type)
{
case StackType.I4:
return 4;
case StackType.I8:
return 8;
case StackType.I:
case StackType.Ref:
return NativeIntSize;
default:
return 0;
}
}
public static IType GetLargerType(IType type1, IType type2)
{
return GetSize(type1) >= GetSize(type2) ? type1 : type2;
}
/// <summary>
/// Gets whether the type is a small integer type.
/// Small integer types are:
/// * bool, sbyte, byte, char, short, ushort
/// * any enums that have a small integer type as underlying type
/// </summary>
public static bool IsSmallIntegerType(this IType type)
{
int size = GetSize(type);
return size > 0 && size < 4;
}
/// <summary>
/// Gets whether the type is a C# small integer type: byte, sbyte, short or ushort.
///
/// Unlike the ILAst, C# does not consider bool, char or enums to be small integers.
/// </summary>
public static bool IsCSharpSmallIntegerType(this IType type)
{
switch (type.GetDefinition()?.KnownTypeCode)
{
case KnownTypeCode.Byte:
case KnownTypeCode.SByte:
case KnownTypeCode.Int16:
case KnownTypeCode.UInt16:
return true;
default:
return false;
}
}
/// <summary>
/// Gets whether the type is a C# 9 native integer type: nint or nuint.
///
/// Returns false for (U)IntPtr.
/// </summary>
public static bool IsCSharpNativeIntegerType(this IType type)
{
switch (type.Kind)
{
case TypeKind.NInt:
case TypeKind.NUInt:
return true;
default:
return false;
}
}
/// <summary>
/// Gets whether the type is a C# primitive integer type: byte, sbyte, short, ushort, int, uint, long and ulong.
///
/// Unlike the ILAst, C# does not consider bool, enums, pointers or IntPtr to be integers.
/// </summary>
public static bool IsCSharpPrimitiveIntegerType(this IType type)
{
switch (type.GetDefinition()?.KnownTypeCode)
{
case KnownTypeCode.Byte:
case KnownTypeCode.SByte:
case KnownTypeCode.Int16:
case KnownTypeCode.UInt16:
case KnownTypeCode.Int32:
case KnownTypeCode.UInt32:
case KnownTypeCode.Int64:
case KnownTypeCode.UInt64:
return true;
default:
return false;
}
}
/// <summary>
/// Gets whether the type is an IL integer type.
/// Returns true for I4, I, or I8.
/// </summary>
public static bool IsIntegerType(this StackType type)
{
switch (type)
{
case StackType.I4:
case StackType.I:
case StackType.I8:
return true;
default:
return false;
}
}
/// <summary>
/// Gets whether the type is an IL floating point type.
/// Returns true for F4 or F8.
/// </summary>
public static bool IsFloatType(this StackType type)
{
switch (type)
{
case StackType.F4:
case StackType.F8:
return true;
default:
return false;
}
}
/// <summary>
/// Gets whether reading/writing an element of accessType from the pointer
/// is equivalent to reading/writing an element of the pointer's element type.
/// </summary>
/// <remarks>
/// The access semantics may sligthly differ on read accesses of small integer types,
/// due to zero extension vs. sign extension when the signs differ.
/// </remarks>
public static bool IsCompatiblePointerTypeForMemoryAccess(IType pointerType, IType accessType)
{
IType memoryType;
if (pointerType is PointerType || pointerType is ByReferenceType)
memoryType = ((TypeWithElementType)pointerType).ElementType;
else
return false;
return IsCompatibleTypeForMemoryAccess(memoryType, accessType);
}
/// <summary>
/// Gets whether reading/writing an element of accessType from the pointer
/// is equivalent to reading/writing an element of the memoryType.
/// </summary>
/// <remarks>
/// The access semantics may sligthly differ on read accesses of small integer types,
/// due to zero extension vs. sign extension when the signs differ.
/// </remarks>
public static bool IsCompatibleTypeForMemoryAccess(IType memoryType, IType accessType)
{
memoryType = memoryType.AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
accessType = accessType.AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
if (memoryType.Equals(accessType))
return true;
// If the types are not equal, the access still might produce equal results in some cases:
// 1) Both types are reference types
if (memoryType.IsReferenceType == true && accessType.IsReferenceType == true)
return true;
// 2) Both types are integer types of equal size
StackType memoryStackType = memoryType.GetStackType();
StackType accessStackType = accessType.GetStackType();
if (memoryStackType == accessStackType && memoryStackType.IsIntegerType() && GetSize(memoryType) == GetSize(accessType))
return true;
// 3) Any of the types is unknown: we assume they are compatible.
return memoryType.Kind == TypeKind.Unknown || accessType.Kind == TypeKind.Unknown;
}
/// <summary>
/// Gets the stack type corresponding to this type.
/// </summary>
public static StackType GetStackType(this IType type)
{
switch (type.Kind)
{
case TypeKind.Unknown:
if (type.IsReferenceType == true)
{
return StackType.O;
}
return StackType.Unknown;
case TypeKind.ByReference:
return StackType.Ref;
case TypeKind.Pointer:
case TypeKind.NInt:
case TypeKind.NUInt:
case TypeKind.FunctionPointer:
return StackType.I;
case TypeKind.TypeParameter:
// Type parameters are always considered StackType.O, even
// though they might be instantiated with primitive types.
return StackType.O;
case TypeKind.ModOpt:
case TypeKind.ModReq:
return type.SkipModifiers().GetStackType();
}
ITypeDefinition typeDef = type.GetEnumUnderlyingType().GetDefinition();
if (typeDef == null)
return StackType.O;
switch (typeDef.KnownTypeCode)
{
case KnownTypeCode.Boolean:
case KnownTypeCode.Char:
case KnownTypeCode.SByte:
case KnownTypeCode.Byte:
case KnownTypeCode.Int16:
case KnownTypeCode.UInt16:
case KnownTypeCode.Int32:
case KnownTypeCode.UInt32:
return StackType.I4;
case KnownTypeCode.Int64:
case KnownTypeCode.UInt64:
return StackType.I8;
case KnownTypeCode.Single:
return StackType.F4;
case KnownTypeCode.Double:
return StackType.F8;
case KnownTypeCode.Void:
return StackType.Void;
case KnownTypeCode.IntPtr:
case KnownTypeCode.UIntPtr:
return StackType.I;
default:
return StackType.O;
}
}
/// <summary>
/// If type is an enumeration type, returns the underlying type.
/// Otherwise, returns type unmodified.
/// </summary>
public static IType GetEnumUnderlyingType(this IType type)
{
type = type.SkipModifiers();
return (type.Kind == TypeKind.Enum) ? type.GetDefinition().EnumUnderlyingType : type;
}
/// <summary>
/// Gets the sign of the input type.
/// </summary>
/// <remarks>
/// Integer types (including IntPtr/UIntPtr) return the sign as expected.
/// Floating point types and <c>decimal</c> are considered to be signed.
/// <c>char</c>, <c>bool</c> and pointer types (e.g. <c>void*</c>) are unsigned.
/// Enums have a sign based on their underlying type.
/// All other types return <c>Sign.None</c>.
/// </remarks>
public static Sign GetSign(this IType type)
{
type = type.SkipModifiers();
switch (type.Kind)
{
case TypeKind.Pointer:
case TypeKind.NUInt:
case TypeKind.FunctionPointer:
return Sign.Unsigned;
case TypeKind.NInt:
return Sign.Signed;
}
var typeDef = type.GetEnumUnderlyingType().GetDefinition();
if (typeDef == null)
return Sign.None;
switch (typeDef.KnownTypeCode)
{
case KnownTypeCode.SByte:
case KnownTypeCode.Int16:
case KnownTypeCode.Int32:
case KnownTypeCode.Int64:
case KnownTypeCode.IntPtr:
case KnownTypeCode.Single:
case KnownTypeCode.Double:
case KnownTypeCode.Decimal:
return Sign.Signed;
case KnownTypeCode.UIntPtr:
case KnownTypeCode.Char:
case KnownTypeCode.Boolean:
case KnownTypeCode.Byte:
case KnownTypeCode.UInt16:
case KnownTypeCode.UInt32:
case KnownTypeCode.UInt64:
return Sign.Unsigned;
default:
return Sign.None;
}
}
/// <summary>
/// Maps the KnownTypeCode values to the corresponding PrimitiveTypes.
/// </summary>
public static PrimitiveType ToPrimitiveType(this KnownTypeCode knownTypeCode)
{
switch (knownTypeCode)
{
case KnownTypeCode.SByte:
return PrimitiveType.I1;
case KnownTypeCode.Int16:
return PrimitiveType.I2;
case KnownTypeCode.Int32:
return PrimitiveType.I4;
case KnownTypeCode.Int64:
return PrimitiveType.I8;
case KnownTypeCode.Single:
return PrimitiveType.R4;
case KnownTypeCode.Double:
return PrimitiveType.R8;
case KnownTypeCode.Byte:
return PrimitiveType.U1;
case KnownTypeCode.UInt16:
case KnownTypeCode.Char:
return PrimitiveType.U2;
case KnownTypeCode.UInt32:
return PrimitiveType.U4;
case KnownTypeCode.UInt64:
return PrimitiveType.U8;
case KnownTypeCode.IntPtr:
return PrimitiveType.I;
case KnownTypeCode.UIntPtr:
return PrimitiveType.U;
default:
return PrimitiveType.None;
}
}
/// <summary>
/// Maps the KnownTypeCode values to the corresponding PrimitiveTypes.
/// </summary>
public static PrimitiveType ToPrimitiveType(this IType type)
{
type = type.SkipModifiers();
switch (type.Kind)
{
case TypeKind.Unknown:
return PrimitiveType.Unknown;
case TypeKind.ByReference:
return PrimitiveType.Ref;
case TypeKind.NInt:
case TypeKind.FunctionPointer:
return PrimitiveType.I;
case TypeKind.NUInt:
return PrimitiveType.U;
}
var def = type.GetEnumUnderlyingType().GetDefinition();
return def != null ? def.KnownTypeCode.ToPrimitiveType() : PrimitiveType.None;
}
/// <summary>
/// Maps the PrimitiveType values to the corresponding KnownTypeCodes.
/// </summary>
public static KnownTypeCode ToKnownTypeCode(this PrimitiveType primitiveType)
{
switch (primitiveType)
{
case PrimitiveType.I1:
return KnownTypeCode.SByte;
case PrimitiveType.I2:
return KnownTypeCode.Int16;
case PrimitiveType.I4:
return KnownTypeCode.Int32;
case PrimitiveType.I8:
return KnownTypeCode.Int64;
case PrimitiveType.R4:
return KnownTypeCode.Single;
case PrimitiveType.R8:
case PrimitiveType.R:
return KnownTypeCode.Double;
case PrimitiveType.U1:
return KnownTypeCode.Byte;
case PrimitiveType.U2:
return KnownTypeCode.UInt16;
case PrimitiveType.U4:
return KnownTypeCode.UInt32;
case PrimitiveType.U8:
return KnownTypeCode.UInt64;
case PrimitiveType.I:
return KnownTypeCode.IntPtr;
case PrimitiveType.U:
return KnownTypeCode.UIntPtr;
default:
return KnownTypeCode.None;
}
}
public static KnownTypeCode ToKnownTypeCode(this StackType stackType, Sign sign = Sign.None)
{
switch (stackType)
{
case StackType.I4:
return sign == Sign.Unsigned ? KnownTypeCode.UInt32 : KnownTypeCode.Int32;
case StackType.I8:
return sign == Sign.Unsigned ? KnownTypeCode.UInt64 : KnownTypeCode.Int64;
case StackType.I:
return sign == Sign.Unsigned ? KnownTypeCode.UIntPtr : KnownTypeCode.IntPtr;
case StackType.F4:
return KnownTypeCode.Single;
case StackType.F8:
return KnownTypeCode.Double;
case StackType.O:
return KnownTypeCode.Object;
case StackType.Void:
return KnownTypeCode.Void;
default:
return KnownTypeCode.None;
}
}
public static PrimitiveType ToPrimitiveType(this StackType stackType, Sign sign = Sign.None)
{
switch (stackType)
{
case StackType.I4:
return sign == Sign.Unsigned ? PrimitiveType.U4 : PrimitiveType.I4;
case StackType.I8:
return sign == Sign.Unsigned ? PrimitiveType.U8 : PrimitiveType.I8;
case StackType.I:
return sign == Sign.Unsigned ? PrimitiveType.U : PrimitiveType.I;
case StackType.F4:
return PrimitiveType.R4;
case StackType.F8:
return PrimitiveType.R8;
case StackType.Ref:
return PrimitiveType.Ref;
case StackType.Unknown:
return PrimitiveType.Unknown;
default:
return PrimitiveType.None;
}
}
}
public enum Sign : byte
{
None,
Signed,
Unsigned
}
}
| ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeUtils.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/TypeSystem/TypeUtils.cs",
"repo_id": "ILSpy",
"token_count": 5983
} | 240 |
#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;
namespace ICSharpCode.Decompiler.Util
{
/// <summary>
/// Represents a half-closed interval.
/// The start position is inclusive; but the end position is exclusive.
/// </summary>
/// <remarks>
/// Start <= unchecked(End - 1): normal interval
/// Start == End: empty interval
/// Special case: Start == End == int.MinValue: interval containing all integers, not an empty interval!
/// </remarks>
public struct Interval : IEquatable<Interval>
{
/// <summary>
/// Gets the inclusive start of the interval.
/// </summary>
public readonly int Start;
/// <summary>
/// Gets the exclusive end of the interval.
/// </summary>
/// <remarks>
/// Note that an End of int.MinValue is a special case, and stands
/// for an actual End of int.MaxValue+1.
/// If possible, prefer using InclusiveEnd for comparisons, as that does not have an overflow problem.
/// </remarks>
public readonly int End;
/// <summary>
/// Creates a new interval.
/// </summary>
/// <param name="start">Start position (inclusive)</param>
/// <param name="end">End position (exclusive).
/// Note that it is possible to create an interval that includes int.MaxValue
/// by using end==int.MaxValue+1==int.MinValue.</param>
public Interval(int start, int end)
{
if (!(start <= unchecked(end - 1) || start == end))
throw new ArgumentException("The end must be after the start", nameof(end));
this.Start = start;
this.End = end;
}
/// <summary>
/// Gets the inclusive end of the interval. (End - 1)
/// For empty intervals, this returns Start - 1.
/// </summary>
/// <remarks>
/// Because there is no empty interval at int.MinValue,
/// (Start==End==int.MinValue is a special case referring to [int.MinValue..int.MaxValue]),
/// integer overflow is not a problem here.
/// </remarks>
public int InclusiveEnd {
get {
return unchecked(End - 1);
}
}
public bool IsEmpty {
get {
return Start > InclusiveEnd;
}
}
public bool Contains(int val)
{
// Use 'val <= InclusiveEnd' instead of 'val < End' to allow intervals to include int.MaxValue.
return Start <= val && val <= InclusiveEnd;
}
/// <summary>
/// Calculates the intersection between this interval and the other interval.
/// </summary>
public Interval Intersect(Interval other)
{
int start = Math.Max(this.Start, other.Start);
int inclusiveEnd = Math.Min(this.InclusiveEnd, other.InclusiveEnd);
if (start <= inclusiveEnd)
return new Interval(start, unchecked(inclusiveEnd + 1));
else
return default(Interval);
}
public override string ToString()
{
if (End == int.MinValue)
return string.Format("[{0}..int.MaxValue]", Start);
else
return string.Format("[{0}..{1})", Start, End);
}
#region Equals and GetHashCode implementation
public override bool Equals(object? obj)
{
return (obj is Interval) && Equals((Interval)obj);
}
public bool Equals(Interval other)
{
return this.Start == other.Start && this.End == other.End;
}
public override int GetHashCode()
{
return Start ^ End ^ (End << 7);
}
public static bool operator ==(Interval lhs, Interval rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(Interval lhs, Interval rhs)
{
return !(lhs == rhs);
}
#endregion
}
/// <summary>
/// Represents a half-closed interval.
/// The start position is inclusive; but the end position is exclusive.
/// </summary>
/// <remarks>
/// Start <= unchecked(End - 1): normal interval
/// Start == End: empty interval
/// Special case: Start == End == long.MinValue: interval containing all integers, not an empty interval!
/// </remarks>
public struct LongInterval : IEquatable<LongInterval>
{
/// <summary>
/// Gets the inclusive start of the interval.
/// </summary>
public readonly long Start;
/// <summary>
/// Gets the exclusive end of the interval.
/// </summary>
/// <remarks>
/// Note that an End of long.MinValue is a special case, and stands
/// for an actual End of long.MaxValue+1.
/// If possible, prefer using InclusiveEnd for comparisons, as that does not have an overflow problem.
/// </remarks>
public readonly long End;
/// <summary>
/// Creates a new interval.
/// </summary>
/// <param name="start">Start position (inclusive)</param>
/// <param name="end">End position (exclusive).
/// Note that it is possible to create an interval that includes long.MaxValue
/// by using end==long.MaxValue+1==long.MinValue.</param>
/// <remarks>
/// This method can be used to create an empty interval by specifying start==end,
/// however this is error-prone due to the special case of
/// start==end==long.MinValue being interpreted as the full interval [long.MinValue,long.MaxValue].
/// </remarks>
public LongInterval(long start, long end)
{
if (!(start <= unchecked(end - 1) || start == end))
throw new ArgumentException("The end must be after the start", nameof(end));
this.Start = start;
this.End = end;
}
/// <summary>
/// Creates a new interval from start to end.
/// Unlike the constructor where the end position is exclusive,
/// this method interprets the end position as inclusive.
///
/// This method cannot be used to construct an empty interval.
/// </summary>
public static LongInterval Inclusive(long start, long inclusiveEnd)
{
if (!(start <= inclusiveEnd))
throw new ArgumentException();
return new LongInterval(start, unchecked(inclusiveEnd + 1));
}
/// <summary>
/// Gets the inclusive end of the interval. (End - 1)
/// For empty intervals, this returns Start - 1.
/// </summary>
/// <remarks>
/// Because there is no empty interval at int.MinValue,
/// (Start==End==int.MinValue is a special case referring to [int.MinValue..int.MaxValue]),
/// integer overflow is not a problem here.
/// </remarks>
public long InclusiveEnd {
get {
return unchecked(End - 1);
}
}
public bool IsEmpty {
get {
return Start > InclusiveEnd;
}
}
public bool Contains(long val)
{
// Use 'val <= InclusiveEnd' instead of 'val < End' to allow intervals to include long.MaxValue.
return Start <= val && val <= InclusiveEnd;
}
/// <summary>
/// Calculates the intersection between this interval and the other interval.
/// </summary>
public LongInterval Intersect(LongInterval other)
{
long start = Math.Max(this.Start, other.Start);
long inclusiveEnd = Math.Min(this.InclusiveEnd, other.InclusiveEnd);
if (start <= inclusiveEnd)
return new LongInterval(start, unchecked(inclusiveEnd + 1));
else
return default(LongInterval);
}
/// <summary>
/// Returns an enumerator over all values in this interval.
/// </summary>
public IEnumerable<long> Range()
{
if (End == long.MinValue)
{
long i = Start;
while (true)
{
yield return i;
if (i == long.MaxValue)
break;
i++;
}
}
else
{
for (long i = Start; i < End; i++)
yield return i;
}
}
public override string ToString()
{
if (End == long.MinValue)
{
if (Start == long.MinValue)
return "[long.MinValue..long.MaxValue]";
else
return $"[{Start}..long.MaxValue]";
}
else if (Start == long.MinValue)
{
return $"[long.MinValue..{End})";
}
else
{
return $"[{Start}..{End})";
}
}
#region Equals and GetHashCode implementation
public override bool Equals(object? obj)
{
return (obj is LongInterval) && Equals((LongInterval)obj);
}
public bool Equals(LongInterval other)
{
return this.Start == other.Start && this.End == other.End;
}
public override int GetHashCode()
{
return (Start ^ End ^ (End << 7)).GetHashCode();
}
public static bool operator ==(LongInterval lhs, LongInterval rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(LongInterval lhs, LongInterval rhs)
{
return !(lhs == rhs);
}
#endregion
}
}
| ILSpy/ICSharpCode.Decompiler/Util/Interval.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler/Util/Interval.cs",
"repo_id": "ILSpy",
"token_count": 3123
} | 241 |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ServerGarbageCollection>true</ServerGarbageCollection>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>true</IsPackable>
<PackAsTool>true</PackAsTool>
<InvariantGlobalization>true</InvariantGlobalization>
<NeutralLanguage>en-US</NeutralLanguage>
<GenerateAssemblyVersionAttribute>False</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>False</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyInformationalVersionAttribute>False</GenerateAssemblyInformationalVersionAttribute>
<AssemblyName>ilspycmd</AssemblyName>
<ToolCommandName>ilspycmd</ToolCommandName>
<Description>Command-line decompiler using the ILSpy decompilation engine</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageVersion>8.0.0.0-noversion</PackageVersion>
<Copyright>Copyright 2011-$([System.DateTime]::Now.Year) AlphaSierraPapa</Copyright>
<PackageProjectUrl>https://github.com/icsharpcode/ILSpy/</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageIcon>ILSpyCmdNuGetPackageIcon.png</PackageIcon>
<RepositoryUrl>https://github.com/icsharpcode/ILSpy/</RepositoryUrl>
<Company>ic#code</Company>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>ILSpy Team</Authors>
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors>NU1605</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<None Include="ILSpyCmdNuGetPackageIcon.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.ILSpyX\ICSharpCode.ILSpyX.csproj" />
<ProjectReference Include="..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="McMaster.Extensions.Hosting.CommandLine" />
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="NuGet.Protocol" />
</ItemGroup>
<Target Name="ILSpyUpdateAssemblyInfo" AfterTargets="ResolveProjectReferences">
<ReadLinesFromFile ContinueOnError="true" File="..\VERSION">
<Output TaskParameter="Lines" PropertyName="PackageVersion" />
</ReadLinesFromFile>
</Target>
</Project>
| ILSpy/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj/0 | {
"file_path": "ILSpy/ICSharpCode.ILSpyCmd/ICSharpCode.ILSpyCmd.csproj",
"repo_id": "ILSpy",
"token_count": 887
} | 242 |
// 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.
namespace ICSharpCode.ILSpyX
{
/// <summary>
/// Version-DisplayName pair used in UI scenarios, for example ILSpy's language version dropdown.
/// </summary>
public class LanguageVersion
{
public string Version { get; }
public string DisplayName { get; }
public LanguageVersion(string version, string? name = null)
{
Version = version ?? "";
DisplayName = name ?? Version.ToString();
}
public override string ToString()
{
return $"[LanguageVersion DisplayName={DisplayName}, Version={Version}]";
}
}
}
| ILSpy/ICSharpCode.ILSpyX/LanguageVersion.cs/0 | {
"file_path": "ILSpy/ICSharpCode.ILSpyX/LanguageVersion.cs",
"repo_id": "ILSpy",
"token_count": 462
} | 243 |
using System;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using VSLangProj;
namespace ICSharpCode.ILSpy.AddIn.Commands
{
class OpenReferenceCommand : ILSpyCommand
{
static OpenReferenceCommand instance;
public OpenReferenceCommand(ILSpyAddInPackage owner)
: base(owner, PkgCmdIDList.cmdidOpenReferenceInILSpy)
{
ThreadHelper.ThrowIfNotOnUIThread();
}
protected override void OnBeforeQueryStatus(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (sender is OleMenuCommand menuItem)
{
menuItem.Visible = false;
var selectedItemData = owner.GetSelectedItemsData<object>().FirstOrDefault();
if (selectedItemData == null)
return;
/*
* Assure that we only show the context menu item on items we intend:
* - Project references
* - NuGet package references
*/
if ((AssemblyReferenceForILSpy.Detect(selectedItemData) != null)
|| (ProjectReferenceForILSpy.Detect(selectedItemData) != null)
|| (NuGetReferenceForILSpy.Detect(selectedItemData) != null))
{
menuItem.Visible = true;
}
}
}
protected override void OnExecute(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
var itemObject = owner.GetSelectedItemsData<object>().FirstOrDefault();
if (itemObject == null)
return;
var referenceItem = AssemblyReferenceForILSpy.Detect(itemObject);
if (referenceItem != null)
{
Reference reference = itemObject as Reference;
var project = reference.ContainingProject;
var roslynProject = owner.Workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == project.FileName);
var references = GetReferences(roslynProject);
var parameters = referenceItem.GetILSpyParameters(references);
if (references.TryGetValue(reference.Name, out var path))
OpenAssembliesInILSpy(parameters);
else
owner.ShowMessage("Could not find reference '{0}', please ensure the project and all references were built correctly!", reference.Name);
return;
}
// Handle project references
var projectRefItem = ProjectReferenceForILSpy.Detect(itemObject);
if (projectRefItem != null)
{
var projectItem = itemObject as ProjectItem;
string fileName = projectItem.ContainingProject?.FileName;
if (!string.IsNullOrEmpty(fileName))
{
var roslynProject = owner.Workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == fileName);
var references = GetReferences(roslynProject);
if (references.TryGetValue(projectItem.Name, out DetectedReference path))
{
OpenAssembliesInILSpy(projectRefItem.GetILSpyParameters(references));
return;
}
}
OpenAssembliesInILSpy(projectRefItem.GetILSpyParameters());
return;
}
// Handle NuGet references
var nugetRefItem = NuGetReferenceForILSpy.Detect(itemObject);
if (nugetRefItem != null)
{
OpenAssembliesInILSpy(nugetRefItem.GetILSpyParameters());
return;
}
}
internal static void Register(ILSpyAddInPackage owner)
{
ThreadHelper.ThrowIfNotOnUIThread();
instance = new OpenReferenceCommand(owner);
}
}
}
| ILSpy/ILSpy.AddIn.Shared/Commands/OpenReferenceCommand.cs/0 | {
"file_path": "ILSpy/ILSpy.AddIn.Shared/Commands/OpenReferenceCommand.cs",
"repo_id": "ILSpy",
"token_count": 1153
} | 244 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ad="clr-namespace:AvalonDock">
<SolidColorBrush x:Key="ManagedContentTabControlNormalBorderBrush" Color="#919B9C" />
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DefaultBackgroundBrush}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="#FFF4F2E8" />
<LinearGradientBrush x:Key="ManagedContentTabItemNormalBackground" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStop Color="#FFECEBE6" Offset="0" />
<GradientStop Color="#FFFFFFFF" Offset="1" />
</GradientBrush.GradientStops>
</LinearGradientBrush>
<LinearGradientBrush x:Key="ManagedContentTabItemInvNormalBackground" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStop Color="#FFFFFFFF" Offset="0" />
<GradientStop Color="#FFECEBE6" Offset="1" />
</GradientBrush.GradientStops>
</LinearGradientBrush>
<LinearGradientBrush x:Key="ManagedContentTabItemHotBackground" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStop Color="#FFFFFFFF" Offset="0" />
<GradientStop Color="#FFECEBE6" Offset="1" />
</GradientBrush.GradientStops>
</LinearGradientBrush>
<SolidColorBrush x:Key="ManagedContentTabItemSelectedBackground" Color="#FFFCFCFE" />
<SolidColorBrush x:Key="ManagedContentTabItemDisabledBackground" Color="#FFF5F4EA" />
<LinearGradientBrush x:Key="ManagedContentTabItemSelectedBorderBackround" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFFFC73C" Offset="0" />
<GradientStop Color="#FFE68B2C" Offset="1" />
</LinearGradientBrush>
<SolidColorBrush x:Key="ManagedContentTabItemSelectedBorderBrush" Color="#FFE68B2C" />
<SolidColorBrush x:Key="ManagedContentTabItemHotBorderBackround" Color="#FFFFC73C" />
<SolidColorBrush x:Key="ManagedContentTabItemHotBorderBrush" Color="#FFE68B2C" />
<SolidColorBrush x:Key="ManagedContentTabItemDisabledBorderBrush" Color="#FFC9C7BA" />
<LinearGradientBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DockablePaneTitleBackgroundSelected}, TypeInTargetAssembly={x:Type ad:DockingManager}}" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStop Color="#FF3B80ED" Offset="0" />
<GradientStop Color="#FF316AC5" Offset="1" />
</GradientBrush.GradientStops>
</LinearGradientBrush>
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DockablePaneTitleBackground}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="#FFCCC5BA" />
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DockablePaneTitleForeground}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="Black" />
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DockablePaneTitleForegroundSelected}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="White" />
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.PaneHeaderCommandBackground}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="{x:Static SystemColors.ControlLightLightColor}" Opacity="0.5" />
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.PaneHeaderCommandBorderBrush}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="{x:Static SystemColors.ControlDarkColor}" />
<LinearGradientBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DocumentHeaderBackground}, TypeInTargetAssembly={x:Type ad:DockingManager}}" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFFFFFFF" Offset="0" />
<GradientStop Color="#FFE0E0E0" Offset="1" />
</LinearGradientBrush>
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DocumentHeaderForeground}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="{x:Static SystemColors.WindowTextColor}" />
<LinearGradientBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DocumentHeaderBackgroundSelected}, TypeInTargetAssembly={x:Type ad:DockingManager}}" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFFFFFFF" Offset="0" />
<GradientStop Color="#FFC1D2EE" Offset="1" />
</LinearGradientBrush>
<SolidColorBrush x:Key="{ComponentResourceKey ResourceId={x:Static ad:AvalonDockBrushes.DocumentHeaderBackgroundMouseOver}, TypeInTargetAssembly={x:Type ad:DockingManager}}" Color="White" />
</ResourceDictionary> | ILSpy/ILSpy.BamlDecompiler.Tests/Cases/AvalonDockBrushes.xaml/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/AvalonDockBrushes.xaml",
"repo_id": "ILSpy",
"token_count": 1624
} | 245 |
<Label xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Blub}" Content="{Binding Path=Blah, StringFormat={}{0} items}">
<FrameworkElement.Style>
<Style />
</FrameworkElement.Style>
</Label> | ILSpy/ILSpy.BamlDecompiler.Tests/Cases/MarkupExtension.xaml/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/MarkupExtension.xaml",
"repo_id": "ILSpy",
"token_count": 105
} | 246 |
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.BamlDecompiler;
using ICSharpCode.ILSpy;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.ViewModels;
namespace ILSpy.BamlDecompiler
{
public sealed class BamlResourceEntryNode : ResourceEntryNode
{
public BamlResourceEntryNode(string key, Func<Stream> data) : base(key, data)
{
}
public override bool View(TabPageModel tabPage)
{
IHighlightingDefinition highlighting = null;
tabPage.SupportsLanguageSwitching = false;
tabPage.ShowTextView(textView => textView.RunWithCancellation(
token => Task.Factory.StartNew(
() => {
AvalonEditTextOutput output = new AvalonEditTextOutput();
try
{
LoadBaml(output, token);
highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
}
catch (Exception ex)
{
output.Write(ex.ToString());
}
return output;
}, token))
.Then(output => textView.ShowNode(output, this, highlighting))
.HandleExceptions());
return true;
}
void LoadBaml(AvalonEditTextOutput output, CancellationToken cancellationToken)
{
var asm = this.Ancestors().OfType<AssemblyTreeNode>().First().LoadedAssembly;
using var data = OpenStream();
BamlDecompilerTypeSystem typeSystem = new BamlDecompilerTypeSystem(asm.GetPEFileOrNull(), asm.GetAssemblyResolver());
var decompiler = new XamlDecompiler(typeSystem, new BamlDecompilerSettings());
decompiler.CancellationToken = cancellationToken;
var result = decompiler.Decompile(data);
output.Write(result.Xaml.ToString());
}
}
}
| ILSpy/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs/0 | {
"file_path": "ILSpy/ILSpy.BamlDecompiler/BamlResourceEntryNode.cs",
"repo_id": "ILSpy",
"token_count": 946
} | 247 |
{
"profiles": {
"ILSpy.ReadyToRun": {
"commandName": "Executable",
"executablePath": "C:\\Users\\sie_p\\Projects\\ILSpy\\ILSpy\\bin\\Debug\\net472\\ILSpy.exe",
"commandLineArgs": "/separate /language:ReadyToRun"
}
}
} | ILSpy/ILSpy.ReadyToRun/Properties/launchSettings.json/0 | {
"file_path": "ILSpy/ILSpy.ReadyToRun/Properties/launchSettings.json",
"repo_id": "ILSpy",
"token_count": 112
} | 248 |
// 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.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpy.Themes;
using ICSharpCode.ILSpy.Updates;
using ICSharpCode.ILSpyX.Settings;
namespace ICSharpCode.ILSpy
{
[ExportMainMenuCommand(ParentMenuID = nameof(Resources._Help), Header = nameof(Resources._About), MenuOrder = 99999)]
sealed class AboutPage : SimpleCommand
{
public override void Execute(object parameter)
{
MainWindow.Instance.NavigateTo(
new RequestNavigateEventArgs(new Uri("resource://aboutpage"), null),
inNewTabPage: true
);
}
public static void Display(DecompilerTextView textView)
{
AvalonEditTextOutput output = new AvalonEditTextOutput() {
Title = Resources.About,
EnableHyperlinks = true
};
output.WriteLine(Resources.ILSpyVersion + DecompilerVersionInfo.FullVersion);
string prodVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(Uri).Assembly.Location).ProductVersion;
output.WriteLine(Resources.NETFrameworkVersion + prodVersion);
output.AddUIElement(
delegate {
StackPanel stackPanel = new StackPanel();
stackPanel.HorizontalAlignment = HorizontalAlignment.Center;
stackPanel.Orientation = Orientation.Horizontal;
if (NotifyOfUpdatesStrategy.LatestAvailableVersion == null)
{
AddUpdateCheckButton(stackPanel, textView);
}
else
{
// we already retrieved the latest version sometime earlier
ShowAvailableVersion(NotifyOfUpdatesStrategy.LatestAvailableVersion, stackPanel);
}
CheckBox checkBox = new CheckBox();
checkBox.Margin = new Thickness(4);
checkBox.Content = Resources.AutomaticallyCheckUpdatesEveryWeek;
UpdateSettings settings = new UpdateSettings(ILSpySettings.Load());
checkBox.SetBinding(CheckBox.IsCheckedProperty, new Binding("AutomaticUpdateCheckEnabled") { Source = settings });
return new StackPanel {
Margin = new Thickness(0, 4, 0, 0),
Cursor = Cursors.Arrow,
Children = { stackPanel, checkBox }
};
});
output.WriteLine();
foreach (var plugin in App.ExportProvider.GetExportedValues<IAboutPageAddition>())
plugin.Write(output);
output.WriteLine();
output.Address = new Uri("resource://AboutPage");
using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt))
{
using (StreamReader r = new StreamReader(s))
{
string line;
while ((line = r.ReadLine()) != null)
{
output.WriteLine(line);
}
}
}
output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MIT License", "resource:license.txt"));
output.AddVisualLineElementGenerator(new MyLinkElementGenerator("third-party notices", "resource:third-party-notices.txt"));
textView.ShowText(output);
}
sealed class MyLinkElementGenerator : LinkElementGenerator
{
readonly Uri uri;
public MyLinkElementGenerator(string matchText, string url) : base(new Regex(Regex.Escape(matchText)))
{
this.uri = new Uri(url);
this.RequireControlModifierForClick = false;
}
protected override Uri GetUriFromMatch(Match match)
{
return uri;
}
}
static void AddUpdateCheckButton(StackPanel stackPanel, DecompilerTextView textView)
{
Button button = ThemeManager.Current.CreateButton();
button.Content = Resources.CheckUpdates;
button.Cursor = Cursors.Arrow;
stackPanel.Children.Add(button);
button.Click += async delegate {
button.Content = Resources.Checking;
button.IsEnabled = false;
try
{
AvailableVersionInfo vInfo = await NotifyOfUpdatesStrategy.GetLatestVersionAsync();
stackPanel.Children.Clear();
ShowAvailableVersion(vInfo, stackPanel);
}
catch (Exception ex)
{
AvalonEditTextOutput exceptionOutput = new AvalonEditTextOutput();
exceptionOutput.WriteLine(ex.ToString());
textView.ShowText(exceptionOutput);
}
};
}
static void ShowAvailableVersion(AvailableVersionInfo availableVersion, StackPanel stackPanel)
{
if (AppUpdateService.CurrentVersion == availableVersion.Version)
{
stackPanel.Children.Add(
new Image {
Width = 16, Height = 16,
Source = Images.OK,
Margin = new Thickness(4, 0, 4, 0)
});
stackPanel.Children.Add(
new TextBlock {
Text = Resources.UsingLatestRelease,
VerticalAlignment = VerticalAlignment.Bottom
});
}
else if (AppUpdateService.CurrentVersion < availableVersion.Version)
{
stackPanel.Children.Add(
new TextBlock {
Text = string.Format(Resources.VersionAvailable, availableVersion.Version),
Margin = new Thickness(0, 0, 8, 0),
VerticalAlignment = VerticalAlignment.Bottom
});
if (availableVersion.DownloadUrl != null)
{
Button button = ThemeManager.Current.CreateButton();
button.Content = Resources.Download;
button.Cursor = Cursors.Arrow;
button.Click += delegate {
MainWindow.OpenLink(availableVersion.DownloadUrl);
};
stackPanel.Children.Add(button);
}
}
else
{
stackPanel.Children.Add(new TextBlock { Text = Resources.UsingNightlyBuildNewerThanLatestRelease });
}
}
}
/// <summary>
/// Interface that allows plugins to extend the about page.
/// </summary>
public interface IAboutPageAddition
{
void Write(ISmartTextOutput textOutput);
}
}
| ILSpy/ILSpy/AboutPage.cs/0 | {
"file_path": "ILSpy/ILSpy/AboutPage.cs",
"repo_id": "ILSpy",
"token_count": 2338
} | 249 |
// 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.Windows;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.ILSpy.Options;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpy.ViewModels;
using ICSharpCode.TreeView;
using Microsoft.Win32;
namespace ICSharpCode.ILSpy.TextView
{
[ExportContextMenuEntry(Header = nameof(Resources._SaveCode), Category = nameof(Resources.Save), Icon = "Images/Save")]
sealed class SaveCodeContextMenuEntry : IContextMenuEntry
{
public void Execute(TextViewContext context)
{
Execute(context.SelectedTreeNodes);
}
public bool IsEnabled(TextViewContext context) => true;
public bool IsVisible(TextViewContext context)
{
return CanExecute(context.SelectedTreeNodes);
}
public static bool CanExecute(IReadOnlyList<SharpTreeNode> selectedNodes)
{
if (selectedNodes == null || selectedNodes.Any(n => !(n is ILSpyTreeNode)))
return false;
return selectedNodes.Count == 1
|| (selectedNodes.Count > 1 && (selectedNodes.All(n => n is AssemblyTreeNode) || selectedNodes.All(n => n is IMemberTreeNode)));
}
public static void Execute(IReadOnlyList<SharpTreeNode> selectedNodes)
{
var currentLanguage = MainWindow.Instance.CurrentLanguage;
var tabPage = Docking.DockWorkspace.Instance.ActiveTabPage;
tabPage.ShowTextView(textView => {
if (selectedNodes.Count == 1 && selectedNodes[0] is ILSpyTreeNode singleSelection)
{
// if there's only one treenode selected
// we will invoke the custom Save logic
if (singleSelection.Save(tabPage))
return;
}
else if (selectedNodes.Count > 1 && selectedNodes.All(n => n is AssemblyTreeNode))
{
var selectedPath = SelectSolutionFile();
if (!string.IsNullOrEmpty(selectedPath))
{
var assemblies = selectedNodes.OfType<AssemblyTreeNode>()
.Select(n => n.LoadedAssembly)
.Where(a => a.IsLoadedAsValidAssembly).ToArray();
SolutionWriter.CreateSolution(textView, selectedPath, currentLanguage, assemblies);
}
return;
}
// Fallback: if nobody was able to handle the request, use default behavior.
// try to save all nodes to disk.
var options = MainWindow.Instance.CreateDecompilationOptions();
options.FullDecompilation = true;
textView.SaveToDisk(currentLanguage, selectedNodes.OfType<ILSpyTreeNode>(), options);
});
}
/// <summary>
/// Shows a File Selection dialog where the user can select the target file for the solution.
/// </summary>
/// <param name="path">The initial path to show in the dialog. If not specified, the 'Documents' directory
/// will be used.</param>
///
/// <returns>The full path of the selected target file, or <c>null</c> if the user canceled.</returns>
static string SelectSolutionFile()
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "Solution.sln";
dlg.Filter = Resources.VisualStudioSolutionFileSlnAllFiles;
if (dlg.ShowDialog() != true)
{
return null;
}
string selectedPath = Path.GetDirectoryName(dlg.FileName);
bool directoryNotEmpty;
try
{
directoryNotEmpty = Directory.EnumerateFileSystemEntries(selectedPath).Any();
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is System.Security.SecurityException)
{
MessageBox.Show(
"The directory cannot be accessed. Please ensure it exists and you have sufficient rights to access it.",
"Solution directory not accessible",
MessageBoxButton.OK, MessageBoxImage.Error);
return null;
}
if (directoryNotEmpty)
{
var result = MessageBox.Show(
Resources.AssemblySaveCodeDirectoryNotEmpty,
Resources.AssemblySaveCodeDirectoryNotEmptyTitle,
MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (result == MessageBoxResult.No)
return null; // -> abort
}
return dlg.FileName;
}
}
}
| ILSpy/ILSpy/Commands/SaveCodeContextMenuEntry.cs/0 | {
"file_path": "ILSpy/ILSpy/Commands/SaveCodeContextMenuEntry.cs",
"repo_id": "ILSpy",
"token_count": 1698
} | 250 |
// 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.Markup;
namespace ICSharpCode.ILSpy.Controls
{
/// <summary>
/// ExtensionMethods used in ILSpy.
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Sets the value of a dependency property on <paramref name="targetObject"/> using a markup extension.
/// </summary>
/// <remarks>This method does not support markup extensions like x:Static that depend on
/// having a XAML file as context.</remarks>
public static void SetValueToExtension(this DependencyObject targetObject, DependencyProperty property, MarkupExtension markupExtension)
{
// This method was copied from ICSharpCode.Core.Presentation (with permission to switch license to X11)
if (targetObject == null)
throw new ArgumentNullException(nameof(targetObject));
if (property == null)
throw new ArgumentNullException(nameof(property));
if (markupExtension == null)
throw new ArgumentNullException(nameof(markupExtension));
var serviceProvider = new SetValueToExtensionServiceProvider(targetObject, property);
targetObject.SetValue(property, markupExtension.ProvideValue(serviceProvider));
}
sealed class SetValueToExtensionServiceProvider : IServiceProvider, IProvideValueTarget
{
// This class was copied from ICSharpCode.Core.Presentation (with permission to switch license to X11)
readonly DependencyObject targetObject;
readonly DependencyProperty targetProperty;
public SetValueToExtensionServiceProvider(DependencyObject targetObject, DependencyProperty property)
{
this.targetObject = targetObject;
this.targetProperty = property;
}
public object GetService(Type serviceType)
{
if (serviceType == typeof(IProvideValueTarget))
return this;
else
return null;
}
public object TargetObject {
get { return targetObject; }
}
public object TargetProperty {
get { return targetProperty; }
}
}
}
}
| ILSpy/ILSpy/Controls/ExtensionMethods.cs/0 | {
"file_path": "ILSpy/ILSpy/Controls/ExtensionMethods.cs",
"repo_id": "ILSpy",
"token_count": 903
} | 251 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.ILSpy.Properties;
namespace ICSharpCode.ILSpy.Docking
{
[ExportMainMenuCommand(Header = nameof(Resources.Window_CloseAllDocuments), ParentMenuID = nameof(Resources._Window))]
class CloseAllDocumentsCommand : SimpleCommand
{
public override void Execute(object parameter)
{
DockWorkspace.Instance.CloseAllTabs();
}
}
[ExportMainMenuCommand(Header = nameof(Resources.Window_ResetLayout), ParentMenuID = nameof(Resources._Window))]
class ResetLayoutCommand : SimpleCommand
{
public override void Execute(object parameter)
{
DockWorkspace.Instance.ResetLayout();
}
}
}
| ILSpy/ILSpy/Docking/CloseAllDocumentsCommand.cs/0 | {
"file_path": "ILSpy/ILSpy/Docking/CloseAllDocumentsCommand.cs",
"repo_id": "ILSpy",
"token_count": 239
} | 252 |
<!-- 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="F1M8.0001,3.0004L8.0001,6.0004 6.0001,6.0004 6.0001,4.0004 9.99999999997669E-05,4.0004 9.99999999997669E-05,10.9994 6.0001,10.9994 6.0001,8.9994 8.0001,8.9994 8.0001,12.0004 16.0001,12.0004 16.0001,3.0004z" />
<GeometryDrawing Brush="#FF414141" Geometry="F1M1,10L5,10 5,5 1,5z" />
<GeometryDrawing Brush="#FF414141" Geometry="F1M9,11L15,11 15,4 9,4z" />
<GeometryDrawing Brush="#FF414141" Geometry="F1M6,8L8,8 8,7 6,7z" />
</DrawingGroup.Children>
</DrawingGroup>
| ILSpy/ILSpy/Images/Assembly.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/Assembly.xaml",
"repo_id": "ILSpy",
"token_count": 364
} | 253 |
<!-- This file was generated by the AiToXaml tool.-->
<!-- Tool Version: 14.0.22307.0 -->
<DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ClipGeometry="M0,0 V16 H16 V0 H0 Z">
<GeometryDrawing Geometry="F1 M16,16z M0,0z M16,16L0,16 0,0 16,0 16,16z">
<GeometryDrawing.Brush>
<SolidColorBrush Color="#FFF6F6F6" Opacity="0" />
</GeometryDrawing.Brush>
</GeometryDrawing>
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1 M16,16z M0,0z M15,3.349L15,11.752 8.975,16 8.07,16 1,11.582 1,3.327 7.595,0 8.713,0 15,3.349z" />
<GeometryDrawing Brush="#FFF0EFF1" Geometry="F1 M16,16z M0,0z M12.715,4.398L8.487,7.02 3.565,4.272 8.143,1.963 12.715,4.398z M3,5.102L8,7.894 8,13.599 3,10.474 3,5.102z M9,13.536L9,7.878 13,5.398 13,10.715 9,13.536z" />
<GeometryDrawing Brush="#FF218022" Geometry="F1 M16,16z M0,0z M8.156,0.837L2,3.942 2,11.027 8.517,15.1 14,11.233 14,3.95 8.156,0.837z M12.715,4.398L8.487,7.02 3.565,4.272 8.143,1.963 12.715,4.398z M3,5.102L8,7.894 8,13.599 3,10.474 3,5.102z M9,13.536L9,7.878 13,5.398 13,10.715 9,13.536z" />
</DrawingGroup>
| ILSpy/ILSpy/Images/Constructor.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/Constructor.xaml",
"repo_id": "ILSpy",
"token_count": 571
} | 254 |
<!-- 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="F1M15.993,16L-0.00699999999999967,16 -0.00699999999999967,0 15.993,0z" />
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M1,15L16,15 16,1 1,1z" />
<GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M14,7L3,7 3,5 14,5z M14,10L3,10 3,8 14,8z M14,13L3,13 3,11 14,11z" />
<GeometryDrawing Brush="#FF424242" Geometry="F1M14,7L3,7 3,5 14,5z M14,10L3,10 3,8 14,8z M14,13L3,13 3,11 14,11z M2,14L15,14 15,2 2,2z" />
</DrawingGroup.Children>
</DrawingGroup> | ILSpy/ILSpy/Images/Heap.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/Heap.xaml",
"repo_id": "ILSpy",
"token_count": 330
} | 255 |
<!-- 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="F1M8,16C3.589,16 0,12.411 0,8 0,3.589 3.589,0 8,0 12.411,0 16,3.589 16,8 16,12.411 12.411,16 8,16" />
<GeometryDrawing Brush="#FF329932" Geometry="F1M6.2998,12.3887L3.0428,9.1317 4.4568,7.7177 6.2998,9.5607 11.5428,4.3177 12.9568,5.7317z M7.9998,0.999700000000001C4.1338,0.999700000000001 0.9998,4.1337 0.9998,7.9997 0.9998,11.8657 4.1338,14.9997 7.9998,14.9997 11.8658,14.9997 14.9998,11.8657 14.9998,7.9997 14.9998,4.1337 11.8658,0.999700000000001 7.9998,0.999700000000001" />
<GeometryDrawing Brush="#FFFFFFFF" Geometry="F1M6.2998,12.3887L3.0428,9.1317 4.4568,7.7177 6.2998,9.5607 11.5428,4.3177 12.9568,5.7317z" />
</DrawingGroup.Children>
</DrawingGroup> | ILSpy/ILSpy/Images/OK.xaml/0 | {
"file_path": "ILSpy/ILSpy/Images/OK.xaml",
"repo_id": "ILSpy",
"token_count": 488
} | 256 |
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Windows;
using System.Windows.Controls;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.CSharp.OutputVisitor;
using ICSharpCode.Decompiler.CSharp.ProjectDecompiler;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Transforms;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Output;
using ICSharpCode.Decompiler.Solution;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.ILSpy.TreeNodes;
using ICSharpCode.ILSpyX;
using LanguageVersion = ICSharpCode.ILSpyX.LanguageVersion;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// C# decompiler integration into ILSpy.
/// Note: if you're interested in using the decompiler without the ILSpy UI,
/// please directly use the CSharpDecompiler class.
/// </summary>
[Export(typeof(Language))]
public class CSharpLanguage : Language
{
string name = "C#";
bool showAllMembers = false;
int transformCount = int.MaxValue;
#if DEBUG
internal static IEnumerable<CSharpLanguage> GetDebugLanguages()
{
string lastTransformName = "no transforms";
int transformCount = 0;
foreach (var transform in CSharpDecompiler.GetAstTransforms())
{
yield return new CSharpLanguage {
transformCount = transformCount,
name = "C# - " + lastTransformName,
showAllMembers = true
};
lastTransformName = "after " + transform.GetType().Name;
transformCount++;
}
yield return new CSharpLanguage {
name = "C# - " + lastTransformName,
showAllMembers = true
};
}
#endif
public override string Name {
get { return name; }
}
public override string FileExtension {
get { return ".cs"; }
}
public override string ProjectFileExtension {
get { return ".csproj"; }
}
IReadOnlyList<LanguageVersion> versions;
public override IReadOnlyList<LanguageVersion> LanguageVersions {
get {
if (versions == null)
{
versions = new List<LanguageVersion>() {
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp1.ToString(), "C# 1.0 / VS .NET"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp2.ToString(), "C# 2.0 / VS 2005"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp3.ToString(), "C# 3.0 / VS 2008"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp4.ToString(), "C# 4.0 / VS 2010"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp5.ToString(), "C# 5.0 / VS 2012"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp6.ToString(), "C# 6.0 / VS 2015"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp7.ToString(), "C# 7.0 / VS 2017"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp7_1.ToString(), "C# 7.1 / VS 2017.3"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp7_2.ToString(), "C# 7.2 / VS 2017.4"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp7_3.ToString(), "C# 7.3 / VS 2017.7"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp8_0.ToString(), "C# 8.0 / VS 2019"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp9_0.ToString(), "C# 9.0 / VS 2019.8"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp10_0.ToString(), "C# 10.0 / VS 2022"),
new LanguageVersion(Decompiler.CSharp.LanguageVersion.CSharp11_0.ToString(), "C# 11.0 / VS 2022.4"),
};
}
return versions;
}
}
CSharpDecompiler CreateDecompiler(PEFile module, DecompilationOptions options)
{
CSharpDecompiler decompiler = new CSharpDecompiler(module, module.GetAssemblyResolver(options.DecompilerSettings.AutoLoadAssemblyReferences), options.DecompilerSettings);
decompiler.CancellationToken = options.CancellationToken;
decompiler.DebugInfoProvider = module.GetDebugInfoOrNull();
while (decompiler.AstTransforms.Count > transformCount)
decompiler.AstTransforms.RemoveAt(decompiler.AstTransforms.Count - 1);
if (options.EscapeInvalidIdentifiers)
{
decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
}
return decompiler;
}
void WriteCode(ITextOutput output, DecompilerSettings settings, SyntaxTree syntaxTree, IDecompilerTypeSystem typeSystem)
{
syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true });
output.IndentationString = settings.CSharpFormattingOptions.IndentationString;
TokenWriter tokenWriter = new TextTokenWriter(output, settings, typeSystem);
if (output is ISmartTextOutput highlightingOutput)
{
tokenWriter = new CSharpHighlightingTokenWriter(tokenWriter, highlightingOutput);
}
syntaxTree.AcceptVisitor(new CSharpOutputVisitor(tokenWriter, settings.CSharpFormattingOptions));
}
public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
{
PEFile assembly = method.ParentModule.PEFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output);
WriteCommentLine(output, assembly.FullName);
WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
var methodDefinition = decompiler.TypeSystem.MainModule.ResolveEntity(method.MetadataToken) as IMethod;
if (methodDefinition.IsConstructor && methodDefinition.DeclaringType.IsReferenceType != false)
{
var members = CollectFieldsAndCtors(methodDefinition.DeclaringTypeDefinition, methodDefinition.IsStatic);
decompiler.AstTransforms.Add(new SelectCtorTransform(methodDefinition));
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
}
else
{
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(method.MetadataToken), decompiler.TypeSystem);
}
}
class SelectCtorTransform : IAstTransform
{
readonly IMethod ctor;
readonly HashSet<ISymbol> removedSymbols = new HashSet<ISymbol>();
public SelectCtorTransform(IMethod ctor)
{
this.ctor = ctor;
}
public void Run(AstNode rootNode, TransformContext context)
{
ConstructorDeclaration ctorDecl = null;
foreach (var node in rootNode.Children)
{
switch (node)
{
case ConstructorDeclaration ctor:
if (ctor.GetSymbol() == this.ctor)
{
ctorDecl = ctor;
}
else
{
// remove other ctors
ctor.Remove();
removedSymbols.Add(ctor.GetSymbol());
}
break;
case FieldDeclaration fd:
// Remove any fields without initializers
if (fd.Variables.All(v => v.Initializer.IsNull))
{
fd.Remove();
removedSymbols.Add(fd.GetSymbol());
}
break;
}
}
if (ctorDecl?.Initializer.ConstructorInitializerType == ConstructorInitializerType.This)
{
// remove all fields
foreach (var node in rootNode.Children)
{
switch (node)
{
case FieldDeclaration fd:
fd.Remove();
removedSymbols.Add(fd.GetSymbol());
break;
}
}
}
foreach (var node in rootNode.Children)
{
if (node is Comment && removedSymbols.Contains(node.GetSymbol()))
node.Remove();
}
}
}
public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options)
{
PEFile assembly = property.ParentModule.PEFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output);
WriteCommentLine(output, assembly.FullName);
WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true));
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(property.MetadataToken), decompiler.TypeSystem);
}
public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options)
{
PEFile assembly = field.ParentModule.PEFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output);
WriteCommentLine(output, assembly.FullName);
WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
if (field.IsConst)
{
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(field.MetadataToken), decompiler.TypeSystem);
}
else
{
var members = CollectFieldsAndCtors(field.DeclaringTypeDefinition, field.IsStatic);
var resolvedField = decompiler.TypeSystem.MainModule.GetDefinition((FieldDefinitionHandle)field.MetadataToken);
decompiler.AstTransforms.Add(new SelectFieldTransform(resolvedField));
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
}
}
static List<EntityHandle> CollectFieldsAndCtors(ITypeDefinition type, bool isStatic)
{
var members = new List<EntityHandle>();
foreach (var field in type.Fields)
{
if (!field.MetadataToken.IsNil && field.IsStatic == isStatic)
members.Add(field.MetadataToken);
}
foreach (var ctor in type.Methods)
{
if (!ctor.MetadataToken.IsNil && ctor.IsConstructor && ctor.IsStatic == isStatic)
members.Add(ctor.MetadataToken);
}
return members;
}
/// <summary>
/// Removes all top-level members except for the specified fields.
/// </summary>
sealed class SelectFieldTransform : IAstTransform
{
readonly IField field;
public SelectFieldTransform(IField field)
{
this.field = field;
}
public void Run(AstNode rootNode, TransformContext context)
{
foreach (var node in rootNode.Children)
{
switch (node)
{
case EntityDeclaration ed:
if (node.GetSymbol() != field)
node.Remove();
break;
case Comment c:
if (c.GetSymbol() != field)
node.Remove();
break;
}
}
}
}
public override void DecompileEvent(IEvent @event, ITextOutput output, DecompilationOptions options)
{
PEFile assembly = @event.ParentModule.PEFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output);
WriteCommentLine(output, assembly.FullName);
WriteCommentLine(output, TypeToString(@event.DeclaringType, includeNamespace: true));
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(@event.MetadataToken), decompiler.TypeSystem);
}
public override void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options)
{
PEFile assembly = type.ParentModule.PEFile;
CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
AddReferenceAssemblyWarningMessage(assembly, output);
AddReferenceWarningMessage(assembly, output);
WriteCommentLine(output, assembly.FullName);
WriteCommentLine(output, TypeToString(type, includeNamespace: true));
WriteCode(output, options.DecompilerSettings, decompiler.Decompile(type.MetadataToken), decompiler.TypeSystem);
}
void AddReferenceWarningMessage(PEFile module, ITextOutput output)
{
var loadedAssembly = MainWindow.Instance.CurrentAssemblyList.GetAssemblies().FirstOrDefault(la => la.GetPEFileOrNull() == module);
if (loadedAssembly == null || !loadedAssembly.LoadedAssemblyReferencesInfo.HasErrors)
return;
string line1 = Properties.Resources.WarningSomeAssemblyReference;
string line2 = Properties.Resources.PropertyManuallyMissingReferencesListLoadedAssemblies;
AddWarningMessage(module, output, line1, line2, Properties.Resources.ShowAssemblyLoad, Images.ViewCode, delegate {
ILSpyTreeNode assemblyNode = MainWindow.Instance.FindTreeNode(module);
assemblyNode.EnsureLazyChildren();
MainWindow.Instance.SelectNode(assemblyNode.Children.OfType<ReferenceFolderTreeNode>().Single());
});
}
void AddReferenceAssemblyWarningMessage(PEFile module, ITextOutput output)
{
var metadata = module.Metadata;
if (!metadata.GetCustomAttributes(Handle.AssemblyDefinition).HasKnownAttribute(metadata, KnownAttribute.ReferenceAssembly))
return;
string line1 = Properties.Resources.WarningAsmMarkedRef;
AddWarningMessage(module, output, line1);
}
void AddWarningMessage(PEFile module, ITextOutput output, string line1, string line2 = null,
string buttonText = null, System.Windows.Media.ImageSource buttonImage = null, RoutedEventHandler buttonClickHandler = null)
{
if (output is ISmartTextOutput fancyOutput)
{
string text = line1;
if (!string.IsNullOrEmpty(line2))
text += Environment.NewLine + line2;
fancyOutput.AddUIElement(() => new StackPanel {
Margin = new Thickness(5),
Orientation = Orientation.Horizontal,
Children = {
new Image {
Width = 32,
Height = 32,
Source = Images.Load(this, "Images/Warning")
},
new TextBlock {
Margin = new Thickness(5, 0, 0, 0),
Text = text
}
}
});
fancyOutput.WriteLine();
if (buttonText != null && buttonClickHandler != null)
{
fancyOutput.AddButton(buttonImage, buttonText, buttonClickHandler);
fancyOutput.WriteLine();
}
}
else
{
WriteCommentLine(output, line1);
if (!string.IsNullOrEmpty(line2))
WriteCommentLine(output, line2);
}
}
public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
{
var module = assembly.GetPEFileOrNull();
if (module == null)
{
return null;
}
if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
{
if (!WholeProjectDecompiler.CanUseSdkStyleProjectFormat(module))
{
options.DecompilerSettings.UseSdkStyleProjectFormat = false;
}
var decompiler = new ILSpyWholeProjectDecompiler(assembly, options);
decompiler.ProgressIndicator = options.Progress;
return decompiler.DecompileProject(module, options.SaveAsProjectDirectory, new TextOutputWriter(output), options.CancellationToken);
}
else
{
AddReferenceAssemblyWarningMessage(module, output);
AddReferenceWarningMessage(module, output);
output.WriteLine();
base.DecompileAssembly(assembly, output, options);
// don't automatically load additional assemblies when an assembly node is selected in the tree view
IAssemblyResolver assemblyResolver = assembly.GetAssemblyResolver(loadOnDemand: options.FullDecompilation && options.DecompilerSettings.AutoLoadAssemblyReferences);
var typeSystem = new DecompilerTypeSystem(module, assemblyResolver, options.DecompilerSettings);
var globalType = typeSystem.MainModule.TypeDefinitions.FirstOrDefault();
if (globalType != null)
{
output.Write("// Global type: ");
output.WriteReference(globalType, EscapeName(globalType.FullName));
output.WriteLine();
}
var metadata = module.Metadata;
var corHeader = module.Reader.PEHeaders.CorHeader;
var entrypointHandle = MetadataTokenHelpers.EntityHandleOrNil(corHeader.EntryPointTokenOrRelativeVirtualAddress);
if (!entrypointHandle.IsNil && entrypointHandle.Kind == HandleKind.MethodDefinition)
{
var entrypoint = typeSystem.MainModule.ResolveMethod(entrypointHandle, new Decompiler.TypeSystem.GenericContext());
if (entrypoint != null)
{
output.Write("// Entry point: ");
output.WriteReference(entrypoint, EscapeName(entrypoint.DeclaringType.FullName + "." + entrypoint.Name));
output.WriteLine();
}
}
output.WriteLine("// Architecture: " + GetPlatformDisplayName(module));
if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.ILOnly) == 0)
{
output.WriteLine("// This assembly contains unmanaged code.");
}
string runtimeName = GetRuntimeDisplayName(module);
if (runtimeName != null)
{
output.WriteLine("// Runtime: " + runtimeName);
}
if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.StrongNameSigned) != 0)
{
output.WriteLine("// This assembly is signed with a strong name key.");
}
if (module.Reader.ReadDebugDirectory().Any(d => d.Type == DebugDirectoryEntryType.Reproducible))
{
output.WriteLine("// This assembly was compiled using the /deterministic option.");
}
if (module.Metadata.MetadataKind != MetadataKind.Ecma335)
{
output.WriteLine("// This assembly was loaded with Windows Runtime projections applied.");
}
if (metadata.IsAssembly)
{
var asm = metadata.GetAssemblyDefinition();
if (asm.HashAlgorithm != AssemblyHashAlgorithm.None)
output.WriteLine("// Hash algorithm: " + asm.HashAlgorithm.ToString().ToUpper());
if (!asm.PublicKey.IsNil)
{
output.Write("// Public key: ");
var reader = metadata.GetBlobReader(asm.PublicKey);
while (reader.RemainingBytes > 0)
output.Write(reader.ReadByte().ToString("x2"));
output.WriteLine();
}
}
var debugInfo = assembly.GetDebugInfoOrNull();
if (debugInfo != null)
{
output.WriteLine("// Debug info: " + debugInfo.Description);
}
output.WriteLine();
CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings);
decompiler.CancellationToken = options.CancellationToken;
if (options.EscapeInvalidIdentifiers)
{
decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
}
SyntaxTree st;
if (options.FullDecompilation)
{
st = decompiler.DecompileWholeModuleAsSingleFile();
}
else
{
st = decompiler.DecompileModuleAndAssemblyAttributes();
}
WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem);
return null;
}
}
class ILSpyWholeProjectDecompiler : WholeProjectDecompiler
{
readonly LoadedAssembly assembly;
readonly DecompilationOptions options;
public ILSpyWholeProjectDecompiler(LoadedAssembly assembly, DecompilationOptions options)
: base(options.DecompilerSettings, assembly.GetAssemblyResolver(options.DecompilerSettings.AutoLoadAssemblyReferences, options.DecompilerSettings.ApplyWindowsRuntimeProjections), assembly.GetAssemblyReferenceClassifier(options.DecompilerSettings.ApplyWindowsRuntimeProjections), assembly.GetDebugInfoOrNull())
{
this.assembly = assembly;
this.options = options;
}
protected override IEnumerable<ProjectItemInfo> WriteResourceToFile(string fileName, string resourceName, Stream entryStream)
{
var context = new ResourceFileHandlerContext(options);
foreach (var handler in App.ExportProvider.GetExportedValues<IResourceFileHandler>())
{
if (handler.CanHandle(fileName, context))
{
entryStream.Position = 0;
fileName = handler.WriteResourceToFile(assembly, fileName, entryStream, context);
return new[] { new ProjectItemInfo(handler.EntryType, fileName) { PartialTypes = context.PartialTypes }.With(context.AdditionalProperties) };
}
}
return base.WriteResourceToFile(fileName, resourceName, entryStream);
}
}
static CSharpAmbience CreateAmbience()
{
CSharpAmbience ambience = new CSharpAmbience();
// Do not forget to update CSharpAmbienceTests.ILSpyMainTreeViewTypeFlags, if this ever changes.
ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList | ConversionFlags.PlaceReturnTypeAfterParameterList;
if (MainWindow.Instance.CurrentDecompilerSettings.LiftNullables)
{
ambience.ConversionFlags |= ConversionFlags.UseNullableSpecifierForValueTypes;
}
return ambience;
}
static string EntityToString(IEntity entity, bool includeDeclaringTypeName, bool includeNamespace, bool includeNamespaceOfDeclaringTypeName)
{
// Do not forget to update CSharpAmbienceTests, if this ever changes.
var ambience = CreateAmbience();
ambience.ConversionFlags |= ConversionFlags.ShowReturnType | ConversionFlags.ShowParameterList | ConversionFlags.ShowParameterModifiers;
if (includeDeclaringTypeName)
ambience.ConversionFlags |= ConversionFlags.ShowDeclaringType;
if (includeNamespace)
ambience.ConversionFlags |= ConversionFlags.UseFullyQualifiedTypeNames;
if (includeNamespaceOfDeclaringTypeName)
ambience.ConversionFlags |= ConversionFlags.UseFullyQualifiedEntityNames;
return ambience.ConvertSymbol(entity);
}
public override string TypeToString(IType type, bool includeNamespace)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var ambience = CreateAmbience();
// Do not forget to update CSharpAmbienceTests.ILSpyMainTreeViewFlags, if this ever changes.
if (includeNamespace)
{
ambience.ConversionFlags |= ConversionFlags.UseFullyQualifiedTypeNames;
ambience.ConversionFlags |= ConversionFlags.UseFullyQualifiedEntityNames;
}
if (type is ITypeDefinition definition)
{
return ambience.ConvertSymbol(definition);
// HACK : UnknownType is not supported by CSharpAmbience.
}
else if (type.Kind == TypeKind.Unknown)
{
return (includeNamespace ? type.FullName : type.Name)
+ (type.TypeParameterCount > 0 ? "<" + string.Join(", ", type.TypeArguments.Select(t => t.Name)) + ">" : "");
}
else
{
return ambience.ConvertType(type);
}
}
public override string FieldToString(IField field, bool includeDeclaringTypeName, bool includeNamespace, bool includeNamespaceOfDeclaringTypeName)
{
if (field == null)
throw new ArgumentNullException(nameof(field));
return EntityToString(field, includeDeclaringTypeName, includeNamespace, includeNamespaceOfDeclaringTypeName);
}
public override string PropertyToString(IProperty property, bool includeDeclaringTypeName, bool includeNamespace, bool includeNamespaceOfDeclaringTypeName)
{
if (property == null)
throw new ArgumentNullException(nameof(property));
return EntityToString(property, includeDeclaringTypeName, includeNamespace, includeNamespaceOfDeclaringTypeName);
}
public override string MethodToString(IMethod method, bool includeDeclaringTypeName, bool includeNamespace, bool includeNamespaceOfDeclaringTypeName)
{
if (method == null)
throw new ArgumentNullException(nameof(method));
return EntityToString(method, includeDeclaringTypeName, includeNamespace, includeNamespaceOfDeclaringTypeName);
}
public override string EventToString(IEvent @event, bool includeDeclaringTypeName, bool includeNamespace, bool includeNamespaceOfDeclaringTypeName)
{
if (@event == null)
throw new ArgumentNullException(nameof(@event));
return EntityToString(@event, includeDeclaringTypeName, includeNamespace, includeNamespaceOfDeclaringTypeName);
}
static string ToCSharpString(MetadataReader metadata, TypeDefinitionHandle handle, bool fullName, bool omitGenerics)
{
var currentTypeDefHandle = handle;
var typeDef = metadata.GetTypeDefinition(currentTypeDefHandle);
List<string> builder = new List<string>();
while (!currentTypeDefHandle.IsNil)
{
if (builder.Count > 0)
builder.Add(".");
typeDef = metadata.GetTypeDefinition(currentTypeDefHandle);
var part = ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(typeDef.Name), out int typeParamCount);
var genericParams = typeDef.GetGenericParameters();
if (!omitGenerics && genericParams.Count > 0)
{
builder.Add(">");
int firstIndex = genericParams.Count - typeParamCount;
for (int i = genericParams.Count - 1; i >= genericParams.Count - typeParamCount; i--)
{
builder.Add(metadata.GetString(metadata.GetGenericParameter(genericParams[i]).Name));
builder.Add(i == firstIndex ? "<" : ",");
}
}
builder.Add(part);
currentTypeDefHandle = typeDef.GetDeclaringType();
if (!fullName)
break;
}
if (fullName && !typeDef.Namespace.IsNil)
{
builder.Add(".");
builder.Add(metadata.GetString(typeDef.Namespace));
}
switch (builder.Count)
{
case 0:
return string.Empty;
case 1:
return builder[0];
case 2:
return builder[1] + builder[0];
case 3:
return builder[2] + builder[1] + builder[0];
case 4:
return builder[3] + builder[2] + builder[1] + builder[0];
default:
builder.Reverse();
return string.Concat(builder);
}
}
public override string GetEntityName(PEFile module, EntityHandle handle, bool fullName, bool omitGenerics)
{
MetadataReader metadata = module.Metadata;
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
return ToCSharpString(metadata, (TypeDefinitionHandle)handle, fullName, omitGenerics);
case HandleKind.FieldDefinition:
var fd = metadata.GetFieldDefinition((FieldDefinitionHandle)handle);
var declaringType = fd.GetDeclaringType();
if (fullName)
return ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(fd.Name);
return metadata.GetString(fd.Name);
case HandleKind.MethodDefinition:
var md = metadata.GetMethodDefinition((MethodDefinitionHandle)handle);
declaringType = md.GetDeclaringType();
string methodName = metadata.GetString(md.Name);
switch (methodName)
{
case ".ctor":
case ".cctor":
var td = metadata.GetTypeDefinition(declaringType);
methodName = ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name));
break;
case "Finalize":
const MethodAttributes finalizerAttributes = (MethodAttributes.Virtual | MethodAttributes.Family | MethodAttributes.HideBySig);
if ((md.Attributes & finalizerAttributes) != finalizerAttributes)
goto default;
MethodSignature<IType> methodSignature = md.DecodeSignature(MetadataExtensions.MinimalSignatureTypeProvider, default);
if (methodSignature.GenericParameterCount != 0 || methodSignature.ParameterTypes.Length != 0)
goto default;
td = metadata.GetTypeDefinition(declaringType);
methodName = "~" + ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name));
break;
default:
var genericParams = md.GetGenericParameters();
if (!omitGenerics && genericParams.Count > 0)
{
methodName += "<";
int i = 0;
foreach (var h in genericParams)
{
if (i > 0)
methodName += ",";
var gp = metadata.GetGenericParameter(h);
methodName += metadata.GetString(gp.Name);
}
methodName += ">";
}
break;
}
if (fullName)
return ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + methodName;
return methodName;
case HandleKind.EventDefinition:
var ed = metadata.GetEventDefinition((EventDefinitionHandle)handle);
declaringType = metadata.GetMethodDefinition(ed.GetAccessors().GetAny()).GetDeclaringType();
if (fullName && !declaringType.IsNil)
return ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(ed.Name);
return metadata.GetString(ed.Name);
case HandleKind.PropertyDefinition:
var pd = metadata.GetPropertyDefinition((PropertyDefinitionHandle)handle);
declaringType = metadata.GetMethodDefinition(pd.GetAccessors().GetAny()).GetDeclaringType();
if (fullName && !declaringType.IsNil)
return ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(pd.Name);
return metadata.GetString(pd.Name);
default:
return null;
}
}
public override bool ShowMember(IEntity member)
{
PEFile assembly = member.ParentModule.PEFile;
return showAllMembers || !CSharpDecompiler.MemberIsHidden(assembly, member.MetadataToken, MainWindow.Instance.CurrentDecompilerSettings);
}
public override RichText GetRichTextTooltip(IEntity entity)
{
var flags = ConversionFlags.All & ~(ConversionFlags.ShowBody | ConversionFlags.PlaceReturnTypeAfterParameterList);
var output = new StringWriter();
var decoratedWriter = new TextWriterTokenWriter(output);
var writer = new CSharpHighlightingTokenWriter(TokenWriter.InsertRequiredSpaces(decoratedWriter), locatable: decoratedWriter);
var settings = MainWindow.Instance.CurrentDecompilerSettings;
if (!settings.LiftNullables)
{
flags &= ~ConversionFlags.UseNullableSpecifierForValueTypes;
}
if (settings.RecordClasses)
{
flags |= ConversionFlags.SupportRecordClasses;
}
if (settings.RecordStructs)
{
flags |= ConversionFlags.SupportRecordStructs;
}
if (settings.UnsignedRightShift)
{
flags |= ConversionFlags.SupportUnsignedRightShift;
}
if (settings.CheckedOperators)
{
flags |= ConversionFlags.SupportOperatorChecked;
}
if (settings.InitAccessors)
{
flags |= ConversionFlags.SupportInitAccessors;
}
if (entity is IMethod m && m.IsLocalFunction)
{
writer.WriteIdentifier(Identifier.Create("(local)"));
}
new CSharpAmbience() {
ConversionFlags = flags,
}.ConvertSymbol(entity, writer, settings.CSharpFormattingOptions);
return new RichText(output.ToString(), writer.HighlightingModel);
}
public override CodeMappingInfo GetCodeMappingInfo(PEFile module, EntityHandle member)
{
return CSharpDecompiler.GetCodeMappingInfo(module, member);
}
CSharpBracketSearcher bracketSearcher = new CSharpBracketSearcher();
public override IBracketSearcher BracketSearcher => bracketSearcher;
}
}
| ILSpy/ILSpy/Languages/CSharpLanguage.cs/0 | {
"file_path": "ILSpy/ILSpy/Languages/CSharpLanguage.cs",
"repo_id": "ILSpy",
"token_count": 10981
} | 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.
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.ILSpy.Metadata
{
class EventMapTableTreeNode : MetadataTableTreeNode
{
public EventMapTableTreeNode(MetadataFile metadataFile)
: base((HandleKind)0x12, metadataFile)
{
}
public override object Text => $"12 EventMap ({metadataFile.Metadata.GetTableRowCount(TableIndex.EventMap)})";
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<EventMapEntry>();
EventMapEntry scrollTargetEntry = default;
var length = metadata.GetTableRowCount(TableIndex.EventMap);
ReadOnlySpan<byte> ptr = metadata.AsReadOnlySpan();
for (int rid = 1; rid <= length; rid++)
{
EventMapEntry entry = new EventMapEntry(metadataFile, ptr, rid);
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;
}
readonly struct EventMap
{
public readonly TypeDefinitionHandle Parent;
public readonly EventDefinitionHandle EventList;
public EventMap(ReadOnlySpan<byte> ptr, int typeDefSize, int eventDefSize)
{
Parent = MetadataTokens.TypeDefinitionHandle(Helpers.GetValueLittleEndian(ptr.Slice(0, typeDefSize)));
EventList = MetadataTokens.EventDefinitionHandle(Helpers.GetValueLittleEndian(ptr.Slice(typeDefSize, eventDefSize)));
}
}
struct EventMapEntry
{
readonly MetadataFile metadataFile;
readonly EventMap eventMap;
public int RID { get; }
public int Token => 0x12000000 | RID;
public int Offset { get; }
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Parent => MetadataTokens.GetToken(eventMap.Parent);
public void OnParentClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, eventMap.Parent, protocol: "metadata"));
}
string parentTooltip;
public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, eventMap.Parent);
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int EventList => MetadataTokens.GetToken(eventMap.EventList);
public void OnEventListClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, eventMap.EventList, protocol: "metadata"));
}
string eventListTooltip;
public string EventListTooltip => GenerateTooltip(ref eventListTooltip, metadataFile, eventMap.EventList);
public EventMapEntry(MetadataFile metadataFile, ReadOnlySpan<byte> ptr, int row)
{
this.metadataFile = metadataFile;
this.RID = row;
var rowOffset = metadataFile.Metadata.GetTableMetadataOffset(TableIndex.EventMap)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.EventMap) * (row - 1);
this.Offset = metadataFile.MetadataOffset + rowOffset;
int typeDefSize = metadataFile.Metadata.GetTableRowCount(TableIndex.TypeDef) < ushort.MaxValue ? 2 : 4;
int eventDefSize = metadataFile.Metadata.GetTableRowCount(TableIndex.Event) < ushort.MaxValue ? 2 : 4;
this.eventMap = new EventMap(ptr.Slice(rowOffset), typeDefSize, eventDefSize);
this.parentTooltip = null;
this.eventListTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "EventMap");
}
}
}
| ILSpy/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/EventMapTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1607
} | 258 |
// 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.Disassembler;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.ILSpy.Metadata
{
internal class MethodSpecTableTreeNode : MetadataTableTreeNode
{
public MethodSpecTableTreeNode(MetadataFile metadataFile)
: base(HandleKind.MethodSpecification, metadataFile)
{
}
public override object Text => $"2B MethodSpec ({metadataFile.Metadata.GetTableRowCount(TableIndex.MethodSpec)})";
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<MethodSpecEntry>();
MethodSpecEntry scrollTargetEntry = default;
foreach (var row in metadata.GetMethodSpecifications())
{
MethodSpecEntry entry = new MethodSpecEntry(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 MethodSpecEntry
{
readonly MetadataFile metadataFile;
readonly MethodSpecificationHandle handle;
readonly MethodSpecification methodSpec;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataFile.MetadataOffset
+ metadataFile.Metadata.GetTableMetadataOffset(TableIndex.MethodSpec)
+ metadataFile.Metadata.GetTableRowSize(TableIndex.MethodSpec) * (RID - 1);
[ColumnInfo("X8", Kind = ColumnKind.Token)]
public int Method => MetadataTokens.GetToken(methodSpec.Method);
public void OnMethodClick()
{
MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, methodSpec.Method, protocol: "metadata"));
}
string methodTooltip;
public string MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, methodSpec.Method);
[ColumnInfo("X8", Kind = ColumnKind.HeapOffset)]
public int Signature => MetadataTokens.GetHeapOffset(methodSpec.Signature);
public string SignatureTooltip {
get {
ITextOutput output = new PlainTextOutput();
var signature = methodSpec.DecodeSignature(new DisassemblerSignatureTypeProvider(metadataFile, output), default);
bool first = true;
foreach (var type in signature)
{
if (first)
first = false;
else
output.Write(", ");
type(ILNameSyntax.TypeName);
}
return output.ToString();
}
}
public MethodSpecEntry(MetadataFile metadataFile, MethodSpecificationHandle handle)
{
this.metadataFile = metadataFile;
this.handle = handle;
this.methodSpec = metadataFile.Metadata.GetMethodSpecification(handle);
this.methodTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "MethodSpecs");
}
}
} | ILSpy/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/CorTables/MethodSpecTableTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1419
} | 259 |
// 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.Collections.Generic;
using System.Reflection.PortableExecutable;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TreeNodes;
namespace ICSharpCode.ILSpy.Metadata
{
class DebugDirectoryTreeNode : ILSpyTreeNode
{
private PEFile module;
public DebugDirectoryTreeNode(PEFile module)
{
this.module = module;
this.LazyLoading = true;
}
public override object Text => "Debug Directory";
public override object Icon => Images.ListFolder;
public override object ExpandedIcon => Images.ListFolderOpen;
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var dataGrid = Helpers.PrepareDataGrid(tabPage, this);
var entries = new List<DebugDirectoryEntryView>();
foreach (var entry in module.Reader.ReadDebugDirectory())
{
int dataOffset = module.Reader.IsLoadedImage ? entry.DataRelativeVirtualAddress : entry.DataPointer;
var data = module.Reader.GetEntireImage().GetContent(dataOffset, entry.DataSize);
entries.Add(new DebugDirectoryEntryView(entry, data.ToHexString(data.Length)));
}
dataGrid.ItemsSource = entries.ToArray();
tabPage.Content = dataGrid;
return true;
}
protected override void LoadChildren()
{
foreach (var entry in module.Reader.ReadDebugDirectory())
{
switch (entry.Type)
{
case DebugDirectoryEntryType.CodeView:
var codeViewData = module.Reader.ReadCodeViewDebugDirectoryData(entry);
this.Children.Add(new CodeViewTreeNode(codeViewData));
break;
case DebugDirectoryEntryType.EmbeddedPortablePdb:
var embeddedPortablePdbProvider = module.Reader.ReadEmbeddedPortablePdbDebugDirectoryData(entry);
var embeddedPortablePdbMetadataFile = new MetadataFile(module.FileName, embeddedPortablePdbProvider, isEmbedded: true);
this.Children.Add(new MetadataTreeNode(embeddedPortablePdbMetadataFile, "Debug Metadata (Embedded)"));
break;
case DebugDirectoryEntryType.PdbChecksum:
var pdbChecksumData = module.Reader.ReadPdbChecksumDebugDirectoryData(entry);
this.Children.Add(new PdbChecksumTreeNode(pdbChecksumData));
break;
case DebugDirectoryEntryType.Unknown:
case DebugDirectoryEntryType.Coff:
case DebugDirectoryEntryType.Reproducible:
default:
this.Children.Add(new DebugDirectoryEntryTreeNode(module, entry));
break;
}
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "Data Directories");
}
class DebugDirectoryEntryView
{
public uint Timestamp { get; set; }
public ushort MajorVersion { get; set; }
public ushort MinorVersion { get; set; }
public string Type { get; set; }
public int SizeOfRawData { get; set; }
public int AddressOfRawData { get; set; }
public int PointerToRawData { get; set; }
public string RawData { get; set; }
public DebugDirectoryEntryView(DebugDirectoryEntry entry, string data)
{
this.RawData = data;
this.Timestamp = entry.Stamp;
this.MajorVersion = entry.MajorVersion;
this.MinorVersion = entry.MinorVersion;
this.Type = entry.Type.ToString();
this.SizeOfRawData = entry.DataSize;
this.AddressOfRawData = entry.DataRelativeVirtualAddress;
this.AddressOfRawData = entry.DataPointer;
}
}
}
}
| ILSpy/ILSpy/Metadata/DebugDirectoryTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/DebugDirectoryTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 1526
} | 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.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
namespace ICSharpCode.ILSpy.Metadata
{
internal class BlobHeapTreeNode : MetadataHeapTreeNode
{
readonly List<BlobHeapEntry> list;
public BlobHeapTreeNode(MetadataFile metadataFile)
: base(HandleKind.Blob, metadataFile)
{
list = new List<BlobHeapEntry>();
var metadata = metadataFile.Metadata;
BlobHandle handle = MetadataTokens.BlobHandle(0);
do
{
BlobHeapEntry entry = new BlobHeapEntry(metadata, handle);
list.Add(entry);
handle = metadata.GetNextHandle(handle);
} while (!handle.IsNil);
}
public override object Text => $"Blob Heap ({list.Count})";
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
view.ItemsSource = list;
tabPage.Content = view;
return true;
}
class BlobHeapEntry
{
readonly MetadataReader metadata;
readonly BlobHandle handle;
public int Offset => metadata.GetHeapOffset(handle);
public int Length => metadata.GetBlobReader(handle).Length;
public string Value => metadata.GetBlobReader(handle).ToHexString();
public BlobHeapEntry(MetadataReader metadata, BlobHandle handle)
{
this.metadata = metadata;
this.handle = handle;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "Blob Heap");
}
}
} | ILSpy/ILSpy/Metadata/Heaps/BlobHeapTreeNode.cs/0 | {
"file_path": "ILSpy/ILSpy/Metadata/Heaps/BlobHeapTreeNode.cs",
"repo_id": "ILSpy",
"token_count": 890
} | 261 |
// 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;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace ICSharpCode.ILSpy
{
static class NativeMethods
{
public const uint WM_COPYDATA = 0x4a;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern unsafe int GetWindowThreadProcessId(IntPtr hWnd, int* lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder title, int size);
public static string GetWindowText(IntPtr hWnd, int maxLength)
{
StringBuilder b = new StringBuilder(maxLength + 1);
if (GetWindowText(hWnd, b, b.Capacity) != 0)
return b.ToString();
else
return string.Empty;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint msg, IntPtr wParam, ref CopyDataStruct lParam,
uint flags, uint timeout, out IntPtr result);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern unsafe char** CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr hMem);
#region CommandLine <-> Argument Array
/// <summary>
/// Decodes a command line into an array of arguments according to the CommandLineToArgvW rules.
/// </summary>
/// <remarks>
/// Command line parsing rules:
/// - 2n backslashes followed by a quotation mark produce n backslashes, and the quotation mark is considered to be the end of the argument.
/// - (2n) + 1 backslashes followed by a quotation mark again produce n backslashes followed by a quotation mark.
/// - n backslashes not followed by a quotation mark simply produce n backslashes.
/// </remarks>
public static unsafe string[] CommandLineToArgumentArray(string commandLine)
{
if (string.IsNullOrEmpty(commandLine))
return new string[0];
int numberOfArgs;
char** arr = CommandLineToArgvW(commandLine, out numberOfArgs);
if (arr == null)
throw new Win32Exception();
try
{
string[] result = new string[numberOfArgs];
for (int i = 0; i < numberOfArgs; i++)
{
result[i] = new string(arr[i]);
}
return result;
}
finally
{
// Free memory obtained by CommandLineToArgW.
LocalFree(new IntPtr(arr));
}
}
static readonly char[] charsNeedingQuoting = { ' ', '\t', '\n', '\v', '"' };
/// <summary>
/// Escapes a set of arguments according to the CommandLineToArgvW rules.
/// </summary>
/// <remarks>
/// Command line parsing rules:
/// - 2n backslashes followed by a quotation mark produce n backslashes, and the quotation mark is considered to be the end of the argument.
/// - (2n) + 1 backslashes followed by a quotation mark again produce n backslashes followed by a quotation mark.
/// - n backslashes not followed by a quotation mark simply produce n backslashes.
/// </remarks>
public static string ArgumentArrayToCommandLine(params string[] arguments)
{
if (arguments == null)
return null;
StringBuilder b = new StringBuilder();
for (int i = 0; i < arguments.Length; i++)
{
if (i > 0)
b.Append(' ');
AppendArgument(b, arguments[i]);
}
return b.ToString();
}
static void AppendArgument(StringBuilder b, string arg)
{
if (arg == null)
{
return;
}
if (arg.Length > 0 && arg.IndexOfAny(charsNeedingQuoting) < 0)
{
b.Append(arg);
}
else
{
b.Append('"');
for (int j = 0; ; j++)
{
int backslashCount = 0;
while (j < arg.Length && arg[j] == '\\')
{
backslashCount++;
j++;
}
if (j == arg.Length)
{
b.Append('\\', backslashCount * 2);
break;
}
else if (arg[j] == '"')
{
b.Append('\\', backslashCount * 2 + 1);
b.Append('"');
}
else
{
b.Append('\\', backslashCount);
b.Append(arg[j]);
}
}
b.Append('"');
}
}
#endregion
public unsafe static string GetProcessNameFromWindow(IntPtr hWnd)
{
int processId;
GetWindowThreadProcessId(hWnd, &processId);
try
{
using (var p = Process.GetProcessById(processId))
{
return p.ProcessName;
}
}
catch (ArgumentException ex)
{
Debug.WriteLine(ex.Message);
return null;
}
catch (InvalidOperationException ex)
{
Debug.WriteLine(ex.Message);
return null;
}
catch (Win32Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
[DllImport("dwmapi.dll", PreserveSig = true)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, DwmWindowAttribute attr, ref int attrValue, int attrSize);
public static bool UseImmersiveDarkMode(IntPtr hWnd, bool enable)
{
int darkMode = enable ? 1 : 0;
int hr = DwmSetWindowAttribute(hWnd, DwmWindowAttribute.UseImmersiveDarkMode, ref darkMode, sizeof(int));
return hr >= 0;
}
}
[return: MarshalAs(UnmanagedType.Bool)]
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
struct CopyDataStruct
{
public IntPtr Padding;
public int Size;
public IntPtr Buffer;
public CopyDataStruct(IntPtr padding, int size, IntPtr buffer)
{
this.Padding = padding;
this.Size = size;
this.Buffer = buffer;
}
}
public enum DwmWindowAttribute : uint
{
NCRenderingEnabled = 1,
NCRenderingPolicy,
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds,
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds,
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Cloak,
Cloaked,
FreezeRepresentation,
PassiveUpdateMode,
UseHostBackdropBrush,
UseImmersiveDarkMode = 20,
WindowCornerPreference = 33,
BorderColor,
CaptionColor,
TextColor,
VisibleFrameBorderThickness,
SystemBackdropType,
Last
}
}
| ILSpy/ILSpy/NativeMethods.cs/0 | {
"file_path": "ILSpy/ILSpy/NativeMethods.cs",
"repo_id": "ILSpy",
"token_count": 2838
} | 262 |
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="About" xml:space="preserve">
<value>About</value>
</data>
<data name="AddPreconfiguredList" xml:space="preserve">
<value>Add preconfigured list...</value>
</data>
<data name="AddShellIntegration" xml:space="preserve">
<value>Add shell integration</value>
</data>
<data name="AddShellIntegrationMessage" xml:space="preserve">
<value>This will add "{0}" to the registry at "HKCU\Software\Classes\dllfile\shell\Open with ILSpy\command" and "HKCU\Software\Classes\exefile\shell\Open with ILSpy\command" to allow opening .dll and .exe files from the Windows Explorer context menu.
Do you want to continue?</value>
</data>
<data name="AllFiles" xml:space="preserve">
<value>|All Files|*.*</value>
</data>
<data name="AllowMultipleInstances" xml:space="preserve">
<value>Allow multiple instances</value>
</data>
<data name="AlwaysBraces" xml:space="preserve">
<value>Always use braces</value>
</data>
<data name="Analyze" xml:space="preserve">
<value>Analyze</value>
</data>
<data name="Assemblies" xml:space="preserve">
<value>Assemblies</value>
</data>
<data name="Assembly" xml:space="preserve">
<value>Assembly</value>
</data>
<data name="AssemblySaveCodeDirectoryNotEmpty" xml:space="preserve">
<value>The directory is not empty. File will be overwritten.
Are you sure you want to continue?</value>
</data>
<data name="AssemblySaveCodeDirectoryNotEmptyTitle" xml:space="preserve">
<value>Project Directory not empty</value>
</data>
<data name="AutomaticallyCheckUpdatesEveryWeek" xml:space="preserve">
<value>Automatically check for updates every week</value>
</data>
<data name="Back" xml:space="preserve">
<value>Back</value>
</data>
<data name="BaseTypes" xml:space="preserve">
<value>Base Types</value>
</data>
<data name="C_lone" xml:space="preserve">
<value>C_lone</value>
</data>
<data name="Cancel" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="CannotAnalyzeMissingRef" xml:space="preserve">
<value>Entity could not be resolved. Cannot analyze entities from missing assembly references. Add the missing reference and try again.</value>
</data>
<data name="CannotCreatePDBFile" xml:space="preserve">
<value>Cannot create PDB file for {0}, because it does not contain a PE Debug Directory Entry of type 'CodeView'.</value>
</data>
<data name="CheckAgain" xml:space="preserve">
<value>Check again</value>
</data>
<data name="CheckUpdates" xml:space="preserve">
<value>Check for updates</value>
</data>
<data name="Checking" xml:space="preserve">
<value>Checking...</value>
</data>
<data name="ClearAssemblyList" xml:space="preserve">
<value>Clear assembly list</value>
</data>
<data name="Close" xml:space="preserve">
<value>Close</value>
</data>
<data name="CollapseTreeNodes" xml:space="preserve">
<value>Collapse all tree nodes</value>
</data>
<data name="Copy" xml:space="preserve">
<value>Copy</value>
</data>
<data name="CopyErrorMessage" xml:space="preserve">
<value>Copy error message</value>
</data>
<data name="CopyName" xml:space="preserve">
<value>Copy FQ Name</value>
</data>
<data name="CouldNotUseSdkStyleProjectFormat" xml:space="preserve">
<value>Could not use SDK-style project format, because no compatible target-framework moniker was found.</value>
</data>
<data name="Create" xml:space="preserve">
<value>Create</value>
</data>
<data name="CultureLabel" xml:space="preserve">
<value>Culture</value>
</data>
<data name="DEBUGDecompile" xml:space="preserve">
<value>DEBUG -- Decompile All</value>
</data>
<data name="DEBUGDecompile100x" xml:space="preserve">
<value>DEBUG -- Decompile 100x</value>
</data>
<data name="DEBUGDisassemble" xml:space="preserve">
<value>DEBUG -- Disassemble All</value>
</data>
<data name="DEBUGDumpPDBAsXML" xml:space="preserve">
<value>DEBUG -- Dump PDB as XML</value>
</data>
<data name="DebugSteps" xml:space="preserve">
<value>Debug Steps</value>
</data>
<data name="DebugThisStep" xml:space="preserve">
<value>Debug this step</value>
</data>
<data name="DecompilationCompleteInF1Seconds" xml:space="preserve">
<value>Decompilation complete in {0:F1} seconds.</value>
</data>
<data name="DecompilationViewOptions" xml:space="preserve">
<value>Decompilation view options</value>
</data>
<data name="DecompilationWasCancelled" xml:space="preserve">
<value>Decompilation was cancelled.</value>
</data>
<data name="Decompile" xml:space="preserve">
<value>Decompile</value>
</data>
<data name="DecompileToNewPanel" xml:space="preserve">
<value>Decompile to new tab</value>
</data>
<data name="Decompiler" xml:space="preserve">
<value>Decompiler</value>
</data>
<data name="DecompilerSettings.AggressiveInlining" xml:space="preserve">
<value>Always inline local variables if possible</value>
</data>
<data name="DecompilerSettings.AllowExtensionAddMethodsInCollectionInitializerExpressions" xml:space="preserve">
<value>Allow extension 'Add' methods in collection initializer expressions</value>
</data>
<data name="DecompilerSettings.AllowExtensionMethodSyntaxOnRef" xml:space="preserve">
<value>Use 'ref' extension methods</value>
</data>
<data name="DecompilerSettings.AlwaysCastTargetsOfExplicitInterfaceImplementationCalls" xml:space="preserve">
<value>Always cast targets of explicit interface implementation calls</value>
</data>
<data name="DecompilerSettings.AlwaysQualifyMemberReferences" xml:space="preserve">
<value>Always qualify member references</value>
</data>
<data name="DecompilerSettings.AlwaysShowEnumMemberValues" xml:space="preserve">
<value>Always show enum member values</value>
</data>
<data name="DecompilerSettings.AlwaysUseBraces" xml:space="preserve">
<value>Always use braces</value>
</data>
<data name="DecompilerSettings.AlwaysUseGlobal" xml:space="preserve">
<value>Always fully qualify namespaces using the "global::" prefix</value>
</data>
<data name="DecompilerSettings.ApplyWindowsRuntimeProjectionsOnLoadedAssemblies" xml:space="preserve">
<value>Apply Windows Runtime projections on loaded assemblies</value>
</data>
<data name="DecompilerSettings.ArrayInitializerExpressions" xml:space="preserve">
<value>Array initializer expressions</value>
</data>
<data name="DecompilerSettings.AsyncEnumerator" xml:space="preserve">
<value>Decompile async IAsyncEnumerator methods</value>
</data>
<data name="DecompilerSettings.AutoLoadAssemblyReferences" xml:space="preserve">
<value>Automatically load assembly references</value>
</data>
<data name="DecompilerSettings.CheckedOperators" xml:space="preserve">
<value>User-defined checked operators</value>
</data>
<data name="DecompilerSettings.DecompileAnonymousMethodsLambdas" xml:space="preserve">
<value>Decompile anonymous methods/lambdas</value>
</data>
<data name="DecompilerSettings.DecompileAnonymousTypes" xml:space="preserve">
<value>Decompile anonymous types</value>
</data>
<data name="DecompilerSettings.DecompileAsyncMethods" xml:space="preserve">
<value>Decompile async methods</value>
</data>
<data name="DecompilerSettings.DecompileAutomaticEvents" xml:space="preserve">
<value>Decompile automatic events</value>
</data>
<data name="DecompilerSettings.DecompileAutomaticProperties" xml:space="preserve">
<value>Decompile automatic properties</value>
</data>
<data name="DecompilerSettings.DecompileAwaitInCatchFinallyBlocks" xml:space="preserve">
<value>Decompile await in catch/finally blocks</value>
</data>
<data name="DecompilerSettings.DecompileC10PublicUnsafeFixedIntArr10Members" xml:space="preserve">
<value>Decompile C# 1.0 'public unsafe fixed int arr[10];' members</value>
</data>
<data name="DecompilerSettings.DecompileDecimalConstantAsSimpleLiteralValues" xml:space="preserve">
<value>Decompile [DecimalConstant(...)] as simple literal values</value>
</data>
<data name="DecompilerSettings.DecompileEnumeratorsYieldReturn" xml:space="preserve">
<value>Decompile enumerators (yield return)</value>
</data>
<data name="DecompilerSettings.DecompileExpressionTrees" xml:space="preserve">
<value>Decompile expression trees</value>
</data>
<data name="DecompilerSettings.DecompileForEachWithGetEnumeratorExtension" xml:space="preserve">
<value>Decompile foreach statements with GetEnumerator extension methods</value>
</data>
<data name="DecompilerSettings.DecompileUseOfTheDynamicType" xml:space="preserve">
<value>Decompile use of the 'dynamic' type</value>
</data>
<data name="DecompilerSettings.Deconstruction" xml:space="preserve">
<value>Detect deconstruction assignments</value>
</data>
<data name="DecompilerSettings.DetectAsyncUsingAndForeachStatements" xml:space="preserve">
<value>Detect awaited using and foreach statements</value>
</data>
<data name="DecompilerSettings.DetectForeachStatements" xml:space="preserve">
<value>Detect foreach statements</value>
</data>
<data name="DecompilerSettings.DetectLockStatements" xml:space="preserve">
<value>Detect lock statements</value>
</data>
<data name="DecompilerSettings.DetectSwitchOnString" xml:space="preserve">
<value>Detect switch on string</value>
</data>
<data name="DecompilerSettings.DetectTupleComparisons" xml:space="preserve">
<value>Detect tuple comparisons</value>
</data>
<data name="DecompilerSettings.DetectUsingStatements" xml:space="preserve">
<value>Detect using statements</value>
</data>
<data name="DecompilerSettings.DictionaryInitializerExpressions" xml:space="preserve">
<value>Dictionary initializer expressions</value>
</data>
<data name="DecompilerSettings.DoWhileStatement" xml:space="preserve">
<value>Transform to do-while, if possible</value>
</data>
<data name="DecompilerSettings.FSpecificOptions" xml:space="preserve">
<value>F#-specific options</value>
</data>
<data name="DecompilerSettings.FileScopedNamespaces" xml:space="preserve">
<value>Use file-scoped namespace declarations</value>
</data>
<data name="DecompilerSettings.ForStatement" xml:space="preserve">
<value>Transform to for, if possible</value>
</data>
<data name="DecompilerSettings.FunctionPointers" xml:space="preserve">
<value>Function pointers</value>
</data>
<data name="DecompilerSettings.GetterOnlyAutomaticProperties" xml:space="preserve">
<value>Decompile getter-only automatic properties</value>
</data>
<data name="DecompilerSettings.IncludeXMLDocumentationCommentsInTheDecompiledCode" xml:space="preserve">
<value>Include XML documentation comments in the decompiled code</value>
</data>
<data name="DecompilerSettings.InitAccessors" xml:space="preserve">
<value>Allow init; accessors</value>
</data>
<data name="DecompilerSettings.InsertUsingDeclarations" xml:space="preserve">
<value>Insert using declarations</value>
</data>
<data name="DecompilerSettings.IntroduceLocalFunctions" xml:space="preserve">
<value>Introduce local functions</value>
</data>
<data name="DecompilerSettings.IntroduceStaticLocalFunctions" xml:space="preserve">
<value>Introduce static local functions</value>
</data>
<data name="DecompilerSettings.IsByRefLikeAttributeShouldBeReplacedWithRefModifiersOnStructs" xml:space="preserve">
<value>IsByRefLikeAttribute should be replaced with 'ref' modifiers on structs</value>
</data>
<data name="DecompilerSettings.IsReadOnlyAttributeShouldBeReplacedWithReadonlyInModifiersOnStructsParameters" xml:space="preserve">
<value>IsReadOnlyAttribute should be replaced with 'readonly'/'in' modifiers on structs/parameters</value>
</data>
<data name="DecompilerSettings.IsUnmanagedAttributeOnTypeParametersShouldBeReplacedWithUnmanagedConstraints" xml:space="preserve">
<value>IsUnmanagedAttribute on type parameters should be replaced with 'unmanaged' constraints</value>
</data>
<data name="DecompilerSettings.NativeIntegers" xml:space="preserve">
<value>Use nint/nuint types</value>
</data>
<data name="DecompilerSettings.NullPropagation" xml:space="preserve">
<value>Decompile ?. and ?[] operators</value>
</data>
<data name="DecompilerSettings.NullableReferenceTypes" xml:space="preserve">
<value>Nullable reference types</value>
</data>
<data name="DecompilerSettings.NumericIntPtr" xml:space="preserve">
<value>Treat (U)IntPtr as n(u)int</value>
</data>
<data name="DecompilerSettings.ObjectCollectionInitializerExpressions" xml:space="preserve">
<value>Object/collection initializer expressions</value>
</data>
<data name="DecompilerSettings.Other" xml:space="preserve">
<value>Other</value>
</data>
<data name="DecompilerSettings.ParameterNullCheck" xml:space="preserve">
<value>Use parameter null checking</value>
</data>
<data name="DecompilerSettings.PatternCombinators" xml:space="preserve">
<value>Pattern combinators (and, or, not)</value>
</data>
<data name="DecompilerSettings.PatternMatching" xml:space="preserve">
<value>Use pattern matching expressions</value>
</data>
<data name="DecompilerSettings.ProjectExport" xml:space="preserve">
<value>Project export</value>
</data>
<data name="DecompilerSettings.Ranges" xml:space="preserve">
<value>Ranges</value>
</data>
<data name="DecompilerSettings.ReadOnlyMethods" xml:space="preserve">
<value>Read-only methods</value>
</data>
<data name="DecompilerSettings.RecordClasses" xml:space="preserve">
<value>Record classes</value>
</data>
<data name="DecompilerSettings.RecordStructs" xml:space="preserve">
<value>Record structs</value>
</data>
<data name="DecompilerSettings.RecursivePatternMatching" xml:space="preserve">
<value>Recursive pattern matching</value>
</data>
<data name="DecompilerSettings.RelationalPatterns" xml:space="preserve">
<value>Relational patterns</value>
</data>
<data name="DecompilerSettings.RemoveDeadAndSideEffectFreeCodeUseWithCaution" xml:space="preserve">
<value>Remove dead and side effect free code (use with caution!)</value>
</data>
<data name="DecompilerSettings.RemoveDeadStores" xml:space="preserve">
<value>Remove dead stores (use with caution!)</value>
</data>
<data name="DecompilerSettings.RemoveOptionalArgumentsIfPossible" xml:space="preserve">
<value>Remove optional arguments, if possible</value>
</data>
<data name="DecompilerSettings.RequiredMembers" xml:space="preserve">
<value>Required members</value>
</data>
<data name="DecompilerSettings.ScopedRef" xml:space="preserve">
<value>'scoped' lifetime annotation</value>
</data>
<data name="DecompilerSettings.SeparateLocalVariableDeclarations" xml:space="preserve">
<value>Separate local variable declarations and initializers (int x = 5; -> int x; x = 5;), if possible</value>
</data>
<data name="DecompilerSettings.ShowInfoFromDebugSymbolsIfAvailable" xml:space="preserve">
<value>Show info from debug symbols, if available</value>
</data>
<data name="DecompilerSettings.SparseIntegerSwitch" xml:space="preserve">
<value>Detect switch on integer even if IL code does not use a jump table</value>
</data>
<data name="DecompilerSettings.StringConcat" xml:space="preserve">
<value>Decompile 'string.Concat(a, b)' calls into 'a + b'</value>
</data>
<data name="DecompilerSettings.SwitchExpressions" xml:space="preserve">
<value>Switch expressions</value>
</data>
<data name="DecompilerSettings.SwitchOnReadOnlySpanChar" xml:space="preserve">
<value>Use switch on (ReadOnly)Span<char></value>
</data>
<data name="DecompilerSettings.UnsignedRightShift" xml:space="preserve">
<value>Unsigned right shift (>>>)</value>
</data>
<data name="DecompilerSettings.UseDiscards" xml:space="preserve">
<value>Use discards</value>
</data>
<data name="DecompilerSettings.UseEnhancedUsing" xml:space="preserve">
<value>Use enhanced using variable declarations</value>
</data>
<data name="DecompilerSettings.UseExpressionBodiedMemberSyntaxForGetOnlyProperties" xml:space="preserve">
<value>Use expression-bodied member syntax for get-only properties</value>
</data>
<data name="DecompilerSettings.UseExtensionMethodSyntax" xml:space="preserve">
<value>Use extension method syntax</value>
</data>
<data name="DecompilerSettings.UseImplicitConversionsBetweenTupleTypes" xml:space="preserve">
<value>Use implicit conversions between tuple types</value>
</data>
<data name="DecompilerSettings.UseImplicitMethodGroupConversions" xml:space="preserve">
<value>Use implicit method group conversions</value>
</data>
<data name="DecompilerSettings.UseLINQExpressionSyntax" xml:space="preserve">
<value>Use LINQ expression syntax</value>
</data>
<data name="DecompilerSettings.UseLambdaSyntaxIfPossible" xml:space="preserve">
<value>Use lambda syntax, if possible</value>
</data>
<data name="DecompilerSettings.UseLiftedOperatorsForNullables" xml:space="preserve">
<value>Use lifted operators for nullables</value>
</data>
<data name="DecompilerSettings.UseNamedArguments" xml:space="preserve">
<value>Use named arguments</value>
</data>
<data name="DecompilerSettings.UseNestedDirectoriesForNamespaces" xml:space="preserve">
<value>Use nested directories for namespaces</value>
</data>
<data name="DecompilerSettings.UseNonTrailingNamedArguments" xml:space="preserve">
<value>Use non-trailing named arguments</value>
</data>
<data name="DecompilerSettings.UseOutVariableDeclarations" xml:space="preserve">
<value>Use out variable declarations</value>
</data>
<data name="DecompilerSettings.UsePatternBasedFixedStatement" xml:space="preserve">
<value>Use pattern-based fixed statement</value>
</data>
<data name="DecompilerSettings.UsePrimaryConstructorSyntax" xml:space="preserve">
<value>Use primary constructor syntax with records</value>
</data>
<data name="DecompilerSettings.UseRefLocalsForAccurateOrderOfEvaluation" xml:space="preserve">
<value>Use ref locals to accurately represent order of evaluation</value>
</data>
<data name="DecompilerSettings.UseSdkStyleProjectFormat" xml:space="preserve">
<value>Use new SDK style format for generated project files (*.csproj)</value>
</data>
<data name="DecompilerSettings.UseStackallocInitializerSyntax" xml:space="preserve">
<value>Use stackalloc initializer syntax</value>
</data>
<data name="DecompilerSettings.UseStringInterpolation" xml:space="preserve">
<value>Use string interpolation</value>
</data>
<data name="DecompilerSettings.UseThrowExpressions" xml:space="preserve">
<value>Use throw expressions</value>
</data>
<data name="DecompilerSettings.UseTupleTypeSyntax" xml:space="preserve">
<value>Use tuple type syntax</value>
</data>
<data name="DecompilerSettings.UseVariableNamesFromDebugSymbolsIfAvailable" xml:space="preserve">
<value>Use variable names from debug symbols, if available</value>
</data>
<data name="DecompilerSettings.Utf8StringLiterals" xml:space="preserve">
<value>UTF-8 string literals</value>
</data>
<data name="DecompilerSettings.VBSpecificOptions" xml:space="preserve">
<value>VB-specific options</value>
</data>
<data name="DecompilerSettings.WithExpressions" xml:space="preserve">
<value>'with' initializer expressions</value>
</data>
<data name="DecompilerSettingsPanelLongText" xml:space="preserve">
<value>The settings selected below are applied to the decompiler output in combination with the selection in the language drop-down. Selecting a lower language version in the drop-down will deactivate all selected options of the higher versions. Note that some settings implicitly depend on each other, e.g.: LINQ expressions cannot be introduced without first transforming static calls to extension method calls.</value>
</data>
<data name="Decompiling" xml:space="preserve">
<value>Decompiling...</value>
</data>
<data name="Dependencies" xml:space="preserve">
<value>Dependencies</value>
</data>
<data name="DerivedTypes" xml:space="preserve">
<value>Derived Types</value>
</data>
<data name="Display" xml:space="preserve">
<value>Display</value>
</data>
<data name="DisplayCode" xml:space="preserve">
<value>Display Code</value>
</data>
<data name="DisplaySettingsPanel_Font" xml:space="preserve">
<value>Font:</value>
</data>
<data name="DisplaySettingsPanel_Theme" xml:space="preserve">
<value>Theme:</value>
</data>
<data name="Download" xml:space="preserve">
<value>Download</value>
</data>
<data name="E_xit" xml:space="preserve">
<value>E_xit</value>
</data>
<data name="Editor" xml:space="preserve">
<value>Editor</value>
</data>
<data name="EnableFoldingBlocksBraces" xml:space="preserve">
<value>Enable folding on all blocks in braces</value>
</data>
<data name="EnableWordWrap" xml:space="preserve">
<value>Enable word wrap</value>
</data>
<data name="EnterListName" xml:space="preserve">
<value>Enter a list name:</value>
</data>
<data name="Exit" xml:space="preserve">
<value>Exit</value>
</data>
<data name="ExpandMemberDefinitionsAfterDecompilation" xml:space="preserve">
<value>Expand member definitions after decompilation</value>
</data>
<data name="ExpandUsingDeclarationsAfterDecompilation" xml:space="preserve">
<value>Expand using declarations after decompilation</value>
</data>
<data name="ExtractPackageEntry" xml:space="preserve">
<value>Extract package entry</value>
</data>
<data name="Folding" xml:space="preserve">
<value>Folding</value>
</data>
<data name="Font" xml:space="preserve">
<value>Font</value>
</data>
<data name="Forward" xml:space="preserve">
<value>Forward</value>
</data>
<data name="GeneratePortable" xml:space="preserve">
<value>Generate portable PDB</value>
</data>
<data name="GenerationCompleteInSeconds" xml:space="preserve">
<value>Generation complete in {0} seconds.</value>
</data>
<data name="GenerationWasCancelled" xml:space="preserve">
<value>Generation was cancelled.</value>
</data>
<data name="GoToToken" xml:space="preserve">
<value>Go to token</value>
</data>
<data name="HideEmptyMetadataTables" xml:space="preserve">
<value>Hide empty metadata tables from tree view</value>
</data>
<data name="HighlightCurrentLine" xml:space="preserve">
<value>Highlight current line</value>
</data>
<data name="HighlightMatchingBraces" xml:space="preserve">
<value>Highlight matching braces</value>
</data>
<data name="ILSpyAboutPageTxt" xml:space="preserve">
<value>ILSpyAboutPage.txt</value>
</data>
<data name="ILSpyVersion" xml:space="preserve">
<value>ILSpy version </value>
</data>
<data name="ILSpyVersionAvailable" xml:space="preserve">
<value>A new ILSpy version is available.</value>
</data>
<data name="IndentSize" xml:space="preserve">
<value>Indent size:</value>
</data>
<data name="Indentation" xml:space="preserve">
<value>Indentation</value>
</data>
<data name="InsertUsingDeclarations" xml:space="preserve">
<value>Insert using declarations</value>
</data>
<data name="ListDeleteConfirmation" xml:space="preserve">
<value>Are you sure that you want to delete the selected assembly list?</value>
</data>
<data name="ListExistsAlready" xml:space="preserve">
<value>A list with the same name was found.</value>
</data>
<data name="ListsResetConfirmation" xml:space="preserve">
<value>Are you sure that you want to remove all assembly lists and recreate the default assembly lists?</value>
</data>
<data name="LoadAssembliesThatWereLoadedInTheLastInstance" xml:space="preserve">
<value>Load assemblies that were loaded in the last instance.</value>
</data>
<data name="Loading" xml:space="preserve">
<value>Loading...</value>
</data>
<data name="Location" xml:space="preserve">
<value>Location</value>
</data>
<data name="ManageAssemblyLists" xml:space="preserve">
<value>Manage Assembly Lists</value>
</data>
<data name="ManageAssembly_Lists" xml:space="preserve">
<value>Manage assembly _lists...</value>
</data>
<data name="Metadata" xml:space="preserve">
<value>Metadata</value>
</data>
<data name="Misc" xml:space="preserve">
<value>Misc</value>
</data>
<data name="NETFrameworkVersion" xml:space="preserve">
<value>.NET version </value>
</data>
<data name="Name" xml:space="preserve">
<value>Name</value>
</data>
<data name="Navigation" xml:space="preserve">
<value>Navigation</value>
</data>
<data name="NavigationFailed" xml:space="preserve">
<value>Navigation failed because the target is hidden or a compiler-generated class.\n
Please disable all filters that might hide the item (i.e. activate "View > Show internal types and members") and try again.</value>
</data>
<data name="NewList" xml:space="preserve">
<value>New list</value>
</data>
<data name="NewTab" xml:space="preserve">
<value>New Tab</value>
</data>
<data name="NugetPackageBrowser" xml:space="preserve">
<value>Nuget Package Browser</value>
</data>
<data name="OK" xml:space="preserve">
<value>OK</value>
</data>
<data name="Open" xml:space="preserve">
<value>Open</value>
</data>
<data name="OpenExplorer" xml:space="preserve">
<value>Open Explorer</value>
</data>
<data name="OpenFrom" xml:space="preserve">
<value>Open From GAC</value>
</data>
<data name="OpenFrom_GAC" xml:space="preserve">
<value>Open from _GAC...</value>
</data>
<data name="OpenListDialog__Delete" xml:space="preserve">
<value>_Delete</value>
</data>
<data name="OpenListDialog__Open" xml:space="preserve">
<value>_Open</value>
</data>
<data name="OperationWasCancelled" xml:space="preserve">
<value>Operation was cancelled.</value>
</data>
<data name="Options" xml:space="preserve">
<value>Options</value>
</data>
<data name="Other" xml:space="preserve">
<value>Other</value>
</data>
<data name="OtherOptions" xml:space="preserve">
<value>Other options</value>
</data>
<data name="OtherResources" xml:space="preserve">
<value>Other Resources</value>
</data>
<data name="PortablePDBPdbAllFiles" xml:space="preserve">
<value>Portable PDB|*.pdb|All files|*.*</value>
</data>
<data name="ProjectExportFormatChangeSettingHint" xml:space="preserve">
<value>You can change this by toggling the setting at Options > Decompiler > Project export > Use new SDK style format for generated project files (*.csproj).</value>
</data>
<data name="ProjectExportFormatNonSDKHint" xml:space="preserve">
<value>A Non-SDK project was generated. Learn more at https://docs.microsoft.com/en-us/nuget/resources/check-project-format.</value>
</data>
<data name="ProjectExportFormatSDKHint" xml:space="preserve">
<value>A SDK-style project was generated. Learn more at https://docs.microsoft.com/en-us/nuget/resources/check-project-format.</value>
</data>
<data name="ProjectExportPathTooLong" xml:space="preserve">
<value>Failed to decompile the assemblies {0} because the namespace names are too long or the directory structure is nested too deep.
If you are using Windows 10.0.14393 (Windows 10 version 1607) or later, you can enable "Long path support" by creating a REG_DWORD registry key named "LongPathsEnabled" with value 0x1 at "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem" (see https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation for more information).
If this does not solve the problem and your system supports long paths, you can try to use a nested path structure. You can change this by toggling the setting at Options > Decompiler > Project export > Use nested directories for namespaces. This helps because even on "long-path-aware" platforms, the length of a directory name is limited, on Windows/NTFS this is 255 characters.</value>
</data>
<data name="PropertyManuallyMissingReferencesListLoadedAssemblies" xml:space="preserve">
<value>for ex. property getter/setter access. To get optimal decompilation results, please manually add the missing references to the list of loaded assemblies.</value>
</data>
<data name="PublicToken" xml:space="preserve">
<value>Public Key Token</value>
</data>
<data name="R_ename" xml:space="preserve">
<value>R_ename</value>
</data>
<data name="ReferenceName" xml:space="preserve">
<value>Reference Name</value>
</data>
<data name="References" xml:space="preserve">
<value>References</value>
</data>
<data name="RefreshCommand_ReloadAssemblies" xml:space="preserve">
<value>Reload all assemblies</value>
</data>
<data name="ReloadAssemblies" xml:space="preserve">
<value>Reload all assemblies</value>
</data>
<data name="Remove" xml:space="preserve">
<value>Remove</value>
</data>
<data name="RemoveDeadSideEffectFreeCode" xml:space="preserve">
<value>Remove dead and side effect free code</value>
</data>
<data name="RemoveShellIntegration" xml:space="preserve">
<value>Remove shell integration</value>
</data>
<data name="RemoveShellIntegrationMessage" xml:space="preserve">
<value>This will remove "{0}" from the registry at "HKCU\Software\Classes\dllfile\shell\Open with ILSpy\command" and "HKCU\Software\Classes\exefile\shell\Open with ILSpy\command".
Do you want to continue?</value>
</data>
<data name="RenameList" xml:space="preserve">
<value>Rename list</value>
</data>
<data name="ResetToDefaults" xml:space="preserve">
<value>Reset to defaults</value>
</data>
<data name="ResetToDefaultsConfirmationMessage" xml:space="preserve">
<value>Do you really want to load the default settings for the active page?</value>
</data>
<data name="ResourcesFileFilter" xml:space="preserve">
<value>Resources file (*.resources)|*.resources|Resource XML file|*.resx</value>
</data>
<data name="Save" xml:space="preserve">
<value>Save</value>
</data>
<data name="SaveCode" xml:space="preserve">
<value>Save Code</value>
</data>
<data name="ScopeSearchToThisAssembly" xml:space="preserve">
<value>Scope search to this assembly</value>
</data>
<data name="ScopeSearchToThisNamespace" xml:space="preserve">
<value>Scope search to this namespace</value>
</data>
<data name="Search" xml:space="preserve">
<value>Search...</value>
</data>
<data name="SearchAbortedMoreThan1000ResultsFound" xml:space="preserve">
<value>Search aborted, more than 1000 results found.</value>
</data>
<data name="SearchCtrlShiftFOrCtrlE" xml:space="preserve">
<value>Search (Ctrl+Shift+F or Ctrl+E)</value>
</data>
<data name="SearchMSDN" xml:space="preserve">
<value>Search Microsoft Docs...</value>
</data>
<data name="SearchPane_Search" xml:space="preserve">
<value>Search</value>
</data>
<data name="Searching" xml:space="preserve">
<value>Searching...</value>
</data>
<data name="Select" xml:space="preserve">
<value>Select All</value>
</data>
<data name="SelectAssembliesOpen" xml:space="preserve">
<value>Select assemblies to open:</value>
</data>
<data name="SelectAssemblyListDropdownTooltip" xml:space="preserve">
<value>Select a list of assemblies (Alt+A)</value>
</data>
<data name="SelectLanguageDropdownTooltip" xml:space="preserve">
<value>Select language to decompile to (Alt+L)</value>
</data>
<data name="SelectList" xml:space="preserve">
<value>Select a list:</value>
</data>
<data name="SelectPDB" xml:space="preserve">
<value>Select PDB...</value>
</data>
<data name="SelectVersionDropdownTooltip" xml:space="preserve">
<value>Select version of language to output (Alt+E)</value>
</data>
<data name="SettingsChangeRestartRequired" xml:space="preserve">
<value>You must restart ILSpy for the change to take effect.</value>
</data>
<data name="Shell" xml:space="preserve">
<value>Shell</value>
</data>
<data name="ShowAllTypesAndMembers" xml:space="preserve">
<value>Show all types and members</value>
</data>
<data name="ShowAssemblyLoad" xml:space="preserve">
<value>Show assembly load log</value>
</data>
<data name="ShowChildIndexInBlock" xml:space="preserve">
<value>ShowChildIndexInBlock</value>
</data>
<data name="ShowDocumentationDecompiledCode" xml:space="preserve">
<value>Show XML documentation in decompiled code</value>
</data>
<data name="ShowILRanges" xml:space="preserve">
<value>ShowILRanges</value>
</data>
<data name="ShowInfoFromDebugSymbolsAvailable" xml:space="preserve">
<value>Show info from debug symbols, if available</value>
</data>
<data name="ShowInternalTypesMembers" xml:space="preserve">
<value>Show public, private and internal</value>
</data>
<data name="ShowLineNumbers" xml:space="preserve">
<value>Show line numbers</value>
</data>
<data name="ShowMetadataTokens" xml:space="preserve">
<value>Show metadata tokens</value>
</data>
<data name="ShowMetadataTokensInBase10" xml:space="preserve">
<value>Show metadata tokens in base 10</value>
</data>
<data name="ShowPublicOnlyTypesMembers" xml:space="preserve">
<value>Show only public types and members</value>
</data>
<data name="ShowRawOffsetsAndBytesBeforeInstruction" xml:space="preserve">
<value>Show raw offsets and bytes before each instruction</value>
</data>
<data name="ShowStateAfterThisStep" xml:space="preserve">
<value>Show state after this step</value>
</data>
<data name="ShowStateBeforeThisStep" xml:space="preserve">
<value>Show state before this step</value>
</data>
<data name="Show_allTypesAndMembers" xml:space="preserve">
<value>Show _all types and members</value>
</data>
<data name="Show_internalTypesMembers" xml:space="preserve">
<value>Show public, private and internal</value>
</data>
<data name="Show_publiconlyTypesMembers" xml:space="preserve">
<value>Show only _public types and members</value>
</data>
<data name="Size" xml:space="preserve">
<value>Size:</value>
</data>
<data name="SortAssemblyListName" xml:space="preserve">
<value>Sort assembly list by name</value>
</data>
<data name="SortAssembly_listName" xml:space="preserve">
<value>Sort assembly _list by name</value>
</data>
<data name="SortResultsFitness" xml:space="preserve">
<value>Sort results by fitness</value>
</data>
<data name="StandBy" xml:space="preserve">
<value>Stand by...</value>
</data>
<data name="Status" xml:space="preserve">
<value>Status</value>
</data>
<data name="StringTable" xml:space="preserve">
<value>String Table</value>
</data>
<data name="StyleTheWindowTitleBar" xml:space="preserve">
<value>Style the window title bar</value>
</data>
<data name="TabSize" xml:space="preserve">
<value>Tab size:</value>
</data>
<data name="Theme" xml:space="preserve">
<value>Theme</value>
</data>
<data name="ToggleFolding" xml:space="preserve">
<value>Toggle All Folding</value>
</data>
<data name="TreeViewOptions" xml:space="preserve">
<value>Tree view options</value>
</data>
<data name="Type" xml:space="preserve">
<value>Type</value>
</data>
<data name="UILanguage" xml:space="preserve">
<value>UI Language</value>
</data>
<data name="UILanguage_System" xml:space="preserve">
<value>System</value>
</data>
<data name="UpdateILSpyFound" xml:space="preserve">
<value>No update for ILSpy found.</value>
</data>
<data name="UseFieldSugar" xml:space="preserve">
<value>UseFieldSugar</value>
</data>
<data name="UseLogicOperationSugar" xml:space="preserve">
<value>UseLogicOperationSugar</value>
</data>
<data name="UseNestedNamespaceNodes" xml:space="preserve">
<value>Use nested namespace structure</value>
</data>
<data name="UseTabsInsteadOfSpaces" xml:space="preserve">
<value>Use tabs instead of spaces</value>
</data>
<data name="UsingLatestRelease" xml:space="preserve">
<value>You are using the latest release.</value>
</data>
<data name="UsingNightlyBuildNewerThanLatestRelease" xml:space="preserve">
<value>You are using a nightly build newer than the latest release.</value>
</data>
<data name="Value" xml:space="preserve">
<value>Value</value>
</data>
<data name="ValueString" xml:space="preserve">
<value>Value (as string)</value>
</data>
<data name="VariableNamesFromDebugSymbolsAvailable" xml:space="preserve">
<value>Use variable names from debug symbols, if available</value>
</data>
<data name="Version" xml:space="preserve">
<value>Version</value>
</data>
<data name="VersionAvailable" xml:space="preserve">
<value>Version {0} is available.</value>
</data>
<data name="View" xml:space="preserve">
<value>View</value>
</data>
<data name="VisualStudioSolutionFileSlnAllFiles" xml:space="preserve">
<value>Visual Studio Solution file|*.sln|All files|*.*</value>
</data>
<data name="WarningAsmMarkedRef" xml:space="preserve">
<value>Warning: This assembly is marked as 'reference assembly', which means that it only contains metadata and no executable code.</value>
</data>
<data name="WarningSomeAssemblyReference" xml:space="preserve">
<value>Warning: Some assembly references could not be resolved automatically. This might lead to incorrect decompilation of some parts,</value>
</data>
<data name="WatermarkText" xml:space="preserve">
<value>Search for t:TypeName, m:Member or c:Constant; use exact match (=term), 'should not contain' (-term) or 'must contain' (+term); use /reg(ular)?Ex(pressions)?/ or both - t:/Type(Name)?/...</value>
</data>
<data name="Window_CloseAllDocuments" xml:space="preserve">
<value>_Close all documents</value>
</data>
<data name="Window_ResetLayout" xml:space="preserve">
<value>_Reset layout</value>
</data>
<data name="_About" xml:space="preserve">
<value>_About</value>
</data>
<data name="_AddMainList" xml:space="preserve">
<value>_Add To Main List</value>
</data>
<data name="_Analyzer" xml:space="preserve">
<value>Analy_zer</value>
</data>
<data name="_Assemblies" xml:space="preserve">
<value>_Assemblies</value>
</data>
<data name="_CheckUpdates" xml:space="preserve">
<value>_Check for Updates</value>
</data>
<data name="_CollapseTreeNodes" xml:space="preserve">
<value>_Collapse all tree nodes</value>
</data>
<data name="_File" xml:space="preserve">
<value>_File</value>
</data>
<data name="_Help" xml:space="preserve">
<value>_Help</value>
</data>
<data name="_LoadDependencies" xml:space="preserve">
<value>_Load Dependencies</value>
</data>
<data name="_New" xml:space="preserve">
<value>_New</value>
</data>
<data name="_Open" xml:space="preserve">
<value>_Open...</value>
</data>
<data name="_OpenCommandLineHere" xml:space="preserve">
<value>_Open Command Line Here</value>
</data>
<data name="_OpenContainingFolder" xml:space="preserve">
<value>_Open Containing Folder</value>
</data>
<data name="_Options" xml:space="preserve">
<value>_Options...</value>
</data>
<data name="_Reload" xml:space="preserve">
<value>_Reload</value>
</data>
<data name="_Remove" xml:space="preserve">
<value>_Remove</value>
</data>
<data name="_RemoveAssembliesWithLoadErrors" xml:space="preserve">
<value>_Remove Assemblies with load errors</value>
</data>
<data name="_Reset" xml:space="preserve">
<value>_Reset</value>
</data>
<data name="_Resources" xml:space="preserve">
<value>Resources</value>
</data>
<data name="_SaveCode" xml:space="preserve">
<value>_Save Code...</value>
</data>
<data name="_Search" xml:space="preserve">
<value>_Search:</value>
</data>
<data name="_SearchFor" xml:space="preserve">
<value>_Search for:</value>
</data>
<data name="_ShowDebugSteps" xml:space="preserve">
<value>_Show debug steps</value>
</data>
<data name="_ToggleFolding" xml:space="preserve">
<value>Toggle Folding</value>
</data>
<data name="_View" xml:space="preserve">
<value>_View</value>
</data>
<data name="_Window" xml:space="preserve">
<value>_Window</value>
</data>
</root> | ILSpy/ILSpy/Properties/Resources.resx/0 | {
"file_path": "ILSpy/ILSpy/Properties/Resources.resx",
"repo_id": "ILSpy",
"token_count": 16123
} | 263 |
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Rendering;
namespace ICSharpCode.ILSpy.TextView;
public class DecompilerTextEditor : TextEditor
{
protected override IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
return new ThemeAwareHighlightingColorizer(highlightingDefinition);
}
}
| ILSpy/ILSpy/TextView/DecompilerTextEditor.cs/0 | {
"file_path": "ILSpy/ILSpy/TextView/DecompilerTextEditor.cs",
"repo_id": "ILSpy",
"token_count": 118
} | 264 |
#nullable enable
using System.Windows;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Highlighting;
namespace ICSharpCode.ILSpy.Themes;
public class SyntaxColor
{
public Color? Foreground { get; set; }
public Color? Background { get; set; }
public FontWeight? FontWeight { get; set; }
public FontStyle? FontStyle { get; set; }
public void ApplyTo(HighlightingColor color)
{
color.Foreground = Foreground is { } foreground ? new SimpleHighlightingBrush(foreground) : null;
color.Background = Background is { } background ? new SimpleHighlightingBrush(background) : null;
color.FontWeight = FontWeight ?? FontWeights.Normal;
color.FontStyle = FontStyle ?? FontStyles.Normal;
}
public static void ResetColor(HighlightingColor color)
{
color.Foreground = null;
color.Background = null;
color.FontWeight = null;
color.FontStyle = null;
}
}
| ILSpy/ILSpy/Themes/SyntaxColor.cs/0 | {
"file_path": "ILSpy/ILSpy/Themes/SyntaxColor.cs",
"repo_id": "ILSpy",
"token_count": 277
} | 265 |
// 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.Linq;
using System.Threading;
using ICSharpCode.Decompiler;
using ICSharpCode.ILSpyX;
namespace ICSharpCode.ILSpy.TreeNodes
{
using ICSharpCode.Decompiler.TypeSystem;
class DerivedTypesEntryNode : ILSpyTreeNode, IMemberTreeNode
{
readonly AssemblyList list;
readonly ITypeDefinition type;
readonly ThreadingSupport threading;
public DerivedTypesEntryNode(AssemblyList list, ITypeDefinition type)
{
this.list = list;
this.type = type;
this.LazyLoading = true;
threading = new ThreadingSupport();
}
public override bool ShowExpander => !type.IsSealed && base.ShowExpander;
public override object Text {
get { return Language.TypeToString(type, includeNamespace: true) + GetSuffixString(type.MetadataToken); }
}
public override object Icon => TypeTreeNode.GetIcon(type);
public override FilterResult Filter(FilterSettings settings)
{
if (settings.ShowApiLevel == ApiVisibility.PublicOnly && !IsPublicAPI)
return FilterResult.Hidden;
if (settings.SearchTermMatches(type.Name))
{
if (type.DeclaringType != null && (settings.ShowApiLevel != ApiVisibility.All || !settings.Language.ShowMember(type)))
return FilterResult.Hidden;
else
return FilterResult.Match;
}
else
return FilterResult.Recurse;
}
public override bool IsPublicAPI {
get {
switch (type.Accessibility)
{
case Accessibility.Public:
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal:
return true;
default:
return false;
}
}
}
protected override void LoadChildren()
{
threading.LoadChildren(this, FetchChildren);
}
IEnumerable<ILSpyTreeNode> FetchChildren(CancellationToken ct)
{
// FetchChildren() runs on the main thread; but the enumerator will be consumed on a background thread
return DerivedTypesTreeNode.FindDerivedTypes(list, type, ct);
}
public override void ActivateItem(System.Windows.RoutedEventArgs e)
{
e.Handled = BaseTypesEntryNode.ActivateItem(this, type);
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, language.TypeToString(type, includeNamespace: true));
}
IEntity IMemberTreeNode.Member => type;
}
}
| ILSpy/ILSpy/TreeNodes/DerivedTypesEntryNode.cs/0 | {
"file_path": "ILSpy/ILSpy/TreeNodes/DerivedTypesEntryNode.cs",
"repo_id": "ILSpy",
"token_count": 1106
} | 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;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using ICSharpCode.ILSpyX.Settings;
namespace ICSharpCode.ILSpy.Updates
{
internal static class NotifyOfUpdatesStrategy
{
static readonly Uri UpdateUrl = new Uri("https://ilspy.net/updates.xml");
const string band = "stable";
public static AvailableVersionInfo LatestAvailableVersion { get; private set; }
public static async Task<AvailableVersionInfo> GetLatestVersionAsync()
{
var client = new HttpClient(new HttpClientHandler() {
UseProxy = true,
UseDefaultCredentials = true,
});
string data = await client.GetStringAsync(UpdateUrl).ConfigureAwait(false);
XDocument doc = XDocument.Load(new StringReader(data));
var bands = doc.Root.Elements("band");
var currentBand = bands.FirstOrDefault(b => (string)b.Attribute("id") == band) ?? bands.First();
Version version = new Version((string)currentBand.Element("latestVersion"));
string url = (string)currentBand.Element("downloadUrl");
if (!(url.StartsWith("http://", StringComparison.Ordinal) || url.StartsWith("https://", StringComparison.Ordinal)))
url = null; // don't accept non-urls
LatestAvailableVersion = new AvailableVersionInfo { Version = version, DownloadUrl = url };
return LatestAvailableVersion;
}
/// <summary>
/// If automatic update checking is enabled, checks if there are any updates available.
/// Returns the download URL if an update is available.
/// Returns null if no update is available, or if no check was performed.
/// </summary>
public static async Task<string> CheckForUpdatesIfEnabledAsync(ILSpySettings spySettings)
{
UpdateSettings s = new UpdateSettings(spySettings);
// If we're in an MSIX package, updates work differently
if (s.AutomaticUpdateCheckEnabled)
{
// perform update check if we never did one before;
// or if the last check wasn't in the past 7 days
if (s.LastSuccessfulUpdateCheck == null
|| s.LastSuccessfulUpdateCheck < DateTime.UtcNow.AddDays(-7)
|| s.LastSuccessfulUpdateCheck > DateTime.UtcNow)
{
return await CheckForUpdateInternal(s).ConfigureAwait(false);
}
else
{
return null;
}
}
else
{
return null;
}
}
public static Task<string> CheckForUpdatesAsync(ILSpySettings spySettings)
{
UpdateSettings s = new UpdateSettings(spySettings);
return CheckForUpdateInternal(s);
}
static async Task<string> CheckForUpdateInternal(UpdateSettings s)
{
try
{
var v = await GetLatestVersionAsync().ConfigureAwait(false);
s.LastSuccessfulUpdateCheck = DateTime.UtcNow;
if (v.Version > AppUpdateService.CurrentVersion)
return v.DownloadUrl;
else
return null;
}
catch (Exception)
{
// ignore errors getting the version info
return null;
}
}
}
}
| ILSpy/ILSpy/Updates/NotifyOfUpdatesStrategy.cs/0 | {
"file_path": "ILSpy/ILSpy/Updates/NotifyOfUpdatesStrategy.cs",
"repo_id": "ILSpy",
"token_count": 1295
} | 267 |
// 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.
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
// //
// DO NOT EDIT GlobalAssemblyInfo.cs, it is recreated using AssemblyInfo.template whenever //
// ICSharpCode.Core is compiled. //
// //
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Resources;
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: AssemblyCompany("ic#code")]
[assembly: AssemblyProduct("SharpDevelop")]
[assembly: AssemblyCopyright("2000-2012 AlphaSierraPapa for the SharpDevelop Team")]
[assembly: AssemblyVersion(RevisionClass.Major + "." + RevisionClass.Minor + "." + RevisionClass.Build + "." + RevisionClass.Revision)]
[assembly: AssemblyInformationalVersion(RevisionClass.FullVersion + "-ca8a8e28")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly",
Justification = "AssemblyInformationalVersion does not need to be a parsable version")]
internal static class RevisionClass
{
public const string Major = "4";
public const string Minor = "2";
public const string Build = "0";
public const string Revision = "8752";
public const string VersionName = "Beta 2";
public const string FullVersion = Major + "." + Minor + "." + Build + ".8752-Beta 2";
}
| ILSpy/SharpTreeView/Properties/GlobalAssemblyInfo.cs/0 | {
"file_path": "ILSpy/SharpTreeView/Properties/GlobalAssemblyInfo.cs",
"repo_id": "ILSpy",
"token_count": 898
} | 268 |
// 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.Reflection.Metadata;
using System.Windows.Controls;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpy;
namespace TestPlugin
{
/// <summary>
/// Adds a new language to the decompiler.
/// </summary>
[Export(typeof(Language))]
public class CustomLanguage : Language
{
public override string Name {
get {
return "Custom";
}
}
public override string FileExtension {
get {
// used in 'Save As' dialog
return ".txt";
}
}
// There are several methods available to override; in this sample, we deal with methods only
public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
{
var module = ((MetadataModule)method.ParentModule).PEFile;
var methodDef = module.Metadata.GetMethodDefinition((MethodDefinitionHandle)method.MetadataToken);
if (methodDef.HasBody())
{
var methodBody = module.Reader.GetMethodBody(methodDef.RelativeVirtualAddress);
output.WriteLine("Size of method: {0} bytes", methodBody.GetCodeSize());
ISmartTextOutput smartOutput = output as ISmartTextOutput;
if (smartOutput != null)
{
// when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons:
smartOutput.AddButton(null, "Click me!", (sender, e) => (sender as Button).Content = "I was clicked!");
smartOutput.WriteLine();
}
// ICSharpCode.Decompiler.CSharp.CSharpDecompiler can be used to decompile to C#.
/*
ModuleDefinition module = LoadModule(assemblyFileName);
var typeSystem = new DecompilerTypeSystem(module);
CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, new DecompilerSettings());
decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
SyntaxTree syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();
var visitor = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());
syntaxTree.AcceptVisitor(visitor);
*/
}
}
}
}
| ILSpy/TestPlugin/CustomLanguage.cs/0 | {
"file_path": "ILSpy/TestPlugin/CustomLanguage.cs",
"repo_id": "ILSpy",
"token_count": 773
} | 269 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace BeeBuildProgramCommon.Data
{
public class PackageInfo
{
public string Name;
public string ResolvedPath;
}
public struct Version
{
public int Release, Major, Minor;
public Version(int release, int major, int minor)
{
Release = release;
Major = major;
Minor = minor;
}
}
public class ConfigurationData
{
public string Il2CppDir;
public string UnityLinkerPath;
public string Il2CppPath;
public string NetCoreRunPath;
public string DotNetExe;
public string EditorContentsPath;
public PackageInfo[] Packages;
public string UnityVersion;
public Version UnityVersionNumeric;
public string UnitySourceCodePath;
public bool AdvancedLicense;
public bool Batchmode;
public bool EmitDataForBeeWhy;
public string NamedPipeOrUnixSocket;
}
}
| UnityCsReference/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/Data.cs/0 | {
"file_path": "UnityCsReference/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/Data.cs",
"repo_id": "UnityCsReference",
"token_count": 449
} | 270 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.U2D;
using UnityEditor.Build;
using UnityEditor.U2D.Common;
using UnityEditor.U2D.Interface;
using UnityEditorInternal;
using UnityEditor.AssetImporters;
namespace UnityEditor.U2D
{
[CustomEditor(typeof(SpriteAtlasImporter))]
internal class SpriteAtlasImporterInspector : AssetImporterEditor
{
class SpriteAtlasInspectorPlatformSettingView : TexturePlatformSettingsView
{
private bool m_ShowMaxSizeOption;
public SpriteAtlasInspectorPlatformSettingView(bool showMaxSizeOption)
{
m_ShowMaxSizeOption = showMaxSizeOption;
}
public override int DrawMaxSize(int defaultValue, bool isMixedValue, bool isDisabled, out bool changed)
{
if (m_ShowMaxSizeOption)
return base.DrawMaxSize(defaultValue, isMixedValue, isDisabled, out changed);
else
changed = false;
return defaultValue;
}
}
class Styles
{
public readonly GUIStyle preDropDown = "preDropDown";
public readonly GUIStyle previewButton = "preButton";
public readonly GUIStyle previewSlider = "preSlider";
public readonly GUIStyle previewSliderThumb = "preSliderThumb";
public readonly GUIStyle previewLabel = "preLabel";
public readonly GUIContent textureSettingLabel = EditorGUIUtility.TrTextContent("Texture");
public readonly GUIContent variantSettingLabel = EditorGUIUtility.TrTextContent("Variant");
public readonly GUIContent packingParametersLabel = EditorGUIUtility.TrTextContent("Packing");
public readonly GUIContent atlasTypeLabel = EditorGUIUtility.TrTextContent("Type");
public readonly GUIContent defaultPlatformLabel = EditorGUIUtility.TrTextContent("Default");
public readonly GUIContent masterAtlasLabel = EditorGUIUtility.TrTextContent("Master Atlas", "Assigning another Sprite Atlas asset will make this atlas a variant of it.");
public readonly GUIContent packerLabel = EditorGUIUtility.TrTextContent("Scriptable Packer", "Scriptable Object that implements custom packing for Sprite-Atlas.");
public readonly GUIContent bindAsDefaultLabel = EditorGUIUtility.TrTextContent("Include in Build", "Packed textures will be included in the build by default.");
public readonly GUIContent enableRotationLabel = EditorGUIUtility.TrTextContent("Allow Rotation", "Try rotating the sprite to fit better during packing.");
public readonly GUIContent enableTightPackingLabel = EditorGUIUtility.TrTextContent("Tight Packing", "Use the mesh outline to fit instead of the whole texture rect during packing.");
public readonly GUIContent enableAlphaDilationLabel = EditorGUIUtility.TrTextContent("Alpha Dilation", "Enable Alpha Dilation for SpriteAtlas padding pixels.");
public readonly GUIContent paddingLabel = EditorGUIUtility.TrTextContent("Padding", "The amount of extra padding between packed sprites.");
public readonly GUIContent generateMipMapLabel = EditorGUIUtility.TrTextContent("Generate Mip Maps");
public readonly GUIContent packPreviewLabel = EditorGUIUtility.TrTextContent("Pack Preview", "Save and preview packed Sprite Atlas textures.");
public readonly GUIContent sRGBLabel = EditorGUIUtility.TrTextContent("sRGB", "Texture content is stored in gamma space.");
public readonly GUIContent readWrite = EditorGUIUtility.TrTextContent("Read/Write", "Enable to be able to access the raw pixel data from code.");
public readonly GUIContent variantMultiplierLabel = EditorGUIUtility.TrTextContent("Scale", "Down scale ratio.");
public readonly GUIContent copyMasterButton = EditorGUIUtility.TrTextContent("Copy Master's Settings", "Copy all master's settings into this variant.");
public readonly GUIContent disabledPackLabel = EditorGUIUtility.TrTextContent("Sprite Atlas packing is disabled. Enable it in Edit > Project Settings > Editor.", null, EditorGUIUtility.GetHelpIcon(MessageType.Info));
public readonly GUIContent packableListLabel = EditorGUIUtility.TrTextContent("Objects for Packing", "Only accepts Folders, Sprite Sheet (Texture) and Sprite.");
public readonly GUIContent notPowerOfTwoWarning = EditorGUIUtility.TrTextContent("This scale will produce a Variant Sprite Atlas with a packed Texture that is NPOT (non - power of two). This may cause visual artifacts in certain compression/Texture formats.");
public readonly GUIContent secondaryTextureNameLabel = EditorGUIUtility.TrTextContent("Secondary Texture Name", "The name of the Secondary Texture to apply the following settings to.");
public readonly GUIContent platformSettingsDropDownLabel = EditorGUIUtility.TrTextContent("Show Platform Settings For");
public readonly GUIContent smallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow");
public readonly GUIContent largeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh");
public readonly GUIContent alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha");
public readonly GUIContent RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB");
public readonly GUIContent trashIcon = EditorGUIUtility.TrIconContent("TreeEditor.Trash", "Delete currently selected settings.");
public readonly int packableElementHash = "PackableElement".GetHashCode();
public readonly int packableSelectorHash = "PackableSelector".GetHashCode();
public readonly string swapObjectRegisterUndo = L10n.Tr("Swap Packable");
public readonly string secondaryTextureNameTextControlName = "secondary_texture_name_text_field";
public readonly string defaultTextForSecondaryTextureName = L10n.Tr("(Matches the names of the Secondary Textures in your Sprites.)");
public readonly string nameUniquenessWarning = L10n.Tr("Secondary Texture names must be unique within a Sprite or Sprite Atlas.");
public readonly int[] atlasTypeValues = { 0, 1 };
public readonly GUIContent[] atlasTypeOptions =
{
EditorGUIUtility.TrTextContent("Master"),
EditorGUIUtility.TrTextContent("Variant"),
};
public readonly int[] paddingValues = { 2, 4, 8 };
public readonly GUIContent[] paddingOptions;
public Styles()
{
paddingOptions = new GUIContent[paddingValues.Length];
for (var i = 0; i < paddingValues.Length; ++i)
paddingOptions[i] = EditorGUIUtility.TextContent(paddingValues[i].ToString());
}
}
private static Styles s_Styles;
private static Styles styles
{
get
{
s_Styles = s_Styles ?? new Styles();
return s_Styles;
}
}
private SpriteAtlasAsset spriteAtlasAsset
{
get { return m_TargetAsset; }
}
private SpriteAtlasImporter spriteAtlasImporter
{
get { return target as SpriteAtlasImporter; }
}
private enum AtlasType { Undefined = -1, Master = 0, Variant = 1 }
private SerializedProperty m_FilterMode;
private SerializedProperty m_AnisoLevel;
private SerializedProperty m_GenerateMipMaps;
private SerializedProperty m_Readable;
private SerializedProperty m_UseSRGB;
private SerializedProperty m_EnableTightPacking;
private SerializedProperty m_EnableAlphaDilation;
private SerializedProperty m_EnableRotation;
private SerializedProperty m_Padding;
private SerializedProperty m_BindAsDefault;
private SerializedProperty m_Packables;
private SerializedProperty m_MasterAtlas;
private SerializedProperty m_VariantScale;
private SerializedProperty m_ScriptablePacker;
private string m_Hash;
private int m_PreviewPage = 0;
private int m_TotalPages = 0;
private int[] m_OptionValues = null;
private string[] m_OptionDisplays = null;
private Texture2D[] m_PreviewTextures = null;
private Texture2D[] m_PreviewAlphaTextures = null;
private bool m_PackableListExpanded = true;
private ReorderableList m_PackableList;
private SpriteAtlasAsset m_TargetAsset;
private string m_AssetPath;
private float m_MipLevel = 0;
private bool m_ShowAlpha;
private bool m_Discard = false;
private List<string> m_PlatformSettingsOptions;
private int m_SelectedPlatformSettings = 0;
private int m_ContentHash = 0;
private List<BuildPlatform> m_ValidPlatforms;
private Dictionary<string, List<TextureImporterPlatformSettings>> m_TempPlatformSettings;
private ITexturePlatformSettingsView m_TexturePlatformSettingsView;
private ITexturePlatformSettingsView m_SecondaryTexturePlatformSettingsView;
private ITexturePlatformSettingsFormatHelper m_TexturePlatformSettingTextureHelper;
private ITexturePlatformSettingsController m_TexturePlatformSettingsController;
private SerializedObject m_SerializedAssetObject = null;
// The first two options are the main texture and a separator while the last two options are another separator and the new settings menu.
private bool secondaryTextureSelected { get { return m_SelectedPlatformSettings >= 2 && m_SelectedPlatformSettings <= m_PlatformSettingsOptions.Count - 3; } }
static bool IsPackable(Object o)
{
return o != null && (o.GetType() == typeof(Sprite) || o.GetType() == typeof(Texture2D) || (o.GetType() == typeof(DefaultAsset) && ProjectWindowUtil.IsFolder(o.GetInstanceID())));
}
static Object ValidateObjectForPackableFieldAssignment(Object[] references, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidatorOptions options)
{
// We only validate and care about the first one as this is a object field assignment.
if (references.Length > 0 && IsPackable(references[0]))
return references[0];
return null;
}
bool IsTargetVariant()
{
return spriteAtlasAsset ? spriteAtlasAsset.isVariant : false;
}
bool IsTargetMaster()
{
return spriteAtlasAsset ? !spriteAtlasAsset.isVariant : true;
}
protected override bool needsApplyRevert => false;
internal override string targetTitle
{
get
{
return spriteAtlasAsset ? ( Path.GetFileNameWithoutExtension(m_AssetPath) + " (Sprite Atlas)" ) : "SpriteAtlasImporter Settings";
}
}
private string LoadSourceAsset()
{
var assetPath = AssetDatabase.GetAssetPath(target);
var loadedObjects = InternalEditorUtility.LoadSerializedFileAndForget(assetPath);
if (loadedObjects.Length > 0)
m_TargetAsset = loadedObjects[0] as SpriteAtlasAsset;
return assetPath;
}
private SerializedObject serializedAssetObject
{
get
{
return GetSerializedAssetObject();
}
}
internal static int SpriteAtlasAssetHash(SerializedObject obj)
{
int hashCode = 0;
if (obj == null)
return 0;
unchecked
{
hashCode = (int)2166136261 ^ (int) obj.FindProperty("m_MasterAtlas").contentHash;
hashCode = hashCode * 16777619 ^ (int) obj.FindProperty("m_ImporterData").contentHash;
hashCode = hashCode * 16777619 ^ (int) obj.FindProperty("m_IsVariant").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_ScriptablePacker").contentHash;
}
return hashCode;
}
internal static int SpriteAtlasImporterHash(SerializedObject obj)
{
int hashCode = 0;
if (obj == null)
return 0;
unchecked
{
hashCode = (int)2166136261 ^ (int)obj.FindProperty("m_PackingSettings").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_TextureSettings").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_PlatformSettings").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_SecondaryTextureSettings").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_BindAsDefault").contentHash;
hashCode = hashCode * 16777619 ^ (int)obj.FindProperty("m_VariantMultiplier").contentHash;
}
return hashCode;
}
internal int GetInspectorHash()
{
return SpriteAtlasAssetHash(m_SerializedAssetObject) * 16777619 ^ SpriteAtlasImporterHash(m_SerializedObject);
}
private SerializedObject GetSerializedAssetObject()
{
if (m_SerializedAssetObject == null)
{
try
{
m_SerializedAssetObject = new SerializedObject(spriteAtlasAsset, m_Context);
m_SerializedAssetObject.inspectorMode = inspectorMode;
m_ContentHash = GetInspectorHash();
m_EnabledProperty = m_SerializedAssetObject.FindProperty("m_Enabled");
}
catch (System.ArgumentException e)
{
m_SerializedAssetObject = null;
m_EnabledProperty = null;
throw new SerializedObjectNotCreatableException(e.Message);
}
}
return m_SerializedAssetObject;
}
public override void OnEnable()
{
base.OnEnable();
m_FilterMode = serializedObject.FindProperty("m_TextureSettings.filterMode");
m_AnisoLevel = serializedObject.FindProperty("m_TextureSettings.anisoLevel");
m_GenerateMipMaps = serializedObject.FindProperty("m_TextureSettings.generateMipMaps");
m_Readable = serializedObject.FindProperty("m_TextureSettings.readable");
m_UseSRGB = serializedObject.FindProperty("m_TextureSettings.sRGB");
m_EnableTightPacking = serializedObject.FindProperty("m_PackingSettings.enableTightPacking");
m_EnableRotation = serializedObject.FindProperty("m_PackingSettings.enableRotation");
m_EnableAlphaDilation = serializedObject.FindProperty("m_PackingSettings.enableAlphaDilation");
m_Padding = serializedObject.FindProperty("m_PackingSettings.padding");
m_BindAsDefault = serializedObject.FindProperty("m_BindAsDefault");
m_VariantScale = serializedObject.FindProperty("m_VariantMultiplier");
PopulatePlatformSettingsOptions();
SyncPlatformSettings();
m_TexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(IsTargetMaster());
m_TexturePlatformSettingTextureHelper = new TexturePlatformSettingsFormatHelper();
m_TexturePlatformSettingsController = new TexturePlatformSettingsViewController();
// Don't show max size option for secondary textures as they must have the same size as the main texture.
m_SecondaryTexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(false);
m_AssetPath = LoadSourceAsset();
if (spriteAtlasAsset == null)
return;
m_MasterAtlas = serializedAssetObject.FindProperty("m_MasterAtlas");
m_ScriptablePacker = serializedAssetObject.FindProperty("m_ScriptablePacker");
m_Packables = serializedAssetObject.FindProperty("m_ImporterData.packables");
m_PackableList = new ReorderableList(serializedAssetObject, m_Packables, true, true, true, true);
m_PackableList.onAddCallback = AddPackable;
m_PackableList.drawElementCallback = DrawPackableElement;
m_PackableList.elementHeight = EditorGUIUtility.singleLineHeight;
m_PackableList.headerHeight = 0f;
}
// Populate the platform settings dropdown list with secondary texture names found through serialized properties of the Sprite Atlas assets.
private void PopulatePlatformSettingsOptions()
{
m_PlatformSettingsOptions = new List<string> { L10n.Tr("Main Texture"), "", "", L10n.Tr("New Secondary Texture settings.") };
SerializedProperty secondaryPlatformSettings = serializedObject.FindProperty("m_SecondaryTextureSettings");
if (secondaryPlatformSettings != null && !secondaryPlatformSettings.hasMultipleDifferentValues)
{
int numSecondaryTextures = secondaryPlatformSettings.arraySize;
List<string> secondaryTextureNames = new List<string>(numSecondaryTextures);
for (int i = 0; i < numSecondaryTextures; ++i)
secondaryTextureNames.Add(secondaryPlatformSettings.GetArrayElementAtIndex(i).displayName);
// Insert after main texture and the separator.
m_PlatformSettingsOptions.InsertRange(2, secondaryTextureNames);
}
m_SelectedPlatformSettings = 0;
}
void SyncPlatformSettings()
{
m_TempPlatformSettings = new Dictionary<string, List<TextureImporterPlatformSettings>>();
string secondaryTextureName = null;
if (secondaryTextureSelected)
secondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings];
// Default platform
var defaultSettings = new List<TextureImporterPlatformSettings>();
m_TempPlatformSettings.Add(TextureImporterInspector.s_DefaultPlatformName, defaultSettings);
var settings = secondaryTextureSelected
? spriteAtlasImporter.GetSecondaryPlatformSettings(TextureImporterInspector.s_DefaultPlatformName, secondaryTextureName)
: spriteAtlasImporter.GetPlatformSettings(TextureImporterInspector.s_DefaultPlatformName);
defaultSettings.Add(settings);
m_ValidPlatforms = BuildPlatforms.instance.GetValidPlatforms();
foreach (var platform in m_ValidPlatforms)
{
var platformSettings = new List<TextureImporterPlatformSettings>();
m_TempPlatformSettings.Add(platform.name, platformSettings);
var perPlatformSettings = secondaryTextureSelected ? spriteAtlasImporter.GetSecondaryPlatformSettings(platform.name, secondaryTextureName) : spriteAtlasImporter.GetPlatformSettings(platform.name);
// setting will be in default state if copy failed
platformSettings.Add(perPlatformSettings);
}
}
void RenameSecondaryPlatformSettings(string oldName, string newName)
{
spriteAtlasImporter.DeleteSecondaryPlatformSettings(oldName);
var defaultPlatformSettings = m_TempPlatformSettings[TextureImporterInspector.s_DefaultPlatformName];
spriteAtlasImporter.SetSecondaryPlatformSettings(defaultPlatformSettings[0], newName);
foreach (var buildPlatform in m_ValidPlatforms)
{
var platformSettings = m_TempPlatformSettings[buildPlatform.name];
spriteAtlasImporter.SetSecondaryPlatformSettings(platformSettings[0], newName);
}
}
void AddPackable(ReorderableList list)
{
ObjectSelector.get.Show(null, typeof(Object), null, false);
ObjectSelector.get.searchFilter = "t:sprite t:texture2d t:folder";
ObjectSelector.get.objectSelectorID = styles.packableSelectorHash;
}
void DrawPackableElement(Rect rect, int index, bool selected, bool focused)
{
var property = m_Packables.GetArrayElementAtIndex(index);
var controlID = EditorGUIUtility.GetControlID(styles.packableElementHash, FocusType.Passive);
var previousObject = property.objectReferenceValue;
var changedObject = EditorGUI.DoObjectField(rect, rect, controlID, previousObject, target, typeof(Object), ValidateObjectForPackableFieldAssignment, false);
if (changedObject != previousObject)
{
Undo.RegisterCompleteObjectUndo(spriteAtlasAsset, styles.swapObjectRegisterUndo);
property.objectReferenceValue = changedObject;
}
if (GUIUtility.keyboardControl == controlID && !selected)
m_PackableList.index = index;
}
protected override void Apply()
{
if (HasModified())
{
if (spriteAtlasAsset)
{
SpriteAtlasAsset.Save(spriteAtlasAsset, m_AssetPath);
AssetDatabase.ImportAsset(m_AssetPath);
}
m_ContentHash = GetInspectorHash();
}
base.Apply();
}
protected override bool useAssetDrawPreview { get { return false; } }
protected void PackPreviewGUI()
{
EditorGUILayout.Space();
using (new GUILayout.HorizontalScope())
{
using (new EditorGUI.DisabledScope(!HasModified() || !IsValidAtlas() || Application.isPlaying))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button(styles.packPreviewLabel))
{
GUI.FocusControl(null);
SpriteAtlasUtility.EnableV2Import(true);
SaveChanges();
SpriteAtlasUtility.EnableV2Import(false);
}
}
}
}
private bool IsValidAtlas()
{
if (IsTargetVariant())
return m_MasterAtlas.objectReferenceValue != null;
else
return true;
}
public override bool HasModified()
{
return !m_Discard && (base.HasModified() || m_ContentHash != GetInspectorHash());
}
private void ValidateMasterAtlas()
{
if (m_MasterAtlas.objectReferenceValue != null)
{
var assetPath = AssetDatabase.GetAssetPath(m_MasterAtlas.objectReferenceValue);
if (assetPath == m_AssetPath)
{
UnityEngine.Debug.LogWarning("Cannot set itself as MasterAtlas. Please assign a valid MasterAtlas.");
m_MasterAtlas.objectReferenceValue = null;
}
}
if (m_MasterAtlas.objectReferenceValue != null)
{
SpriteAtlas masterAsset = m_MasterAtlas.objectReferenceValue as SpriteAtlas;
if (masterAsset != null && masterAsset.isVariant)
{
UnityEngine.Debug.LogWarning("Cannot set a VariantAtlas as MasterAtlas. Please assign a valid MasterAtlas.");
m_MasterAtlas.objectReferenceValue = null;
}
}
}
public override void OnInspectorGUI()
{
// Ensure changes done through script are reflected immediately in Inspector by Syncing m_TempPlatformSettings with Actual Settings.
SyncPlatformSettings();
serializedObject.Update();
if (spriteAtlasAsset)
{
serializedAssetObject.Update();
HandleCommonSettingUI();
}
EditorGUILayout.PropertyField(m_BindAsDefault, styles.bindAsDefaultLabel);
GUILayout.Space(EditorGUI.kSpacing);
bool isTargetMaster = true;
if (spriteAtlasAsset)
isTargetMaster = IsTargetMaster();
if (isTargetMaster)
HandleMasterSettingUI();
if (!spriteAtlasAsset || IsTargetVariant())
HandleVariantSettingUI();
GUILayout.Space(EditorGUI.kSpacing);
HandleTextureSettingUI();
GUILayout.Space(EditorGUI.kSpacing);
// Only show the packable object list when:
// - This is a master atlas.
if (targets.Length == 1 && IsTargetMaster() && spriteAtlasAsset)
HandlePackableListUI();
serializedObject.ApplyModifiedProperties();
if (spriteAtlasAsset)
{
serializedAssetObject.ApplyModifiedProperties();
PackPreviewGUI();
}
ApplyRevertGUI();
}
private void HandleCommonSettingUI()
{
var atlasType = AtlasType.Undefined;
if (IsTargetMaster())
atlasType = AtlasType.Master;
else if (IsTargetVariant())
atlasType = AtlasType.Variant;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = atlasType == AtlasType.Undefined;
atlasType = (AtlasType)EditorGUILayout.IntPopup(styles.atlasTypeLabel, (int)atlasType, styles.atlasTypeOptions, styles.atlasTypeValues);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
bool setToVariant = atlasType == AtlasType.Variant;
spriteAtlasAsset.SetIsVariant(setToVariant);
// Reinit the platform setting view
m_TexturePlatformSettingsView = new SpriteAtlasInspectorPlatformSettingView(IsTargetMaster());
}
m_ScriptablePacker.objectReferenceValue = EditorGUILayout.ObjectField(styles.packerLabel, m_ScriptablePacker.objectReferenceValue, typeof(UnityEditor.U2D.ScriptablePacker), false);
if (atlasType == AtlasType.Variant)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_MasterAtlas, styles.masterAtlasLabel);
if (EditorGUI.EndChangeCheck())
{
ValidateMasterAtlas();
// Apply modified properties here to have latest master atlas reflected in native codes.
serializedAssetObject.ApplyModifiedPropertiesWithoutUndo();
PopulatePlatformSettingsOptions();
SyncPlatformSettings();
}
}
}
private void HandleVariantSettingUI()
{
EditorGUILayout.LabelField(styles.variantSettingLabel, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_VariantScale, styles.variantMultiplierLabel);
// Test if the multiplier scale a power of two size (1024) into another power of 2 size.
if (!Mathf.IsPowerOfTwo((int)(m_VariantScale.floatValue * 1024)))
EditorGUILayout.HelpBox(styles.notPowerOfTwoWarning.text, MessageType.Warning, true);
}
private void HandleBoolToIntPropertyField(SerializedProperty prop, GUIContent content)
{
Rect rect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(rect, content, prop);
EditorGUI.BeginChangeCheck();
var boolValue = EditorGUI.Toggle(rect, content, prop.boolValue);
if (EditorGUI.EndChangeCheck())
prop.boolValue = boolValue;
EditorGUI.EndProperty();
}
private void HandleMasterSettingUI()
{
EditorGUILayout.LabelField(styles.packingParametersLabel, EditorStyles.boldLabel);
HandleBoolToIntPropertyField(m_EnableRotation, styles.enableRotationLabel);
HandleBoolToIntPropertyField(m_EnableTightPacking, styles.enableTightPackingLabel);
HandleBoolToIntPropertyField(m_EnableAlphaDilation, styles.enableAlphaDilationLabel);
EditorGUILayout.IntPopup(m_Padding, styles.paddingOptions, styles.paddingValues, styles.paddingLabel);
GUILayout.Space(EditorGUI.kSpacing);
}
private void HandleTextureSettingUI()
{
EditorGUILayout.LabelField(styles.textureSettingLabel, EditorStyles.boldLabel);
HandleBoolToIntPropertyField(m_Readable, styles.readWrite);
HandleBoolToIntPropertyField(m_GenerateMipMaps, styles.generateMipMapLabel);
HandleBoolToIntPropertyField(m_UseSRGB, styles.sRGBLabel);
EditorGUILayout.PropertyField(m_FilterMode);
var showAniso = !m_FilterMode.hasMultipleDifferentValues && !m_GenerateMipMaps.hasMultipleDifferentValues
&& (FilterMode)m_FilterMode.intValue != FilterMode.Point && m_GenerateMipMaps.boolValue;
if (showAniso)
EditorGUILayout.IntSlider(m_AnisoLevel, 0, 16);
GUILayout.Space(EditorGUI.kSpacing);
// "Show Platform Settings For" dropdown
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel(s_Styles.platformSettingsDropDownLabel);
EditorGUI.BeginChangeCheck();
m_SelectedPlatformSettings = EditorGUILayout.Popup(m_SelectedPlatformSettings, m_PlatformSettingsOptions.ToArray(), GUILayout.MaxWidth(150.0f));
if (EditorGUI.EndChangeCheck())
{
// New settings option is selected...
if (m_SelectedPlatformSettings == m_PlatformSettingsOptions.Count - 1)
{
m_PlatformSettingsOptions.Insert(m_SelectedPlatformSettings - 1, s_Styles.defaultTextForSecondaryTextureName);
m_SelectedPlatformSettings--;
EditorGUI.FocusTextInControl(s_Styles.secondaryTextureNameTextControlName);
}
SyncPlatformSettings();
}
if (secondaryTextureSelected)
{
// trash can button
if (GUILayout.Button(s_Styles.trashIcon, EditorStyles.iconButton, GUILayout.ExpandWidth(false)))
{
EditorGUI.EndEditingActiveTextField();
spriteAtlasImporter.DeleteSecondaryPlatformSettings(m_PlatformSettingsOptions[m_SelectedPlatformSettings]);
m_PlatformSettingsOptions.RemoveAt(m_SelectedPlatformSettings);
m_SelectedPlatformSettings--;
if (m_SelectedPlatformSettings == 1)
m_SelectedPlatformSettings = 0;
SyncPlatformSettings();
}
}
}
EditorGUILayout.EndHorizontal();
// Texture platform settings UI.
EditorGUILayout.BeginHorizontal();
{
EditorGUI.indentLevel++;
GUILayout.Space(EditorGUI.indent);
EditorGUI.indentLevel--;
if (m_SelectedPlatformSettings == 0)
{
GUILayout.Space(EditorGUI.kSpacing);
HandlePlatformSettingUI(null);
}
else
{
EditorGUILayout.BeginVertical();
{
GUILayout.Space(EditorGUI.kSpacing);
string oldSecondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings];
GUI.SetNextControlName(s_Styles.secondaryTextureNameTextControlName);
EditorGUI.BeginChangeCheck();
string textFieldText = EditorGUILayout.DelayedTextField(s_Styles.secondaryTextureNameLabel, oldSecondaryTextureName);
if (EditorGUI.EndChangeCheck() && oldSecondaryTextureName != textFieldText)
{
if (!m_PlatformSettingsOptions.Exists(x => x == textFieldText))
{
m_PlatformSettingsOptions[m_SelectedPlatformSettings] = textFieldText;
RenameSecondaryPlatformSettings(oldSecondaryTextureName, textFieldText);
}
else
{
Debug.LogWarning(s_Styles.nameUniquenessWarning);
EditorGUI.FocusTextInControl(s_Styles.secondaryTextureNameTextControlName);
}
}
string secondaryTextureName = m_PlatformSettingsOptions[m_SelectedPlatformSettings];
EditorGUI.BeginChangeCheck();
bool value = EditorGUILayout.Toggle(s_Styles.sRGBLabel, spriteAtlasImporter.GetSecondaryColorSpace(secondaryTextureName));
if (EditorGUI.EndChangeCheck())
spriteAtlasImporter.SetSecondaryColorSpace(secondaryTextureName, value);
HandlePlatformSettingUI(textFieldText);
}
EditorGUILayout.EndVertical();
}
}
EditorGUILayout.EndHorizontal();
}
private void HandlePlatformSettingUI(string secondaryTextureName)
{
int shownTextureFormatPage = EditorGUILayout.BeginPlatformGrouping(m_ValidPlatforms.ToArray(), styles.defaultPlatformLabel);
var defaultPlatformSettings = m_TempPlatformSettings[TextureImporterInspector.s_DefaultPlatformName];
bool isSecondary = secondaryTextureName != null;
ITexturePlatformSettingsView view = isSecondary ? m_SecondaryTexturePlatformSettingsView : m_TexturePlatformSettingsView;
if (shownTextureFormatPage == -1)
{
if (m_TexturePlatformSettingsController.HandleDefaultSettings(defaultPlatformSettings, view, m_TexturePlatformSettingTextureHelper))
{
for (var i = 0; i < defaultPlatformSettings.Count; ++i)
{
if (isSecondary)
spriteAtlasImporter.SetSecondaryPlatformSettings(defaultPlatformSettings[i], secondaryTextureName);
else
spriteAtlasImporter.SetPlatformSettings(defaultPlatformSettings[i]);
}
}
}
else
{
var buildPlatform = m_ValidPlatforms[shownTextureFormatPage];
var platformSettings = m_TempPlatformSettings[buildPlatform.name];
for (var i = 0; i < platformSettings.Count; ++i)
{
var settings = platformSettings[i];
if (!settings.overridden)
{
if (defaultPlatformSettings[0].format == TextureImporterFormat.Automatic)
{
settings.format = (TextureImporterFormat)spriteAtlasImporter.GetTextureFormat(buildPlatform.defaultTarget);
}
else
{
settings.format = defaultPlatformSettings[0].format;
}
settings.maxTextureSize = defaultPlatformSettings[0].maxTextureSize;
settings.crunchedCompression = defaultPlatformSettings[0].crunchedCompression;
settings.compressionQuality = defaultPlatformSettings[0].compressionQuality;
}
}
m_TexturePlatformSettingsView.buildPlatformTitle = buildPlatform.title.text;
if (m_TexturePlatformSettingsController.HandlePlatformSettings(buildPlatform.defaultTarget, platformSettings, view, m_TexturePlatformSettingTextureHelper))
{
for (var i = 0; i < platformSettings.Count; ++i)
{
if (isSecondary)
spriteAtlasImporter.SetSecondaryPlatformSettings(platformSettings[i], secondaryTextureName);
else
spriteAtlasImporter.SetPlatformSettings(platformSettings[i]);
}
}
}
EditorGUILayout.EndPlatformGrouping();
}
private void HandlePackableListUI()
{
var currentEvent = Event.current;
var usedEvent = false;
Rect rect = EditorGUILayout.GetControlRect();
var controlID = EditorGUIUtility.s_LastControlID;
switch (currentEvent.type)
{
case EventType.DragExited:
if (GUI.enabled)
HandleUtility.Repaint();
break;
case EventType.DragUpdated:
case EventType.DragPerform:
if (rect.Contains(currentEvent.mousePosition) && GUI.enabled)
{
// Check each single object, so we can add multiple objects in a single drag.
var didAcceptDrag = false;
var references = DragAndDrop.objectReferences;
foreach (var obj in references)
{
if (IsPackable(obj))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (currentEvent.type == EventType.DragPerform)
{
m_Packables.AppendFoldoutPPtrValue(obj);
didAcceptDrag = true;
DragAndDrop.activeControlID = 0;
}
else
DragAndDrop.activeControlID = controlID;
}
}
if (didAcceptDrag)
{
GUI.changed = true;
DragAndDrop.AcceptDrag();
usedEvent = true;
}
}
break;
case EventType.ValidateCommand:
if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == styles.packableSelectorHash)
usedEvent = true;
break;
case EventType.ExecuteCommand:
if (currentEvent.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == styles.packableSelectorHash)
{
var obj = ObjectSelector.GetCurrentObject();
if (IsPackable(obj))
{
m_Packables.AppendFoldoutPPtrValue(obj);
m_PackableList.index = m_Packables.arraySize - 1;
}
usedEvent = true;
}
break;
}
// Handle Foldout after we handle the current event because Foldout might process the drag and drop event and used it.
m_PackableListExpanded = EditorGUI.Foldout(rect, m_PackableListExpanded, styles.packableListLabel, true);
if (usedEvent)
currentEvent.Use();
if (m_PackableListExpanded)
{
EditorGUI.indentLevel++;
m_PackableList.DoLayoutList();
EditorGUI.indentLevel--;
}
}
public override void SaveChanges()
{
if (!m_Discard)
base.SaveChanges();
m_ContentHash = GetInspectorHash();
}
public override void DiscardChanges()
{
m_Discard = true;
base.DiscardChanges();
m_ContentHash = GetInspectorHash();
}
void CachePreviewTexture()
{
var spriteAtlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(m_AssetPath);
if (spriteAtlas != null)
{
bool hasPreview = m_PreviewTextures != null && m_PreviewTextures.Length > 0;
if (hasPreview)
{
foreach (var previewTexture in m_PreviewTextures)
hasPreview = previewTexture != null;
}
if (!hasPreview || m_Hash != spriteAtlas.GetHash())
{
m_PreviewTextures = spriteAtlas.GetPreviewTextures();
m_PreviewAlphaTextures = spriteAtlas.GetPreviewAlphaTextures();
m_Hash = spriteAtlas.GetHash();
if (m_PreviewTextures != null
&& m_PreviewTextures.Length > 0
&& m_TotalPages != m_PreviewTextures.Length)
{
m_TotalPages = m_PreviewTextures.Length;
m_OptionDisplays = new string[m_TotalPages];
m_OptionValues = new int[m_TotalPages];
for (int i = 0; i < m_TotalPages; ++i)
{
string texName = m_PreviewTextures[i].name;
var pageNum = SpriteAtlasExtensions.GetPageNumberInAtlas(texName);
var secondaryName = SpriteAtlasExtensions.GetSecondaryTextureNameInAtlas(texName);
m_OptionDisplays[i] = secondaryName == "" ? string.Format("MainTex - Page ({0})", pageNum) : string.Format("{0} - Page ({1})", secondaryName, pageNum);
m_OptionValues[i] = i;
}
}
}
}
}
public override string GetInfoString()
{
if (m_PreviewTextures != null && m_PreviewPage < m_PreviewTextures.Length)
{
Texture2D t = m_PreviewTextures[m_PreviewPage];
GraphicsFormat format = GraphicsFormatUtility.GetFormat(t);
return string.Format("{0}x{1} {2}\n{3}", t.width, t.height, GraphicsFormatUtility.GetFormatString(format), EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySizeLong(t)));
}
return "";
}
public override bool HasPreviewGUI()
{
CachePreviewTexture();
if (m_PreviewTextures != null && m_PreviewTextures.Length > 0)
{
Texture2D t = m_PreviewTextures[0];
return t != null;
}
return false;
}
public override void OnPreviewSettings()
{
// Do not allow changing of pages when multiple atlases is selected.
if (targets.Length == 1 && m_OptionDisplays != null && m_OptionValues != null && m_TotalPages > 1)
m_PreviewPage = EditorGUILayout.IntPopup(m_PreviewPage, m_OptionDisplays, m_OptionValues, styles.preDropDown, GUILayout.MaxWidth(50));
else
m_PreviewPage = 0;
if (m_PreviewTextures != null)
{
m_PreviewPage = Mathf.Min(m_PreviewPage, m_PreviewTextures.Length - 1);
Texture2D t = m_PreviewTextures[m_PreviewPage];
if (t == null)
return;
if (GraphicsFormatUtility.HasAlphaChannel(t.format) || (m_PreviewAlphaTextures != null && m_PreviewAlphaTextures.Length > 0))
m_ShowAlpha = GUILayout.Toggle(m_ShowAlpha, m_ShowAlpha ? styles.alphaIcon : styles.RGBIcon, styles.previewButton);
int mipCount = Mathf.Max(1, TextureUtil.GetMipmapCount(t));
if (mipCount > 1)
{
GUILayout.Box(styles.smallZoom, styles.previewLabel);
m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(m_MipLevel, mipCount - 1, 0, styles.previewSlider, styles.previewSliderThumb, GUILayout.MaxWidth(64)));
GUILayout.Box(styles.largeZoom, styles.previewLabel);
}
}
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
CachePreviewTexture();
if (m_ShowAlpha && m_PreviewAlphaTextures != null && m_PreviewPage < m_PreviewAlphaTextures.Length)
{
var at = m_PreviewAlphaTextures[m_PreviewPage];
var bias = m_MipLevel - (float)(System.Math.Log(at.width / r.width) / System.Math.Log(2));
EditorGUI.DrawTextureTransparent(r, at, ScaleMode.ScaleToFit, 0, bias);
}
else if (m_PreviewTextures != null && m_PreviewPage < m_PreviewTextures.Length)
{
Texture2D t = m_PreviewTextures[m_PreviewPage];
if (t == null)
return;
float bias = m_MipLevel - (float)(System.Math.Log(t.width / r.width) / System.Math.Log(2));
if (m_ShowAlpha)
EditorGUI.DrawTextureAlpha(r, t, ScaleMode.ScaleToFit, 0, bias);
else
EditorGUI.DrawTextureTransparent(r, t, ScaleMode.ScaleToFit, 0, bias);
}
}
}
}
| UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 21056
} | 271 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditorInternal
{
[System.Serializable]
struct AnimationKeyTime
{
[SerializeField] private float m_FrameRate;
[SerializeField] private int m_Frame;
[SerializeField] private float m_Time;
public float time { get { return m_Time; } }
public int frame { get { return m_Frame; } }
public float frameRate { get { return m_FrameRate; } }
/// <summary>
/// A frame has a range of time. This is the beginning of the frame.
/// </summary>
public float frameFloor
{
get
{
return ((float)frame - 0.5f) / frameRate;
}
}
/// <summary>
/// A frame has a range of time. This is the end of the frame.
/// </summary>
public float frameCeiling
{
get
{
return ((float)frame + 0.5f) / frameRate;
}
}
public float timeRound
{
get
{
return (float)frame / frameRate;
}
}
public static AnimationKeyTime Time(float time, float frameRate)
{
AnimationKeyTime key = new AnimationKeyTime();
key.m_Time = Mathf.Max(time, 0f);
key.m_FrameRate = frameRate;
key.m_Frame = UnityEngine.Mathf.RoundToInt(key.m_Time * frameRate);
return key;
}
public static AnimationKeyTime Frame(int frame, float frameRate)
{
AnimationKeyTime key = new AnimationKeyTime();
key.m_Frame = (frame < 0) ? 0 : frame;
key.m_Time = key.m_Frame / frameRate;
key.m_FrameRate = frameRate;
return key;
}
// Check if a time in seconds overlaps with the frame
public bool ContainsTime(float time)
{
return time >= frameFloor && time < frameCeiling;
}
public bool Equals(AnimationKeyTime key)
{
return m_Frame == key.m_Frame &&
m_FrameRate == key.m_FrameRate &&
Mathf.Approximately(m_Time, key.m_Time);
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationKeyTime.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationKeyTime.cs",
"repo_id": "UnityCsReference",
"token_count": 1156
} | 272 |
// 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 Object = UnityEngine.Object;
namespace UnityEditor
{
internal class AnimationWindowManipulator
{
public delegate bool OnStartDragDelegate(AnimationWindowManipulator manipulator, Event evt);
public delegate bool OnDragDelegate(AnimationWindowManipulator manipulator, Event evt);
public delegate bool OnEndDragDelegate(AnimationWindowManipulator manipulator, Event evt);
public OnStartDragDelegate onStartDrag;
public OnDragDelegate onDrag;
public OnEndDragDelegate onEndDrag;
public Rect rect;
public int controlID;
public AnimationWindowManipulator()
{
// NoOps...
onStartDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; };
onDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; };
onEndDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; };
}
public virtual void HandleEvents()
{
controlID = GUIUtility.GetControlID(FocusType.Passive);
Event evt = Event.current;
EventType eventType = evt.GetTypeForControl(controlID);
bool handled = false;
switch (eventType)
{
case EventType.MouseDown:
if (evt.button == 0)
{
handled = onStartDrag(this, evt);
if (handled)
GUIUtility.hotControl = controlID;
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == controlID)
{
handled = onDrag(this, evt);
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == controlID)
{
handled = onEndDrag(this, evt);
GUIUtility.hotControl = 0;
}
break;
}
if (handled)
evt.Use();
}
public virtual void IgnoreEvents()
{
GUIUtility.GetControlID(FocusType.Passive);
}
}
internal class AreaManipulator : AnimationWindowManipulator
{
private GUIStyle m_Style;
private MouseCursor m_Cursor;
public AreaManipulator(GUIStyle style, MouseCursor cursor)
{
m_Style = style;
m_Cursor = cursor;
}
public AreaManipulator(GUIStyle style)
{
m_Style = style;
m_Cursor = MouseCursor.Arrow;
}
public void OnGUI(Rect widgetRect)
{
if (m_Style == null)
return;
rect = widgetRect;
if (Mathf.Approximately(widgetRect.width * widgetRect.height, 0f))
return;
GUI.Label(widgetRect, GUIContent.none, m_Style);
if (GUIUtility.hotControl == 0 && m_Cursor != MouseCursor.Arrow)
{
EditorGUIUtility.AddCursorRect(widgetRect, m_Cursor);
}
else if (GUIUtility.hotControl == controlID)
{
Vector2 mousePosition = Event.current.mousePosition;
EditorGUIUtility.AddCursorRect(new Rect(mousePosition.x - 10, mousePosition.y - 10, 20, 20), m_Cursor);
}
}
}
internal class TimeCursorManipulator : AnimationWindowManipulator
{
public enum Alignment
{
Center,
Left,
Right
}
public Alignment alignment;
public Color headColor;
public Color lineColor;
public bool dottedLine;
public bool drawLine;
public bool drawHead;
public string tooltip;
private GUIStyle m_Style;
public TimeCursorManipulator(GUIStyle style)
{
m_Style = style;
dottedLine = false;
headColor = Color.white;
lineColor = style.normal.textColor;
drawLine = true;
drawHead = true;
tooltip = string.Empty;
alignment = Alignment.Center;
}
public void OnGUI(Rect windowRect, float pixelTime)
{
float widgetWidth = m_Style.fixedWidth;
float widgetHeight = m_Style.fixedHeight;
Vector2 windowCoordinate = new Vector2(pixelTime, windowRect.yMin);
switch (alignment)
{
case Alignment.Center:
rect = new Rect((windowCoordinate.x - widgetWidth / 2.0f), windowCoordinate.y, widgetWidth, widgetHeight);
break;
case Alignment.Left:
rect = new Rect(windowCoordinate.x - widgetWidth, windowCoordinate.y, widgetWidth, widgetHeight);
break;
case Alignment.Right:
rect = new Rect(windowCoordinate.x, windowCoordinate.y, widgetWidth, widgetHeight);
break;
}
Vector3 p1 = new Vector3(windowCoordinate.x, windowCoordinate.y + widgetHeight, 0.0f);
Vector3 p2 = new Vector3(windowCoordinate.x, windowRect.height, 0.0f);
if (drawLine)
{
Handles.color = lineColor;
if (dottedLine)
Handles.DrawDottedLine(p1, p2, 5.0f);
else
Handles.DrawLine(p1, p2);
}
if (drawHead)
{
Color c = GUI.color;
GUI.color = headColor;
GUI.Box(rect, GUIContent.none, m_Style);
GUI.color = c;
}
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowManipulator.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowManipulator.cs",
"repo_id": "UnityCsReference",
"token_count": 3090
} | 273 |
// 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 System.Collections;
using System.Collections.Generic;
namespace UnityEditor
{
internal class EulerCurveCombinedRenderer
{
const int kSegmentResolution = 40;
const float epsilon = 0.001f;
private AnimationCurve quaternionX;
private AnimationCurve quaternionY;
private AnimationCurve quaternionZ;
private AnimationCurve quaternionW;
private AnimationCurve eulerX;
private AnimationCurve eulerY;
private AnimationCurve eulerZ;
private SortedDictionary<float, Vector3> points;
private float cachedEvaluationTime = Mathf.Infinity;
private Vector3 cachedEvaluationValue;
private float cachedRangeStart = Mathf.Infinity;
private float cachedRangeEnd = Mathf.NegativeInfinity;
private Vector3 refEuler;
private float m_CustomRangeStart = 0;
private float m_CustomRangeEnd = 0;
private float rangeStart { get { return (m_CustomRangeStart == 0 && m_CustomRangeEnd == 0 && eulerX.length > 0 ? eulerX.keys[0].time : m_CustomRangeStart); } }
private float rangeEnd { get { return (m_CustomRangeStart == 0 && m_CustomRangeEnd == 0 && eulerX.length > 0 ? eulerX.keys[eulerX.length - 1].time : m_CustomRangeEnd); } }
private WrapMode preWrapMode = WrapMode.Once;
private WrapMode postWrapMode = WrapMode.Once;
public EulerCurveCombinedRenderer(
AnimationCurve quaternionX,
AnimationCurve quaternionY,
AnimationCurve quaternionZ,
AnimationCurve quaternionW,
AnimationCurve eulerX,
AnimationCurve eulerY,
AnimationCurve eulerZ
)
{
this.quaternionX = (quaternionX == null ? new AnimationCurve() : quaternionX);
this.quaternionY = (quaternionY == null ? new AnimationCurve() : quaternionY);
this.quaternionZ = (quaternionZ == null ? new AnimationCurve() : quaternionZ);
this.quaternionW = (quaternionW == null ? new AnimationCurve() : quaternionW);
this.eulerX = (eulerX == null ? new AnimationCurve() : eulerX);
this.eulerY = (eulerY == null ? new AnimationCurve() : eulerY);
this.eulerZ = (eulerZ == null ? new AnimationCurve() : eulerZ);
}
public AnimationCurve GetCurveOfComponent(int component)
{
switch (component)
{
case 0: return eulerX;
case 1: return eulerY;
case 2: return eulerZ;
default: return null;
}
}
public float RangeStart() { return rangeStart; }
public float RangeEnd() { return rangeEnd; }
public WrapMode PreWrapMode() { return preWrapMode; }
public WrapMode PostWrapMode() { return postWrapMode; }
public void SetWrap(WrapMode wrap)
{
preWrapMode = wrap;
postWrapMode = wrap;
}
public void SetWrap(WrapMode preWrap, WrapMode postWrap)
{
preWrapMode = preWrap;
postWrapMode = postWrap;
}
public void SetCustomRange(float start, float end)
{
m_CustomRangeStart = start;
m_CustomRangeEnd = end;
}
private Vector3 GetValues(float time, bool keyReference)
{
if (quaternionX == null) Debug.LogError("X curve is null!");
if (quaternionY == null) Debug.LogError("Y curve is null!");
if (quaternionZ == null) Debug.LogError("Z curve is null!");
if (quaternionW == null) Debug.LogError("W curve is null!");
Quaternion q;
if (quaternionX.length != 0 &&
quaternionY.length != 0 &&
quaternionZ.length != 0 &&
quaternionW.length != 0)
{
q = EvaluateQuaternionCurvesDirectly(time);
if (keyReference)
refEuler = EvaluateEulerCurvesDirectly(time);
refEuler = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(q, refEuler);
}
else //euler curves only
{
refEuler = EvaluateEulerCurvesDirectly(time);
}
return refEuler;
}
private Quaternion EvaluateQuaternionCurvesDirectly(float time)
{
return new Quaternion(
quaternionX.Evaluate(time),
quaternionY.Evaluate(time),
quaternionZ.Evaluate(time),
quaternionW.Evaluate(time));
}
private Vector3 EvaluateEulerCurvesDirectly(float time)
{
return new Vector3(
eulerX.Evaluate(time),
eulerY.Evaluate(time),
eulerZ.Evaluate(time));
}
private void CalculateCurves(float minTime, float maxTime)
{
points = new SortedDictionary<float, Vector3>();
float[,] ranges = NormalCurveRenderer.CalculateRanges(minTime, maxTime, rangeStart, rangeEnd, preWrapMode, postWrapMode);
for (int i = 0; i < ranges.GetLength(0); i++)
AddPoints(ranges[i, 0], ranges[i, 1]);
}
private void AddPoints(float minTime, float maxTime)
{
AnimationCurve refCurve = quaternionX;
if (refCurve.length == 0)
{
refCurve = eulerX;
}
if (refCurve.length == 0)
return;
if (refCurve[0].time >= minTime)
{
Vector3 val = GetValues(refCurve[0].time, true);
points[rangeStart] = val;
points[refCurve[0].time] = val;
}
if (refCurve[refCurve.length - 1].time <= maxTime)
{
Vector3 val = GetValues(refCurve[refCurve.length - 1].time, true);
points[refCurve[refCurve.length - 1].time] = val;
points[rangeEnd] = val;
}
for (int i = 0; i < refCurve.length - 1; i++)
{
// Ignore segments that are outside of the range from minTime to maxTime
if (refCurve[i + 1].time < minTime || refCurve[i].time > maxTime)
continue;
// Get first value from euler curve and move forwards
float newTime = refCurve[i].time;
points[newTime] = GetValues(newTime, true);
// Iterate forwards through curve segments
for (float j = 1; j <= kSegmentResolution / 2; j++)
{
newTime = Mathf.Lerp(refCurve[i].time, refCurve[i + 1].time, (j - 0.001f) / kSegmentResolution);
points[newTime] = GetValues(newTime, false);
}
// Get last value from euler curve and move backwards
newTime = refCurve[i + 1].time;
points[newTime] = GetValues(newTime, true);
// Iterate backwards through curve segment
for (float j = 1; j <= kSegmentResolution / 2; j++)
{
newTime = Mathf.Lerp(refCurve[i].time, refCurve[i + 1].time, 1 - (j - 0.001f) / kSegmentResolution);
points[newTime] = GetValues(newTime, false);
}
}
}
public float EvaluateCurveDeltaSlow(float time, int component)
{
if (quaternionX == null)
return 0;
return (EvaluateCurveSlow(time + epsilon, component) - EvaluateCurveSlow(time - epsilon, component)) / (epsilon * 2);
}
public float EvaluateCurveSlow(float time, int component)
{
if (GetCurveOfComponent(component).length == 1)
{
return GetCurveOfComponent(component)[0].value;
}
if (time == cachedEvaluationTime)
return cachedEvaluationValue[component];
if (time < cachedRangeStart || time > cachedRangeEnd)
{
// if an evaluate call is outside of cached range we might as well calculate whole range
CalculateCurves(rangeStart, rangeEnd);
cachedRangeStart = Mathf.NegativeInfinity;
cachedRangeEnd = Mathf.Infinity;
}
float[] times = new float[points.Count];
Vector3[] values = new Vector3[points.Count];
int c = 0;
foreach (KeyValuePair<float, Vector3> kvp in points)
{
times[c] = kvp.Key;
values[c] = kvp.Value;
c++;
}
for (int i = 0; i < times.Length - 1; i++)
{
if (time < times[i + 1])
{
float lerp = Mathf.InverseLerp(times[i], times[i + 1], time);
cachedEvaluationValue = Vector3.Lerp(values[i], values[i + 1], lerp);
cachedEvaluationTime = time;
return cachedEvaluationValue[component];
}
}
if (values.Length > 0)
return values[values.Length - 1][component];
Debug.LogError("List of euler curve points is empty, probably caused by lack of euler curve key synching");
return 0;
}
public void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, int component, Color wrapColor)
{
if (minTime < cachedRangeStart || maxTime > cachedRangeEnd)
{
CalculateCurves(minTime, maxTime);
if (minTime <= rangeStart && maxTime >= rangeEnd)
{
// if we are covering whole range
cachedRangeStart = Mathf.NegativeInfinity;
cachedRangeEnd = Mathf.Infinity;
}
else
{
cachedRangeStart = minTime;
cachedRangeEnd = maxTime;
}
}
List<Vector3> polyLine = new List<Vector3>();
foreach (KeyValuePair<float, Vector3> kvp in points)
{
polyLine.Add(new Vector3(kvp.Key, kvp.Value[component]));
}
NormalCurveRenderer.DrawCurveWrapped(minTime, maxTime, rangeStart, rangeEnd, preWrapMode, postWrapMode, color, transform, polyLine.ToArray(), wrapColor);
}
public Bounds GetBounds(float minTime, float maxTime, int component)
{
//if (alreadyDrawn[component])
//{
CalculateCurves(minTime, maxTime);
// for (int i=0; i<alreadyDrawn.Length; i++) alreadyDrawn[i] = false;
//}
//alreadyDrawn[component] = true;
float min = Mathf.Infinity;
float max = Mathf.NegativeInfinity;
foreach (KeyValuePair<float, Vector3> kvp in points)
{
if (kvp.Value[component] > max)
max = kvp.Value[component];
if (kvp.Value[component] < min)
min = kvp.Value[component];
}
if (min == Mathf.Infinity)
{
min = 0;
max = 0;
}
return new Bounds(new Vector3((maxTime + minTime) * 0.5f, (max + min) * 0.5f, 0), new Vector3(maxTime - minTime, max - min, 0));
}
}
} // namespace
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/EulerCurveCombinedRenderer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/EulerCurveCombinedRenderer.cs",
"repo_id": "UnityCsReference",
"token_count": 5858
} | 274 |
// 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 RectangleTool
{
private TimeArea m_TimeArea;
private Styles m_Styles;
internal enum ToolCoord
{
BottomLeft,
Bottom,
BottomRight,
Left,
Center,
Right,
TopLeft,
Top,
TopRight
}
internal class Styles
{
public GUIStyle rectangleToolHBarLeft = "RectangleToolHBarLeft";
public GUIStyle rectangleToolHBarRight = "RectangleToolHBarRight";
public GUIStyle rectangleToolHBar = "RectangleToolHBar";
public GUIStyle rectangleToolVBarBottom = "RectangleToolVBarBottom";
public GUIStyle rectangleToolVBarTop = "RectangleToolVBarTop";
public GUIStyle rectangleToolVBar = "RectangleToolVBar";
public GUIStyle rectangleToolSelection = "RectangleToolSelection";
public GUIStyle rectangleToolHighlight = "RectangleToolHighlight";
public GUIStyle rectangleToolScaleLeft = "RectangleToolScaleLeft";
public GUIStyle rectangleToolScaleRight = "RectangleToolScaleRight";
public GUIStyle rectangleToolScaleBottom = "RectangleToolScaleBottom";
public GUIStyle rectangleToolScaleTop = "RectangleToolScaleTop";
public GUIStyle rectangleToolRippleLeft = "RectangleToolRippleLeft";
public GUIStyle rectangleToolRippleRight = "RectangleToolRippleRight";
public GUIStyle dopesheetScaleLeft = "DopesheetScaleLeft";
public GUIStyle dopesheetScaleRight = "DopesheetScaleRight";
public GUIStyle dopesheetRippleLeft = "DopesheetRippleLeft";
public GUIStyle dopesheetRippleRight = "DopesheetRippleRight";
public GUIStyle dragLabel = "ProfilerBadge";
}
public TimeArea timeArea { get { return m_TimeArea; } }
public Styles styles { get { return m_Styles; } }
public Rect contentRect
{
get
{
return new Rect(0, 0, m_TimeArea.drawRect.width, m_TimeArea.drawRect.height);
}
}
public virtual void Initialize(TimeArea timeArea)
{
m_TimeArea = timeArea;
if (m_Styles == null)
m_Styles = new Styles();
}
public Vector2 ToolCoordToPosition(ToolCoord coord, Bounds bounds)
{
switch (coord)
{
case ToolCoord.BottomLeft:
return bounds.min;
case ToolCoord.Bottom:
return new Vector2(bounds.center.x, bounds.min.y);
case ToolCoord.BottomRight:
return new Vector2(bounds.max.x, bounds.min.y);
case ToolCoord.Left:
return new Vector2(bounds.min.x, bounds.center.y);
case ToolCoord.Center:
return bounds.center;
case ToolCoord.Right:
return new Vector2(bounds.max.x, bounds.center.y);
case ToolCoord.TopLeft:
return new Vector2(bounds.min.x, bounds.max.y);
case ToolCoord.Top:
return new Vector2(bounds.center.x, bounds.max.y);
case ToolCoord.TopRight:
return bounds.max;
}
return Vector2.zero;
}
public bool CalculateScaleTimeMatrix(float fromTime, float toTime, float offsetTime, float pivotTime, float frameRate, out Matrix4x4 transform, out bool flipKeys)
{
transform = Matrix4x4.identity;
flipKeys = false;
float thresholdTime = (Mathf.Approximately(frameRate, 0f)) ? 0.001f : 1f / frameRate;
float dtNum = toTime - pivotTime;
float dtDenum = fromTime - pivotTime;
// Scale handle overlaps pivot, discard operation.
if ((Mathf.Abs(dtNum) - Mathf.Abs(offsetTime)) < 0f)
return false;
dtNum = (Mathf.Sign(dtNum) == Mathf.Sign(dtDenum)) ? dtNum - offsetTime : dtNum + offsetTime;
if (Mathf.Approximately(dtDenum, 0f))
{
transform.SetTRS(new Vector3(dtNum, 0f, 0f), Quaternion.identity, Vector3.one);
flipKeys = false;
return true;
}
if (Mathf.Abs(dtNum) < thresholdTime)
dtNum = (dtNum < 0f) ? -thresholdTime : thresholdTime;
float scaleTime = dtNum / dtDenum;
transform.SetTRS(new Vector3(pivotTime, 0f, 0f), Quaternion.identity, Vector3.one);
transform = transform * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(scaleTime, 1f, 1f));
transform = transform * Matrix4x4.TRS(new Vector3(-pivotTime, 0f), Quaternion.identity, Vector3.one);
flipKeys = scaleTime < 0f;
return true;
}
public bool CalculateScaleValueMatrix(float fromValue, float toValue, float offsetValue, float pivotValue, out Matrix4x4 transform, out bool flipKeys)
{
transform = Matrix4x4.identity;
flipKeys = false;
float thresholdValue = 0.001f;
float dvNum = toValue - pivotValue;
float dvDenum = fromValue - pivotValue;
// Scale handle overlaps pivot, discard operation.
if ((Mathf.Abs(dvNum) - Mathf.Abs(offsetValue)) < 0f)
return false;
dvNum = (Mathf.Sign(dvNum) == Mathf.Sign(dvDenum)) ? dvNum - offsetValue : dvNum + offsetValue;
if (Mathf.Approximately(dvDenum, 0f))
{
transform.SetTRS(new Vector3(0f, dvNum, 0f), Quaternion.identity, Vector3.one);
flipKeys = false;
return true;
}
if (Mathf.Abs(dvNum) < thresholdValue)
dvNum = (dvNum < 0f) ? -thresholdValue : thresholdValue;
float scaleValue = dvNum / dvDenum;
transform.SetTRS(new Vector3(0f, pivotValue, 0f), Quaternion.identity, Vector3.one);
transform = transform * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1f, scaleValue, 1f));
transform = transform * Matrix4x4.TRS(new Vector3(0f, -pivotValue, 0f), Quaternion.identity, Vector3.one);
flipKeys = scaleValue < 0f;
return true;
}
public float PixelToTime(float pixelTime, float frameRate)
{
float width = contentRect.width;
float visibleTimeSpan = m_TimeArea.shownArea.xMax - m_TimeArea.shownArea.xMin;
float minVisibleTime = m_TimeArea.shownArea.xMin;
float time = ((pixelTime / width) * visibleTimeSpan + minVisibleTime);
if (frameRate != 0f)
time = Mathf.Round(time * frameRate) / frameRate;
return time;
}
public float PixelToValue(float pixelValue)
{
float height = contentRect.height;
float pixelPerValue = m_TimeArea.m_Scale.y * -1f;
float zeroValuePixel = m_TimeArea.shownArea.yMin * pixelPerValue * -1f;
float value = (height - pixelValue - zeroValuePixel) / pixelPerValue;
return value;
}
public float TimeToPixel(float time)
{
float width = contentRect.width;
float visibleTimeSpan = m_TimeArea.shownArea.xMax - m_TimeArea.shownArea.xMin;
float minVisibleTime = m_TimeArea.shownArea.xMin;
float pixelTime = (time - minVisibleTime) * width / visibleTimeSpan;
return pixelTime;
}
public float ValueToPixel(float value)
{
float height = contentRect.height;
float pixelPerValue = m_TimeArea.m_Scale.y * -1f;
float zeroValuePixel = m_TimeArea.shownArea.yMin * pixelPerValue * -1f;
float pixelValue = height - (value * pixelPerValue + zeroValuePixel);
return pixelValue;
}
}
}
| UnityCsReference/Editor/Mono/Animation/AnimationWindow/RectangleTool.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/RectangleTool.cs",
"repo_id": "UnityCsReference",
"token_count": 3918
} | 275 |
// 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.Playables;
using UnityEngine.Animations;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngineInternal;
using UnityEditor;
using System.Runtime.InteropServices;
namespace UnityEditor.Animations
{
[NativeHeader("Modules/Animation/Animator.h")]
[NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")]
[NativeHeader("Editor/Src/Animation/AnimatorController.bindings.h")]
[NativeHeader("Modules/Animation/AnimatorController.h")]
public partial class AnimatorController : RuntimeAnimatorController
{
public AnimatorController()
{
Internal_Create(this);
}
[FreeFunction("AnimatorControllerBindings::Internal_Create")]
extern private static void Internal_Create([Writable] AnimatorController self);
extern public AnimatorControllerLayer[] layers
{
[FreeFunction(Name = "AnimatorControllerBindings::GetLayers", HasExplicitThis = true)]
get;
[FreeFunction(Name = "AnimatorControllerBindings::SetLayers", HasExplicitThis = true, ThrowsException = true)]
[param: Unmarshalled]
set;
}
extern public AnimatorControllerParameter[] parameters
{
[FreeFunction(Name = "AnimatorControllerBindings::GetParameters", HasExplicitThis = true)]
get;
[FreeFunction(Name = "AnimatorControllerBindings::SetParameters", HasExplicitThis = true, ThrowsException = true)]
[param: Unmarshalled]
set;
}
[FreeFunction(Name = "AnimatorControllerBindings::GetEffectiveAnimatorController")]
extern internal static AnimatorController GetEffectiveAnimatorController(Animator animator);
internal static AnimatorControllerPlayable FindAnimatorControllerPlayable(Animator animator, AnimatorController controller)
{
PlayableHandle handle = new PlayableHandle();
Internal_FindAnimatorControllerPlayable(ref handle, animator, controller);
if (!handle.IsValid())
return AnimatorControllerPlayable.Null;
return new AnimatorControllerPlayable(handle);
}
[FreeFunction(Name = "AnimatorControllerBindings::Internal_FindAnimatorControllerPlayable")]
extern internal static void Internal_FindAnimatorControllerPlayable(ref PlayableHandle ret, Animator animator, AnimatorController controller);
public static void SetAnimatorController(Animator animator, AnimatorController controller)
{
animator.runtimeAnimatorController = controller;
}
extern internal int IndexOfParameter(string name);
extern internal void RenameParameter(string prevName, string newName);
extern public string MakeUniqueParameterName(string name);
extern public string MakeUniqueLayerName(string name);
static public StateMachineBehaviourContext[] FindStateMachineBehaviourContext(StateMachineBehaviour behaviour)
{
return Internal_FindStateMachineBehaviourContext(behaviour);
}
[FreeFunction("FindStateMachineBehaviourContext")]
extern internal static StateMachineBehaviourContext[] Internal_FindStateMachineBehaviourContext(ScriptableObject behaviour);
[FreeFunction("AnimatorControllerBindings::Internal_CreateStateMachineBehaviour")]
extern public static int CreateStateMachineBehaviour(MonoScript script);
[FreeFunction("AnimatorControllerBindings::CanAddStateMachineBehaviours")]
extern internal static bool CanAddStateMachineBehaviours();
extern internal MonoScript GetBehaviourMonoScript(AnimatorState state, int layerIndex, int behaviourIndex);
[FreeFunction]
extern private static ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType, [NotNull] AnimatorController controller, [NotNull] AnimatorState state, int layerIndex);
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public StateMachineBehaviour AddEffectiveStateMachineBehaviour(Type stateMachineBehaviourType, AnimatorState state, int layerIndex)
{
return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType, this, state, layerIndex);
}
public T AddEffectiveStateMachineBehaviour<T>(AnimatorState state, int layerIndex) where T : StateMachineBehaviour
{
return AddEffectiveStateMachineBehaviour(typeof(T), state, layerIndex) as T;
}
public T[] GetBehaviours<T>() where T : StateMachineBehaviour
{
return ConvertStateMachineBehaviour<T>(InternalGetBehaviours(typeof(T)));
}
[FreeFunction(Name = "AnimatorControllerBindings::Internal_GetBehaviours", HasExplicitThis = true)]
extern internal ScriptableObject[] InternalGetBehaviours([NotNull] Type type);
internal static T[] ConvertStateMachineBehaviour<T>(ScriptableObject[] rawObjects) where T : StateMachineBehaviour
{
if (rawObjects == null) return null;
T[] typedObjects = new T[rawObjects.Length];
for (int i = 0; i < typedObjects.Length; i++)
typedObjects[i] = (T)rawObjects[i];
return typedObjects;
}
extern internal UnityEngine.Object[] CollectObjectsUsingParameter(string parameterName);
internal extern bool isAssetBundled
{
[NativeName("IsAssetBundled")]
get;
}
extern internal void AddStateEffectiveBehaviour([NotNull] AnimatorState state, int layerIndex, int instanceID);
extern internal void RemoveStateEffectiveBehaviour([NotNull] AnimatorState state, int layerIndex, int behaviourIndex);
[FreeFunction(Name = "AnimatorControllerBindings::Internal_GetEffectiveBehaviours", HasExplicitThis = true)]
extern internal ScriptableObject[] Internal_GetEffectiveBehaviours([NotNull] AnimatorState state, int layerIndex);
[FreeFunction(Name = "AnimatorControllerBindings::Internal_SetEffectiveBehaviours", HasExplicitThis = true)]
extern internal void Internal_SetEffectiveBehaviours([NotNull] AnimatorState state, int layerIndex, [Unmarshalled] ScriptableObject[] behaviours);
}
}
| UnityCsReference/Editor/Mono/AnimatorController.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AnimatorController.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2263
} | 276 |
// 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.Runtime.InteropServices;
using UnityEngine;
using UnityEditor.AssetImporters;
using UnityEngine.Bindings;
namespace UnityEditor
{
partial class AssetDatabase
{
// Gets the path to the text .meta file associated with an asset
[Obsolete("GetTextMetaDataPathFromAssetPath has been renamed to GetTextMetaFilePathFromAssetPath (UnityUpgradable) -> GetTextMetaFilePathFromAssetPath(*)",true)]
public static string GetTextMetaDataPathFromAssetPath(string path) { return null; }
}
// Used to be part of Asset Server, and public API for some reason.
[Obsolete("AssetStatus enum is not used anymore (Asset Server has been removed)",true)]
public enum AssetStatus
{
Calculating = -1,
ClientOnly = 0,
ServerOnly = 1,
Unchanged = 2,
Conflict = 3,
Same = 4,
NewVersionAvailable = 5,
NewLocalVersion = 6,
RestoredFromTrash = 7,
Ignored = 8,
BadState = 9
}
// Used to be part of Asset Server, and public API for some reason.
[Obsolete("AssetsItem class is not used anymore (Asset Server has been removed)",true)]
[StructLayout(LayoutKind.Sequential)]
[System.Serializable]
public sealed class AssetsItem
{
public string guid;
public string pathName;
public string message;
public string exportedAssetPath;
public string guidFolder;
public int enabled;
public int assetIsDir;
public int changeFlags;
public string previewPath;
public int exists;
}
}
namespace UnityEditor.Experimental
{
public partial class AssetDatabaseExperimental
{
[FreeFunction("AssetDatabase::ClearImporterOverride")]
[Obsolete("AssetDatabaseExperimental.ClearImporterOverride() has been deprecated. Use AssetDatabase.ClearImporterOverride() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.ClearImporterOverride(*)", true)]
extern public static void ClearImporterOverride(string path);
[FreeFunction("AssetDatabase::IsCacheServerEnabled")]
[Obsolete("AssetDatabaseExperimental.IsCacheServerEnabled() has been deprecated. Use AssetDatabase.IsCacheServerEnabled() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.IsCacheServerEnabled(*)", true)]
public extern static bool IsCacheServerEnabled();
[Obsolete("AssetDatabaseExperimental.SetImporterOverride<T>() has been deprecated. Use AssetDatabase.SetImporterOverride<T>() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.SetImporterOverride<T>(*)", true)]
public static void SetImporterOverride<T>(string path)
where T : ScriptedImporter
{
AssetDatabase.SetImporterOverrideInternal(path, typeof(T));
}
[FreeFunction("AssetDatabase::GetImporterOverride")]
[Obsolete("AssetDatabaseExperimental.GetImporterOverride() has been deprecated. Use AssetDatabase.GetImporterOverride() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetImporterOverride(*)", true)]
extern public static System.Type GetImporterOverride(string path);
[FreeFunction("AssetDatabase::GetAvailableImporters")]
[Obsolete("AssetDatabaseExperimental.GetAvailableImporterTypes() has been deprecated. Use AssetDatabase.GetAvailableImporters() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetAvailableImporters(*)", true)]
extern public static Type[] GetAvailableImporterTypes(string path);
[FreeFunction("AcceleratorClientCanConnectTo")]
[Obsolete("AssetDatabaseExperimental.CanConnectToCacheServer() has been deprecated. Use AssetDatabase.CanConnectToCacheServer() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.CanConnectToCacheServer(*)", true)]
public extern static bool CanConnectToCacheServer(string ip, UInt16 port);
[FreeFunction()]
[Obsolete("AssetDatabaseExperimental.RefreshSettings() has been deprecated. Use AssetDatabase.RefreshSettings() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.RefreshSettings(*)", true)]
public extern static void RefreshSettings();
[Obsolete("AssetDatabaseExperimental.CacheServerConnectionChangedParameters has been deprecated. Use UnityEditor.CacheServerConnectionChangedParameters instead (UnityUpgradable) -> UnityEditor.CacheServerConnectionChangedParameters", true)]
public struct CacheServerConnectionChangedParameters
{
}
#pragma warning disable 67
[Obsolete("AssetDatabaseExperimental.cacheServerConnectionChanged has been deprecated. Use AssetDatabase.cacheServerConnectionChanged instead (UnityUpgradable) -> UnityEditor.AssetDatabase.cacheServerConnectionChanged", true)]
public static event Action<CacheServerConnectionChangedParameters> cacheServerConnectionChanged;
#pragma warning restore 67
[FreeFunction("AcceleratorClientIsConnected")]
[Obsolete("AssetDatabaseExperimental.IsConnectedToCacheServer() has been deprecated. Use AssetDatabase.IsConnectedToCacheServer() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.IsConnectedToCacheServer(*)", true)]
public extern static bool IsConnectedToCacheServer();
[FreeFunction()]
[Obsolete("AssetDatabaseExperimental.GetCacheServerAddress() has been deprecated. Use AssetDatabase.GetCacheServerAddress() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetCacheServerAddress(*)", true)]
public extern static string GetCacheServerAddress();
[FreeFunction()]
[Obsolete("AssetDatabaseExperimental.GetCacheServerPort() has been deprecated. Use AssetDatabase.GetCacheServerPort() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetCacheServerPort(*)", true)]
public extern static UInt16 GetCacheServerPort();
[FreeFunction("AssetDatabase::GetCacheServerNamespacePrefix")]
[Obsolete("AssetDatabaseExperimental.GetCacheServerNamespacePrefix() has been deprecated. Use AssetDatabase.GetCacheServerNamespacePrefix() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetCacheServerNamespacePrefix(*)", true)]
public extern static string GetCacheServerNamespacePrefix();
[FreeFunction("AssetDatabase::GetCacheServerEnableDownload")]
[Obsolete("AssetDatabaseExperimental.GetCacheServerEnableDownload() has been deprecated. Use AssetDatabase.GetCacheServerEnableDownload() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetCacheServerEnableDownload(*)", true)]
public extern static bool GetCacheServerEnableDownload();
[FreeFunction("AssetDatabase::GetCacheServerEnableUpload")]
[Obsolete("AssetDatabaseExperimental.GetCacheServerEnableUpload() has been deprecated. Use AssetDatabase.GetCacheServerEnableUpload() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.GetCacheServerEnableUpload(*)", true)]
public extern static bool GetCacheServerEnableUpload();
[FreeFunction("AssetDatabase::IsDirectoryMonitoringEnabled")]
[Obsolete("AssetDatabaseExperimental.IsDirectoryMonitoringEnabled() has been deprecated. Use AssetDatabase.IsDirectoryMonitoringEnabled() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.IsDirectoryMonitoringEnabled(*)", true)]
public extern static bool IsDirectoryMonitoringEnabled();
[FreeFunction("AssetDatabaseExperimental::RegisterCustomDependency")]
[PreventExecutionInState(AssetDatabasePreventExecution.kPreventCustomDependencyChanges, PreventExecutionSeverity.PreventExecution_ManagedException, "Custom dependencies can only be removed when the assetdatabase is not importing.")]
[Obsolete("AssetDatabaseExperimental.RegisterCustomDependency() has been deprecated. Use AssetDatabase.RegisterCustomDependency() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.RegisterCustomDependency(*)", true)]
public extern static void RegisterCustomDependency(string dependency, Hash128 hashOfValue);
[FreeFunction("AssetDatabaseExperimental::UnregisterCustomDependencyPrefixFilter")]
[PreventExecutionInState(AssetDatabasePreventExecution.kPreventCustomDependencyChanges, PreventExecutionSeverity.PreventExecution_ManagedException, "Custom dependencies can only be removed when the assetdatabase is not importing.")]
[Obsolete("AssetDatabaseExperimental.UnregisterCustomDependencyPrefixFilter() has been deprecated. Use AssetDatabase.UnregisterCustomDependencyPrefixFilter() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.UnregisterCustomDependencyPrefixFilter(*)", true)]
public extern static UInt32 UnregisterCustomDependencyPrefixFilter(string prefixFilter);
[FreeFunction("AssetDatabase::IsAssetImportProcess")]
[Obsolete("AssetDatabaseExperimental.IsAssetImportWorkerProcess() has been deprecated. Use AssetDatabase.IsAssetImportWorkerProcess() instead (UnityUpgradable) -> UnityEditor.AssetDatabase.IsAssetImportWorkerProcess(*)", true)]
public extern static bool IsAssetImportWorkerProcess();
}
}
| UnityCsReference/Editor/Mono/AssetDatabase/AssetDatabase.deprecated.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetDatabase/AssetDatabase.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 2781
} | 277 |
// 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;
namespace UnityEditor
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("DDSImporter is obsolete. Use IHVImageFormatImporter instead (UnityUpgradable) -> IHVImageFormatImporter", true)]
[NativeClass(null)]
public sealed class DDSImporter : AssetImporter
{
public bool isReadable { get {return false; } set {} }
}
[NativeHeader("Editor/Src/AssetPipeline/TextureImporting/IHVImageFormatImporter.h")]
public sealed class IHVImageFormatImporter : AssetImporter
{
public extern bool isReadable
{
get;
set;
}
public extern FilterMode filterMode
{
get;
set;
}
// note: wrapMode getter returns U wrapping axis
public extern TextureWrapMode wrapMode
{
[NativeName("GetWrapU")]
get;
[NativeName("SetWrapUVW")]
set;
}
[NativeName("WrapU")]
public extern TextureWrapMode wrapModeU
{
get;
set;
}
[NativeName("WrapV")]
public extern TextureWrapMode wrapModeV
{
get;
set;
}
[NativeName("WrapW")]
public extern TextureWrapMode wrapModeW
{
get;
set;
}
[NativeConditional("ENABLE_TEXTURE_STREAMING")]
public extern bool streamingMipmaps
{
get;
set;
}
[NativeConditional("ENABLE_TEXTURE_STREAMING")]
public extern int streamingMipmapsPriority
{
get;
set;
}
public extern bool ignoreMipmapLimit
{
get;
set;
}
public extern string mipmapLimitGroupName
{
get;
set;
}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/IHVImageFormatImporter.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/IHVImageFormatImporter.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1051
} | 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.IO;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Rendering;
namespace UnityEditor
{
[NativeHeader("Editor/Src/AssetPipeline/SpeedTreeImporter.h")]
[NativeHeader("Editor/Src/AssetPipeline/SpeedTreeImporter.bindings.h")]
[NativeHeader("Runtime/Camera/ReflectionProbeTypes.h")]
public partial class SpeedTreeImporter : AssetImporter
{
public enum MaterialLocation
{
External = 0,
InPrefab = 1
}
public extern bool hasImported
{
[FreeFunction(Name = "SpeedTreeImporterBindings::HasImported", HasExplicitThis = true)]
get;
}
public extern string materialFolderPath
{
get;
}
public extern MaterialLocation materialLocation
{
get;
set;
}
public extern bool isV8
{
get;
}
public extern Shader defaultShader { get; }
public extern Shader defaultBillboardShader { get; }
/////////////////////////////////////////////////////////////////////////////
// Mesh properties
public extern float scaleFactor { get; set; }
/////////////////////////////////////////////////////////////////////////////
// Material properties
public extern Color mainColor { get; set; }
// The below properties (specColor and shininess) were first made obsolete in 5.4, they didn't work anyway, AND SpeedTreeImporter should rarely be scripted by anyone
// because of that I would say they can be safely removed for 5.6
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("specColor is no longer used and has been deprecated.", true)]
public Color specColor { get; set; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("shininess is no longer used and has been deprecated.", true)]
public float shininess { get; set; }
public extern Color hueVariation { get; set; }
public extern float alphaTestRef { get; set; }
public extern bool enableBumpByDefault { get; set; }
public extern bool enableHueByDefault { get; set; }
public extern bool enableSubsurfaceByDefault { get; set; }
/////////////////////////////////////////////////////////////////////////////
// Lighting properties
public extern bool castShadowsByDefault { get; set; }
public extern bool receiveShadowsByDefault { get; set; }
public extern bool useLightProbesByDefault { get; set; }
public extern int reflectionProbeUsagesByDefault { get; set; }
/////////////////////////////////////////////////////////////////////////////
// Wind properties
public static readonly string[] windQualityNames = new[] { "None", "Fastest", "Fast", "Better", "Best", "Palm" };
public extern int bestWindQuality { get; }
public extern int selectedWindQuality { get; set; }
/////////////////////////////////////////////////////////////////////////////
// Physics settings
public extern bool generateRigidbody { get; set; }
public extern bool generateColliders { get; set; }
/////////////////////////////////////////////////////////////////////////////
// LOD settings
public extern bool hasBillboard
{
[NativeName("HasBillboard")]
get;
}
public extern bool enableSmoothLODTransition { get; set; }
public extern bool animateCrossFading { get; set; }
public extern float billboardTransitionCrossFadeWidth { get; set; }
public extern float fadeOutWidth { get; set; }
public extern bool[] enableSettingOverride
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetEnableSettingOverride", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetEnableSettingOverride", HasExplicitThis = true)]
set;
}
public extern float[] LODHeights
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetLODHeights", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetLODHeights", HasExplicitThis = true)]
set;
}
public extern bool[] castShadows
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetCastShadows", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetCastShadows", HasExplicitThis = true)]
set;
}
public extern bool[] receiveShadows
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetReceiveShadows", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetReceiveShadows", HasExplicitThis = true)]
set;
}
public extern bool[] useLightProbes
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetUseLightProbes", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetUseLightProbes", HasExplicitThis = true)]
set;
}
public extern ReflectionProbeUsage[] reflectionProbeUsages
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetReflectionProbeUsages", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetReflectionProbeUsages", HasExplicitThis = true)]
set;
}
public extern bool[] enableBump
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetEnableBump", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetEnableBump", HasExplicitThis = true)]
set;
}
public extern bool[] enableHue
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetEnableHue", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetEnableHue", HasExplicitThis = true)]
set;
}
public extern bool[] enableSubsurface
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetEnableSubsurface", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetEnableSubsurface", HasExplicitThis = true)]
set;
}
public extern int[] windQualities
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetWindQuality", HasExplicitThis = true)]
get;
[NativeThrows]
[FreeFunction(Name = "SpeedTreeImporterBindings::SetWindQuality", HasExplicitThis = true)]
set;
}
/////////////////////////////////////////////////////////////////////////////
public extern void GenerateMaterials();
internal extern bool materialsShouldBeRegenerated
{
[NativeName("MaterialsShouldBeRegenerated")]
get;
}
internal extern void SetMaterialVersionToCurrent();
internal extern SourceAssetIdentifier[] sourceMaterials
{
[FreeFunction(Name = "SpeedTreeImporterBindings::GetSourceMaterials", HasExplicitThis = true)]
get;
}
public bool SearchAndRemapMaterials(string materialFolderPath)
{
bool changedMappings = false;
if (materialFolderPath == null)
throw new ArgumentNullException("materialFolderPath");
if (string.IsNullOrEmpty(materialFolderPath))
throw new ArgumentException(string.Format("Invalid material folder path: {0}.", materialFolderPath), "materialFolderPath");
var guids = AssetDatabase.FindAssets("t:Material", new string[] { materialFolderPath });
List<Tuple<string, Material>> materials = new List<Tuple<string, Material>>();
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
// ensure that we only load material assets, not embedded materials
var material = AssetDatabase.LoadMainAssetAtPath(path) as Material;
if (material)
materials.Add(new Tuple<string, Material>(path, material));
}
var importedMaterials = sourceMaterials;
foreach (var material in materials)
{
var materialName = material.Item2.name;
var materialFile = material.Item1;
// the legacy materials have the LOD in the path, while the new materials have the LOD as part of the name
var isLegacyMaterial = !materialName.Contains("LOD") && !materialName.Contains("Billboard");
var hasLOD = isLegacyMaterial && materialFile.Contains("LOD");
var lod = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(materialFile));
var importedMaterial = Array.Find(importedMaterials, x => x.name.Contains(materialName) && (!hasLOD || x.name.Contains(lod)));
if (!string.IsNullOrEmpty(importedMaterial.name))
{
AddRemap(importedMaterial, material.Item2);
changedMappings = true;
}
}
return changedMappings;
}
}
class SpeedTreePostProcessor : AssetPostprocessor
{
private static void FixExtraTexture_sRGB(IEnumerable<UnityEngine.Object> subAssets)
{
AssetDatabase.StartAssetEditing();
foreach (var subAsset in subAssets)
{
if (subAsset is Material)
{
Material m = subAsset as Material;
Texture tex = m.GetTexture("_ExtraTex");
if (tex)
{
string texturePath = AssetDatabase.GetAssetOrScenePath(tex);
TextureImporter texImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter;
if(texImporter)
{
// Multiple materials may be referencing the same ExtraTexture, therefore
// we'll need to check the importer's setting and only queue a single reimport
// for a given texture.
if (texImporter.sRGBTexture)
{
texImporter.sRGBTexture = false; // extra texture does not contain color data, hence shouldn't be sRGB.
texImporter.SaveAndReimport();
}
}
}
}
}
AssetDatabase.StopAssetEditing();
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (var asset in importedAssets)
{
bool st8 = asset.EndsWith(".st", StringComparison.OrdinalIgnoreCase);
if(st8)
{
// Check the external materials in case the user has extracted
Dictionary<AssetImporter.SourceAssetIdentifier, UnityEngine.Object> externalAssets = (AssetImporter.GetAtPath(asset) as SpeedTreeImporter).GetExternalObjectMap();
FixExtraTexture_sRGB(externalAssets.Values);
// Check the object subassets -- updates the materials if they're embedded in the SpeedTree asset
UnityEngine.Object[] subAssets = AssetDatabase.LoadAllAssetsAtPath(asset);
FixExtraTexture_sRGB(subAssets);
}
}
}
}
}
| UnityCsReference/Editor/Mono/AssetPipeline/SpeedTreeImporter.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTreeImporter.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 5416
} | 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 UnityEngine.Bindings;
using UnityEditor.PackageManager;
using System.Runtime.InteropServices;
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
namespace UnityEditorInternal
{
internal partial class AssetStoreCachePathManager
{
public enum ConfigStatus
{
Success = 0,
InvalidPath,
ReadOnly,
EnvironmentOverride,
NotFound,
Failed
};
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeAsStruct]
internal class CachePathConfig
{
[SerializeField]
[NativeName("path")]
private string m_Path = "";
[SerializeField]
[NativeName("source")]
private ConfigSource m_Source = ConfigSource.Unknown;
[SerializeField]
[NativeName("status")]
private ConfigStatus m_Status = ConfigStatus.Success;
public string path => m_Path;
public ConfigSource source => m_Source;
public ConfigStatus status => m_Status;
}
}
}
| UnityCsReference/Editor/Mono/AssetStoreCachePathManager.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/AssetStoreCachePathManager.cs",
"repo_id": "UnityCsReference",
"token_count": 578
} | 280 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.Audio
{
public class AudioMixerEffectPlugin : IAudioEffectPlugin
{
internal AudioMixerController m_Controller;
internal AudioMixerEffectController m_Effect;
internal MixerParameterDefinition[] m_ParamDefs;
static bool s_ParameterChangeUndoIsRecorded;
static bool s_ParameterChangeUndoGroupNameIsSet;
static readonly Dictionary<string, float> k_UpdatedParameterMap = new Dictionary<string, float>();
readonly HashSet<string> m_VerifiedParameters = new HashSet<string>();
public override bool SetFloatParameter(string name, float value)
{
if (!HasParameter(name))
{
return false;
}
GetFloatParameter(name, out var previousValue);
if (Mathf.Approximately(value, previousValue))
{
return true;
}
if (k_UpdatedParameterMap.Count == 0 && !s_ParameterChangeUndoIsRecorded)
{
Undo.RecordObject(m_Controller.TargetSnapshot, $"Change {name}");
}
k_UpdatedParameterMap[name] = value;
if (k_UpdatedParameterMap.Count > 1 && !s_ParameterChangeUndoGroupNameIsSet)
{
Undo.SetCurrentGroupName("Change Effect Parameters");
s_ParameterChangeUndoGroupNameIsSet = true;
}
m_Effect.SetValueForParameter(m_Controller, m_Controller.TargetSnapshot, name, value);
return true;
}
public override bool GetFloatParameter(string name, out float value)
{
if (!HasParameter(name))
{
value = default;
return false;
}
if (k_UpdatedParameterMap.TryGetValue(name, out value))
{
return true;
}
value = m_Effect.GetValueForParameter(m_Controller, m_Controller.TargetSnapshot, name);
return true;
}
public override bool GetFloatParameterInfo(string name, out float minRange, out float maxRange, out float defaultValue)
{
foreach (var p in m_ParamDefs)
{
if (p.name == name)
{
minRange = p.minRange;
maxRange = p.maxRange;
defaultValue = p.defaultValue;
return true;
}
}
minRange = 0.0f;
maxRange = 1.0f;
defaultValue = 0.5f;
return false;
}
public override bool GetFloatBuffer(string name, out float[] data, int numsamples)
{
m_Effect.GetFloatBuffer(m_Controller, name, out data, numsamples);
return true;
}
public override int GetSampleRate()
{
return AudioSettings.outputSampleRate;
}
public override bool IsPluginEditableAndEnabled()
{
return AudioMixerController.EditingTargetSnapshot() && !m_Effect.bypass;
}
// Call this after each interaction that changes effect parameters.
// NOTE: It is assumed that parameter changes can only happen on a single effect at a time.
internal static void OnParameterChangesDone()
{
k_UpdatedParameterMap.Clear();
s_ParameterChangeUndoIsRecorded = false;
s_ParameterChangeUndoGroupNameIsSet = false;
}
bool HasParameter(string name)
{
if (m_VerifiedParameters.Contains(name))
{
return true;
}
for (var i = 0; i < m_ParamDefs.Length; ++i)
{
if (m_ParamDefs[i].name.Equals(name))
{
m_VerifiedParameters.Add(name);
return true;
}
}
return false;
}
}
}
| UnityCsReference/Editor/Mono/Audio/Effects/AudioMixerEffectPlugin.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/Effects/AudioMixerEffectPlugin.cs",
"repo_id": "UnityCsReference",
"token_count": 1998
} | 281 |
// 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.IO;
using System;
using UnityEditorInternal;
using UnityEditor.Audio;
using UnityEditor.IMGUI.Controls;
using Object = UnityEngine.Object;
namespace UnityEditor
{
// Item
internal class AudioMixerTreeViewNode : TreeViewItem
{
public AudioMixerGroupController group { get; set; }
public AudioMixerTreeViewNode(int instanceID, int depth, TreeViewItem parent, string displayName, AudioMixerGroupController group)
: base(instanceID, depth, parent, displayName)
{
this.group = group;
}
}
// Dragging
// We want dragging to work from the mixer window to the inspector like the project browser, but also want
// custom dragging behavior (reparent the group sub assets) so we derive from AssetOrGameObjectTreeViewDragging
// and override DoDrag.
internal class AudioGroupTreeViewDragging : AssetsTreeViewDragging
{
private AudioMixerGroupTreeView m_owner;
public AudioGroupTreeViewDragging(TreeViewController treeView, AudioMixerGroupTreeView owner)
: base(treeView)
{
m_owner = owner;
}
public override void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs)
{
if (!EditorApplication.isPlaying)
base.StartDrag(draggedItem, draggedItemIDs);
}
public override DragAndDropVisualMode DoDrag(TreeViewItem parentNode, TreeViewItem targetNode, bool perform, DropPosition dragPos)
{
var parentGroupNode = parentNode as AudioMixerTreeViewNode;
var draggedGroups = new List<Object>(DragAndDrop.objectReferences).OfType<AudioMixerGroupController>().ToList();
if (parentGroupNode != null && draggedGroups.Count > 0)
{
var draggedIDs = (from i in draggedGroups select i.GetInstanceID()).ToList();
bool validDrag = ValidDrag(parentNode, draggedIDs) && !AudioMixerController.WillModificationOfTopologyCauseFeedback(m_owner.Controller.GetAllAudioGroupsSlow(), draggedGroups, parentGroupNode.group, null);
if (perform && validDrag)
{
AudioMixerGroupController parentGroup = parentGroupNode.group;
// If insertionIndex is -1 we are dropping upon the parentNode
int insertionIndex = GetInsertionIndex(parentNode, targetNode, dragPos);
m_owner.Controller.ReparentSelection(parentGroup, insertionIndex, draggedGroups);
m_owner.ReloadTree();
m_owner.Controller.OnSubAssetChanged();
m_TreeView.SetSelection(draggedIDs.ToArray(), true); // Ensure dropped item(s) are selected and revealed (fixes selection if click dragging a single item that is not selected when drag was started)
}
return validDrag ? DragAndDropVisualMode.Move : DragAndDropVisualMode.Rejected;
}
return DragAndDropVisualMode.None;
}
bool ValidDrag(TreeViewItem parent, List<int> draggedInstanceIDs)
{
TreeViewItem currentParent = parent;
while (currentParent != null)
{
if (draggedInstanceIDs.Contains(currentParent.id))
return false;
currentParent = currentParent.parent;
}
return true;
}
}
// Datasource
internal class AudioGroupDataSource : TreeViewDataSource
{
public AudioGroupDataSource(TreeViewController treeView, AudioMixerController controller)
: base(treeView)
{
m_Controller = controller;
}
private void AddNodesRecursively(AudioMixerGroupController group, TreeViewItem parent, int depth)
{
var children = new List<TreeViewItem>();
for (int i = 0; i < group.children.Length; ++i)
{
int uniqueNodeID = GetUniqueNodeID(group.children[i]);
var node = new AudioMixerTreeViewNode(uniqueNodeID, depth, parent, group.children[i].name, group.children[i]);
node.parent = parent;
children.Add(node);
AddNodesRecursively(group.children[i], node, depth + 1);
}
parent.children = children;
}
static public int GetUniqueNodeID(AudioMixerGroupController group)
{
return group.GetInstanceID(); // alternative: group.groupID.GetHashCode();
}
public override void FetchData()
{
if (m_Controller == null)
{
m_RootItem = null;
return;
}
if (m_Controller.masterGroup == null)
{
Debug.LogError("The Master group is missing !!!");
m_RootItem = null;
return;
}
int uniqueNodeID = GetUniqueNodeID(m_Controller.masterGroup);
m_RootItem = new AudioMixerTreeViewNode(uniqueNodeID, 0, null, m_Controller.masterGroup.name, m_Controller.masterGroup);
AddNodesRecursively(m_Controller.masterGroup, m_RootItem, 1);
m_NeedRefreshRows = true;
}
public override bool IsRenamingItemAllowed(TreeViewItem node)
{
var audioNode = node as AudioMixerTreeViewNode;
if (audioNode.group == m_Controller.masterGroup)
return false;
return true;
}
public AudioMixerController m_Controller;
}
// Node GUI
internal class AudioGroupTreeViewGUI : TreeViewGUI
{
readonly float column1Width = 20f;
readonly GUIContent k_VisibleON = EditorGUIUtility.TrIconContent("animationvisibilitytoggleon");
readonly GUIContent k_VisibleOFF = EditorGUIUtility.TrIconContent("animationvisibilitytoggleoff");
public Action<AudioMixerTreeViewNode, bool> NodeWasToggled;
public AudioMixerController m_Controller = null;
public AudioGroupTreeViewGUI(TreeViewController treeView)
: base(treeView)
{
k_BaseIndent = column1Width;
k_IconWidth = 0;
k_TopRowMargin = k_BottomRowMargin = 2f;
}
void OpenGroupContextMenu(AudioMixerTreeViewNode audioNode, bool visible)
{
GenericMenu menu = new GenericMenu();
if (NodeWasToggled != null)
{
menu.AddItem(new GUIContent(visible ? "Hide group" : "Show Group"), false, () => NodeWasToggled(audioNode, !visible));
}
menu.AddSeparator(string.Empty);
AudioMixerGroupController[] groups;
if (m_Controller.CachedSelection.Contains(audioNode.group))
groups = m_Controller.CachedSelection.ToArray();
else
groups = new AudioMixerGroupController[] { audioNode.group };
AudioMixerColorCodes.AddColorItemsToGenericMenu(menu, groups);
menu.ShowAsContext();
}
override public void OnRowGUI(Rect rowRect, TreeViewItem node, int row, bool selected, bool focused)
{
Event evt = Event.current;
DoItemGUI(rowRect, row, node, selected, focused, false);
if (m_Controller == null)
return;
var audioNode = node as AudioMixerTreeViewNode;
if (audioNode != null)
{
bool oldSelected = m_Controller.CurrentViewContainsGroup(audioNode.group.groupID);
const float kIconSize = 16f;
float xMargin = 3f;
Rect iconRect = new Rect(rowRect.x + xMargin, rowRect.y, kIconSize, kIconSize);
Rect iconBgRect = new Rect(iconRect.x + 1, iconRect.y + 1, iconRect.width - 2, iconRect.height - 2);
int colorIndex = audioNode.group.userColorIndex;
if (colorIndex > 0)
EditorGUI.DrawRect(new Rect(rowRect.x, iconBgRect.y, 2, iconBgRect.height), AudioMixerColorCodes.GetColor(colorIndex));
if (oldSelected)
GUI.DrawTexture(iconRect, k_VisibleON.image);
else
GUI.DrawTexture(iconRect, k_VisibleOFF.image);
Rect toggleRect = new Rect(2, rowRect.y, rowRect.height, rowRect.height);
if (evt.type == EventType.MouseUp && evt.button == 0 && toggleRect.Contains(evt.mousePosition))
{
if (NodeWasToggled != null)
NodeWasToggled(audioNode, !oldSelected);
}
if (evt.type == EventType.ContextClick && iconRect.Contains(evt.mousePosition))
{
OpenGroupContextMenu(audioNode, oldSelected);
evt.Use();
}
}
}
protected override Texture GetIconForItem(TreeViewItem node)
{
if (node != null && node.icon != null)
return node.icon;
return null;
}
protected override void SyncFakeItem() {}
protected override void RenameEnded()
{
bool userAccepted = GetRenameOverlay().userAcceptedRename;
if (userAccepted)
{
string name = string.IsNullOrEmpty(GetRenameOverlay().name) ? GetRenameOverlay().originalName : GetRenameOverlay().name;
int instanceID = GetRenameOverlay().userData;
var audioNode = m_TreeView.FindItem(instanceID) as AudioMixerTreeViewNode;
if (audioNode != null)
{
ObjectNames.SetNameSmartWithInstanceID(instanceID, name);
foreach (var effect in audioNode.group.effects)
effect.ClearCachedDisplayName();
m_TreeView.ReloadData();
if (m_Controller != null)
m_Controller.OnSubAssetChanged();
}
}
}
}
// TreeView
internal class AudioMixerGroupPopupContext
{
public AudioMixerGroupPopupContext(AudioMixerController controller, AudioMixerGroupController group)
{
this.controller = controller;
this.groups = new AudioMixerGroupController[] { group };
}
public AudioMixerGroupPopupContext(AudioMixerController controller, AudioMixerGroupController[] groups)
{
this.controller = controller;
this.groups = groups;
}
public AudioMixerController controller;
public AudioMixerGroupController[] groups;
}
internal class AudioMixerGroupTreeView
{
private AudioMixerController m_Controller;
private AudioGroupDataSource m_AudioGroupTreeDataSource;
private TreeViewState m_AudioGroupTreeState;
private TreeViewController m_AudioGroupTree;
private AudioGroupTreeViewGUI m_TreeViewGUI;
private AudioMixerGroupController m_ScrollToItem;
class Styles
{
public GUIContent header = EditorGUIUtility.TrTextContent("Groups", "An Audio Mixer Group is used by e.g Audio Sources to modify the audio output before it reaches the Audio Listener. An Audio Mixer Group will route its output to another Audio Mixer Group if it is made a child of that group. The Master Group will route its output to the Audio Listener if it doesn't route its output into another Mixer.");
public GUIContent addButton = EditorGUIUtility.TrIconContent("CreateAddNew", "Add child group");
public Texture2D audioMixerGroupIcon = EditorGUIUtility.FindTexture(typeof(UnityEngine.Audio.AudioMixerGroup));
}
static Styles s_Styles;
public AudioMixerGroupTreeView(AudioMixerWindow mixerWindow, TreeViewState treeState)
{
m_AudioGroupTreeState = treeState;
m_AudioGroupTree = new TreeViewController(mixerWindow, m_AudioGroupTreeState);
m_AudioGroupTree.deselectOnUnhandledMouseDown = false;
m_AudioGroupTree.selectionChangedCallback += OnTreeSelectionChanged;
m_AudioGroupTree.contextClickItemCallback += OnTreeViewContextClick;
m_AudioGroupTree.expandedStateChanged += SaveExpandedState;
m_TreeViewGUI = new AudioGroupTreeViewGUI(m_AudioGroupTree);
m_TreeViewGUI.NodeWasToggled += OnNodeToggled;
m_AudioGroupTreeDataSource = new AudioGroupDataSource(m_AudioGroupTree, m_Controller);
m_AudioGroupTree.Init(mixerWindow.position,
m_AudioGroupTreeDataSource, m_TreeViewGUI,
new AudioGroupTreeViewDragging(m_AudioGroupTree, this)
);
m_AudioGroupTree.ReloadData();
}
public AudioMixerController Controller
{
get { return m_Controller; }
}
public AudioMixerGroupController ScrollToItem
{
get { return m_ScrollToItem; }
}
public void UseScrollView(bool useScrollView)
{
m_AudioGroupTree.useScrollView = useScrollView;
}
public void ReloadTreeData()
{
m_AudioGroupTree.ReloadData();
}
public void ReloadTree()
{
m_AudioGroupTree.ReloadData();
if (m_Controller != null)
m_Controller.SanitizeGroupViews();
}
public void AddChildGroupPopupCallback(object obj)
{
AudioMixerGroupPopupContext context = (AudioMixerGroupPopupContext)obj;
if (context.groups != null && context.groups.Length > 0)
AddAudioMixerGroup(context.groups[0]);
}
public void AddSiblingGroupPopupCallback(object obj)
{
AudioMixerGroupPopupContext context = (AudioMixerGroupPopupContext)obj;
if (context.groups != null && context.groups.Length > 0)
{
var item = m_AudioGroupTree.FindItem(context.groups[0].GetInstanceID()) as AudioMixerTreeViewNode;
if (item != null)
{
var parent = item.parent as AudioMixerTreeViewNode;
AddAudioMixerGroup(parent.group);
}
}
}
public void AddAudioMixerGroup(AudioMixerGroupController parent)
{
if (parent == null || m_Controller == null)
return;
var newGroup = m_Controller.CreateNewGroup("New Group", true);
Undo.RecordObjects(new UnityEngine.Object[] { m_Controller, parent }, "Add Child Group");
m_Controller.AddChildToParent(newGroup, parent);
m_Controller.AddGroupToCurrentView(newGroup);
Selection.objects = new[] { newGroup };
m_Controller.OnUnitySelectionChanged();
m_AudioGroupTree.SetSelection(new int[] { newGroup.GetInstanceID() }, true);
ReloadTree();
m_Controller.OnSubAssetChanged();
m_AudioGroupTree.BeginNameEditing(0f);
}
static string PluralIfNeeded(int count)
{
return count > 1 ? "s" : "";
}
public void DeleteGroups(List<AudioMixerGroupController> groups)
{
foreach (AudioMixerGroupController group in groups)
{
if (group.HasDependentMixers())
{
if (!EditorUtility.DisplayDialog("Referenced Group", "Deleted group is referenced by another AudioMixer, are you sure?", "Delete", "Cancel"))
return;
break;
}
}
m_Controller.DeleteGroups(groups.ToArray());
ReloadTree();
m_Controller.OnSubAssetChanged();
}
public void DuplicateGroups(List<AudioMixerGroupController> groups, bool recordUndo)
{
if (recordUndo)
{
Undo.RecordObject(m_Controller, "Duplicate group" + PluralIfNeeded(groups.Count));
Undo.RecordObject(m_Controller.masterGroup, "");
}
var duplicatedRoots = m_Controller.DuplicateGroups(groups.ToArray(), recordUndo);
if (duplicatedRoots.Count > 0)
{
ReloadTree();
m_Controller.OnSubAssetChanged();
var instanceIDs = duplicatedRoots.Select(audioMixerGroup => audioMixerGroup.GetInstanceID()).ToArray();
m_AudioGroupTree.SetSelection(instanceIDs, false);
m_AudioGroupTree.Frame(instanceIDs[instanceIDs.Length - 1], true, false);
}
}
void DeleteGroupsPopupCallback(object obj)
{
var audioMixerGroupTreeView = (AudioMixerGroupTreeView)obj;
audioMixerGroupTreeView.DeleteGroups(GetGroupSelectionWithoutMasterGroup());
}
void DuplicateGroupPopupCallback(object obj)
{
var audioMixerGroupTreeView = (AudioMixerGroupTreeView)obj;
audioMixerGroupTreeView.DuplicateGroups(GetGroupSelectionWithoutMasterGroup(), true);
}
void RenameGroupCallback(object obj)
{
var item = (TreeViewItem)obj;
m_AudioGroupTree.SetSelection(new int[] { item.id }, false);
m_AudioGroupTree.BeginNameEditing(0f);
}
List<AudioMixerGroupController> GetGroupSelectionWithoutMasterGroup()
{
var items = GetAudioMixerGroupsFromNodeIDs(m_AudioGroupTree.GetSelection());
items.Remove(m_Controller.masterGroup);
return items;
}
public void OnTreeViewContextClick(int index)
{
var node = m_AudioGroupTree.FindItem(index);
if (node != null)
{
AudioMixerTreeViewNode mixerNode = node as AudioMixerTreeViewNode;
if (mixerNode != null && mixerNode.group != null)
{
GenericMenu pm = new GenericMenu();
if (!EditorApplication.isPlaying)
{
pm.AddItem(EditorGUIUtility.TrTextContent("Add child group"), false, AddChildGroupPopupCallback, new AudioMixerGroupPopupContext(m_Controller, mixerNode.group));
if (mixerNode.group != m_Controller.masterGroup)
{
pm.AddItem(EditorGUIUtility.TrTextContent("Add sibling group"), false, AddSiblingGroupPopupCallback, new AudioMixerGroupPopupContext(m_Controller, mixerNode.group));
pm.AddSeparator("");
pm.AddItem(EditorGUIUtility.TrTextContent("Rename"), false, RenameGroupCallback, node);
// Mastergroup cannot be deleted nor duplicated
var selection = GetGroupSelectionWithoutMasterGroup().ToArray();
pm.AddItem(new GUIContent((selection.Length > 1) ? "Duplicate groups (and children)" : "Duplicate group (and children)"), false, DuplicateGroupPopupCallback, this);
pm.AddItem(new GUIContent((selection.Length > 1) ? "Remove groups (and children)" : "Remove group (and children)"), false, DeleteGroupsPopupCallback, this);
}
}
else
{
pm.AddDisabledItem(EditorGUIUtility.TrTextContent("Modifying group topology in play mode is not allowed"));
}
pm.ShowAsContext();
}
}
}
void OnNodeToggled(AudioMixerTreeViewNode node, bool nodeWasEnabled)
{
Undo.RecordObject(m_Controller, "Changed Group Visibility");
var treeSelection = GetAudioMixerGroupsFromNodeIDs(m_AudioGroupTree.GetSelection());
if (!treeSelection.Contains(node.group))
treeSelection = new List<AudioMixerGroupController> { node.group };
var newSelection = new List<GUID>();
var allGroups = m_Controller.GetAllAudioGroupsSlow();
foreach (var g in allGroups)
{
bool inOldSelection = m_Controller.CurrentViewContainsGroup(g.groupID);
bool inNewSelection = treeSelection.Contains(g);
bool add = inOldSelection && !inNewSelection;
if (!inOldSelection && inNewSelection)
add = nodeWasEnabled;
if (add)
newSelection.Add(g.groupID);
}
m_Controller.SetCurrentViewVisibility(newSelection.ToArray());
}
List<AudioMixerGroupController> GetAudioMixerGroupsFromNodeIDs(int[] instanceIDs)
{
List<AudioMixerGroupController> newSelectedGroups = new List<AudioMixerGroupController>();
foreach (var s in instanceIDs)
{
var node = m_AudioGroupTree.FindItem(s);
if (node != null)
{
AudioMixerTreeViewNode mixerNode = node as AudioMixerTreeViewNode;
if (mixerNode != null)
newSelectedGroups.Add(mixerNode.group);
}
}
return newSelectedGroups;
}
public void OnTreeSelectionChanged(int[] selection)
{
var groups = GetAudioMixerGroupsFromNodeIDs(selection);
Selection.objects = groups.ToArray();
m_Controller.OnUnitySelectionChanged();
if (groups.Count == 1)
m_ScrollToItem = groups[0];
InspectorWindow.RepaintAllInspectors();
}
public void InitSelection(bool revealSelectionAndFrameLastSelected)
{
if (m_Controller == null)
return;
var groups = m_Controller.CachedSelection;
m_AudioGroupTree.SetSelection((from x in groups select x.GetInstanceID()).ToArray(), revealSelectionAndFrameLastSelected);
}
public float GetTotalHeight()
{
if (m_Controller == null)
return 0f;
return m_AudioGroupTree.gui.GetTotalSize().y + AudioMixerDrawUtils.kSectionHeaderHeight;
}
public void OnGUI(Rect rect)
{
int treeViewKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard);
m_ScrollToItem = null;
if (s_Styles == null)
s_Styles = new Styles();
m_AudioGroupTree.OnEvent();
Rect headerRect, contentRect;
using (new EditorGUI.DisabledScope(m_Controller == null))
{
AudioMixerDrawUtils.DrawRegionBg(rect, out headerRect, out contentRect);
AudioMixerDrawUtils.HeaderLabel(headerRect, s_Styles.header, s_Styles.audioMixerGroupIcon);
}
if (m_Controller != null)
{
AudioMixerGroupController parent = (m_Controller.CachedSelection.Count == 1) ? m_Controller.CachedSelection[0] : m_Controller.masterGroup;
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
if (GUI.Button(new Rect(headerRect.xMax - 17f, headerRect.y + 3f, 16f, 16f), s_Styles.addButton, EditorStyles.iconButton))
AddAudioMixerGroup(parent);
}
m_AudioGroupTree.OnGUI(contentRect, treeViewKeyboardControlID);
AudioMixerDrawUtils.DrawScrollDropShadow(contentRect, m_AudioGroupTree.state.scrollPos.y, m_AudioGroupTree.gui.GetTotalSize().y);
HandleKeyboardEvents(treeViewKeyboardControlID);
HandleCommandEvents(treeViewKeyboardControlID);
}
}
void HandleCommandEvents(int treeViewKeyboardControlID)
{
if (GUIUtility.keyboardControl != treeViewKeyboardControlID)
return;
EventType eventType = Event.current.type;
if (eventType == EventType.ExecuteCommand || eventType == EventType.ValidateCommand)
{
bool execute = eventType == EventType.ExecuteCommand;
if (Event.current.commandName == EventCommandNames.Delete || Event.current.commandName == EventCommandNames.SoftDelete)
{
Event.current.Use();
if (execute)
{
DeleteGroups(GetGroupSelectionWithoutMasterGroup());
GUIUtility.ExitGUI(); // Cached groups might have been deleted to so early out of event
}
}
else if (Event.current.commandName == EventCommandNames.Duplicate)
{
Event.current.Use();
if (execute)
DuplicateGroups(GetGroupSelectionWithoutMasterGroup(), true);
}
}
}
void HandleKeyboardEvents(int treeViewKeyboardControlID)
{
if (GUIUtility.keyboardControl != treeViewKeyboardControlID)
return;
Event evt = Event.current;
if (evt.keyCode == KeyCode.Space && evt.type == EventType.KeyDown)
{
int[] selection = m_AudioGroupTree.GetSelection();
if (selection.Length > 0)
{
AudioMixerTreeViewNode node = m_AudioGroupTree.FindItem(selection[0]) as AudioMixerTreeViewNode;
bool shown = m_Controller.CurrentViewContainsGroup(node.group.groupID);
OnNodeToggled(node, !shown);
evt.Use();
}
}
}
public void OnMixerControllerChanged(AudioMixerController controller)
{
if (m_Controller != controller)
{
m_TreeViewGUI.m_Controller = controller;
m_Controller = controller;
m_AudioGroupTreeDataSource.m_Controller = controller;
if (controller != null)
{
ReloadTree();
InitSelection(false);
LoadExpandedState();
m_AudioGroupTree.data.SetExpandedWithChildren(m_AudioGroupTree.data.root, true);
}
}
}
static string GetUniqueAudioMixerName(AudioMixerController controller)
{
return "AudioMixer_" + controller.GetInstanceID();
}
void SaveExpandedState()
{
SessionState.SetIntArray(GetUniqueAudioMixerName(m_Controller), m_AudioGroupTreeState.expandedIDs.ToArray());
}
void LoadExpandedState()
{
int[] cachedExpandedState = SessionState.GetIntArray(GetUniqueAudioMixerName(m_Controller), null);
if (cachedExpandedState != null)
{
m_AudioGroupTreeState.expandedIDs = new List<int>(cachedExpandedState);
}
else
{
// Expand whole tree. If no cached data then its the first time tree was loaded in this session
m_AudioGroupTree.state.expandedIDs = new List<int>();
m_AudioGroupTree.data.SetExpandedWithChildren(m_AudioGroupTree.data.root, true);
}
}
public void EndRenaming()
{
m_AudioGroupTree.EndNameEditing(true);
}
public void OnUndoRedoPerformed(in UndoRedoInfo info)
{
ReloadTree();
if (m_Controller != null)
m_Controller.OnSubAssetChanged();
}
}
}
| UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerGroupTreeView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerGroupTreeView.cs",
"repo_id": "UnityCsReference",
"token_count": 12950
} | 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 UnityEngine;
namespace UnityEditor
{
class WaveformPreview : IDisposable
{
static int s_BaseTextureWidth = 4096;
static Material s_Material;
public double start { get { return m_Start; } }
public double length { get { return m_Length; } }
public Color backgroundColor { get; set; }
public Color waveColor { get; set; }
public event Action updated;
public UnityEngine.Object presentedObject;
public bool optimized
{
get { return m_Optimized; }
set
{
if (m_Optimized != value)
{
if (value)
m_Dirty = true;
m_Optimized = value;
m_Flags |= MessageFlags.Optimization;
}
}
}
public bool looping
{
get { return m_Looping; }
set
{
if (m_Looping != value)
{
m_Dirty = true;
m_Looping = value;
m_Flags |= MessageFlags.Looping;
}
}
}
public enum ChannelMode
{
MonoSum,
Separate,
SpecificChannel
}
[Flags]
protected enum MessageFlags
{
None = 0,
Size = 1 << 0,
Length = 1 << 1,
Start = 1 << 2,
Optimization = 1 << 3,
TextureChanged = 1 << 4,
ContentsChanged = 1 << 5,
Looping = 1 << 6
}
protected static bool HasFlag(MessageFlags flags, MessageFlags test)
{
return (flags & test) != 0;
}
protected double m_Start;
protected double m_Length;
protected bool m_ClearTexture = true;
protected Vector2 Size { get { return m_Size; } }
Texture2D m_Texture;
Vector2 m_Size;
int m_Channels;
int m_Samples;
int m_SpecificChannel;
ChannelMode m_ChannelMode;
bool m_Looping;
bool m_Optimized;
bool m_Dirty;
bool m_Disposed;
MessageFlags m_Flags;
protected WaveformPreview(UnityEngine.Object presentedObject, int samplesAndWidth, int channels)
{
this.presentedObject = presentedObject;
optimized = true;
m_Samples = samplesAndWidth;
m_Channels = channels;
backgroundColor = new Color(40 / 255.0f, 40 / 255.0f, 40 / 255.0f, 1.0f);
waveColor = new Color(255.0f / 255.0f, 140.0f / 255.0f, 0 / 255.0f, 1.0f);
UpdateTexture(samplesAndWidth, channels);
}
protected internal WaveformPreview(UnityEngine.Object presentedObject, int samplesAndWidth, int channels, bool deferTextureCreation)
{
this.presentedObject = presentedObject;
optimized = true;
m_Samples = samplesAndWidth;
m_Channels = channels;
backgroundColor = new Color(40 / 255.0f, 40 / 255.0f, 40 / 255.0f, 1.0f);
waveColor = new Color(255.0f / 255.0f, 140.0f / 255.0f, 0 / 255.0f, 1.0f);
if (!deferTextureCreation)
UpdateTexture(samplesAndWidth, channels);
}
public void Dispose()
{
if (!m_Disposed)
{
m_Disposed = true;
InternalDispose();
if (m_Texture != null)
{
if (Application.isPlaying)
UnityEngine.Object.Destroy(m_Texture);
else
UnityEngine.Object.DestroyImmediate(m_Texture);
}
m_Texture = null;
}
}
protected virtual void InternalDispose() {}
public void Render(Rect rect)
{
if (s_Material == null)
{
s_Material = EditorGUIUtility.LoadRequired("Previews/PreviewAudioClipWaveform.mat") as Material;
}
s_Material.SetTexture("_WavTex", m_Texture);
s_Material.SetFloat("_SampCount", m_Samples);
s_Material.SetFloat("_ChanCount", m_Channels);
s_Material.SetFloat("_RecPixelSize", 1.0f / rect.height);
s_Material.SetColor("_BacCol", backgroundColor);
s_Material.SetColor("_ForCol", waveColor);
int mode = -2;
if (m_ChannelMode == ChannelMode.Separate)
mode = -1;
else if (m_ChannelMode == ChannelMode.SpecificChannel)
mode = m_SpecificChannel;
s_Material.SetFloat("_ChanDrawMode", (float)mode);
Graphics.DrawTexture(rect, m_Texture, s_Material);
}
public bool ApplyModifications()
{
if (m_Dirty || m_Texture == null)
{
m_Flags |= UpdateTexture((int)m_Size.x, m_Channels) ? MessageFlags.TextureChanged : MessageFlags.None;
OnModifications(m_Flags);
m_Flags = MessageFlags.None;
m_Texture.Apply();
m_Dirty = false;
return true;
}
return false;
}
public void SetChannelMode(ChannelMode mode, int specificChannelToRender)
{
m_ChannelMode = mode;
m_SpecificChannel = specificChannelToRender;
}
public void SetChannelMode(ChannelMode mode)
{
SetChannelMode(mode, 0);
}
bool UpdateTexture(int width, int channels)
{
int widthWithChannels = width * channels;
int textureHeight = 1 + widthWithChannels / s_BaseTextureWidth;
Action<bool> updateTexture =
clear =>
{
if (m_Texture == null)
{
m_Texture = new Texture2D(s_BaseTextureWidth, textureHeight, TextureFormat.RGBAHalf, false, true);
m_Texture.filterMode = FilterMode.Point;
clear = false;
}
else
{
m_Texture.Reinitialize(s_BaseTextureWidth, textureHeight);
}
if (!clear)
return;
var fillColorArray = m_Texture.GetPixels();
for (var i = 0; i < fillColorArray.Length; ++i)
fillColorArray[i] = Color.black;
m_Texture.SetPixels(fillColorArray);
};
if (width == m_Samples && channels == m_Channels && m_Texture != null)
{
return false;
}
// resample texture here
updateTexture(m_ClearTexture);
m_Samples = width;
m_Channels = channels;
return m_Dirty = true;
}
public void OptimizeForSize(Vector2 newSize)
{
newSize = new Vector2(Mathf.Ceil(newSize.x), Mathf.Ceil(newSize.y));
if (newSize.x != m_Size.x)
{
m_Size = newSize;
m_Flags |= MessageFlags.Size;
m_Dirty = true;
}
}
protected virtual void OnModifications(MessageFlags changedFlags) {}
public void SetTimeInfo(double start, double length)
{
if (start != m_Start || length != m_Length)
{
m_Start = start;
m_Length = length;
m_Dirty = true;
m_Flags |= MessageFlags.Start | MessageFlags.Length;
}
}
public virtual void SetMMWaveData(int interleavedOffset, float[] data)
{
// could be optimized, but profiling shows it isn't the bottleneck at all
for (int i = 0; i < data.Length; interleavedOffset++, i += 2)
{
int x = interleavedOffset % s_BaseTextureWidth;
int y = interleavedOffset / s_BaseTextureWidth;
m_Texture.SetPixel(x, y, new Color(data[i], data[i + 1], 0.0f, 0.0f));
}
m_Dirty = true;
m_Flags |= MessageFlags.ContentsChanged;
if (updated != null)
updated();
}
}
}
| UnityCsReference/Editor/Mono/Audio/WaveformPreview.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Audio/WaveformPreview.cs",
"repo_id": "UnityCsReference",
"token_count": 4447
} | 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.Generic;
using DiscoveredTargetInfo = UnityEditor.BuildTargetDiscovery.DiscoveredTargetInfo;
using TargetAttributes = UnityEditor.BuildTargetDiscovery.TargetAttributes;
namespace UnityEditor.Build
{
// All settings for a build platform.
internal class BuildPlatform
{
// short name used for texture settings, etc.
public string name;
public NamedBuildTarget namedBuildTarget;
public bool installed;
public bool hideInUi;
public string tooltip;
public BuildTarget defaultTarget;
// TODO: Some packages are still using targetGroup, so we keep it here as a getter for compatibility
public BuildTargetGroup targetGroup => namedBuildTarget.ToBuildTargetGroup();
ScalableGUIContent m_Title;
ScalableGUIContent m_SmallTitle;
public GUIContent title => m_Title;
public Texture2D smallIcon => ((GUIContent)m_SmallTitle).image as Texture2D;
public BuildPlatform(string locTitle, string iconId, NamedBuildTarget namedBuildTarget, BuildTarget defaultTarget, bool hideInUi, bool installed)
: this(locTitle, "", iconId, namedBuildTarget, defaultTarget, hideInUi, installed)
{
}
public BuildPlatform(string locTitle, string tooltip, string iconId, NamedBuildTarget namedBuildTarget, BuildTarget defaultTarget, bool hideInUi, bool installed)
{
this.namedBuildTarget = namedBuildTarget;
name = namedBuildTarget.TargetName;
m_Title = new ScalableGUIContent(locTitle, null, iconId);
m_SmallTitle = new ScalableGUIContent(null, null, iconId + ".Small");
this.tooltip = tooltip;
this.hideInUi = hideInUi;
this.defaultTarget = defaultTarget;
this.installed = installed;
}
}
internal class BuildPlatformWithSubtarget : BuildPlatform
{
public int subtarget;
public BuildPlatformWithSubtarget(string locTitle, string tooltip, string iconId, NamedBuildTarget namedBuildTarget, BuildTarget defaultTarget, int subtarget, bool hideInUi, bool installed)
: base(locTitle, tooltip, iconId, namedBuildTarget, defaultTarget, hideInUi, installed)
{
this.subtarget = subtarget;
name = namedBuildTarget.TargetName;
}
}
internal class BuildPlatforms
{
static readonly BuildPlatforms s_Instance = new BuildPlatforms();
public static BuildPlatforms instance => s_Instance;
internal BuildPlatforms()
{
List<BuildPlatform> buildPlatformsList = new List<BuildPlatform>();
DiscoveredTargetInfo[] buildTargets = BuildTargetDiscovery.GetBuildTargetInfoList();
// Standalone needs to be first
// Before we had BuildTarget.StandaloneWindows for BuildPlatform.defaultTarget
// But that doesn't make a lot of sense, as editor use it in places, so it should agree with editor platform
// TODO: should we poke module manager for target support? i think we can assume support for standalone for editor platform
// TODO: even then - picking windows standalone unconditionally wasn't much better
BuildTarget standaloneTarget = BuildTarget.StandaloneWindows;
if (Application.platform == RuntimePlatform.OSXEditor)
standaloneTarget = BuildTarget.StandaloneOSX;
else if (Application.platform == RuntimePlatform.LinuxEditor)
standaloneTarget = BuildTarget.StandaloneLinux64;
buildPlatformsList.Add(new BuildPlatformWithSubtarget(BuildPipeline.GetBuildTargetGroupDisplayName(BuildTargetGroup.Standalone), "", "BuildSettings.Standalone",
NamedBuildTarget.Standalone, standaloneTarget, (int)StandaloneBuildSubtarget.Player, false, true));
// TODO: We should consider extend BuildTargetDiscovery to support named targets and subtargets,
// specially if at some point other platforms use them.
// The installed value is set by the linux, mac or win ExtensionModule.cs when they are loaded.
buildPlatformsList.Add(new BuildPlatformWithSubtarget("Dedicated Server", "", "BuildSettings.DedicatedServer",
NamedBuildTarget.Server, standaloneTarget, (int)StandaloneBuildSubtarget.Server, false, false));
foreach (var target in buildTargets)
{
if (!target.HasFlag(TargetAttributes.IsStandalonePlatform))
{
NamedBuildTarget namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(BuildPipeline.GetBuildTargetGroup(target.buildTargetPlatformVal));
buildPlatformsList.Add(new BuildPlatform(
BuildPipeline.GetBuildTargetGroupDisplayName(namedBuildTarget.ToBuildTargetGroup()),
target.iconName,
namedBuildTarget,
target.buildTargetPlatformVal,
hideInUi: target.HasFlag(TargetAttributes.HideInUI),
installed: BuildPipeline.GetPlaybackEngineDirectory(target.buildTargetPlatformVal, BuildOptions.None, false) != string.Empty));
}
}
foreach (var buildPlatform in buildPlatformsList)
{
buildPlatform.tooltip = buildPlatform.title.text + " settings";
}
buildPlatforms = buildPlatformsList.ToArray();
}
public BuildPlatform[] buildPlatforms;
public string GetBuildTargetDisplayName(BuildTargetGroup buildTargetGroup, BuildTarget target, int subtarget)
{
if (buildTargetGroup == BuildTargetGroup.Standalone && subtarget == (int)StandaloneBuildSubtarget.Server)
return GetBuildTargetDisplayName(NamedBuildTarget.Server, target);
return GetBuildTargetDisplayName(NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup), target);
}
public string GetBuildTargetDisplayName(NamedBuildTarget namedBuildTarget, BuildTarget target)
{
foreach (BuildPlatform cur in buildPlatforms)
{
if (cur.defaultTarget == target && cur.namedBuildTarget == namedBuildTarget)
return cur.title.text;
}
var suffix = namedBuildTarget == NamedBuildTarget.Server ? " Server" : "";
switch (target)
{
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return $"Windows{suffix}";
case BuildTarget.StandaloneOSX:
// Deprecated
#pragma warning disable 612, 618
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
#pragma warning restore 612, 618
return $"macOS{suffix}";
// Deprecated
#pragma warning disable 612, 618
case BuildTarget.StandaloneLinux:
case BuildTarget.StandaloneLinuxUniversal:
#pragma warning restore 612, 618
case BuildTarget.StandaloneLinux64:
return $"Linux{suffix}";
}
return "Unsupported Target";
}
public string GetModuleDisplayName(NamedBuildTarget namedBuildTarget, BuildTarget buildTarget)
{
return GetBuildTargetDisplayName(namedBuildTarget, buildTarget);
}
int BuildPlatformIndexFromNamedBuildTarget(NamedBuildTarget target)
{
for (int i = 0; i < buildPlatforms.Length; i++)
if (target == buildPlatforms[i].namedBuildTarget)
return i;
return -1;
}
public BuildPlatform BuildPlatformFromNamedBuildTarget(NamedBuildTarget target)
{
int index = BuildPlatformIndexFromNamedBuildTarget(target);
return index != -1 ? buildPlatforms[index] : null;
}
public List<BuildPlatform> GetValidPlatforms(bool includeMetaPlatforms)
{
List<BuildPlatform> platforms = new List<BuildPlatform>();
foreach (BuildPlatform bp in buildPlatforms)
if (bp.namedBuildTarget == NamedBuildTarget.Standalone ||
(bp.installed && BuildPipeline.IsBuildPlatformSupported(bp.defaultTarget)))
platforms.Add(bp);
return platforms;
}
public List<BuildPlatform> GetValidPlatforms()
{
return GetValidPlatforms(false);
}
}
}
| UnityCsReference/Editor/Mono/BuildPipeline/BuildPlatform.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipeline/BuildPlatform.cs",
"repo_id": "UnityCsReference",
"token_count": 3531
} | 284 |
// 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.Experimental
{
[Obsolete("BuildPipelineExperimental is no longer supported and will be removed")]
public static class BuildPipelineExperimental
{
public static string GetSessionIdForBuildTarget(BuildTarget target)
{
return BuildPipeline.GetSessionIdForBuildTarget(target, 0);
}
}
}
| UnityCsReference/Editor/Mono/BuildPipelineExperimental.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipelineExperimental.cs",
"repo_id": "UnityCsReference",
"token_count": 178
} | 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.Bindings;
namespace UnityEditor
{
// Target build platform.
// When adding new platform, read this first - https://confluence.hq.unity3d.com/display/DEV/Adding+new+platform
// When removing platform, read this first - https://confluence.hq.unity3d.com/display/DEV/Removing+platform
[NativeType("Runtime/Serialize/SerializationMetaFlags.h")]
public enum BuildTarget
{
// Build an OS X standalone (universal build, with x86_64 currently supported).
StandaloneOSX = 2,
[System.Obsolete("Use StandaloneOSX instead (UnityUpgradable) -> StandaloneOSX", true)]
StandaloneOSXUniversal = 3,
[System.Obsolete("StandaloneOSXIntel has been removed in 2017.3")]
StandaloneOSXIntel = 4,
// Build a Windows standalone.
StandaloneWindows = 5,
// *undocumented*
[System.Obsolete("WebPlayer has been removed in 5.4", true)]
WebPlayer = 6,
// *undocumented*
[System.Obsolete("WebPlayerStreamed has been removed in 5.4", true)]
WebPlayerStreamed = 7,
// Build an iOS player
iOS = 9,
// *undocumented*
[System.Obsolete("PS3 has been removed in >=5.5")]
PS3 = 10,
// *undocumented*
[System.Obsolete("XBOX360 has been removed in 5.5")]
XBOX360 = 11,
// was StandaloneBroadcom = 12,
// Build an Android .apk standalone app
Android = 13,
// was StandaloneGLESEmu = 14,
// was StandaloneGLES20Emu = 15,
// was NaCl = 16,
// Build a Linux standalone (i386 only).
[System.Obsolete("StandaloneLinux has been removed in 2019.2")]
StandaloneLinux = 17,
// Build a Windows x86_64 standalone.
StandaloneWindows64 = 19,
// *undocumented*
WebGL = 20,
// *undocumented*
WSAPlayer = 21,
// Build a Linux standalone (x86_64 only).
StandaloneLinux64 = 24,
// Build a Linux standalone (i386/x86_64 universal).
[System.Obsolete("StandaloneLinuxUniversal has been removed in 2019.2")]
StandaloneLinuxUniversal = 25,
[System.Obsolete("Use WSAPlayer with Windows Phone 8.1 selected")]
WP8Player = 26,
[System.Obsolete("StandaloneOSXIntel64 has been removed in 2017.3")]
StandaloneOSXIntel64 = 27,
[System.Obsolete("BlackBerry has been removed in 5.4")]
BlackBerry = 28,
[System.Obsolete("Tizen has been removed in 2017.3")]
Tizen = 29,
/// Build a Vita Standalone
/// SA: BuildPipeline.BuildPlayer.
[System.Obsolete("PSP2 is no longer supported as of Unity 2018.3")]
PSP2 = 30,
/// Build a PS4 Standalone
/// SA: BuildPipeline.BuildPlayer.
PS4 = 31,
/// Build a Unity PlayStation Mobile (PSM) application
/// SA: BuildPipeline.BuildPlayer.
[System.Obsolete("PSM has been removed in >= 5.3")]
PSM = 32,
/// Build an Xbox One Standalone
/// SA: BuildPipeline.BuildPlayer.
XboxOne = 33,
[System.Obsolete("SamsungTV has been removed in 2017.3")]
SamsungTV = 34,
/// Build a Nintendo 3DS application
/// SA: BuildPipeline.BuildPlayer.
[System.Obsolete("Nintendo 3DS support is unavailable since 2018.1")]
N3DS = 35,
/// Build a Wii U player
[System.Obsolete("Wii U support was removed in 2018.1")]
WiiU = 36,
tvOS = 37,
Switch = 38,
[System.Obsolete("Lumin has been removed in 2022.2")]
Lumin = 39,
[System.Obsolete("Stadia has been removed in 2023.1")]
Stadia = 40,
[System.Obsolete("CloudRendering is deprecated, please use LinuxHeadlessSimulation (UnityUpgradable) -> LinuxHeadlessSimulation", false)]
CloudRendering = 41,
LinuxHeadlessSimulation = 41, // LinuxHeadlessSimulation intenionally set to the same as CloudRendering
[System.Obsolete("GameCoreScarlett is deprecated, please use GameCoreXboxSeries (UnityUpgradable) -> GameCoreXboxSeries", false)]
GameCoreScarlett = 42,
GameCoreXboxSeries = 42, // GameCoreXboxSeries intentionally set to the same as GameCoreScarlett
GameCoreXboxOne = 43,
PS5 = 44,
EmbeddedLinux = 45,
QNX = 46,
VisionOS = 47,
// obsolete identifiers. We're using different values so that ToString() works.
[System.Obsolete("Use iOS instead (UnityUpgradable) -> iOS", true)]
iPhone = -1,
[System.Obsolete("BlackBerry has been removed in 5.4")]
BB10 = -1,
[System.Obsolete("Use WSAPlayer instead (UnityUpgradable) -> WSAPlayer", true)]
MetroPlayer = -1,
// *undocumented*
NoTarget = -2,
}
}
| UnityCsReference/Editor/Mono/BuildTarget.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildTarget.cs",
"repo_id": "UnityCsReference",
"token_count": 2031
} | 286 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor
{
[NativeHeader("Editor/Src/Utility/ChangeTracker.h")]
[RequiredByNativeCode]
internal struct ChangeTrackerHandle
{
IntPtr m_Handle;
internal static ChangeTrackerHandle AcquireTracker(UnityEngine.Object obj)
{
if (obj == null)
throw new ArgumentNullException("Not a valid unity engine object");
return new ChangeTrackerHandle() { m_Handle = Internal_AcquireTracker(obj) };
}
[FreeFunction("ChangeTrackerRegistry::AcquireTracker")]
private static extern IntPtr Internal_AcquireTracker(UnityEngine.Object o);
internal void ReleaseTracker()
{
if (m_Handle == IntPtr.Zero)
throw new ArgumentNullException("Not a valid handle, has it been released already?");
Internal_ReleaseTracker(m_Handle);
m_Handle = IntPtr.Zero;
}
[FreeFunction("ChangeTrackerRegistry::ReleaseTracker")]
private static extern void Internal_ReleaseTracker(IntPtr handle);
// returns true if object changed since last poll
internal bool PollForChanges()
{
if (m_Handle == IntPtr.Zero)
throw new ArgumentNullException("Not a valid handle, has it been released already?");
return Internal_PollChanges(m_Handle);
}
[FreeFunction("ChangeTrackerRegistry::PollChanges")]
private static extern bool Internal_PollChanges(IntPtr handle);
internal void ForceDirtyNextPoll()
{
if (m_Handle == IntPtr.Zero)
throw new ArgumentNullException("Not a valid handle, has it been released already?");
Internal_ForceUpdate(m_Handle);
}
[FreeFunction("ChangeTrackerRegistry::ForceUpdate")]
private static extern void Internal_ForceUpdate(IntPtr handle);
}
}
| UnityCsReference/Editor/Mono/ChangeTrackerHandle.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ChangeTrackerHandle.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 807
} | 287 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
// This file was introduced as part of the collab removal, it supports any versions of com.unity.collab-proxy under 1.17.7
// It allows for an error free upgrade by provinding mock classes for the removed ones.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using UnityEditor.Connect;
using UnityEditor.PackageManager;
using UnityEngine;
#pragma warning disable 0067
#pragma warning disable 0618
namespace UnityEditor.Collaboration
{
internal static class LogObsolete
{
static bool s_Initialized;
static bool s_NeedsLogging;
static Stopwatch s_Stopwatch = Stopwatch.StartNew();
internal static void Log()
{
if (!s_Initialized)
s_NeedsLogging = IsObsolete("com.unity.collab-proxy", "1.1");
s_Initialized = true;
if (!s_NeedsLogging)
return;
if (s_Stopwatch.ElapsedMilliseconds < 1000)
return;
UnityEngine.Debug.unityLogger.LogWarning(
"com.unity.collab-proxy",
"This version of the package is not supported, please upgrade to the latest version. https://unity.com/solutions/version-control");
s_Stopwatch.Restart();
}
internal static bool IsObsolete(string packageName, string version)
{
UnityEditor.PackageManager.PackageInfo package = null;
try
{
package = UnityEditor.PackageManager.PackageInfo.FindForPackageName(packageName);
}
catch
{
return false;
}
if (package == null)
return false;
if (package.version == null)
return false;
return package.version.StartsWith(version);
}
}
internal class Collab
{
static Collab s_instance = null;
public static Collab instance {
get
{
if (s_instance == null)
s_instance = new Collab();
LogObsolete.Log();
return s_instance;
}
}
Collab()
{
}
[Flags]
public enum Operation
{
Noop = 0,
Publish = 1 << 0,
Update = 1 << 1,
Revert = 1 << 2,
GoBack = 1 << 3,
Restore = 1 << 4,
Diff = 1 << 5,
ConflictDiff = 1 << 6,
Exclude = 1 << 7,
Include = 1 << 8,
ChooseMine = 1 << 9,
ChooseTheirs = 1 << 10,
ExternalMerge = 1 << 11,
}
[Flags]
public enum CollabStates : uint
{
kCollabNone = 0,
kCollabLocal = 1,
kCollabSynced = 1 << 1,
kCollabOutOfSync = 1 << 2,
kCollabIgnored = 1 << 3,
kCollabCheckedOutLocal = 1 << 4,
kCollabCheckedOutRemote = 1 << 5,
kCollabDeletedLocal = 1 << 6,
kCollabDeletedRemote = 1 << 7,
kCollabAddedLocal = 1 << 8,
kCollabAddedRemote = 1 << 9,
kCollabConflicted = 1 << 10,
kCollabMovedLocal = 1 << 11,
kCollabMovedRemote = 1 << 12,
kCollabUpdating = 1 << 13,
kCollabReadOnly = 1 << 14,
kCollabMetaFile = 1 << 15,
kCollabUseMine = 1 << 16,
kCollabUseTheir = 1 << 17,
kCollabMerged = 1 << 18,
kCollabPendingMerge = 1 << 19,
kCollabFolderMetaFile = 1 << 20,
KCollabContentChanged = 1 << 21,
KCollabContentConflicted = 1 << 22,
KCollabContentDeleted = 1 << 23,
kCollabInvalidState = 1 << 30,
kAnyLocalChanged = (kCollabAddedLocal | kCollabCheckedOutLocal | kCollabDeletedLocal | kCollabMovedLocal),
kAnyLocalEdited = (kCollabAddedLocal | kCollabCheckedOutLocal | kCollabMovedLocal),
kCollabAny = 0xFFFFFFFF
}
internal enum CollabStateID { None, Uninitialized, Initialized }
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(Collab collab){ return IntPtr.Zero; }
}
public event StateChangedDelegate StateChanged;
public event StateChangedDelegate RevisionUpdated;
public event RevisionChangedDelegate RevisionUpdated_V2;
public event StateChangedDelegate JobsCompleted;
public event ErrorDelegate ErrorOccurred;
public event SetErrorDelegate ErrorOccurred_V2;
public event ErrorDelegate ErrorCleared;
public event ChangeItemsChangedDelegate ChangeItemsChanged;
public event ChangeItemsChangedDelegate SelectedChangeItemsChanged;
public event StateChangedDelegate CollabInfoChanged;
public static int GetRevisionsData(bool withChanges, int startIndex, int numRevisions){ return 0; }
public static int GetSingleRevisionData(bool withChanges, string id){ return 0; }
public static RevisionsData PopulateRevisionsData(IntPtr nativeData){ return new RevisionsData(); }
public static Revision PopulateSingleRevisionData(IntPtr nativeData){ return new Revision(); }
public static ShowToolbarAtPositionDelegate ShowToolbarAtPosition = null;
public static IsToolbarVisibleDelegate IsToolbarVisible = null;
public static CloseToolbarDelegate CloseToolbar = null;
public static ShowHistoryWindowDelegate ShowHistoryWindow = null;
public static ShowChangesWindowDelegate ShowChangesWindow = null;
public static string[] clientType = Array.Empty<string>();
internal static string editorPrefCollabClientType = string.Empty;
public static string GetProjectClientType() { return string.Empty; }
public static void SetVersionControl(IVersionControl instance){}
internal static bool HasVersionControl(){ return false; }
internal static void ShowChangesWindowView(){}
internal static CollabStates GetAssetState(string assetGuid, string assetPath){ return (CollabStates)0; }
public static void OnSettingStatusChanged(CollabSettingType type, CollabSettingStatus status){}
public static bool InitializeSoftlocksViewController(){ return false; }
public static bool IsDiffToolsAvailable(){ return false; }
public static void SwitchToDefaultMode(){}
public static void OnProgressEnabledSettingStatusChanged(CollabSettingType type, CollabSettingStatus status){}
public CollabInfo collabInfo { get; }
public void SetSeat(bool value){}
public void RefreshSeatAvailabilityAsync(){}
public string GetProjectGUID(){ return string.Empty; }
public bool ShouldDoInitialCommit(){ return false; }
public void ShowDifferences(string path){}
public void SendNotification(){}
public void SetError(int errorCode){}
public void ClearError(int errorCode){}
public void ClearErrors(){}
public void ForceRefresh(bool refreshAssetDatabase){}
public void SetCollabEnabledForCurrentProject(bool enabled){}
public bool IsCollabEnabledForCurrentProject(){ return false; }
public bool IsAssetIgnored(string path){ return false; }
public bool ShouldTrackAsset(string path){ return false; }
public string GetProjectPath(){ return string.Empty; }
public bool IsConnected(){ return false; }
public bool AnyJobRunning(){ return false; }
public bool JobRunning(int a_jobID){ return false; }
public CollabStates GetAssetState(string guid){ return (CollabStates)0; }
public CollabStates GetSelectedAssetState(){ return (CollabStates)0; }
public CollabStateID GetCollabState(){ return (CollabStateID)0; }
public bool ValidateSelectiveCommit(){ return false; }
public void Disconnect(){}
public void CancelJobByType(int jobType, bool forceCancel){}
public void DoInitialCommit(){}
public void Update(string revisionID, bool updateToRevision){}
public void RevertFile(string path, bool forceOverwrite){}
public void RevertFiles(ChangeItem[] changeItems, bool forceOverwrite){}
public void LaunchConflictExternalMerge(string path){}
public void ShowConflictDifferences(string path){}
public void ResyncSnapshot(){}
public void GoBackToRevision(string revisionID, bool updateToRevision){}
public void ResyncToRevision(string revisionID){}
public Change[] GetCollabConflicts(){ return Array.Empty<Change>(); }
public void CheckConflictsResolvedExternal(){}
public bool AreTestsRunning(){ return false; }
public void SetTestsRunning(bool running){}
public void ClearAllFailures(){}
public void ClearNextOperationFailure(){}
public void ClearNextOperationFailureForFile(string path){}
public string GetGUIDForTests(){ return string.Empty; }
public void NewGUIDForTests(){}
public void FailNextOperation(Collab.Operation operation, int code){}
public void TimeOutNextOperation(Collab.Operation operation, int timeOutSec){}
public void FailNextOperationForFile(string path, Collab.Operation operation, int code){}
public void TimeOutNextOperationForFile(string path, Collab.Operation operation, int timeOutSec){}
public void TestPostSoftLockAsCollaborator(string projectGuid, string projectPath, string machineGuid, string assetGuid){}
public void TestClearSoftLockAsCollaborator(string projectGuid, string projectPath, string machineGuid, string softLockHash){}
internal bool GetErrorInternal(int errorFilter, out UnityErrorInfo info){ info = new UnityErrorInfo(); return false; }
public void Publish(string comment, bool useSelectedAssets, bool confirmMatchesPrevious){}
public void PublishAssetsAsync(string comment, ChangeItem[] changes){}
public void ClearSelectedChangesToPublish(){}
public void SendCollabInfoNotification(){}
public CollabFilters collabFilters = new CollabFilters();
public String projectBrowserSingleSelectionPath { get; set; }
public String projectBrowserSingleMetaSelectionPath { get; set; }
public string[] currentProjectBrowserSelection;
public void RefreshAvailableLocalChangesSynchronous(){}
public bool GetError(UnityConnect.UnityErrorFilter errorFilter, out UnityErrorInfo info){ info = new UnityErrorInfo(); return false; }
public void CancelJob(int jobType){}
public void UpdateEditorSelectionCache(){}
public CollabInfo GetCollabInfo(){ return new CollabInfo(); }
public void SaveAssets(){}
public void ShowInProjectBrowser(string filterString){}
public bool SetConflictsResolvedMine(string[] paths){ return false; }
public bool SetConflictsResolvedTheirs(string[] paths){ return false; }
public PublishInfo GetChangesToPublish() { return new PublishInfo(); }
public PublishInfo_V2 GetChangesToPublish_V2() { return new PublishInfo_V2(); }
public void SetChangesToPublish(ChangeItem[] changes){}
public ProgressInfo GetJobProgress(int jobId){ return new ProgressInfo(); }
}
internal enum CollabSettingType
{
InProgressEnabled = 0,
InProgressProjectEnabled = 1,
InProgressGlobalEnabled = 2
}
internal enum CollabSettingStatus
{
None = 0,
Available = 1
}
internal class CollabSettingsManager
{
public delegate void SettingStatusChanged(CollabSettingType type, CollabSettingStatus status);
public static Dictionary<CollabSettingType, SettingStatusChanged> statusNotifier = new Dictionary<CollabSettingType, SettingStatusChanged>();
static CollabSettingsManager(){}
public static bool IsAvailable(CollabSettingType type)
{
return false;
}
public static bool inProgressEnabled { get; }
}
internal class ProgressInfo
{
public enum ProgressType : uint
{
None = 0,
Count = 1,
Percent = 2,
Both = 3
}
public int jobId { get { return 0; } }
public string title { get { return string.Empty; } }
public string extraInfo { get { return string.Empty; } }
public int currentCount { get { return 0; } }
public int totalCount { get { return 0; } }
public bool completed { get { return true; } }
public bool cancelled { get { return false; } }
public bool canCancel { get { return false; } }
public string lastErrorString { get { return string.Empty; } }
public ulong lastError { get { return 0; } }
public int percentComplete { get{ return 0; } }
public bool isProgressTypeCount { get { return false; } }
public bool isProgressTypePercent { get { return false; } }
public bool errorOccured { get { return false; } }
}
internal class ChangeItem
{
public string Path { get; set; }
public Change.RevertableStates RevertableState { get; set; }
public string RelatedTo { get; set; }
public string RevisionId { get; set; }
public string Hash { get; set; }
public Collab.CollabStates State { get; set; }
public long Size { get; set; }
public string DownloadPath { get; set; }
public string FromPath { get; set; }
}
internal class PublishInfo
{
public Change[] changes;
public bool filter;
}
internal class PublishInfo_V2
{
public ChangeItem[] changes;
public bool filter;
}
internal class RevisionsResult
{
public List<Revision> Revisions = new List<Revision>();
public int RevisionsInRepo = -1;
public int Count { get { return 0; } }
public void Clear(){}
}
internal interface IRevisionsService
{
event RevisionsDelegate FetchRevisionsCallback;
void GetRevisions(int offset, int count);
string tipRevision { get; }
string currentUser { get; }
}
internal class RevisionsService : IRevisionsService
{
public event RevisionsDelegate FetchRevisionsCallback;
public event SingleRevisionDelegate FetchSingleRevisionCallback;
public string tipRevision { get { return string.Empty; } }
public string currentUser { get { return string.Empty; } }
public RevisionsService(Collab collabInstance, UnityConnect connectInstance)
{
}
public void GetRevisions(int offset, int count){}
public void GetRevision(string revId){}
}
internal class Change
{
public enum RevertableStates : uint
{
Revertable = 1 << 0,
NotRevertable = 1 << 1,
Revertable_File = 1 << 2,
Revertable_Folder = 1 << 3,
Revertable_EmptyFolder = 1 << 4,
NotRevertable_File = 1 << 5,
NotRevertable_Folder = 1 << 6,
NotRevertable_FileAdded = 1 << 7,
NotRevertable_FolderAdded = 1 << 8,
NotRevertable_FolderContainsAdd = 1 << 9,
InvalidRevertableState = (uint)1 << 31
}
public string path { get { return string.Empty; } }
public Collab.CollabStates state { get { return (Collab.CollabStates)0; } }
public bool isRevertable { get { return false; } }
public RevertableStates revertableState { get { return (RevertableStates)0; } }
public string relatedTo { get { return string.Empty; } }
public bool isMeta { get { return false; } }
public bool isConflict { get { return false; } }
public bool isFolderMeta { get { return false; } }
public bool isResolved { get { return false; } }
public string localStatus { get { return string.Empty; } }
public string remoteStatus { get { return string.Empty; } }
public string resolveStatus { get { return string.Empty; } }
internal bool HasState(Collab.CollabStates states)
{
return false;
}
internal bool HasRevertableState(RevertableStates revertableStates)
{
return false;
}
}
internal abstract class AbstractFilters
{
public List<string[]> filters { get; set;}
public abstract void InitializeFilters();
public bool ContainsSearchFilter(string name, string searchString){ return false; }
public void ShowInFavoriteSearchFilters(){}
public void HideFromFavoriteSearchFilters(){}
}
internal class CollabFilters : AbstractFilters
{
public override void InitializeFilters(){}
public void ShowInProjectBrowser(string filterString){}
public void OnCollabStateChanged(CollabInfo info){}
}
internal delegate void StateChangedDelegate(CollabInfo info);
internal delegate void RevisionChangedDelegate(CollabInfo info, string rev, string action);
internal delegate void SetErrorDelegate(UnityErrorInfo error);
internal delegate void ErrorDelegate();
internal delegate bool ShowToolbarAtPositionDelegate(Rect screenRect);
internal delegate bool IsToolbarVisibleDelegate();
internal delegate void ShowHistoryWindowDelegate();
internal delegate void ShowChangesWindowDelegate();
internal delegate void CloseToolbarDelegate();
internal delegate void ChangesChangedDelegate(Change[] changes, bool isFiltered);
internal delegate void ChangeItemsChangedDelegate(ChangeItem[] changes, bool isFiltered);
delegate void RevisionsDelegate(RevisionsResult revisionsResult);
delegate void SingleRevisionDelegate(Revision? revision);
internal struct CollabInfo
{
public bool ready { get { return true; } }
public bool update { get { return false; } }
public bool publish { get { return false; } }
public bool inProgress { get { return false; } }
public bool maintenance { get { return false; } }
public bool conflict { get { return false; } }
public bool refresh { get { return false; } }
public bool seat { get { return false; } }
public string tip { get { return string.Empty; } }
public bool Equals(CollabInfo other){ return false; }
}
internal struct ChangeAction
{
public ChangeAction(string path = "", string action = ""){}
public string path { get { return string.Empty; } }
public string action { get { return string.Empty; } }
}
internal struct Revision
{
internal Revision(string revisionID = "", string authorName = "", string author = "", string comment = "", string reference = "", ulong timeStamp = 0, bool isObtained = false, ChangeAction[] entries = null, CloudBuildStatus[] buildStatuses = null){}
public string authorName { get { return string.Empty; } }
public string author { get { return string.Empty; } }
public string comment { get { return string.Empty; } }
public string revisionID { get { return string.Empty; } }
public string reference { get { return string.Empty; } }
public ulong timeStamp { get { return 0; } }
public bool isObtained { get { return false; } }
public ChangeAction[] entries { get { return Array.Empty<ChangeAction>(); } }
public CloudBuildStatus[] buildStatuses { get { return Array.Empty<CloudBuildStatus>(); } }
}
internal struct CloudBuildStatus
{
internal CloudBuildStatus(string platform = "", bool complete = false, bool success = false){}
public string platform { get { return string.Empty; } }
public bool complete { get { return false; } }
public bool success { get { return false; } }
}
internal struct RevisionData
{
public string id;
public int index;
public DateTime timeStamp;
public string authorName;
public string comment;
public bool obtained;
public bool current;
public bool inProgress;
public bool enabled;
public BuildState buildState;
public int buildFailures;
public ICollection<ChangeData> changes;
public int changesTotal;
public bool changesTruncated;
}
internal struct RevisionsData
{
public int RevisionsInRepo {get { return 0; }}
public int RevisionOffset {get { return 0; }}
public int ReturnedRevisions {get { return 0; }}
public Revision[] Revisions {get { return Array.Empty<Revision>(); }}
}
internal enum HistoryState
{
Error,
Offline,
Maintenance,
LoggedOut,
NoSeat,
Disabled,
Waiting,
Ready,
}
internal enum BuildState
{
None,
Configure,
Success,
Failed,
InProgress,
}
internal struct ChangeData
{
public string path;
public string action;
}
}
| UnityCsReference/Editor/Mono/Collab/CollabToUVCSBridge.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Collab/CollabToUVCSBridge.cs",
"repo_id": "UnityCsReference",
"token_count": 8296
} | 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 UnityEngine;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal static class CutBoard
{
internal static bool hasCutboardData { get { return m_GOCutboard != null && m_GOCutboard.Length > 0; } }
private static Transform[] m_GOCutboard;
private static Object[] m_SelectedObjects;
private static HashSet<Transform> m_CutAffectedGOs = new HashSet<Transform>();
private const string kCutAndPaste = "Cut And Paste";
private static Stage m_StageCutWasPerformedIn;
internal static void CutGO()
{
m_GOCutboard = Selection.transforms;
m_SelectedObjects = Selection.objects;
// Selection.transform does not provide correct list order, so we have to do it manually
m_GOCutboard = m_GOCutboard.ToList().OrderBy(g => Array.IndexOf(m_SelectedObjects, g.gameObject)).ToArray();
// Return if nothing selected
if (!hasCutboardData)
return;
m_StageCutWasPerformedIn = StageUtility.GetStage(m_GOCutboard[0].gameObject);
// If cut gameObject is prefab, get its root transform
for (int i = 0; i < m_GOCutboard.Length; i++)
{
if (PrefabUtility.GetPrefabAssetType(m_GOCutboard[i].gameObject) != PrefabAssetType.NotAPrefab)
{
m_GOCutboard[i] = PrefabUtility.GetOutermostPrefabInstanceRoot(m_GOCutboard[i].gameObject)?.transform;
}
}
// Cut gameObjects should be visually marked as cut, so adding them to the hashset
m_CutAffectedGOs.Clear();
foreach (var item in m_GOCutboard)
{
m_CutAffectedGOs.Add(item);
AddChildrenToHashset(item);
}
// Clean pasteboard when cutting gameObjects
Unsupported.ClearPasteboard();
}
internal static bool CanGameObjectsBePasted()
{
return hasCutboardData && AreCutAndPasteStagesSame();
}
internal static void PasteGameObjects(Transform fallbackParent, bool worldPositionStays)
{
if (!AreCutAndPasteStagesSame())
return;
// Paste as a sibling of a active transform
if (Selection.activeTransform != null)
{
PasteAsSiblings(Selection.activeTransform, worldPositionStays);
}
// If nothing selected, paste as child of the fallback parent if present
else if (fallbackParent != null)
{
PasteAsChildren(fallbackParent, worldPositionStays);
}
// Otherwise, move to the scene of the active object
else
{
Scene targetScene = EditorSceneManager.GetSceneByHandle(Selection.activeInstanceID);
PasteToScene(targetScene, fallbackParent);
}
}
internal static void PasteAsChildren(Transform parent, bool worldPositionStays)
{
if (m_GOCutboard == null || !AreCutAndPasteStagesSame())
return;
foreach (var go in m_GOCutboard)
{
if (go != null && CanSetParent(go, parent))
{
SetParent(go, parent, worldPositionStays);
}
}
Selection.objects = m_SelectedObjects;
// Reset cutBoard and greyed out gameObject list after paste
Reset();
}
private static void PasteAsSiblings(Transform target, bool worldPositionStays)
{
foreach (var go in m_GOCutboard)
{
if (go != null && CanSetParent(go, target))
{
if (target.parent != null)
SetParent(go, target.parent, worldPositionStays);
else
MoveToScene(go, target.gameObject.scene);
}
}
Selection.objects = m_SelectedObjects;
// Reset cutBoard and greyed out gameObject list after paste
Reset();
}
internal static void PasteToScene(Scene targetScene, Transform targetGO)
{
foreach (var go in m_GOCutboard)
{
if (go != null && CanSetParent(go, targetGO))
{
MoveToScene(go, targetScene);
}
}
Selection.objects = m_SelectedObjects;
// Reset cutBoard and greyed out gameObject list after paste
Reset();
}
private static void SetParent(Transform go, Transform parent, bool worldPositionStays)
{
Undo.SetTransformParent(go, parent, worldPositionStays, kCutAndPaste);
go.SetAsLastSibling();
}
private static void MoveToScene(Transform current, Scene target)
{
if (current == null)
return;
Undo.SetTransformParent(current, null, kCutAndPaste);
if (target.isLoaded)
{
Undo.MoveGameObjectToScene(current.gameObject, target, kCutAndPaste);
}
current.SetAsLastSibling();
}
private static void AddChildrenToHashset(Transform parent)
{
for (int i = 0; i < parent.childCount; i++)
{
Transform childTransform = parent.transform.GetChild(i);
m_CutAffectedGOs.Add(childTransform);
if (childTransform.childCount > 0)
{
AddChildrenToHashset(childTransform);
}
}
}
internal static bool IsGameObjectPartOfCutAndPaste(GameObject gameObject)
{
if (gameObject == null || !hasCutboardData)
return false;
var transform = gameObject.transform;
if (transform == null)
return false;
if (m_CutAffectedGOs.Contains(transform))
return true;
return false;
}
internal static void Reset()
{
m_SelectedObjects = null;
m_GOCutboard = null;
m_CutAffectedGOs.Clear();
}
internal static bool AreCutAndPasteStagesSame()
{
return m_StageCutWasPerformedIn == StageUtility.GetCurrentStage();
}
private static bool CanSetParent(Transform transform, Transform target)
{
bool canSetParent = transform != target;
if (target != null)
canSetParent = canSetParent && !transform.IsChildOf(target) && !target.IsChildOf(transform);
if (SubSceneGUI.IsSubSceneHeader(transform.gameObject))
canSetParent = canSetParent && !SubSceneGUI.IsChildOrSameAsOtherTransform(transform, target) && !SubSceneGUI.IsChildOrSameAsOtherTransform(target, transform);
return canSetParent;
}
}
}
| UnityCsReference/Editor/Mono/CutBoard.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/CutBoard.cs",
"repo_id": "UnityCsReference",
"token_count": 3476
} | 289 |
// 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.Reflection;
using UnityEditor.Scripting.ScriptCompilation;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityEditor
{
// Main Application class.
[NativeHeader("Editor/Mono/EditorApplication.bindings.h")]
[NativeHeader("Editor/Src/ScriptCompilation/ScriptCompilationPipeline.h")]
[NativeHeader("Runtime/BaseClasses/TagManager.h")]
[NativeHeader("Runtime/Camera/RenderSettings.h")]
[NativeHeader("Runtime/Input/TimeManager.h")]
[NativeHeader("Editor/Src/ProjectVersion.h")]
[StaticAccessor("EditorApplicationBindings", StaticAccessorType.DoubleColon)]
public sealed partial class EditorApplication
{
internal static extern string kLastOpenedScene
{
[NativeMethod("GetLastOpenedScenePref")]
get;
}
// Load the level at /path/ in play mode.
[Obsolete("Use EditorSceneManager.LoadSceneInPlayMode instead.")]
public static void LoadLevelInPlayMode(string path)
{
LoadSceneParameters parameters = new LoadSceneParameters {loadSceneMode = LoadSceneMode.Single};
EditorSceneManager.LoadSceneInPlayMode(path, parameters);
}
// Load the level at /path/ additively in play mode.
[Obsolete("Use EditorSceneManager.LoadSceneInPlayMode instead.")]
public static void LoadLevelAdditiveInPlayMode(string path)
{
LoadSceneParameters parameters = new LoadSceneParameters {loadSceneMode = LoadSceneMode.Additive};
EditorSceneManager.LoadSceneInPlayMode(path, parameters);
}
// Load the level at /path/ in play mode asynchronously.
[Obsolete("Use EditorSceneManager.LoadSceneAsyncInPlayMode instead.")]
public static AsyncOperation LoadLevelAsyncInPlayMode(string path)
{
LoadSceneParameters parameters = new LoadSceneParameters {loadSceneMode = LoadSceneMode.Single};
return EditorSceneManager.LoadSceneAsyncInPlayMode(path, parameters);
}
// Load the level at /path/ additively in play mode asynchronously.
[Obsolete("Use EditorSceneManager.LoadSceneAsyncInPlayMode instead.")]
public static AsyncOperation LoadLevelAdditiveAsyncInPlayMode(string path)
{
LoadSceneParameters parameters = new LoadSceneParameters {loadSceneMode = LoadSceneMode.Additive};
return EditorSceneManager.LoadSceneAsyncInPlayMode(path, parameters);
}
// Open another project.
public static void OpenProject(string projectPath, params string[] args)
{
OpenProjectInternal(projectPath, args);
}
private static extern void OpenProjectInternal(string projectPath, string[] args);
internal static extern void OpenFileGeneric(string path);
// Saves all serializable assets that have not yet been written to disk (eg. Materials)
[System.Obsolete("Use AssetDatabase.SaveAssets instead (UnityUpgradable) -> AssetDatabase.SaveAssets()", true)]
public static void SaveAssets() {}
// Is editor currently in play mode?
public static extern bool isPlaying
{
get;
set;
}
public static void EnterPlaymode()
{
isPlaying = true;
}
public static void ExitPlaymode()
{
isPlaying = false;
}
// Is editor either currently in play mode, or about to switch to it? (RO)
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
public static extern bool isPlayingOrWillChangePlaymode
{
[NativeMethod("IsPlayingOrWillEnterExitPlaymode")]
get;
}
// Perform a single frame step.
[StaticAccessor("GetApplication().GetPlayerLoopController()", StaticAccessorType.Dot)]
public static extern void Step();
// Is editor currently paused?
[StaticAccessor("GetApplication().GetPlayerLoopController()", StaticAccessorType.Dot)]
public static extern bool isPaused
{
[NativeMethod("IsPaused")]
get;
[NativeMethod("SetPaused")]
set;
}
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern bool IsInitialized();
// Is editor currently compiling scripts? (RO)
public static bool isCompiling => EditorCompilationInterface.IsCompiling();
// Is editor currently updating? (RO)
public static extern bool isUpdating
{
get;
}
// Is remote connected to a client app?
public static extern bool isRemoteConnected
{
get;
}
[Obsolete("ScriptingRuntimeVersion has been deprecated in 2019.3 due to the removal of legacy mono")]
public static ScriptingRuntimeVersion scriptingRuntimeVersion
{
get { return ScriptingRuntimeVersion.Latest; }
}
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern string GetLicenseType();
// Prevents loading of assemblies when it is inconvenient.
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
public static extern void LockReloadAssemblies();
// Must be called after LockReloadAssemblies, to reenable loading of assemblies.
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
public static extern void UnlockReloadAssemblies();
// Check if assemblies are unlocked.
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern bool CanReloadAssemblies();
private static extern bool ExecuteMenuItemInternal(string menuItemPath, bool logErrorOnUnfoundItem);
// Invokes the menu item in the specified path.
public static bool ExecuteMenuItem(string menuItemPath)
{
var sanitizedPath = MenuService.SanitizeMenuItemName(menuItemPath);
var isDefaultMode = ModeService.currentId == ModeService.k_DefaultModeId;
var result = ExecuteMenuItemInternal(sanitizedPath, isDefaultMode);
if (result)
return true;
if (!isDefaultMode)
{
// Check if the menu was found first. If so, it means that the menu just
// didn't pass validation. No need to check further.
if (Menu.MenuItemExists(sanitizedPath))
return false;
var menuItems = TypeCache.GetMethodsWithAttribute<MenuItem>();
MethodInfo validateItem = null;
MethodInfo executeItem = null;
foreach (var item in menuItems)
{
MenuItem itemData = (MenuItem)item.GetCustomAttributes(typeof(MenuItem), false)[0];
var hotKeyIndex = Menu.FindHotkeyStartIndex(itemData.menuItem);
var hasHotkey = hotKeyIndex != -1 && hotKeyIndex != itemData.menuItem.Length;
bool matches;
if (!hasHotkey)
{
matches = itemData.menuItem == sanitizedPath;
}
else
{
var stringView = itemData.menuItem.AsSpan(0, hotKeyIndex);
stringView = stringView.TrimEnd();
matches = stringView == sanitizedPath;
}
if (!matches)
continue;
if (itemData.validate)
validateItem = item;
else
executeItem = item;
if (validateItem != null && executeItem != null)
break;
}
if (validateItem != null)
{
if (!ExecuteMenuItem(validateItem, true))
return false;
}
if (executeItem != null)
{
return ExecuteMenuItem(executeItem, false);
}
Debug.LogError($"ExecuteMenuItem failed because there is no menu named '{menuItemPath}'");
}
return false;
}
static bool ExecuteMenuItem(MethodInfo menuMethodInfo, bool validate)
{
if (menuMethodInfo.GetParameters().Length == 0)
{
var result = menuMethodInfo.Invoke(null, new object[0]);
return !validate || (bool)result;
}
if (menuMethodInfo.GetParameters()[0].ParameterType == typeof(MenuCommand))
{
var result = menuMethodInfo.Invoke(null, new[] { new MenuCommand(null) });
return !validate || (bool)result;
}
return false;
}
// Validates the menu item in the specific path
internal static extern bool ValidateMenuItem(string menuItemPath);
// Like ExecuteMenuItem, but applies action to specified GameObjects if the menu action supports it.
internal static extern bool ExecuteMenuItemOnGameObjects(string menuItemPath, GameObject[] objects);
// Like ExecuteMenuItem, but applies action to specified GameObjects if the menu action supports it.
internal static extern bool ExecuteMenuItemWithTemporaryContext(string menuItemPath, Object[] objects);
// Path to the Unity editor contents folder (RO)
public static extern string applicationContentsPath
{
[FreeFunction("GetApplicationContentsPath", IsThreadSafe = true)]
get;
}
// Returns the path to the Unity editor application (RO)
public static extern string applicationPath
{
[FreeFunction("GetApplicationPath", IsThreadSafe = true)]
get;
}
// Returns true if resources are being built
internal static extern bool isBuildingAnyResources
{
[FreeFunction("IsBuildingAnyResources")]
get;
}
// Returns true if the Package Manager is disabled
internal static extern bool isPackageManagerDisabled
{
[FreeFunction("IsPackageManagerDisabled")]
get;
}
public static extern bool isCreateFromTemplate
{
[FreeFunction("IsCreateFromTemplate")]
get;
}
internal static extern string userJavascriptPackagesPath
{
get;
}
public static extern bool isTemporaryProject
{
[FreeFunction("IsTemporaryProject")]
get;
}
[NativeThrows]
public static extern void SetTemporaryProjectKeepPath(string path);
// Exit the Unity editor application.
public static extern void Exit(int returnValue);
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern void SetSceneRepaintDirty();
public static void QueuePlayerLoopUpdate() { SetSceneRepaintDirty(); }
internal static extern void UpdateSceneIfNeeded();
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
public static extern void UpdateMainWindowTitle();
// Plays system beep sound.
[FreeFunction("UnityBeep")]
public static extern void Beep();
internal static extern Object tagManager
{
[FreeFunction]
get;
}
internal static extern Object renderSettings
{
[FreeFunction]
get;
}
// The time since the editor was started (RO)
public static extern double timeSinceStartup
{
[FreeFunction]
get;
}
internal static extern string windowTitle
{
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
get;
}
internal static extern void CloseAndRelaunch(string[] arguments);
internal static extern void RequestCloseAndRelaunchWithCurrentArguments();
// Triggers the editor to restart, after which all scripts will be recompiled.
internal static void RestartEditorAndRecompileScripts()
{
// Clear the script assemblies so we compile after the restart.
EditorCompilationInterface.Instance.DeleteScriptAssemblies();
RequestCloseAndRelaunchWithCurrentArguments();
}
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern void FileMenuNewScene();
[ThreadSafe]
internal static extern void SignalTick();
[StaticAccessor("GetApplication()", StaticAccessorType.Dot)]
internal static extern void UpdateInteractionModeSettings();
internal static extern void UpdateTooltipsInPlayModeSettings();
[FreeFunction("GetProjectVersion().Write")]
internal static extern void WriteVersion();
}
}
| UnityCsReference/Editor/Mono/EditorApplication.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorApplication.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 5543
} | 290 |
// 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 UnityEngine.Scripting;
namespace UnityEditor
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal sealed partial class EditorHeaderItemAttribute : CallbackOrderAttribute
{
public EditorHeaderItemAttribute(Type targetType, int priority = 1)
{
TargetType = targetType;
m_CallbackOrder = priority;
}
public Type TargetType;
[RequiredSignature]
static bool SignatureBool(Rect rectangle, UnityEngine.Object[] targetObjets) { throw new InvalidOperationException(); }
}
}
| UnityCsReference/Editor/Mono/EditorHeaderItemAttribute.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorHeaderItemAttribute.cs",
"repo_id": "UnityCsReference",
"token_count": 262
} | 291 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum QNXOsVersion
{
[System.Obsolete("Neutrino RTOS 7.0 has been removed in 2023.2")]
Neutrino70 = 0,
[UnityEngine.InspectorName("Neutrino RTOS 7.1")]
Neutrino71 = 1,
}
}
| UnityCsReference/Editor/Mono/EditorUserBuildSettingsQNX.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorUserBuildSettingsQNX.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 201
} | 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine.LightTransport
{
[DebuggerDisplay("BufferID({Value})")]
public struct BufferID : IEquatable<BufferID>
{
public UInt64 Value;
public BufferID(UInt64 value)
{
Value = value;
}
public BufferSlice<T> Slice<T>(UInt64 offset = 0)
where T : struct
{
return new BufferSlice<T>(this, offset);
}
// Value type semantics
public override int GetHashCode() => Value.GetHashCode();
public bool Equals(BufferID other) => other.Value == Value;
public override bool Equals(object obj) => obj is BufferID other && Equals(other);
public static bool operator ==(BufferID a, BufferID b) => a.Equals(b);
public static bool operator !=(BufferID a, BufferID b) => !a.Equals(b);
}
[DebuggerDisplay("BufferSlice(Id: {Id.Value}, Offset: {Offset})")]
public struct BufferSlice<T> : IEquatable<BufferSlice<T>>
where T : struct
{
public BufferSlice(BufferID id, UInt64 offset)
{
Id = id;
Offset = offset;
}
public BufferID Id;
public UInt64 Offset;
public BufferSlice<U> SafeReinterpret<U>()
where U : struct
{
if (!UnsafeUtility.IsBlittable<U>())
throw new ArgumentException($"Type {typeof(U)} must be blittable. {UnsafeUtility.GetReasonForTypeNonBlittable(typeof(U))}.");
int oldSize = UnsafeUtility.SizeOf<T>();
int newSize = UnsafeUtility.SizeOf<U>();
if (oldSize % newSize != 0)
throw new ArgumentException($"Type {typeof(T)} size must be a multiple of {typeof(U)} size.");
return UnsafeReinterpret<U>();
}
public unsafe BufferSlice<U> UnsafeReinterpret<U>()
where U : struct
{
int oldSize = UnsafeUtility.SizeOf<T>();
int newSize = UnsafeUtility.SizeOf<U>();
UInt64 newOffset = (Offset * (UInt64)oldSize) / (UInt64)newSize;
return new BufferSlice<U>(Id, newOffset);
}
// Value type semantics
public override int GetHashCode() => HashCode.Combine(Id, Offset);
public bool Equals(BufferSlice<T> other) => other.Id == Id && other.Offset == Offset;
public override bool Equals(object obj) => obj is BufferSlice<T> other && Equals(other);
public static bool operator ==(BufferSlice<T> a, BufferSlice<T> b) => a.Equals(b);
public static bool operator !=(BufferSlice<T> a, BufferSlice<T> b) => !a.Equals(b);
}
[DebuggerDisplay("EventID({Value})")]
public struct EventID : IEquatable<EventID>
{
public UInt64 Value;
public EventID(UInt64 value)
{
Value = value;
}
// Value type semantics
public override int GetHashCode() => Value.GetHashCode();
public bool Equals(EventID other) => other.Value == Value;
public override bool Equals(object obj) => obj is EventID other && Equals(other);
public static bool operator ==(EventID a, EventID b) => a.Equals(b);
public static bool operator !=(EventID a, EventID b) => !a.Equals(b);
}
/// <summary>
/// Buffer and command queue abstraction layer hiding the underlying storage
/// and compute architecture (CPU or GPU with unified or dedicated memory).
/// </summary>
public interface IDeviceContext : IDisposable
{
bool Initialize();
BufferID CreateBuffer(UInt64 size);
void DestroyBuffer(BufferID id);
EventID WriteBuffer<T>(BufferSlice<T> dst, NativeArray<T> src) where T : struct;
EventID ReadBuffer<T>(BufferSlice<T> src, NativeArray<T> dst) where T : struct;
bool IsCompleted(EventID id);
bool Wait(EventID id);
bool Flush();
}
[StructLayout(LayoutKind.Sequential)]
public class ReferenceContext : IDeviceContext
{
private Dictionary<BufferID, NativeArray<byte>> buffers = new();
private uint nextFreeBufferId;
private uint nextFreeEventId;
public bool Initialize()
{
return true;
}
public void Dispose()
{
foreach (var entry in buffers)
{
Debug.Assert(entry.Value.IsCreated, "A buffer was unexpectedly not created.");
entry.Value.Dispose();
}
}
public BufferID CreateBuffer(UInt64 size)
{
Debug.Assert(size != 0, "Buffer size cannot be zero.");
var buffer = new NativeArray<byte>((int)size, Allocator.Persistent);
var idInteger = nextFreeBufferId++;
var id = new BufferID(idInteger);
buffers[id] = buffer;
return id;
}
public void DestroyBuffer(BufferID id)
{
Debug.Assert(buffers.ContainsKey(id), "Invalid buffer ID given.");
buffers[id].Dispose();
buffers.Remove(id);
}
public EventID WriteBuffer<T>(BufferSlice<T> dst, NativeArray<T> src)
where T : struct
{
Debug.Assert(buffers.ContainsKey(dst.Id), "Invalid buffer ID given.");
var dstBuffer = buffers[dst.Id].Reinterpret<T>(1);
dstBuffer.GetSubArray((int)dst.Offset, dstBuffer.Length - (int)dst.Offset).CopyFrom(src);
return new EventID();
}
public EventID ReadBuffer<T>(BufferSlice<T> src, NativeArray<T> dst)
where T : struct
{
Debug.Assert(buffers.ContainsKey(src.Id), "Invalid buffer ID given.");
var srcBuffer = buffers[src.Id].Reinterpret<T>(1);
dst.CopyFrom(srcBuffer.GetSubArray((int)src.Offset, srcBuffer.Length - (int)src.Offset));
return new EventID { Value = nextFreeEventId++ };
}
public bool IsCompleted(EventID id)
{
return true;
}
public bool Wait(EventID id)
{
return true;
}
public NativeArray<byte> GetNativeArray(BufferID id)
{
return buffers[id];
}
public bool Flush()
{
return true;
}
}
}
| UnityCsReference/Editor/Mono/GI/DeviceContext.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GI/DeviceContext.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2897
} | 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;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEditor.LightBaking;
using UnityEngine.Rendering;
namespace UnityEngine.LightTransport
{
public interface IProbeIntegrator : IDisposable
{
public enum ResultType : uint
{
Success = 0,
Cancelled,
JobFailed,
OutOfMemory,
InvalidInput,
LowLevelAPIFailure,
IOFailed,
Undefined
}
public struct Result
{
public Result(ResultType _type, String _message)
{
type = _type;
message = _message;
}
public ResultType type;
public String message;
public override string ToString()
{
if (message.Length == 0)
return $"Result type: '{type}'";
else
return $"Result type: '{type}', message: '{message}'";
}
}
public void Prepare(IDeviceContext context, IWorld world, BufferSlice<Vector3> positions, float pushoff, int bounceCount);
public void SetProgressReporter(BakeProgressState progress);
public Result IntegrateDirectRadiance(IDeviceContext context, int positionOffset, int positionCount, int sampleCount,
bool ignoreDirectEnvironment, BufferSlice<SphericalHarmonicsL2> radianceEstimateOut);
public Result IntegrateIndirectRadiance(IDeviceContext context, int positionOffset, int positionCount, int sampleCount,
bool ignoreIndirectEnvironment, BufferSlice<SphericalHarmonicsL2> radianceEstimateOut);
public Result IntegrateValidity(IDeviceContext context, int positionOffset, int positionCount, int sampleCount, BufferSlice<float> validityEstimateOut);
}
internal class WintermuteProbeIntegrator : IProbeIntegrator
{
private IntegrationContext _integrationContext;
private BufferSlice<Vector3> _positions;
private float _pushoff;
private int _bounceCount;
private BakeProgressState _progress;
private const int SizeOfFloat = 4;
private const int SHL2RGBElements = 3 * 9;
private const int SizeOfSHL2 = SizeOfFloat * SHL2RGBElements;
private const int SizeOfVector3 = SizeOfFloat * 3;
public void Prepare(IDeviceContext context, IWorld world, BufferSlice<Vector3> positions, float pushoff, int bounceCount)
{
Debug.Assert(world is WintermuteWorld);
var wmWorld = world as WintermuteWorld;
_integrationContext = wmWorld.GetIntegrationContext();
_positions = positions;
_pushoff = pushoff;
_bounceCount = bounceCount;
}
public void SetProgressReporter(BakeProgressState progress)
{
_progress = progress;
}
public unsafe IProbeIntegrator.Result IntegrateDirectRadiance(IDeviceContext context, int positionOffset, int positionCount, int sampleCount,
bool ignoreDirectEnvironment, BufferSlice<SphericalHarmonicsL2> radianceEstimateOut)
{
Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else.");
var wmContext = context as WintermuteContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
var positionsPtr = (Vector3*)positions.GetUnsafePtr();
using var radianceBuffer = new NativeArray<Rendering.SphericalHarmonicsL2>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* shPtr = NativeArrayUnsafeUtility.GetUnsafePtr(radianceBuffer);
int directSampleCount = sampleCount;
int giSampleCount = 0;
int envSampleCount = 0;
const bool ignoreIndirectEnvironment = true;
var lightBakerResult = LightBaker.IntegrateProbeDirectRadianceWintermute(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, ignoreDirectEnvironment, ignoreIndirectEnvironment, wmContext, _progress, shPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(radianceEstimateOut, radianceBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write radiance to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write radiance to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public unsafe IProbeIntegrator.Result IntegrateIndirectRadiance(IDeviceContext context,
int positionOffset, int positionCount, int sampleCount, bool ignoreIndirectEnvironment,
BufferSlice<SphericalHarmonicsL2> radianceEstimateOut)
{
Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else.");
var wmContext = context as WintermuteContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
var positionsPtr = (Vector3*)NativeArrayUnsafeUtility.GetUnsafePtr(positions);
using var radianceBuffer = new NativeArray<Rendering.SphericalHarmonicsL2>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* shPtr = NativeArrayUnsafeUtility.GetUnsafePtr(radianceBuffer);
int directSampleCount = 0;
const bool ignoreDirectEnvironment = false;
int giSampleCount = sampleCount;
int envSampleCount = ignoreIndirectEnvironment ? 0 : sampleCount;
var lightBakerResult = LightBaker.IntegrateProbeIndirectRadianceWintermute(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, ignoreDirectEnvironment, ignoreIndirectEnvironment, wmContext, _progress, shPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(radianceEstimateOut, radianceBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write radiance to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write radiance to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public unsafe IProbeIntegrator.Result IntegrateValidity(IDeviceContext context,
int positionOffset, int positionCount, int sampleCount, BufferSlice<float> validityEstimateOut)
{
Debug.Assert(context is WintermuteContext, "Expected RadeonRaysContext but got something else.");
var wmContext = context as WintermuteContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
void* positionsPtr = NativeArrayUnsafeUtility.GetUnsafePtr(positions);
using var validityBuffer = new NativeArray<float>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* validityPtr = NativeArrayUnsafeUtility.GetUnsafePtr(validityBuffer);
int directSampleCount = 0;
int giSampleCount = sampleCount;
int envSampleCount = 0;
var lightBakerResult = LightBaker.IntegrateProbeValidityWintermute(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, wmContext, _progress, validityPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(validityEstimateOut, validityBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write validity to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write validity to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public void Dispose()
{
}
}
public class RadeonRaysProbeIntegrator : IProbeIntegrator
{
private IntegrationContext _integrationContext;
private BufferSlice<Vector3> _positions;
private float _pushoff;
private int _bounceCount;
BakeProgressState _progress = null;
const int SizeOfFloat = 4;
const int SHL2RGBElements = 3 * 9;
const int SizeOfSHL2 = SizeOfFloat * SHL2RGBElements;
public void Prepare(IDeviceContext context, IWorld world, BufferSlice<Vector3> positions, float pushoff, int bounceCount)
{
Debug.Assert(world is RadeonRaysWorld);
var rrWorld = world as RadeonRaysWorld;
_integrationContext = rrWorld.GetIntegrationContext();
_positions = positions;
_pushoff = pushoff;
_bounceCount = bounceCount;
}
public void SetProgressReporter(BakeProgressState progress)
{
_progress = progress;
}
public unsafe IProbeIntegrator.Result IntegrateDirectRadiance(IDeviceContext context, int positionOffset, int positionCount, int sampleCount,
bool ignoreDirectEnvironment, BufferSlice<SphericalHarmonicsL2> radianceEstimateOut)
{
Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else.");
var rrContext = context as RadeonRaysContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
UnityEngine.Vector3* positionsPtr = (Vector3*)NativeArrayUnsafeUtility.GetUnsafePtr(positions);
using var radianceBuffer = new NativeArray<Rendering.SphericalHarmonicsL2>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* shPtr = NativeArrayUnsafeUtility.GetUnsafePtr(radianceBuffer);
int directSampleCount = sampleCount;
int giSampleCount = 0;
int envSampleCount = 0;
const bool ignoreIndirectEnvironment = true;
var lightBakerResult = LightBaker.IntegrateProbeDirectRadianceRadeonRays(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, ignoreDirectEnvironment, ignoreIndirectEnvironment, rrContext, _progress, shPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(radianceEstimateOut, radianceBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write radiance to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write radiance to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public unsafe IProbeIntegrator.Result IntegrateIndirectRadiance(IDeviceContext context, int positionOffset, int positionCount, int sampleCount,
bool ignoreIndirectEnvironment, BufferSlice<SphericalHarmonicsL2> radianceEstimateOut)
{
Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else.");
var rrContext = context as RadeonRaysContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
UnityEngine.Vector3* positionsPtr = (Vector3*)NativeArrayUnsafeUtility.GetUnsafePtr(positions);
using var radianceBuffer = new NativeArray<Rendering.SphericalHarmonicsL2>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* shPtr = NativeArrayUnsafeUtility.GetUnsafePtr(radianceBuffer);
int directSampleCount = 0;
const bool ignoreDirectEnvironment = false;
int giSampleCount = sampleCount;
int envSampleCount = ignoreIndirectEnvironment ? 0 : sampleCount;
var lightBakerResult = LightBaker.IntegrateProbeIndirectRadianceRadeonRays(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, ignoreDirectEnvironment, ignoreIndirectEnvironment, rrContext, _progress, shPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(radianceEstimateOut, radianceBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write radiance to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write radiance to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public unsafe IProbeIntegrator.Result IntegrateValidity(IDeviceContext context,
int positionOffset, int positionCount, int sampleCount, BufferSlice<float> validityEstimateOut)
{
Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else.");
var rrContext = context as RadeonRaysContext;
using var positions = new NativeArray<Vector3>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
EventID eventId = context.ReadBuffer(_positions, positions);
bool waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to read positions from context.");
void* positionsPtr = NativeArrayUnsafeUtility.GetUnsafePtr(positions);
using var validityBuffer = new NativeArray<float>(positionCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
void* validityPtr = NativeArrayUnsafeUtility.GetUnsafePtr(validityBuffer);
int directSampleCount = 0;
int giSampleCount = sampleCount;
int envSampleCount = 0;
var lightBakerResult = LightBaker.IntegrateProbeValidityRadeonRays(positionsPtr, _integrationContext, positionOffset, positionCount, _pushoff,
_bounceCount, directSampleCount, giSampleCount, envSampleCount, rrContext, _progress, validityPtr);
// TODO: Fix this in LIGHT-1479, synchronization and read-back should be done by the user.
if (lightBakerResult.type != LightBaker.ResultType.Success)
return lightBakerResult.ConvertToIProbeIntegratorResult();
eventId = context.WriteBuffer(validityEstimateOut, validityBuffer);
waitResult = context.Wait(eventId);
Debug.Assert(waitResult, "Failed to write validity to context.");
if (!waitResult)
lightBakerResult = new LightBaker.Result {type = LightBaker.ResultType.IOFailed, message = "Failed to write validity to context."};
return lightBakerResult.ConvertToIProbeIntegratorResult();
}
public void Dispose()
{
}
}
}
| UnityCsReference/Editor/Mono/GI/ProbeIntegrator.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GI/ProbeIntegrator.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 6863
} | 294 |
// 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.Experimental;
namespace UnityEditor
{
internal class CacheServerToggle
{
private readonly GUIContent m_CacheServerNotEnabledContent;
private readonly GUIContent m_CacheServerDisconnectedContent;
private readonly GUIContent m_CacheServerConnectedContent;
private readonly PopupLocation[] m_PopupLocation;
static CacheServerToggle()
{
AssetDatabase.cacheServerConnectionChanged += OnCacherServerConnectionChanged;
}
public CacheServerToggle()
{
m_CacheServerNotEnabledContent = EditorGUIUtility.TrIconContent("CacheServerDisabled", "Cache Server disabled");
m_CacheServerDisconnectedContent = EditorGUIUtility.TrIconContent("CacheServerDisconnected", "Cache Server disconnected");
m_CacheServerConnectedContent = EditorGUIUtility.TrIconContent("CacheServerConnected", "Cache Server connected");
m_PopupLocation = new[] { PopupLocation.AboveAlignRight };
}
public void OnGUI()
{
var content = GetStatusContent();
var style = AppStatusBar.Styles.statusIcon;
var rect = GUILayoutUtility.GetRect(content, style);
if (GUI.Button(rect, content, style))
{
PopupWindow.Show(rect, new CacheServerWindow(), m_PopupLocation);
GUIUtility.ExitGUI();
}
}
private GUIContent GetStatusContent()
{
if (!AssetDatabase.IsCacheServerEnabled())
{
return m_CacheServerNotEnabledContent;
}
if (!AssetDatabase.IsConnectedToCacheServer())
{
return m_CacheServerDisconnectedContent;
}
return m_CacheServerConnectedContent;
}
private static void OnCacherServerConnectionChanged(CacheServerConnectionChangedParameters param)
{
AppStatusBar.StatusChanged();
}
}
}
| UnityCsReference/Editor/Mono/GUI/CacheServerToggle.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/CacheServerToggle.cs",
"repo_id": "UnityCsReference",
"token_count": 890
} | 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.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor
{
internal class ExposablePopupMenu
{
public class ItemData
{
public ItemData(GUIContent content, GUIStyle style, bool on, bool enabled, object userData)
{
m_GUIContent = content;
m_Style = style;
m_On = on;
m_Enabled = enabled;
m_UserData = userData;
}
public GUIContent m_GUIContent;
public GUIStyle m_Style;
public bool m_On;
public bool m_Enabled;
public object m_UserData;
public float m_Width;
public float m_Height;
}
public class PopupButtonData
{
public PopupButtonData(GUIContent content, GUIStyle style)
{
m_GUIContent = content;
m_Style = style;
}
public GUIContent m_GUIContent;
public GUIStyle m_Style;
}
List<ItemData> m_Items;
float m_ItemSpacing;
PopupButtonData m_PopupButtonData;
GUIContent m_Label;
int[] m_ItemControlIDs;
int m_DropDownButtonControlID;
static readonly int s_ItemHash = "ItemButton".GetHashCode();
static readonly int m_DropDownButtonHash = "DropDownButton".GetHashCode();
float m_SpacingLabelToButton = 5f;
float m_WidthOfLabel;
float m_WidthOfButtons;
float m_MinWidthOfPopup;
Vector2 m_PopupButtonSize = Vector2.zero;
System.Action<ItemData> m_SelectionChangedCallback = null; // <userData>
public float widthOfButtonsAndLabel { get { return m_WidthOfButtons + labelAndSpacingWidth; } }
public float widthOfPopupAndLabel { get { return m_PopupButtonSize.x + labelAndSpacingWidth; } }
public bool rightAligned { get; set; }
float labelAndSpacingWidth { get { return m_WidthOfLabel > 0 ? m_WidthOfLabel + m_SpacingLabelToButton : 0f; } }
bool hasLabel { get { return m_Label != null && m_Label != GUIContent.none; } }
public void Init(List<ItemData> items, float itemSpacing, float minWidthOfPopup, PopupButtonData popupButtonData, System.Action<ItemData> selectionChangedCallback)
{
Init(GUIContent.none, items, itemSpacing, minWidthOfPopup, popupButtonData, selectionChangedCallback);
}
public void Init(GUIContent label, List<ItemData> items, float itemSpacing, float minWidthOfPopup, PopupButtonData popupButtonData, System.Action<ItemData> selectionChangedCallback)
{
m_Label = label;
m_Items = items;
m_ItemSpacing = itemSpacing;
m_PopupButtonData = popupButtonData;
m_SelectionChangedCallback = selectionChangedCallback;
m_MinWidthOfPopup = minWidthOfPopup;
CalcWidths();
}
public float OnGUI(Rect rect)
{
// To ensure we allocate a consistent amount of controlIDs on every OnGUI we preallocate before any logic
if (m_Items.Count > 0 && (m_ItemControlIDs == null || m_ItemControlIDs.Length != m_Items.Count))
m_ItemControlIDs = new int[m_Items.Count];
for (int i = 0; i < m_Items.Count; ++i)
m_ItemControlIDs[i] = GUIUtility.GetControlID(s_ItemHash, FocusType.Passive);
m_DropDownButtonControlID = GUIUtility.GetControlID(m_DropDownButtonHash, FocusType.Passive);
if (rect.width >= widthOfButtonsAndLabel && rect.width > m_MinWidthOfPopup)
{
// Show as buttons
if (hasLabel)
{
Rect labelRect = rect;
labelRect.width = m_WidthOfLabel;
if (rightAligned)
labelRect.x = rect.xMax - widthOfButtonsAndLabel;
GUI.Label(labelRect, m_Label, EditorStyles.boldLabel);
rect.xMin += (m_WidthOfLabel + m_SpacingLabelToButton);
}
Rect buttonRect = rect;
buttonRect.width = widthOfButtonsAndLabel;
if (rightAligned)
buttonRect.x = rect.xMax - m_WidthOfButtons;
for (int i = 0; i < m_Items.Count; ++i)
{
var item = m_Items[i];
buttonRect.width = item.m_Width;
buttonRect.y = rect.y + (rect.height - item.m_Height) / 2;
buttonRect.height = item.m_Height;
EditorGUI.BeginChangeCheck();
using (new EditorGUI.DisabledScope(!item.m_Enabled))
{
GUI.Toggle(buttonRect, m_ItemControlIDs[i], item.m_On, item.m_GUIContent, item.m_Style);
}
if (EditorGUI.EndChangeCheck())
{
SelectionChanged(item);
GUIUtility.ExitGUI(); // To make sure we can survive if m_Buttons are reallocated in the callback we exit gui
}
buttonRect.x += item.m_Width + m_ItemSpacing;
}
return widthOfButtonsAndLabel;
}
else
{
// Show as popup
var dropDownRect = rect;
if (hasLabel)
{
Rect labelRect = dropDownRect;
labelRect.width = m_WidthOfLabel;
if (rightAligned)
labelRect.x = rect.xMax - widthOfPopupAndLabel;
GUI.Label(labelRect, m_Label, EditorStyles.boldLabel);
dropDownRect.x = labelRect.x + (m_WidthOfLabel + m_SpacingLabelToButton);
}
else
{
if (rightAligned)
dropDownRect.x = rect.xMax - dropDownRect.width;
}
dropDownRect.width = Mathf.Clamp(dropDownRect.width, 0, m_PopupButtonSize.x);
dropDownRect.height = m_PopupButtonSize.y;
dropDownRect.y = rect.y + (rect.height - dropDownRect.height) / 2;
if (EditorGUI.DropdownButton(m_DropDownButtonControlID, dropDownRect, m_PopupButtonData.m_GUIContent, m_PopupButtonData.m_Style))
PopUpMenu.Show(dropDownRect, m_Items, this);
return widthOfPopupAndLabel;
}
}
void CalcWidths()
{
// Buttons
m_WidthOfButtons = 0f;
foreach (var item in m_Items)
{
var itemSize = item.m_Style.CalcSize(item.m_GUIContent);
item.m_Width = itemSize.x;
item.m_Height = itemSize.y;
m_WidthOfButtons += item.m_Width;
}
m_WidthOfButtons += (m_Items.Count - 1) * m_ItemSpacing;
// Popup
m_PopupButtonSize = m_PopupButtonData.m_Style.CalcSize(m_PopupButtonData.m_GUIContent);
// Label
m_WidthOfLabel = hasLabel ? EditorStyles.boldLabel.CalcSize(m_Label).x : 0;
}
void SelectionChanged(ItemData item)
{
if (m_SelectionChangedCallback != null)
m_SelectionChangedCallback(item);
else
Debug.LogError("Callback is null");
}
internal class PopUpMenu
{
static List<ItemData> m_Data;
static ExposablePopupMenu m_Caller;
static internal void Show(Rect activatorRect, List<ItemData> buttonData, ExposablePopupMenu caller)
{
m_Data = buttonData;
m_Caller = caller;
GenericMenu menu = new GenericMenu();
foreach (ItemData item in m_Data)
if (item.m_Enabled)
menu.AddItem(item.m_GUIContent, item.m_On, SelectionCallback, item);
else
menu.AddDisabledItem(item.m_GUIContent);
menu.DropDown(activatorRect);
}
static void SelectionCallback(object userData)
{
ItemData item = (ItemData)userData;
m_Caller.SelectionChanged(item);
// Cleanup
m_Caller = null;
m_Data = null;
}
}
}
} // end namespace UnityEditor
| UnityCsReference/Editor/Mono/GUI/ExposablePopupMenu.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/ExposablePopupMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 4469
} | 296 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor
{
//----------------------------------------------------------------------------------------------------------------------
// What is this : Custom drawer for fields of type LazyLoadReference<T> that filters presented candidate list to assets of type 'T'.
// Motivation(s): default object field drawer is not aware that the generic argument of LazyLoadReference<> should be used
// to filter the list of candidate assets.
//----------------------------------------------------------------------------------------------------------------------
[CustomPropertyDrawer(typeof(LazyLoadReference<>))]
internal sealed class LazyLoadedReferenceField : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
System.Type fieldType;
ScriptAttributeUtility.GetFieldInfoFromProperty(property, out fieldType);
EditorGUI.BeginChangeCheck();
var value = property.objectReferenceValue;
position = EditorGUI.PrefixLabel(position, label);
value = EditorGUI.ObjectField(position, value, fieldType.GetGenericArguments()[0], false);
if (EditorGUI.EndChangeCheck())
property.objectReferenceValue = value;
}
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
ScriptAttributeUtility.GetFieldInfoFromProperty(property, out var fieldType);
var objectField = new ObjectField(preferredLabel);
var genericType = fieldType.GetGenericArguments()[0];
objectField.objectType = genericType;
objectField.value = property.objectReferenceValue;
objectField.bindingPath = property.propertyPath;
PropertyField.ConfigureFieldStyles<ObjectField, Object>(objectField);
return objectField;
}
}
}
| UnityCsReference/Editor/Mono/GUI/LazyLoadReferenceField.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/LazyLoadReferenceField.cs",
"repo_id": "UnityCsReference",
"token_count": 695
} | 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.StyleSheets;
using UnityEditor.Experimental;
namespace UnityEditor
{
// This uses a normal editor window with a single view inside.
internal class PaneDragTab : GUIView
{
const float kMaxArea = 50000.0f;
#pragma warning disable 169
private static PaneDragTab s_Get;
private float m_TargetAlpha = 1.0f;
private DropInfo.Type m_Type = (DropInfo.Type)(-1);
private GUIContent m_Content;
[SerializeField] bool m_Shadow;
[SerializeField] Vector2 m_FullWindowSize = new Vector2(80, 60);
[SerializeField] Rect m_TargetRect;
[SerializeField] internal ContainerWindow m_Window;
[SerializeField] ContainerWindow m_InFrontOfWindow = null;
private static class Styles
{
private static readonly StyleBlock tab = EditorResources.GetStyle("tab");
public static readonly float tabMinWidth = tab.GetFloat(StyleCatalogKeyword.minWidth, 50.0f);
public static readonly float tabMaxWidth = tab.GetFloat(StyleCatalogKeyword.maxWidth, 150.0f);
public static readonly float tabWidthPadding = tab.GetFloat(StyleCatalogKeyword.paddingRight);
public static GUIStyle dragtab = "dragtab";
public static GUIStyle view = "TabWindowBackground";
public static readonly GUIStyle tabLabel = new GUIStyle("dragtab") { name = "dragtab-label" };
public static readonly SVC<Color> backgroundColor = new SVC<Color>("--theme-background-color");
}
static public PaneDragTab get
{
get
{
if (!s_Get)
{
Object[] objs = Resources.FindObjectsOfTypeAll(typeof(PaneDragTab));
if (objs.Length != 0)
s_Get = (PaneDragTab)objs[0];
if (s_Get)
{
return s_Get;
}
s_Get = ScriptableObject.CreateInstance<PaneDragTab>();
}
return s_Get;
}
}
public void SetDropInfo(DropInfo di, Vector2 mouseScreenPos, ContainerWindow inFrontOf)
{
if (m_Type != di.type || (di.type == DropInfo.Type.Pane && di.rect != m_TargetRect))
{
m_Type = di.type;
switch (di.type)
{
case DropInfo.Type.Window:
m_TargetAlpha = 0.6f;
break;
case DropInfo.Type.Pane:
case DropInfo.Type.Tab:
m_TargetAlpha = 1.0f;
break;
}
}
switch (di.type)
{
case DropInfo.Type.Window:
m_TargetRect = new Rect(mouseScreenPos.x - m_FullWindowSize.x / 2, mouseScreenPos.y - m_FullWindowSize.y / 2,
m_FullWindowSize.x, m_FullWindowSize.y);
break;
case DropInfo.Type.Pane:
case DropInfo.Type.Tab:
m_TargetRect = di.rect;
break;
}
m_TargetRect.x = Mathf.Floor(m_TargetRect.x);
m_TargetRect.y = Mathf.Floor(m_TargetRect.y);
m_TargetRect.width = Mathf.Floor(m_TargetRect.width);
m_TargetRect.height = Mathf.Floor(m_TargetRect.height);
m_InFrontOfWindow = inFrontOf;
m_Window.MoveInFrontOf(m_InFrontOfWindow);
// On Windows, repainting without setting proper size first results in one garbage frame... For some reason.
SetWindowPos(m_TargetRect);
// Yes, repaint.
Repaint();
}
public void Close()
{
if (m_Window)
m_Window.Close();
DestroyImmediate(this, true);
s_Get = null;
}
public void Show(Rect pixelPos, GUIContent content, Vector2 viewSize, Vector2 mouseScreenPosition)
{
m_Content = content;
// scale not to be larger then maxArea pixels.
var area = viewSize.x * viewSize.y;
m_FullWindowSize = viewSize * Mathf.Sqrt(Mathf.Clamp01(kMaxArea / area));
if (!m_Window)
{
m_Window = ScriptableObject.CreateInstance<ContainerWindow>();
m_Window.m_DontSaveToLayout = true;
SetMinMaxSizes(Vector2.zero, new Vector2(10000, 10000));
SetWindowPos(pixelPos);
m_Window.rootView = this;
}
else
{
SetWindowPos(pixelPos);
}
// Do not steal focus from the pane
m_Window.Show(ShowMode.NoShadow, loadPosition: true, displayImmediately: false, setFocus: false);
m_TargetRect = pixelPos;
}
void SetWindowPos(Rect screenPosition)
{
m_Window.position = screenPosition;
}
protected override void OldOnGUI()
{
if (!m_Window)
return;
if (Event.current.type != EventType.Repaint)
return;
Rect windowRect = new Rect(0, 0, position.width, position.height);
if (Event.current.type == EventType.Repaint)
GUI.DrawTexture(windowRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, false, 0f, Styles.backgroundColor, 0, 0);
if (m_Type == DropInfo.Type.Tab)
{
Styles.dragtab.Draw(windowRect, false, true, false, false);
GUI.Label(windowRect, m_Content, Styles.tabLabel);
}
else
{
const float dragTabOffsetX = 2f;
const float dragTabHeight = DockArea.kTabHeight;
float minWidth, expectedWidth;
Styles.dragtab.CalcMinMaxWidth(m_Content, out minWidth, out expectedWidth);
float tabWidth = Mathf.Max(Mathf.Min(expectedWidth, Styles.tabMaxWidth), Styles.tabMinWidth) + Styles.tabWidthPadding;
Rect tabPositionRect = new Rect(1, 2f, tabWidth, dragTabHeight);
float roundedPosX = Mathf.Floor(tabPositionRect.x);
float roundedWidth = Mathf.Ceil(tabPositionRect.x + tabPositionRect.width) - roundedPosX;
Rect tabContentRect = new Rect(roundedPosX, tabPositionRect.y, roundedWidth, tabPositionRect.height);
Rect viewRect = new Rect(dragTabOffsetX, tabContentRect.yMax - 2f,
position.width - dragTabOffsetX * 2, position.height - tabContentRect.yMax);
Styles.dragtab.Draw(tabContentRect, false, true, false, false);
Styles.view.Draw(viewRect, GUIContent.none, false, false, true, true);
GUI.Label(tabPositionRect, m_Content, Styles.tabLabel);
}
// We currently only support this on macOS
m_Window.SetAlpha(m_TargetAlpha);
}
}
} // namespace
| UnityCsReference/Editor/Mono/GUI/PaneDragTab.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/PaneDragTab.cs",
"repo_id": "UnityCsReference",
"token_count": 3587
} | 298 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
class SubToolbar
{
public float Width { get; set; }
public virtual void OnGUI(Rect rect)
{
}
}
} // namespace
| UnityCsReference/Editor/Mono/GUI/SubToolbar.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/SubToolbar.cs",
"repo_id": "UnityCsReference",
"token_count": 132
} | 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.Collections.Generic;
using UnityEngine;
namespace UnityEditor.IMGUI.Controls
{
// The TreeView requires implementations from the following three interfaces:
// ITreeViewDataSource: Should handle data fetching and data structure
// ITreeViewGUI: Should handle visual representation of TreeView and input handling
// ITreeViewDragging Should handle dragging, temp expansion of items, allow/disallow dropping
// The TreeView handles: Navigation, Item selection and initiates dragging
// DragNDrop interface for tree views
internal interface ITreeViewDragging
{
void OnInitialize();
bool CanStartDrag(TreeViewItem targetItem, List<int> draggedItemIDs, Vector2 mouseDownPosition);
void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs);
bool DragElement(TreeViewItem targetItem, Rect targetItemRect, int row); // 'targetItem' is null when not hovering over any target Item. Returns true if drag was handled.
void DragCleanup(bool revertExpanded);
int GetDropTargetControlID();
int GetRowMarkerControlID();
bool drawRowMarkerAbove { get; set; }
}
}
| UnityCsReference/Editor/Mono/GUI/TreeView/ITreeViewDragging.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/ITreeViewDragging.cs",
"repo_id": "UnityCsReference",
"token_count": 433
} | 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 System.Globalization;
using UnityEngine;
namespace UnityEditor.IMGUI.Controls
{
// Setup animation, tracks animation, fires callback when done (fully expanded/collapsed)
//
internal class TreeViewItemExpansionAnimator
{
TreeViewAnimationInput m_Setup; // when null we are not animating
bool m_InsideGUIClip;
Rect m_CurrentClipRect;
static bool s_Debug = false;
public void BeginAnimating(TreeViewAnimationInput setup)
{
if (m_Setup != null)
{
if (m_Setup.item.id == setup.item.id && m_Setup.expanding != setup.expanding)
{
// If same item (changed expand/collapse while animating) then just change direction, but skip the time that already passed
if (m_Setup.elapsedTime >= 0)
{
setup.elapsedTime = m_Setup.animationDuration - m_Setup.elapsedTime;
}
else
Debug.LogError("Invalid duration " + m_Setup.elapsedTime);
m_Setup = setup;
}
else
{
// Ensure current animation ends before starting a new (just finish it immediately)
SkipAnimating();
m_Setup = setup;
}
m_Setup.expanding = setup.expanding;
}
m_Setup = setup;
if (m_Setup == null)
Debug.LogError("Setup is null");
if (printDebug)
Console.WriteLine("Begin animating: " + m_Setup);
m_CurrentClipRect = GetCurrentClippingRect();
}
public void SkipAnimating()
{
if (m_Setup != null)
{
m_Setup.FireAnimationEndedEvent();
m_Setup = null;
}
}
// Returns true if row should be culled
public bool CullRow(int row, ITreeViewGUI gui)
{
if (!isAnimating)
{
return false;
}
if (printDebug && row == 0)
Console.WriteLine("--------");
// Check rows that are inside animation clip rect if they can be culled
if (row > m_Setup.startRow && row <= m_Setup.endRow)
{
Rect rowRect = gui.GetRowRect(row, 1); // we do not care about the width
// Check row Y local to clipRect
float rowY = rowRect.y - m_Setup.startRowRect.y;
if (rowY > m_CurrentClipRect.height)
{
// Ensure to end animation clip since items after
// culling should be rendered normally
if (m_InsideGUIClip)
{
EndClip();
}
return true;
}
}
// Row is not culled
return false;
}
public void OnRowGUI(int row)
{
if (printDebug)
Console.WriteLine(row + " Do item " + DebugItemName(row));
}
// Call before of TreeViewGUI's OnRowGUI (Needs to be called for all items (changes rects for rows comming after the animating rows)
public Rect OnBeginRowGUI(int row, Rect rowRect)
{
if (!isAnimating)
return rowRect;
if (row == m_Setup.startRow)
{
BeginClip();
}
// Make row rect local to guiclip if animating
if (row >= m_Setup.startRow && row <= m_Setup.endRow)
{
rowRect.y -= m_Setup.startRowRect.y;
}
// rows following the animation snap to cliprect bottom
else if (row > m_Setup.endRow)
{
rowRect.y -= m_Setup.rowsRect.height - m_CurrentClipRect.height;
}
return rowRect;
}
// Call at the after TreeViewGUI's OnRowGUI
public void OnEndRowGUI(int row)
{
if (!isAnimating)
return;
if (m_InsideGUIClip && row == m_Setup.endRow)
{
EndClip();
}
}
// Call before all items are being handling
private void BeginClip()
{
GUI.BeginClip(m_CurrentClipRect);
m_InsideGUIClip = true;
if (printDebug)
Console.WriteLine("BeginClip startRow: " + m_Setup.startRow);
}
private void EndClip()
{
GUI.EndClip();
m_InsideGUIClip = false;
if (printDebug)
Console.WriteLine("EndClip endRow: " + m_Setup.endRow);
}
public void OnBeforeAllRowsGUI()
{
if (!isAnimating)
return;
// Cache to ensure consistent across all rows (it is dependant on time)
m_CurrentClipRect = GetCurrentClippingRect();
// Stop animation when duration has passed
if (m_Setup.elapsedTime > m_Setup.animationDuration)
{
m_Setup.FireAnimationEndedEvent();
m_Setup = null;
if (printDebug)
Debug.Log("Animation ended");
}
}
public void OnAfterAllRowsGUI()
{
// Ensure to end clip if not done in CullRow (while iterating rows)
if (m_InsideGUIClip)
{
EndClip();
}
// Capture time at intervals to ensure that expansion value is consistent across layout and repaint.
// This fixes that the scroll view showed its scrollbars during expansion since using realtime
// would give higher values on repaint than on layout event.
if (isAnimating && Event.current.type == EventType.Repaint)
{
HandleUtility.Repaint();
m_Setup.CaptureTime();
}
}
public bool IsAnimating(int itemID)
{
if (!isAnimating)
return false;
return m_Setup.item.id == itemID;
}
// 1 fully expanded, 0 fully collapsed
public float expandedValueNormalized
{
get
{
float frac = m_Setup.elapsedTimeNormalized;
return m_Setup.expanding ? frac : (1.0f - frac);
}
}
public int startRow
{
get { return m_Setup.startRow; }
}
public int endRow
{
get { return m_Setup.endRow; }
}
public float deltaHeight
{
get { return Mathf.Floor(m_Setup.rowsRect.height - m_Setup.rowsRect.height * expandedValueNormalized); }
}
public bool isAnimating
{
get { return m_Setup != null; }
}
public bool isExpanding
{
get { return m_Setup.expanding; }
}
Rect GetCurrentClippingRect()
{
Rect rect = m_Setup.rowsRect;
rect.height *= expandedValueNormalized;
return rect;
}
bool printDebug
{
get { return s_Debug && (m_Setup != null) && (m_Setup.treeView != null) && (Event.current.type == EventType.Repaint); }
}
string DebugItemName(int row)
{
return m_Setup.treeView.data.GetRows()[row].displayName;
}
}
internal class TreeViewAnimationInput
{
public TreeViewAnimationInput()
{
startTime = timeCaptured = EditorApplication.timeSinceStartup;
}
public void CaptureTime()
{
timeCaptured = EditorApplication.timeSinceStartup;
}
public float elapsedTimeNormalized
{
get
{
return Mathf.Clamp01((float)elapsedTime / (float)animationDuration);
}
}
public double elapsedTime
{
get
{
return timeCaptured - startTime;
}
set
{
startTime = timeCaptured - value;
}
}
public int startRow { get; set; }
public int endRow { get; set; }
public Rect rowsRect {get; set; } // the rect encapsulating startrow and endrow
public Rect startRowRect {get; set; }
public double startTime { get; set; }
public double timeCaptured { get; set; }
public double animationDuration { get; set; }
public bool expanding { get; set; }
public bool includeChildren { get; set; }
public TreeViewItem item { get; set; }
public TreeViewController treeView { get; set; }
public System.Action<TreeViewAnimationInput> animationEnded; // set to get a callback when animation ends
public void FireAnimationEndedEvent()
{
if (animationEnded != null)
animationEnded(this);
}
public override string ToString()
{
return "Input: startRow " + startRow + " endRow " + endRow + " rowsRect " + rowsRect + " startTime " + startTime.ToString(CultureInfo.InvariantCulture.NumberFormat) + " anitmationDuration" + animationDuration + " " + expanding + " " + item.displayName;
}
}
} // UnityEditor
| UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewExpandAnimator.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewExpandAnimator.cs",
"repo_id": "UnityCsReference",
"token_count": 4848
} | 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 System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using UnityEditor.ShortcutManagement;
using UnityEditor.VersionControl;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Scripting;
using Directory = System.IO.Directory;
using UnityObject = UnityEngine.Object;
using JSONObject = System.Collections.IDictionary;
namespace UnityEditor
{
class LayoutException : Exception
{
public LayoutException()
{
}
public LayoutException(string message)
: base(message)
{
}
}
[InitializeOnLoad]
internal static class WindowLayout
{
struct LayoutViewInfo
{
public LayoutViewInfo(object key, float defaultSize, bool usedByDefault)
{
this.key = key;
used = usedByDefault;
this.defaultSize = defaultSize;
className = string.Empty;
type = null;
isContainer = false;
extendedData = null;
}
public object key;
public string className;
public Type type;
public bool used;
public float defaultSize;
public bool isContainer;
public JSONObject extendedData;
public float size
{
get
{
if (!used)
return 0;
return defaultSize;
}
}
}
const string tabsLayoutKey = "tabs";
const string verticalLayoutKey = "vertical";
const string horizontalLayoutKey = "horizontal";
const string k_TopViewClassName = "top_view";
const string k_CenterViewClassName = "center_view";
const string k_BottomViewClassName = "bottom_view";
// used by tests
internal const string kMaximizeRestoreFile = "CurrentMaximizeLayout.dwlt";
private const string kDefaultLayoutName = "Default.wlt";
internal static string layoutResourcesPath => Path.Combine(EditorApplication.applicationContentsPath, "Resources/Layouts");
internal static string layoutsPreferencesPath => FileUtil.CombinePaths(InternalEditorUtility.unityPreferencesFolder, "Layouts");
internal static string layoutsModePreferencesPath => FileUtil.CombinePaths(layoutsPreferencesPath, ModeService.currentId);
internal static string layoutsDefaultModePreferencesPath => FileUtil.CombinePaths(layoutsPreferencesPath, "default");
internal static string layoutsCurrentModePreferencesPath => FileUtil.CombinePaths(layoutsPreferencesPath, "current");
internal static string layoutsProjectPath => FileUtil.CombinePaths("UserSettings", "Layouts");
internal static string ProjectLayoutPath => GetProjectLayoutPerMode(ModeService.currentId);
internal static string currentLayoutName => GetLayoutFileName(ModeService.currentId, Application.unityVersionVer);
[UsedImplicitly, RequiredByNativeCode]
public static void LoadDefaultWindowPreferences()
{
LoadCurrentModeLayout(keepMainWindow: FindMainWindow());
ModeService.InitializeCurrentMode();
}
public static void LoadCurrentModeLayout(bool keepMainWindow)
{
InitializeLayoutPreferencesFolder();
var dynamicLayout = ModeService.GetDynamicLayout();
if (dynamicLayout == null)
LoadLastUsedLayoutForCurrentMode(keepMainWindow);
else
{
var projectLayoutExists = File.Exists(ProjectLayoutPath);
if ((projectLayoutExists && Convert.ToBoolean(dynamicLayout["restore_saved_layout"]))
|| !LoadModeDynamicLayout(keepMainWindow, dynamicLayout))
LoadLastUsedLayoutForCurrentMode(keepMainWindow);
}
}
private static bool LoadModeDynamicLayout(bool keepMainWindow, JSONObject layoutData)
{
LayoutViewInfo topViewInfo = new LayoutViewInfo(k_TopViewClassName, MainView.kToolbarHeight, true);
LayoutViewInfo bottomViewInfo = new LayoutViewInfo(k_BottomViewClassName, MainView.kStatusbarHeight, true);
LayoutViewInfo centerViewInfo = new LayoutViewInfo(k_CenterViewClassName, 0, true);
var availableEditorWindowTypes = TypeCache.GetTypesDerivedFrom<EditorWindow>().ToArray();
if (!GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref centerViewInfo))
return false;
GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref topViewInfo);
GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref bottomViewInfo);
var mainWindow = FindMainWindow();
if (keepMainWindow && mainWindow == null)
{
Debug.LogWarning($"No main window to restore layout from while loading dynamic layout for mode {ModeService.currentId}");
return false;
}
var mainViewID = $"MainView_{ModeService.currentId}";
InitContainerWindow(ref mainWindow, mainViewID, layoutData);
GenerateLayout(mainWindow, ShowMode.MainWindow, availableEditorWindowTypes, centerViewInfo, topViewInfo, bottomViewInfo, layoutData);
mainWindow.m_DontSaveToLayout = !Convert.ToBoolean(layoutData["restore_saved_layout"]);
return true;
}
private static View LoadLayoutView<T>(Type[] availableEditorWindowTypes, LayoutViewInfo viewInfo, float width, float height) where T : View
{
if (!viewInfo.used)
return null;
View view = null;
if (viewInfo.isContainer)
{
bool useTabs = viewInfo.extendedData.Contains(tabsLayoutKey) && Convert.ToBoolean(viewInfo.extendedData[tabsLayoutKey]);
bool useSplitter = viewInfo.extendedData.Contains(verticalLayoutKey) || viewInfo.extendedData.Contains(horizontalLayoutKey);
bool isVertical = viewInfo.extendedData.Contains(verticalLayoutKey) && Convert.ToBoolean(viewInfo.extendedData[verticalLayoutKey]);
if (useTabs && useSplitter)
Debug.LogWarning($"{ModeService.currentId} defines both tabs and splitter (horizontal or vertical) layouts.\n You can only define one to true (i.e. tabs = true) in the editor mode file.");
if (useSplitter)
{
var splitView = ScriptableObject.CreateInstance<SplitView>();
splitView.vertical = isVertical;
view = splitView;
}
else if (useTabs)
{
var dockAreaView = ScriptableObject.CreateInstance<DockArea>();
view = dockAreaView;
}
view.position = new Rect(0, 0, width, height);
var childrenData = viewInfo.extendedData["children"] as IList;
if (childrenData == null)
throw new LayoutException("Invalid split view data");
int childIndex = 0;
foreach (var childData in childrenData)
{
var lvi = new LayoutViewInfo(childIndex, useTabs ? 1f : 1f / childrenData.Count, true);
if (!ParseViewData(availableEditorWindowTypes, childData, ref lvi))
continue;
var cw = useTabs ? width : (isVertical ? width : width * lvi.size);
var ch = useTabs ? height : (isVertical ? height * lvi.size : height);
if (useTabs && view is DockArea da)
{
da.AddTab((EditorWindow)ScriptableObject.CreateInstance(lvi.type));
}
else
{
view.AddChild(LoadLayoutView<HostView>(availableEditorWindowTypes, lvi, cw, ch));
view.children[childIndex].position = new Rect(0, 0, cw, ch);
}
childIndex++;
}
}
else
{
if (viewInfo.type != null)
{
var hostView = ScriptableObject.CreateInstance<HostView>();
hostView.SetActualViewInternal(ScriptableObject.CreateInstance(viewInfo.type) as EditorWindow, true);
view = hostView;
}
else
view = ScriptableObject.CreateInstance<T>();
}
return view;
}
internal static void InitContainerWindow(ref ContainerWindow window, string windowId, JSONObject layoutData)
{
if (window == null)
{
window = ScriptableObject.CreateInstance<ContainerWindow>();
var windowMinSize = new Vector2(120, 80);
var windowMaxSize = new Vector2(8192, 8192);
if (layoutData.Contains("min_width"))
{
windowMinSize.x = Convert.ToSingle(layoutData["min_width"]);
}
if (layoutData.Contains("min_height"))
{
windowMinSize.y = Convert.ToSingle(layoutData["min_height"]);
}
if (layoutData.Contains("max_width"))
{
windowMaxSize.x = Convert.ToSingle(layoutData["max_width"]);
}
if (layoutData.Contains("max_height"))
{
windowMaxSize.y = Convert.ToSingle(layoutData["max_height"]);
}
window.SetMinMaxSizes(windowMinSize, windowMaxSize);
}
var hasMainViewGeometrySettings = EditorPrefs.HasKey($"{windowId}h");
window.windowID = windowId;
var loadInitialWindowGeometry = Convert.ToBoolean(layoutData["restore_layout_dimension"]);
if (loadInitialWindowGeometry && hasMainViewGeometrySettings)
window.LoadGeometry(true);
}
internal static ContainerWindow FindMainWindow()
{
return Resources.FindObjectsOfTypeAll<ContainerWindow>().FirstOrDefault(w => w.showMode == ShowMode.MainWindow);
}
internal static ContainerWindow ShowWindowWithDynamicLayout(string windowId, string layoutDataPath)
{
try
{
ContainerWindow.SetFreezeDisplay(true);
if (!File.Exists(layoutDataPath))
{
Debug.LogError($"Failed to find layout data file at path {layoutDataPath}");
return null;
}
var layoutDataJson = File.ReadAllText(layoutDataPath);
var layoutData = SJSON.LoadString(layoutDataJson);
var availableEditorWindowTypes = TypeCache.GetTypesDerivedFrom<EditorWindow>().ToArray();
LayoutViewInfo topViewInfo = new LayoutViewInfo(k_TopViewClassName, MainView.kToolbarHeight, false);
LayoutViewInfo bottomViewInfo = new LayoutViewInfo(k_BottomViewClassName, MainView.kStatusbarHeight, false);
// Supports both view and center_view.
var centerViewKey = "view";
if (!layoutData.Contains(centerViewKey))
{
centerViewKey = "center_view";
}
LayoutViewInfo centerViewInfo = new LayoutViewInfo(centerViewKey, 0, true);
if (!GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref centerViewInfo))
{
Debug.LogError("Failed to load window layout; no view defined");
return null;
}
GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref topViewInfo);
GetLayoutViewInfo(layoutData, availableEditorWindowTypes, ref bottomViewInfo);
var window = Resources.FindObjectsOfTypeAll<ContainerWindow>().FirstOrDefault(w => w.windowID == windowId);
InitContainerWindow(ref window, windowId, layoutData);
window.m_IsMppmCloneWindow = true;
GenerateLayout(window, ShowMode.Utility, availableEditorWindowTypes, centerViewInfo, topViewInfo, bottomViewInfo, layoutData);
window.m_DontSaveToLayout = !Convert.ToBoolean(layoutData["restore_saved_layout"]);
return window;
}
finally
{
ContainerWindow.SetFreezeDisplay(false);
}
}
private static void GenerateLayout(ContainerWindow window, ShowMode showMode, Type[] availableEditorWindowTypes,
LayoutViewInfo center, LayoutViewInfo top, LayoutViewInfo bottom, JSONObject layoutData)
{
try
{
ContainerWindow.SetFreezeDisplay(true);
var width = window.position.width;
var height = window.position.height;
// Create center view
View centerView = LoadLayoutView<DockArea>(availableEditorWindowTypes, center, width, height);
var topView = LoadLayoutView<Toolbar>(availableEditorWindowTypes, top, width, height);
var bottomView = LoadLayoutView<AppStatusBar>(availableEditorWindowTypes, bottom, width, height);
var main = ScriptableObject.CreateInstance<MainView>();
main.useTopView = top.used;
main.useBottomView = bottom.used;
main.topViewHeight = top.size;
main.bottomViewHeight = bottom.size;
// Top View
if (topView)
{
topView.position = new Rect(0, 0, width, top.size);
main.AddChild(topView);
}
// Center View
var centerViewHeight = height - bottom.size - top.size;
centerView.position = new Rect(0, top.size, width, centerViewHeight);
main.AddChild(centerView);
// Bottom View
if (bottomView)
{
bottomView.position = new Rect(0, height - bottom.size, width, bottom.size);
main.AddChild(bottomView);
}
if (window.rootView)
ScriptableObject.DestroyImmediate(window.rootView, true);
window.rootView = main;
window.rootView.position = new Rect(0, 0, width, height);
window.Show(showMode, true, true, true);
window.DisplayAllViews();
}
finally
{
ContainerWindow.SetFreezeDisplay(false);
}
}
private static bool GetLayoutViewInfo(JSONObject layoutData, Type[] availableEditorWindowTypes, ref LayoutViewInfo viewInfo)
{
if (!layoutData.Contains(viewInfo.key))
return false;
var viewData = layoutData[viewInfo.key];
return ParseViewData(availableEditorWindowTypes, viewData, ref viewInfo);
}
private static bool ParseViewData(Type[] availableEditorWindowTypes, object viewData, ref LayoutViewInfo viewInfo)
{
if (viewData is string)
{
viewInfo.className = Convert.ToString(viewData);
viewInfo.used = !string.IsNullOrEmpty(viewInfo.className);
if (!viewInfo.used)
return true;
}
else if (viewData is JSONObject viewExpandedData)
{
if (viewExpandedData.Contains("children")
|| viewExpandedData.Contains(verticalLayoutKey)
|| viewExpandedData.Contains(horizontalLayoutKey)
|| viewExpandedData.Contains(tabsLayoutKey))
{
viewInfo.isContainer = true;
viewInfo.className = string.Empty;
}
else
{
viewInfo.isContainer = false;
viewInfo.className = Convert.ToString(viewExpandedData["class_name"]);
}
if (viewExpandedData.Contains("size"))
viewInfo.defaultSize = Convert.ToSingle(viewExpandedData["size"]);
viewInfo.extendedData = viewExpandedData;
viewInfo.used = true;
}
else
{
viewInfo.className = string.Empty;
viewInfo.type = null;
viewInfo.used = false;
return true;
}
if (string.IsNullOrEmpty(viewInfo.className))
return true;
foreach (var t in availableEditorWindowTypes)
{
if (t.Name != viewInfo.className)
continue;
viewInfo.type = t;
break;
}
if (viewInfo.type == null)
{
Debug.LogWarning($"Invalid layout view {viewInfo.key} with type {viewInfo.className} for mode {ModeService.currentId}");
return false;
}
return true;
}
// Used by tests
internal static string GetLayoutFileName(string mode, int version) => $"{mode}-{version}.dwlt";
static IEnumerable<string> GetCurrentModeLayouts()
{
var layouts = ModeService.GetModeDataSection(ModeService.currentIndex, ModeDescriptor.LayoutsKey);
if (layouts is IList<object> modeLayoutPaths)
{
foreach (var layoutPath in modeLayoutPaths.Cast<string>())
{
if (!File.Exists(layoutPath))
continue;
yield return layoutPath;
}
}
}
// Iterate through potential layouts in descending order of precedence.
// 1. Last loaded layout in project for matching Unity version
// 2. Last loaded layout in project for any Unity version, in descending alphabetical order
// 3. Last loaded layout in global preferences for matching Unity version
// 4. Last loaded layout in global preferences for any Unity version, in descending alphabetical order
// 5. Any available layouts specified by the EditorMode, if EditorMode supplies layouts
// 6. The factory default layout
private static void LoadLastUsedLayoutForCurrentMode(bool keepMainWindow)
{
// steps 1-4
foreach (var layout in GetLastLayout())
if (LoadWindowLayout(layout, layout != ProjectLayoutPath, false, keepMainWindow, false))
return;
// step 5
foreach (var layout in GetCurrentModeLayouts())
if (LoadWindowLayout(layout, layout != ProjectLayoutPath, false, keepMainWindow, false))
return;
// It is not mandatory that modes define a layout. In that case, skip right to the default layout.
if (!string.IsNullOrEmpty(ModeService.GetDefaultModeLayout())
&& LoadWindowLayout(ModeService.GetDefaultModeLayout(), true, false, keepMainWindow, false))
return;
// If all else fails, load the default layout that ships with the editor. If that fails, prompt the user to
// restore the default layouts.
if (!LoadWindowLayout(GetDefaultLayoutPath(), true, false, keepMainWindow, false))
{
int option = 0;
if (!Application.isTestRun && Application.isHumanControllingUs)
{
option = EditorUtility.DisplayDialogComplex("Missing Default Layout", "No valid user created or " +
"default window layout found. Please revert factory settings to restore the default layouts.",
"Quit", "Revert Factory Settings", "");
}
else
{
ResetUserLayouts();
}
switch (option)
{
case 0:
EditorApplication.Exit(0);
break;
case 1:
ResetFactorySettings();
break;
}
}
}
[UsedImplicitly, RequiredByNativeCode]
public static void SaveDefaultWindowPreferences()
{
// Do not save layout to default if running tests
if (!InternalEditorUtility.isHumanControllingUs)
return;
SaveCurrentLayoutPerMode(ModeService.currentId);
}
internal static void SaveCurrentLayoutPerMode(string modeId)
{
// Save the layout in two places. Once in the Project/UserSettings directory, then again the global
// preferences. The latter is used when opening a new project (or any case where UserSettings/Layouts/ does
// not exist).
SaveWindowLayout(FileUtil.CombinePaths(Directory.GetCurrentDirectory(), GetProjectLayoutPerMode(modeId)));
SaveWindowLayout(Path.Combine(layoutsCurrentModePreferencesPath, GetLayoutFileName(modeId, Application.unityVersionVer)));
}
// Iterate through potential layout files, prioritizing exact match followed by descending unity version.
// IMPORTANT: This function is "dumb" in that it does not do any kind of sophisticated version comparison. If the
// naming scheme for current layouts is changed, or this function is called on to sort user saved layouts, you will
// need to add more sophisticated filtering.
public static IEnumerable<string> GetLastLayout(string directory, string mode, int version)
{
var currentModeAndVersionLayout = GetLayoutFileName(mode, version);
string layoutSearchPattern = $"{mode}-*.*wlt";
// first try the exact match
var preferred = Path.Combine(directory, currentModeAndVersionLayout);
if(File.Exists(preferred))
yield return preferred;
// if that fails, fall back to layouts for this mode from other unity versions in descending order
if (Directory.Exists(directory))
{
var paths = Directory.GetFiles(directory, layoutSearchPattern)
.Where(p => string.Compare(p, preferred, StringComparison.OrdinalIgnoreCase) != 0)
.OrderByDescending(p => p, StringComparer.OrdinalIgnoreCase);
foreach (var path in paths)
yield return path;
}
}
// used by Tests/EditModeAndPlayModeTests/EditorModes
internal static IEnumerable<string> GetLastLayout()
{
var mode = ModeService.currentId;
var version = Application.unityVersionVer;
foreach (var layout in GetLastLayout(layoutsProjectPath, mode, version))
yield return layout;
foreach (var layout in GetLastLayout(layoutsCurrentModePreferencesPath, mode, version))
yield return layout;
}
internal static string GetCurrentLayoutPath()
{
var currentLayoutPath = ProjectLayoutPath;
// Make sure we have a current layout file created
if (!File.Exists(ProjectLayoutPath))
currentLayoutPath = GetDefaultLayoutPath();
return currentLayoutPath;
}
internal static string GetDefaultLayoutPath()
{
return Path.Combine(layoutsModePreferencesPath, kDefaultLayoutName);
}
internal static string GetProjectLayoutPerMode(string modeId)
{
return FileUtil.CombinePaths(layoutsProjectPath, GetLayoutFileName(modeId, Application.unityVersionVer));
}
private static void InitializeLayoutPreferencesFolder()
{
string defaultLayoutPath = GetDefaultLayoutPath();
if (!Directory.Exists(layoutsPreferencesPath))
Directory.CreateDirectory(layoutsPreferencesPath);
if (!Directory.Exists(layoutsModePreferencesPath))
{
Console.WriteLine($"[LAYOUT] {layoutsModePreferencesPath} does not exist. Copying base layouts.");
// Make sure we have a valid default mode folder initialized with the proper default layouts.
if (layoutsDefaultModePreferencesPath == layoutsModePreferencesPath)
{
// Backward compatibility: if the default layout folder doesn't exists but some layouts have been
// saved be sure to copy them to the "default layout per mode folder".
FileUtil.CopyFileOrDirectory(layoutResourcesPath, layoutsDefaultModePreferencesPath);
var defaultModeUserLayouts = Directory.GetFiles(layoutsPreferencesPath, "*.wlt");
foreach (var layoutPath in defaultModeUserLayouts)
{
var fileName = Path.GetFileName(layoutPath);
var dst = Path.Combine(layoutsDefaultModePreferencesPath, fileName);
if (!File.Exists(dst))
FileUtil.CopyFileIfExists(layoutPath, dst, false);
}
}
else
{
Directory.CreateDirectory(layoutsModePreferencesPath);
}
}
// Make sure we have the default layout file in the preferences folder
if (!File.Exists(defaultLayoutPath))
{
var defaultModeLayoutPath = ModeService.GetDefaultModeLayout();
if (!File.Exists(defaultModeLayoutPath))
{
// No mode default layout, use the editor_resources Default:
defaultModeLayoutPath = Path.Combine(layoutResourcesPath, kDefaultLayoutName);
}
Console.WriteLine($"[LAYOUT] Copying {defaultModeLayoutPath} to {defaultLayoutPath}");
// If not copy our default file to the preferences folder
FileUtil.CopyFileOrDirectory(defaultModeLayoutPath, defaultLayoutPath);
}
Debug.Assert(File.Exists(defaultLayoutPath));
}
static WindowLayout()
{
EditorApplication.CallDelayed(UpdateWindowLayoutMenu);
}
internal static void UpdateWindowLayoutMenu()
{
if (!ModeService.HasCapability(ModeCapability.LayoutWindowMenu, true))
return;
ReloadWindowLayoutMenu();
}
internal static void ReloadWindowLayoutMenu()
{
Menu.RemoveMenuItem("Window/Layouts");
if (!ModeService.HasCapability(ModeCapability.LayoutWindowMenu, true))
return;
int layoutMenuItemPriority = 20;
// Get user saved layouts
string[] layoutPaths = new string[0];
if (Directory.Exists(layoutsModePreferencesPath))
{
layoutPaths = Directory.GetFiles(layoutsModePreferencesPath).Where(path => path.EndsWith(".wlt")).ToArray();
foreach (var layoutPath in layoutPaths)
{
var name = Path.GetFileNameWithoutExtension(layoutPath);
Menu.AddMenuItem("Window/Layouts/" + name, "", false, layoutMenuItemPriority++, () => LoadWindowLayout(layoutPath, false, true, true, true), null);
}
layoutMenuItemPriority += 500;
}
// Get all version current layouts
AddLegacyLayoutMenuItems(ref layoutMenuItemPriority);
// Get mode layouts
var modeLayoutPaths = ModeService.GetModeDataSection(ModeService.currentIndex, ModeDescriptor.LayoutsKey) as IList<object>;
if (modeLayoutPaths != null)
{
foreach (var layoutPath in modeLayoutPaths.Cast<string>())
{
if (!File.Exists(layoutPath))
continue;
var name = Path.GetFileNameWithoutExtension(layoutPath);
Menu.AddMenuItem("Window/Layouts/" + name, "", Toolbar.lastLoadedLayoutName == name, layoutMenuItemPriority++, () => TryLoadWindowLayout(layoutPath, false), null);
}
}
layoutMenuItemPriority += 500;
Menu.AddMenuItem("Window/Layouts/Save Layout...", "", false, layoutMenuItemPriority++, SaveGUI, null);
Menu.AddMenuItem("Window/Layouts/Save Layout to File...", "", false, layoutMenuItemPriority++, SaveToFile, null);
Menu.AddMenuItem("Window/Layouts/Load Layout from File...", "", false, layoutMenuItemPriority++, LoadFromFile, null);
Menu.AddMenuItem("Window/Layouts/Delete Layout/", "", false, layoutMenuItemPriority++, null, null);
foreach (var layoutPath in layoutPaths)
{
var name = Path.GetFileNameWithoutExtension(layoutPath);
Menu.AddMenuItem("Window/Layouts/Delete Layout/" + name, "", false, layoutMenuItemPriority++, () => DeleteWindowLayout(layoutPath), null);
}
Menu.AddMenuItem("Window/Layouts/Reset All Layouts", "", false, layoutMenuItemPriority++, () => ResetAllLayouts(false), null);
}
private static void AddLegacyLayoutMenuItems(ref int layoutMenuItemPriority)
{
const string legacyRootMenu = "Window/Layouts/Other Versions";
const string legacyCurrentLayoutPath = "Library/CurrentLayout-default.dwlt";
if (File.Exists(legacyCurrentLayoutPath))
Menu.AddMenuItem($"{legacyRootMenu}/Default (2020)", "", false, layoutMenuItemPriority++, () => LoadWindowLayout(legacyCurrentLayoutPath, false, true, false, true), null);
if (!Directory.Exists(layoutsProjectPath))
return;
foreach (var layoutPath in Directory.GetFiles(layoutsProjectPath, "*.dwlt"))
{
if (layoutPath == GetCurrentLayoutPath())
continue;
var name = Path.GetFileNameWithoutExtension(layoutPath);
var names = Path.GetFileName(name).Split('-');
var menuName = $"{legacyRootMenu}/{name}";
if (names.Length == 2)
{
name = ObjectNames.NicifyVariableName(names[0]);
menuName = $"{legacyRootMenu}/{name} ({names[1]})";
}
Menu.AddMenuItem(menuName, "", false, layoutMenuItemPriority++, () => LoadWindowLayout(layoutPath, false, true, false, true), null);
}
}
internal static EditorWindow FindEditorWindowOfType(Type type)
{
UnityObject[] obj = Resources.FindObjectsOfTypeAll(type);
if (obj.Length > 0)
return obj[0] as EditorWindow;
return null;
}
internal static void CheckWindowConsistency()
{
UnityObject[] wins = Resources.FindObjectsOfTypeAll(typeof(EditorWindow));
foreach (EditorWindow win in wins)
{
if (win.m_Parent == null)
{
Debug.LogErrorFormat(
"Invalid editor window of type: {0}, title: {1}",
win.GetType(), win.titleContent.text);
}
}
}
internal static EditorWindow TryGetLastFocusedWindowInSameDock()
{
// Get type of window that was docked together with game view and was focused before play mode
Type type = null;
string windowTypeName = WindowFocusState.instance.m_LastWindowTypeInSameDock;
if (windowTypeName != "")
type = Type.GetType(windowTypeName);
// Also get the PlayModeView Window
var playModeView = PlayModeView.GetMainPlayModeView();
if (type != null && playModeView && playModeView != null && playModeView.m_Parent is DockArea)
{
// Get all windows of that type
object[] potentials = Resources.FindObjectsOfTypeAll(type);
DockArea dock = playModeView.m_Parent as DockArea;
// Find the one that is actually docked together with the GameView
for (int i = 0; i < potentials.Length; i++)
{
EditorWindow window = potentials[i] as EditorWindow;
if (window && window.m_Parent == dock)
return window;
}
}
return null;
}
internal static void SaveCurrentFocusedWindowInSameDock(EditorWindow windowToBeFocused)
{
if (windowToBeFocused.m_Parent != null && windowToBeFocused.m_Parent is DockArea)
{
DockArea dock = windowToBeFocused.m_Parent as DockArea;
// Get currently focused window/tab in that dock
EditorWindow actualView = dock.actualView;
if (actualView)
WindowFocusState.instance.m_LastWindowTypeInSameDock = actualView.GetType().ToString();
}
}
internal static void FindFirstGameViewAndSetToMaximizeOnPlay()
{
GameView gameView = (GameView)FindEditorWindowOfType(typeof(GameView));
if (gameView)
gameView.enterPlayModeBehavior = PlayModeView.EnterPlayModeBehavior.PlayMaximized;
}
internal static void FindFirstGameViewAndSetToPlayFocused()
{
GameView gameView = (GameView)FindEditorWindowOfType(typeof(GameView));
if (gameView)
gameView.enterPlayModeBehavior = PlayModeView.EnterPlayModeBehavior.PlayFocused;
}
internal static EditorWindow TryFocusAppropriateWindow(bool enteringPlaymode)
{
// If PlayModeView behavior is set to 'Do Nothing' ignore focusing windows when entering/exiting PlayMode
var playModeView = PlayModeView.GetCorrectPlayModeViewToFocus();
bool shouldFocusView = playModeView && playModeView.enterPlayModeBehavior != PlayModeView.EnterPlayModeBehavior.PlayUnfocused;
if (enteringPlaymode)
{
if (shouldFocusView)
{
SaveCurrentFocusedWindowInSameDock(playModeView);
playModeView.Focus();
}
return playModeView;
}
else
{
// If we can retrieve what window type was active when we went into play mode,
// go back to focus a window of that type if needed.
if (shouldFocusView)
{
EditorWindow window = TryGetLastFocusedWindowInSameDock();
if (window)
window.ShowTab();
return window;
}
return EditorWindow.focusedWindow;
}
}
internal static EditorWindow GetMaximizedWindow()
{
UnityObject[] maximized = Resources.FindObjectsOfTypeAll(typeof(MaximizedHostView));
if (maximized.Length != 0)
{
MaximizedHostView maximizedView = maximized[0] as MaximizedHostView;
if (maximizedView.actualView)
return maximizedView.actualView;
}
return null;
}
internal static EditorWindow ShowAppropriateViewOnEnterExitPlaymode(bool entering)
{
// Prevent trying to go into the same state as we're already in, as it will break things
if (WindowFocusState.instance.m_CurrentlyInPlayMode == entering)
return null;
WindowFocusState.instance.m_CurrentlyInPlayMode = entering;
EditorWindow window = null;
EditorWindow maximized = GetMaximizedWindow();
if (entering)
{
if (!GameView.openWindowOnEnteringPlayMode && !(PlayModeView.GetCorrectPlayModeViewToFocus() is PlayModeView))
return null;
WindowFocusState.instance.m_WasMaximizedBeforePlay = (maximized != null);
// If a view is already maximized before entering play mode,
// just keep that maximized view, no matter if it's the game view or some other.
// Trust that user has a good reason (desire by Ethan etc.)
if (maximized != null)
return maximized;
}
else
{
// If a view was already maximized before entering play mode,
// then it was kept when switching to play mode, and can simply still be kept when exiting
if (WindowFocusState.instance.m_WasMaximizedBeforePlay)
return maximized;
}
// Unmaximize if maximized
if (maximized)
Unmaximize(maximized);
// Try finding and focusing appropriate window/tab
window = TryFocusAppropriateWindow(entering);
if (window)
return window;
// If we are entering Play more and no Game View was found, create one
if (entering && PlayModeView.openWindowOnEnteringPlayMode)
{
// Try to create and focus a Game View tab docked together with the Scene View tab
EditorWindow sceneView = FindEditorWindowOfType(typeof(SceneView));
GameView gameView;
if (sceneView && sceneView.m_Parent is DockArea)
{
DockArea dock = sceneView.m_Parent as DockArea;
if (dock)
{
WindowFocusState.instance.m_LastWindowTypeInSameDock = sceneView.GetType().ToString();
gameView = ScriptableObject.CreateInstance<GameView>();
dock.AddTab(gameView);
return gameView;
}
}
// If no Scene View was found at all, just create a floating Game View
gameView = ScriptableObject.CreateInstance<GameView>();
gameView.Show(true);
gameView.Focus();
return gameView;
}
return window;
}
internal static bool IsMaximized(EditorWindow window)
{
return window.m_Parent is MaximizedHostView;
}
public static void Unmaximize(EditorWindow win)
{
HostView maximizedHostView = win.m_Parent;
if (maximizedHostView == null)
{
Debug.LogError("Host view was not found");
ResetAllLayouts();
return;
}
var restoreLayout = Path.Combine(layoutsProjectPath, kMaximizeRestoreFile);
UnityObject[] newWindows = InternalEditorUtility.LoadSerializedFileAndForget(restoreLayout);
if (newWindows.Length < 2)
{
Debug.LogError("Maximized serialized file backup not found.");
ResetAllLayouts();
return;
}
SplitView oldRoot = newWindows[0] as SplitView;
EditorWindow oldWindow = newWindows[1] as EditorWindow;
if (oldRoot == null)
{
Debug.LogError("Maximization failed because the root split view was not found.");
ResetAllLayouts();
return;
}
ContainerWindow parentWindow = win.m_Parent.window;
if (parentWindow == null)
{
Debug.LogError("Maximization failed because the root split view has no container window.");
ResetAllLayouts();
return;
}
try
{
ContainerWindow.SetFreezeDisplay(true);
// Put the loaded SplitView where the MaximizedHostView was
if (maximizedHostView.parent)
{
int i = maximizedHostView.parent.IndexOfChild(maximizedHostView);
Rect r = maximizedHostView.position;
View parent = maximizedHostView.parent;
parent.RemoveChild(i);
parent.AddChild(oldRoot, i);
oldRoot.position = r;
// Move the Editor Window to the right spot in the
DockArea newDockArea = oldWindow.m_Parent as DockArea;
int oldDockAreaIndex = newDockArea.m_Panes.IndexOf(oldWindow);
maximizedHostView.actualView = null;
win.m_Parent = null;
newDockArea.AddTab(oldDockAreaIndex, win);
newDockArea.RemoveTab(oldWindow);
UnityObject.DestroyImmediate(oldWindow);
foreach (UnityObject o in newWindows)
{
EditorWindow curWin = o as EditorWindow;
if (curWin != null)
curWin.MakeParentsSettingsMatchMe();
}
parent.Initialize(parent.window);
//If parent window had to be resized, call this to make sure new size gets propagated
parent.position = parent.position;
oldRoot.Reflow();
}
else
{
throw new LayoutException("No parent view");
}
// Kill the maximizedMainView
UnityObject.DestroyImmediate(maximizedHostView);
win.Focus();
var gv = win as GameView;
if (gv != null)
gv.m_Parent.EnableVSync(gv.vSyncEnabled);
parentWindow.DisplayAllViews();
win.m_Parent.MakeVistaDWMHappyDance();
}
catch (Exception ex)
{
Debug.Log("Maximization failed: " + ex);
ResetAllLayouts();
}
try
{
// Weird bug on AMD graphic cards under OSX Lion: Sometimes when unmaximizing we get stray white rectangles.
// work around that by issuing an extra repaint (case 438764)
if (Application.platform == RuntimePlatform.OSXEditor && SystemInfo.operatingSystem.Contains("10.7") && SystemInfo.graphicsDeviceVendor.Contains("ATI"))
{
foreach (GUIView v in Resources.FindObjectsOfTypeAll(typeof(GUIView)))
v.Repaint();
}
}
finally
{
ContainerWindow.SetFreezeDisplay(false);
}
}
internal static void MaximizeGestureHandler()
{
if (Event.current.type != EditorGUIUtility.magnifyGestureEventType || GUIUtility.hotControl != 0)
return;
var mouseOverWindow = EditorWindow.mouseOverWindow;
if (mouseOverWindow == null)
return;
var args = new ShortcutArguments { stage = ShortcutStage.End };
if (IsMaximized(mouseOverWindow))
args.context = Event.current.delta.x < -0.05f ? mouseOverWindow : null;
else
args.context = Event.current.delta.x > 0.05f ? mouseOverWindow : null;
if (args.context != null)
MaximizeKeyHandler(args);
}
[Shortcut("Window/Maximize View", KeyCode.Space, ShortcutModifiers.Shift)]
[FormerlyPrefKeyAs("Window/Maximize View", "# ")]
internal static void MaximizeKeyHandler(ShortcutArguments args)
{
if (args.context is PreviewWindow)
return;
var mouseOverWindow = EditorWindow.mouseOverWindow;
if (mouseOverWindow != null)
{
if (IsMaximized(mouseOverWindow))
Unmaximize(mouseOverWindow);
else
Maximize(mouseOverWindow);
}
}
private static View FindRootSplitView(EditorWindow win)
{
View itor = win.m_Parent.parent;
View rootSplit = itor;
while (itor is SplitView)
{
rootSplit = itor;
itor = itor.parent;
}
return rootSplit;
}
public static void AddSplitViewAndChildrenRecurse(View splitview, ArrayList list)
{
list.Add(splitview);
DockArea dock = splitview as DockArea;
if (dock != null)
{
list.AddRange(dock.m_Panes);
list.Add(dock.actualView);
}
foreach (View child in splitview.children)
AddSplitViewAndChildrenRecurse(child, list);
}
public static void SaveSplitViewAndChildren(View splitview, EditorWindow win, string path)
{
ArrayList all = new ArrayList();
AddSplitViewAndChildrenRecurse(splitview, all);
all.Remove(splitview);
all.Remove(win);
all.Insert(0, splitview);
all.Insert(1, win);
if (EnsureDirectoryCreated(path))
InternalEditorUtility.SaveToSerializedFileAndForget(all.ToArray(typeof(UnityObject)) as UnityObject[], path, true);
}
static bool EnsureDirectoryCreated(string path)
{
var parentFolderPath = Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(parentFolderPath))
return false;
if (!Directory.Exists(parentFolderPath))
Directory.CreateDirectory(parentFolderPath);
return true;
}
public static void Maximize(EditorWindow win)
{
bool maximizePending = MaximizePrepare(win);
if (maximizePending)
MaximizePresent(win);
}
public static bool MaximizePrepare(EditorWindow win)
{
View rootSplit = FindRootSplitView(win);
View itor = rootSplit.parent;
// Make sure it has a dockarea
DockArea dockArea = win.m_Parent as DockArea;
if (dockArea == null)
return false;
if (itor == null)
return false;
var mainView = rootSplit.parent as MainView;
if (mainView == null)
return false;
ContainerWindow parentWindow = win.m_Parent.window;
if (parentWindow == null)
return false;
int oldDockIndex = dockArea.m_Panes.IndexOf(win);
if (oldDockIndex == -1)
return false;
if (!parentWindow.CanCloseAllExcept(win))
return false;
dockArea.selected = oldDockIndex;
// Save current state to disk
SaveSplitViewAndChildren(rootSplit, win, Path.Combine(layoutsProjectPath, kMaximizeRestoreFile));
// Remove the window from the HostView now in order to invoke OnBecameInvisible before OnBecameVisible
dockArea.actualView = null;
dockArea.m_Panes[oldDockIndex] = null;
MaximizedHostView maximizedHostView = ScriptableObject.CreateInstance<MaximizedHostView>();
int i = itor.IndexOfChild(rootSplit);
Rect p = rootSplit.position;
itor.RemoveChild(rootSplit);
itor.AddChild(maximizedHostView, i);
maximizedHostView.actualView = win;
maximizedHostView.position = p; // Must be set after actualView so that value is propagated
var gv = win as GameView;
if (gv != null)
maximizedHostView.EnableVSync(gv.vSyncEnabled);
UnityObject.DestroyImmediate(rootSplit, true);
return true;
}
public static void MaximizePresent(EditorWindow win)
{
ContainerWindow.SetFreezeDisplay(true);
win.Focus();
CheckWindowConsistency();
ContainerWindow parentWindow = win.m_Parent.window;
parentWindow.DisplayAllViews();
win.m_Parent.MakeVistaDWMHappyDance();
ContainerWindow.SetFreezeDisplay(false);
win.OnMaximized();
}
static void DeleteWindowLayout(string path)
{
var name = Path.GetFileNameWithoutExtension(path);
if (!EditorUtility.DisplayDialog("Delete Layout", $"Delete window layout '{name}'?", "Delete", "Cancel"))
return;
DeleteWindowLayoutImpl(name, path);
}
[UsedImplicitly] // used by SaveLayoutTests.cs
internal static void DeleteNamedWindowLayoutNoDialog(string name)
{
var path = Path.Combine(layoutsModePreferencesPath, name + ".wlt");
DeleteWindowLayoutImpl(name, path);
}
static void DeleteWindowLayoutImpl(string name, string path)
{
if (Toolbar.lastLoadedLayoutName == name)
Toolbar.lastLoadedLayoutName = null;
File.Delete(path);
ReloadWindowLayoutMenu();
EditorUtility.Internal_UpdateAllMenus();
ShortcutIntegration.instance.RebuildShortcuts();
}
// Attempts to load a layout. If unsuccessful, restores the previous layout.
public static bool TryLoadWindowLayout(string path, bool newProjectLayoutWasCreated)
{
if (LoadWindowLayout(path, newProjectLayoutWasCreated, true, false, true))
return true;
LoadCurrentModeLayout(FindMainWindow());
return false;
}
[Flags]
public enum LoadWindowLayoutFlags
{
None = 0,
NewProjectCreated = 1 << 0,
SetLastLoadedLayoutName = 1 << 1,
KeepMainWindow = 1 << 2,
LogsErrorToConsole = 1 << 3,
NoMainWindowSupport = 1 << 4,
SaveLayoutPreferences = 1 << 5
}
public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated, bool setLastLoadedLayoutName, bool keepMainWindow, bool logErrorsToConsole)
{
var flags = LoadWindowLayoutFlags.SaveLayoutPreferences;
if (newProjectLayoutWasCreated)
flags |= LoadWindowLayoutFlags.NewProjectCreated;
if (setLastLoadedLayoutName)
flags |= LoadWindowLayoutFlags.SetLastLoadedLayoutName;
if (keepMainWindow)
flags |= LoadWindowLayoutFlags.KeepMainWindow;
if (logErrorsToConsole)
flags |= LoadWindowLayoutFlags.LogsErrorToConsole;
return LoadWindowLayout(path, flags);
}
public static bool LoadWindowLayout(string path, LoadWindowLayoutFlags flags)
{
Console.WriteLine($"[LAYOUT] About to load {path}, keepMainWindow={flags.HasFlag(LoadWindowLayoutFlags.KeepMainWindow)}");
if (!Application.isTestRun && !ContainerWindow.CanCloseAll(flags.HasFlag(LoadWindowLayoutFlags.KeepMainWindow)))
return false;
bool mainWindowMaximized = ContainerWindow.mainWindow?.maximized ?? false;
Rect mainWindowPosition = ContainerWindow.mainWindow?.position ?? new Rect();
// Load new windows and show them
try
{
ContainerWindow.SetFreezeDisplay(true);
CloseWindows(flags.HasFlag(LoadWindowLayoutFlags.KeepMainWindow));
ContainerWindow mainWindowToSetSize = null;
ContainerWindow mainWindow = null;
UnityObject[] remainingContainers = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow));
foreach (ContainerWindow window in remainingContainers)
{
if (mainWindow == null && window.showMode == ShowMode.MainWindow)
mainWindow = window;
else
window.Close();
}
// Load data
UnityObject[] loadedWindows = InternalEditorUtility.LoadSerializedFileAndForget(path);
if (loadedWindows == null || loadedWindows.Length == 0)
throw new LayoutException("No windows found in layout.");
List<UnityObject> newWindows = new List<UnityObject>();
// At this point, unparented editor windows are neither desired nor desirable.
// This can be caused by (legacy) serialization of FallbackEditorWindows or
// other serialization hiccups (note that unparented editor windows should not exist in theory).
// Same goes for empty DockAreas (no panes). Leave them behind.
for (int i = 0; i < loadedWindows.Length; i++)
{
UnityObject o = loadedWindows[i];
if (o is EditorWindow editorWin)
{
if (!editorWin || !editorWin.m_Parent || !editorWin.m_Parent.window)
{
Console.WriteLine($"[LAYOUT] Removed un-parented EditorWindow while reading window layout" +
$" window #{i}, type={o.GetType()} instanceID={o.GetInstanceID()}");
UnityObject.DestroyImmediate(editorWin, true);
continue;
}
}
else
{
if (o is ContainerWindow cw && cw.rootView == null)
{
cw.Close();
UnityObject.DestroyImmediate(cw, true);
continue;
}
else if (o is DockArea dockArea && dockArea.m_Panes.Count == 0)
{
dockArea.Close(null);
UnityObject.DestroyImmediate(dockArea, true);
continue;
}
else if (o is HostView hostview && hostview.actualView == null)
{
UnityObject.DestroyImmediate(hostview, true);
continue;
}
}
newWindows.Add(o);
}
for (int i = 0; i < newWindows.Count; i++)
{
ContainerWindow cur = newWindows[i] as ContainerWindow;
if (cur != null && cur.showMode == ShowMode.MainWindow)
{
if (mainWindow == null)
{
mainWindow = cur;
}
else
{
mainWindow.rootView = cur.rootView;
UnityObject.DestroyImmediate(cur, true);
cur = mainWindow;
newWindows[i] = null;
}
if (mainWindowPosition.width != 0.0)
{
mainWindowToSetSize = cur;
// This is the same reference as the mainwindow, so need to freeze it too on for Linux during reload.
mainWindowToSetSize.SetFreeze(true);
mainWindowToSetSize.position = mainWindowPosition;
}
break;
}
}
for (int i = 0; i < newWindows.Count; i++)
{
UnityObject o = newWindows[i];
if (!o)
continue;
if (flags.HasFlag(LoadWindowLayoutFlags.NewProjectCreated))
{
MethodInfo method = o.GetType().GetMethod("OnNewProjectLayoutWasCreated", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
method?.Invoke(o, null);
}
}
if (mainWindowToSetSize)
{
mainWindowToSetSize.SetFreeze(true);
mainWindowToSetSize.position = mainWindowPosition;
}
// Always show main window before other windows. So that other windows can
// get their parent/owner.
if (mainWindow)
{
// Don't adjust height to prevent main window shrink during layout on Linux.
mainWindow.SetFreeze(true);
mainWindow.Show(mainWindow.showMode, loadPosition: true, displayImmediately: true, setFocus: true);
if (mainWindowToSetSize && mainWindow.maximized != mainWindowMaximized)
mainWindow.ToggleMaximize();
// Unfreeze to make sure resize work properly.
mainWindow.SetFreeze(false);
// Make sure to restore the save to layout flag when loading a layout from a file.
if (flags.HasFlag(LoadWindowLayoutFlags.KeepMainWindow))
mainWindow.m_DontSaveToLayout = false;
}
else if (!flags.HasFlag(LoadWindowLayoutFlags.NoMainWindowSupport))
{
throw new LayoutException("Error while reading window layout: no main window found");
}
// Show other windows
for (int i = 0; i < newWindows.Count; i++)
{
if (newWindows[i] == null)
continue;
EditorWindow win = newWindows[i] as EditorWindow;
if (win)
win.minSize = win.minSize; // Causes minSize to be propagated upwards to parents!
ContainerWindow containerWindow = newWindows[i] as ContainerWindow;
if (containerWindow && containerWindow != mainWindow)
{
containerWindow.Show(containerWindow.showMode, loadPosition: false, displayImmediately: true, setFocus: true);
if (flags.HasFlag(LoadWindowLayoutFlags.NoMainWindowSupport))
{
containerWindow.m_DontSaveToLayout = mainWindow != null;
}
}
}
// Un-maximize maximized PlayModeView window if maximize on play is enabled
PlayModeView playModeView = GetMaximizedWindow() as PlayModeView;
if (playModeView != null && playModeView.enterPlayModeBehavior == PlayModeView.EnterPlayModeBehavior.PlayMaximized)
Unmaximize(playModeView);
}
catch (Exception ex)
{
// When loading a new project we don't want to log an error if one of the last saved layouts throws.
// There isn't anything useful a user can do about it, and we can gracefully recover. However when a
// layout is loaded from the menu or a mode change, we do want to let the user know about layout loading
// problems because they can act on it by either deleting the layout or importing whatever asset is
// missing.
var error = $"Failed to load window layout \"{path}\": {ex}";
if(flags.HasFlag(LoadWindowLayoutFlags.LogsErrorToConsole))
Debug.LogError(error);
else
Console.WriteLine($"[LAYOUT] {error}");
return false;
}
finally
{
ContainerWindow.SetFreezeDisplay(false);
if (flags.HasFlag(LoadWindowLayoutFlags.SetLastLoadedLayoutName) && Path.GetExtension(path) == ".wlt")
Toolbar.lastLoadedLayoutName = Path.GetFileNameWithoutExtension(path);
else
Toolbar.lastLoadedLayoutName = null;
}
if (flags.HasFlag(LoadWindowLayoutFlags.SaveLayoutPreferences))
SaveDefaultWindowPreferences();
return true;
}
internal static void LoadDefaultLayout()
{
InitializeLayoutPreferencesFolder();
FileUtil.DeleteFileOrDirectory(ProjectLayoutPath);
if (EnsureDirectoryCreated(ProjectLayoutPath))
{
Console.WriteLine($"[LAYOUT] LoadDefaultLayout: Copying Project Current Layout: {ProjectLayoutPath} from {GetDefaultLayoutPath()}");
FileUtil.CopyFileOrDirectory(GetDefaultLayoutPath(), ProjectLayoutPath);
}
Debug.Assert(File.Exists(ProjectLayoutPath));
LoadWindowLayout(ProjectLayoutPath, true, true, false, false);
}
public static void CloseWindows()
{
CloseWindows(false);
}
private static void CloseWindows(bool keepMainWindow)
{
try
{
// ForceClose any existing tooltips
TooltipView.ForceClose();
}
catch (Exception)
{
// ignored
}
// ForceClose all container windows
ContainerWindow mainWindow = null;
UnityObject[] containers = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow));
foreach (ContainerWindow window in containers)
{
try
{
if (window.showMode != ShowMode.MainWindow || !keepMainWindow || mainWindow != null)
{
window.Close();
UnityObject.DestroyImmediate(window, true);
}
else
{
UnityObject.DestroyImmediate(window.rootView, true);
window.rootView = null;
mainWindow = window;
}
}
catch (Exception)
{
// ignored
}
}
// Double check correct closing
UnityObject[] oldWindows = Resources.FindObjectsOfTypeAll(typeof(EditorWindow));
if (oldWindows.Length != 0)
{
string output = "";
foreach (EditorWindow killme in oldWindows)
{
output += $"{killme.GetType().Name} {killme.name} {killme.titleContent.text} [{killme.GetInstanceID()}]\r\n";
UnityObject.DestroyImmediate(killme, true);
}
}
UnityObject[] oldViews = Resources.FindObjectsOfTypeAll(typeof(View));
if (oldViews.Length != 0)
{
foreach (View killme in oldViews)
UnityObject.DestroyImmediate(killme, true);
}
}
internal static void SaveWindowLayout(string path)
{
SaveWindowLayout(path, true);
}
public static void SaveWindowLayout(string path, bool reportErrors)
{
if (!EnsureDirectoryCreated(path))
return;
Console.WriteLine($"[LAYOUT] About to save layout {path}");
TooltipView.ForceClose();
UnityObject[] windows = Resources.FindObjectsOfTypeAll(typeof(EditorWindow));
UnityObject[] containers = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow));
UnityObject[] views = Resources.FindObjectsOfTypeAll(typeof(View));
var all = new List<UnityObject>();
var ignoredViews = new List<ScriptableObject>();
foreach (ContainerWindow w in containers)
{
// skip ContainerWindows that are "dont save me"
if (!w || w.m_DontSaveToLayout)
ignoredViews.Add(w);
else
all.Add(w);
}
foreach (View w in views)
{
// skip Views that belong to "dont save me" container
if (!w || !w.window || ignoredViews.Contains(w.window))
ignoredViews.Add(w);
else
all.Add(w);
}
foreach (EditorWindow w in windows)
{
// skip EditorWindows that belong to "dont save me" container
if (!w || !w.m_Parent || ignoredViews.Contains(w.m_Parent))
{
if (reportErrors && w)
Debug.LogWarning($"Cannot save invalid window {w.titleContent.text} {w} to layout.");
continue;
}
all.Add(w);
}
if (all.Any())
InternalEditorUtility.SaveToSerializedFileAndForget(all.Where(o => o).ToArray(), path, true);
}
// ReSharper disable once MemberCanBePrivate.Global - used by SaveLayoutTests.cs
internal static void SaveGUI()
{
UnityEditor.SaveWindowLayout.ShowWindow();
}
public static void LoadFromFile()
{
var layoutFilePath = EditorUtility.OpenFilePanelWithFilters("Load layout from disk...", "", new[] {"Layout", "wlt"});
if (string.IsNullOrEmpty(layoutFilePath))
return;
TryLoadWindowLayout(layoutFilePath, false);
}
public static void SaveToFile()
{
var layoutFilePath = EditorUtility.SaveFilePanel("Save layout to disk...", "", "layout", "wlt");
if (String.IsNullOrEmpty(layoutFilePath))
return;
SaveWindowLayout(layoutFilePath);
EditorUtility.RevealInFinder(layoutFilePath);
}
private static void ResetUserLayouts()
{
// Copy installation layouts to user global layouts and overwrite any existing ones.
var layoutPaths = Directory.GetFiles(layoutResourcesPath, "*.wlt");
foreach (var installationLayoutPath in layoutPaths)
{
var layoutFilename = Path.GetFileName(installationLayoutPath);
var userLayoutDstPath = FileUtil.CombinePaths(layoutsDefaultModePreferencesPath, layoutFilename);
FileUtil.CopyFileIfExists(installationLayoutPath, userLayoutDstPath, overwrite: true);
}
// delete per-project layouts
if (Directory.Exists(layoutsProjectPath))
Directory.Delete(layoutsProjectPath, true);
// delete per-user layouts
if (Directory.Exists(layoutsCurrentModePreferencesPath))
Directory.Delete(layoutsCurrentModePreferencesPath, true);
}
public static void ResetAllLayouts(bool quitOnCancel = true)
{
if (!Application.isTestRun && !EditorUtility.DisplayDialog("Revert All Window Layouts",
"Unity is about to delete all window layouts and restore them to the default settings.",
"Continue", quitOnCancel ? "Quit" : "Cancel"))
{
if (quitOnCancel)
EditorApplication.Exit(0);
return;
}
ResetFactorySettings();
}
public static void ResetFactorySettings()
{
// Reset user layouts
ResetUserLayouts();
// Reset mode settings
ModeService.ChangeModeById("default");
LoadCurrentModeLayout(keepMainWindow: false);
ReloadWindowLayoutMenu();
EditorUtility.Internal_UpdateAllMenus();
ShortcutIntegration.instance.RebuildShortcuts();
}
}
[EditorWindowTitle(title = "Save Layout")]
internal class SaveWindowLayout : EditorWindow
{
bool m_DidFocus;
const int k_Width = 200;
const int k_Height = 48;
const int k_HelpBoxHeight = 40;
const int k_MaxLayoutNameLength = 128;
static readonly string k_InvalidChars = EditorUtility.GetInvalidFilenameChars();
static readonly string s_InvalidCharsFormatString = L10n.Tr("Invalid characters: {0}");
string m_CurrentInvalidChars = "";
string m_LayoutName = Toolbar.lastLoadedLayoutName;
internal static SaveWindowLayout ShowWindow()
{
SaveWindowLayout w = GetWindowDontShow<SaveWindowLayout>();
w.minSize = w.maxSize = new Vector2(k_Width, k_Height);
w.m_Pos = new Rect(0, 0,k_Width, k_Height);
w.ShowAuxWindow();
return w;
}
void UpdateCurrentInvalidChars()
{
m_CurrentInvalidChars = new string(m_LayoutName.Intersect(k_InvalidChars).Distinct().ToArray());
}
void OnEnable()
{
titleContent = GetLocalizedTitleContent();
}
void OnGUI()
{
GUILayout.Space(5);
Event evt = Event.current;
bool hitEnter = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter);
bool hitEscape = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Escape);
if (hitEscape)
{
Close();
GUIUtility.ExitGUI();
}
GUI.SetNextControlName("m_PreferencesName");
EditorGUI.BeginChangeCheck();
m_LayoutName = EditorGUILayout.TextField(m_LayoutName);
if (EditorGUI.EndChangeCheck())
{
if (m_LayoutName.Length > k_MaxLayoutNameLength)
{
m_LayoutName = m_LayoutName.Substring(0, k_MaxLayoutNameLength);
}
m_LayoutName = m_LayoutName.TrimEnd();
UpdateCurrentInvalidChars();
}
if (!m_DidFocus)
{
m_DidFocus = true;
EditorGUI.FocusTextInControl("m_PreferencesName");
}
if (m_CurrentInvalidChars.Length != 0)
{
EditorGUILayout.HelpBox(string.Format(s_InvalidCharsFormatString, m_CurrentInvalidChars), MessageType.Warning);
minSize = new Vector2(k_Width, k_Height + k_HelpBoxHeight);
}
else
{
minSize = new Vector2(k_Width, k_Height);
}
bool canSaveLayout = m_LayoutName.Length > 0 && m_CurrentInvalidChars.Length == 0;
EditorGUI.BeginDisabled(!canSaveLayout);
if (GUILayout.Button("Save") || hitEnter && canSaveLayout)
{
Close();
if (!Directory.Exists(WindowLayout.layoutsModePreferencesPath))
Directory.CreateDirectory(WindowLayout.layoutsModePreferencesPath);
string path = Path.Combine(WindowLayout.layoutsModePreferencesPath, m_LayoutName + ".wlt");
if (File.Exists(path))
{
if (!EditorUtility.DisplayDialog("Overwrite layout?",
"Do you want to overwrite '" + m_LayoutName + "' layout?",
"Overwrite", "Cancel"))
GUIUtility.ExitGUI();
}
Toolbar.lastLoadedLayoutName = m_LayoutName;
WindowLayout.SaveWindowLayout(path);
WindowLayout.ReloadWindowLayoutMenu();
EditorUtility.Internal_UpdateAllMenus();
ShortcutIntegration.instance.RebuildShortcuts();
GUIUtility.ExitGUI();
}
else
{
m_DidFocus = false;
}
EditorGUI.EndDisabled();
}
}
internal static class CreateBuiltinWindows
{
[MenuItem("Window/General/Scene %1", false, 1)]
static void ShowSceneView()
{
EditorWindow.GetWindow<SceneView>();
}
[MenuItem("Window/General/Game %2", false, 2)]
static void ShowGameView()
{
EditorWindow.GetWindow<GameView>();
}
[MenuItem("Window/General/Inspector %3", false, 3)]
static void ShowInspector()
{
EditorWindow.GetWindow<InspectorWindow>();
}
[MenuItem("Window/General/Hierarchy %4", false, 4)]
static void ShowNewHierarchy()
{
EditorWindow.GetWindow<SceneHierarchyWindow>();
}
[MenuItem("Window/General/Project %5", false, 5)]
static void ShowProject()
{
EditorWindow.GetWindow<ProjectBrowser>();
}
[MenuItem("Window/Animation/Animation %6", false, 1)]
static void ShowAnimationWindow()
{
EditorWindow.GetWindow<AnimationWindow>();
}
[MenuItem("Window/Audio/Audio Random Container", false, 1)]
static void ShowAudioRandomContainerWindow()
{
AudioContainerWindow.CreateAudioRandomContainerWindow();
}
[MenuItem("Window/Audio/Audio Mixer %8", false, 2)]
static void ShowAudioMixer()
{
AudioMixerWindow.CreateAudioMixerWindow();
}
// Version Control is registered from native code (EditorWindowController.cpp), for license check
// [MenuItem ("Window/Version Control", false, 2010)]
[RequiredByNativeCode]
static void ShowVersionControl()
{
EditorWindow.GetWindow<WindowPending>();
}
[MenuItem("Window/General/Console %#c", false, 6)]
static void ShowConsole()
{
EditorWindow.GetWindow<ConsoleWindow>();
}
}
internal class WindowFocusState : ScriptableObject
{
private static WindowFocusState m_Instance;
internal string m_LastWindowTypeInSameDock = "";
internal bool m_WasMaximizedBeforePlay = false;
internal bool m_CurrentlyInPlayMode = false;
internal static WindowFocusState instance
{
get
{
if (m_Instance == null)
m_Instance = FindFirstObjectByType(typeof(WindowFocusState)) as WindowFocusState;
if (m_Instance == null)
m_Instance = CreateInstance<WindowFocusState>();
return m_Instance;
}
}
void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
m_Instance = this;
}
}
} // namespace
| UnityCsReference/Editor/Mono/GUI/WindowLayout.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/WindowLayout.cs",
"repo_id": "UnityCsReference",
"token_count": 36305
} | 302 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Editor/Mono/GameObjectUtility.bindings.h")]
[NativeHeader("Editor/Src/CommandImplementation.h")]
public sealed partial class GameObjectUtility
{
public static extern StaticEditorFlags GetStaticEditorFlags(GameObject go);
public static extern void SetStaticEditorFlags(GameObject go, StaticEditorFlags flags);
public static extern bool AreStaticEditorFlagsSet(GameObject go, StaticEditorFlags flags);
internal static extern string GetFirstItemPathAfterGameObjectCreationMenuItems();
public static extern string GetUniqueNameForSibling(Transform parent, string name);
public static extern void EnsureUniqueNameForSibling(GameObject self);
internal static bool ContainsStatic(GameObject[] objects)
{
if (objects == null || objects.Length == 0)
return false;
for (int i = 0; i < objects.Length; i++)
{
if (objects[i] != null && objects[i].isStatic)
return true;
}
return false;
}
internal static bool ContainsMainStageGameObjects(GameObject[] objects)
{
if (objects == null || objects.Length == 0)
return false;
for (int i = 0; i < objects.Length; i++)
{
if (objects[i] != null && StageUtility.GetStageHandle(objects[i]).isMainStage)
return true;
}
return false;
}
internal static bool HasChildren(IEnumerable<GameObject> gameObjects)
{
return gameObjects.Any(go => go.transform.childCount > 0);
}
internal enum ShouldIncludeChildren
{
HasNoChildren = -1,
IncludeChildren = 0,
DontIncludeChildren = 1,
Cancel = 2
}
internal static ShouldIncludeChildren DisplayUpdateChildrenDialogIfNeeded(IEnumerable<GameObject> gameObjects,
string title, string message)
{
if (!HasChildren(gameObjects))
return ShouldIncludeChildren.HasNoChildren;
return
(ShouldIncludeChildren)
EditorUtility.DisplayDialogComplex(title, message, L10n.Tr("Yes, change children"), L10n.Tr("No, this object only"), L10n.Tr("Cancel"));
}
public static void SetParentAndAlign(GameObject child, GameObject parent)
{
if (parent == null)
return;
child.transform.SetParent(parent.transform, false);
RectTransform rectTransform = child.transform as RectTransform;
if (rectTransform)
{
rectTransform.anchoredPosition = Vector2.zero;
Vector3 localPosition = rectTransform.localPosition;
localPosition.z = 0;
rectTransform.localPosition = localPosition;
}
else
{
child.transform.localPosition = Vector3.zero;
}
child.transform.localRotation = Quaternion.identity;
child.transform.localScale = Vector3.one;
SetLayerRecursively(child, parent.layer);
}
internal static void SetDefaultParentForNewObject(GameObject gameObject, Transform parent = null, bool align = false)
{
if (parent == null && (parent = SceneView.GetDefaultParentObjectIfSet()) == null)
{
return;
}
if(align)
{
GameObjectUtility.SetParentAndAlign(gameObject, parent?.gameObject);
}
else
{
gameObject.transform.SetParent(parent);
}
}
private static void SetLayerRecursively(GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer);
}
[FreeFunction]
public static extern int GetMonoBehavioursWithMissingScriptCount([NotNull] GameObject go);
[FreeFunction]
public static extern int RemoveMonoBehavioursWithMissingScript([NotNull] GameObject go);
public static ulong ModifyMaskIfGameObjectIsHiddenForPrefabModeInContext(ulong sceneCullingMask, GameObject gameObject)
{
if (!IsPrefabInstanceHiddenForInContextEditing(gameObject))
return sceneCullingMask;
return sceneCullingMask & ~SceneManagement.SceneCullingMasks.MainStageExcludingPrefabInstanceObjectsOpenInPrefabMode;
}
internal static extern bool IsPrefabInstanceHiddenForInContextEditing([NotNull] GameObject go);
public static GameObject[] DuplicateGameObjects(GameObject[] gameObjects)
{
if (gameObjects == null)
throw new System.ArgumentNullException("gameObjects array is null");
if (gameObjects.Length == 0)
return new GameObject[0];
foreach (GameObject go in gameObjects)
{
if (go == null)
throw new System.ArgumentNullException("GameObject in gameObjects array is null");
if (EditorUtility.IsPersistent(go))
throw new System.ArgumentException("Duplicating Assets is unsupported by this function. Use AssetDatabase.CopyAsset to duplicate Assets.");
}
return DuplicateGameObjects_Internal(gameObjects);
}
public static GameObject DuplicateGameObject(GameObject gameObject)
{
if (gameObject == null)
throw new System.ArgumentNullException("gameObject is null");
if (EditorUtility.IsPersistent(gameObject))
throw new System.ArgumentException("Duplicating Assets is unsupported by this function. Use AssetDatabase.CopyAsset to duplicate Assets.");
var gameObjects = DuplicateGameObjects_Internal(new[] { gameObject });
if (gameObjects.Length != 0)
return gameObjects[0];
else
return null;
}
[NativeMethod("DuplicateGameObjects", IsFreeFunction = true)]
extern private static GameObject[] DuplicateGameObjects_Internal(GameObject[] gameObjects);
}
}
| UnityCsReference/Editor/Mono/GameObjectUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GameObjectUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2894
} | 303 |
// 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 Object = UnityEngine.Object;
namespace UnityEditor
{
[NativeHeader("Runtime/Shaders/Material.h"), StaticAccessor("Material", StaticAccessorType.DoubleColon)]
[NativeHeader("Editor/Mono/Graphics/EditorMaterialUtility.bindings.h")]
[NativeHeader("Runtime/Shaders/MaterialIsBackground.h")]
public sealed partial class EditorMaterialUtility
{
[NativeProperty("disableApplyMaterialPropertyDrawers", false, TargetType.Field)]
extern internal static bool disableApplyMaterialPropertyDrawers { get; set; }
[FreeFunction("EditorMaterialUtilityBindings::ResetDefaultTextures")]
extern public static void ResetDefaultTextures([NotNull] Material material, bool overrideSetTextures);
[FreeFunction]
extern public static bool IsBackgroundMaterial([NotNull] Material material);
[FreeFunction("EditorMaterialUtilityBindings::SetShaderDefaults")]
extern public static void SetShaderDefaults([NotNull] Shader shader, string[] name, Texture[] textures);
[FreeFunction("EditorMaterialUtilityBindings::SetShaderNonModifiableDefaults")]
extern public static void SetShaderNonModifiableDefaults([NotNull] Shader shader, string[] name, Texture[] textures);
[FreeFunction("EditorMaterialUtilityBindings::GetShaderDefaultTexture")]
extern internal static Texture GetShaderDefaultTexture([NotNull] Shader shader, string name);
[FreeFunction("EditorMaterialUtilityBindings::GetMaterialParentFromFile")]
extern internal static GUID GetMaterialParentFromFile(string assetPath);
}
}
| UnityCsReference/Editor/Mono/Graphics/EditorMaterialUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Graphics/EditorMaterialUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 551
} | 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;
using UnityEditor;
using UnityEngine;
namespace UnityEditorInternal
{
internal class Button
{
internal static bool Do(int id, Vector3 position, Quaternion direction, float size, float pickSize, Handles.CapFunction capFunction, bool useLayoutAndMouseMove)
{
if(!useLayoutAndMouseMove)
{
Event evt = Event.current;
if(evt.type == EventType.Layout || evt.type == EventType.MouseMove)
{
//Consuming event id
evt.GetTypeForControl(id);
return false;
}
}
return Do(id, position, direction, size, pickSize, capFunction);
}
public static bool Do(int id, Vector3 position, Quaternion direction, float size, float pickSize, Handles.CapFunction capFunction)
{
Event evt = Event.current;
switch (evt.GetTypeForControl(id))
{
case EventType.Layout:
if (GUI.enabled)
capFunction(id, position, direction, pickSize, EventType.Layout);
break;
case EventType.MouseMove:
if (HandleUtility.nearestControl == id)
HandleUtility.Repaint();
break;
case EventType.MouseDown:
// am I closest to the thingy?
if (HandleUtility.nearestControl == id && ((evt.button == 0 || evt.button == 2) && !evt.alt))
{
GUIUtility.hotControl = id; // Grab mouse focus
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2))
{
GUIUtility.hotControl = 0;
evt.Use();
if (HandleUtility.nearestControl == id)
return true;
}
break;
case EventType.Repaint:
Color origColor = Handles.color;
if (HandleUtility.nearestControl == id && GUI.enabled && GUIUtility.hotControl == 0 && !evt.alt)
Handles.color = Handles.preselectionColor;
capFunction(id, position, direction, size, EventType.Repaint);
Handles.color = origColor;
break;
}
return false;
}
}
}
| UnityCsReference/Editor/Mono/Handles/Button.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/Button.cs",
"repo_id": "UnityCsReference",
"token_count": 1489
} | 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 UnityEditor;
using UnityEngine;
namespace UnityEditorInternal
{
internal class Slider1D
{
// Used for plane intersection translation
static Vector3 s_ConstraintOrigin, s_ConstraintDirection, s_HandleOffset;
static float s_StartHandleSize;
static Matrix4x4 s_StartInverseHandleMatrix;
// Used for 2D translation (fallback when ray plane intersection fails)
static Vector2 s_StartMousePosition;
static Vector3 s_StartPosition;
internal static Vector3 Do(int id, Vector3 position, Vector3 direction, float size, Handles.CapFunction capFunction, float snap)
{
return Do(id, position, Vector3.zero, direction, direction, size, capFunction, snap);
}
private static Quaternion ToQuaternion(Vector3 direction)
{
if (direction == Vector3.zero)
{
return Quaternion.identity;
}
return Quaternion.LookRotation(direction);
}
internal static Vector3 Do(int id, Vector3 position, Vector3 offset, Vector3 handleDirection, Vector3 slideDirection, float size, Handles.CapFunction capFunction, float snap)
{
Event evt = Event.current;
var eventType = evt.GetTypeForControl(id);
switch (eventType)
{
case EventType.Layout:
case EventType.MouseMove:
if (capFunction != null)
capFunction(id, position + offset, ToQuaternion(handleDirection), size, EventType.Layout);
else
HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + offset, size * .2f));
break;
case EventType.MouseDown:
// am I closest to the thingy?
if (HandleUtility.nearestControl == id && evt.button == 0 && GUIUtility.hotControl == 0 && !evt.alt)
{
GUIUtility.hotControl = id; // Grab mouse focus
s_StartMousePosition = evt.mousePosition;
s_ConstraintOrigin = Handles.matrix.MultiplyPoint3x4(position);
s_StartPosition = position;
s_ConstraintDirection = Handles.matrix.MultiplyVector(slideDirection);
s_HandleOffset = HandleUtility.CalcPositionOnConstraint(Camera.current, evt.mousePosition, s_ConstraintOrigin, s_ConstraintDirection, out Vector3 point)
? s_ConstraintOrigin - point
: Vector3.zero;
evt.Use();
s_StartHandleSize = HandleUtility.GetHandleSize(point);
s_StartInverseHandleMatrix = Handles.inverseMatrix;
}
break;
case EventType.MouseDrag:
capFunction?.Invoke(id, position + offset, ToQuaternion(handleDirection), size, EventType.Layout);
if (GUIUtility.hotControl == id)
{
// First try to calculate the translation by casting a mouse ray against a world position plane
// oriented towards the camera. This gives more accurate results than doing the line translation
// in 2D space, but is more prone towards skewing extreme values when the ray is near parallel
// to the plane. To address this, CalcPositionOnConstraint will fail if the mouse ray is close
// to parallel (see HandleUtility.k_MinRayConstraintDot) and fall back to 2D based movement.
if (HandleUtility.CalcPositionOnConstraint(Camera.current, evt.mousePosition, s_ConstraintOrigin, s_ConstraintDirection, out Vector3 worldPosition))
{
var handleOffset = s_HandleOffset * (HandleUtility.GetHandleSize(worldPosition) / s_StartHandleSize);
worldPosition += handleOffset;
if (EditorSnapSettings.incrementalSnapActive)
{
Vector3 dir = worldPosition - s_ConstraintOrigin;
float dist = Handles.SnapValue(dir.magnitude, snap) * Mathf.Sign(Vector3.Dot(s_ConstraintDirection, dir));
worldPosition = s_ConstraintOrigin + s_ConstraintDirection.normalized * dist;
}
else if (EditorSnapSettings.gridSnapActive)
{
worldPosition = Snapping.Snap(worldPosition, GridSettings.size, (SnapAxis) new SnapAxisFilter(s_ConstraintDirection));
}
position = s_StartInverseHandleMatrix.MultiplyPoint(worldPosition);
s_StartPosition = position;
s_StartMousePosition = evt.mousePosition;
}
else
{
// Unlike HandleUtility.CalcPositionOnConstraint, CalcLineTranslation _does_ multiply constraint
// origin and direction by Handles.matrix, so make sure to pass in unmodified vectors here
float dist = HandleUtility.CalcLineTranslation(s_StartMousePosition, evt.mousePosition, s_StartPosition, slideDirection);
dist = Handles.SnapValue(dist, snap);
worldPosition = Handles.matrix.MultiplyPoint(s_StartPosition) + s_ConstraintDirection * dist;
if (EditorSnapSettings.gridSnapActive)
worldPosition = Snapping.Snap(worldPosition, GridSettings.size, (SnapAxis) new SnapAxisFilter(s_ConstraintDirection));
position = Handles.inverseMatrix.MultiplyPoint(worldPosition);
}
GUI.changed = true;
evt.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2))
{
GUIUtility.hotControl = 0;
evt.Use();
}
break;
case EventType.Repaint:
Handles.SetupHandleColor(id, evt, out var prevColor, out var thickness);
capFunction(id, position + offset, ToQuaternion(handleDirection), size, EventType.Repaint);
Handles.color = prevColor;
break;
}
return position;
}
}
}
| UnityCsReference/Editor/Mono/Handles/Slider1D.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/Slider1D.cs",
"repo_id": "UnityCsReference",
"token_count": 3519
} | 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 UnityEditor;
namespace UnityEditor
{
// Interface for drag-dropping windows over each other.
// Must be implemented by anyone who can handle a dragged tab.
internal interface IDropArea
{
// Fill out a dropinfo class telling what should be done.
// NULL if no action
DropInfo DragOver(EditorWindow w, Vector2 screenPos);
// If the client returned a DropInfo from the DragOver, they will get this call when the user releases the mouse
bool PerformDrop(EditorWindow w, DropInfo dropInfo, Vector2 screenPos);
}
}
| UnityCsReference/Editor/Mono/IDropArea.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/IDropArea.cs",
"repo_id": "UnityCsReference",
"token_count": 230
} | 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 UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(SpeedTreeImporter))]
[CanEditMultipleObjects]
internal class SpeedTreeImporterInspector : AssetImporterTabbedEditor
{
private static class Styles
{
public static GUIContent ApplyAndGenerate = EditorGUIUtility.TrTextContent("Apply & Generate Materials", "Apply current importer settings and generate materials with new settings.");
public static GUIContent Regenerate = EditorGUIUtility.TrTextContent("Regenerate Materials", "Regenerate materials from the current importer settings.");
public static GUIContent RegenerateRemapped = EditorGUIUtility.TrTextContent("Regenerate Materials", "Regenerate the remapped materials from the current import settings.");
public static GUIContent ApplyAndGenerateRemapped = EditorGUIUtility.TrTextContent("Apply & Generate Materials", "Apply current importer settings and regenerate the remapped materials with new settings.");
}
private SerializedProperty m_MaterialLocation;
private SerializedProperty m_Materials;
private bool m_HasRemappedMaterials = false;
public override void OnEnable()
{
m_MaterialLocation = serializedObject.FindProperty("m_MaterialLocation");
m_Materials = serializedObject.FindProperty("m_Materials");
if (tabs == null)
{
tabs = new BaseAssetImporterTabUI[] { new SpeedTreeImporterModelEditor(this), new SpeedTreeImporterMaterialEditor(this) };
m_TabNames = new string[] { "Model", "Materials" };
}
base.OnEnable();
}
public override void OnDisable()
{
foreach (var tab in tabs)
{
tab.OnDisable();
}
base.OnDisable();
}
//None of the ModelImporter sub editors support multi preview
public override bool HasPreviewGUI()
{
return base.HasPreviewGUI() && targets.Length < 2;
}
public override GUIContent GetPreviewTitle()
{
var tab = activeTab as ModelImporterClipEditor;
if (tab != null)
return new GUIContent(tab.selectedClipName);
return base.GetPreviewTitle();
}
// Only show the imported GameObject when the Model tab is active
public override bool showImportedObject { get { return activeTab is SpeedTreeImporterModelEditor; } }
internal IEnumerable<SpeedTreeImporter> importers
{
get { return targets.Cast<SpeedTreeImporter>(); }
}
internal bool upgradeMaterials
{
get { return importers.Any(i => i.materialsShouldBeRegenerated); }
}
internal GUIContent GetGenButtonText(bool modified, bool upgrade)
{
if (modified || upgrade)
{
if (m_MaterialLocation.intValue == (int)SpeedTreeImporter.MaterialLocation.External)
return Styles.ApplyAndGenerate;
else
return Styles.ApplyAndGenerateRemapped;
}
else
{
if (m_MaterialLocation.intValue == (int)SpeedTreeImporter.MaterialLocation.External)
return Styles.Regenerate;
else
return Styles.RegenerateRemapped;
}
}
protected override bool OnApplyRevertGUI()
{
bool applied = base.OnApplyRevertGUI();
bool hasModified = HasModified();
if (tabs == null) // Hitting apply, we lose the tabs object within base.OnApplyRevertGUI()
{
if(hasModified)
Apply();
return applied;
}
bool doMatsHaveDifferentShaders = (tabs[0] as SpeedTreeImporterModelEditor).doMaterialsHaveDifferentShader;
if (HasRemappedMaterials() || doMatsHaveDifferentShaders)
{
// Force material upgrade when a custom render pipeline is active so that render pipeline-specific material
// modifications may be applied.
bool upgrade = upgradeMaterials || (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline != null);
if (GUILayout.Button(GetGenButtonText(hasModified, upgrade)))
{
// Apply the changes and generate the materials before importing so that asset previews are up-to-date.
if (hasModified)
Apply();
if (upgrade)
{
foreach (var importer in importers)
importer.SetMaterialVersionToCurrent();
}
GenerateMaterials();
if (hasModified || upgrade)
{
SaveChanges();
applied = true;
}
}
}
return applied;
}
private void GenerateMaterials()
{
var matFolders = importers.Where(im => im.materialLocation == SpeedTreeImporter.MaterialLocation.External).Select(im => im.materialFolderPath).ToList();
var guids = AssetDatabase.FindAssets("t:Material", matFolders.ToArray());
var paths = guids.Select(guid => AssetDatabase.GUIDToAssetPath(guid)).ToList();
var importersWithEmbeddedMaterials = importers.Where(im => im.materialLocation == SpeedTreeImporter.MaterialLocation.InPrefab);
foreach (var importer in importersWithEmbeddedMaterials)
{
var remappedAssets = importer.GetExternalObjectMap();
var materials = remappedAssets.Where(kv => kv.Value is Material && kv.Value != null).Select(kv => kv.Value);
foreach (var material in materials)
{
var path = AssetDatabase.GetAssetPath(material);
paths.Add(path);
matFolders.Add(FileUtil.DeleteLastPathNameComponent(path));
}
}
bool doGenerate = true;
if (paths.Count > 0)
doGenerate = AssetDatabase.MakeEditable(paths.ToArray(), $"Materials will be checked out in:\n{string.Join("\n", matFolders.ToArray())}");
if (doGenerate)
{
foreach (var importer in importers)
importer.GenerateMaterials();
}
}
private bool HasRemappedMaterials()
{
if (m_MaterialLocation.intValue == 0)
{
m_HasRemappedMaterials = true;
}
if (m_Materials.arraySize == 0)
return true;
// if the m_ExternalObjecs map has any unapplied changes, keep the state of the button as is
if (serializedObject.hasModifiedProperties)
return m_HasRemappedMaterials;
m_HasRemappedMaterials = true;
foreach (var importer in importers)
{
var externalObjectMap = importer.GetExternalObjectMap();
var materialsList = importer.sourceMaterials;
int remappedMaterialCount = 0;
foreach (var entry in externalObjectMap)
{
if (entry.Key.type == typeof(Material) && Array.Exists(materialsList, x => x.name == entry.Key.name))
++remappedMaterialCount;
}
m_HasRemappedMaterials = m_HasRemappedMaterials && remappedMaterialCount != 0;
if (!m_HasRemappedMaterials)
break;
}
return m_HasRemappedMaterials;
}
}
}
| UnityCsReference/Editor/Mono/ImportSettings/SpeedTreeImporterInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ImportSettings/SpeedTreeImporterInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 3694
} | 308 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(AudioClip))]
[CanEditMultipleObjects]
internal class AudioClipInspector : Editor
{
private PreviewRenderUtility m_PreviewUtility;
private AudioClip m_Clip;
private bool playing => s_PlayingInstance == this && m_Clip != null && AudioUtil.IsPreviewClipPlaying();
Vector2 m_Position = Vector2.zero;
private bool m_MultiEditing;
static GUIStyle s_PreButton;
static Rect s_WantedRect;
static bool s_AutoPlay;
static bool s_Loop;
static bool s_PlayFirst;
static AudioClipInspector s_PlayingInstance;
static GUIContent s_PlayIcon;
static GUIContent s_AutoPlayIcon;
static GUIContent s_LoopIcon;
static private string s_PreviewDisabledMessage = "AudioClip preview not available when Unity Audio is disabled in Project Settings";
static private string s_TrPreviewDisabledMessage = L10n.Tr(s_PreviewDisabledMessage);
static Texture2D s_DefaultIcon;
private Material m_HandleLinesMaterial;
public override void OnInspectorGUI()
{
// We can't always check this from preview methods
m_MultiEditing = targets.Length > 1;
// Override with inspector that doesn't show anything
}
static void Init()
{
if (s_PreButton != null)
return;
s_PreButton = "preButton";
s_AutoPlay = EditorPrefs.GetBool("AutoPlayAudio", false);
s_Loop = false;
var unityAudioDisabled = AudioSettings.unityAudioDisabled;
s_AutoPlayIcon = EditorGUIUtility.TrIconContent("preAudioAutoPlayOff", unityAudioDisabled ? s_PreviewDisabledMessage : "Turn Auto Play on/off");
s_PlayIcon = EditorGUIUtility.TrIconContent("PlayButton", unityAudioDisabled ? s_PreviewDisabledMessage : "Play");
s_LoopIcon = EditorGUIUtility.TrIconContent("preAudioLoopOff", unityAudioDisabled ? s_PreviewDisabledMessage : "Loop on/off");
s_DefaultIcon = EditorGUIUtility.LoadIcon("Profiler.Audio");
}
public void OnDisable()
{
if (s_PlayingInstance == this)
{
AudioUtil.StopAllPreviewClips();
s_PlayingInstance = null;
}
EditorPrefs.SetBool("AutoPlayAudio", s_AutoPlay);
if (m_PreviewUtility != null)
{
m_PreviewUtility.Cleanup();
m_PreviewUtility = null;
}
m_HandleLinesMaterial = null;
}
public void OnEnable()
{
s_AutoPlay = EditorPrefs.GetBool("AutoPlayAudio", false);
if (s_AutoPlay)
s_PlayFirst = true;
m_HandleLinesMaterial = EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat") as Material;
}
public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
{
AudioClip clip = target as AudioClip;
AssetImporter importer = AssetImporter.GetAtPath(assetPath);
AudioImporter audioImporter = importer as AudioImporter;
if (audioImporter == null || !ShaderUtil.hardwareSupportsRectRenderTexture)
return null;
if (m_PreviewUtility == null)
m_PreviewUtility = new PreviewRenderUtility();
m_PreviewUtility.BeginStaticPreview(new Rect(0, 0, width, height));
m_HandleLinesMaterial.SetPass(0);
// We're drawing into an offscreen here which will have a resolution defined by EditorGUIUtility.pixelsPerPoint. This is different from the DoRenderPreview call below where we draw directly to the screen, so we need to take
// the higher resolution into account when drawing into the offscreen, otherwise only the upper-left quarter of the preview texture will be drawn.
DoRenderPreview(false, clip, audioImporter, new Rect(0.05f * width * EditorGUIUtility.pixelsPerPoint, 0.05f * width * EditorGUIUtility.pixelsPerPoint, 1.9f * width * EditorGUIUtility.pixelsPerPoint, 1.9f * height * EditorGUIUtility.pixelsPerPoint), 1.0f);
return m_PreviewUtility.EndStaticPreview();
}
public override bool HasPreviewGUI()
{
return (targets != null);
}
public override void OnPreviewSettings()
{
if (s_DefaultIcon == null) Init();
AudioClip clip = target as AudioClip;
m_MultiEditing = targets.Length > 1;
using (new EditorGUI.DisabledScope(AudioSettings.unityAudioDisabled))
{
using (new EditorGUI.DisabledScope(m_MultiEditing && !playing))
{
bool newPlaying = GUILayout.Toggle(playing, s_PlayIcon, EditorStyles.toolbarButton);
if (newPlaying != playing)
{
if (newPlaying)
PlayClip(clip, 0, s_Loop);
else
{
AudioUtil.StopAllPreviewClips();
m_Clip = null;
}
}
}
using (new EditorGUI.DisabledScope(m_MultiEditing))
{
s_AutoPlay = s_AutoPlay && !m_MultiEditing;
s_AutoPlay = GUILayout.Toggle(s_AutoPlay, s_AutoPlayIcon, EditorStyles.toolbarButton);
}
bool loop = s_Loop;
s_Loop = GUILayout.Toggle(s_Loop, s_LoopIcon, EditorStyles.toolbarButton);
if ((loop != s_Loop) && playing)
AudioUtil.LoopPreviewClip(s_Loop);
}
}
void PlayClip(AudioClip clip, int startSample = 0, bool loop = false)
{
AudioUtil.StopAllPreviewClips();
AudioUtil.PlayPreviewClip(clip, startSample, loop);
m_Clip = clip;
s_PlayingInstance = this;
}
// Passing in clip and importer separately as we're not completely done with the asset setup at the time we're asked to generate the preview.
private void DoRenderPreview(bool setMaterial, AudioClip clip, AudioImporter audioImporter, Rect wantedRect, float scaleFactor)
{
scaleFactor *= 0.95f; // Reduce amplitude slightly to make highly compressed signals fit.
float[] minMaxData = (audioImporter == null) ? null : AudioUtil.GetMinMaxData(audioImporter);
int numChannels = clip.channels;
int numSamples = (minMaxData == null) ? 0 : (minMaxData.Length / (2 * numChannels));
float h = (float)wantedRect.height / (float)numChannels;
for (int channel = 0; channel < numChannels; channel++)
{
Rect channelRect = new Rect(wantedRect.x, wantedRect.y + h * channel, wantedRect.width, h);
Color curveColor = new Color(1.0f, 140.0f / 255.0f, 0.0f, 1.0f);
AudioCurveRendering.AudioMinMaxCurveAndColorEvaluator dlg = delegate(float x, out Color col, out float minValue, out float maxValue)
{
col = curveColor;
if (numSamples <= 0)
{
minValue = 0.0f;
maxValue = 0.0f;
}
else
{
float p = Mathf.Clamp(x * (numSamples - 2), 0.0f, numSamples - 2);
int i = (int)Mathf.Floor(p);
int offset1 = (i * numChannels + channel) * 2;
int offset2 = offset1 + numChannels * 2;
minValue = Mathf.Min(minMaxData[offset1 + 1], minMaxData[offset2 + 1]) * scaleFactor;
maxValue = Mathf.Max(minMaxData[offset1 + 0], minMaxData[offset2 + 0]) * scaleFactor;
if (minValue > maxValue) { float tmp = minValue; minValue = maxValue; maxValue = tmp; }
}
};
if (setMaterial)
AudioCurveRendering.DrawMinMaxFilledCurve(channelRect, dlg);
else
AudioCurveRendering.DrawMinMaxFilledCurveInternal(channelRect, dlg);
}
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (s_DefaultIcon == null) Init();
AudioClip clip = target as AudioClip;
Event evt = Event.current;
if (evt.type != EventType.Repaint && evt.type != EventType.Layout && evt.type != EventType.Used)
{
switch (evt.type)
{
case EventType.MouseDrag:
case EventType.MouseDown:
{
if (r.Contains(evt.mousePosition))
{
var startSample = (int)(evt.mousePosition.x * (AudioUtil.GetSampleCount(clip) / (int)r.width));
if (!AudioUtil.IsPreviewClipPlaying() || clip != m_Clip)
PlayClip(clip, startSample, s_Loop);
else
AudioUtil.SetPreviewClipSamplePosition(clip, startSample);
evt.Use();
}
}
break;
}
return;
}
if (Event.current.type == EventType.Repaint)
background.Draw(r, false, false, false, false);
int c = AudioUtil.GetChannelCount(clip);
s_WantedRect = new Rect(r.x, r.y , r.width, r.height);
float sec2px = ((float)s_WantedRect.width / clip.length);
bool previewAble = AudioUtil.HasPreview(clip) || !(AudioUtil.IsTrackerFile(clip));
if (!previewAble)
{
float labelY = (r.height > 150) ? r.y + (r.height / 2) - 10 : r.y + (r.height / 2) - 25;
if (r.width > 64)
{
if (AudioUtil.IsTrackerFile(clip))
{
EditorGUI.DropShadowLabel(new Rect(r.x, labelY, r.width, 20), string.Format("Module file with " + AudioUtil.GetMusicChannelCount(clip) + " channels."));
}
else
EditorGUI.DropShadowLabel(new Rect(r.x, labelY, r.width, 20), "Can not show PCM data for this file");
}
if (m_Clip == clip && playing)
{
float t = AudioUtil.GetPreviewClipPosition();
System.TimeSpan ts = new System.TimeSpan(0, 0, 0, 0, (int)(t * 1000.0f));
EditorGUI.DropShadowLabel(new Rect(s_WantedRect.x, s_WantedRect.y, s_WantedRect.width, 20), string.Format("Playing - {0:00}:{1:00}.{2:000}", ts.Minutes, ts.Seconds, ts.Milliseconds));
}
}
else
{
PreviewGUI.BeginScrollView(s_WantedRect, m_Position, s_WantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb");
if (Event.current.type == EventType.Repaint)
{
DoRenderPreview(true, clip, AudioUtil.GetImporterFromClip(clip), s_WantedRect, 1.0f);
}
for (int i = 0; i < c; ++i)
{
if (c > 1 && r.width > 64)
{
var labelRect = new Rect(s_WantedRect.x + 5, s_WantedRect.y + (s_WantedRect.height / c) * i, 30, 20);
EditorGUI.DropShadowLabel(labelRect, "ch " + (i + 1));
}
}
if (m_Clip == clip && playing)
{
float t = AudioUtil.GetPreviewClipPosition();
System.TimeSpan ts = new System.TimeSpan(0, 0, 0, 0, (int)(t * 1000.0f));
GUI.DrawTexture(new Rect(s_WantedRect.x + (int)(sec2px * t), s_WantedRect.y, 2, s_WantedRect.height), EditorGUIUtility.whiteTexture);
if (r.width > 64)
EditorGUI.DropShadowLabel(new Rect(s_WantedRect.x, s_WantedRect.y, s_WantedRect.width, 20), string.Format("{0:00}:{1:00}.{2:000}", ts.Minutes, ts.Seconds, ts.Milliseconds));
else
EditorGUI.DropShadowLabel(new Rect(s_WantedRect.x, s_WantedRect.y, s_WantedRect.width, 20), string.Format("{0:00}:{1:00}", ts.Minutes, ts.Seconds));
}
PreviewGUI.EndScrollView();
}
if (!m_MultiEditing && (s_PlayFirst || (s_AutoPlay && m_Clip != clip)))
{
// Autoplay preview
PlayClip(clip, 0, s_Loop);
s_PlayFirst = false;
}
if (AudioSettings.unityAudioDisabled)
{
EditorGUILayout.HelpBox(s_TrPreviewDisabledMessage, MessageType.Info);
}
// force update GUI
if (playing)
GUIView.current.Repaint();
}
public override string GetInfoString()
{
AudioClip clip = target as AudioClip;
int c = AudioUtil.GetChannelCount(clip);
string ch = c == 1 ? "Mono" : c == 2 ? "Stereo" : (c - 1) + ".1";
AudioCompressionFormat platformFormat = AudioUtil.GetTargetPlatformSoundCompressionFormat(clip);
AudioCompressionFormat editorFormat = AudioUtil.GetSoundCompressionFormat(clip);
string s = platformFormat.ToString();
if (platformFormat != editorFormat)
s += " (" + editorFormat + " in editor" + ")";
s += ", " + AudioUtil.GetFrequency(clip) + " Hz, " + ch + ", ";
System.TimeSpan ts = new System.TimeSpan(0, 0, 0, 0, (int)AudioUtil.GetDuration(clip));
if ((uint)AudioUtil.GetDuration(clip) == 0xffffffff)
s += "Unlimited";
else
s += UnityString.Format("{0:00}:{1:00}.{2:000}", ts.Minutes, ts.Seconds, ts.Milliseconds);
return s;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/AudioClipInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/AudioClipInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 7272
} | 309 |
// 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
{
public enum BodyPart
{
None = -1,
Avatar = 0,
Body,
Head,
LeftArm,
LeftFingers,
RightArm,
RightFingers,
LeftLeg,
RightLeg,
Last
}
internal class AvatarControl
{
class Styles
{
// IF you change the order of this array, please update:
// BodyPartMapping
// m_BodyPartHumanBone
// BodyPart
public GUIContent[] Silhouettes =
{
EditorGUIUtility.IconContent("AvatarInspector/BodySilhouette"),
EditorGUIUtility.IconContent("AvatarInspector/HeadZoomSilhouette"),
EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoomSilhouette"),
EditorGUIUtility.IconContent("AvatarInspector/RightHandZoomSilhouette")
};
public GUIContent[,] BodyPart =
{
{
null,
EditorGUIUtility.IconContent("AvatarInspector/Torso"),
EditorGUIUtility.IconContent("AvatarInspector/Head"),
EditorGUIUtility.IconContent("AvatarInspector/LeftArm"),
EditorGUIUtility.IconContent("AvatarInspector/LeftFingers"),
EditorGUIUtility.IconContent("AvatarInspector/RightArm"),
EditorGUIUtility.IconContent("AvatarInspector/RightFingers"),
EditorGUIUtility.IconContent("AvatarInspector/LeftLeg"),
EditorGUIUtility.IconContent("AvatarInspector/RightLeg")
},
{
null,
null,
EditorGUIUtility.IconContent("AvatarInspector/HeadZoom"),
null,
null,
null,
null,
null,
null
},
{
null,
null,
null,
null,
EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoom"),
null,
null,
null,
null
},
{
null,
null,
null,
null,
null,
null,
EditorGUIUtility.IconContent("AvatarInspector/RightHandZoom"),
null,
null
},
};
}
static Styles styles { get { if (s_Styles == null) s_Styles = new Styles(); return s_Styles; } }
static Styles s_Styles;
public enum BodyPartColor
{
Off = 0x00,
Green = 0x01 << 0,
Red = 0x01 << 1,
IKGreen = 0x01 << 2,
IKRed = 0x01 << 3,
}
public delegate BodyPartColor BodyPartFeedback(BodyPart bodyPart);
static public int ShowBoneMapping(int shownBodyView, BodyPartFeedback bodyPartCallback, AvatarSetupTool.BoneWrapper[] bones, SerializedObject serializedObject, AvatarMappingEditor editor)
{
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (styles.Silhouettes[shownBodyView].image)
{
Rect rect = GUILayoutUtility.GetRect(styles.Silhouettes[shownBodyView], GUIStyle.none, GUILayout.MaxWidth(styles.Silhouettes[shownBodyView].image.width));
DrawBodyParts(rect, shownBodyView, bodyPartCallback);
for (int i = 0; i < bones.Length; i++)
DrawBone(shownBodyView, i, rect, bones[i], serializedObject, editor);
}
else
GUILayout.Label("texture missing,\nfix me!");
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
// Body view buttons
Rect buttonsRect = GUILayoutUtility.GetLastRect();
const float buttonHeight = 18;
string[] labels = new string[] { "Body", "Head", "Left Hand", "Right Hand"};
buttonsRect.x += 5;
buttonsRect.width = 80;
buttonsRect.yMin = buttonsRect.yMax - (buttonHeight * 4 + 5);
buttonsRect.height = buttonHeight;
for (int i = 0; i < labels.Length; i++)
{
if (GUI.Toggle(buttonsRect, shownBodyView == i, labels[i], EditorStyles.miniButton))
shownBodyView = i;
buttonsRect.y += buttonHeight;
}
return shownBodyView;
}
static public void DrawBodyParts(Rect rect, int shownBodyView, BodyPartFeedback bodyPartCallback)
{
GUI.color = new Color(0.2f, 0.2f, 0.2f, 1.0f);
if (styles.Silhouettes[shownBodyView] != null)
GUI.DrawTexture(rect, styles.Silhouettes[shownBodyView].image);
for (int i = 1; i < (int)BodyPart.Last; i++)
DrawBodyPart(shownBodyView, i, rect, bodyPartCallback((BodyPart)i));
}
static protected void DrawBodyPart(int shownBodyView, int i, Rect rect, BodyPartColor bodyPartColor)
{
if (styles.BodyPart[shownBodyView, i] != null && styles.BodyPart[shownBodyView, i].image != null)
{
if ((bodyPartColor & BodyPartColor.Green) == BodyPartColor.Green)
GUI.color = Color.green;
else if ((bodyPartColor & BodyPartColor.Red) == BodyPartColor.Red)
GUI.color = Color.red;
else
GUI.color = Color.gray;
GUI.DrawTexture(rect, styles.BodyPart[shownBodyView, i].image);
GUI.color = Color.white;
}
}
static Vector2[,] s_BonePositions = new Vector2[4, HumanTrait.BoneCount];
public static List<int> GetViewsThatContainBone(int bone)
{
List<int> views = new List<int>();
if (bone < 0 || bone >= HumanTrait.BoneCount)
return views;
for (int i = 0; i < 4; i++)
{
if (s_BonePositions[i, bone] != Vector2.zero)
views.Add(i);
}
return views;
}
static AvatarControl()
{
// Body view
int view = 0;
// hips
s_BonePositions[view, (int)HumanBodyBones.Hips] = new Vector2(0.00f, 0.08f);
// upper leg
s_BonePositions[view, (int)HumanBodyBones.LeftUpperLeg] = new Vector2(0.16f, 0.01f);
s_BonePositions[view, (int)HumanBodyBones.RightUpperLeg] = new Vector2(-0.16f, 0.01f);
// lower leg
s_BonePositions[view, (int)HumanBodyBones.LeftLowerLeg] = new Vector2(0.21f, -0.40f);
s_BonePositions[view, (int)HumanBodyBones.RightLowerLeg] = new Vector2(-0.21f, -0.40f);
// foot
s_BonePositions[view, (int)HumanBodyBones.LeftFoot] = new Vector2(0.23f, -0.80f);
s_BonePositions[view, (int)HumanBodyBones.RightFoot] = new Vector2(-0.23f, -0.80f);
// spine - head
s_BonePositions[view, (int)HumanBodyBones.Spine] = new Vector2(0.00f, 0.20f);
s_BonePositions[view, (int)HumanBodyBones.Chest] = new Vector2(0.00f, 0.35f);
s_BonePositions[view, (int)HumanBodyBones.UpperChest] = new Vector2(0.00f, 0.50f);
s_BonePositions[view, (int)HumanBodyBones.Neck] = new Vector2(0.00f, 0.66f);
s_BonePositions[view, (int)HumanBodyBones.Head] = new Vector2(0.00f, 0.76f);
// shoulder
s_BonePositions[view, (int)HumanBodyBones.LeftShoulder] = new Vector2(0.14f, 0.60f);
s_BonePositions[view, (int)HumanBodyBones.RightShoulder] = new Vector2(-0.14f, 0.60f);
// upper arm
s_BonePositions[view, (int)HumanBodyBones.LeftUpperArm] = new Vector2(0.30f, 0.57f);
s_BonePositions[view, (int)HumanBodyBones.RightUpperArm] = new Vector2(-0.30f, 0.57f);
// lower arm
s_BonePositions[view, (int)HumanBodyBones.LeftLowerArm] = new Vector2(0.48f, 0.30f);
s_BonePositions[view, (int)HumanBodyBones.RightLowerArm] = new Vector2(-0.48f, 0.30f);
// hand
s_BonePositions[view, (int)HumanBodyBones.LeftHand] = new Vector2(0.66f, 0.03f);
s_BonePositions[view, (int)HumanBodyBones.RightHand] = new Vector2(-0.66f, 0.03f);
// toe
s_BonePositions[view, (int)HumanBodyBones.LeftToes] = new Vector2(0.25f, -0.89f);
s_BonePositions[view, (int)HumanBodyBones.RightToes] = new Vector2(-0.25f, -0.89f);
// Head view
view = 1;
// neck - head
s_BonePositions[view, (int)HumanBodyBones.Neck] = new Vector2(-0.20f, -0.62f);
s_BonePositions[view, (int)HumanBodyBones.Head] = new Vector2(-0.15f, -0.30f);
// left, right eye
s_BonePositions[view, (int)HumanBodyBones.LeftEye] = new Vector2(0.63f, 0.16f);
s_BonePositions[view, (int)HumanBodyBones.RightEye] = new Vector2(0.15f, 0.16f);
// jaw
s_BonePositions[view, (int)HumanBodyBones.Jaw] = new Vector2(0.45f, -0.40f);
// Left hand view
view = 2;
// finger bases, thumb - little
s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal] = new Vector2(-0.35f, 0.11f);
s_BonePositions[view, (int)HumanBodyBones.LeftIndexProximal] = new Vector2(0.19f, 0.11f);
s_BonePositions[view, (int)HumanBodyBones.LeftMiddleProximal] = new Vector2(0.22f, 0.00f);
s_BonePositions[view, (int)HumanBodyBones.LeftRingProximal] = new Vector2(0.16f, -0.12f);
s_BonePositions[view, (int)HumanBodyBones.LeftLittleProximal] = new Vector2(0.09f, -0.23f);
// finger tips, thumb - little
s_BonePositions[view, (int)HumanBodyBones.LeftThumbDistal] = new Vector2(-0.03f, 0.33f);
s_BonePositions[view, (int)HumanBodyBones.LeftIndexDistal] = new Vector2(0.65f, 0.16f);
s_BonePositions[view, (int)HumanBodyBones.LeftMiddleDistal] = new Vector2(0.74f, 0.00f);
s_BonePositions[view, (int)HumanBodyBones.LeftRingDistal] = new Vector2(0.66f, -0.14f);
s_BonePositions[view, (int)HumanBodyBones.LeftLittleDistal] = new Vector2(0.45f, -0.25f);
// finger middles, thumb - little
for (int i = 0; i < 5; i++)
s_BonePositions[view, (int)HumanBodyBones.LeftThumbIntermediate + i * 3] = Vector2.Lerp(s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal + i * 3], s_BonePositions[view, (int)HumanBodyBones.LeftThumbDistal + i * 3], 0.58f);
// Right hand view
view = 3;
for (int i = 0; i < 15; i++)
s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal + i + 15] = Vector2.Scale(s_BonePositions[view - 1, (int)HumanBodyBones.LeftThumbProximal + i], new Vector2(-1, 1));
}
static protected void DrawBone(int shownBodyView, int i, Rect rect, AvatarSetupTool.BoneWrapper bone, SerializedObject serializedObject, AvatarMappingEditor editor)
{
if (s_BonePositions[shownBodyView, i] == Vector2.zero)
return;
Vector2 pos = s_BonePositions[shownBodyView, i];
pos.y *= -1; // because higher values should be up
pos.Scale(new Vector2(rect.width * 0.5f, rect.height * 0.5f));
pos = rect.center + pos;
int kIconSize = AvatarSetupTool.BoneWrapper.kIconSize;
Rect r = new Rect(pos.x - kIconSize * 0.5f, pos.y - kIconSize * 0.5f, kIconSize, kIconSize);
bone.BoneDotGUI(r, r, i, true, true, true, serializedObject, editor);
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarControl.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarControl.cs",
"repo_id": "UnityCsReference",
"token_count": 6332
} | 310 |
// 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.AnimatedValues;
using UnityEditorInternal.VR;
using System.Linq;
namespace UnityEditor
{
/// <summary>
/// Editor class used to edit UI Canvases.
/// </summary>
[CanEditMultipleObjects]
[CustomEditor(typeof(Canvas))]
internal class CanvasEditor : Editor
{
SerializedProperty m_RenderMode;
SerializedProperty m_Camera;
SerializedProperty m_PixelPerfect;
SerializedProperty m_PixelPerfectOverride;
SerializedProperty m_PlaneDistance;
SerializedProperty m_SortingLayerID;
SerializedProperty m_SortingOrder;
SerializedProperty m_TargetDisplay;
SerializedProperty m_OverrideSorting;
SerializedProperty m_ShaderChannels;
SerializedProperty m_UpdateRectTransformForStandalone;
SerializedProperty m_VertexColorAlwaysGammaSpace;
AnimBool m_OverlayMode;
AnimBool m_CameraMode;
AnimBool m_WorldMode;
AnimBool m_SortingOverride;
private static class Styles
{
public static GUIContent eventCamera = EditorGUIUtility.TrTextContent("Event Camera", "The Camera which the events are triggered through. This is used to determine clicking and hover positions if the Canvas is in World Space render mode.");
public static GUIContent renderCamera = EditorGUIUtility.TrTextContent("Render Camera", "The Camera which will render the canvas. This is also the camera used to send events.");
public static GUIContent sortingOrder = EditorGUIUtility.TrTextContent("Sort Order", "The order in which Screen Space - Overlay canvas will render");
public static string s_RootAndNestedMessage = "Cannot multi-edit root Canvas together with nested Canvas.";
public static GUIContent m_SortingLayerStyle = EditorGUIUtility.TrTextContent("Sorting Layer", "Name of the Renderer's sorting layer");
public static GUIContent targetDisplay = EditorGUIUtility.TrTextContent("Target Display", "Display on which to render the canvas when in overlay mode");
public static GUIContent m_SortingOrderStyle = EditorGUIUtility.TrTextContent("Order in Layer", "Renderer's order within a sorting layer");
public static GUIContent m_ShaderChannel = EditorGUIUtility.TrTextContent("Additional Shader Channels");
public static GUIContent pixelPerfectContent = EditorGUIUtility.TrTextContent("Pixel Perfect");
public static GUIContent standaloneRenderResize = EditorGUIUtility.TrTextContent("Resize Canvas", "For manual Camera.Render calls should the canvas resize to match the destination target.");
public static GUIContent vertexColorAlwaysGammaSpace = EditorGUIUtility.TrTextContent("Vertex Color Always In Gamma Color Space", "UI vertex colors are always in gamma color space disregard of the player settings");
}
private bool m_AllNested = false;
private bool m_AllRoot = false;
private bool m_AllOverlay = false;
private bool m_NoneOverlay = false;
private string[] shaderChannelOptions = { "TexCoord1", "TexCoord2", "TexCoord3", "Normal", "Tangent" };
enum PixelPerfect
{
Inherit,
On,
Off
}
private PixelPerfect pixelPerfect = PixelPerfect.Inherit;
void OnEnable()
{
m_RenderMode = serializedObject.FindProperty("m_RenderMode");
m_Camera = serializedObject.FindProperty("m_Camera");
m_PixelPerfect = serializedObject.FindProperty("m_PixelPerfect");
m_PlaneDistance = serializedObject.FindProperty("m_PlaneDistance");
m_SortingLayerID = serializedObject.FindProperty("m_SortingLayerID");
m_SortingOrder = serializedObject.FindProperty("m_SortingOrder");
m_TargetDisplay = serializedObject.FindProperty("m_TargetDisplay");
m_OverrideSorting = serializedObject.FindProperty("m_OverrideSorting");
m_PixelPerfectOverride = serializedObject.FindProperty("m_OverridePixelPerfect");
m_ShaderChannels = serializedObject.FindProperty("m_AdditionalShaderChannelsFlag");
m_UpdateRectTransformForStandalone = serializedObject.FindProperty("m_UpdateRectTransformForStandalone");
m_VertexColorAlwaysGammaSpace = serializedObject.FindProperty("m_VertexColorAlwaysGammaSpace");
m_OverlayMode = new AnimBool(m_RenderMode.intValue == 0);
m_OverlayMode.valueChanged.AddListener(Repaint);
m_CameraMode = new AnimBool(m_RenderMode.intValue == 1);
m_CameraMode.valueChanged.AddListener(Repaint);
m_WorldMode = new AnimBool(m_RenderMode.intValue == 2);
m_WorldMode.valueChanged.AddListener(Repaint);
m_SortingOverride = new AnimBool(m_OverrideSorting.boolValue);
m_SortingOverride.valueChanged.AddListener(Repaint);
if (m_PixelPerfectOverride.boolValue)
pixelPerfect = m_PixelPerfect.boolValue ? PixelPerfect.On : PixelPerfect.Off;
else
pixelPerfect = PixelPerfect.Inherit;
m_AllNested = true;
m_AllRoot = true;
m_AllOverlay = true;
m_NoneOverlay = true;
for (int i = 0; i < targets.Length; i++)
{
Canvas canvas = targets[i] as Canvas;
Canvas[] parentCanvas = canvas.transform.parent != null ? canvas.transform.parent.GetComponentsInParent<Canvas>(true) : null;
if (canvas.transform.parent == null || (parentCanvas != null && parentCanvas.Length == 0))
m_AllNested = false;
else
m_AllRoot = false;
RenderMode renderMode = canvas.renderMode;
if (parentCanvas != null && parentCanvas.Length > 0)
renderMode = parentCanvas[parentCanvas.Length - 1].renderMode;
if (renderMode == RenderMode.ScreenSpaceOverlay)
m_NoneOverlay = false;
else
m_AllOverlay = false;
}
}
void OnDisable()
{
m_OverlayMode.valueChanged.RemoveListener(Repaint);
m_CameraMode.valueChanged.RemoveListener(Repaint);
m_WorldMode.valueChanged.RemoveListener(Repaint);
m_SortingOverride.valueChanged.RemoveListener(Repaint);
}
private void AllRootCanvases()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_RenderMode);
if (EditorGUI.EndChangeCheck())
{
var rectTransforms = targets.Select(c => (c as Canvas).transform).ToArray();
Undo.RegisterCompleteObjectUndo(rectTransforms, "Modified RectTransform Values");
serializedObject.ApplyModifiedProperties();
foreach (Canvas canvas in targets)
{
canvas.UpdateCanvasRectTransform(true);
}
GUIUtility.ExitGUI();
}
m_OverlayMode.target = m_RenderMode.intValue == 0;
m_CameraMode.target = m_RenderMode.intValue == 1;
m_WorldMode.target = m_RenderMode.intValue == 2;
EditorGUI.indentLevel++;
if (EditorGUILayout.BeginFadeGroup(m_OverlayMode.faded))
{
DoPixelPerfectGUIForRoot();
EditorGUILayout.PropertyField(m_SortingOrder, Styles.sortingOrder);
GUIContent[] displayNames = DisplayUtility.GetDisplayNames();
EditorGUILayout.IntPopup(m_TargetDisplay, displayNames, DisplayUtility.GetDisplayIndices(), Styles.targetDisplay);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_CameraMode.faded))
{
DoPixelPerfectGUIForRoot();
EditorGUILayout.PropertyField(m_Camera, Styles.renderCamera);
if (m_Camera.objectReferenceValue == null)
EditorGUILayout.HelpBox("A Screen Space Canvas with no specified camera acts like an Overlay Canvas.",
MessageType.Warning);
if (m_Camera.objectReferenceValue != null)
{
EditorGUILayout.PropertyField(m_PlaneDistance);
EditorGUILayout.PropertyField(m_UpdateRectTransformForStandalone, Styles.standaloneRenderResize);
}
EditorGUILayout.Space();
if (m_Camera.objectReferenceValue != null)
EditorGUILayout.SortingLayerField(Styles.m_SortingLayerStyle, m_SortingLayerID, EditorStyles.popup, EditorStyles.label);
EditorGUILayout.PropertyField(m_SortingOrder, Styles.m_SortingOrderStyle);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_WorldMode.faded))
{
EditorGUILayout.PropertyField(m_Camera, Styles.eventCamera);
if (m_Camera.objectReferenceValue == null)
EditorGUILayout.HelpBox("A World Space Canvas with no specified Event Camera may not register UI events correctly.",
MessageType.Warning);
EditorGUILayout.Space();
EditorGUILayout.SortingLayerField(Styles.m_SortingLayerStyle, m_SortingLayerID, EditorStyles.popup);
EditorGUILayout.PropertyField(m_SortingOrder, Styles.m_SortingOrderStyle);
}
EditorGUILayout.EndFadeGroup();
EditorGUI.indentLevel--;
}
private void DoPixelPerfectGUIForRoot()
{
bool pixelPerfectValue = m_PixelPerfect.boolValue;
EditorGUI.BeginChangeCheck();
var rect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(rect, Styles.pixelPerfectContent, m_PixelPerfect);
pixelPerfectValue = EditorGUI.Toggle(rect, Styles.pixelPerfectContent, pixelPerfectValue);
EditorGUI.EndProperty();
if (EditorGUI.EndChangeCheck())
{
for (int i = 0; i < targets.Length; i++)
{
Canvas canvas = targets[i] as Canvas;
Undo.RecordObject(canvas, "Set Pixel Perfect");
canvas.pixelPerfect = pixelPerfectValue;
}
}
}
private void DoPixelPerfectGUIForNested()
{
EditorGUI.BeginChangeCheck();
pixelPerfect = (PixelPerfect)EditorGUILayout.EnumPopup(Styles.pixelPerfectContent, pixelPerfect);
if (EditorGUI.EndChangeCheck())
{
if (pixelPerfect == PixelPerfect.Inherit)
{
m_PixelPerfectOverride.boolValue = false;
}
else
{
m_PixelPerfectOverride.boolValue = true;
for (int i = 0; i < targets.Length; i++)
{
Canvas canvas = targets[i] as Canvas;
Undo.RecordObject(canvas, "Set Pixel Perfect");
canvas.pixelPerfect = pixelPerfect == PixelPerfect.On;
}
}
}
}
private void AllNestedCanvases()
{
DoPixelPerfectGUIForNested();
EditorGUILayout.PropertyField(m_OverrideSorting);
m_SortingOverride.target = m_OverrideSorting.boolValue;
if (EditorGUILayout.BeginFadeGroup(m_SortingOverride.faded))
{
GUIContent sortingOrderStyle = null;
if (m_AllOverlay)
{
sortingOrderStyle = Styles.sortingOrder;
}
else if (m_NoneOverlay)
{
sortingOrderStyle = Styles.m_SortingOrderStyle;
EditorGUILayout.SortingLayerField(Styles.m_SortingLayerStyle, m_SortingLayerID, EditorStyles.popup);
}
if (sortingOrderStyle != null)
{
EditorGUILayout.PropertyField(m_SortingOrder, sortingOrderStyle);
}
}
EditorGUILayout.EndFadeGroup();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
if (m_AllRoot || m_AllNested)
{
if (m_AllRoot)
{
AllRootCanvases();
}
else if (m_AllNested)
{
AllNestedCanvases();
}
EditorGUI.BeginChangeCheck();
var rect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(rect, Styles.m_ShaderChannel, m_ShaderChannels);
var newShaderChannelValue = EditorGUI.MaskField(rect, Styles.m_ShaderChannel, m_ShaderChannels.intValue, shaderChannelOptions);
EditorGUI.EndProperty();
if (EditorGUI.EndChangeCheck())
m_ShaderChannels.intValue = newShaderChannelValue;
if (m_RenderMode.intValue == 0) // Overlay canvas
{
if (((newShaderChannelValue & (int)AdditionalCanvasShaderChannels.Normal) | (newShaderChannelValue & (int)AdditionalCanvasShaderChannels.Tangent)) != 0)
{
var helpMessage = "Shader channels Normal and Tangent are most often used with lighting, which an Overlay canvas does not support. Its likely these channels are not needed.";
rect = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(helpMessage, EditorGUIUtility.GetHelpIcon(MessageType.Warning)), EditorStyles.helpBox);
EditorGUI.HelpBox(rect, helpMessage, MessageType.Warning);
}
}
EditorGUILayout.PropertyField(m_VertexColorAlwaysGammaSpace, Styles.vertexColorAlwaysGammaSpace);
if (PlayerSettings.colorSpace == ColorSpace.Linear)
{
if (!m_VertexColorAlwaysGammaSpace.boolValue)
EditorGUILayout.HelpBox( "Keep vertex color in Gamma space to allow gamma to linear color space conversion to happen in UI shaders. This will enhance UI color precision in linear color space.", MessageType.Warning);
}
}
else
{
GUILayout.Label(Styles.s_RootAndNestedMessage, EditorStyles.helpBox);
}
serializedObject.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Editor/Mono/Inspector/CanvasEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/CanvasEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 6775
} | 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;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.IMGUI.Controls
{
public class AdvancedDropdownItem : IComparable
{
string m_Name;
int m_Id;
int m_ElementIndex = -1;
bool m_Enabled = true;
GUIContent m_Content;
List<AdvancedDropdownItem> m_Children = new List<AdvancedDropdownItem>();
public string name
{
get { return m_Name; }
set { m_Name = value; }
}
internal GUIContent content => m_Content;
internal string tooltip
{
get => m_Content.tooltip;
set { m_Content.tooltip = value; }
}
internal virtual string displayName
{
get => string.IsNullOrEmpty(m_Content.text) ? m_Name : m_Content.text;
set { m_Content.text = value; }
}
public Texture2D icon
{
get => m_Content?.image as Texture2D;
set { m_Content.image = value; }
}
public int id
{
get => m_Id;
set { m_Id = value; }
}
internal int elementIndex
{
get { return m_ElementIndex; }
set { m_ElementIndex = value; }
}
public bool enabled
{
get { return m_Enabled; }
set { m_Enabled = value; }
}
internal object userData { get; set; }
public IEnumerable<AdvancedDropdownItem> children => m_Children;
internal bool hasChildren => m_Children.Count > 0;
public void AddChild(AdvancedDropdownItem child)
{
m_Children.Add(child);
}
static readonly AdvancedDropdownItem k_SeparatorItem = new SeparatorDropdownItem();
public AdvancedDropdownItem(string name)
{
m_Name = name;
m_Id = name.GetHashCode();
m_Content = new GUIContent(m_Name);
}
public override int GetHashCode()
{
return name.GetHashCode();
}
public virtual int CompareTo(object o)
{
return string.CompareOrdinal(name, ((AdvancedDropdownItem)o).name);
}
public void AddSeparator()
{
AddChild(k_SeparatorItem);
}
internal bool IsSeparator()
{
return k_SeparatorItem == this;
}
public override string ToString()
{
return m_Name;
}
internal void SortChildren(Comparison<AdvancedDropdownItem> comparer, bool recursive = false)
{
if (recursive)
{
foreach (var child in m_Children)
child.SortChildren(comparer, recursive);
}
m_Children.Sort(comparer);
}
class SeparatorDropdownItem : AdvancedDropdownItem
{
public SeparatorDropdownItem() : base("SEPARATOR")
{
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownItem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownItem.cs",
"repo_id": "UnityCsReference",
"token_count": 1533
} | 312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.