Beispiel #1
0
        /// <summary>
        /// Starts a process asynchronously.<para/>
        /// <remarks>The provided Process Start Info must not use shell execution, and should redirect the standard output and errors.</remarks>
        /// </summary>
        /// <param name="process">This Process.</param>
        /// <param name="startInfo">The Process start info.</param>
        /// <param name="showDebug">Should output debug code to Editor Console?</param>
        /// <returns><see cref="Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities.ProcessResult"/></returns>
        public static async Task <ProcessResult> StartProcessAsync(this Process process, ProcessStartInfo startInfo, bool showDebug = false)
        {
            Debug.Assert(!startInfo.UseShellExecute, "Process Start Info must not use shell execution.");
            Debug.Assert(startInfo.RedirectStandardOutput, "Process Start Info must redirect standard output.");
            Debug.Assert(startInfo.RedirectStandardError, "Process Start Info must redirect standard errors.");

            process.StartInfo           = startInfo;
            process.EnableRaisingEvents = true;

            var processResult    = new TaskCompletionSource <ProcessResult>();
            var errorCodeResult  = new TaskCompletionSource <string[]>();
            var errorList        = new List <string>();
            var outputCodeResult = new TaskCompletionSource <string[]>();
            var outputList       = new List <string>();

            process.Exited += async(sender, args) =>
            {
                processResult.TrySetResult(new ProcessResult(process.ExitCode, await errorCodeResult.Task, await outputCodeResult.Task));
                process.Close();
                process.Dispose();
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    errorList.Add(args.Data);
                    if (showDebug)
                    {
                        Debug.LogError(args.Data);
                    }
                }
                else
                {
                    errorCodeResult.TrySetResult(errorList.ToArray());
                }
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    outputList.Add(args.Data);
                    if (showDebug)
                    {
                        Debug.Log(args.Data);
                    }
                }
                else
                {
                    outputCodeResult.TrySetResult(outputList.ToArray());
                }
            };

            if (!process.Start())
            {
                if (showDebug)
                {
                    Debug.LogError("Failed to start process!");
                }

                processResult.TrySetResult(new ProcessResult(process.ExitCode, new[] { "Failed to start process!" }, null));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return(await processResult.Task);
        }
Beispiel #2
0
        private static void Init()
        {
            var projectDirectory = Directory.GetParent(Application.dataPath).FullName;

            var projectName = Path.GetFileName(projectDirectory);

            SlnFile = Path.GetFullPath($"{projectName}.sln");

            InitializeEditorInstanceJson();

            // for the case when files were changed and user just alt+tab to unity to make update, we want to fire
            CsprojAssetPostprocessor.OnGeneratedCSProjectFiles();

            Log.DefaultFactory = new RiderLoggerFactory();

            var lifetimeDefinition = Lifetimes.Define(EternalLifetime.Instance);
            var lifetime           = lifetimeDefinition.Lifetime;

            AppDomain.CurrentDomain.DomainUnload += (EventHandler)((_, __) =>
            {
                ourLogger.Verbose("lifetimeDefinition.Terminate");
                lifetimeDefinition.Terminate();
            });

            if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.VERBOSE)
            {
                Debug.Log($"Rider plugin initialized. LoggingLevel: {PluginSettings.SelectedLoggingLevel}. Change it in Unity Preferences -> Rider. Logs path: {LogPath}.");
            }

            try
            {
                var riderProtocolController = new RiderProtocolController(MainThreadDispatcher.Instance, lifetime);

                var serializers = new Serializers();
                var identities  = new Identities(IdKind.Server);

                MainThreadDispatcher.AssertThread();

                riderProtocolController.Wire.Connected.View(lifetime, (lt, connected) =>
                {
                    if (connected)
                    {
                        var protocol = new Protocol(serializers, identities, MainThreadDispatcher.Instance, riderProtocolController.Wire);
                        ourLogger.Log(LoggingLevel.VERBOSE, "Create UnityModel and advise for new sessions...");

                        ourModel.Value = CreateModel(protocol, lt);
                    }
                    else
                    {
                        ourModel.Value = null;
                    }
                });
            }
            catch (Exception ex)
            {
                ourLogger.Error("Init Rider Plugin " + ex);
            }

            ourAssetHandler = new OnOpenAssetHandler(ourModel, ourRiderPathLocator, ourPluginSettings, SlnFile);

            ourInitialized = true;
        }
Beispiel #3
0
        private static List <List <Person> > GenerateTables(int count, int fixedTarget, int complexity)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            Action stop = () =>
            {
                stopwatch.Stop();
                Debug.Log("GenerateTables: stopWatch.Elapsed=" + stopwatch.Elapsed.TotalSeconds);
            };

            const int iterations = 1000;

            for (var i = 0; i <= iterations; i++)
            {
                var tables = CreateRandomTables(count);
                int max, fake;
                List <List <Person> > worst;
                List <List <Person> > best;

                Analize(tables, out worst, out best, out max, out fake);

                Debug.Log("max = " + max);

                if (fixedTarget == -1 && complexity == -1)
                {
                    stop();
                    return(worst);
                }

                if (fixedTarget != -1 && complexity != -1)
                {
                    if (max == fixedTarget && fake == complexity)
                    {
                        stop();
                        return(worst);
                    }
                }
                else if (fixedTarget != -1 && max == fixedTarget)
                {
                    stop();
                    return(worst);
                }
                else if (complexity != -1 && fake == complexity)
                {
                    stop();
                    return(worst);
                }
                else if (i == iterations)
                {
                    stop();
                    return(worst);
                }
                else if (stopwatch.Elapsed.TotalSeconds > 20)
                {
                    stop();
                    return(worst);
                }
            }

            throw new Exception();
        }
