示例#1
0
文件: Entity.cs 项目: GlenDC/L20n.cs
				public static void Parse(
					CharStream stream, string identifier,
					Internal.LocaleContext.Builder builder)
				{
					var startingPos = stream.Position;

					try
					{
						// private identifiers start with an underscore
						// and can only be referenced from within an l20n file
						bool isPrivate = (identifier.IndexOf('_') == 0);

						// an optional index is possible
						AST.INode index = null;
						Index.PeekAndParse(stream, out index);

						// White Space is required
						WhiteSpace.Parse(stream, false);

						var valuePos = stream.Position;

						// Now we need the actual value
						var value = Value.Parse(stream);

						if ((value as IO.AST.HashValue) == null && index != null)
						{
							string msg = String.Format(
								"an index was given, but a stringValue was given, while a hashValue was expected",
								stream.ComputeDetailedPosition(valuePos));
							throw new Exceptions.ParseException(msg);
						}

						// an optional attributes collection is possible
						AST.Attributes attributes;
						Attributes.PeekAndParse(stream, out attributes);

						// White Space is optional
						WhiteSpace.Parse(stream, true);

						stream.SkipCharacter('>');
						
						var entityAST = new AST.Entity(identifier, isPrivate, index, value, attributes);
						try
						{
							var entity = (Objects.Entity)entityAST.Eval();
							builder.AddEntity(identifier, entity);
						} catch (Exception e)
						{
							throw new Exceptions.EvaluateException(
								String.Format("couldn't evaluate `{0}`", entityAST.Display()),
								e);
						}
					} catch (Exception e)
					{
						string msg = String.Format(
							"something went wrong parsing an <entity> starting at {0}",
							stream.ComputeDetailedPosition(startingPos));
						throw new Exceptions.ParseException(msg, e);
					}
				}
示例#2
0
文件: Macro.cs 项目: GlenDC/L20n.cs
				public static void Parse(
					CharStream stream,
					string identifier, Internal.LocaleContext.Builder builder)
				{
					var startingPos = stream.Position;
					
					try
					{
						var macroAST = new AST.Macro(identifier);
						
						stream.SkipCharacter('(');
						WhiteSpace.Parse(stream, true);

						// variables are optional,
						// but we do have them, we need at least one (duh)
						if (Expressions.Variable.Peek(stream))
						{
							macroAST.AddParameter(Macro.ParseVariable(stream));

							// more than 1 is possible as well
							while (stream.SkipIfPossible(','))
							{
								WhiteSpace.Parse(stream, true);
								macroAST.AddParameter(Macro.ParseVariable(stream));
							}
						}

						stream.SkipCharacter(')');
						WhiteSpace.Parse(stream, false);

						stream.SkipCharacter('{');
						WhiteSpace.Parse(stream, true);

						// Parse the Actual Macro Expression
						macroAST.SetExpression(Expression.Parse(stream));

						WhiteSpace.Parse(stream, true);
						stream.SkipCharacter('}');
						WhiteSpace.Parse(stream, true);
						stream.SkipCharacter('>');

						// return the fully parsed macro
						try
						{
							var macro = (Objects.Macro)macroAST.Eval();
							builder.AddMacro(identifier, macro);
						} catch (Exception e)
						{
							throw new Exceptions.EvaluateException(
								String.Format("couldn't evaluate `{0}`", macroAST.Display()),
								e);
						}
					} catch (Exception e)
					{
						string msg = String.Format(
							"something went wrong parsing a <macro> starting at {0}",
							stream.ComputeDetailedPosition(startingPos));
						throw new Exceptions.ParseException(msg, e);
					}
				}
 /// <summary>
 /// Initializes the mechanism.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="credentials">The credentials.</param>
 /// <returns>The initial step.</returns>
 public ISaslStep Initialize(Internal.MongoConnection connection, MongoCredentials credentials)
 {
     return new ManagedDigestMD5Implementation(
         connection.ServerInstance.Address.Host,
         credentials.Username,
         ((PasswordEvidence)credentials.Evidence).Password);
 }       
示例#4
0
文件: TXT.cs 项目: boethin/dnstools
        internal override void ReadRDATA(Internal.ByteReader reader)
        {
            // The format of the data within a DNS TXT record is one or more
              // strings, packed together in memory without any intervening gaps
              // or padding bytes for word alignment.
              //
              // The format of each constituent string within the DNS TXT record is
              // a single length byte, followed by 0-255 bytes of text data.

              // TXT-DATA strings are not guaranteed to consist purely of ASCII printable
              // characters though this is usually the case.

              List<Datagram> strings = new List<Datagram>();
              for (int total = 0; total < Base.RDLENGTH; )
              {
            byte length = reader.ReadByte();
            if (length > 0)
            {
              if (total + length >= Base.RDLENGTH)
            throw new InvalidResponseException(
              "Invalid length byte in TXT record: String data would exceed RDLENGTH.");
              strings.Add(reader.ReadBytes(length));
            }
            total += (length + 1);
              }
              Strings = strings.ToArray();
        }
        private Data BuildArrayValue(Internal.ValueNode n)
        {
            Data data = null;

            switch (n.Type)
            {
                case Internal.ValueNodeType.Statement:
                    data = new Data();
                    DataGroup group = BuildGroup(n.Statement);
                    data.Group = group;
                    break;
                case Internal.ValueNodeType.Integer:
                    data = new Data();
                    data.Integer = n.Integer;
                    break;
                case Internal.ValueNodeType.Float:
                    data = new Data();
                    data.Float = n.Float;
                    break;
                case Internal.ValueNodeType.Bool:
                    data = new Data();
                    data.Bool = n.Boolean;
                    break;
                case Internal.ValueNodeType.String:
                    data = new Data();
                    data.String = n.String;
                    break;
                case Internal.ValueNodeType.Array:
                    data = new Data();
                    data.Array = BuildArray(n.Array);
                    break;
            }

            return data;
        }
