示例#1
0
 public ABManifestLoader()
 {
     _manifestPath = PathTools.GetWWWPath() + "/" + PathTools.GetPlatfromName();
 }
示例#2
0
        private static Result CalculateMain(IAtomContainer container, int nhigh, int nlow)
        {
            var iso    = CDK.IsotopeFactory;
            int nheavy = 0;

            // find number of heavy atoms
            nheavy += container.Atoms.Count(atom => !atom.AtomicNumber.Equals(AtomicNumbers.H));
            if (nheavy == 0)
            {
                throw new CDKException("No heavy atoms in the container");
            }

            var diagvalue = new double[nheavy];

            // get atomic mass weighted BCUT
            try
            {
                var counter = 0;
                foreach (var atom in container.Atoms.Where(atom => !atom.AtomicNumber.Equals(AtomicNumbers.H)))
                {
                    diagvalue[counter] = iso.GetMajorIsotope(atom.AtomicNumber).ExactMass.Value;
                    counter++;
                }
            }
            catch (Exception e)
            {
                throw new CDKException($"Could not calculate weight: {e.Message}", e);
            }

            double[] eval1, eval2, eval3;
            {
                var burdenMatrix = BurdenMatrix.EvalMatrix(container, diagvalue);
                if (HasUndefined(burdenMatrix))
                {
                    throw new CDKException("Burden matrix has undefined values");
                }
                var matrix = Matrix <double> .Build.DenseOfColumnArrays(burdenMatrix);

                var eigenDecomposition = matrix.Evd().EigenValues;
                eval1 = eigenDecomposition.Select(n => n.Real).ToArray();
            }
            try
            {
                // get charge weighted BCUT
                CDK.LonePairElectronChecker.Saturate(container);
                var charges = new double[container.Atoms.Count];
                var peoe    = new GasteigerMarsiliPartialCharges();
                peoe.AssignGasteigerMarsiliSigmaPartialCharges(container, true);
                for (int i = 0; i < container.Atoms.Count; i++)
                {
                    charges[i] += container.Atoms[i].Charge.Value;
                }
                for (int i = 0; i < container.Atoms.Count; i++)
                {
                    container.Atoms[i].Charge = charges[i];
                }
            }
            catch (Exception e)
            {
                throw new CDKException("Could not calculate partial charges: " + e.Message, e);
            }
            {
                var counter = 0;
                foreach (var atom in container.Atoms.Where(atom => !atom.AtomicNumber.Equals(AtomicNumbers.H)))
                {
                    diagvalue[counter++] = atom.Charge.Value;
                }
            }
            {
                var burdenMatrix = BurdenMatrix.EvalMatrix(container, diagvalue);
                if (HasUndefined(burdenMatrix))
                {
                    throw new CDKException("Burden matrix has undefined values");
                }
                var matrix = Matrix <double> .Build.DenseOfColumnArrays(burdenMatrix);

                var eigenDecomposition = matrix.Evd().EigenValues;
                eval2 = eigenDecomposition.Select(n => n.Real).ToArray();
            }

            var topoDistance = PathTools.ComputeFloydAPSP(AdjacencyMatrix.GetMatrix(container));

            // get polarizability weighted BCUT
            {
                var counter = 0;
                foreach (var atom in container.Atoms.Where(atom => !atom.AtomicNumber.Equals(AtomicNumbers.H)))
                {
                    diagvalue[counter++] = Polarizability.CalculateGHEffectiveAtomPolarizability(container, atom, false, topoDistance);
                }
            }
            {
                var burdenMatrix = BurdenMatrix.EvalMatrix(container, diagvalue);
                if (HasUndefined(burdenMatrix))
                {
                    throw new CDKException("Burden matrix has undefined values");
                }
                var matrix = Matrix <double> .Build.DenseOfColumnArrays(burdenMatrix);

                var eigenDecomposition = matrix.Evd().EigenValues;
                eval3 = eigenDecomposition.Select(n => n.Real).ToArray();
            }

            // return only the n highest & lowest eigenvalues
            int lnlow, lnhigh, enlow, enhigh;

            if (nlow > nheavy)
            {
                lnlow = nheavy;
                enlow = nlow - nheavy;
            }
            else
            {
                lnlow = nlow;
                enlow = 0;
            }

            if (nhigh > nheavy)
            {
                lnhigh = nheavy;
                enhigh = nhigh - nheavy;
            }
            else
            {
                lnhigh = nhigh;
                enhigh = 0;
            }

            var retval = new List <double>((lnlow + enlow + lnhigh + enhigh) * 3);

            for (int i = 0; i < lnlow; i++)
            {
                retval.Add(eval1[i]);
            }
            for (int i = 0; i < enlow; i++)
            {
                retval.Add(double.NaN);
            }
            for (int i = 0; i < lnhigh; i++)
            {
                retval.Add(eval1[eval1.Length - i - 1]);
            }
            for (int i = 0; i < enhigh; i++)
            {
                retval.Add(double.NaN);
            }

            for (int i = 0; i < lnlow; i++)
            {
                retval.Add(eval2[i]);
            }
            for (int i = 0; i < enlow; i++)
            {
                retval.Add(double.NaN);
            }
            for (int i = 0; i < lnhigh; i++)
            {
                retval.Add(eval2[eval2.Length - i - 1]);
            }
            for (int i = 0; i < enhigh; i++)
            {
                retval.Add(double.NaN);
            }

            for (int i = 0; i < lnlow; i++)
            {
                retval.Add(eval3[i]);
            }
            for (int i = 0; i < enlow; i++)
            {
                retval.Add(double.NaN);
            }
            for (int i = 0; i < lnhigh; i++)
            {
                retval.Add(eval3[eval3.Length - i - 1]);
            }
            for (int i = 0; i < enhigh; i++)
            {
                retval.Add(double.NaN);
            }

            return(new Result(retval, nhigh, nlow));
        }