Beispiel #4
0
        public void handleBeginFrame(TimeSpan?rawTimeStamp)
        {
            this._firstRawTimeStampInEpoch = this._firstRawTimeStampInEpoch ?? rawTimeStamp;
            this._currentFrameTimeStamp    = this._adjustForEpoch(rawTimeStamp ?? this._lastRawTimeStamp);

            if (rawTimeStamp != null)
            {
                this._lastRawTimeStamp = rawTimeStamp.Value;
            }

            D.assert(() => {
                this._profileFrameNumber += 1;
                return(true);
            });

            D.assert(() => {
                if (D.debugPrintBeginFrameBanner || D.debugPrintEndFrameBanner)
                {
                    var frameTimeStampDescription = new StringBuilder();
                    if (rawTimeStamp != null)
                    {
                        _debugDescribeTimeStamp(
                            this._currentFrameTimeStamp.Value, frameTimeStampDescription);
                    }
                    else
                    {
                        frameTimeStampDescription.Append("(warm-up frame)");
                    }

                    this._debugBanner =
                        $"▄▄▄▄▄▄▄▄ Frame {this._profileFrameNumber.ToString().PadRight(7)}   {frameTimeStampDescription.ToString().PadLeft(18)} ▄▄▄▄▄▄▄▄";
                    if (D.debugPrintBeginFrameBanner)
                    {
                        Debug.Log(this._debugBanner);
                    }
                }

                return(true);
            });

            D.assert(this._schedulerPhase == SchedulerPhase.idle);
            this._hasScheduledFrame = false;

            try {
                this._schedulerPhase = SchedulerPhase.transientCallbacks;
                var callbacks = this._transientCallbacks;
                this._transientCallbacks = new Dictionary <int, _FrameCallbackEntry>();
                foreach (var entry in callbacks)
                {
                    if (!this._removedIds.Contains(entry.Key))
                    {
                        this._invokeFrameCallback(
                            entry.Value.callback, this._currentFrameTimeStamp.Value, entry.Value.debugStack);
                    }
                }

                this._removedIds.Clear();
            } finally {
                this._schedulerPhase = SchedulerPhase.midFrameMicrotasks;
            }
        }
Beispiel #5
0
        internal static Promise <Process> Listen(string gameDataPath, string lockFilePath, int port, bool shadowCopy = true, Action <string, float> progressCallback = null)
        {
            if (string.IsNullOrEmpty(gameDataPath))
            {
                throw new ArgumentException("Value cannot be null or empty.", "gameDataPath");
            }
            if (string.IsNullOrEmpty(lockFilePath))
            {
                throw new ArgumentException("Value cannot be null or empty.", "lockFilePath");
            }
            if (port <= 0 || port > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            var charonPath = Path.GetFullPath(Settings.CharonExecutablePath);

            if (File.Exists(gameDataPath) == false)
            {
                throw new IOException(string.Format("File '{0}' doesn't exists.", gameDataPath));
            }
            if (File.Exists(charonPath) == false)
            {
                throw new IOException(string.Format("File '{0}' doesn't exists.", charonPath));
            }

            if (shadowCopy)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_WINDOW_EDITOR_COPYING_EXECUTABLE, 0.10f);
                }

                var charonMd5       = FileAndPathUtils.ComputeHash(charonPath);
                var shadowDirectory = Path.GetFullPath(Path.Combine(Settings.TempPath, charonMd5));
                if (Directory.Exists(shadowDirectory) == false)
                {
                    if (Settings.Current.Verbose)
                    {
                        Debug.Log("Making shadow copy of '" + Path.GetFileName(charonPath) + "' to '" + shadowDirectory + "'.");
                    }

                    Directory.CreateDirectory(shadowDirectory);

                    var shadowCharonPath = Path.Combine(shadowDirectory, Path.GetFileName(charonPath));
                    File.Copy(charonPath, shadowCharonPath, overwrite: true);

                    var configPath       = charonPath + ".config";
                    var configShadowPath = shadowCharonPath + ".config";
                    if (File.Exists(configPath))
                    {
                        if (Settings.Current.Verbose)
                        {
                            Debug.Log("Making shadow copy of '" + Path.GetFileName(configPath) + "' to '" + shadowDirectory + "'.");
                        }

                        File.Copy(configPath, configShadowPath);
                    }
                    else
                    {
                        Debug.LogWarning("Missing required configuration file at '" + configPath + "'.");
                    }

                    charonPath = shadowCharonPath;
                }
                else
                {
                    charonPath = Path.Combine(shadowDirectory, Path.GetFileName(charonPath));
                }
            }
            if (progressCallback != null)
            {
                progressCallback(Resources.UI_UNITYPLUGIN_WINDOW_EDITOR_LAUNCHING_EXECUTABLE, 0.30f);
            }
            var unityPid            = Process.GetCurrentProcess().Id;
            var scriptingAssemblies = FindAndLoadScriptingAssemblies(gameDataPath);
            var runTask             = CommandLine.Run(
                new RunOptions
                (
                    charonPath,

                    RunOptions.FlattenArguments(
                        "SERVE", Path.GetFullPath(gameDataPath),
                        "--port", port.ToString(),
                        "--watchPid", unityPid.ToString(),
                        "--lockFile", Path.GetFullPath(lockFilePath),
                        "--environment", "Unity",
                        "--extensions", Settings.SupportedExtensions,
                        "--scriptAssemblies", scriptingAssemblies,
                        Settings.Current.Verbose ? "--verbose" : ""
                        )
                )
            {
                RequireDotNetRuntime  = true,
                CaptureStandardError  = false,
                CaptureStandardOutput = false,
                ExecutionTimeout      = TimeSpan.Zero,
                WaitForExit           = false,
                StartInfo             =
                {
                    EnvironmentVariables =
                    {
                        { "CHARON_APP_DATA", Settings.GetLocalUserDataPath() },
                        { "CHARON_SERVER",   Settings.Current.ServerAddress  }
                    }
                }
            }
                );

            if (progressCallback != null)
            {
                runTask.ContinueWith(_ => progressCallback(Resources.UI_UNITYPLUGIN_WINDOW_EDITOR_LAUNCHING_EXECUTABLE, 1.0f));
            }

            return(runTask.ContinueWith(t => t.GetResult().Process));
        }