示例#6
0
 internal MPoolStats(Internal.MempStatStruct stats) {
     st = stats.st;
     ci = new CacheInfo(st.st_gbytes, st.st_bytes, (int)st.st_max_ncache);
     mempfiles = new List<MPoolFileStats>();
     foreach (Internal.MPoolFileStatStruct file in stats.files)
         mempfiles.Add(new MPoolFileStats(file));
 }
        private static MemberAssignment BindEnumerableExpression(IMappingEngine mappingEngine, PropertyMap propertyMap,
            ExpressionRequest request, ExpressionResolutionResult result,
            Internal.IDictionary<ExpressionRequest, int> typePairCount)
        {
            MemberAssignment bindExpression;
            Type destinationListType = GetDestinationListTypeFor(propertyMap);
            Type sourceListType = null;
            // is list

            if (result.Type.IsArray)
            {
                sourceListType = result.Type.GetElementType();
            }
            else
            {
                sourceListType = result.Type.GetGenericArguments().First();
            }
            var listTypePair = new ExpressionRequest(sourceListType, destinationListType, request.IncludedMembers);

            var selectExpression = result.ResolutionExpression;
            if (sourceListType != destinationListType)
            {
                var transformedExpression = Extensions.CreateMapExpression(mappingEngine, listTypePair, typePairCount);
                selectExpression = Expression.Call(
                    typeof (Enumerable),
                    "Select",
                    new[] {sourceListType, destinationListType},
                    result.ResolutionExpression,
                    transformedExpression);
            }

            if (typeof (IList<>).MakeGenericType(destinationListType)
                .IsAssignableFrom(propertyMap.DestinationPropertyType)
                ||
                typeof (ICollection<>).MakeGenericType(destinationListType)
                    .IsAssignableFrom(propertyMap.DestinationPropertyType))
            {
                // Call .ToList() on IEnumerable
                var toListCallExpression = GetToListCallExpression(propertyMap, destinationListType, selectExpression);

                bindExpression = Expression.Bind(propertyMap.DestinationProperty.MemberInfo, toListCallExpression);
            }
            else if (propertyMap.DestinationPropertyType.IsArray)
            {
                // Call .ToArray() on IEnumerable
                MethodCallExpression toArrayCallExpression = Expression.Call(
                    typeof (Enumerable),
                    "ToArray",
                    new[] {destinationListType},
                    selectExpression);
                bindExpression = Expression.Bind(propertyMap.DestinationProperty.MemberInfo, toArrayCallExpression);
            }
            else
            {
                // destination type implements ienumerable, but is not an ilist. allow deferred enumeration
                bindExpression = Expression.Bind(propertyMap.DestinationProperty.MemberInfo, selectExpression);
            }
            return bindExpression;
        }
示例#8
0
 internal TransactionStats(Internal.TxnStatStruct stats) {
     st = stats.st;
     lastCkp = new LSN(st.st_last_ckp.file, st.st_last_ckp.offset);
     txns = new List<ActiveTransaction>();
     for (int i = 0; i < st.st_nactive; i++)
         txns.Add(new ActiveTransaction(
             stats.st_txnarray[i], stats.st_txngids[i], stats.st_txnnames[i]));
 }
 public static IntPtr gtk_application_new(string application_id, Internal.GIO.Constants.GApplicationFlags flags)
 {
     if (LIBRARY_FILENAME == LIBRARY_FILENAME_V2) {
         return IntPtr.Zero;
     } else {
         return gtk_application_new_v3 (application_id, flags);
     }
 }
示例#10
0
 internal void Build(Internal.SyntaxTree tree)
 {
     foreach(Internal.StatementNode n in tree.Nodes)
     {
         DataGroup group = BuildGroup(n);
         _TopGroups.Add(group);
     }
 }
示例#11
0
        private void OnGetRootDirectoryFromCommandLineResult(Internal.GetRootDirectoryFromCommandLineResult message)
        {
            var directory = message.RootDirectory;

            if (directory != null)
            {
                SetRootDir(directory);
            }
        }
示例#12
0
        internal ReplicationStats(Internal.ReplicationStatStruct stats) {
            st = stats;
            next = new LSN(st.st_next_lsn.file, st.st_next_lsn.offset);
            waiting = new LSN(st.st_waiting_lsn.file, st.st_waiting_lsn.offset);
            maxPerm =
                new LSN(st.st_max_perm_lsn.file, st.st_max_perm_lsn.offset);
            winner = new LSN(st.st_election_lsn.file, st.st_election_lsn.offset);

        }
示例#13
0
 public MappingEngine(IMapperContext mapperContext,
     Internal.IDictionary<TypePair, IObjectMapper> objectMapperCache,
     Func<Type, object> serviceCtor)
 {
     /* Never, ever carry a previously configured engine forward:
     that's the whole point of facilitating micro-mapping. */
     _mapperContext = mapperContext;
     ObjectMapperCache = objectMapperCache;
     ServiceCtor = serviceCtor;
     _mapperContext.ConfigurationProvider.TypeMapCreated += ClearTypeMap;
 }
示例#14
0
        private DataArray BuildArray(Internal.ArrayNode n)
        {
            DataArray array = new DataArray();
            foreach(Internal.ValueNode v in n.Nodes)
            {
                Data data = BuildArrayValue(v);
                if (data != null)
                    array.Add(data);
            }

            return array;
        }
示例#15
0
文件: Macro.cs 项目: GlenDC/L20n.cs
				public static bool PeekAndParse(
					CharStream stream,
					string identifier, Internal.LocaleContext.Builder builder)
				{
					if (stream.PeekNext() != '(')
					{
						return false;
					}

					Macro.Parse(stream, identifier, builder);
					return true;
				}