示例#3
0
        public static SideloaderModInfo LoadFromFile(string filename)
        {
            var location = new FileInfo(filename);

            if (!IsValidZipmodExtension(location.Extension))
            {
                throw new ArgumentException($"The file {filename} has an invalid extension and can't be a zipmod", nameof(filename));
            }

            using (var zf = SharpCompress.Archives.ArchiveFactory.Open(location))
            {
                var manifestEntry = zf.Entries.FirstOrDefault(x => PathTools.PathsEqual(x.Key, "manifest.xml"));

                if (manifestEntry == null)
                {
                    if (zf.Entries.Any(x => x.IsDirectory && PathTools.PathsEqual(x.Key, "abdata")))
                    {
                        throw new NotSupportedException("The file is a hardmod and cannot be installed automatically. It's recommeded to look for a sideloader version.");
                    }

                    throw new InvalidDataException("manifest.xml was not found in the mod archive. Make sure this is a zipmod.");
                }

                using (var fileStream = manifestEntry.OpenEntryStream())
                {
                    var manifest = XDocument.Load(fileStream, LoadOptions.None);

                    if (manifest.Root?.Element("guid")?.IsEmpty != false)
                    {
                        throw new InvalidDataException("The manifest.xml file is in an invalid format");
                    }

                    var guid        = manifest.Root.Element("guid")?.Value;
                    var version     = manifest.Root.Element("version")?.Value;
                    var name        = manifest.Root.Element("name")?.Value ?? location.Name;
                    var author      = manifest.Root.Element("author")?.Value;
                    var description = manifest.Root.Element("description")?.Value;
                    var website     = manifest.Root.Element("website")?.Value;

                    var images = new List <Image>();
                    // TODO load from drive instead of caching to ram
                    foreach (var imageFile in zf.Entries
                             .Where(x => ".jpg".Equals(Path.GetExtension(x.Key), StringComparison.OrdinalIgnoreCase) ||
                                    ".png".Equals(Path.GetExtension(x.Key), StringComparison.OrdinalIgnoreCase))
                             .OrderBy(x => x.Key).Take(3))
                    {
                        try
                        {
                            using (var stream = imageFile.OpenEntryStream())
                                using (var img = Image.FromStream(stream))
                                {
                                    images.Add(img.GetThumbnailImage(200, 200, null, IntPtr.Zero));
                                }
                        }
                        catch (SystemException ex)
                        {
                            Console.WriteLine($"Failed to load image \"{imageFile.Key}\" from mod archive \"{location.Name}\" with error: {ex.Message}");
                        }
                    }

                    var contents = zf.Entries.Where(x => !x.IsDirectory).Select(x => x.Key.Replace('/', '\\')).ToList();

                    return(new SideloaderModInfo(location, guid, name, version, author, description, website, images, contents));
                }
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            string outputDir = Path.GetFullPath(@"..\..\Output");
            string dataDir   = Path.GetFullPath(@"..\..\data");

            Directory.CreateDirectory(outputDir);
            string mbedRoot = Path.Combine(outputDir, "mbed");

            List <KeyValuePair <Regex, string> > nameRules = new List <KeyValuePair <Regex, string> >();

            foreach (var line in File.ReadAllLines(Path.Combine(dataDir, "DeviceNameRules.txt")))
            {
                int idx = line.IndexOf('=');
                nameRules.Add(new KeyValuePair <Regex, string>(new Regex(line.Substring(0, idx).Trim()), line.Substring(idx + 1).Trim()));
            }

            bool regenerate = true;

            if (regenerate)
            {
                string gitExe    = (Registry.CurrentUser.OpenSubKey(@"Software\Sysprogs\BSPGenerators")?.GetValue("git") as string) ?? "git.exe";
                string pythonExe = (Registry.CurrentUser.OpenSubKey(@"Software\Sysprogs\BSPGenerators")?.GetValue("python") as string) ?? "python.exe";

                Process proc;
                if (Directory.Exists(mbedRoot))
                {
                    // Prevent pull fail due to modified files
                    proc = Process.Start(new ProcessStartInfo(gitExe, "reset --hard")
                    {
                        WorkingDirectory = mbedRoot, UseShellExecute = false
                    });
                    proc.WaitForExit();
                    if (proc.ExitCode != 0)
                    {
                        throw new Exception("Git reset command exited with code " + proc.ExitCode);
                    }
                    proc = Process.Start(new ProcessStartInfo(gitExe, "pull origin fix_5.2")
                    {
                        WorkingDirectory = mbedRoot, UseShellExecute = false
                    });
                }
                else
                {
                    proc = Process.Start(new ProcessStartInfo(gitExe, "clone https://github.com/oter/mbed-os.git -b fix_5.2 mbed")
                    {
                        WorkingDirectory = outputDir, UseShellExecute = false
                    });
                }
                proc.WaitForExit();
                if (proc.ExitCode != 0)
                {
                    throw new Exception("Git exited with code " + proc.ExitCode);
                }

                string sampleDir = Path.Combine(mbedRoot, "samples");
                if (Directory.Exists(sampleDir))
                {
                    Directory.Delete(sampleDir, true);
                }
                PathTools.CopyDirectoryRecursive(Path.Combine(dataDir, "samples"), sampleDir);

                ProcessStartInfo bspGenInfo = new ProcessStartInfo(pythonExe, Path.Combine(dataDir, "visualgdb_bsp.py") + " --alltargets");
                bspGenInfo.UseShellExecute = false;
                bspGenInfo.EnvironmentVariables["PYTHONPATH"] = mbedRoot;
                proc = Process.Start(bspGenInfo);
                proc.WaitForExit();

                if (proc.ExitCode != 0)
                {
                    throw new Exception("BSP generator exited with code " + proc.ExitCode);
                }
            }

            File.Copy(Path.Combine(dataDir, "stubs.cpp"), Path.Combine(mbedRoot, "stubs.cpp"), true);
            Dictionary <string, string> mcuDefs = new Dictionary <string, string>();
            var linkedBSPs = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\VisualGDB\EmbeddedBSPs\arm-eabi", "*.bsplink").Select(f => File.ReadAllText(f));

            foreach (var dir in Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\VisualGDB\EmbeddedBSPs\arm-eabi").Concat(linkedBSPs))
            {
                var anotherBSP = XmlTools.LoadObject <BoardSupportPackage>(Path.Combine(dir, "bsp.xml"));
                foreach (var mcu in anotherBSP.SupportedMCUs)
                {
                    if (mcu.MCUDefinitionFile != null)
                    {
                        mcuDefs[mcu.ID] = Path.Combine(dir, mcu.MCUDefinitionFile);
                    }
                }
            }

            string bspFile = Path.Combine(mbedRoot, "BSP.xml");
            var    bsp     = XmlTools.LoadObject <BoardSupportPackage>(bspFile);
            var    defDir  = Directory.CreateDirectory(Path.Combine(mbedRoot, "DeviceDefinitions"));

            foreach (var mcu in bsp.SupportedMCUs)
            {
                foreach (var rule in nameRules)
                {
                    var m = rule.Key.Match(mcu.ID);
                    if (m.Success)
                    {
                        string devRegex = rule.Value;
                        for (int i = 1; i < m.Groups.Count; i++)
                        {
                            devRegex = devRegex.Replace(@"\" + i, m.Groups[i].Value);
                        }

                        Regex  devRegexObj = new Regex(devRegex);
                        string definition  = null;
                        foreach (var dev in mcuDefs)
                        {
                            if (devRegexObj.IsMatch(dev.Key))
                            {
                                definition = dev.Value;
                            }
                        }

                        if (definition == null)
                        {
                            Console.WriteLine("Warning: cannot find device register definition for " + devRegex);
                        }
                        else
                        {
                            mcu.MCUDefinitionFile = "DeviceDefinitions/" + Path.GetFileName(definition);
                            File.Copy(definition + ".gz", Path.Combine(mbedRoot, mcu.MCUDefinitionFile + ".gz"), true);
                        }
                        break;
                    }
                }
            }
            ProduceBSPArchive(mbedRoot, bsp);

            var  testfFiles   = new TestInfo[] { new TestInfo("test_usbcd.xml", 0, 0), new TestInfo("test_ledblink_rtos.xml", 0, 0), new TestInfo("test_ledblink.xml", 0, 0), };
            bool performTests = true;

            if (performTests)
            {
                foreach (var test in testfFiles)
                {
                    Console.WriteLine("Testing BSP...");
                    var job = XmlTools.LoadObject <TestJob>(Path.Combine(dataDir, test.Filename));
                    if (job.ToolchainPath.StartsWith("["))
                    {
                        job.ToolchainPath = (string)Registry.CurrentUser.OpenSubKey(@"Software\Sysprogs\GNUToolchains").GetValue(job.ToolchainPath.Trim('[', ']'));
                        if (job.ToolchainPath == null)
                        {
                            throw new Exception("Cannot locate toolchain path from registry");
                        }
                    }
                    var toolchain = LoadedToolchain.Load(Environment.ExpandEnvironmentVariables(job.ToolchainPath), new ToolchainRelocationManager());
                    var lbsp      = LoadedBSP.Load(new BSPManager.BSPSummary(Environment.ExpandEnvironmentVariables(Path.Combine(outputDir, "mbed"))), toolchain);
                    var r         = StandaloneBSPValidator.Program.TestBSP(job, lbsp, Path.Combine(outputDir, "TestResults"));
                    test.Passed = r.Passed;
                    test.Failed = r.Failed;
                }

                foreach (var test in testfFiles)
                {
                    Console.WriteLine("Results for the test: " + test.Filename);
                    Console.WriteLine("Passed: " + test.Passed.ToString());
                    Console.WriteLine("Failed: " + test.Failed.ToString());
                    Console.WriteLine();
                }
            }
        }
示例#5
0
 internal static string Combine(List <String> components)
 {
     return(PathTools.Combine(components.ToArray()));
 }
示例#6
0
 /// <summary>
 /// If a directory specified relative to the Unity data dir is not yet in the PATH, add it.
 /// </summary>
 /// <param name="dirComponents">Components of a directory name relative to the Unity data dir.</param>
 private void ConditionallyAddRelativeDir(List <string> dirComponents)
 {
     ConditionallyAddRelativeDir(PathTools.Combine(dirComponents));
 }
示例#7
0
        public void UpdateGitAndRescanTargets()
        {
            string gitExe    = (Registry.CurrentUser.OpenSubKey(@"Software\Sysprogs\BSPGenerators")?.GetValue("git") as string) ?? "git.exe";
            string pythonExe = (Registry.CurrentUser.OpenSubKey(@"Software\Sysprogs\BSPGenerators")?.GetValue("python") as string) ?? "python.exe";

            Process proc;

            if (Directory.Exists(mbedRoot))
            {
                proc = Process.Start(new ProcessStartInfo(gitExe, "reset --hard")
                {
                    WorkingDirectory = mbedRoot, UseShellExecute = false
                });
            }
            else
            {
                proc = Process.Start(new ProcessStartInfo(gitExe, $"clone https://github.com/ARMmbed/mbed-os.git mbed")
                {
                    WorkingDirectory = outputDir, UseShellExecute = false
                });
                proc.WaitForExit();

                if (proc.ExitCode != 0)
                {
                    throw new Exception("Git exited with code " + proc.ExitCode);
                }

                proc = Process.Start(new ProcessStartInfo(gitExe, $"checkout mbed-os-{Version}")
                {
                    WorkingDirectory = outputDir + "\\mbed", UseShellExecute = false
                });
            }
            proc.WaitForExit();

            if (proc.ExitCode != 0)
            {
                throw new Exception("Git exited with code " + proc.ExitCode);
            }

            foreach (var lds in Directory.GetFiles(mbedRoot, "*.ld", SearchOption.AllDirectories))
            {
                if (File.ReadAllText(lds).Contains("\n#if"))
                {
                    ProcessStartInfo preprocessInfo = new ProcessStartInfo($@"{toolchainDir}\bin\arm-eabi-cpp.exe", $"-P -C {lds} -o {lds}.preprocessed");
                    preprocessInfo.UseShellExecute = false;
                    preprocessInfo.EnvironmentVariables["PATH"] += $@";{toolchainDir}\bin";
                    proc = Process.Start(preprocessInfo);
                    proc.WaitForExit();

                    File.Copy(lds + ".preprocessed", lds, true);
                    File.Delete(lds + ".preprocessed");
                }
            }

            var patchedFile = Path.Combine(mbedRoot, @"tools\config\__init__.py");
            var lines       = File.ReadAllLines(patchedFile).ToList();
            var idx2        = Enumerable.Range(0, lines.Count).First(i => lines[i].Contains("self.value = int(value) if isinstance(value, bool) else value"));

            if (!lines[idx2 + 1].Contains("is_bool"))
            {
                lines.Insert(idx2 + 1, "        self.is_bool = isinstance(value, bool)  #Patch by Sysprogs");
                File.WriteAllLines(patchedFile, lines);
            }

            //7. Enable exporting LPC targets
            patchedFile = Path.Combine(mbedRoot, @"tools\export\exporters.py");
            lines       = File.ReadAllLines(patchedFile).ToList();
            string str = "target.post_binary_hook['function'] in whitelist:";

            idx2 = Enumerable.Range(0, lines.Count).FirstOrDefault(i => lines[i].Contains(str));
            if (idx2 > 0)
            {
                int subIdx = lines[idx2].IndexOf(str);
                lines[idx2] = lines[idx2].Substring(0, subIdx) + "True:";
                File.WriteAllLines(patchedFile, lines);
            }

            string sampleDir = Path.Combine(mbedRoot, "samples");

            if (Directory.Exists(sampleDir))
            {
                Directory.Delete(sampleDir, true);
            }
            PathTools.CopyDirectoryRecursive(Path.Combine(dataDir, "samples"), sampleDir);

            ProcessStartInfo bspGenInfo = new ProcessStartInfo(pythonExe, Path.Combine(dataDir, "BuildConfigExtractor.py"));

            bspGenInfo.UseShellExecute = false;
            bspGenInfo.EnvironmentVariables["PYTHONPATH"] = mbedRoot;
            bspGenInfo.EnvironmentVariables["PATH"]      += $@";{toolchainDir}\bin";
            proc = Process.Start(bspGenInfo);
            proc.WaitForExit();

            if (proc.ExitCode != 0)
            {
                throw new Exception("BSP generator exited with code " + proc.ExitCode);
            }
        }
示例#8
0
 /// <summary>
 /// Checks to see if a directory specified relative to the Unity data dir is included in the path so far.
 /// It checks using both forward-slashed and backslashed versions of the Unity data dir.
 /// </summary>
 /// <param name="relativePortion">Directory relative to the Unity data dir</param>
 /// <returns>true if the given directory is included in the path so far</returns>
 private bool IsRelativeDirIncludedInPath(string relativePortion)
 {
     return(IsIncludedInPath(PathTools.Combine(UnityDataDir, relativePortion)) || IsIncludedInPath(PathTools.Combine(UnityDataDirBackslashed, relativePortion)));
 }
示例#9
0
        public void UninstallFromDirectory(IEnumerable <ApplicationUninstallerEntry> allUninstallers)
        {
            if (!TryGetUninstallLock())
            {
                return;
            }
            var listRefreshNeeded = false;

            var applicationUninstallerEntries = allUninstallers as IList <ApplicationUninstallerEntry> ?? allUninstallers.ToList();

            try
            {
                var result = MessageBoxes.SelectFolder(Localisable.UninstallFromDirectory_FolderBrowse);

                if (result == null)
                {
                    return;
                }

                var items = new List <ApplicationUninstallerEntry>();
                LoadingDialog.ShowDialog(MessageBoxes.DefaultOwner, Localisable.UninstallFromDirectory_ScanningTitle,
                                         _ =>
                {
                    items.AddRange(DirectoryFactory.TryCreateFromDirectory(
                                       new DirectoryInfo(result), null, Array.Empty <string>()));
                });

                if (items.Count == 0)
                {
                    items.AddRange(applicationUninstallerEntries
                                   .Where(x => PathTools.PathsEqual(result, x.InstallLocation)));
                }

                if (items.Count == 0)
                {
                    MessageBoxes.UninstallFromDirectoryNothingFound();
                }
                else
                {
                    foreach (var item in items.ToList())
                    {
                        if (item.UninstallPossible && item.UninstallerKind != UninstallerType.SimpleDelete &&
                            MessageBoxes.UninstallFromDirectoryUninstallerFound(item.DisplayName, item.UninstallString))
                        {
                            item.RunUninstaller(false, Settings.Default.AdvancedSimulate).WaitForExit(60000);
                            items.Remove(item);
                            listRefreshNeeded = true;
                        }
                        else
                        {
                            var found = applicationUninstallerEntries.Where(
                                x => PathTools.PathsEqual(item.InstallLocation, x.InstallLocation)).ToList();

                            if (!found.Any())
                            {
                                continue;
                            }

                            items.Remove(item);

                            foreach (var entry in found)
                            {
                                if (entry.UninstallPossible && entry.UninstallerKind != UninstallerType.SimpleDelete &&
                                    MessageBoxes.UninstallFromDirectoryUninstallerFound(entry.DisplayName, entry.UninstallString))
                                {
                                    try { item.RunUninstaller(false, Settings.Default.AdvancedSimulate).WaitForExit(60000); }
                                    catch (Exception ex) { PremadeDialogs.GenericError(ex); }

                                    listRefreshNeeded = true;
                                }
                                else
                                {
                                    items.Add(entry);
                                }
                            }
                        }
                    }

                    AdvancedUninstall(items, applicationUninstallerEntries.Where(
                                          x => !items.Any(y => PathTools.PathsEqual(y.InstallLocation, x.InstallLocation))));
                }
            }
            finally
            {
                ReleaseUninstallLock();
                _lockApplication(false);
                if (listRefreshNeeded)
                {
                    _initiateListRefresh();
                }
            }
        }
 private bool TestPathsMatchExe(string keyValue)
 {
     return(PathTools.SubPathIsInsideBasePath(_uninstaller.InstallLocation, Path.GetDirectoryName(keyValue), true));
 }
        public override IEnumerable <IJunkResult> FindJunk(ApplicationUninstallerEntry target)
        {
            var results = new List <FileSystemJunk>();

            if (!string.IsNullOrEmpty(target.InstallLocation))
            {
                results.AddRange(GetLinksPointingToLocation(entry => entry.InstallLocation, target)
                                 .DoForEach(x => x.Confidence.Add(ConfidenceRecords.ExplicitConnection)));
            }

            if (!string.IsNullOrEmpty(target.UninstallerFullFilename))
            {
                results.AddRange(GetLinksPointingToLocation(entry => entry.UninstallerFullFilename, target)
                                 .DoForEach(x => x.Confidence.Add(ConfidenceRecords.ExplicitConnection)));
            }

            if (!string.IsNullOrEmpty(target.UninstallerLocation))
            {
                var exceptUninstallerShortcut = GetLinksPointingToLocation(entry => entry.UninstallerLocation, target)
                                                .Where(possibleResult => results.All(result => !PathTools.PathsEqual(result.Path, possibleResult.Path)))
                                                .ToList();

                results.AddRange(exceptUninstallerShortcut);
            }

            // Remove shortcuts that we aren't sure about
            foreach (var junkNode in results.ToList())
            {
                var name = Path.GetFileNameWithoutExtension(junkNode.Path.Name);
                junkNode.Confidence.AddRange(ConfidenceGenerators.GenerateConfidence(name, target));

                if (junkNode.Confidence.IsEmpty)
                {
                    results.Remove(junkNode);
                }
            }

            return(results.Cast <IJunkResult>());
        }
        /// <summary>
        /// Méthode qui charge l'animation courante
        /// </summary>
        public void LoadAnimation(Guid guid)
        {
            Cursor.Current = Cursors.WaitCursor;

            //Stop Timer
            _FrequencyTimer.Stop();

            //Anim courante
            Animation = guid;
            if (this.AnimationLoading != null)
            {
                this.AnimationLoading(this, new EventArgs());
            }

            if (AnimationFilter == Enums.AnimationType.CharacterAnimation)
            {
                _CurrentAnim = _Service.LoadVOObject(ParentCharacter, Animation);
            }
            else
            {
                _CurrentAnim = _Service.LoadVOObject(AnimationFilter, Animation);
            }

            //Rechargement de la ressource
            if (_CurrentAnim != null && _CurrentAnim.ResourcePath != null)
            {
                //Mise en place du sprite root.
                _CurrentSprite.X      = 0;
                _CurrentSprite.Width  = _CurrentAnim.SpriteWidth;
                _CurrentSprite.Height = _CurrentAnim.SpriteHeight;
                if (UseCustomRow)
                {
                    _CurrentSprite.Y = Row * _CurrentSprite.Height;
                }
                else
                {
                    _CurrentSprite.Y = _CurrentAnim.Row * _CurrentSprite.Height;
                }
                if (!string.IsNullOrEmpty(_CurrentAnim.ResourcePath))
                {
                    _Service.LoadSurfaceFromURI(PathTools.GetProjectPath(AnimationFilter) + _CurrentAnim.ResourcePath);
                }
                else
                {
                    _Service.LoadSurfaceFromURI(string.Empty);
                    _CurrentSprite.Y = 0;
                }


                //Timer
                if (UseCustomFrequency)
                {
                    _FrequencyTimer.Interval = 10000 / Frequency;
                }
                else
                {
                    _FrequencyTimer.Interval = 10000 / _CurrentAnim.Frequency;
                }
            }
            //TODO: A vérif si toujours nécessaire
            else
            {
                _Service.LoadEmptySurface();
                _CurrentSprite.X      = 0;
                _CurrentSprite.Width  = 1;
                _CurrentSprite.Height = 1;
            }
            //FINTODO

            //Récupération de la taille de la ressource originale
            _OriginalResourceSize = _Service.GetSizeOfResource();

            RefreshPreview();

            Cursor.Current = DefaultCursor;
        }
示例#13
0
        public static void Process(string folderPath, IFileSystem newBaseFolderFs, Keyset keyset, Output Out)
        {
            var dirDecrypted = new DirectoryInfo(folderPath);

            foreach (var inFile in dirDecrypted.GetFiles("*.tca"))
            {
                Out.Log($"{inFile}\r\n");
                var ncaStorage = new StreamStorage(new FileStream(inFile.FullName, FileMode.Open, FileAccess.Read),
                                                   false);
                var DecryptedHeader = new byte[0xC00];
                ncaStorage.Read(DecryptedHeader, 0, 0xC00, 0);
                var Header = new NcaHeader(new BinaryReader(new MemoryStream(DecryptedHeader)), keyset);

                var fragmentTrimmed = false;
                for (var i = 0; i < 4; ++i)
                {
                    var section = NcaParseSection.ParseSection(Header, i);

                    if (section == null || section.Header.Type != SectionType.Pfs0)
                    {
                        continue;
                    }

                    if (fragmentTrimmed)
                    {
                        Out.Warn(
                            "Multiple fragments in NCA found! Skip trimming this fragment.\r\n");
                        continue;
                    }

                    IStorage sectionStorage = ncaStorage.Slice(section.Offset, section.Size, false);
                    IStorage pfs0Storage    = sectionStorage.Slice(section.Header.Sha256Info.DataOffset,
                                                                   section.Header.Sha256Info.DataSize, false);
                    var Pfs0Header = new PartitionFileSystemHeader(new BinaryReader(pfs0Storage.AsStream()));
                    var FileDict   = Pfs0Header.Files.ToDictionary(x => x.Name, x => x);
                    var path       = PathTools.Normalize(FragmentFileName).TrimStart('/');
                    if (Pfs0Header.NumFiles == 1 && FileDict.TryGetValue(path, out var fragmentFile))
                    {
                        var inFileNameNoExtension = Path.GetFileNameWithoutExtension(inFile.Name);
                        var writer       = File.Open($"{folderPath}/{inFileNameNoExtension}.nca", FileMode.Create);
                        var offsetBefore = section.Offset + section.Header.Sha256Info.DataOffset +
                                           Pfs0Header.HeaderSize +
                                           fragmentFile.Offset;
                        IStorage ncaStorageBeforeFragment = ncaStorage.Slice(0, offsetBefore, false);
                        IStorage fragmentStorageOverflow  = ncaStorage.Slice(offsetBefore,
                                                                             ncaStorage.GetSize() - offsetBefore, false);
                        ncaStorageBeforeFragment.CopyToStream(writer);
                        var      TDV0len              = RecreateDelta.Recreate(fragmentStorageOverflow, writer, newBaseFolderFs);
                        var      offsetAfter          = offsetBefore + TDV0len;
                        IStorage fragmentStorageAfter = ncaStorage.Slice(offsetAfter,
                                                                         ncaStorage.GetSize() - offsetAfter, false);
                        fragmentStorageAfter.CopyToStream(writer);
                        writer.Position = 0x200;
                        writer.WriteByte(0x4E);
                        writer.Dispose();
                        fragmentTrimmed = true;
                    }
                }

                ncaStorage.Dispose();
                File.Delete(inFile.FullName);
            }
        }
        private IEnumerable <FileSystemJunk> FindJunkRecursively(DirectoryInfo directory, int level = 0)
        {
            var results = new List <FileSystemJunk>();

            try
            {
                var dirs = directory.GetDirectories();

                foreach (var dir in dirs)
                {
                    if (UninstallToolsGlobalConfig.IsSystemDirectory(dir))
                    {
                        continue;
                    }

                    var generatedConfidence = GenerateConfidence(dir.Name, directory.FullName, level).ToList();

                    FileSystemJunk newNode = null;
                    if (generatedConfidence.Any())
                    {
                        newNode = new FileSystemJunk(dir, _uninstaller, this);
                        newNode.Confidence.AddRange(generatedConfidence);

                        if (CheckIfDirIsStillUsed(dir.FullName, GetOtherInstallLocations(_uninstaller)))
                        {
                            newNode.Confidence.Add(ConfidenceRecord.DirectoryStillUsed);
                        }

                        results.Add(newNode);
                    }

                    if (level > 1)
                    {
                        continue;
                    }

                    var junkNodes = FindJunkRecursively(dir, level + 1).ToList();
                    results.AddRange(junkNodes);

                    if (newNode != null)
                    {
                        // Check if the directory will have nothing left after junk removal.
                        if (!dir.GetFiles().Any())
                        {
                            var subDirs = dir.GetDirectories();
                            if (!subDirs.Any() || subDirs.All(d => junkNodes.Any(y => PathTools.PathsEqual(d.FullName, y.Path.FullName))))
                            {
                                newNode.Confidence.Add(ConfidenceRecord.AllSubdirsMatched);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    throw;
                }
                Console.WriteLine(ex);
            }

            return(results);
        }
示例#15
0
    /// <summary>
    /// 初始化
    /// </summary>
    static public void Init()
    {
        SetPath();

        string md5filelist = "md5filelist.txt";

        string dataPath = assetsUpdatePath;           //Util.DataPath;  //数据目录
        string resPath  = PathTools.AppContentPath(); //Util.AppContentPath(); //游戏包资源目录

        string localMD5BakFilePath = PathTools.Combine(dataPath, "/md5filelist.txt.bak");

        string infile  = PathTools.Combine(resPath, "md5filelist.txt");
        string outfile = PathTools.Combine(dataPath, "md5filelist.txt");

        Debug.Log(infile);

        if (PathTools.ExistsPersistentPath("md5filelist.txt"))
        {
            Debug.LogWarning("非首次启动!");
        }
        else
        {
            Debug.LogWarning("首次启动!");

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

            Debug.LogErrorFormat("localMD5BakFilePath {0} {1}", localMD5BakFilePath, File.Exists(localMD5BakFilePath));

            if (File.Exists(localMD5BakFilePath))
            {
                Debug.LogErrorFormat("本地列表文件 bak 存在!{0}", localMD5BakFilePath);
                File.Delete(localMD5BakFilePath);
            }
            if (File.Exists(localMD5BakFilePath))
            {
                Debug.LogErrorFormat("本地列表文件 bak 删除成功!{0}", localMD5BakFilePath);
            }

            string message = "正在解包文件:>md5filelist.txt";

            if (Application.platform == RuntimePlatform.Android)
            {
                WWW www = new WWW(infile);

                while (true)
                {
                    if (www.isDone || !string.IsNullOrEmpty(www.error))
                    {
                        System.Threading.Thread.Sleep(50);
                        if (!string.IsNullOrEmpty(www.error))
                        {
                            Debug.LogError(www.error);
                        }
                        else
                        {
                            File.WriteAllBytes(outfile, www.bytes);
                            Debug.LogWarning(">>" + outfile);
                        }
                        break;
                    }
                }
            }
            else
            {
                File.Copy(infile, outfile, true);
            }
        }

        string path = PathTools.Combine(PathTools.PersistentDataPath(), md5filelist);

        Debug.LogWarningFormat("热更新步骤 1 【初始化拷贝】完成!{0} {1}", path, System.IO.File.Exists(path));
    }