Beispiel #6
0
 public static void RegenerateSDKProjects()
 {
     RegenerateEverything(unityProjectInfo = new UnityProjectInfo(Debug.unityLogger, SupportedBuildTargets, Config, performCompleteParse: true), completeGeneration: true);
     Debug.Log($"{nameof(RegenerateSDKProjects)} Completed Succesfully.");
 }
Beispiel #7
0
        internal static void InjectionAssembliesScan(bool forced)
        {
            if (!IsInjectionDetectorTargetCompatible() && !forced)
            {
                InjectionDetectorTargetCompatibleCheck();
                return;
            }

#if (ACTK_DEBUG || ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            Stopwatch sw = Stopwatch.StartNew();
#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Injection Detector Assemblies Scan\n");
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Paths:\n" +

                      "Assets: " + ActEditorGlobalStuff.ASSETS_PATH + "\n" +
                      "Assemblies: " + ActEditorGlobalStuff.ASSEMBLIES_PATH + "\n" +
                      "Injection Detector Data: " + ActEditorGlobalStuff.INJECTION_DATA_PATH);
            sw.Start();
#endif
#endif

#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Looking for all assemblies in current project...");
            sw.Start();
#endif
            allLibraries.Clear();
            allowedAssemblies.Clear();

            allLibraries.AddRange(ActEditorGlobalStuff.FindLibrariesAt(ActEditorGlobalStuff.assetsPath));
            allLibraries.AddRange(ActEditorGlobalStuff.FindLibrariesAt(ActEditorGlobalStuff.assembliesPath));
#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Total libraries found: " + allLibraries.Count);
            sw.Start();
#endif
            const string editorSubdir            = "/editor/";
            var          assembliesPathLowerCase = ActEditorGlobalStuff.AssembliesPathRelative.ToLower();
            foreach (var libraryPath in allLibraries)
            {
                var libraryPathLowerCase = libraryPath.ToLower();
#if (ACTK_DEBUG_PARANIOD)
                sw.Stop();
                Debug.Log(ActEditorGlobalStuff.LogPrefix + "Checking library at the path: " + libraryPathLowerCase);
                sw.Start();
#endif
                if (libraryPathLowerCase.Contains(editorSubdir))
                {
                    continue;
                }
                if (libraryPathLowerCase.Contains("-editor.dll") && libraryPathLowerCase.Contains(assembliesPathLowerCase))
                {
                    continue;
                }

                try
                {
                    var assName = AssemblyName.GetAssemblyName(libraryPath);
                    var name    = assName.Name;
                    var hash    = ActEditorGlobalStuff.GetAssemblyHash(assName);

                    var allowed = allowedAssemblies.FirstOrDefault(allowedAssembly => allowedAssembly.name == name);

                    if (allowed != null)
                    {
                        allowed.AddHash(hash);
                    }
                    else
                    {
                        allowed = new AllowedAssembly(name, new[] { hash });
                        allowedAssemblies.Add(allowed);
                    }
                }
                catch
                {
                    // not a valid IL assembly, skipping
                }
            }

#if (ACTK_DEBUG || ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            string trace = ActEditorGlobalStuff.LogPrefix + "Found assemblies (" + allowedAssemblies.Count + "):\n";

            foreach (AllowedAssembly allowedAssembly in allowedAssemblies)
            {
                trace += "  Name: " + allowedAssembly.name + "\n";
                trace  = allowedAssembly.hashes.Aggregate(trace, (current, hash) => current + ("    Hash: " + hash + "\n"));
            }

            Debug.Log(trace);
            sw.Start();
#endif
            if (!Directory.Exists(ActEditorGlobalStuff.resourcesPath))
            {
#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
                sw.Stop();
                Debug.Log(ActEditorGlobalStuff.LogPrefix + "Creating resources folder: " + ActEditorGlobalStuff.RESOURCES_PATH);
                sw.Start();
#endif
                Directory.CreateDirectory(ActEditorGlobalStuff.resourcesPath);
            }

            ActEditorGlobalStuff.RemoveReadOnlyAttribute(ActEditorGlobalStuff.injectionDataPath);
            var bw = new BinaryWriter(new FileStream(ActEditorGlobalStuff.injectionDataPath, FileMode.Create, FileAccess.Write, FileShare.Read));
            var allowedAssembliesCount = allowedAssemblies.Count;

            int totalWhitelistedAssemblies;

#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Processing default whitelist");
            sw.Start();