示例#16
0
文件: AAAA.cs 项目: boethin/dnstools
        internal override void ReadRDATA(Internal.ByteReader reader)
        {
            if (Base.RDLENGTH != 16)
            throw new InvalidResponseException(String.Format(
              "Invalid RDLENGTH value {0}: expected 16.",
              Base.RDLENGTH));

              byte[] buf = reader.ReadBytes(16);
              ADDRESS = new IPAddress(buf);
              if (ADDRESS.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
            throw new InvalidResponseException(String.Format(
              "Not an IPv6 address: {0}.", ADDRESS.ToString()));
        }
        private static MemberAssignment BindMappedTypeExpression(IMappingEngine mappingEngine, PropertyMap propertyMap,
            ExpressionRequest request, ExpressionResolutionResult result, Internal.IDictionary<ExpressionRequest, int> typePairCount)
        {
            var transformedExpression = ((IMappingEngineRunner)mappingEngine).CreateMapExpression(request, result.ResolutionExpression, typePairCount);

            // Handles null source property so it will not create an object with possible non-nullable propeerties
            // which would result in an exception.
            if (mappingEngine.ConfigurationProvider.MapNullSourceValuesAsNull)
            {
                var expressionNull = Expression.Constant(null, propertyMap.DestinationPropertyType);
                transformedExpression =
                    Expression.Condition(Expression.NotEqual(result.ResolutionExpression, Expression.Constant(null)),
                        transformedExpression, expressionNull);
            }

            return Expression.Bind(propertyMap.DestinationProperty.MemberInfo, transformedExpression);
        }
        public RuntimeMethodSignature GetSignature(Internal.Metadata.NativeFormat.Handle token)
        {
            switch (token.HandleType)
            {
                // These are the only valid token types for creating a method signature
                case Internal.Metadata.NativeFormat.HandleType.Method:
                case Internal.Metadata.NativeFormat.HandleType.MemberReference:
                case Internal.Metadata.NativeFormat.HandleType.QualifiedMethod:
                case Internal.Metadata.NativeFormat.HandleType.MethodInstantiation:
                case Internal.Metadata.NativeFormat.HandleType.MethodSignature:
                    break;

                default:
                    Environment.FailFast("Unknown and invalid handle type");
                    break;
            }
            return RuntimeMethodSignature.CreateFromMethodHandle(_metadataUnit.RuntimeModule, token.ToInt());
        }
示例#19
0
        /// <summary>
        /// Construct one or more TestMethods from a given MethodInfo,
        /// using available parameter data.
        /// </summary>
        /// <param name="method">The MethodInfo for which tests are to be constructed.</param>
        /// <param name="suite">The suite to which the tests will be added.</param>
        /// <returns>One or more TestMethods</returns>
        public IEnumerable<TestMethod> BuildFrom(MethodInfo method, Internal.Test suite)
        {
            ParameterInfo[] parameters = method.GetParameters();

            List<TestMethod> tests = new List<TestMethod>();

            if (parameters.Length > 0)
            {
                IEnumerable[] sources = new IEnumerable[parameters.Length];
                for (int i = 0; i < parameters.Length; i++)
                    sources[i] = _dataProvider.GetDataFor(parameters[i]);

                foreach (var parms in new CombinatorialStrategy().GetTestCases(sources))
                    tests.Add(_builder.BuildTestMethod(method, suite, (ParameterSet)parms));
            }

            return tests;
        }
示例#20
0
				public static void Parse(CharStream stream, Internal.LocaleContext.Builder builder)
				{
					var startingPos = stream.Position;
					
					try
					{
						stream.SkipString("import(");
						WhiteSpace.Parse(stream, true);
						var path = PureStringValue.Parse(stream);
						WhiteSpace.Parse(stream, true);
						stream.SkipCharacter(')');

						LocalizableObjectsList.ImportAndParse(path, builder);
					} catch (Exception e)
					{
						string msg = String.Format(
							"something went wrong parsing an <import_statement> starting at {0}",
							stream.ComputeDetailedPosition(startingPos));
						throw new Exceptions.ParseException(msg, e);
					}
				}
示例#21
0
        void Internal.IResponseReader.ReadResponse(Internal.ByteReader reader)
        {
            // header
              ((Internal.IResponseReader)Header).ReadResponse(reader);

              // question section
              for (int i = 0; i < Header.QDCOUNT; i++)
              {
            DNS.Question q = new DNS.Question();
            ((Internal.IResponseReader)q).ReadResponse(reader);
            Questions.Add(q);
              }

              // answer section
              ReadRecords(reader, AnswerRecordsList, Header.ANCOUNT);

              // authority records section.
              ReadRecords(reader, AuthorityRecordsList, Header.NSCOUNT);

              // additional records section
              ReadRecords(reader, AdditionalRecordsList, Header.ARCOUNT);
        }
示例#22
0
			/// <summary>
			/// Reads the L20n resource at the given path, and adds all the entries found in that resource,
			/// to the given <c>builder</c>.
			/// Throws a <see cref="L20nCore.Exceptions.ParseException"/> in case something went wrong,
			/// during the parsing of the given resource.
			/// </summary>
			public static void ImportAndParse(string path, Internal.LocaleContext.Builder builder)
			{
				try
				{
					using (CharStream stream = CharStream.CreateFromFile(path))
					{
						while (stream.InputLeft())
						{
							// Skip WhiteSpace
							IO.Parsers.WhiteSpace.Parse(stream, true);
							
							// Read Entry
							Parsers.Entry.Parse(stream, builder);
						}
					}
				} catch (Exception exception)
				{
					throw new Exceptions.ParseException(
						String.Format("couldn't parse <localizble_objects_list> from file: {0}", path),
						exception);
				}
			}
示例#23
0
文件: Entry.cs 项目: GlenDC/L20n.cs
				public static void Parse(CharStream stream, Internal.LocaleContext.Builder builder)
				{
					var startingPos = stream.Position;
					
					try
					{
						if (Comment.PeekAndParse(stream))
							return;

						// normally we keep the requirements of a format for a parser internal,
						// but in this case we have the same start for both a <macro> and an <entity>
						// so we simply have to make an exception in this case for performance reasons
						if (stream.SkipIfPossible('<'))
						{
							var identifier = Identifier.Parse(stream, true);

							if (Macro.PeekAndParse(stream, identifier, builder))
								return;

							// now it NEEDS to be a entitiy, else our input is simply invalid
							// knowing that we are already on a path of no return
							// because of the fact that we started parsing '<' and an identifier.
							Entity.Parse(stream, identifier, builder);
						} else
						{
							// it has to be an import statement at this point
							ImportStatement.Parse(stream, builder);
						}
					} catch (Exception e)
					{
						string msg = String.Format(
							"something went wrong parsing an <entry> starting at {0}",
							stream.ComputeDetailedPosition(startingPos));
						throw new ParseException(msg, e);
					}
				}
示例#24
0
 internal void FromInternal(Internal* native)
 {
     var __ptr = native;
     ID = __ptr->ID;
 }
示例#25
0
 internal MPoolFileStats(Internal.MPoolFileStatStruct stats)
 {
     st = stats;
 }
示例#26
0
 /// <summary>
 /// Practically wipes the slate clean for this user. If includeAchievements is true, will wipe
 /// any achievements too.
 /// </summary>
 /// <returns></returns>
 public static bool ResetAll(bool includeAchievements)
 {
     return(Internal.ResetAllStats(includeAchievements));
 }
示例#27
0
 /// <summary>
 /// Returns whether the specified move path point is valid.
 /// </summary>
 public bool IsValidPoint(int pointIndex)
 {
     AssertNotDisposed();
     return(Internal.IsValidMovePoint(Id, pointIndex));
 }
示例#28
0
 /***** TODO: create a custom collection to manage move points *****/
 /// <summary>
 /// Adds a point to the move path.
 /// </summary>
 public bool AddPoint(Vector3 point)
 {
     AssertNotDisposed();
     return(Internal.AddPointToPath(Id, point.X, point.Y, point.Z));
 }
示例#29
0
 /// <summary>
 /// Creates a new move path.
 /// </summary>
 public static MovePath Create()
 {
     return(Create(Internal.CreateMovePath()));
 }
示例#30
0
 /// <summary>
 /// Send the changed stats and achievements data to the server for permanent storage.
 /// If this fails then nothing is sent to the server. It's advisable to keep trying until the call is successful.
 /// This call can be rate limited. Call frequency should be on the order of minutes, rather than seconds.You should only be calling this during major state changes such as the end of a round, the map changing, or the user leaving a server. This call is required to display the achievement unlock notification dialog though, so if you have called SetAchievement then it's advisable to call this soon after that.
 /// If you have stats or achievements that you have saved locally but haven't uploaded with this function when your application process ends then this function will automatically be called.
 /// You can find additional debug information written to the %steam_install%\logs\stats_log.txt file.
 /// This function returns true upon success if :
 /// RequestCurrentStats has completed and successfully returned its callback AND
 /// the current game has stats associated with it in the Steamworks Partner backend, and those stats are published.
 /// </summary>
 public static bool StoreStats()
 {
     return(Internal.StoreStats());
 }
示例#31
0
 /// <summary>
 /// Set a stat value. This will automatically call StoreStats() after a successful call
 /// unless you pass false as the last argument.
 /// </summary>
 public static bool SetStat(string name, float value)
 {
     return(Internal.SetStat(name, value));
 }
示例#32
0
 public static Double Pow(Double x, Double y)
 {
     return(Internal.Math_Pow(x, y));
 }
示例#33
0
 public static Double Tan(Double val)
 {
     return(Internal.Math_Tan(val));
 }
示例#34
0
    ////////// ////////// ////////// ////////// //////////
    // Others.

    public static Double Sqrt(Double val)
    {
        return(Internal.Math_Sqrt(val));
    }
示例#35
0
 public DynamicCheckpoint(Vector3 position, float size = 1.0f, int worldid          = -1, int interiorid       = -1,
                          BasePlayer player            = null, float streamdistance = 100.0f, DynamicArea area = null, int priority = 0)
 {
     Id = Internal.CreateDynamicCP(position.X, position.Y, position.Z, size, worldid, interiorid,
                                   player?.Id ?? -1, streamdistance, area?.Id ?? -1, priority);
 }
示例#36
0
        public static DynamicCheckpoint GetPlayerVisibleDynamicCheckpoint(BasePlayer player)
        {
            var id = Internal.GetPlayerVisibleDynamicCP(player.Id);

            return(id < 0 ? null : FindOrCreate(id));
        }
示例#37
0
        private bool CreateProjectSolution()
        {
            using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 3))
            {
                pr.Step("Generating C# project...".TTR());

                string resourceDir = ProjectSettings.GlobalizePath("res://");

                string path = resourceDir;
                string name = ProjectAssemblyName;

                string guid = CsProjOperations.GenerateGameProject(path, name);

                if (guid.Length > 0)
                {
                    var solution = new DotNetSolution(name)
                    {
                        DirectoryPath = path
                    };

                    var projectInfo = new DotNetSolution.ProjectInfo
                    {
                        Guid = guid,
                        PathRelativeToSolution = name + ".csproj",
                        Configs = new List <string> {
                            "Debug", "ExportDebug", "ExportRelease"
                        }
                    };

                    solution.AddNewProject(name, projectInfo);

                    try
                    {
                        solution.Save();
                    }
                    catch (IOException e)
                    {
                        ShowErrorDialog("Failed to save solution. Exception message: ".TTR() + e.Message);
                        return(false);
                    }

                    pr.Step("Updating Godot API assemblies...".TTR());

                    string debugApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Debug");

                    if (!string.IsNullOrEmpty(debugApiAssembliesError))
                    {
                        ShowErrorDialog("Failed to update the Godot API assemblies: " + debugApiAssembliesError);
                        return(false);
                    }

                    string releaseApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Release");

                    if (!string.IsNullOrEmpty(releaseApiAssembliesError))
                    {
                        ShowErrorDialog("Failed to update the Godot API assemblies: " + releaseApiAssembliesError);
                        return(false);
                    }

                    pr.Step("Done".TTR());

                    // Here, after all calls to progress_task_step
                    CallDeferred(nameof(_RemoveCreateSlnMenuOption));
                }
                else
                {
                    ShowErrorDialog("Failed to create C# project.".TTR());
                }

                return(true);
            }
        }