#endif

            var defaultWhitelistPath = ActEditorGlobalStuff.ResolveInjectionDefaultWhitelistPath();
            if (File.Exists(defaultWhitelistPath))
            {
                var br = new BinaryReader(new FileStream(defaultWhitelistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                var assembliesCount = br.ReadInt32();
                totalWhitelistedAssemblies = assembliesCount + allowedAssembliesCount;

                bw.Write(totalWhitelistedAssemblies);

                for (var i = 0; i < assembliesCount; i++)
                {
                    bw.Write(br.ReadString());
                }
                br.Close();
            }
            else
            {
#if (ACTK_DEBUG || ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
                sw.Stop();
#endif
                bw.Close();
                Debug.LogError(ActEditorGlobalStuff.LogPrefix + "Can't find " + ActEditorGlobalStuff.InjectionDefaultWhitelistFile + " file!\nPlease, report to " + ActEditorGlobalStuff.ReportEmail);
                return;
            }

#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Processing user whitelist");
            sw.Start();
#endif

            var userWhitelistPath = ActEditorGlobalStuff.ResolveInjectionUserWhitelistPath();
            if (File.Exists(userWhitelistPath))
            {
                var br = new BinaryReader(new FileStream(userWhitelistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                var assembliesCount = br.ReadInt32();

                bw.Seek(0, SeekOrigin.Begin);
                bw.Write(totalWhitelistedAssemblies + assembliesCount);
                bw.Seek(0, SeekOrigin.End);
                for (var i = 0; i < assembliesCount; i++)
                {
                    bw.Write(br.ReadString());
                }
                br.Close();
            }

#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Processing project assemblies");
            sw.Start();
#endif

            for (var i = 0; i < allowedAssembliesCount; i++)
            {
                var assembly = allowedAssemblies[i];
                var name     = assembly.name;
                var hashes   = "";

                for (var j = 0; j < assembly.hashes.Length; j++)
                {
                    hashes += assembly.hashes[j];
                    if (j < assembly.hashes.Length - 1)
                    {
                        hashes += ActEditorGlobalStuff.InjectionDataSeparator;
                    }
                }

                var line = ObscuredString.EncryptDecrypt(name + ActEditorGlobalStuff.InjectionDataSeparator + hashes, "Elina");

#if (ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
                Debug.Log(ActEditorGlobalStuff.LogPrefix + "Writing assembly:\n" + name + ActEditorGlobalStuff.INJECTION_DATA_SEPARATOR + hashes);
#endif
                bw.Write(line);
            }

            bw.Close();
#if (ACTK_DEBUG || ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD)
            sw.Stop();
            Debug.Log(ActEditorGlobalStuff.LogPrefix + "Assemblies scan duration: " + sw.ElapsedMilliseconds + " ms.");
#endif

            if (allowedAssembliesCount == 0)
            {
                Debug.LogError(ActEditorGlobalStuff.LogPrefix + "Can't find any assemblies!\nPlease, report to " + ActEditorGlobalStuff.ReportEmail);
            }

            AssetDatabase.Refresh();
            //EditorApplication.UnlockReloadAssemblies();
        }
 public static void Orange(this object t)
 {
     Debug.Log(string.Format("<color=orange>{0}</color>", t));
 }
 public static void Magenta(this object t)
 {
     Debug.Log(string.Format("<color=magenta>{0}</color>", t));
 }
 public static void Cyan(this object t)
 {
     Debug.Log(string.Format("<color=cyan>{0}</color>", t));
 }
 public static void Yellow(this object t)
 {
     Debug.Log(string.Format("<color=yellow>{0}</color>", t));
 }
 public static void Green(this object t)
 {
     Debug.Log(string.Format("<color=green>{0}</color>", t));
 }
Beispiel #13
0
 public void Debug(string message) => UnityDebug.Log(message);
Beispiel #14
0
 public void Debug(string message, Exception e) => UnityDebug.Log($"{message}: {e.StackTrace}");
Beispiel #15
0
 public void OnExit()
 {
     Debug.Log("Idle: Exited");
 }
 public static void Blue(this object t)
 {
     Debug.Log(string.Format("<color=blue>{0}</color>", t));
 }
Beispiel #17
0
 public void Tick()
 {
     Debug.Log("Idle: Tick() called.");
 }
 public static void Red(this object t)
 {
     Debug.Log(string.Format("<color=red>{0}</color>", t));
 }
Beispiel #19
0
        private static void RegenerateEverything(UnityProjectInfo unityProjectInfo, bool completeGeneration)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            long postCleanupAndCopyStamp = 0, solutionExportStart = 0, solutionExportEnd = 0, exporterStart = 0, exporterEnd = 0, propsFileGenerationStart = 0, propsFileGenerationEnd = 0;

            try
            {
                if (Directory.Exists(Utilities.MSBuildProjectFolder))
                {
                    // Create a copy of the packages as they might change after we create the MSBuild project
                    foreach (string file in Directory.EnumerateFiles(Utilities.MSBuildProjectFolder, "*", SearchOption.TopDirectoryOnly))
                    {
                        File.SetAttributes(file, FileAttributes.Normal);
                        File.Delete(file);
                    }
                }
                else
                {
                    Directory.CreateDirectory(Utilities.MSBuildProjectFolder);
                }

                postCleanupAndCopyStamp = stopwatch.ElapsedMilliseconds;

                propsFileGenerationStart = stopwatch.ElapsedMilliseconds;
                MSBuildUnityProjectExporter.ExportCommonPropsFile(Exporter, MSBuildForUnityVersion, unityProjectInfo.CurrentPlayerPlatform);
                if (completeGeneration)
                {
                    ExportCoreUnityPropFiles(unityProjectInfo);
                }
                propsFileGenerationEnd = stopwatch.ElapsedMilliseconds;

                solutionExportStart = stopwatch.ElapsedMilliseconds;
                if (completeGeneration)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(Utilities.MSBuildProjectFolder);
                    unityProjectInfo.ExportSolution(Exporter, new FileInfo(Exporter.GetSolutionFilePath(unityProjectInfo)), directoryInfo);
                    unityProjectInfo.ExportProjects(Exporter, directoryInfo);
                }
                MSBuildUnityProjectExporter.ExportTopLevelDependenciesProject(Exporter, MSBuildForUnityVersion, Config, new DirectoryInfo(Utilities.MSBuildProjectFolder), unityProjectInfo);
                solutionExportEnd = stopwatch.ElapsedMilliseconds;


                string nuGetConfigPath = Path.Combine(Utilities.AssetPath, Path.GetFileNameWithoutExtension(TemplateFiles.Instance.NuGetConfigPath));

                // Copy the NuGet.config file if it does not exist
                if (!File.Exists(nuGetConfigPath))
                {
                    File.Copy(TemplateFiles.Instance.NuGetConfigPath, nuGetConfigPath);
                }

                foreach (string otherFile in TemplateFiles.Instance.OtherFiles)
                {
                    File.Copy(otherFile, Path.Combine(Utilities.MSBuildProjectFolder, Path.GetFileName(otherFile)));
                }

                if (completeGeneration)
                {
                    string buildProjectsFile = "BuildProjects.proj";
                    if (!File.Exists(Path.Combine(Utilities.MSBuildOutputFolder, buildProjectsFile)))
                    {
                        GenerateBuildProjectsFile(buildProjectsFile, Exporter.GetSolutionFilePath(unityProjectInfo), unityProjectInfo.AvailablePlatforms);
                    }
                }
            }
            finally
            {
                stopwatch.Stop();
                Debug.Log($"Whole Generate Projects process took {stopwatch.ElapsedMilliseconds} ms; actual generation took {stopwatch.ElapsedMilliseconds - postCleanupAndCopyStamp}; solution export: {solutionExportEnd - solutionExportStart}; exporter creation: {exporterEnd - exporterStart}; props file generation: {propsFileGenerationEnd - propsFileGenerationStart}");
            }
        }
        private void DoTest()
        {
            var amount = PerformanceComparisonConfig.ObjectCount;
            var world  = new BVHTreeWorld(amount, Allocator.Persistent);

            Random.InitState(0);
            var colliders  = new NativeArray <Collider>(amount, Allocator.TempJob);
            var transforms = new NativeArray <RigidTransform>(amount, Allocator.TempJob);

            for (int i = 0; i < PerformanceComparisonConfig.ObjectCount; i++)
            {
                colliders[i]  = BoxCollider.Create(float3.zero, PerformanceComparisonConfig.GetRandomSize());
                transforms[i] = new RigidTransform(quaternion.identity, PerformanceComparisonConfig.GetRandomPosition());
            }


            var s = Stopwatch.StartNew();

            Profiler.BeginSample("broad");
            new BVHTreeWorld.InsertCollidersAndTransformsJob {
                Tree       = world.tree,
                Bodies     = world.bodies,
                Colliders  = colliders,
                Transforms = transforms
            }.Run();
            Profiler.EndSample();
            if (enableLog)
            {
                Debug.Log("Building broad phase took: " + s.Elapsed.TotalMilliseconds);
            }

            var rayResult = new NativeList <int>(64, Allocator.TempJob);

            var start = PerformanceComparisonConfig.RayStart;
            var end   = PerformanceComparisonConfig.RayEnd;

            var rayJob = new RayJob {
                Tree     = world.tree,
                RayInput = new NativeBVHTree.Ray {
                    origin      = start,
                    direction   = math.normalize(end - start),
                    maxDistance = math.distance(start, end),
                },
                Results = rayResult
            };

            s.Restart();
            rayJob.Run();
            if (enableLog)
            {
                Debug.Log("Raycasts took: " + s.Elapsed.TotalMilliseconds + " results: " + rayResult.Length);
            }

            s.Restart();
            world.Update();
            if (enableLog)
            {
                Debug.Log("Building broad phase again after no changes took: " + s.Elapsed.TotalMilliseconds);
            }

            for (int i = 0; i < 100; i++)
            {
                int randomIndex = Random.Range(1, PerformanceComparisonConfig.ObjectCount);
                world.UpdateTransform(randomIndex, new RigidTransform(quaternion.identity, PerformanceComparisonConfig.GetRandomPosition()));
            }
            s.Restart();
            world.Update();
            if (enableLog)
            {
                Debug.Log("Building broad phase again after some changes took: " + s.Elapsed.TotalMilliseconds);
            }
        }
Beispiel #21
0
        internal static void FindAndEndGracefully(string lockFilePath = null)
        {
            if (string.IsNullOrEmpty(lockFilePath))
            {
                lockFilePath = GetDefaultLockFilePath();
            }

            if (File.Exists(lockFilePath) == false)
            {
                return;
            }

            var pidStr = default(string);

            using (var lockFileStream = new FileStream(lockFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1024, FileOptions.SequentialScan))
                pidStr = new StreamReader(lockFileStream, detectEncodingFromByteOrderMarks: true).ReadToEnd();

            var pid = 0;

            if (string.IsNullOrEmpty(pidStr) || int.TryParse(pidStr, out pid) == false)
            {
                return;
            }

            var stopError = default(Exception);

            try
            {
                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("Trying to end process with id {0}.", pidStr));
                }

                using (var process = Process.GetProcessById(pid))
                    process.EndGracefully();

                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("Successfully ended process with id {0}.", pidStr));
                }
            }
            catch (Exception endError)
            {
                stopError = endError;
                if (Settings.Current.Verbose)
                {
                    Debug.LogWarning(string.Format("Failed to get process by id {0}.\r\n{1}", pidStr, endError));
                }
            }

            try
            {
                if (File.Exists(lockFilePath))
                {
                    File.Delete(lockFilePath);
                }
            }
            catch (Exception lockDeleteError)
            {
                stopError = stopError ?? lockDeleteError;
                Debug.LogWarning(string.Format("Failed to stop running process with id {0}.\r\n{1}", pidStr, stopError));
                throw stopError;
            }
        }
Beispiel #22
0
 public override void Write(string Message, string Category)
 {
     Debug.Log("T:" + Category + ": " + Message);
 }
Beispiel #23
0
        public static void RunProcess(string filename, string arguments, int timeout)
        {
            using (Process process = new Process())
            {
                process.StartInfo.FileName               = filename;
                process.StartInfo.Arguments              = arguments;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;

                StringBuilder output = new StringBuilder();
                StringBuilder error  = new StringBuilder();

                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                    {
                        process.OutputDataReceived += (sender, e) => {
                            if (e.Data == null)
                            {
                                outputWaitHandle.Set();
                            }
                            else
                            {
                                output.AppendLine(e.Data);
                            }
                        };
                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                errorWaitHandle.Set();
                            }
                            else
                            {
                                error.AppendLine(e.Data);
                            }
                        };

                        process.Start();

                        Debug.Log("Start Run " + filename + " arguments =" + arguments);

                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();

                        if (process.WaitForExit(timeout) &&
                            outputWaitHandle.WaitOne(timeout) &&
                            errorWaitHandle.WaitOne(timeout) && process.ExitCode == 0)
                        {
                            Debug.Log("Finished ExitCode " + process.ExitCode + " Run " + filename + " arguments =" + arguments);
                        }
                        else if (process.ExitCode != 0)
                        {
                            throw new Exception("Run " + filename + " arguments= " + arguments + " Exit Error :" + process.ExitCode);
                        }
                        else
                        {
                            throw new Exception("Run " + filename + " arguments= " + arguments + " Time Out");
                        }
                    }
            }
        }