示例#38
0
 public static Double Cosh(Double val)
 {
     return(Internal.Math_Cosh(val));
 }
示例#39
0
 internal BTreeStats(Internal.BTreeStatStruct stats)
 {
     st = stats;
 }
示例#40
0
 public static Double Asin(Double val)
 {
     return(Internal.Math_Asin(val));
 }
示例#41
0
 /// <summary>
 /// Removes a point from the move path.
 /// </summary>
 public bool RemovePoint(int pointIndex)
 {
     AssertNotDisposed();
     return(Internal.RemovePointFromPath(Id, pointIndex));
 }
示例#42
0
 public static Double Acos(Double val)
 {
     return(Internal.Math_Acos(val));
 }
示例#43
0
 /// <summary>
 /// Destroys the move path.
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     Internal.DestroyMovePath(Id);
     base.Dispose(disposing);
 }
示例#44
0
 public static Double Atanh(Double val)
 {
     return(Internal.Math_Atanh(val));
 }
示例#45
0
 /// <summary>
 /// Gets the the count of points.
 /// </summary>
 public int GetPointCount()
 {
     AssertNotDisposed();
     return(Internal.GetNumberMovePoint(Id));
 }
示例#46
0
 public static Double Log10(Double val)
 {
     return(Internal.Math_Log10(val));
 }
示例#47
0
 /// <summary>
 /// Gets the specified point.
 /// </summary>
 public Vector3 GetPoint(int pointIndex)
 {
     AssertNotDisposed();
     Internal.GetMovePoint(Id, pointIndex, out float x, out float y, out float z);
     return(new Vector3(x, y, z));
 }
示例#48
0
 protected override async Task BeforeEach()
 {
     inte = await Internal.New(RpcClient);
 }
示例#49
0
        public PanelTab AddTab(RectTransform tabContent, int tabIndex = -1)
        {
            if (!tabContent)
            {
                return(null);
            }

            // Reset active tab because otherwise, it acts buggy in rare cases
            if (activeTab >= 0 && activeTab < tabs.Count)
            {
                tabs[activeTab].Internal.SetActive(false);
            }

            activeTab = -1;

            if (tabIndex < 0 || tabIndex > tabs.Count)
            {
                tabIndex = tabs.Count;
            }

            int thisTabIndex = GetTabIndex(tabContent);

            if (thisTabIndex == -1)
            {
                PanelTab tab = PanelUtils.GetAssociatedTab(tabContent);
                if (!tab)
                {
                    tab = Instantiate(tabPrefab, tabsParent, false);
                    tabs.Insert(tabIndex, tab);

                    tabContent.anchorMin        = Vector2.zero;
                    tabContent.anchorMax        = Vector2.one;
                    tabContent.sizeDelta        = Vector2.zero;
                    tabContent.anchoredPosition = Vector2.zero;
                    tabContent.localScale       = Vector3.one;
                }
                else
                {
                    tabs.Insert(tabIndex, tab);

                    tab.Internal.rectTransform.SetParent(null, false); // workaround for a rare internal Unity crash
                    tab.Internal.rectTransform.SetParent(tabsParent, false);

                    tab.Panel.Internal.RemoveTab(tab.Index, false);
                }

                tab.Internal.Initialize(this, tabContent);
                tab.Internal.rectTransform.SetSiblingIndex(tabIndex);

                tabContent.SetParent(null, false); // workaround for a rare internal Unity crash
                tabContent.SetParent(contentParent, false);

                Internal.RecalculateMinSize();
            }
            else if (thisTabIndex != tabIndex)
            {
                if (tabIndex == tabs.Count)
                {
                    tabIndex = tabs.Count - 1;
                }

                PanelTab tab = tabs[thisTabIndex];
                tab.Internal.rectTransform.SetSiblingIndex(tabIndex);

                tabs.RemoveAt(thisTabIndex);
                tabs.Insert(tabIndex, tab);
            }

            ActiveTab = tabIndex;
            return(tabs[tabIndex]);
        }
示例#50
0
 internal QueueStats(Internal.QueueStatStruct stats)
 {
     st = stats;
 }
示例#51
0
 internal SequenceStats(Internal.SequenceStatStruct stats)
 {
     st = stats;
 }