Beispiel #24
0
 public static void Info(string rMsg)
 {
     Debug.Log(rMsg);
 }
Beispiel #25
0
        private static IEnumerable DownloadCharonAsync(Action <string, float> progressCallback = null)
        {
            var checkRequirements = CharonCli.CheckRequirementsAsync();

            yield return(checkRequirements);

            var checkResult = checkRequirements.GetResult();

            if (checkResult == RequirementsCheckResult.MissingRuntime)
            {
                yield return(UpdateRuntimeWindow.ShowAsync());
            }

            var currentVersion = default(SemanticVersion);
            var charonPath     = Path.GetFullPath(Settings.CharonExecutablePath);
            var toolName       = Path.GetFileNameWithoutExtension(Path.GetFileName(charonPath));

            if (File.Exists(charonPath))
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_CHECKING_TOOLS_VERSION, 0.05f);
                }

                var checkToolsVersion = CharonCli.GetVersionAsync();
                yield return(checkToolsVersion.IgnoreFault());

                currentVersion = checkToolsVersion.HasErrors ? default(SemanticVersion) : checkToolsVersion.GetResult();
            }

            if (progressCallback != null)
            {
                progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_GETTING_AVAILABLE_BUILDS, 0.10f);
            }

            var getBuildsAsync = PackageManager.GetVersions(ProductInformation.PRODUCT_CHARON);

            yield return(getBuildsAsync.IgnoreFault());

            if (getBuildsAsync.HasErrors)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                Debug.LogError(string.Format("Failed to get builds list from server. Error: {0}", getBuildsAsync.Error.Unwrap().Message));
                yield break;
            }

            var builds          = getBuildsAsync.GetResult();
            var buildsByVersion = builds.ToDictionary(b => b.Version);
            var lastBuild       = builds.OrderByDescending(b => b.Version).FirstOrDefault();

            if (lastBuild == null)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("No builds of {0} are available.", toolName));
                }
                yield break;
            }

            var currentBuild = currentVersion != null?builds.FirstOrDefault(b => b.Version == currentVersion) : null;

            var lastVersion     = lastBuild.Version;
            var isMissing       = File.Exists(charonPath);
            var hashFileName    = currentBuild == null ? null : Path.Combine(Path.Combine(Settings.ToolBasePath, currentVersion.ToString()), Path.GetFileName(charonPath) + ".sha1");
            var actualHash      = isMissing || currentBuild == null ? null : FileAndPathUtils.ComputeHash(charonPath, "SHA1");
            var expectedHash    = isMissing || hashFileName == null || File.Exists(hashFileName) == false ? null : File.ReadAllText(hashFileName);
            var isCorrupted     = currentBuild != null && string.Equals(expectedHash, actualHash, StringComparison.OrdinalIgnoreCase) == false;
            var expectedVersion = string.IsNullOrEmpty(Settings.Current.EditorVersion) ? default(SemanticVersion) : new SemanticVersion(Settings.Current.EditorVersion);

            if (!isMissing && !isCorrupted && expectedVersion == currentVersion && currentVersion != null)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("{0} version '{1}' is expected and file hash is matching.", toolName, currentVersion));
                }
                yield break;
            }

            var versionToDeploy = expectedVersion ?? lastVersion;

            if (buildsByVersion.ContainsKey(versionToDeploy) == false)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                Debug.LogError(string.Format("Package of {0} with version '{1}' is not available to download.", toolName, versionToDeploy));
                yield break;
            }

            if (progressCallback != null)
            {
                progressCallback(string.Format(Resources.UI_UNITYPLUGIN_PROGRESS_DOWNLOADING, 0, 0, ProductInformation.PRODUCT_CHARON), 0.10f);
            }

            var deployAction = new CharonDeploymentAction(versionToDeploy, progressCallback);
            var prepareAsync = deployAction.Prepare();

            yield return(prepareAsync.IgnoreFault());

            if (prepareAsync.HasErrors)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                Debug.LogError(string.Format("Failed to download package of {0} with version '{1}'.{2}{3}", toolName, versionToDeploy, Environment.NewLine, prepareAsync.Error.Unwrap()));

                deployAction.Complete();
                yield break;
            }

            var deployAsync = deployAction.Complete();

            yield return(deployAsync.IgnoreFault());

            if (deployAsync.HasErrors)
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
                }

                Debug.LogError(string.Format("Failed to deploy package of {0} with version '{1}'.{2}{3}", toolName, versionToDeploy, Environment.NewLine, deployAsync.Error.Unwrap()));

                deployAction.Complete();
                yield break;
            }

            // cleanup resources
            deployAction.Complete();

            if (File.Exists(charonPath))
            {
                if (progressCallback != null)
                {
                    progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_CHECKING_TOOLS_VERSION, 0.95f);
                }

                var checkToolsVersion = CharonCli.GetVersionAsync();
                yield return(checkToolsVersion.IgnoreFault());

                currentVersion = checkToolsVersion.HasErrors ? default(SemanticVersion) : checkToolsVersion.GetResult();
            }

            Settings.Current.EditorVersion = currentVersion != null?currentVersion.ToString() : null;

            Settings.Current.Save();

            Debug.Log(string.Format("{1} version is '{0}'. Update is completed.", currentVersion, Path.GetFileName(charonPath)));

            if (progressCallback != null)
            {
                progressCallback(Resources.UI_UNITYPLUGIN_PROGRESS_DONE, 1.0f);
            }
        }
Beispiel #26
0
        public static void Init()
        {
            if (ourInitialized)
            {
                return;
            }

            var projectDirectory = Directory.GetParent(Application.dataPath).FullName;
            var projectName      = Path.GetFileName(projectDirectory);

            SlnFile = Path.GetFullPath($"{projectName}.sln");

            InitializeEditorInstanceJson();

            var lifetimeDefinition = Lifetime.Define(Lifetime.Eternal);
            var lifetime           = lifetimeDefinition.Lifetime;

            AppDomain.CurrentDomain.DomainUnload += (EventHandler)((_, __) =>
            {
                ourLogger.Verbose("lifetimeDefinition.Terminate");
                lifetimeDefinition.Terminate();
            });

            if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.VERBOSE)
            {
                var location = Assembly.GetExecutingAssembly().Location;
                Debug.Log($"Rider plugin initialized{(string.IsNullOrEmpty(location)? "" : " from: " + location )}. LoggingLevel: {PluginSettings.SelectedLoggingLevel}. Change it in Unity Preferences -> Rider. Logs path: {LogPath}.");
            }

            var list = new List <ProtocolInstance>();

            CreateProtocolAndAdvise(lifetime, list, new DirectoryInfo(Directory.GetCurrentDirectory()).Name);

            // list all sln files in CurrentDirectory, except main one and create server protocol for each of them
            var currentDir    = new DirectoryInfo(Directory.GetCurrentDirectory());
            var solutionFiles = currentDir.GetFiles("*.sln", SearchOption.TopDirectoryOnly);

            foreach (var solutionFile in solutionFiles)
            {
                if (Path.GetFileNameWithoutExtension(solutionFile.FullName) != currentDir.Name)
                {
                    CreateProtocolAndAdvise(lifetime, list, Path.GetFileNameWithoutExtension(solutionFile.FullName));
                }
            }

            OpenAssetHandler = new OnOpenAssetHandler(ourRiderPathProvider, ourPluginSettings, SlnFile);
            ourLogger.Verbose("Writing Library/ProtocolInstance.json");
            var protocolInstanceJsonPath = Path.GetFullPath("Library/ProtocolInstance.json");

            File.WriteAllText(protocolInstanceJsonPath, ProtocolInstance.ToJson(list));

            AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
            {
                ourLogger.Verbose("Deleting Library/ProtocolInstance.json");
                File.Delete(protocolInstanceJsonPath);
            };

            PlayModeSavedState = GetPlayModeState();

            ourInitialized = true;
        }
Beispiel #27
0
        private static void Analize(List <List <Person> > tables, out List <List <Person> > worst, out List <List <Person> > best, out int max, out int complexity)
        {
            var combinations = new List <List <List <Person> > >();
            var boys         = tables.Select(p => p.Single(c => c.Male)).ToList();
            var girls        = tables.Select(p => p.Single(c => !c.Male)).ToList();

            if (Settings.Debug)
            {
                Dump(boys, girls);
            }

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            GetCombinations(boys, girls, ref combinations, new List <List <Person> >());

            Debug.Log("combinations.Count = " + combinations.Count);

            var  mins = new List <int>();
            var  maxs = new List <int>();
            var  min  = 999;
            long sum  = 0;

            max = complexity = 0;

            var sympathies = GetSympathies(boys, girls);

            for (var j = 0; j < combinations.Count; j++)
            {
                var s = 0;

                foreach (var table in combinations[j])
                {
                    var sympathy = sympathies[table[0]][table[1]];

                    s += sympathy;
                }

                if (s < min)
                {
                    min  = s;
                    mins = new List <int> {
                        j
                    };
                }
                else if (s == min)
                {
                    mins.Add(j);
                }

                if (s > max)
                {
                    max  = s;
                    maxs = new List <int> {
                        j
                    };
                }
                else if (s == max)
                {
                    maxs.Add(j);
                }

                sum += s;
            }

            var m = 0;

            foreach (var i in maxs)
            {
                foreach (var table in combinations[i])
                {
                    var sympathy = Table.GetSympathy(table[0], table[1]);

                    if (sympathy > m)
                    {
                        m = sympathy;
                    }
                }
            }

            foreach (var boy in boys)
            {
                foreach (var girl in girls)
                {
                    if (IsComplex(boy, girl, boys, girls, m, max, sympathies))
                    {
                        complexity++;
                    }
                }
            }

            worst = combinations[mins[CRandom.GetRandom(0, mins.Count)]];
            best  = combinations[maxs[CRandom.GetRandom(0, maxs.Count)]];

            stopWatch.Stop();

            Debug.Log(string.Format("min={0}, max={1}, avg={2}, minRate={3}, maxRate={4}, m={5} complexity={6}", min, max, (float)sum / combinations.Count, mins.Count, maxs.Count, m, complexity));
            Debug.Log("Analize: stopWatch.Elapsed=" + stopWatch.Elapsed.TotalSeconds);
        }
Beispiel #28
0
 public void OnEnter()
 {
     Debug.Log("Idle: Entered");
 }