示例#52
0
        /// <summary>
        /// Create a single cell to resolve based on a MetadataFixupKind, and the matching tokens
        /// </summary>
        internal static GenericDictionaryCell CreateCellFromFixupKindAndToken(MetadataFixupKind kind, FixupCellMetadataResolver metadata, Internal.Metadata.NativeFormat.Handle token, Internal.Metadata.NativeFormat.Handle token2)
        {
            GenericDictionaryCell cell;

            switch (kind)
            {
                case MetadataFixupKind.TypeHandle:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("TypeHandle: " + type.ToString());

                        cell = new TypeHandleCell() { Type = type };
                    }
                    break;

                case MetadataFixupKind.ArrayOfTypeHandle:
                    {
                        var type = metadata.GetType(token);
                        var arrayType = type.Context.GetArrayType(type);
                        TypeLoaderLogger.WriteLine("TypeHandle: " + arrayType.ToString());

                        cell = new TypeHandleCell() { Type = arrayType };
                    }
                    break;

                case MetadataFixupKind.VirtualCallDispatch:
                    {
                        var method = metadata.GetMethod(token);


                        var containingType = method.OwningType;
                        if (containingType.IsInterface)
                        {
                            ushort slot;
                            if (!LazyVTableResolver.TryGetInterfaceSlotNumberFromMethod(method, out slot))
                            {
                                Environment.FailFast("Unable to get interface slot while resolving InterfaceCall dictionary cell");
                            }

                            TypeLoaderLogger.WriteLine("InterfaceCall: " + containingType.ToString() + ", slot #" + ((int)slot).LowLevelToString());

                            cell = new InterfaceCallCell() { InterfaceType = containingType, Slot = (int)slot };
                        }
                        else
                        {
                            // TODO! Implement virtual dispatch cell creation
                            throw NotImplemented.ByDesign;
                        }
                    }
                    break;

                case MetadataFixupKind.MethodDictionary:
                    {
                        var genericMethod = metadata.GetMethod(token);
                        TypeLoaderLogger.WriteLine("MethodDictionary: " + genericMethod.ToString());

                        cell = new MethodDictionaryCell { GenericMethod = (InstantiatedMethod)genericMethod };
                    }
                    break;

                case MetadataFixupKind.GcStaticData:
                    {
                        var type = metadata.GetType(token);
                        var staticDataKind = StaticDataKind.Gc;
                        TypeLoaderLogger.WriteLine("StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());

                        cell = new StaticDataCell() { DataKind = staticDataKind, Type = type };
                    }
                    break;

                case MetadataFixupKind.NonGcStaticData:
                    {
                        var type = metadata.GetType(token);
                        var staticDataKind = StaticDataKind.NonGc;
                        TypeLoaderLogger.WriteLine("StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());

                        cell = new StaticDataCell() { DataKind = staticDataKind, Type = type };
                    }
                    break;

                case MetadataFixupKind.DirectGcStaticData:
                    {
                        var type = metadata.GetType(token);
                        var staticDataKind = StaticDataKind.Gc;
                        TypeLoaderLogger.WriteLine("Direct StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());

                        cell = new StaticDataCell() { DataKind = staticDataKind, Type = type, Direct = true };
                    }
                    break;

                case MetadataFixupKind.DirectNonGcStaticData:
                    {
                        var type = metadata.GetType(token);
                        var staticDataKind = StaticDataKind.NonGc;
                        TypeLoaderLogger.WriteLine("Direct StaticData (" + (staticDataKind == StaticDataKind.Gc ? "Gc" : "NonGc") + ": " + type.ToString());

                        cell = new StaticDataCell() { DataKind = staticDataKind, Type = type, Direct = true };
                    }
                    break;

                case MetadataFixupKind.UnwrapNullableType:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("UnwrapNullableType of: " + type.ToString());

                        cell = new UnwrapNullableTypeCell() { Type = (DefType)type };
                    }
                    break;

                case MetadataFixupKind.FieldLdToken:
                    {
                        var field = metadata.GetField(token);

                        TypeLoaderLogger.WriteLine("LdToken on: " + field.ToString());
                        IntPtr fieldName = TypeLoaderEnvironment.Instance.GetNativeFormatStringForString(field.Name);
                        cell = new FieldLdTokenCell() { FieldName = fieldName, ContainingType = field.OwningType };
                    }
                    break;

                case MetadataFixupKind.MethodLdToken:
                    {
                        var method = metadata.GetMethod(token);
                        TypeLoaderLogger.WriteLine("LdToken on: " + method.ToString());
                        var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();

                        cell = new MethodLdTokenCell
                        {
                            Method = method,
                            MethodName = IntPtr.Zero,
                            MethodSignature = RuntimeMethodSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
                        };
                    }
                    break;

                case MetadataFixupKind.TypeSize:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("TypeSize: " + type.ToString());

                        cell = new TypeSizeCell() { Type = type };
                    }
                    break;

                case MetadataFixupKind.FieldOffset:
                    {
                        var field = metadata.GetField(token);
                        TypeLoaderLogger.WriteLine("FieldOffset: " + field.ToString());

                        cell = new FieldOffsetCell() { Field = field };
                    }
                    break;

                case MetadataFixupKind.AllocateObject:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("AllocateObject on: " + type.ToString());

                        cell = new AllocateObjectCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.DefaultConstructor:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("DefaultConstructor on: " + type.ToString());

                        cell = new DefaultConstructorCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.TlsIndex:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("TlsIndex on: " + type.ToString());

                        cell = new TlsIndexCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.TlsOffset:
                    {
                        var type = metadata.GetType(token);
                        TypeLoaderLogger.WriteLine("TlsOffset on: " + type.ToString());

                        cell = new TlsOffsetCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.UnboxingStubMethod:
                    {
                        var method = metadata.GetMethod(token);
                        TypeLoaderLogger.WriteLine("Unboxing Stub Method: " + method.ToString());
                        if (method.OwningType.IsValueType)
                        {
                            // If an unboxing stub could exists, that's actually what we want
                            method = method.Context.ResolveGenericMethodInstantiation(true/* get the unboxing stub */, method.OwningType.GetClosestDefType(), method.NameAndSignature, method.Instantiation, IntPtr.Zero, false);
                        }

                        var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();

                        cell = new MethodCell
                        {
                            Method = method,
                            MethodSignature = RuntimeMethodSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
                        };
                    }
                    break;

                case MetadataFixupKind.Method:
                    {
                        var method = metadata.GetMethod(token);
                        TypeLoaderLogger.WriteLine("Method: " + method.ToString());
                        var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();

                        cell = new MethodCell
                        {
                            Method = method,
                            MethodSignature = RuntimeMethodSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
                        };
                    }
                    break;

                case MetadataFixupKind.CallableMethod:
                    {
                        var method = metadata.GetMethod(token);
                        TypeLoaderLogger.WriteLine("CallableMethod: " + method.ToString());
                        var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();

                        cell = new MethodCell
                        {
                            ExactCallableAddressNeeded = true,
                            Method = method,
                            MethodSignature = RuntimeMethodSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
                        };
                    }
                    break;

                case MetadataFixupKind.NonGenericDirectConstrainedMethod:
                    {
                        var constraintType = metadata.GetType(token);
                        var method = metadata.GetMethod(token2);
                        var constrainedMethodType = method.OwningType;
                        var constrainedMethodSlot = ComputeConstrainedMethodSlot(method);

                        TypeLoaderLogger.WriteLine("NonGenericDirectConstrainedMethod: " + constraintType.ToString() + " Method:" + method.ToString() + " Consisting of " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());

                        cell = new NonGenericDirectConstrainedMethodCell()
                        {
                            ConstraintType = constraintType,
                            ConstrainedMethodType = constrainedMethodType,
                            ConstrainedMethodSlot = (int)constrainedMethodSlot
                        };
                    }
                    break;

                case MetadataFixupKind.NonGenericConstrainedMethod:
                    {
                        var constraintType = metadata.GetType(token);
                        var method = metadata.GetMethod(token2);
                        var constrainedMethodType = method.OwningType;
                        var constrainedMethodSlot = ComputeConstrainedMethodSlot(method);

                        TypeLoaderLogger.WriteLine("NonGenericConstrainedMethod: " + constraintType.ToString() + " Method:" + method.ToString() + " Consisting of " + constrainedMethodType.ToString() + ", slot #" + constrainedMethodSlot.LowLevelToString());

                        cell = new NonGenericConstrainedMethodCell()
                        {
                            ConstraintType = constraintType,
                            ConstrainedMethodType = constrainedMethodType,
                            ConstrainedMethodSlot = (int)constrainedMethodSlot
                        };
                    }
                    break;

                case MetadataFixupKind.GenericConstrainedMethod:
                    {
                        var constraintType = metadata.GetType(token);
                        var method = metadata.GetMethod(token2);
                        var nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)method.GetTypicalMethodDefinition();


                        TypeLoaderLogger.WriteLine("GenericConstrainedMethod: " + constraintType.ToString() + " Method " + method.ToString());

                        cell = new GenericConstrainedMethodCell()
                        {
                            ConstraintType = constraintType,
                            ConstrainedMethod = method,
                            MethodName = IntPtr.Zero,
                            MethodSignature = RuntimeMethodSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt())
                        };
                    }
                    break;

                case MetadataFixupKind.IsInst:
                case MetadataFixupKind.CastClass:
                    {
                        var type = metadata.GetType(token);

                        TypeLoaderLogger.WriteLine("Casting on: " + type.ToString());

                        cell = new CastingCell { Type = type, Throwing = (kind == MetadataFixupKind.CastClass) };
                    }
                    break;

                case MetadataFixupKind.AllocateArray:
                    {
                        var type = metadata.GetType(token);

                        TypeLoaderLogger.WriteLine("AllocateArray on: " + type.ToString());

                        cell = new AllocateArrayCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.CheckArrayElementType:
                    {
                        var type = metadata.GetType(token);

                        TypeLoaderLogger.WriteLine("CheckArrayElementType on: " + type.ToString());

                        cell = new CheckArrayElementTypeCell { Type = type };
                    }
                    break;

                case MetadataFixupKind.CallingConventionConverter_NoInstantiatingParam:
                case MetadataFixupKind.CallingConventionConverter_MaybeInstantiatingParam:
                case MetadataFixupKind.CallingConventionConverter_HasInstantiatingParam:
                    {
                        CallingConventionConverterKind converterKind;
                        switch (kind)
                        {
                            case MetadataFixupKind.CallingConventionConverter_NoInstantiatingParam:
                                converterKind = CallingConventionConverterKind.NoInstantiatingParam;
                                break;
                            case MetadataFixupKind.CallingConventionConverter_MaybeInstantiatingParam:
                                converterKind = CallingConventionConverterKind.MaybeInstantiatingParam;
                                break;
                            case MetadataFixupKind.CallingConventionConverter_HasInstantiatingParam:
                                converterKind = CallingConventionConverterKind.HasInstantiatingParam;
                                break;
                            default:
                                Environment.FailFast("Unknown converter kind");
                                throw new BadImageFormatException();
                        }

                        cell = new CallingConventionConverterCell
                        {
                            Flags = converterKind,
                            Signature = metadata.GetSignature(token),
                            MethodArgs = metadata.MethodInstantiation,
                            TypeArgs = metadata.TypeInstantiation
                        };

#if TYPE_LOADER_TRACE
                        TypeLoaderLogger.WriteLine("CallingConventionConverter on: ");
                        TypeLoaderLogger.WriteLine("     -> Flags: " + ((int)converterKind).LowLevelToString());
                        TypeLoaderLogger.WriteLine("     -> Signature: " + token.ToInt().LowLevelToString());
                        for (int i = 0; i < metadata.TypeInstantiation.Length; i++)
                            TypeLoaderLogger.WriteLine("     -> TypeArg[" + i.LowLevelToString() + "]: " + metadata.TypeInstantiation[i]);
                        for (int i = 0; i < metadata.MethodInstantiation.Length; i++)
                            TypeLoaderLogger.WriteLine("     -> MethodArg[" + i.LowLevelToString() + "]: " + metadata.MethodInstantiation[i]);
#endif
                    }
                    break;

                default:
                    Environment.FailFast("Unknown fixup kind");
                    // Throw here so that the compiler won't complain.
                    throw new BadImageFormatException();
            }

            return cell;
        }
 public MemberAssignment Build(IMappingEngine mappingEngine, PropertyMap propertyMap, TypeMap propertyTypeMap,
     ExpressionRequest request, ExpressionResolutionResult result, Internal.IDictionary<ExpressionRequest, int> typePairCount)
 {
     return BindMappedTypeExpression(mappingEngine, propertyMap, request, result, typePairCount);
 }
示例#54
0
        public Error OpenInExternalEditor(Script script, int line, int col)
        {
            var editorId = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor");

            switch (editorId)
            {
            case ExternalEditorId.None:
                // Not an error. Tells the caller to fallback to the global external editor settings or the built-in editor.
                return(Error.Unavailable);

            case ExternalEditorId.VisualStudio:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                var args = new List <string>
                {
                    GodotSharpDirs.ProjectSlnPath,
                    line >= 0 ? $"{scriptPath};{line + 1};{col + 1}" : scriptPath
                };

                string command = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "GodotTools.OpenVisualStudio.exe");

                try
                {
                    if (Godot.OS.IsStdoutVerbose())
                    {
                        Console.WriteLine($"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}");
                    }

                    OS.RunProcess(command, args);
                }
                catch (Exception e)
                {
                    GD.PushError($"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'");
                }

                break;
            }

            case ExternalEditorId.VisualStudioForMac:
                goto case ExternalEditorId.MonoDevelop;

            case ExternalEditorId.Rider:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
                RiderPathManager.OpenFile(GodotSharpDirs.ProjectSlnPath, scriptPath, line);
                return(Error.Ok);
            }

            case ExternalEditorId.MonoDevelop:
            {
                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                GodotIdeManager.LaunchIdeAsync().ContinueWith(launchTask =>
                    {
                        var editorPick = launchTask.Result;
                        if (line >= 0)
                        {
                            editorPick?.SendOpenFile(scriptPath, line + 1, col);
                        }
                        else
                        {
                            editorPick?.SendOpenFile(scriptPath);
                        }
                    });

                break;
            }

            case ExternalEditorId.VsCode:
            {
                if (string.IsNullOrEmpty(_vsCodePath) || !File.Exists(_vsCodePath))
                {
                    // Try to search it again if it wasn't found last time or if it was removed from its location
                    _vsCodePath = VsCodeNames.SelectFirstNotNull(OS.PathWhich, orElse: string.Empty);
                }

                var args = new List <string>();

                bool osxAppBundleInstalled = false;

                if (OS.IsOSX)
                {
                    // The package path is '/Applications/Visual Studio Code.app'
                    const string vscodeBundleId = "com.microsoft.VSCode";

                    osxAppBundleInstalled = Internal.IsOsxAppBundleInstalled(vscodeBundleId);

                    if (osxAppBundleInstalled)
                    {
                        args.Add("-b");
                        args.Add(vscodeBundleId);

                        // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is
                        // editing our folder. It's better to ask for a new window and let VSCode do the window management.
                        args.Add("-n");

                        // The open process must wait until the application finishes (which is instant in VSCode's case)
                        args.Add("--wait-apps");

                        args.Add("--args");
                    }
                }

                var resourcePath = ProjectSettings.GlobalizePath("res://");
                args.Add(resourcePath);

                string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);

                if (line >= 0)
                {
                    args.Add("-g");
                    args.Add($"{scriptPath}:{line}:{col}");
                }
                else
                {
                    args.Add(scriptPath);
                }

                string command;

                if (OS.IsOSX)
                {
                    if (!osxAppBundleInstalled && string.IsNullOrEmpty(_vsCodePath))
                    {
                        GD.PushError("Cannot find code editor: VSCode");
                        return(Error.FileNotFound);
                    }

                    command = osxAppBundleInstalled ? "/usr/bin/open" : _vsCodePath;
                }
                else
                {
                    if (string.IsNullOrEmpty(_vsCodePath))
                    {
                        GD.PushError("Cannot find code editor: VSCode");
                        return(Error.FileNotFound);
                    }

                    command = _vsCodePath;
                }

                try
                {
                    OS.RunProcess(command, args);
                }
                catch (Exception e)
                {
                    GD.PushError($"Error when trying to run code editor: VSCode. Exception message: '{e.Message}'");
                }

                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(Error.Ok);
        }
示例#55
0
        private static string FindMsBuildToolsPathOnWindows()
        {
            if (!OS.IsWindows)
            {
                throw new PlatformNotSupportedException();
            }

            // Try to find 15.0 with vswhere

            string[] envNames = Internal.GodotIs32Bits() ?
                                envNames = new[] { "ProgramFiles", "ProgramW6432" } :
            envNames = new[] { "ProgramFiles(x86)", "ProgramFiles" };

            string vsWherePath = null;

            foreach (var envName in envNames)
            {
                vsWherePath = Environment.GetEnvironmentVariable(envName);
                if (!string.IsNullOrEmpty(vsWherePath))
                {
                    vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
                    if (File.Exists(vsWherePath))
                    {
                        break;
                    }
                }

                vsWherePath = null;
            }

            var vsWhereArgs = new[] { "-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild" };

            var outputArray = new Godot.Collections.Array <string>();
            int exitCode    = Godot.OS.Execute(vsWherePath, vsWhereArgs,
                                               blocking: true, output: (Godot.Collections.Array)outputArray);

            if (exitCode != 0)
            {
                return(string.Empty);
            }

            if (outputArray.Count == 0)
            {
                return(string.Empty);
            }

            var lines = outputArray[0].Split('\n');

            foreach (string line in lines)
            {
                int sepIdx = line.IndexOf(':');

                if (sepIdx <= 0)
                {
                    continue;
                }

                string key = line.Substring(0, sepIdx); // No need to trim

                if (key != "installationPath")
                {
                    continue;
                }

                string value = line.Substring(sepIdx + 1).StripEdges();

                if (string.IsNullOrEmpty(value))
                {
                    throw new FormatException("installationPath value is empty");
                }

                if (!value.EndsWith("\\"))
                {
                    value += "\\";
                }

                // Since VS2019, the directory is simply named "Current"
                string msbuildDir = Path.Combine(value, "MSBuild\\Current\\Bin");

                if (Directory.Exists(msbuildDir))
                {
                    return(msbuildDir);
                }

                // Directory name "15.0" is used in VS 2017
                return(Path.Combine(value, "MSBuild\\15.0\\Bin"));
            }

            return(string.Empty);
        }
示例#56
0
        public static void GenerateScriptsMetadata(string projectPath, string outputPath)
        {
            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            var oldDict = Internal.GetScriptsMetadataOrNothing();
            var newDict = new Godot.Collections.Dictionary <string, object>();

            foreach (var includeFile in ProjectUtils.GetIncludeFiles(projectPath, "Compile"))
            {
                string projectIncludeFile = ("res://" + includeFile).SimplifyGodotPath();

                ulong modifiedTime = File.GetLastWriteTime(projectIncludeFile).ConvertToTimestamp();

                if (oldDict.TryGetValue(projectIncludeFile, out var oldFileVar))
                {
                    var oldFileDict = (Dictionary)oldFileVar;

                    if (ulong.TryParse(oldFileDict["modified_time"] as string, out ulong storedModifiedTime))
                    {
                        if (storedModifiedTime == modifiedTime)
                        {
                            // No changes so no need to parse again
                            newDict[projectIncludeFile] = oldFileDict;
                            continue;
                        }
                    }
                }

                ScriptClassParser.ParseFileOrThrow(projectIncludeFile, out var classes);

                string searchName = System.IO.Path.GetFileNameWithoutExtension(projectIncludeFile);

                var classDict = new Dictionary();

                foreach (var classDecl in classes)
                {
                    if (classDecl.BaseCount == 0)
                    {
                        continue; // Does not inherit nor implement anything, so it can't be a script class
                    }
                    string classCmp = classDecl.Nested ?
                                      classDecl.Name.Substring(classDecl.Name.LastIndexOf(".", StringComparison.Ordinal) + 1) :
                                      classDecl.Name;

                    if (classCmp != searchName)
                    {
                        continue;
                    }

                    classDict["namespace"]  = classDecl.Namespace;
                    classDict["class_name"] = classDecl.Name;
                    classDict["nested"]     = classDecl.Nested;
                    break;
                }

                if (classDict.Count == 0)
                {
                    continue; // Not found
                }
                newDict[projectIncludeFile] = new Dictionary {
                    ["modified_time"] = $"{modifiedTime}", ["class"] = classDict
                };
            }

            if (newDict.Count > 0)
            {
                string json = JSON.Print(newDict);

                string baseDir = outputPath.GetBaseDir();

                if (!Directory.Exists(baseDir))
                {
                    Directory.CreateDirectory(baseDir);
                }

                File.WriteAllText(outputPath, json);
            }
        }
示例#57
0
 public virtual void Cancel() => Internal.CancelQuery(request);
示例#58
0
 public bool Equals(RubyObject other) => !(other is null) && rb_obj_equal(Internal, other.Internal).IsTrue;
示例#59
0
 public static Double Sinh(Double val)
 {
     return(Internal.Math_Sinh(val));
 }
示例#60
0
 /// <summary>
 /// Asynchronously request the user's current stats and achievements from the server.
 /// You must always call this first to get the initial status of stats and achievements.
 /// Only after the resulting callback comes back can you start calling the rest of the stats
 /// and achievement functions for the current user.
 /// </summary>
 public static bool RequestCurrentStats()
 {
     return(Internal.RequestCurrentStats());
 }