Beispiel #29
0
        internal IEnumerator ProcessQueueElement(ModUpdateRequest modUpdateRequest)
        {
            Package pk;

            try { pk = Package.GetPackage(modUpdateRequest.packageName); }
            catch { yield break; }

            if ((pk.Versions == null) || pk.Versions.Length <= 0)
            {
                Debug.LogWarning(LOG + "Couldnt find versions for the package named '" + modUpdateRequest.packageName + "' in the package list. Update check will not be performed for that mod.");
                yield break;
            }
            else if (modUpdateRequest.currentVersion < pk.Versions[0].VersionNumber)
            {
                ModUpdateLog mul = new ModUpdateLog(modUpdateRequest.packageName, modUpdateRequest.currentVersion, pk.Versions[0].VersionNumber);

                if (ModUpdateLog.checkIfSimilarUpdateAlreadyProceed(mul))
                {
                    Debug.LogWarning(LOG + "Similar update already proceed last time. Maybe the modder forgot to change the version number ?");
                }
                else
                {
                    if (modUpdateRequest.flag.Equals(Flag.UpdateAlways))
                    {
                        yield return(StartPerformUpdate(modUpdateRequest, pk));
                    }
                    else if (modUpdateRequest.flag.Equals(Flag.UpdateIfSameDependencyOnlyElseWarnOnly))
                    {
                        bool sameDependencies;
                        try { sameDependencies = Package.EqualsDependecy(pk, modUpdateRequest.currentVersion); }
                        catch { yield break; }

                        if (!sameDependencies)
                        {
                            Debug.LogWarning(LOG + "An update for " + modUpdateRequest.packageName + " is available. Current version(" + modUpdateRequest.currentVersion.ToString() + "). Newest version (" + pk.Versions[0].VersionNumber.ToString() + ")."
                                             + System.Environment.NewLine + "However, the newest version uses a different dependency version. This mod specifie not to update automaticly in that case. Please go to " + pk.PackageUrl + " and update manually.");
                        }
                        else
                        {
                            yield return(StartPerformUpdate(modUpdateRequest, pk));
                        }
                    }
                    else if (modUpdateRequest.flag.Equals(Flag.UpdateIfSameDependencyOnlyElseWarnAndDeactivate))
                    {
                        if (Package.EqualsDependecy(pk, modUpdateRequest.currentVersion))
                        {
                            yield return(StartPerformUpdate(modUpdateRequest, pk));
                        }
                        else
                        {
                            Debug.LogWarning(LOG + "An update for " + modUpdateRequest.packageName + " is available. Current version(" + modUpdateRequest.currentVersion.ToString() + "). Newest version (" + pk.Versions[0].VersionNumber.ToString() + ")."
                                             + System.Environment.NewLine + "However, the newest version uses a different dependency version. This mod specifie not to update automaticly in that case and to deactivate the mod at the next game start. Please go to " + pk.PackageUrl + " and update manually.");

                            DeactivateMod(modUpdateRequest);
                        }
                    }
                    else if (modUpdateRequest.flag.Equals(Flag.WarnOnly))
                    {
                        Debug.LogWarning(LOG + "An update for " + modUpdateRequest.packageName + " is available. Current version(" + modUpdateRequest.currentVersion.ToString() + "). Newest version (" + pk.Versions[0].VersionNumber.ToString() + ")."
                                         + System.Environment.NewLine + "This mod specifie not to update automaticly. Please go to " + pk.PackageUrl + " and update manually.");
                    }
                    else if (modUpdateRequest.flag.Equals(Flag.WarnAndDeactivate))
                    {
                        Debug.LogWarning(LOG + "An update for " + modUpdateRequest.packageName + " is available. Current version(" + modUpdateRequest.currentVersion.ToString() + "). Newest version (" + pk.Versions[0].VersionNumber.ToString() + ")."
                                         + System.Environment.NewLine + "This mod specifie to deactivate the mod when you will close the game. Please go to " + pk.PackageUrl + " and reinstall manually.");
                        DeactivateMod(modUpdateRequest);
                    }
                }
                ModUpdateLog.logModUpdate(mul);
            }
            else if (pk.IsDeprecated)
            {
                Debug.LogWarning(LOG + pk.Name + "Has been flagged as deprecated. This means it doesnt work anymore. The mod will be deactivate when you will close the game except if you specified otherwise in the config file.");
                if (ConfigPerformDepreactedCheckAndRemove.Value)
                {
                    DeactivateMod(modUpdateRequest);
                }
            }
            else
            {
                Debug.Log(LOG + "The package (mod) named '" + modUpdateRequest.packageName + "' (" + modUpdateRequest.currentVersion.ToString() + ") is up to date.");
            }
        }
Beispiel #30
0
        /// <summary>
        /// 执行批处理命令
        /// </summary>
        /// <param name="command"></param>
        /// <param name="workingDirectory"></param>
        public static void ExecuteCommand(string command, string workingDirectory = null)
        {
            var fProgress = .1f;

            EditorUtility.DisplayProgressBar("KEditorUtils.ExecuteCommand", command, fProgress);

            try
            {
                string cmd;
                string preArg;
                var    os = Environment.OSVersion;

                Debug.Log(String.Format("[ExecuteCommand]Command on OS: {0}", os.ToString()));
                if (os.ToString().Contains("Windows"))
                {
                    cmd    = "cmd.exe";
                    preArg = "/C ";
                }
                else
                {
                    cmd    = "sh";
                    preArg = "-c ";
                }
                Debug.Log("[ExecuteCommand]" + command);
                var allOutput = new StringBuilder();
                using (var process = new Process())
                {
                    if (workingDirectory != null)
                    {
                        process.StartInfo.WorkingDirectory = workingDirectory;
                    }
                    process.StartInfo.FileName               = cmd;
                    process.StartInfo.Arguments              = preArg + "\"" + command + "\"";
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.Start();

                    while (true)
                    {
                        var line = process.StandardOutput.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        allOutput.AppendLine(line);
                        EditorUtility.DisplayProgressBar("[ExecuteCommand] " + command, line, fProgress);
                        fProgress += .001f;
                    }

                    var err = process.StandardError.ReadToEnd();
                    if (!String.IsNullOrEmpty(err))
                    {
                        Debug.LogError(String.Format("[ExecuteCommand] {0}", err));
                    }
                    process.WaitForExit();
                }
                Debug.Log("[ExecuteResult]" + allOutput);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }